hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
5b2f6eafcde4a0b779990b187de0f3219d0a63a9 | 3,559 | import XCTest
class BobTest: XCTestCase {
func testStatingSomething() {
let input = "Tom-ay-to, tom-aaaah-to."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShouting() {
let input = "WATCH OUT!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testAskingAQustion() {
let input = "Does this cryogenic chamber make me look fat?"
let expected = "Sure."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testTalkingForcefully() {
let input = "Let's go make out behind the gym!"
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testUsingAcronyms() {
let input = "It's OK if you don't want to go to the DMV."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testForcefulQuestions() {
let input = "WHAT THE HELL WERE YOU THINKING?"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingNumbers() {
let input = "1, 2, 3 GO!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testOnlyNumbers() {
let input = "1, 2, 3."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testQuestionWithOnlyNumbers() {
let input = "4?"
let expected = "Sure."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithSpecialCharacters() {
let input = "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithUmlautsCharacters() {
let input = "ÄMLÄTS!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testCalmlySpeakingAboutUmlauts() {
let input = "ÄMLäTS!"
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithNoExclamationmark() {
let input = "I HATE YOU"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testStatementContainingQuestionsMark() {
let input = "Ending with a ? means a question."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testPrattlingOn() {
let input = "Wait! Hang on. Are you going to be OK?"
let expected = "Sure."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testSilence() {
let input = ""
let expected = "Fine, be that way."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testProlongedSilence() {
let input = " "
let expected = "Fine, be that way."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
}
| 28.023622 | 67 | 0.570385 |
14f705cb5df95f5eb433a6e1ff62efad822284cc | 778 | //
// DeletingProduct.swift
// CleanArchitecture
//
// Created by Tuan Truong on 6/26/20.
// Copyright © 2020 Sun Asterisk. All rights reserved.
//
import Dto
import ValidatedPropertyKit
import RxSwift
struct DeleteProductDto: Dto {
@Validated(Validation.greater(0))
var id: Int?
var validatedProperties: [ValidatedProperty] {
return [_id]
}
init(id: Int) {
self.id = id
}
}
protocol DeletingProduct {
var productGateway: ProductGatewayType { get }
}
extension DeletingProduct {
func deleteProduct(dto: DeleteProductDto) -> Observable<Void> {
if let error = dto.validationError {
return Observable.error(error)
}
return productGateway.deleteProduct(dto: dto)
}
}
| 19.948718 | 67 | 0.6491 |
efd8470255d9d8d62f97ae88cf34fff959cccc5f | 1,149 | //
// Request.swift
// YouTube
//
// Created by Josh Kowarsky on 9/20/20.
//
import Alamofire
import Combine
enum RequestError: Error {
case createURLError
}
public protocol Request: URLRequestConvertible {
var hostURLString: String { get }
var method: HTTPMethod { get }
var path: String { get }
var parameters: Parameters { get }
var headers: HTTPHeaders? { get }
var isAuthenticated: Bool { get }
func refreshTokenIfNecessary() -> AnyPublisher<Request, Error>
}
extension Request {
public func asURLRequest() throws -> URLRequest {
guard var components = URLComponents(string: hostURLString) else {
throw RequestError.createURLError
}
components.path = "\(components.path)/\(path)"
components.queryItems = parameters.map { URLQueryItem(name: $0.key, value: $0.value as? String) }
let url = try components.asURL()
return try URLRequest(url: url, method: method, headers: headers)
}
func refreshTokenIfNecessary() -> AnyPublisher<Request, Error> {
return Just(self).setFailureType(to: Error.self).eraseToAnyPublisher()
}
}
| 28.02439 | 105 | 0.671889 |
5089eec8ac32ee37f96a642d44743e931e5576e7 | 2,212 | import Foundation
final class CodeFilesSearch: FilesSearchable {
private let baseDirectoryPath: String
private let basePathComponents: [String]
init(
baseDirectoryPath: String
) {
self.baseDirectoryPath = baseDirectoryPath
self.basePathComponents = URL(fileURLWithPath: baseDirectoryPath).pathComponents
}
func shouldSkipFile(at url: URL, subpathsToIgnore: [String]) -> Bool {
var subpath = url.path
if let potentialBaseDirSubstringRange = subpath.range(of: baseDirectoryPath) {
if potentialBaseDirSubstringRange.lowerBound == subpath.startIndex {
subpath.removeSubrange(potentialBaseDirSubstringRange)
}
}
let subpathComponents = subpath.components(separatedBy: "/").filter { !$0.isBlank }
for subpathToIgnore in subpathsToIgnore {
let subpathToIgnoreComponents = subpathToIgnore.components(separatedBy: "/")
if subpathComponents.containsCaseInsensitive(subarray: subpathToIgnoreComponents) {
return true
}
}
return false
}
func findCodeFiles(subpathsToIgnore: [String]) -> [String] {
guard FileManager.default.fileExists(atPath: baseDirectoryPath) else { return [] }
guard !baseDirectoryPath.hasSuffix(".string") else { return [baseDirectoryPath] }
let codeFileRegex = try! NSRegularExpression(pattern: "\\.swift\\z", options: .caseInsensitive) // swiftlint:disable:this force_try
let codeFiles: [String] = findAllFilePaths(
inDirectoryPath: baseDirectoryPath,
subpathsToIgnore: subpathsToIgnore,
matching: codeFileRegex
)
return codeFiles
}
}
extension Array where Element == String {
func containsCaseInsensitive(subarray: [Element]) -> Bool {
guard let firstSubArrayElement = subarray.first else { return false }
for (index, element) in enumerated() {
// sample: this = [a, b, c], subarray = [b, c], firstIndex = 1, subRange = 1 ..< 3
if element.lowercased() == firstSubArrayElement.lowercased() {
let subRange = index..<index + subarray.count
let subRangeElements = self[subRange]
return subRangeElements.map { $0.lowercased() } == subarray.map { $0.lowercased() }
}
}
return false
}
}
| 34.5625 | 136 | 0.705696 |
1d85f86bf6e5834bec27a3b6b1d7a15a7be5275a | 777 | //
// SavedCardsHeader.swift
// SafexPay
//
// Created by Sandeep on 8/26/20.
// Copyright © 2020 Antino Labs. All rights reserved.
//
import UIKit
protocol SavedCardsHeaderProtocol {
// func sectionExpandPressed(tag: Int, view: SavedCardsHeader)
func sectionExpandPressed(tag: Int)
}
class SavedCardsHeader: UITableViewHeaderFooterView {
@IBOutlet weak var sectionTypeLabel: UILabel!
@IBOutlet weak var sectionExpandButton: UIButton!
var delegate: SavedCardsHeaderProtocol?
override func awakeFromNib() {}
func setdata(headerLbl:String){
self.sectionTypeLabel.text = headerLbl
}
@IBAction func sectionExpandPressed(_ sender: UIButton) {
self.delegate?.sectionExpandPressed(tag: self.tag)
}
}
| 22.852941 | 65 | 0.707851 |
f58ca124b207825ede32860c6dd82b2e2627241f | 1,006 | //
// ExtensionDelegate.swift
// TechTalk WatchKit Extension
//
// Created by Raza Padhani on 8/25/16.
// Copyright © 2016 Raza Padhani. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
}
| 37.259259 | 285 | 0.736581 |
1ed00357f908c45d517ab97ed97cfac884defdf7 | 952 | //
// InstrumentTableViewCell.swift
// MyTuna
//
// Created by Luca Cipressi on 03/01/2018.
// Copyright (c) 2017-2021 Luca Cipressi - lucaji.github.io - [email protected] . All rights reserved.
//
import UIKit
class InstrumentTableViewCell: UITableViewCell {
@IBOutlet weak var instrumentNameLabel: UILabel!
@IBOutlet weak var instrumentCountLabel: BadgeableLabel!
func configureWithInstrument(_ instro:Instrument) {
instrumentNameLabel.text = instro.instrumentName
instrumentCountLabel.text = String(instro.instrumentTunings!.count)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
instrumentNameLabel.textColor = selected ? UIColor.black : UIColor.white
}
}
| 27.2 | 100 | 0.702731 |
1e56757fe91bc8aa4512daa227d019497f20e943 | 11,733 | // Sources/SwiftProtobuf/NameMap.swift - Bidirectional number/name mapping
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
/// TODO: Right now, only the NameMap and the NameDescription enum
/// (which are directly used by the generated code) are public.
/// This means that code outside the library has no way to actually
/// use this data. We should develop and publicize a suitable API
/// for that purpose. (Which might be the same as the internal API.)
/// This must be exactly the same as the corresponding code in the
/// protoc-gen-swift code generator. Changing it will break
/// compatibility of the library with older generated code.
///
/// It does not necessarily need to match protoc's JSON field naming
/// logic, however.
private func toJsonFieldName(_ s: String) -> String {
var result = String()
var capitalizeNext = false
for c in s {
if c == "_" {
capitalizeNext = true
} else if capitalizeNext {
result.append(String(c).uppercased())
capitalizeNext = false
} else {
result.append(String(c))
}
}
return result
}
/// Allocate static memory buffers to intern UTF-8
/// string data. Track the buffers and release all of those buffers
/// in case we ever get deallocated.
fileprivate class InternPool {
private var interned = [UnsafeRawBufferPointer]()
func intern(utf8: String.UTF8View) -> UnsafeRawBufferPointer {
#if swift(>=4.1)
let mutable = UnsafeMutableRawBufferPointer.allocate(byteCount: utf8.count,
alignment: MemoryLayout<UInt8>.alignment)
#else
let mutable = UnsafeMutableRawBufferPointer.allocate(count: utf8.count)
#endif
mutable.copyBytes(from: utf8)
let immutable = UnsafeRawBufferPointer(mutable)
interned.append(immutable)
return immutable
}
func intern(utf8Ptr: UnsafeBufferPointer<UInt8>) -> UnsafeRawBufferPointer {
#if swift(>=4.1)
let mutable = UnsafeMutableRawBufferPointer.allocate(byteCount: utf8Ptr.count,
alignment: MemoryLayout<UInt8>.alignment)
#else
let mutable = UnsafeMutableRawBufferPointer.allocate(count: utf8.count)
#endif
mutable.copyBytes(from: utf8Ptr)
let immutable = UnsafeRawBufferPointer(mutable)
interned.append(immutable)
return immutable
}
deinit {
for buff in interned {
#if swift(>=4.1)
buff.deallocate()
#else
let p = UnsafeMutableRawPointer(mutating: buff.baseAddress)!
p.deallocate(bytes: buff.count, alignedTo: 1)
#endif
}
}
}
#if !swift(>=4.2)
// Constants for FNV hash http://tools.ietf.org/html/draft-eastlake-fnv-03
private let i_2166136261 = Int(bitPattern: 2166136261)
private let i_16777619 = Int(16777619)
#endif
/// An immutable bidirectional mapping between field/enum-case names
/// and numbers, used to record field names for text-based
/// serialization (JSON and text). These maps are lazily instantiated
/// for each message as needed, so there is no run-time overhead for
/// users who do not use text-based serialization formats.
public struct _NameMap: ExpressibleByDictionaryLiteral {
/// An immutable interned string container. The `utf8Start` pointer
/// is guaranteed valid for the lifetime of the `NameMap` that you
/// fetched it from. Since `NameMap`s are only instantiated as
/// immutable static values, that should be the lifetime of the
/// program.
///
/// Internally, this uses `StaticString` (which refers to a fixed
/// block of UTF-8 data) where possible. In cases where the string
/// has to be computed, it caches the UTF-8 bytes in an
/// unmovable and immutable heap area.
internal struct Name: Hashable, CustomStringConvertible {
// This should not be used outside of this file, as it requires
// coordinating the lifecycle with the lifecycle of the pool
// where the raw UTF8 gets interned.
fileprivate init(staticString: StaticString, pool: InternPool) {
self.nameString = .staticString(staticString)
if staticString.hasPointerRepresentation {
self.utf8Buffer = UnsafeRawBufferPointer(start: staticString.utf8Start,
count: staticString.utf8CodeUnitCount)
} else {
self.utf8Buffer = staticString.withUTF8Buffer { pool.intern(utf8Ptr: $0) }
}
}
// This should not be used outside of this file, as it requires
// coordinating the lifecycle with the lifecycle of the pool
// where the raw UTF8 gets interned.
fileprivate init(string: String, pool: InternPool) {
let utf8 = string.utf8
self.utf8Buffer = pool.intern(utf8: utf8)
self.nameString = .string(string)
}
// This is for building a transient `Name` object sufficient for lookup purposes.
// It MUST NOT be exposed outside of this file.
fileprivate init(transientUtf8Buffer: UnsafeRawBufferPointer) {
self.nameString = .staticString("")
self.utf8Buffer = transientUtf8Buffer
}
private(set) var utf8Buffer: UnsafeRawBufferPointer
private enum NameString {
case string(String)
case staticString(StaticString)
}
private var nameString: NameString
public var description: String {
switch nameString {
case .string(let s): return s
case .staticString(let s): return s.description
}
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
for byte in utf8Buffer {
hasher.combine(byte)
}
}
#else // swift(>=4.2)
public var hashValue: Int {
var h = i_2166136261
for byte in utf8Buffer {
h = (h ^ Int(byte)) &* i_16777619
}
return h
}
#endif // swift(>=4.2)
public static func ==(lhs: Name, rhs: Name) -> Bool {
if lhs.utf8Buffer.count != rhs.utf8Buffer.count {
return false
}
return lhs.utf8Buffer.elementsEqual(rhs.utf8Buffer)
}
}
/// The JSON and proto names for a particular field, enum case, or extension.
internal struct Names {
private(set) var json: Name?
private(set) var proto: Name
}
/// A description of the names for a particular field or enum case.
/// The different forms here let us minimize the amount of string
/// data that we store in the binary.
///
/// These are only used in the generated code to initialize a NameMap.
public enum NameDescription {
/// The proto (text format) name and the JSON name are the same string.
case same(proto: StaticString)
/// The JSON name can be computed from the proto string
case standard(proto: StaticString)
/// The JSON and text format names are just different.
case unique(proto: StaticString, json: StaticString)
/// Used for enum cases only to represent a value's primary proto name (the
/// first defined case) and its aliases. The JSON and text format names for
/// enums are always the same.
case aliased(proto: StaticString, aliases: [StaticString])
}
private var internPool = InternPool()
/// The mapping from field/enum-case numbers to names.
private var numberToNameMap: [Int: Names] = [:]
/// The mapping from proto/text names to field/enum-case numbers.
private var protoToNumberMap: [Name: Int] = [:]
/// The mapping from JSON names to field/enum-case numbers.
/// Note that this also contains all of the proto/text names,
/// as required by Google's spec for protobuf JSON.
private var jsonToNumberMap: [Name: Int] = [:]
/// Creates a new empty field/enum-case name/number mapping.
public init() {}
/// Build the bidirectional maps between numbers and proto/JSON names.
public init(dictionaryLiteral elements: (Int, NameDescription)...) {
for (number, description) in elements {
switch description {
case .same(proto: let p):
let protoName = Name(staticString: p, pool: internPool)
let names = Names(json: protoName, proto: protoName)
numberToNameMap[number] = names
protoToNumberMap[protoName] = number
jsonToNumberMap[protoName] = number
case .standard(proto: let p):
let protoName = Name(staticString: p, pool: internPool)
let jsonString = toJsonFieldName(protoName.description)
let jsonName = Name(string: jsonString, pool: internPool)
let names = Names(json: jsonName, proto: protoName)
numberToNameMap[number] = names
protoToNumberMap[protoName] = number
jsonToNumberMap[protoName] = number
jsonToNumberMap[jsonName] = number
case .unique(proto: let p, json: let j):
let jsonName = Name(staticString: j, pool: internPool)
let protoName = Name(staticString: p, pool: internPool)
let names = Names(json: jsonName, proto: protoName)
numberToNameMap[number] = names
protoToNumberMap[protoName] = number
jsonToNumberMap[protoName] = number
jsonToNumberMap[jsonName] = number
case .aliased(proto: let p, aliases: let aliases):
let protoName = Name(staticString: p, pool: internPool)
let names = Names(json: protoName, proto: protoName)
numberToNameMap[number] = names
protoToNumberMap[protoName] = number
jsonToNumberMap[protoName] = number
for alias in aliases {
let protoName = Name(staticString: alias, pool: internPool)
protoToNumberMap[protoName] = number
jsonToNumberMap[protoName] = number
}
}
}
}
/// Returns the name bundle for the field/enum-case with the given number, or
/// `nil` if there is no match.
internal func names(for number: Int) -> Names? {
return numberToNameMap[number]
}
/// Returns the field/enum-case number that has the given JSON name,
/// or `nil` if there is no match.
///
/// This is used by the Text format parser to look up field or enum
/// names using a direct reference to the un-decoded UTF8 bytes.
internal func number(forProtoName raw: UnsafeRawBufferPointer) -> Int? {
let n = Name(transientUtf8Buffer: raw)
return protoToNumberMap[n]
}
/// Returns the field/enum-case number that has the given JSON name,
/// or `nil` if there is no match.
///
/// This accepts a regular `String` and is used in JSON parsing
/// only when a field name or enum name was decoded from a string
/// containing backslash escapes.
///
/// JSON parsing must interpret *both* the JSON name of the
/// field/enum-case provided by the descriptor *as well as* its
/// original proto/text name.
internal func number(forJSONName name: String) -> Int? {
let utf8 = Array(name.utf8)
return utf8.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
let n = Name(transientUtf8Buffer: buffer)
return jsonToNumberMap[n]
}
}
/// Returns the field/enum-case number that has the given JSON name,
/// or `nil` if there is no match.
///
/// This is used by the JSON parser when a field name or enum name
/// required no special processing. As a result, we can avoid
/// copying the name and look up the number using a direct reference
/// to the un-decoded UTF8 bytes.
internal func number(forJSONName raw: UnsafeRawBufferPointer) -> Int? {
let n = Name(transientUtf8Buffer: raw)
return jsonToNumberMap[n]
}
}
| 37.726688 | 98 | 0.670161 |
e8090068bff4439377625f2bbd2cce2b15f327e1 | 19,539 |
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name foreign_errors -parse-as-library %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import errors
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors5test0yyKF : $@convention(thin) () -> @error Error
func test0() throws {
// Create a strong temporary holding nil before we perform any further parts of function emission.
// CHECK: [[ERR_TEMP0:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: inject_enum_addr [[ERR_TEMP0]] : $*Optional<NSError>, #Optional.none!enumelt
// CHECK: [[SELF:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// Create an unmanaged temporary, copy into it, and make a AutoreleasingUnsafeMutablePointer.
// CHECK: [[ERR_TEMP1:%.*]] = alloc_stack $@sil_unmanaged Optional<NSError>
// CHECK: [[T0:%.*]] = load_borrow [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = ref_to_unmanaged [[T0]]
// CHECK: store [[T1]] to [trivial] [[ERR_TEMP1]]
// CHECK: address_to_pointer [[ERR_TEMP1]]
// Call the method.
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{.*}}, [[SELF]])
// Writeback to the first temporary.
// CHECK: [[T0:%.*]] = load [trivial] [[ERR_TEMP1]]
// CHECK: [[T1:%.*]] = unmanaged_to_ref [[T0]]
// CHECK: [[T1_COPY:%.*]] = copy_value [[T1]]
// CHECK: assign [[T1_COPY]] to [[ERR_TEMP0]]
// Pull out the boolean value and compare it to zero.
// CHECK: [[BOOL_OR_INT:%.*]] = struct_extract [[RESULT]]
// CHECK: [[RAW_VALUE:%.*]] = struct_extract [[BOOL_OR_INT]]
// On some platforms RAW_VALUE will be compared against 0; on others it's
// already an i1 (bool) and those instructions will be skipped. Just do a
// looser check.
// CHECK: cond_br {{%.+}}, [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
try ErrorProne.fail()
// Normal path: fall out and return.
// CHECK: [[NORMAL_BB]]:
// CHECK: return
// Error path: fall out and rethrow.
// CHECK: [[ERROR_BB]]:
// CHECK: [[T0:%.*]] = load [take] [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = function_ref @$s10Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF : $@convention(thin) (@guaranteed Optional<NSError>) -> @owned Error
// CHECK: [[T2:%.*]] = apply [[T1]]([[T0]])
// CHECK: "willThrow"([[T2]] : $Error)
// CHECK: throw [[T2]] : $Error
}
extension NSObject {
@objc func abort() throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE5abortyyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: [[T0:%.*]] = function_ref @$sSo8NSObjectC14foreign_errorsE5abortyyKF : $@convention(method) (@guaranteed NSObject) -> @error Error
// CHECK: try_apply [[T0]](
// CHECK: bb1(
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, {{1|-1}}
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb2([[ERR:%.*]] : @owned $Error):
// CHECK: switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt: bb3, case #Optional.none!enumelt: bb4
// CHECK: bb3([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$sSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
// CHECK: bb4:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
// CHECK: bb5:
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, 0
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb6([[BOOL:%.*]] : $ObjCBool):
// CHECK: return [[BOOL]] : $ObjCBool
@objc func badDescription() throws -> String {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE14badDescriptionSSyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[UNOWNED_ARG0:%.*]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[UNOWNED_ARG1:%.*]] : @unowned $NSObject):
// CHECK: [[ARG1:%.*]] = copy_value [[UNOWNED_ARG1]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[T0:%.*]] = function_ref @$sSo8NSObjectC14foreign_errorsE14badDescriptionSSyKF : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error)
// CHECK: try_apply [[T0]]([[BORROWED_ARG1]]) : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error), normal [[NORMAL_BB:bb[0-9][0-9]*]], error [[ERROR_BB:bb[0-9][0-9]*]]
//
// CHECK: [[NORMAL_BB]]([[RESULT:%.*]] : @owned $String):
// CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_RESULT]])
// CHECK: end_borrow [[BORROWED_RESULT]]
// CHECK: [[T2:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[T1]] : $NSString
// CHECK: destroy_value [[RESULT]]
// CHECK: br bb6([[T2]] : $Optional<NSString>)
//
// CHECK: [[ERROR_BB]]([[ERR:%.*]] : @owned $Error):
// CHECK: switch_enum [[UNOWNED_ARG0]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9][0-9]*]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9][0-9]*]]
//
// CHECK: [[SOME_BB]]([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$sSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
//
// CHECK: [[NONE_BB]]:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
//
// CHECK: bb5:
// CHECK: [[T0:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br bb6([[T0]] : $Optional<NSString>)
//
// CHECK: bb6([[T0:%.*]] : @owned $Optional<NSString>):
// CHECK: end_borrow [[BORROWED_ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[T0]] : $Optional<NSString>
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE7takeIntyySiKFTo : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[SELF:%[0-9]+]] : @unowned $NSObject)
@objc func takeInt(_ i: Int) throws { }
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE10takeDouble_3int7closureySd_S3iXEtKFTo : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) @noescape (Int) -> Int, NSObject) -> ObjCBool
// CHECK: bb0([[D:%[0-9]+]] : $Double, [[INT:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[CLOSURE:%[0-9]+]] : @unowned $@convention(block) @noescape (Int) -> Int, [[SELF:%[0-9]+]] : @unowned $NSObject):
@objc func takeDouble(_ d: Double, int: Int, closure: (Int) -> Int) throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
}
let fn = ErrorProne.fail
// CHECK-LABEL: sil private [ossa] @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_ : $@convention(thin) (@thick ErrorProne.Type) -> @owned @callee_guaranteed () -> @error Error {
// CHECK: [[T0:%.*]] = function_ref @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_yyKcfu0_ : $@convention(thin) (@thick ErrorProne.Type) -> @error Error
// CHECK-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[T0]](%0)
// CHECK-NEXT: return [[T1]]
// CHECK-LABEL: sil private [ossa] @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_yyKcfu0_ : $@convention(thin) (@thick ErrorProne.Type) -> @error Error {
// CHECK: [[TEMP:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[SELF:%.*]] = thick_to_objc_metatype %0 : $@thick ErrorProne.Type to $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{%.*}}, [[SELF]])
// CHECK: cond_br
// CHECK: return
// CHECK: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK: [[T1:%.*]] = apply {{%.*}}([[T0]])
// CHECK: "willThrow"([[T1]] : $Error)
// CHECK: throw [[T1]]
func testArgs() throws {
try ErrorProne.consume(nil)
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors8testArgsyyKF : $@convention(thin) () -> @error Error
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.consume!foreign : (ErrorProne.Type) -> (Any?) throws -> (), $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
func testBridgedResult() throws {
let array = try ErrorProne.collection(withCount: 0)
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors17testBridgedResultyyKF : $@convention(thin) () -> @error Error {
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.collection!foreign : (ErrorProne.Type) -> (Int) throws -> [Any], $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> @autoreleased Optional<NSArray>
// CHECK: } // end sil function '$s14foreign_errors17testBridgedResultyyKF'
// rdar://20861374
// Clear out the self box before delegating.
class VeryErrorProne : ErrorProne {
init(withTwo two: AnyObject?) throws {
try super.init(one: two)
}
}
// SEMANTIC SIL TODO: _TFC14foreign_errors14VeryErrorPronec has a lot more going
// on than is being tested here, we should consider adding FileCheck tests for
// it.
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc :
// CHECK: bb0([[ARG1:%.*]] : @owned $Optional<AnyObject>, [[ARG2:%.*]] : @owned $VeryErrorProne):
// CHECK: [[BOX:%.*]] = alloc_box ${ var VeryErrorProne }
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]
// CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_BOX]]
// CHECK: [[PB:%.*]] = project_box [[LIFETIME]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [lexical] [[ARG1]]
// CHECK: store [[ARG2]] to [init] [[PB]]
// CHECK: [[T0:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $VeryErrorProne to $ErrorProne
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK-NOT: [[BOX]]{{^[0-9]}}
// CHECK-NOT: [[PB]]{{^[0-9]}}
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK-NEXT: [[DOWNCAST_BORROWED_T1:%.*]] = unchecked_ref_cast [[BORROWED_T1]] : $ErrorProne to $VeryErrorProne
// CHECK-NEXT: [[T2:%.*]] = objc_super_method [[DOWNCAST_BORROWED_T1]] : $VeryErrorProne, #ErrorProne.init!initializer.foreign : (ErrorProne.Type) -> (Any?) throws -> ErrorProne, $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned ErrorProne) -> @owned Optional<ErrorProne>
// CHECK: end_borrow [[BORROWED_T1]]
// CHECK: apply [[T2]]([[ARG1_COPY]], {{%.*}}, [[T1]])
// CHECK: } // end sil function '$s14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc'
// rdar://21051021
// CHECK: sil hidden [ossa] @$s14foreign_errors12testProtocolyySo010ErrorProneD0_pKF : $@convention(thin) (@guaranteed ErrorProneProtocol) -> @error Error
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $ErrorProneProtocol):
func testProtocol(_ p: ErrorProneProtocol) throws {
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.obliterate!foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, τ_0_0) -> ObjCBool
try p.obliterate()
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.invigorate!foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, {{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, Optional<@convention(block) () -> ()>, τ_0_0) -> ObjCBool
try p.invigorate(callback: {})
}
// rdar://21144509 - Ensure that overrides of replace-with-() imports are possible.
class ExtremelyErrorProne : ErrorProne {
override func conflict3(_ obj: Any, error: ()) throws {}
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKF
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKFTo : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
// These conventions are usable because of swift_error. rdar://21715350
func testNonNilError() throws -> Float {
return try ErrorProne.bounce()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors15testNonNilErrorSfyKF :
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.bounce!foreign : (ErrorProne.Type) -> () throws -> Float, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Float
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: assign {{%.*}} to [[OPTERR]]
// CHECK: [[T0:%.*]] = load [take] [[OPTERR]]
// CHECK: switch_enum [[T0]] : $Optional<NSError>, case #Optional.some!enumelt: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResult() throws -> CInt {
return try ErrorProne.ounce()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors19testPreservedResults5Int32VyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounce!foreign : (ErrorProne.Type) -> () throws -> Int32, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultBridged() throws -> Int {
return try ErrorProne.ounceWord()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors26testPreservedResultBridgedSiyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounceWord!foreign : (ErrorProne.Type) -> () throws -> Int, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int{{.*}}"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultInverted() throws {
try ErrorProne.once()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors27testPreservedResultInvertedyyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.once!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[ERROR_BB:bb[0-9]+]], [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return {{%.+}} : $()
// CHECK: [[ERROR_BB]]
// Make sure that we do not crash when emitting the error value here.
//
// TODO: Add some additional filecheck tests.
extension NSURL {
func resourceValue<T>(forKey key: String) -> T? {
var prop: AnyObject? = nil
_ = try? self.getResourceValue(&prop, forKey: key)
return prop as? T
}
}
| 61.637224 | 340 | 0.657352 |
9b5e4632370a0be7e91df10428a53afba7597f2d | 3,294 | //
// NotificationCenterTests.swift
// Tests
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxCocoa
import class Foundation.NotificationCenter
import class Foundation.NSObject
import struct Foundation.Notification
class NSNotificationCenterTests : RxTest {
func testNotificationCenterWithoutObject() {
let notificationCenter = NotificationCenter()
var numberOfNotifications = 0
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: nil)
XCTAssertTrue(numberOfNotifications == 0)
let subscription = notificationCenter.rx.notification(Notification.Name(rawValue: "testNotification"), object: nil)
.subscribe(onNext: { _ in
numberOfNotifications += 1
})
XCTAssertTrue(numberOfNotifications == 0)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: nil)
XCTAssertTrue(numberOfNotifications == 1)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: NSObject())
XCTAssertTrue(numberOfNotifications == 2)
subscription.dispose()
XCTAssertTrue(numberOfNotifications == 2)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: nil)
XCTAssertTrue(numberOfNotifications == 2)
}
func testNotificationCenterWithObject() {
let notificationCenter = NotificationCenter()
var numberOfNotifications = 0
let targetObject = NSObject()
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: targetObject)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: nil)
XCTAssertTrue(numberOfNotifications == 0)
let subscription = notificationCenter.rx.notification(Notification.Name(rawValue: "testNotification"), object: targetObject)
.subscribe(onNext: { _ in
numberOfNotifications += 1
})
XCTAssertTrue(numberOfNotifications == 0)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: targetObject)
XCTAssertTrue(numberOfNotifications == 1)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: nil)
XCTAssertTrue(numberOfNotifications == 1)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: NSObject())
XCTAssertTrue(numberOfNotifications == 1)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: targetObject)
XCTAssertTrue(numberOfNotifications == 2)
subscription.dispose()
XCTAssertTrue(numberOfNotifications == 2)
notificationCenter.post(name: Notification.Name(rawValue: "testNotification"), object: targetObject)
XCTAssertTrue(numberOfNotifications == 2)
}
}
| 34.673684 | 132 | 0.664238 |
264e8f3222df349f33639d738fc5816cee706c46 | 3,166 | //
// MainCoordinator.swift
//
// Created by Sergio Sánchez Sánchez on 30/3/21.
//
import Foundation
import UIKit
import shared
/// Panrent of all coordinators, responsible to set flows.
final class MainCoordinator: Coordinator {
var childsCoordinator: [String: Coordinator] = [:]
let navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func start() {
let charactersVC = buildCharactersViewController()
let locationsVC = buildLocationsViewController()
let episodesVC = buildEpisodesViewController()
let tabBarController = UITabBarController()
tabBarController.title = "Rick And Morty KMP"
tabBarController.viewControllers = [charactersVC, locationsVC, episodesVC]
tabBarController.selectedViewController = charactersVC
navigationController.setViewControllers([tabBarController], animated: false)
}
private func buildCharactersViewController() -> CharactersViewController {
let getCharactersInteract = koin.get(objCClass: GetCharactersInteract.self, qualifier: nil) as! GetCharactersInteract
let kermit = koin.get(objCClass: Kermit.self, parameter: "CharactersViewModel") as! Kermit
let charactersViewModel = CharactersViewModel(getCharactersInteract: getCharactersInteract, kermit: kermit)
let charactersTableVC = CharactersViewController()
charactersTableVC.viewModel = charactersViewModel
charactersTableVC.coordinator = self
let item = UITabBarItem()
item.title = "Characters"
item.image = UIImage(systemName: "person.3.fill")
charactersTableVC.tabBarItem = item
return charactersTableVC
}
private func buildLocationsViewController() -> LocationsViewController {
let getLocationsInteract = koin.get(objCClass: GetLocationsInteract.self, qualifier: nil) as! GetLocationsInteract
let locationsViewModel = LocationsViewModel(getLocationsInteract: getLocationsInteract)
let locationsTableVC = LocationsViewController()
locationsTableVC.viewModel = locationsViewModel
locationsTableVC.coordinator = self
let item = UITabBarItem()
item.title = "Locations"
item.image = UIImage(systemName: "location.fill")
locationsTableVC.tabBarItem = item
return locationsTableVC
}
private func buildEpisodesViewController() -> EpisodesViewController {
let getEpisodesInteract = koin.get(objCClass: GetEpisodesInteract.self, qualifier: nil) as! GetEpisodesInteract
let episodesViewModel = EpisodesViewModel(getEpisodesInteract: getEpisodesInteract)
let episodesTableVC = EpisodesViewController()
episodesTableVC.viewModel = episodesViewModel
episodesTableVC.coordinator = self
let item = UITabBarItem()
item.title = "Episodes"
item.image = UIImage(systemName: "play.tv.fill")
episodesTableVC.tabBarItem = item
return episodesTableVC
}
}
| 39.575 | 125 | 0.713834 |
f7bba77a453053a1676f042429f54f23380514b1 | 3,780 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import Foundation
import AWSSDKSwiftCore
/**
AWS Mobile Service provides mobile app and website developers with capabilities required to configure AWS resources and bootstrap their developer desktop projects with the necessary SDKs, constants, tools and samples to make use of those resources.
*/
public struct Mobile {
let client: AWSClient
public init(accessKeyId: String? = nil, secretAccessKey: String? = nil, region: AWSSDKSwiftCore.Region? = nil, endpoint: String? = nil) {
self.client = AWSClient(
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
service: "mobile",
serviceProtocol: ServiceProtocol(type: .restjson, version: ServiceProtocol.Version(major: 1, minor: 1)),
apiVersion: "2017-07-01",
endpoint: endpoint,
middlewares: [],
possibleErrorTypes: [MobileErrorType.self]
)
}
/// Get the bundle details for the requested bundle id.
public func describeBundle(_ input: DescribeBundleRequest) throws -> DescribeBundleResult {
return try client.send(operation: "DescribeBundle", path: "/bundles/{bundleId}", httpMethod: "GET", input: input)
}
/// Lists projects in AWS Mobile Hub.
public func listProjects(_ input: ListProjectsRequest) throws -> ListProjectsResult {
return try client.send(operation: "ListProjects", path: "/projects", httpMethod: "GET", input: input)
}
/// Generates customized software development kit (SDK) and or tool packages used to integrate mobile web or mobile app clients with backend AWS resources.
public func exportBundle(_ input: ExportBundleRequest) throws -> ExportBundleResult {
return try client.send(operation: "ExportBundle", path: "/bundles/{bundleId}", httpMethod: "POST", input: input)
}
/// Gets details about a project in AWS Mobile Hub.
public func describeProject(_ input: DescribeProjectRequest) throws -> DescribeProjectResult {
return try client.send(operation: "DescribeProject", path: "/project", httpMethod: "GET", input: input)
}
/// Update an existing project.
public func updateProject(_ input: UpdateProjectRequest) throws -> UpdateProjectResult {
return try client.send(operation: "UpdateProject", path: "/update", httpMethod: "POST", input: input)
}
/// List all available bundles.
public func listBundles(_ input: ListBundlesRequest) throws -> ListBundlesResult {
return try client.send(operation: "ListBundles", path: "/bundles", httpMethod: "GET", input: input)
}
/// Creates an AWS Mobile Hub project.
public func createProject(_ input: CreateProjectRequest) throws -> CreateProjectResult {
return try client.send(operation: "CreateProject", path: "/projects", httpMethod: "POST", input: input)
}
/// Exports project configuration to a snapshot which can be downloaded and shared. Note that mobile app push credentials are encrypted in exported projects, so they can only be shared successfully within the same AWS account.
public func exportProject(_ input: ExportProjectRequest) throws -> ExportProjectResult {
return try client.send(operation: "ExportProject", path: "/exports/{projectId}", httpMethod: "POST", input: input)
}
/// Delets a project in AWS Mobile Hub.
public func deleteProject(_ input: DeleteProjectRequest) throws -> DeleteProjectResult {
return try client.send(operation: "DeleteProject", path: "/projects/{projectId}", httpMethod: "DELETE", input: input)
}
} | 51.780822 | 250 | 0.703704 |
6495858a4cc0112672991bbf5abbc83b44fb6f13 | 2,696 | //
// ImagePickerProtocol.swift
// FilePickerProtocol
//
// Created by Akshay Garg on 30/09/18.
// Copyright © 2018 Akshay Garg. All rights reserved.
//
import UIKit
protocol ImagePickerProtocol : AuthorizationProtocol {
func openCamera(showFront : Bool)
func openGallery()
}
extension ImagePickerProtocol {
func openCamera(showFront : Bool) { }
func openGallery() { }
}
extension ImagePickerProtocol where Self : UIViewController & UIImagePickerControllerDelegate & UINavigationControllerDelegate {
private var imagePickerController : UIImagePickerController {
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = false
imagePickerController.delegate = self
return imagePickerController
}
func openCamera(showFront : Bool) {
checkCameraAuthorization { (authorized) in
if authorized {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let picker = self.imagePickerController
picker.sourceType = .camera
picker.cameraDevice = showFront ? .front : .rear
self.present(picker, animated: true, completion: nil)
} else {
self.openGallery()
}
} else {
self.showGoToSettingsAlert(isCamera: true)
}
}
}
func openGallery() {
checkGalleryAuthorization { (authorized) in
if authorized {
let picker = self.imagePickerController
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
} else {
self.showGoToSettingsAlert(isCamera: false)
}
}
}
private func showGoToSettingsAlert(isCamera : Bool) {
let text = isCamera ? "Camera" : "Gallery"
let alert = UIAlertController(title: "No \(text) Access", message: "Permission for \(text) is not granted. Please go to settings to enable \(text) access.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Go to Settings", style: .destructive, handler: { (_) in
if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
DispatchQueue.main.async{
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}))
present(alert, animated: true, completion: nil)
}
}
| 35.946667 | 188 | 0.613501 |
3a996e16f21e1d6eb4d1500e54f358606c9974da | 1,934 | import Foundation
import SpriteKit
import RxSwift
import RxCocoa
extension Reactive where Base: SKScene {
public var didChangeSize: ControlEvent<CGSize> {
let source = self.methodInvoked(#selector(Base.didChangeSize)).map { $0.first as? CGSize ?? CGSize.zero }
return ControlEvent(events: source)
}
public var sceneDidLoad: ControlEvent<Void> {
let source = self.methodInvoked(#selector(Base.sceneDidLoad)).map { _ in }
return ControlEvent(events: source)
}
#if os(iOS) || os(macOS) || os(tvOS)
public var willMove: ControlEvent<SKView> {
let source = self.methodInvoked(#selector(Base.willMove)).map { $0.first as! SKView }
return ControlEvent(events: source)
}
public var didMove: ControlEvent<SKView> {
let source = self.methodInvoked(#selector(Base.didMove)).map { $0.first as! SKView }
return ControlEvent(events: source)
}
#endif
public var update: ControlEvent<TimeInterval> {
let source = self.methodInvoked(#selector(Base.update)).map { $0.first as? TimeInterval ?? 0 }
return ControlEvent(events: source)
}
public var didEvaluateActions: ControlEvent<Void> {
let source = self.methodInvoked(#selector(Base.didEvaluateActions)).map { _ in }
return ControlEvent(events: source)
}
public var didSimulatePhysics: ControlEvent<Void> {
let source = self.methodInvoked(#selector(Base.didSimulatePhysics)).map { _ in }
return ControlEvent(events: source)
}
public var didApplyConstraints: ControlEvent<Void> {
let source = self.methodInvoked(#selector(Base.didApplyConstraints)).map { _ in }
return ControlEvent(events: source)
}
public var didFinishUpdate: ControlEvent<Void> {
let source = self.methodInvoked(#selector(Base.didFinishUpdate)).map { _ in }
return ControlEvent(events: source)
}
}
| 34.535714 | 113 | 0.678904 |
1cc303e010e6cb7d347c02f894654b7c2435fdfc | 955 | //
// Label.swift
// Tentacle
//
// Created by Romain Pouclet on 2016-05-23.
// Copyright © 2016 Matt Diephouse. All rights reserved.
//
import Foundation
public struct Label: CustomStringConvertible, ResourceType {
public let name: String
public let color: Color
public var description: String {
return name
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.color = Color(hex: try container.decode(String.self, forKey: .color))
}
public init(name: String, color: Color) {
self.name = name
self.color = color
}
private enum CodingKeys: String, CodingKey {
case name
case color
}
}
extension Label: Hashable {
public static func ==(lhs: Label, rhs: Label) -> Bool {
return lhs.name == rhs.name
}
}
| 22.738095 | 82 | 0.638743 |
b9f8a4ed40cde887c3aa3614183b7bad5b05f0fb | 2,216 | //
// ArtistViewController.swift
// MobileChallenge
//
// Created by Erwan Hesry on 12/03/2021.
//
import UIKit
class ArtistViewController: UIViewController {
// MARK: - Properties
var viewModel: ArtistViewModelType? {
didSet {
viewModel?.viewDelegate = self
}
}
let favoriteButton = UIBarButtonItem.init(image: UIImage.init(systemName: "star"), style: .plain, target: self, action: #selector(onFavoriteButtonTouched))
@IBOutlet weak var name: UILabel!
@IBOutlet weak var disambiguation: UILabel!
@IBOutlet weak var ratingVoteCount: UILabel!
@IBOutlet weak var ratingValue: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = viewModel?.artistName
if let vm = viewModel, vm.isAbookmarkArtist() {
favoriteButton.image = UIImage.init(systemName: "star.fill")
}
favoriteButton.target = self
self.navigationItem.rightBarButtonItem = favoriteButton
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewModel?.onCloseArtist()
}
@objc func onFavoriteButtonTouched() {
viewModel?.manageArtistBookmark()
}
}
extension ArtistViewController: ArtistViewModelViewDelegate {
func updateScreen() {
if let artist = viewModel?.artist {
self.name.text = artist.name
self.disambiguation.text = artist.disambiguation
if let rating = artist.rating, let ratingValue = rating.value {
self.ratingValue.text = "ratingValue".localizeWithFormat(inTable: "Artist", ratingValue)
self.ratingVoteCount.text = "ratingCount".localizeWithFormat(inTable: "Artist", rating.voteCount)
}
}
if let vm = viewModel {
if vm.isAbookmarkArtist() {
favoriteButton.image = UIImage.init(systemName: "star.fill")
} else {
favoriteButton.image = UIImage.init(systemName: "star")
}
}
}
}
| 31.657143 | 159 | 0.634025 |
f97a8ac2547e0a81fe863d977b391718c669c988 | 2,025 | //
// SampleViewController1.swift
// vs-metal
//
// Created by SATOSHI NAKAJIMA on 6/20/17.
// Copyright © 2017 SATOSHI NAKAJIMA. All rights reserved.
//
import UIKit
import MetalKit
class SampleViewController1: UIViewController {
@IBOutlet var mtkView:MTKView!
let context = VSContext(device: MTLCreateSystemDefaultDevice()!)
var runtime:VSRuntime?
lazy var session:VSCaptureSession = VSCaptureSession(device: self.context.device, pixelFormat: self.context.pixelFormat, delegate: self.context)
lazy var renderer:VSRenderer = VSRenderer(device:self.context.device, pixelFormat:self.context.pixelFormat)
override func viewDidLoad() {
super.viewDidLoad()
mtkView.device = context.device
mtkView.delegate = self
context.pixelFormat = mtkView.colorPixelFormat
// This is a VideoShader script, which represents a cartoon filter
let json = [
"pipeline":[
[ "name":"gaussian_blur", "attr":["sigma": 2.0] ],
[ "name":"fork" ],
[ "name":"gaussian_blur", "attr":["sigma": 2.0] ],
[ "name":"toone" ],
[ "name":"swap" ],
[ "name":"sobel"],
[ "name":"canny_edge", "attr":["threshold": 0.19, "thin": 0.50] ],
[ "name":"anti_alias" ],
[ "name":"alpha" ],
]
]
let script = VSScript(json: json)
runtime = script.compile(context: context)
session.start()
}
}
extension SampleViewController1 : MTKViewDelegate {
public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {}
public func draw(in view: MTKView) {
if context.hasUpdate {
runtime?.encode(commandBuffer:context.makeCommandBuffer(), context:context).commit()
renderer.encode(commandBuffer:context.makeCommandBuffer(), view:view, texture: context.pop()?.texture)?.commit()
context.flush()
}
}
}
| 33.196721 | 148 | 0.602963 |
48c95b94c1532bcf77d1e808339c74c38bf169b3 | 5,903 | //
// DetailPostViewController.swift
//
//
// Created by Nidhi Manoj on 6/22/16.
//
//
import UIKit
import Parse
import ParseUI
class DetailPostViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var captionLabel: UILabel!
@IBOutlet weak var timeStampLabel: UILabel!
@IBOutlet weak var likesCountLabel: UILabel!
@IBOutlet weak var commentsCountLabel: UILabel!
@IBOutlet weak var photoView: PFImageView!
@IBOutlet weak var commentTextField: UITextField!
@IBOutlet weak var commentsTableView: UITableView!
var post: PFObject!
var commentsUserArray: [PFUser] = []
var commentsCommentsTextArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let caption = post["caption"] as? String
captionLabel.text = caption
let likesCountText = String(post["likesCount"])
likesCountLabel.text = likesCountText + " likes"
let timeStampLabelText = String(post["timeStamp"])
timeStampLabel.text = timeStampLabelText ?? "time unknown"
let authorUser = post["author"] as! PFUser
authorLabel.text = authorUser.username ?? ""
if let photoImage = post.valueForKey("media") as? PFFile {
photoView.file = photoImage
photoView.loadInBackground()
}
commentsTableView.delegate = self
commentsTableView.dataSource = self
updateCommentTable()
}
private func updateCommentTable(){
let commentsCountText = String(post["commentsCount"])
commentsCountLabel.text = commentsCountText + " comments"
//Handle Comments table View
let postCommentsUserArray = post.objectForKey("commentsArrayUsers") as? [PFUser]
if let postCommentsUserArray = postCommentsUserArray {
commentsUserArray = postCommentsUserArray
}
let postCommentsTextArray = post.valueForKey("commentsArrayComments") as? [String]
if let postCommentsTextArray = postCommentsTextArray {
commentsCommentsTextArray = postCommentsTextArray
}
commentsTableView.reloadData() // Reload the tableView now that there is new data
}
/* Function: numberOfRowsInSection
* This function sets the number of rows in commentsTableView
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return commentsCommentsTextArray.count//commentsUserArray.count
}
/* Function: cellForRowAtIndexPath
* This function describes how to populate a given CommentCell
* within the commentsTableView
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let commentCell = tableView.dequeueReusableCellWithIdentifier("CommentCell", forIndexPath: indexPath) as! CommentCell
if( indexPath.row < commentsUserArray.count ){
do {
let commentUser = try (commentsUserArray[indexPath.row]).fetchIfNeeded()
let commentUserUsername = commentUser.username
commentCell.userLabel.text = commentUserUsername?.capitalizedString
} catch {
commentCell.userLabel.text = ""
}
}else{
commentCell.userLabel.text = "Unknown User"
}
print("commentUsername is \(commentCell.userLabel.text)")
let commentText = commentsCommentsTextArray[indexPath.row]
commentCell.commentTextLabel.text = commentText
print("commentText is \(commentText)")
return commentCell
}
@IBAction func addCommentClicked(sender: AnyObject) {
//Updates the commentsCount field of the post
let oldCommentNum = post.valueForKey("commentsCount") as! Int
post["commentsCount"] = oldCommentNum + 1
//Updates the field "commentsArrayUsers" in the post by appending a user
if var usersArrayForComments = post["commentsArrayUsers"] as? [PFUser] {
usersArrayForComments.append(PFUser.currentUser()!)
post["commentsArrayUsers"] = usersArrayForComments
} else {
//The commentsArrayUsers is nil so we want to initialize an array and then append the current user as the first element
var newArrayOfUsers : [PFUser] = []
newArrayOfUsers.append(PFUser.currentUser()!)
post["commentsArrayUsers"] = newArrayOfUsers
}
//Update the field "commentsArrayComments" in the post by appending a comment text string
let commentsTextArrayForComments = post["commentsArrayComments"] as? [String]
if var commentsTextArrayForComments = commentsTextArrayForComments {
commentsTextArrayForComments.append(commentTextField.text!)
post["commentsArrayComments"] = commentsTextArrayForComments
} else {
//The commentsArrayComments is nil so we want to initialize an array and then append this text as the first element
var newArrayOfComments : [String] = []
newArrayOfComments.append(commentTextField.text!)
post["commentsArrayComments"] = newArrayOfComments
}
//Make sure to save in background to actually save network updates to the post's fields
post.saveInBackgroundWithBlock { (success: Bool, error: NSError?) in
//self.viewDidLoad()
dispatch_async(dispatch_get_main_queue()){
self.updateCommentTable()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 38.083871 | 131 | 0.658309 |
0345137a424f27ef00808b5288a2b3eb92162d03 | 895 | //
// Cash4PooTests.swift
// Cash4PooTests
//
// Created by brandon on 7/1/15.
// Copyright (c) 2015 cbcoding. All rights reserved.
//
import UIKit
import XCTest
class Cash4PooTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.189189 | 111 | 0.613408 |
20f285ea2c46b4fd04ea62485ed4254414e7bd06 | 6,132 | import Foundation
import UIKit
import AsyncDisplayKit
import Display
import TelegramCore
import SyncCore
import Postbox
import TelegramPresentationData
import AvatarNode
import AccountContext
public class VoiceChatPeerActionSheetItem: ActionSheetItem {
public let context: AccountContext
public let peer: Peer
public let title: String
public let subtitle: String
public let action: () -> Void
public init(context: AccountContext, peer: Peer, title: String, subtitle: String, action: @escaping () -> Void) {
self.context = context
self.peer = peer
self.title = title
self.subtitle = subtitle
self.action = action
}
public func node(theme: ActionSheetControllerTheme) -> ActionSheetItemNode {
let node = VoiceChatPeerActionSheetItemNode(theme: theme)
node.setItem(self)
return node
}
public func updateNode(_ node: ActionSheetItemNode) {
guard let node = node as? VoiceChatPeerActionSheetItemNode else {
assertionFailure()
return
}
node.setItem(self)
node.requestLayoutUpdate()
}
}
private let avatarFont = avatarPlaceholderFont(size: 15.0)
public class VoiceChatPeerActionSheetItemNode: ActionSheetItemNode {
private let theme: ActionSheetControllerTheme
private let defaultFont: UIFont
private var item: VoiceChatPeerActionSheetItem?
private let button: HighlightTrackingButton
private let avatarNode: AvatarNode
private let titleNode: ImmediateTextNode
private let subtitleNode: ImmediateTextNode
private let accessibilityArea: AccessibilityAreaNode
override public init(theme: ActionSheetControllerTheme) {
self.theme = theme
self.defaultFont = Font.regular(floor(theme.baseFontSize * 20.0 / 17.0))
self.button = HighlightTrackingButton()
self.button.isAccessibilityElement = false
self.avatarNode = AvatarNode(font: avatarFont)
self.avatarNode.isLayerBacked = !smartInvertColorsEnabled()
self.avatarNode.isAccessibilityElement = false
self.titleNode = ImmediateTextNode()
self.titleNode.isUserInteractionEnabled = false
self.titleNode.displaysAsynchronously = false
self.titleNode.maximumNumberOfLines = 1
self.titleNode.isAccessibilityElement = false
self.subtitleNode = ImmediateTextNode()
self.subtitleNode.isUserInteractionEnabled = false
self.subtitleNode.displaysAsynchronously = false
self.subtitleNode.maximumNumberOfLines = 1
self.subtitleNode.isAccessibilityElement = false
self.accessibilityArea = AccessibilityAreaNode()
super.init(theme: theme)
self.view.addSubview(self.button)
self.addSubnode(self.avatarNode)
self.addSubnode(self.titleNode)
self.addSubnode(self.subtitleNode)
self.addSubnode(self.accessibilityArea)
self.button.highligthedChanged = { [weak self] highlighted in
if let strongSelf = self {
if highlighted {
strongSelf.backgroundNode.backgroundColor = strongSelf.theme.itemHighlightedBackgroundColor
} else {
UIView.animate(withDuration: 0.3, animations: {
strongSelf.backgroundNode.backgroundColor = strongSelf.theme.itemBackgroundColor
})
}
}
}
self.button.addTarget(self, action: #selector(self.buttonPressed), for: .touchUpInside)
self.accessibilityArea.activate = { [weak self] in
self?.buttonPressed()
return true
}
}
func setItem(_ item: VoiceChatPeerActionSheetItem) {
self.item = item
let titleFont = Font.regular(floor(self.theme.baseFontSize ))
self.titleNode.attributedText = NSAttributedString(string: item.title, font: titleFont, textColor: self.theme.primaryTextColor)
let subtitleFont = Font.regular(floor(self.theme.baseFontSize * 13.0 / 17.0))
self.subtitleNode.attributedText = NSAttributedString(string: item.subtitle, font: subtitleFont, textColor: self.theme.secondaryTextColor)
let theme = item.context.sharedContext.currentPresentationData.with { $0 }.theme
self.avatarNode.setPeer(context: item.context, theme: theme, peer: item.peer)
self.accessibilityArea.accessibilityTraits = [.button]
self.accessibilityArea.accessibilityLabel = item.title
self.accessibilityArea.accessibilityValue = item.subtitle
}
public override func updateLayout(constrainedSize: CGSize, transition: ContainedViewLayoutTransition) -> CGSize {
let size = CGSize(width: constrainedSize.width, height: 57.0)
self.button.frame = CGRect(origin: CGPoint(), size: size)
let avatarInset: CGFloat = 42.0
let avatarSize: CGFloat = 36.0
self.avatarNode.frame = CGRect(origin: CGPoint(x: size.width - avatarSize - 14.0, y: floor((size.height - avatarSize) / 2.0)), size: CGSize(width: avatarSize, height: avatarSize))
let titleSize = self.titleNode.updateLayout(CGSize(width: max(1.0, size.width - avatarInset - 16.0 - 16.0 - 30.0), height: size.height))
self.titleNode.frame = CGRect(origin: CGPoint(x: 16.0, y: 9.0), size: titleSize)
let subtitleSize = self.subtitleNode.updateLayout(CGSize(width: max(1.0, size.width - avatarInset - 16.0 - 16.0 - 30.0), height: size.height))
self.subtitleNode.frame = CGRect(origin: CGPoint(x: 16.0, y: 32.0), size: subtitleSize)
self.accessibilityArea.frame = CGRect(origin: CGPoint(), size: size)
self.updateInternalLayout(size, constrainedSize: constrainedSize)
return size
}
@objc private func buttonPressed() {
if let item = self.item {
item.action()
}
}
}
| 38.086957 | 187 | 0.660959 |
acd239e2f31ef8617aea1471906375bc2c86fae8 | 887 | //
// JSONParameterEncoder.swift
// NetworkManager
//
// Created by Ahmed Moussa on 1/15/20.
// Copyright © 2020 Ahmed Moussa. All rights reserved.
//
import Foundation
public class JSONParameterEncoder: ParameterEncoder {
public init() {}
public func encode(urlRequest: URLRequest, with parameters: Parameters) -> URLRequest {
var urlRequestAfterEncoding = urlRequest
if parameters.count > 0 {
if JSONSerialization.isValidJSONObject(parameters) {
urlRequestAfterEncoding.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
}
}
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequestAfterEncoding.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
return urlRequestAfterEncoding
}
}
| 31.678571 | 131 | 0.678692 |
f50a29c040ab011a5f87721bf5eec1f65159bb62 | 6,937 | // Copyright (c) 2020 Spotify AB.
//
// 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
/// - Callout(Instantiating): Use `Mobius.loop(update:effectHandler:)` to create an instance.
public final class MobiusLoop<Model, Event, Effect>: Disposable, CustomDebugStringConvertible {
private let eventProcessor: EventProcessor<Model, Event, Effect>
private let consumeEvent: Consumer<Event>
private let modelPublisher: ConnectablePublisher<Model>
private let disposable: Disposable
private var disposed = false
private var access: ConcurrentAccessDetector
private var workBag: WorkBag
public var debugDescription: String {
return access.guard {
if disposed {
return "disposed \(type(of: self))!"
}
return "\(type(of: self)) \(eventProcessor)"
}
}
init(
eventProcessor: EventProcessor<Model, Event, Effect>,
consumeEvent: @escaping Consumer<Event>,
modelPublisher: ConnectablePublisher<Model>,
disposable: Disposable,
accessGuard: ConcurrentAccessDetector,
workBag: WorkBag
) {
self.eventProcessor = eventProcessor
self.consumeEvent = consumeEvent
self.modelPublisher = modelPublisher
self.disposable = disposable
self.access = accessGuard
self.workBag = workBag
}
/// Add an observer of model changes to this loop. If `getMostRecentModel()` is non-nil,
/// the observer will immediately be notified of the most recent model. The observer will be
/// notified of future changes to the model until the loop or the returned `Disposable` is
/// disposed.
/// - Parameter consumer: an observer of model changes
/// - Returns: a `Disposable` that can be used to stop further notifications to the observer
@discardableResult
public func addObserver(_ consumer: @escaping Consumer<Model>) -> Disposable {
return access.guard {
modelPublisher.connect(to: consumer)
}
}
public func dispose() {
return access.guard {
if !disposed {
modelPublisher.dispose()
eventProcessor.dispose()
disposable.dispose()
disposed = true
}
}
}
deinit {
dispose()
}
public var latestModel: Model {
return access.guard { eventProcessor.latestModel }
}
public func dispatchEvent(_ event: Event) {
return access.guard {
guard !disposed else {
// Callers are responsible for ensuring dispatchEvent is never entered after dispose.
MobiusHooks.errorHandler("\(Self.debugTag): event submitted after dispose", #file, #line)
}
unguardedDispatchEvent(event)
}
}
/// Like `dispatchEvent`, but without asserting that the loop hasn’t been disposed.
///
/// This should not be used directly, but is useful in constructing asynchronous wrappers around loops (like
/// `MobiusController`, where the eventConsumerTransformer is used to implement equivalent async-safe assertions).
public func unguardedDispatchEvent(_ event: Event) {
consumeEvent(event)
}
// swiftlint:disable:next function_parameter_count
static func createLoop<EffectHandler: Connectable>(
update: Update<Model, Event, Effect>,
effectHandler: EffectHandler,
initialModel: Model,
effects: [Effect],
eventSource: AnyEventSource<Event>,
eventConsumerTransformer: ConsumerTransformer<Event>,
logger: AnyMobiusLogger<Model, Event, Effect>
) -> MobiusLoop where EffectHandler.Input == Effect, EffectHandler.Output == Event {
let accessGuard = ConcurrentAccessDetector()
let loggingUpdate = update.logging(logger)
let workBag = WorkBag(accessGuard: accessGuard)
// create somewhere for the event processor to push nexts to; later, we'll observe these nexts and
// dispatch models and effects to the right places
let nextPublisher = ConnectablePublisher<Next<Model, Effect>>(accessGuard: accessGuard)
// event processor: process events, publish Next:s, retain current model
let eventProcessor = EventProcessor(
update: loggingUpdate,
publisher: nextPublisher,
accessGuard: accessGuard
)
let consumeEvent = eventConsumerTransformer { event in
workBag.submit {
eventProcessor.accept(event)
}
workBag.service()
}
// effect handler: handle effects, push events to the event processor
let effectHandlerConnection = effectHandler.connect(consumeEvent)
let eventSourceDisposable = eventSource.subscribe(consumer: consumeEvent)
// model observer support
let modelPublisher = ConnectablePublisher<Model>()
// ensure model updates get published and effects dispatched to the effect handler
let nextConsumer: Consumer<Next<Model, Effect>> = { next in
if let model = next.model {
modelPublisher.post(model)
}
next.effects.forEach({ (effect: Effect) in
workBag.submit {
effectHandlerConnection.accept(effect)
}
})
workBag.service()
}
let nextConnection = nextPublisher.connect(to: nextConsumer)
// everything is hooked up, start processing!
eventProcessor.start(from: initialModel, effects: effects)
return MobiusLoop(
eventProcessor: eventProcessor,
consumeEvent: consumeEvent,
modelPublisher: modelPublisher,
disposable: CompositeDisposable(disposables: [
eventSourceDisposable,
nextConnection,
effectHandlerConnection,
]),
accessGuard: accessGuard,
workBag: workBag
)
}
private static var debugTag: String {
return "MobiusLoop<\(Model.self), \(Event.self), \(Effect.self)>"
}
}
| 37.497297 | 118 | 0.651867 |
715df6989774c01708eb47253eb71abe5b6afd01 | 12,371 | //
// KPPayViewController.swift
// KyberPayiOS
//
// Created by Manh Le on 6/8/18.
// Copyright © 2018 manhlx. All rights reserved.
//
import UIKit
import BigInt
public enum KPPayViewEvent {
case close
case selectToken(token: KPTokenObject)
case getBalance(token: KPTokenObject)
case estGastLimit(payment: KPPayment)
case estSwapRate(from: KPTokenObject, to: KPTokenObject, amount: BigInt)
case process(payment: KPPayment)
}
public protocol KPPayViewControllerDelegate: class {
func payViewController(_ controller: KPPayViewController, run event: KPPayViewEvent)
}
public class KPPayViewController: UIViewController {
weak var delegate: KPPayViewControllerDelegate?
fileprivate var viewModel: KPPayViewModel
@IBOutlet weak var scrollContainerView: UIScrollView!
@IBOutlet weak var tokenContainerView: UIView!
@IBOutlet weak var receiverAddressLabel: UILabel!
@IBOutlet weak var srcAddressLabel: UILabel!
@IBOutlet weak var srcTokenButton: UIButton!
@IBOutlet weak var srcAmountTextField: UITextField!
@IBOutlet weak var receiverTokenButton: UIButton!
@IBOutlet weak var receiverAmountTextField: UITextField!
@IBOutlet weak var tokenBalanceTextLabel: UILabel!
@IBOutlet weak var tokenBalanceValueLabel: UILabel!
@IBOutlet weak var estimatedRateValueLabel: UILabel!
@IBOutlet weak var advanceSettingsOptionButton: UIButton!
@IBOutlet weak var advancedSettingsView: UIView!
@IBOutlet weak var gasPriceSegmentedControl: UISegmentedControl!
@IBOutlet weak var gasPriceTextField: UITextField!
@IBOutlet weak var minRateSlider: CustomSlider!
@IBOutlet weak var minRatePercentLabel: UILabel!
@IBOutlet weak var leadingConstraintForMinRatePercentLabel: NSLayoutConstraint!
@IBOutlet weak var minRateValueLabel: UILabel!
@IBOutlet weak var heightConstaintForAdvancedSettingsView: NSLayoutConstraint!
@IBOutlet weak var payButton: UIButton!
fileprivate var loadTimer: Timer?
public init(viewModel: KPPayViewModel) {
self.viewModel = viewModel
super.init(nibName: "KPPayViewController", bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.loadTimer?.invalidate()
self.reloadDataFromNode()
self.loadTimer = Timer.scheduledTimer(
withTimeInterval: 10.0,
repeats: true,
block: { [weak self] _ in
self?.reloadDataFromNode()
})
}
override public func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.loadTimer?.invalidate()
self.loadTimer = nil
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tokenContainerView.addShadow(
color: UIColor.black.withAlphaComponent(0.5),
offset: CGSize(width: 0, height: 7),
opacity: 0.32,
radius: 32
)
}
fileprivate func setupUI() {
self.setupTokenContainerView()
self.setupAdvancedSettingsView()
}
fileprivate func setupTokenContainerView() {
self.receiverAddressLabel.text = self.viewModel.displayReceiverAddress
self.srcAddressLabel.text = self.viewModel.displaySrcAddressString
self.srcAmountTextField.text = ""
self.viewModel.updateFromAmount("")
self.srcAmountTextField.adjustsFontSizeToFitWidth = true
self.srcAmountTextField.delegate = self
if self.viewModel.receiverTokenAmount != nil {
self.receiverAmountTextField.text = self.viewModel.displayReceiverAmount
self.srcAmountTextField.text = self.viewModel.estimatedFromAmountDisplay
self.viewModel.updateFromAmount(self.srcAmountTextField.text ?? "")
self.srcAmountTextField.isEnabled = false
}
self.receiverAmountTextField.adjustsFontSizeToFitWidth = true
// Disable typing dest amount as new behaviour changed for web
self.receiverAmountTextField.isEnabled = false
self.srcTokenButton.setAttributedTitle(
self.viewModel.tokenButtonAttributedText(isSource: true),
for: .normal
)
self.srcTokenButton.setTokenImage(
token: self.viewModel.from,
size: self.viewModel.defaultTokenIconImg?.size
)
self.srcTokenButton.titleLabel?.numberOfLines = 2
self.srcTokenButton.titleLabel?.lineBreakMode = .byWordWrapping
self.receiverTokenButton.setAttributedTitle(
self.viewModel.tokenButtonAttributedText(isSource: false),
for: .normal
)
self.receiverTokenButton.setTokenImage(
token: self.viewModel.receiverToken,
size: self.viewModel.defaultTokenIconImg?.size
)
self.receiverTokenButton.semanticContentAttribute = .forceRightToLeft
self.receiverTokenButton.titleLabel?.numberOfLines = 2
self.receiverTokenButton.titleLabel?.lineBreakMode = .byWordWrapping
self.updateBalanceAndRate()
}
fileprivate func setupAdvancedSettingsView() {
self.gasPriceSegmentedControl.selectedSegmentIndex = 0
self.viewModel.updateSelectedGasPriceType(.fast)
self.gasPriceSegmentedControl.addTarget(self, action: #selector(self.gasPriceSegmentedControlDidTouch(_:)), for: .touchDown)
self.minRateSlider.isEnabled = self.viewModel.from != self.viewModel.receiverToken
self.minRateSlider.addTarget(self, action: #selector(self.minRatePercentDidChange(_:)), for: .valueChanged)
self.minRateSlider.value = self.viewModel.currentMinRatePercentValue
self.minRateValueLabel.text = self.viewModel.minRateText
self.minRatePercentLabel.text = self.viewModel.currentMinRatePercentText
self.leadingConstraintForMinRatePercentLabel.constant = (self.minRateSlider.frame.width - 32.0) * CGFloat(self.viewModel.currentMinRatePercentValue / 100.0)
self.advancedSettingsView.isHidden = true
self.heightConstaintForAdvancedSettingsView.constant = 0
self.advanceSettingsOptionButton.setTitle(
"Show Settings",
for: .normal
)
self.payButton.rounded(radius: self.payButton.frame.height / 2.0)
}
fileprivate func updateBalanceAndRate() {
self.tokenBalanceTextLabel.text = self.viewModel.balanceTextString
self.tokenBalanceValueLabel.text = self.viewModel.balanceValueString
self.estimatedRateValueLabel.text = self.viewModel.exchangeRateText
self.minRateSlider.isEnabled = self.viewModel.from != self.viewModel.receiverToken
self.minRateSlider.value = self.viewModel.currentMinRatePercentValue
self.minRateValueLabel.text = self.viewModel.minRateText
self.minRatePercentLabel.text = self.viewModel.currentMinRatePercentText
self.leadingConstraintForMinRatePercentLabel.constant = (self.minRateSlider.frame.width - 32.0) * CGFloat(self.viewModel.currentMinRatePercentValue / 100.0)
self.view.layoutIfNeeded()
}
@IBAction func backButtonPressed(_ sender: Any) {
}
@IBAction func srcTokenButtonPressed(_ sender: Any) {
}
@IBAction func advancedSettingsOptionPressed(_ sender: Any) {
let isHidden = !self.advancedSettingsView.isHidden
UIView.animate(
withDuration: 0.25,
animations: {
if isHidden { self.advancedSettingsView.isHidden = isHidden }
self.heightConstaintForAdvancedSettingsView.constant = isHidden ? 0.0 : 220.0
self.advanceSettingsOptionButton.setTitle(
isHidden ? "Show Settings" : "Hide Settings",
for: .normal
)
self.view.layoutIfNeeded()
}, completion: { _ in
self.advancedSettingsView.isHidden = isHidden
if !self.advancedSettingsView.isHidden {
let bottomOffset = CGPoint(
x: 0,
y: self.scrollContainerView.contentSize.height - self.scrollContainerView.bounds.size.height
)
self.scrollContainerView.setContentOffset(bottomOffset, animated: true)
}
})
}
@objc func gasPriceSegmentedControlDidTouch(_ sender: Any) {
let selectedId = self.gasPriceSegmentedControl.selectedSegmentIndex
self.viewModel.updateSelectedGasPriceType(KPGasPriceType(rawValue: selectedId) ?? KPGasPriceType.fast)
}
@objc func minRatePercentDidChange(_ sender: CustomSlider) {
let value = Int(floor(sender.value))
self.viewModel.updateExchangeMinRatePercent(Double(value))
self.minRateSlider.value = self.viewModel.currentMinRatePercentValue
self.minRateValueLabel.text = self.viewModel.minRateText
self.minRatePercentLabel.text = self.viewModel.currentMinRatePercentText
self.leadingConstraintForMinRatePercentLabel.constant = (self.minRateSlider.frame.width - 32.0) * CGFloat(self.viewModel.currentMinRatePercentValue / 100.0)
self.view.layoutIfNeeded()
}
@IBAction func proceedButtonPressed(_ sender: Any) {
}
fileprivate func reloadDataFromNode() {
let balanceEvent = KPPayViewEvent.getBalance(
token: self.viewModel.from
)
self.delegate?.payViewController(self, run: balanceEvent)
let estRateEvent = KPPayViewEvent.estSwapRate(
from: self.viewModel.from,
to: self.viewModel.receiverToken,
amount: self.viewModel.amountFromBigInt
)
self.delegate?.payViewController(self, run: estRateEvent)
let estGasLimitEvent = KPPayViewEvent.estGastLimit(payment: self.viewModel.payment)
self.delegate?.payViewController(self, run: estGasLimitEvent)
}
}
extension KPPayViewController: UITextFieldDelegate {
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
textField.text = ""
self.viewModel.updateFromAmount("")
self.updateViewAmountDidChange()
return false
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string).cleanStringToNumber()
if textField == self.srcAmountTextField, text.fullBigInt(decimals: self.viewModel.from.decimals) == nil { return false }
if text.isEmpty || Double(text) != nil {
textField.text = text
self.viewModel.updateFromAmount(text)
self.updateViewAmountDidChange()
}
return false
}
fileprivate func updateViewAmountDidChange() {
if self.viewModel.receiverTokenAmount == nil {
self.receiverAmountTextField.text = self.viewModel.estimatedReceivedAmountDisplay
} else {
self.srcAmountTextField.text = self.viewModel.estimatedFromAmountDisplay
self.viewModel.updateFromAmount(self.srcAmountTextField.text ?? "")
}
}
}
extension KPPayViewController {
func coordinatorUpdateBalance(for token: KPTokenObject, balance: BigInt) {
if token == self.viewModel.from {
self.viewModel.updateBalance([token.address: balance])
self.tokenBalanceValueLabel.text = self.viewModel.balanceValueString
}
}
func coordinatorUpdateExpectedRate(from: KPTokenObject, to: KPTokenObject, amount: BigInt, expectedRate: BigInt, slippageRate: BigInt) {
self.viewModel.updateExchangeRate(
for: from,
to: to,
amount: amount,
rate: expectedRate,
slippageRate: slippageRate
)
self.updateBalanceAndRate()
self.updateViewAmountDidChange()
}
func coordinatorUpdatePayToken(_ token: KPTokenObject) {
self.viewModel.updateSelectedToken(token)
self.minRateSlider.isEnabled = self.viewModel.from != self.viewModel.receiverToken
self.srcTokenButton.setAttributedTitle(
self.viewModel.tokenButtonAttributedText(isSource: true),
for: .normal
)
self.srcTokenButton.setTokenImage(
token: self.viewModel.from,
size: self.viewModel.defaultTokenIconImg?.size
)
self.srcAmountTextField.text = ""
self.viewModel.updateFromAmount("")
self.reloadDataFromNode()
self.updateBalanceAndRate()
self.updateViewAmountDidChange()
}
func coordinatorUpdateEstGasLimit(_ limit: BigInt, payment: KPPayment) {
self.viewModel.updateEstimateGasLimit(
for: payment.from,
to: payment.to,
amount: payment.amountFrom,
gasLimit: limit
)
}
}
class CustomSlider: UISlider {
override func trackRect(forBounds bounds: CGRect) -> CGRect {
let customBounds = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width, height: 8.0))
super.trackRect(forBounds: customBounds)
return customBounds
}
}
| 36.067055 | 160 | 0.749495 |
897c077a09791588285d718fe67236f1a156160b | 839 | //
// AppDelegate.swift
// RxUIApplicationDelegateExample
//
// Created by [email protected] on 09/12/2018.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import RxSwift
import RxUIApplicationDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let backing = RxUIApplicationDelegate(
initial: .empty
)
let cleanup = DisposeBag()
override init() {
backing.render(
new: .empty,
old: .empty
)
backing
.output
.subscribe { _ in }
.disposed(
by: cleanup
)
}
override open func forwardingTarget(for input: Selector!) -> Any? { return
backing
}
override open func responds(to input: Selector!) -> Bool { return
backing
.responds(
to: input
)
}
}
| 17.851064 | 76 | 0.642431 |
ab5d8945b01c7143499f732d69038e0003a50102 | 1,395 | // MIT License
//
// Copyright (c) 2017 Wesley Wickwire
//
// 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
struct EnumMetadata: NominalMetadataType {
var type: Any.Type
var metadata: UnsafeMutablePointer<EnumMetadataLayout>
var nominalTypeDescriptor: UnsafeMutablePointer<NominalTypeDescriptor>
var base: UnsafeMutablePointer<Int>
}
| 42.272727 | 81 | 0.770609 |
fcb035a94f9eed8456c06f8ddfc6905281d01566 | 1,615 | #if MIXBOX_ENABLE_IN_APP_SERVICES
// Provides @dynamicMemberLookup access to dictionary with fields from T.
//
// Example:
//
// struct MyObject {
// let x: Int
// }
//
// let map: DynamicLookupGeneratorSelection<MyObject> = ...
//
// try map.x.generate()
//
public class GeneratorByKeyPath<T> {
public typealias GeneratedType = T
private var generators: [PartialKeyPath<T>: Any] = [:]
private let anyGenerator: AnyGenerator
public init(anyGenerator: AnyGenerator) {
self.anyGenerator = anyGenerator
}
public subscript<V>(keyPath: KeyPath<T, V>) -> Generator<V> {
get {
if let untypedGenerator = generators[keyPath] {
if let typedGenerator = untypedGenerator as? Generator<V> {
return typedGenerator
} else {
assertionFailure(
"""
\(untypedGenerator) was stored for keyPath \(keyPath) of type \(V.self), \
expected: \(Generator<V>.self)
"""
)
// Fallback:
return Generator<V> { [anyGenerator] in
try anyGenerator.generate() as V
}
}
} else {
return Generator<V> { [anyGenerator] in
try anyGenerator.generate() as V
}
}
}
set {
generators[keyPath] = newValue
}
}
}
#endif
| 28.333333 | 98 | 0.479257 |
5d1862aa49f8bbfc337677b15841918d437b9286 | 11,830 | //
// COWProduct8.swift
//
import Foundation
import HDXLCommonUtilities
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - Definition
// -------------------------------------------------------------------------- //
/// Product-8 that stores all values "out-of-line" (e.g. on the heap), implemented
/// as a typical COW-style `struct` wrapper around a `class` that holds the data.
@frozen
public struct COWProduct8<A,B,C,D,E,F,G,H> {
@usableFromInline
internal typealias Storage = COWProduct8Storage<A,B,C,D,E,F,G,H>
@usableFromInline
internal var storage: Storage
/// "Designated initializer" for `COWProduct8` (pseudo-private).
@inlinable
internal init(storage: Storage) {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(storage.isValid)
defer { pedantic_assert(self.isValid) }
// /////////////////////////////////////////////////////////////////////////
self.storage = storage
}
/// "Designated initializer" for `COWProduct8` (pseudo-private).
@inlinable
internal init?(storage: Storage?) {
guard let storage = storage else {
return nil
}
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(storage.isValid)
// /////////////////////////////////////////////////////////////////////////
self.storage = storage
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(self.isValid)
// /////////////////////////////////////////////////////////////////////////
}
/// Construct a `COWProduct8` from the individual components.
@inlinable
public init(
_ a: A,
_ b: B,
_ c: C,
_ d: D,
_ e: E,
_ f: F,
_ g: G,
_ h: H) {
// /////////////////////////////////////////////////////////////////////////
defer { pedantic_assert(self.isValid) }
// /////////////////////////////////////////////////////////////////////////
self.init(
storage: Storage(
a,
b,
c,
d,
e,
f,
g,
h
)
)
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - Property Exposure
// -------------------------------------------------------------------------- //
public extension COWProduct8 {
@inlinable
var a: A {
get {
return self.storage.a
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.a = newValue
} else {
self.storage = self.storage.with(
a: newValue
)
}
}
}
@inlinable
var b: B {
get {
return self.storage.b
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.b = newValue
} else {
self.storage = self.storage.with(
b: newValue
)
}
}
}
@inlinable
var c: C {
get {
return self.storage.c
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.c = newValue
} else {
self.storage = self.storage.with(
c: newValue
)
}
}
}
@inlinable
var d: D {
get {
return self.storage.d
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.d = newValue
} else {
self.storage = self.storage.with(
d: newValue
)
}
}
}
@inlinable
var e: E {
get {
return self.storage.e
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.e = newValue
} else {
self.storage = self.storage.with(
e: newValue
)
}
}
}
@inlinable
var f: F {
get {
return self.storage.f
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.f = newValue
} else {
self.storage = self.storage.with(
f: newValue
)
}
}
}
@inlinable
var g: G {
get {
return self.storage.g
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.g = newValue
} else {
self.storage = self.storage.with(
g: newValue
)
}
}
}
@inlinable
var h: H {
get {
return self.storage.h
}
set {
// ///////////////////////////////////////////////////////////////////////
pedantic_assert(isValidOrIndifferent(newValue))
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// ///////////////////////////////////////////////////////////////////////
if isKnownUniquelyReferenced(&self.storage) {
self.storage.h = newValue
} else {
self.storage = self.storage.with(
h: newValue
)
}
}
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - Mutation
// -------------------------------------------------------------------------- //
public extension COWProduct8 {
/// In-place mutates `self`, *after first obtaining a unique copy*.
@inlinable
mutating func mutateInPlace(using mutation: (inout COWProduct8<A,B,C,D,E,F,G,H>) -> Void) {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(self.isValid)
defer { pedantic_assert(self.isValid) }
defer { pedantic_assert(isKnownUniquelyReferenced(&self.storage)) }
// /////////////////////////////////////////////////////////////////////////
if !isKnownUniquelyReferenced(&self.storage) {
self.storage = self.storage.obtainClone()
}
mutation(&self)
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - Reflection Support
// -------------------------------------------------------------------------- //
internal extension COWProduct8 {
@inlinable
static var shortTypeName: String {
get {
return "COWProduct8"
}
}
@inlinable
static var completeTypeName: String {
get {
return "\(self.shortTypeName)<\(self.typeParameterNames)>"
}
}
@inlinable
static var typeParameterNames: String {
get {
return [
String(reflecting: A.self),
String(reflecting: B.self),
String(reflecting: C.self),
String(reflecting: D.self),
String(reflecting: E.self),
String(reflecting: F.self),
String(reflecting: G.self),
String(reflecting: H.self)
].joined(separator: ", ")
}
}
@inlinable
var componentDescriptions: String {
get {
return [
String(describing: self.a),
String(describing: self.b),
String(describing: self.c),
String(describing: self.d),
String(describing: self.e),
String(describing: self.f),
String(describing: self.g),
String(describing: self.h)
].joined(separator: ", ")
}
}
@inlinable
var componentDebugDescriptions: String {
get {
return [
"a: \(String(reflecting: self.a))",
"b: \(String(reflecting: self.b))",
"c: \(String(reflecting: self.c))",
"d: \(String(reflecting: self.d))",
"e: \(String(reflecting: self.e))",
"f: \(String(reflecting: self.f))",
"g: \(String(reflecting: self.g))",
"h: \(String(reflecting: self.h))"
].joined(separator: ", ")
}
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - AlgebraicProduct8
// -------------------------------------------------------------------------- //
extension COWProduct8 : AlgebraicProduct8 {
public typealias ArityPosition = Arity8Position
@inlinable
public static var withDerivationShouldEnsureUniqueCopyByDefault: Bool {
get {
return false
}
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - Validatable
// -------------------------------------------------------------------------- //
extension COWProduct8 : Validatable {
@inlinable
public var isValid: Bool {
get {
return self.storage.isValid
}
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - CustomStringConvertible
// -------------------------------------------------------------------------- //
extension COWProduct8 : CustomStringConvertible {
@inlinable
public var description: String {
get {
return self.storage.description
}
}
}
// -------------------------------------------------------------------------- //
// MARK: COWProduct8 - CustomDebugStringConvertible
// -------------------------------------------------------------------------- //
extension COWProduct8 : CustomDebugStringConvertible {
@inlinable
public var debugDescription: String {
get {
return "\(type(of: self).completeTypeName)(\(self.componentDebugDescriptions))"
}
}
}
| 28.4375 | 93 | 0.436855 |
abbcb090b4794acda38c0782615c1425ea976023 | 569 | #!/usr/bin/env swift
// This task is specifically for Python, we should have to use the Pickle library
// #!/usr/bin/env python3
// import requests
// import pickle
// page_content = requests.get('http://www.pythonchallenge.com/pc/def/peak.html').text
// binary_file_name = page_content.split('<peakhell src="')[-1].split('"/>')[0]
// binary_dump = requests.get('http://www.pythonchallenge.com/pc/def/{}'.format(binary_file_name)).content
// pattern = pickle.loads(binary_dump)
// [ print(''.join(( symbol * count for symbol, count in line ))) for line in pattern ] | 40.642857 | 106 | 0.706503 |
894db9defa40666a522ef9c245488032312e598b | 536 | //
// Created by Yaroslav Zhurakovskiy
// Copyright © 2019-2020 Yaroslav Zhurakovskiy. All rights reserved.
//
import Foundation
extension NSNumber: TestCaseInputParamConvertible {
public var testCaseInputParamValue: String {
return "\(self)"
}
}
extension NSString: TestCaseInputParamConvertible {
public var testCaseInputParamValue: String {
return "\"\(self)\""
}
}
extension NSNull: TestCaseInputParamConvertible {
public var testCaseInputParamValue: String {
return "null"
}
}
| 21.44 | 69 | 0.70709 |
fb769a003ee2a0220f0aff7677caa83663c6ed7e | 2,105 | //
// SearchSimpleTableViewController.swift
// Graphics&Animation
//
// Created by CharlieW on 2018/4/27.
// Copyright © 2018年 CharlieW. All rights reserved.
//
import UIKit
class SearchTableViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var numberOfPawsLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var searchProgress: UIProgressView!
@IBOutlet weak var pawStepper: UIStepper!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var distanceSlider: UISlider!
@IBOutlet weak var speciesSelector: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(dismissVC))
}
@objc fileprivate func dismissVC() {
self.dismiss(animated: true, completion: nil)
}
fileprivate func hideKeyboard() {
nameTextField.resignFirstResponder()
}
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
hideKeyboard()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
hideKeyboard()
return true
}
@IBAction func updateDistance(_ sender: UISlider) {
distanceLabel.text = "\(Int(sender.value)) miles"
}
@IBAction func updateNumberOfPaws(_ sender: UIStepper) {
numberOfPawsLabel.text = "\(Int(sender.value)) paws"
}
@IBAction func search(_ sender: UIButton) {
UIView.animate(withDuration: 5.0, animations: {
self.searchProgress.setProgress(1.0, animated: true)
self.view.alpha = 0.7
}) { (finished) in
if finished {
self.dismissVC()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 25.670732 | 133 | 0.63753 |
e56bdf36d1711243b6552069b0de76ad4022d6be | 6,355 | //
// RegisterWifiModule2ViewController.swift
// SesameUI
//
// Created by Wayne Hsiao on 2020/8/10.
// Copyright © 2020 CandyHouse. All rights reserved.
//
import UIKit
import CoreLocation
class RegisterWifiModule2ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var dismissButton: UIButton! {
didSet {
dismissButton.setTitle("", for: .normal)
dismissButton.setImage( UIImage.SVGImage(named: "icons_filled_close"), for: .normal)
}
}
let locationManager = CLLocationManager()
var viewModel: RegisterWifiModule2ViewModel!
override func viewDidLoad() {
super.viewDidLoad()
assert(viewModel != nil, "RegisterDeviceListViewModel should not be nil.")
locationManager.requestWhenInUseAuthorization()
tableView.dataSource = self
tableView.delegate = self
viewModel.statusUpdated = { [weak self] status in
guard let strongSelf = self else {
return
}
executeOnMainThread {
switch status {
case .loading:
ViewHelper.showLoadingInView(view: strongSelf.view)
case .update(let action):
if let action = action as? RegisterWifiModule2ViewModel.Action,
action == RegisterWifiModule2ViewModel.Action.dfu {
// strongSelf.dfuSelectedDevice()
} else {
strongSelf.tableView.reloadData()
}
case .finished(let result):
ViewHelper.hideLoadingView(view: strongSelf.view)
switch result {
case .success(let type):
if let type = type as? RegisterWifiModule2ViewModel.Complete,
type == .wifiSetup {
strongSelf.view.makeToast("WiFi setup succeed!")
} else {
strongSelf.tableView.reloadData()
}
case .failure(let error):
strongSelf.view.makeToast(error.errorDescription())
}
}
}
}
tableView.tableFooterView = UIView(frame: .zero)
//backMenuBtn.setImage( UIImage.SVGImage(named: viewModel.backButtonImage), for: .normal)
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 120
tableView.rowHeight = 120
Topic
.updateTopic("$aws/things/testss2/shadow/name/topic_WM2_publish/update")
.subscribe { result in
switch result {
case .success(let content):
executeOnMainThread {
self.view.makeToast(content)
}
case .failure(let error):
executeOnMainThread {
self.view.makeToast(error.errorDescription())
}
}
}
}
@IBAction func dismissTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRows = viewModel.numberOfRowsInSection(section)
if numberOfRows == 0 {
tableView.setEmptyMessage(viewModel.emptyMessage)
} else {
tableView.restore()
}
return numberOfRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellViewModel = viewModel.cellViewModelForRowAtIndexPath(indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: "RegisterWifiModule2Cell", for: indexPath) as! RegisterWifiModule2Cell
cell.viewModel = cellViewModel
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let wifiSSID = UIDevice.current.WiFiSSID else {
if CLLocationManager.authorizationStatus() == .denied ||
!CLLocationManager.locationServicesEnabled() ||
CLLocationManager.authorizationStatus() == .notDetermined {
let alertController = UIAlertController(title: "Permisson Not determind", message: "Go to app setting and grant the location access permission", preferredStyle: .alert)
let action = UIAlertAction(title: "Go", style: .default) { _ in
let url = URL(string: UIApplication.openSettingsURLString)
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
alertController.addAction(action)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancel)
}
L.d("Could not get WiFiSSID: authorizationStatus \(CLLocationManager.authorizationStatus())")
return
}
let alertController = UIAlertController(title: wifiSSID,
message: "Please enter the wifi password",
preferredStyle: .alert)
alertController.addTextField { textField in
textField.placeholder = "WiFi password"
textField.isSecureTextEntry = true
}
let action = UIAlertAction(title: "OK", style: .default) { [weak alertController, weak self] _ in
if let textField = alertController?.textFields?[0] {
self?.viewModel.didSelectCellAtRow(indexPath.row,
ssid: wifiSSID,
password: textField.text!)
}
}
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
}
| 41 | 184 | 0.566955 |
4a35aa133f9fbb4c131eb02602cfbfc8f7a01e8c | 7,057 | //
// CLDCloudinary.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.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 Foundation
import UIKit
public typealias CLDCompletionHandler = (_ responseImage: UIImage?, _ error: NSError?) -> ()
public typealias CLDUploadCompletionHandler = (_ response: CLDUploadResult?, _ error: NSError?) -> ()
@objcMembers open class CLDCloudinary: NSObject {
/**
Holds the configuration parameters to be used by the `CLDCloudinary` instance.
*/
open fileprivate(set) var config: CLDConfiguration
/**
The network coordinator coordinates between the SDK's API level classes to its network adapter layer.
*/
fileprivate var networkCoordinator: CLDNetworkCoordinator
// MARK: - SDK Configurations
// MARK: Log Level
/**
Sets Cloudinary SDK's log level, default level is set to **None**.
*/
public static var logLevel: CLDLogLevel {
get {
return CLDLogManager.minimumLogLevel
}
set {
CLDLogManager.minimumLogLevel = newValue
}
}
// MARK: Image Cache
/**
Sets Cloudinary SDK's caching policy for images that are downloaded via the SDK's CLDDownloader.
The options are: **None**, **Memory** and **Disk**. default is Disk
*/
open var cachePolicy: CLDImageCachePolicy {
get {
return CLDImageCache.defaultImageCache.cachePolicy
}
set {
CLDImageCache.defaultImageCache.cachePolicy = newValue
}
}
/**
Sets Cloudinary SDK's image cache maximum disk capacity.
default is 150 MB.
*/
open var cacheMaxDiskCapacity: UInt64 {
get {
return CLDImageCache.defaultImageCache.maxDiskCapacity
}
set {
CLDImageCache.defaultImageCache.maxDiskCapacity = newValue
}
}
/**
Sets Cloudinary SDK's image cache maximum memory total cost.
default is 30 MB.
*/
open var cacheMaxMemoryTotalCost: Int {
get {
return CLDImageCache.defaultImageCache.maxMemoryTotalCost
}
set {
CLDImageCache.defaultImageCache.maxMemoryTotalCost = newValue
}
}
/**
Removes an image from the downloaded images cache, both disk and memory.
- parameter key: The full url of the image to remove.
*/
open func removeFromCache(key: String) {
CLDImageCache.defaultImageCache.removeCacheImageForKey(key)
}
// MARK: - Init
/**
Initializes the `CLDCloudinary` instance with the specified configuration and network adapter.
- parameter configuration: The configuration used by this CLDCloudinary instance.
- parameter networkAdapter: A network adapter that implements `CLDNetworkAdapter`. CLDNetworkDelegate() by default.
- returns: The new `CLDCloudinary` instance.
*/
public init(configuration: CLDConfiguration, networkAdapter: CLDNetworkAdapter? = nil, sessionConfiguration: URLSessionConfiguration? = nil) {
config = configuration
if let customNetworkAdapter = networkAdapter {
networkCoordinator = CLDNetworkCoordinator(configuration: config, networkAdapter: customNetworkAdapter)
} else {
if let sessionConfiguration = sessionConfiguration {
networkCoordinator = CLDNetworkCoordinator(configuration: config, sessionConfiguration: sessionConfiguration)
} else {
networkCoordinator = CLDNetworkCoordinator(configuration: config)
}
}
super.init()
}
// MARK: Factory Methods
/**
A factory method to create a new `CLDUrl` instance
- returns: A new `CLDUrl` instance.
*/
open func createUrl() -> CLDUrl {
return CLDUrl(configuration: config)
}
/**
A factory method to create a new `CLDUploader` instance
- returns: A new `CLDUploader` instance.
*/
open func createUploader() -> CLDUploader {
return CLDUploader(networkCoordinator: networkCoordinator)
}
/**
A factory method to create a new `CLDDownloader` instance
- returns: A new `CLDDownloader` instance.
*/
open func createDownloader() -> CLDDownloader {
return CLDDownloader(networkCoordinator: networkCoordinator)
}
/**
A factory method to create a new `CLDAdminApi` instance
- returns: A new `CLDAdminApi` instance.
*/
open func createManagementApi() -> CLDManagementApi {
return CLDManagementApi(networkCoordinator: networkCoordinator)
}
// MARK: - Network Adapter
/**
The maximum number of queued downloads that can execute at the same time.
default is NSOperationQueueDefaultMaxConcurrentOperationCount.
- parameter maxConcurrentDownloads: The maximum concurrent downloads to allow.
*/
@available(iOS 8.0, *)
open func setMaxConcurrentDownloads(_ maxConcurrentDownloads: Int) {
networkCoordinator.setMaxConcurrentDownloads(maxConcurrentDownloads)
}
// MARK: Background Session
/**
Set a completion handler provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method.
The handler will be called automatically once the session finishes its events for background URL session.
default is `nil`.
*/
@available(iOS 8.0, *)
open func setBackgroundCompletionHandler(_ newValue: (() -> ())?) {
networkCoordinator.setBackgroundCompletionHandler(newValue)
}
// MARK: - Advanced
/**
Sets the "USER-AGENT" HTTP header on all network requests to be **"PlatformName/ver CloudinaryiOS/ver"**
By default the header is set to **"CloudinaryiOS/ver"**
*/
open func setUserPlatform(_ platformName: String, version: String) {
config.setUserPlatform(platformName, version: version)
}
}
| 33.604762 | 147 | 0.676917 |
7578fb0a4fca7ffd64ea231124ecd551ebe53bc2 | 2,945 | //
// CompleteCommand.swift
// SourceKitten
//
// Created by JP Simard on 9/4/15.
// Copyright © 2015 SourceKitten. All rights reserved.
//
import Commandant
import Foundation
import Result
import SourceKittenFramework
struct CompleteCommand: CommandProtocol {
let verb = "complete"
let function = "Generate code completion options"
struct Options: OptionsProtocol {
let file: String
let text: String
let offset: Int
let spmModule: String
let compilerargs: [String]
static func create(file: String) -> (_ text: String) -> (_ offset: Int) -> (_ spmModule: String) -> (_ compilerargs: [String]) -> Options {
return { text in { offset in { spmModule in { compilerargs in
self.init(file: file, text: text, offset: offset, spmModule: spmModule, compilerargs: compilerargs)
}}}}
}
static func evaluate(_ mode: CommandMode) -> Result<Options, CommandantError<SourceKittenError>> {
return create
<*> mode <| Option(key: "file", defaultValue: "", usage: "relative or absolute path of Swift file to parse")
<*> mode <| Option(key: "text", defaultValue: "", usage: "Swift code text to parse")
<*> mode <| Option(key: "offset", defaultValue: 0, usage: "Offset for which to generate code completion options.")
<*> mode <| Option(key: "spm-module", defaultValue: "", usage: "Read compiler flags from a Swift Package Manager module")
<*> mode <| Argument(defaultValue: [String](), usage: "Compiler arguments to pass to SourceKit. This must be specified following the '--'")
}
}
func run(_ options: Options) -> Result<(), SourceKittenError> {
let path: String
let contents: String
if !options.file.isEmpty {
path = options.file.bridge().absolutePathRepresentation()
guard let file = File(path: path) else {
return .failure(.readFailed(path: options.file))
}
contents = file.contents
} else {
path = "\(NSUUID().uuidString).swift"
contents = options.text
}
var args: [String]
if options.spmModule.isEmpty {
args = ["-c", path] + options.compilerargs
if args.index(of: "-sdk") == nil {
args.append(contentsOf: ["-sdk", sdkPath()])
}
} else {
guard let module = Module(spmName: options.spmModule) else {
return .failure(.invalidArgument(description: "Bad module name"))
}
args = module.compilerArguments
}
let request = Request.codeCompletionRequest(file: path, contents: contents,
offset: Int64(options.offset),
arguments: args)
print(CodeCompletionItem.parse(response: request.send()))
return .success(())
}
}
| 39.266667 | 155 | 0.591851 |
2339f4ef4bce9e850234951599c6136c94f887dd | 125 | import XCTest
import ShoppingListTests
var tests = [XCTestCaseEntry]()
tests += ShoppingListTests.allTests()
XCTMain(tests) | 17.857143 | 37 | 0.8 |
f5d4689d8608b44a096b798e9487a7e788e2e38b | 8,650 | //
// NetworkClient.swift
// Flamingo 1.0
//
// Created by Ilya Kulebyakin on 9/11/17.
// Copyright © 2017 e-Legion. All rights reserved.
//
import Foundation
public typealias CompletionHandler<T> = (Result<T, Error>, NetworkContext?) -> Void
public protocol NetworkClient: class {
@discardableResult
func sendRequest<Request: NetworkRequest>(_ networkRequest: Request, completionHandler: ((Result<Request.Response, Error>, NetworkContext?) -> Void)?) -> Cancellable
func addReporter(_ reporter: NetworkClientReporter, storagePolicy: StoragePolicy)
func removeReporter(_ reporter: NetworkClientReporter)
}
public protocol NetworkClientMutable: NetworkClient {
func addMutater(_ mutater: NetworkClientMutater, storagePolicy: StoragePolicy)
func removeMutater(_ mutater: NetworkClientMutater)
}
open class NetworkDefaultClient: NetworkClientMutable {
private static let operationQueue = DispatchQueue(label: "com.flamingo.operation-queue", attributes: DispatchQueue.Attributes.concurrent)
private let configuration: NetworkConfiguration
open var session: URLSession
private var reporters = ObserversArray<NetworkClientReporter>()
private var mutaters = ObserversArray<NetworkClientMutater>()
public init(configuration: NetworkConfiguration,
session: URLSession) {
self.configuration = configuration
self.session = session
}
private func completionQueue<Request: NetworkRequest>(for request: Request) -> DispatchQueue {
return request.completionQueue ?? configuration.completionQueue
}
private func complete<Request: NetworkRequest>(request: Request, with completion: @escaping () -> Void) {
if configuration.parallel {
completionQueue(for: request).async {
completion()
}
} else {
completion()
}
}
@discardableResult
open func sendRequest<Request>(_ networkRequest: Request, completionHandler: CompletionHandler<Request.Response>?) -> Cancellable where Request: NetworkRequest {
let urlRequest: URLRequest
do {
urlRequest = try self.urlRequest(from: networkRequest)
} catch {
complete(request: networkRequest, with: {
completionHandler?(.failure(error), nil)
})
return EmptyCancellable()
}
reporters.iterate {
(reporter, _) in
reporter.willSendRequest(networkRequest)
}
let handler = self.requestHandler(with: networkRequest, urlRequest: urlRequest, completion: completionHandler)
var foundResponse = false
mutaters.iterate {
(mutater, _) in
if !foundResponse,
let responseTuple = mutater.response(for: networkRequest) {
handler(responseTuple.data, responseTuple.response, responseTuple.error)
foundResponse = true
}
}
if !foundResponse {
let task = session.dataTask(with: urlRequest, completionHandler: handler)
task.resume()
return task
}
return EmptyCancellable()
}
public func addReporter(_ reporter: NetworkClientReporter, storagePolicy: StoragePolicy = .weak) {
reporters.addObserver(observer: reporter, storagePolicy: storagePolicy)
}
public func removeReporter(_ reporter: NetworkClientReporter) {
reporters.removeObserver(observer: reporter)
}
/// Add another mutater
///
/// Priority will be the same as you add them
/// - Parameter mutater: NetworkClientMutater conformance
public func addMutater(_ mutater: NetworkClientMutater, storagePolicy: StoragePolicy = .weak) {
mutaters.addObserver(observer: mutater, storagePolicy: storagePolicy)
}
public func removeMutater(_ mutater: NetworkClientMutater) {
mutaters.removeObserver(observer: mutater)
}
private func requestHandler<Request: NetworkRequest>(with networkRequest: Request,
urlRequest: URLRequest,
completion: ((Result<Request.Response, Error>, NetworkContext) -> Void)?) -> (Data?, URLResponse?, Swift.Error?) -> Void {
return {
[weak self] data, response, error in
let failureClosure = {
(finalError: Swift.Error?, httpResponse: HTTPURLResponse?) in
self?.complete(request: networkRequest, with: {
let context = NetworkContext(request: urlRequest, response: httpResponse, data: data, error: finalError as NSError?)
self?.reporters.iterate {
(reporter, _) in
reporter.didRecieveResponse(for: networkRequest, context: context)
}
completion?(.failure(finalError ?? FlamingoError.invalidRequest), context)
})
}
let jobClosure = {
var finalError: Swift.Error? = error
let httpResponse = response as? HTTPURLResponse
if error != nil {
failureClosure(finalError, httpResponse)
return
}
if httpResponse == nil {
finalError = error ?? FlamingoError.unableToRetrieveHTTPResponse
failureClosure(finalError, httpResponse)
return
}
let validator = Validator(request: urlRequest, response: httpResponse, data: data)
validator.validate()
if let validationError = validator.validationErrors.first {
finalError = validationError
failureClosure(finalError, httpResponse)
return
}
let context = NetworkContext(request: urlRequest, response: httpResponse, data: data, error: finalError as NSError?)
let result = networkRequest.responseSerializer.serialize(request: urlRequest, response: httpResponse, data: data, error: error)
switch result {
case .success(let value):
self?.complete(request: networkRequest, with: {
self?.reporters.iterate {
(reporter, _) in
reporter.didRecieveResponse(for: networkRequest, context: context)
}
completion?(.success(value), context)
})
case .failure(let error):
finalError = error
failureClosure(finalError, httpResponse)
}
}
if let configuration = self?.configuration,
configuration.parallel {
NetworkDefaultClient.operationQueue.async(execute: jobClosure)
} else {
jobClosure()
}
}
}
open func urlRequest<T: NetworkRequest>(from networkRequest: T) throws -> URLRequest {
let _baseURL = networkRequest.baseURL ?? configuration.baseURL
let urlString = try networkRequest.URL.asURL().absoluteString
guard let baseURL = try _baseURL?.asURL(),
let url = URL(string: urlString, relativeTo: baseURL) else {
throw FlamingoError.invalidRequest
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = networkRequest.method.rawValue
for (name, value) in (networkRequest.headers ?? [:]) {
urlRequest.setValue(value, forHTTPHeaderField: name)
}
for (name, value) in (customHeadersForRequest(networkRequest) ?? [:]) {
urlRequest.setValue(value, forHTTPHeaderField: name)
}
urlRequest.timeoutInterval = configuration.defaultTimeoutInterval
if let cachePolicy = networkRequest.cachePolicy {
urlRequest.cachePolicy = cachePolicy
}
if let parametersTuple = networkRequest.parametersTuple {
try parametersTuple.1.encode(parameters: parametersTuple.0, to: &urlRequest)
} else {
try networkRequest.parametersEncoder.encode(parameters: networkRequest.parameters, to: &urlRequest)
}
return urlRequest
}
open func customHeadersForRequest<T: NetworkRequest>(_ networkRequest: T) -> [String: String]? {
return nil
}
}
| 38.616071 | 179 | 0.606705 |
0ea161e33e00f80aac7f1ec43fcb7a0518875983 | 1,021 | //
// CirclePaintableView.swift
// react-native-painter
//
// Created by Juan J LF on 8/30/21.
//
import Foundation
import UIKit
@objc(CirclePaintableView)
class CirclePaintableView: PaintableView {
private var mLayer = CircleLayer()
override init() {
super.init()
layer.addSublayer(mLayer)
}
@objc func setCx(_ v:NSNumber?){
let ev = CGFloat(truncating: v ?? 0)
mLayer.setCx(ev)
}
@objc func setCy(_ v:NSNumber?){
let ev = CGFloat(truncating: v ?? 0)
mLayer.setCy(ev)
}
@objc func setR(_ v:NSNumber?){
let ev = CGFloat(truncating: v ?? 0)
mLayer.setR(ev)
}
override func getLayer() -> Paintable? {
return mLayer
}
override func getCALayer() -> CALayer? {
return mLayer
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 17.912281 | 60 | 0.53477 |
1c722224ebc4e6ab687e4f8ba951c1f1a6c432d0 | 1,232 | //
// ExpenseListViewController.swift
// ExpenseTracker
//
// Created by MAC105 on 11/09/21.
//
import UIKit
class ExpenseListViewController: UIViewController {
@IBOutlet weak var tableViewExpenseList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func didTapOnAddExpense(_ sender: Any) {
if let expenseTrackerVC = self.storyboard?.instantiateViewController(identifier: "ExpenseTrackerViewController") as? ExpenseTrackerViewController {
self.navigationController?.pushViewController(expenseTrackerVC, animated: true)
}
}
}
extension ExpenseListViewController: UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell", for: indexPath) as! ExpenseTableViewCell
return cell
}
}
class ExpenseTableViewCell : UITableViewCell {
@IBOutlet weak var labelDetail: UILabel!
}
| 31.589744 | 155 | 0.730519 |
2f914522b53b16ec05b4bf468b0fdeb71600cfe5 | 516 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "BBMetalImage",
platforms: [.iOS("14"), .macOS("11")],
products: [
.library(name: "BBMetalImage", targets: ["BBMetalImage"]),
],
targets: [
.target(
name: "BBMetalImage",
path: "BBMetalImage/BBMetalImage",
exclude: ["MultipleVideoSource.swift"]
)
]
)
| 25.8 | 96 | 0.606589 |
1e5c37f088b311edfb822241762c489868938b7e | 15,761 | //
// PryntTrimmerView.swift
// PryntTrimmerView
//
// Created by HHK on 27/03/2017.
// Copyright © 2017 Prynt. All rights reserved.
//
import AVFoundation
import UIKit
public enum Handler{
case left
case right
}
public protocol TrimmerViewDelegate: class {
func beganChangePositionBar(fromHandler handler: Handler)
func didChangePositionBar(_ playerTime: CMTime, fromHandler handler: Handler)
func positionBarStoppedMoving(_ playerTime: CMTime, fromHandler handler: Handler)
}
/// A view to select a specific time range of a video. It consists of an asset preview with thumbnails inside a scroll view, two
/// handles on the side to select the beginning and the end of the range, and a position bar to synchronize the control with a
/// video preview, typically with an `AVPlayer`.
/// Load the video by setting the `asset` property. Access the `startTime` and `endTime` of the view to get the selected time
// range
@IBDesignable public class TrimmerView: AVAssetTimeSelector {
// MARK: - Properties
// MARK: Color Customization
/// The color of the main border of the view
@IBInspectable public var mainColor: UIColor = UIColor.orange {
didSet {
updateMainColor()
}
}
/// The color of the handles on the side of the view
@IBInspectable public var handleColor: UIColor = UIColor.gray {
didSet {
updateHandleColor()
}
}
/// The color of the position indicator
@IBInspectable public var positionBarColor: UIColor = UIColor.white {
didSet {
positionBar.backgroundColor = positionBarColor
}
}
@IBInspectable public var unselectedColor: UIColor = UIColor.white{
didSet{
[leftMaskView, rightMaskView].forEach{$0.backgroundColor = unselectedColor}
}
}
/// The color used to mask unselected parts of the video
@IBInspectable public var maskColor: UIColor = UIColor.white {
didSet {
leftMaskView.backgroundColor = maskColor
rightMaskView.backgroundColor = maskColor
}
}
// MARK: Interface
public weak var delegate: TrimmerViewDelegate?
// MARK: Subviews
private let trimView = UIView()
private let leftHandleView = HandlerView()
private let rightHandleView = HandlerView()
private let positionBar = UIView()
private let leftHandleKnob = UIView()
private let rightHandleKnob = UIView()
private let leftMaskView = UIView()
private let rightMaskView = UIView()
// MARK: Constraints
private var currentLeftConstraint: CGFloat = 0
private var currentRightConstraint: CGFloat = 0
private var leftConstraint: NSLayoutConstraint?
private var rightConstraint: NSLayoutConstraint?
private var positionConstraint: NSLayoutConstraint?
private let handleWidth: CGFloat = 15
/// The minimum duration allowed for the trimming. The handles won't pan further if the minimum duration is attained.
public var minDuration: Double = 1
// MARK: - View & constraints configurations
override func setupSubviews() {
super.setupSubviews()
layer.cornerRadius = 2
layer.masksToBounds = true
backgroundColor = UIColor.clear
layer.zPosition = 1
setupTrimmerView()
setupHandleView()
setupMaskView()
setupPositionBar()
setupGestures()
updateMainColor()
updateHandleColor()
}
override func constrainAssetPreview() {
assetPreview.leftAnchor.constraint(equalTo: leftAnchor, constant: handleWidth).isActive = true
assetPreview.rightAnchor.constraint(equalTo: rightAnchor, constant: -handleWidth).isActive = true
assetPreview.topAnchor.constraint(equalTo: topAnchor).isActive = true
assetPreview.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
private func setupTrimmerView() {
trimView.layer.borderWidth = 2.0
trimView.layer.cornerRadius = 2.0
trimView.translatesAutoresizingMaskIntoConstraints = false
trimView.isUserInteractionEnabled = false
addSubview(trimView)
trimView.topAnchor.constraint(equalTo: topAnchor).isActive = true
trimView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
leftConstraint = trimView.leftAnchor.constraint(equalTo: leftAnchor)
rightConstraint = trimView.rightAnchor.constraint(equalTo: rightAnchor)
leftConstraint?.isActive = true
rightConstraint?.isActive = true
}
private func setupHandleView() {
leftHandleView.isUserInteractionEnabled = true
leftHandleView.layer.cornerRadius = 2.0
leftHandleView.translatesAutoresizingMaskIntoConstraints = false
addSubview(leftHandleView)
leftHandleView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
leftHandleView.widthAnchor.constraint(equalToConstant: handleWidth).isActive = true
leftHandleView.leftAnchor.constraint(equalTo: trimView.leftAnchor).isActive = true
leftHandleView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
leftHandleKnob.translatesAutoresizingMaskIntoConstraints = false
leftHandleView.addSubview(leftHandleKnob)
leftHandleKnob.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5).isActive = true
leftHandleKnob.widthAnchor.constraint(equalToConstant: 2).isActive = true
leftHandleKnob.centerYAnchor.constraint(equalTo: leftHandleView.centerYAnchor).isActive = true
leftHandleKnob.centerXAnchor.constraint(equalTo: leftHandleView.centerXAnchor).isActive = true
rightHandleView.isUserInteractionEnabled = true
rightHandleView.layer.cornerRadius = 2.0
rightHandleView.translatesAutoresizingMaskIntoConstraints = false
addSubview(rightHandleView)
rightHandleView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
rightHandleView.widthAnchor.constraint(equalToConstant: handleWidth).isActive = true
rightHandleView.rightAnchor.constraint(equalTo: trimView.rightAnchor).isActive = true
rightHandleView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
rightHandleKnob.translatesAutoresizingMaskIntoConstraints = false
rightHandleView.addSubview(rightHandleKnob)
rightHandleKnob.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5).isActive = true
rightHandleKnob.widthAnchor.constraint(equalToConstant: 2).isActive = true
rightHandleKnob.centerYAnchor.constraint(equalTo: rightHandleView.centerYAnchor).isActive = true
rightHandleKnob.centerXAnchor.constraint(equalTo: rightHandleView.centerXAnchor).isActive = true
}
private func setupMaskView() {
leftMaskView.isUserInteractionEnabled = false
leftMaskView.backgroundColor = unselectedColor
leftMaskView.alpha = 0.7
leftMaskView.translatesAutoresizingMaskIntoConstraints = false
insertSubview(leftMaskView, belowSubview: leftHandleView)
leftMaskView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
leftMaskView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
leftMaskView.topAnchor.constraint(equalTo: topAnchor).isActive = true
leftMaskView.rightAnchor.constraint(equalTo: leftHandleView.centerXAnchor).isActive = true
rightMaskView.isUserInteractionEnabled = false
rightMaskView.backgroundColor = unselectedColor
rightMaskView.alpha = 0.7
rightMaskView.translatesAutoresizingMaskIntoConstraints = false
insertSubview(rightMaskView, belowSubview: rightHandleView)
rightMaskView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
rightMaskView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
rightMaskView.topAnchor.constraint(equalTo: topAnchor).isActive = true
rightMaskView.leftAnchor.constraint(equalTo: rightHandleView.centerXAnchor).isActive = true
}
private func setupPositionBar() {
positionBar.frame = CGRect(x: 0, y: 0, width: 3, height: frame.height)
positionBar.backgroundColor = positionBarColor
positionBar.center = CGPoint(x: leftHandleView.frame.maxX, y: center.y)
positionBar.layer.cornerRadius = 1
positionBar.translatesAutoresizingMaskIntoConstraints = false
positionBar.isUserInteractionEnabled = false
addSubview(positionBar)
positionBar.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
positionBar.widthAnchor.constraint(equalToConstant: 3).isActive = true
positionBar.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
positionConstraint = positionBar.leftAnchor.constraint(equalTo: leftHandleView.rightAnchor, constant: 0)
positionConstraint?.isActive = true
}
private func setupGestures() {
let leftPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TrimmerView.handlePanGesture))
leftHandleView.addGestureRecognizer(leftPanGestureRecognizer)
let rightPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TrimmerView.handlePanGesture))
rightHandleView.addGestureRecognizer(rightPanGestureRecognizer)
}
private func updateMainColor() {
trimView.layer.borderColor = mainColor.cgColor
leftHandleView.backgroundColor = mainColor
rightHandleView.backgroundColor = mainColor
}
private func updateHandleColor() {
leftHandleKnob.backgroundColor = handleColor
rightHandleKnob.backgroundColor = handleColor
}
// MARK: - Trim Gestures
@objc func handlePanGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
guard let view = gestureRecognizer.view, let superView = gestureRecognizer.view?.superview else { return }
let isLeftGesture = view == leftHandleView
let handler: Handler = isLeftGesture ? .left : .right
switch gestureRecognizer.state {
case .began:
if isLeftGesture {
currentLeftConstraint = leftConstraint!.constant
} else {
currentRightConstraint = rightConstraint!.constant
}
updateSelectedTime(state: .began, fromHandler: handler)
case .changed:
let translation = gestureRecognizer.translation(in: superView)
if isLeftGesture {
updateLeftConstraint(with: translation)
} else {
updateRightConstraint(with: translation)
}
layoutIfNeeded()
if let startTime = startTime, isLeftGesture {
seek(to: startTime)
} else if let endTime = endTime {
seek(to: endTime)
}
updateSelectedTime(state: .changed, fromHandler: handler)
case .cancelled, .ended, .failed:
updateSelectedTime(state: .ended, fromHandler: handler)
default: break
}
}
private func updateLeftConstraint(with translation: CGPoint) {
let maxConstraint = max(rightHandleView.frame.origin.x - handleWidth - minimumDistanceBetweenHandle, 0)
let newConstraint = min(max(0, currentLeftConstraint + translation.x), maxConstraint)
leftConstraint?.constant = newConstraint
}
private func updateRightConstraint(with translation: CGPoint) {
let maxConstraint = min(2 * handleWidth - frame.width + leftHandleView.frame.origin.x + minimumDistanceBetweenHandle, 0)
let newConstraint = max(min(0, currentRightConstraint + translation.x), maxConstraint)
rightConstraint?.constant = newConstraint
}
// MARK: - Asset loading
override func assetDidChange(newAsset: AVAsset?) {
super.assetDidChange(newAsset: newAsset)
resetHandleViewPosition()
}
private func resetHandleViewPosition() {
leftConstraint?.constant = 0
rightConstraint?.constant = 0
layoutIfNeeded()
}
// MARK: - Time Equivalence
/// Move the position bar to the given time.
public func seek(to time: CMTime) {
if let newPosition = getPosition(from: time) {
let offsetPosition = newPosition - assetPreview.contentOffset.x - leftHandleView.frame.origin.x
let maxPosition = rightHandleView.frame.origin.x - (leftHandleView.frame.origin.x + handleWidth)
- positionBar.frame.width
let normalizedPosition = min(max(0, offsetPosition), maxPosition)
positionConstraint?.constant = normalizedPosition
layoutIfNeeded()
}
}
/// The selected start time for the current asset.
public var startTime: CMTime? {
let startPosition = leftHandleView.frame.origin.x + assetPreview.contentOffset.x
return getTime(from: startPosition)
}
/// The selected end time for the current asset.
public var endTime: CMTime? {
let endPosition = rightHandleView.frame.origin.x + assetPreview.contentOffset.x - handleWidth
return getTime(from: endPosition)
}
/// Manual set the timerange for the start & end handles
public func setTimeRange(_ timeRange: CMTimeRange){
if let leftPosition = getPosition(from: timeRange.start){
let newStartOrigin = leftPosition - assetPreview.contentOffset.x
currentLeftConstraint = leftConstraint?.constant ?? 0
updateLeftConstraint(with: CGPoint(x: newStartOrigin-leftHandleView.frame.origin.x, y: 0))
}
if let rightPosition = getPosition(from: timeRange.end){
let newRightOrigin = rightPosition - assetPreview.contentOffset.x + handleWidth
currentRightConstraint = rightConstraint?.constant ?? 0
updateRightConstraint(with: CGPoint(x: newRightOrigin-rightHandleView.frame.origin.x, y: 0))
}
layoutIfNeeded()
if let startTime = startTime{
seek(to: startTime)
}
updateSelectedTime(state: .ended)
}
private func updateSelectedTime(state: UIGestureRecognizer.State, fromHandler handler: Handler = .left) {
guard let playerTime = positionBarTime else {
return
}
switch state{
case .began:
delegate?.beganChangePositionBar(fromHandler: handler)
case .changed:
delegate?.didChangePositionBar(playerTime, fromHandler: handler)
case .ended, .failed:
delegate?.positionBarStoppedMoving(playerTime, fromHandler: handler)
default: break
}
}
private var positionBarTime: CMTime? {
let barPosition = positionBar.frame.origin.x + assetPreview.contentOffset.x - handleWidth
return getTime(from: barPosition)
}
private var minimumDistanceBetweenHandle: CGFloat {
guard let asset = asset else { return 0 }
return CGFloat(minDuration) * assetPreview.contentView.frame.width / CGFloat(asset.duration.seconds)
}
// MARK: - Scroll View Delegate
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
updateSelectedTime(state: .began)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
updateSelectedTime(state: .ended)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
updateSelectedTime(state: .ended)
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateSelectedTime(state: .changed)
}
}
| 40.726098 | 128 | 0.701288 |
fe9623d37be7450aa8db05540e1df0612f10d6a2 | 416 | // swift-tools-version:5.4
import PackageDescription
let package = Package(
name: "RangeSeekSlider",
platforms: [
.iOS(.v11),
.macOS(.v11),
.tvOS(.v11)
],
products: [
.library(name: "RangeSeekSlider", targets: ["RangeSeekSlider"])
],
targets: [
.target(name: "RangeSeekSlider", path: "Sources")
],
swiftLanguageVersions: [
.v5
]
)
| 19.809524 | 71 | 0.555288 |
237b4824a6a1afe905fb1485580f8566012b5ec9 | 284 | //
// MGELogger
//
import Foundation
// MARK: - M
public extension Logger {
/// Syntactic sugar for a logger message.
typealias Message = String
}
// MARK: - S
public extension Logger.Log {
/// Syntactic sugar for severity of the log levels.
typealias Severity = Int
}
| 14.2 | 53 | 0.676056 |
1c1279951237182a1cef34cbbe88c7c324a52d90 | 139 | // Copyright © Fleuronic LLC. All rights reserved.
struct Empty {}
// MARK: -
extension Empty: Equatable {}
extension Empty: Codable {}
| 15.444444 | 50 | 0.697842 |
ff1b66d69c7c441688d4f3c44f345f2907dc09a7 | 1,837 | // Please help improve quicktype by enabling anonymous telemetry with:
//
// $ quicktype --telemetry enable
//
// You can also enable telemetry on any quicktype invocation:
//
// $ quicktype pokedex.json -o Pokedex.cs --telemetry enable
//
// This helps us improve quicktype by measuring:
//
// * How many people use quicktype
// * Which features are popular or unpopular
// * Performance
// * Errors
//
// quicktype does not collect:
//
// * Your filenames or input data
// * Any personally identifiable information (PII)
// * Anything not directly related to quicktype's usage
//
// If you don't want to help improve quicktype, you can dismiss this message with:
//
// $ quicktype --telemetry disable
//
// For a full privacy policy, visit app.quicktype.io/privacy
//
import Foundation
/// Client cancels spend order
struct SpendOrderCancelled: KBIEvent {
let client: Client
let common: Common
let eventName: String
let eventType: String
let offerID, orderID: String
let user: User
enum CodingKeys: String, CodingKey {
case client, common
case eventName = "event_name"
case eventType = "event_type"
case offerID = "offer_id"
case orderID = "order_id"
case user
}
}
extension SpendOrderCancelled {
init(offerID: String, orderID: String) throws {
let es = EventsStore.shared
guard let user = es.userProxy?.snapshot,
let common = es.commonProxy?.snapshot,
let client = es.clientProxy?.snapshot else {
throw BIError.proxyNotSet
}
self.user = user
self.common = common
self.client = client
eventName = "spend_order_cancelled"
eventType = "log"
self.offerID = offerID
self.orderID = orderID
}
}
| 25.873239 | 82 | 0.647251 |
38cc97e18010eb3d544e212f9a142657da943862 | 873 | import Foundation
public enum ProcessRunnerError: Error, CustomStringConvertible, Equatable {
/// Thrown when the shell task failed.
case shell(reason: Process.TerminationReason, code: Int32)
/// Thrown when the given executable name can't be found in the environment PATH.
case missingExecutable(String)
/// Error description.
public var description: String {
switch self {
case let .missingExecutable(name):
return "The executable with name '\(name)' was not found"
case let .shell(reason, code):
switch reason {
case .exit:
return "The process errored with code \(code)"
case .uncaughtSignal:
return "The process was interrupted with code \(code)"
@unknown default:
fatalError()
}
}
}
}
| 32.333333 | 85 | 0.607102 |
0a5aea8ec7d32f3434f142b1c65b8a9b0dea1fe1 | 2,036 | //
// Copyright © 2020 Rosberry. All rights reserved.
//
import Foundation
import Networking
final class SessionTaskServiceMock: SessionTaskService {
private(set) var passedRequest: URLRequest?
var dataTask: URLSessionDataTask?
var uploadTask: URLSessionUploadTask?
var downloadTask: URLSessionDownloadTask?
var responseData: Data?
var responseURL: URL?
var error: Error?
private(set) var uploadData: Data?
private(set) var uploadFileURL: URL?
override func dataTask(with request: URLRequest, completion: @escaping ResultCompletion<Data>) -> URLSessionDataTask {
passedRequest = request
call(completion)
return dataTask!
}
override func uploadTask(with request: URLRequest, data: Data?, completion: @escaping ResultCompletion<Data>) -> URLSessionUploadTask {
passedRequest = request
uploadData = data
call(completion)
return uploadTask!
}
override func uploadTask(with request: URLRequest, fileURL: URL, completion: @escaping ResultCompletion<Data>) -> URLSessionUploadTask {
passedRequest = request
uploadFileURL = fileURL
call(completion)
return uploadTask!
}
override func downloadTask(with request: URLRequest, completion: @escaping ResultCompletion<URL>) -> URLSessionDownloadTask {
passedRequest = request
if let responseURL = responseURL {
completion(.success(responseURL))
}
if let error = error {
completion(.failure(error))
}
return downloadTask!
}
func clean() {
passedRequest = nil
responseData = nil
error = nil
dataTask = nil
uploadTask = nil
downloadTask = nil
}
// MARK: - Private
private func call(_ completion: ResultCompletion<Data>) {
if let data = responseData {
completion(.success(data))
}
if let error = error {
completion(.failure(error))
}
}
}
| 27.513514 | 140 | 0.646365 |
6ad4a6bcba983d213a986a3e320ff5ae7c5bc8b1 | 1,164 | //
// RSS_GeneratorUITests.swift
// RSS-GeneratorUITests
//
// Created by zijia on 1/29/20.
// Copyright © 2020 zijia. All rights reserved.
//
import XCTest
class RSS_GeneratorUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.257143 | 182 | 0.691581 |
ddf3ed56d906e9b5feb3883958c7098d0a1941ce | 2,157 | //
// KeystoreCreationTests.swift
// Keystore_Tests
//
// Created by Koray Koska on 28.06.18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import Foundation
@testable import Keystore
class KeystoreCreationTests: QuickSpec {
let decoder = JSONDecoder()
override func spec() {
describe("keystore creation") {
context("random private keys default keystore") {
for _ in 0..<10 {
guard let randomBytes = [UInt8].secureRandom(count: 32) else {
it("should never happen") {
expect(true) == false
}
return
}
let password = UUID().uuidString
let keystore = try? Keystore(privateKey: randomBytes, password: password)
it("should not be nil") {
expect(keystore).toNot(beNil())
}
it("should create a valid keystore") {
expect(keystore?.version) == 3
expect(keystore?.crypto.cipher) == "aes-128-ctr"
expect(keystore?.crypto.kdf) == Keystore.Crypto.KDFType.scrypt
// Scrypt params
expect(keystore?.crypto.kdfparams.n).toNot(beNil())
expect(keystore?.crypto.kdfparams.r).toNot(beNil())
expect(keystore?.crypto.kdfparams.p).toNot(beNil())
// PBKDF2 params
expect(keystore?.crypto.kdfparams.prf).to(beNil())
expect(keystore?.crypto.kdfparams.c).to(beNil())
}
let extracted = (try? keystore?.privateKey(password: password)) ?? nil
it("should not be nil") {
expect(extracted).toNot(beNil())
}
it("should match original key") {
expect(extracted) == randomBytes
}
}
}
}
}
}
| 34.790323 | 93 | 0.472879 |
acea334fc812a901d1a3f743dc0d21b347a35b0d | 1,173 | import Vapor
struct FileConfig {
let themeRoot = "themes"
let imageRoot = "documents/imgs"
let workingDirectory: String
let publicDirecoty: String
let themeDirectory: String
let imageDirectory: String
init(directory: DirectoryConfiguration) {
workingDirectory = directory.workingDirectory
publicDirecoty = directory.publicDirectory
themeDirectory = directory.publicDirectory.finished(with: "/").appending(themeRoot)
imageDirectory = directory.publicDirectory.finished(with: "/").appending(imageRoot)
}
func templateDirectory(in theme: String) -> String {
return themeDirectory.finished(with: "/")
.appending(theme).finished(with: "/")
.appending("template").finished(with: "/")
}
}
extension FileConfig: StorageKey {
typealias Value = FileConfig
}
extension Application {
func register(fileConfig: FileConfig) {
storage[FileConfig.self] = fileConfig
}
var fileConfig: FileConfig {
guard let fileConfig = storage[FileConfig.self] else {
fatalError("service not initialized")
}
return fileConfig
}
}
| 27.928571 | 91 | 0.673487 |
e2bb7a073f27a2e8fb1ab2f45e1ebf4ea0b15aca | 1,661 | //
// ViewController.swift
// YRRangePicker
//
// Created by Yuri on 08/20/2020.
// Copyright (c) 2020 Yuri. All rights reserved.
//
import UIKit
import YRRangePicker
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// picker.rangeBar.updateBarImage(left: <#T##UIImage#>, right: <#T##UIImage#>)
picker.didUpdateRange = { min,max in
print("min:\(min) , max:\(max)")
}
view.addSubview(picker)
changeBtn.frame = CGRect.init(x: 50, y: 200, width: 100, height: 50)
view.addSubview(changeBtn)
}
lazy var picker: YRRangePicker = {
let picker = YRRangePicker.init(pickType: .outside, frame: CGRect.init(x: 50, y: 100, width: 300, height: 40))
picker.contentView.backgroundColor = UIColor.yellow
return picker
}()
lazy var changeBtn: UIButton = {
let view = UIButton.init(type: .custom)
view.setTitle("改变picker类型", for: .normal)
view.setImage(nil, for: .normal)
view.setTitleColor(UIColor.blue, for: .normal)
view.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
view.addTarget(nil, action: #selector(onChangeClick), for: .touchUpInside)
return view
}()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func onChangeClick(){
if self.picker.pickType == .center {
self.picker.pickType = .outside
}else{
self.picker.pickType = .center
}
}
}
| 29.660714 | 118 | 0.611078 |
d54f653d93c171c1b7bc38392b5fdf07811ce90d | 5,942 | // Copyright SIX DAY LLC. All rights reserved.
import XCTest
@testable import AlphaWallet
import TrustKeystore
class InCoordinatorTests: XCTestCase {
func testShowTabBar() {
let config: Config = .make()
let wallet: Wallet = .make()
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: .make(),
keystore: FakeKeystore(wallets: [wallet]),
assetDefinitionStore: AssetDefinitionStore(),
config: config
)
coordinator.start()
let tabbarController = coordinator.navigationController.viewControllers[0] as? UITabBarController
XCTAssertNotNil(tabbarController)
XCTAssert(tabbarController?.viewControllers!.count == 4)
XCTAssert((tabbarController?.viewControllers?[0] as? UINavigationController)?.viewControllers[0] is TokensViewController)
XCTAssert((tabbarController?.viewControllers?[1] as? UINavigationController)?.viewControllers[0] is TransactionsViewController)
XCTAssert((tabbarController?.viewControllers?[2] as? UINavigationController)?.viewControllers[0] is DappsHomeViewController)
XCTAssert((tabbarController?.viewControllers?[3] as? UINavigationController)?.viewControllers[0] is SettingsViewController)
}
func testChangeRecentlyUsedAccount() {
let account1: Wallet = .make(type: .watch(AlphaWallet.Address(string: "0x1000000000000000000000000000000000000000")!))
let account2: Wallet = .make(type: .watch(AlphaWallet.Address(string: "0x2000000000000000000000000000000000000000")!))
let keystore = FakeKeystore(
wallets: [
account1,
account2
]
)
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: .make(),
keystore: keystore,
assetDefinitionStore: AssetDefinitionStore(),
config: .make()
)
coordinator.showTabBar(for: account1)
XCTAssertEqual(coordinator.keystore.recentlyUsedWallet, account1)
coordinator.showTabBar(for: account2)
XCTAssertEqual(coordinator.keystore.recentlyUsedWallet, account2)
}
func testShowSendFlow() {
let wallet: Wallet = .make()
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: wallet,
keystore: FakeKeystore(wallets: [wallet]),
assetDefinitionStore: AssetDefinitionStore(),
config: .make()
)
coordinator.showTabBar(for: .make())
coordinator.showPaymentFlow(for: .send(type: .nativeCryptocurrency(TokenObject(), destination: .none, amount: nil)), server: .main)
let controller = (coordinator.navigationController.presentedViewController as? UINavigationController)?.viewControllers[0]
XCTAssertTrue(coordinator.coordinators.last is PaymentCoordinator)
XCTAssertTrue(controller is SendViewController)
}
func testShowRequstFlow() {
let wallet: Wallet = .make()
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: wallet,
keystore: FakeKeystore(wallets: [wallet]),
assetDefinitionStore: AssetDefinitionStore(),
config: .make()
)
coordinator.showTabBar(for: .make())
coordinator.showPaymentFlow(for: .request, server: .main)
let controller = (coordinator.navigationController.presentedViewController as? UINavigationController)?.viewControllers[0]
XCTAssertTrue(coordinator.coordinators.last is PaymentCoordinator)
XCTAssertTrue(controller is RequestViewController)
}
func testShowTabDefault() {
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: .make(),
keystore: FakeKeystore(),
assetDefinitionStore: AssetDefinitionStore(),
config: .make()
)
coordinator.showTabBar(for: .make())
let viewController = (coordinator.tabBarController?.selectedViewController as? UINavigationController)?.viewControllers[0]
XCTAssert(viewController is TokensViewController)
}
//Commented out because the tokens tab has been moved to be under the More tab and will be moved
// func testShowTabTokens() {
// let coordinator = InCoordinator(
// navigationController: FakeNavigationController(),
// wallet: .make(),
// keystore: FakeEtherKeystore(),
// config: .make()
// )
// coordinator.showTabBar(for: .make())
// coordinator.showTab(.tokens)
// let viewController = (coordinator.tabBarController?.selectedViewController as? UINavigationController)?.viewControllers[0]
// XCTAssert(viewController is TokensViewController)
// }
func testShowTabAlphwaWalletWallet() {
let keystore = FakeEtherKeystore()
switch keystore.createAccount() {
case .success(let account):
let wallet = Wallet(type: .real(account))
keystore.recentlyUsedWallet = wallet
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: wallet,
keystore: keystore,
assetDefinitionStore: AssetDefinitionStore(),
config: .make()
)
coordinator.showTabBar(for: wallet)
coordinator.showTab(.wallet)
let viewController = (coordinator.tabBarController?.selectedViewController as? UINavigationController)?.viewControllers[0]
XCTAssert(viewController is TokensViewController)
case .failure:
XCTFail()
}
}
}
| 38.089744 | 139 | 0.656008 |
01bcd471e3b4c5748365ef0d0fb16421f12198a4 | 4,150 | import Foundation
import Checksum
import Toolkit
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Xcode models structure: //
// XcodeProj - root, represent *.xcodeproj file. It contains pbxproj file represented by Proj (Look below) and xcschemes. //
// Proj - represent project.pbxproj file. It contains all references to objects - projects, files, groups, targets etc. //
// Project - represent build project. It contains build settings and targets. //
// Target - represent build target. It contains build phases. For example source build phase. //
// File - represent source file. Can be obtained from source build phase. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public final class XcodeProjChecksumHolder<ChecksumType: Checksum>: BaseChecksumHolder<ChecksumType> {
override public var children: ThreadSafeDictionary<String, BaseChecksumHolder<ChecksumType>> {
return projs.cast { $0 }
}
var projs = ThreadSafeDictionary<String, ProjChecksumHolder<ChecksumType>>()
private let fullPathProvider: FileElementFullPathProvider
private let checksumProducer: URLChecksumProducer<ChecksumType>
private let projectCache = ThreadSafeDictionary<String, ProjectChecksumHolder<ChecksumType>>()
private let targetCache = ThreadSafeDictionary<String, TargetChecksumHolder<ChecksumType>>()
private let fileCache = ThreadSafeDictionary<String, FileChecksumHolder<ChecksumType>>()
init(
name: String,
fullPathProvider: FileElementFullPathProvider,
checksumProducer: URLChecksumProducer<ChecksumType>)
{
self.fullPathProvider = fullPathProvider
self.checksumProducer = checksumProducer
super.init(
name: name,
parent: nil
)
}
override public func calculateChecksum() throws -> ChecksumType {
return try projs.values.sorted().map {
try $0.obtainChecksum()
}.aggregate()
}
func reflectUpdate(updateModel: XcodeProjUpdateModel) throws {
let projectUpdateModelsDictionary = [updateModel.xcodeProj.pbxproj]
.map { proj in
ProjUpdateModel(
proj: proj,
projectPath: updateModel.projectPath,
sourceRoot: updateModel.sourceRoot,
projectCache: projectCache,
targetCache: targetCache,
fileCache: fileCache
)
}.toDictionary { $0.name }
let shouldInvalidate = try projectUpdateModelsDictionary.update(
childrenDictionary: projs,
update: { projChecksumHolder, projUpdateModel in
projChecksumHolder.parents.write(self, for: name)
try projChecksumHolder.reflectUpdate(updateModel: projUpdateModel)
},
onRemove: { _ in
},
buildValue: { projUpdateModel in
ProjChecksumHolder(
name: projUpdateModel.name,
parent: self,
fullPathProvider: fullPathProvider,
checksumProducer: checksumProducer
)
}
)
try clearCache(cache: projectCache)
try clearCache(cache: targetCache)
try clearCache(cache: fileCache)
if shouldInvalidate {
invalidate()
}
}
private func clearCache<Holder: BaseChecksumHolder<ChecksumType>>(
cache: ThreadSafeDictionary<String, Holder>) throws
{
try cache.copy().enumerateKeysAndObjects(options: .concurrent) { key, holder, _ in
if holder.parents.isEmpty {
cache.removeValue(forKey: key)
}
}
}
}
| 43.229167 | 124 | 0.562651 |
cc70b0f335bcd793bea22f9a540ac7e220d0c55b | 3,116 | import Foundation
import azureSwiftRuntime
public protocol WebAppsGetVnetConnectionGateway {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var name : String { get set }
var vnetName : String { get set }
var gatewayName : String { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (VnetGatewayProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.WebApps {
// GetVnetConnectionGateway gets an app's Virtual Network gateway.
internal class GetVnetConnectionGatewayCommand : BaseCommand, WebAppsGetVnetConnectionGateway {
public var resourceGroupName : String
public var name : String
public var vnetName : String
public var gatewayName : String
public var subscriptionId : String
public var apiVersion = "2016-08-01"
public init(resourceGroupName: String, name: String, vnetName: String, gatewayName: String, subscriptionId: String) {
self.resourceGroupName = resourceGroupName
self.name = name
self.vnetName = vnetName
self.gatewayName = gatewayName
self.subscriptionId = subscriptionId
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections/{vnetName}/gateways/{gatewayName}"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{name}"] = String(describing: self.name)
self.pathParameters["{vnetName}"] = String(describing: self.vnetName)
self.pathParameters["{gatewayName}"] = String(describing: self.gatewayName)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(VnetGatewayData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (VnetGatewayProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: VnetGatewayData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 47.212121 | 190 | 0.63896 |
899799dd5f84fa41cf689ecc6fcab6b59c62a913 | 77 |
public protocol Scene {
associatedtype Content
func launch() -> Content
}
| 12.833333 | 25 | 0.74026 |
67f03f475e1605dcd84c90a0e43a51d6089d37ff | 936 | //
// ChildView.swift
// DataFlow
//
// Created by Sarah Reichelt on 15/09/2019.
// Copyright © 2019 TrozWare. All rights reserved.
//
import SwiftUI
struct ChildView: View {
// Because this view does not use the data, there is no need to pass
// it down to it, but its child can still access that data.
var body: some View {
ZStack {
Color.green
VStack {
Text("This view has no data.")
Text("But it has a child that does.")
GrandChildView().padding()
}
.foregroundColor(.white)
.padding()
}
}
}
struct ChildView_Previews: PreviewProvider {
static var previews: some View {
// Preview must have access to the required environment object
// because this view previews its child which uses it
ChildView()
.environmentObject(UserSettings())
}
}
| 24 | 72 | 0.582265 |
dd24b9a4be7070f1b403308b4ab233128f176c93 | 951 | //
// GettyTests.swift
// GettyTests
//
// Created by Hyyy on 2017/12/12.
// Copyright © 2017年 Getty. All rights reserved.
//
import XCTest
@testable import Getty
class GettyTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.702703 | 111 | 0.626709 |
1da7f07ff12b966d98288d4868f0e89d19c9a00a | 1,360 | //
// StickyHeaderFlowLayoutAttributes.swift
// IcheMusicPlayer
//
// Created by Jakub Slawecki on 02/02/2020.
// Copyright © 2020 Jakub Slawecki. All rights reserved.
//
import UIKit
class StickyHeaderFlowLayoutAttributes: UICollectionViewLayoutAttributes {
var progressiveness: CGFloat = 0
override func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone)
if let copy = copy as? StickyHeaderFlowLayoutAttributes {
copy.progressiveness = progressiveness
}
return copy
}
override var zIndex: Int {
didSet {
// Fixes: Section header go behind cell when insert via performBatchUpdates #68
// https://github.com/jamztang/CSStickyHeaderFlowLayout/issues/68#issuecomment-108678022
// Reference: UICollectionView setLayout:animated: not preserving zIndex
// http://stackoverflow.com/questions/12659301/uicollectionview-setlayoutanimated-not-preserving-zindex
// originally our solution is to translate the section header above the original z position,
// however, scroll indicator will be covered by those cells and section header if z position is >= 1
// so instead we translate the original cell to be -1, and make sure the cell are hit test proven.
transform3D = CATransform3DMakeTranslation(0, 0, zIndex == 1 ? -1 : 0);
}
}
}
| 34.871795 | 109 | 0.716912 |
2f5efb9e722cf2cf46651c48cafd8c921c548651 | 17,926 | import UIKit
import AudioKit
typealias Callback = () -> ()
typealias Chord = [MIDINoteNumber]
// //////////////////////////////
// MARK: AudioKit
// //////////////////////////////
/**
Setup and run AudioKit with array of `AKNode`.
*/
func startAudioKit(withOutputs: [AKNode]) {
do {
let mixer = AKMixer(withOutputs)
AudioKit.output = mixer
try AudioKit.start()
} catch {
AKLog("AudioKit did not start!")
}
}
/**
Setup and run AudioKit with `AKMixer`.
*/
func startAudioKit(withMixer: AKMixer) {
do {
AudioKit.output = withMixer
try AudioKit.start()
} catch {
AKLog("AudioKit did not start!")
}
}
/**
Struct to hold values for ADSR envelope conforming to AudioKit expectations. Attack, Decay, and Release are time values, and Sustain is a normalized gain value.
*/
struct ADSR {
var a: Double, d: Double, s: Double, r: Double
init(a: Double = 0.02, d: Double = 0.1, s: Double = 0.85, r: Double = 0.1) {
self.a = a
self.d = d
self.s = s
self.r = r
}
init(_ a: Double = 0.02, _ d: Double = 0.1, _ s: Double = 0.85, _ r: Double = 0.1) {
self.init(a: a, d: d, s: s, r: r)
}
/**
`return ADSR(a: 0.02, d: 0.1, s: 0.85, r: 0.1)`
*/
static func defaultShort() -> ADSR {
return ADSR(a: 0.02, d: 0.1, s: 0.85, r: 0.1)
}
/**
`return ADSR(a: 0.1, d: 0.0, s: 1.0, r: 0.3)`
*/
static func defaultLong() -> ADSR {
return ADSR(a: 0.1, d: 0.0, s: 1.0, r: 0.3)
}
}
struct MIDINoteProperties {
var frequency: Double
var velocity: MIDIVelocity
init(frequency: Double, velocity: MIDIVelocity) {
self.frequency = frequency
self.velocity = velocity
}
}
struct FM {
var harmonicityRatio: Double,
modulatorMultiplier: Double,
modulationIndex: Double
init(harmonicityRatio: Double = 1.0, modulationIndex: Double = 1.0, modulatorMultiplier: Double = 1.0) {
self.harmonicityRatio = harmonicityRatio
self.modulationIndex = modulationIndex
self.modulatorMultiplier = modulatorMultiplier
}
init(_ harmonicityRatio: Double = 1.0, _ modulationIndex: Double = 1.0, _ modulatorMultiplier: Double = 1.0) {
self.init(harmonicityRatio: harmonicityRatio, modulationIndex: modulationIndex, modulatorMultiplier: modulatorMultiplier)
}
}
extension Array where Element == MIDINoteNumber {
mutating func modulate(_ amount: Int) -> [MIDINoteNumber] {
return self.map({ MIDINoteNumber(Int($0) + amount) })
}
}
// //////////////////////////////
// MARK: App Utility
// //////////////////////////////
// This extension lets us mimic a stored property on AppDelegate, and allows us to publicly set and get `orientationLock`.
// See KD.restrictTo(orientation:)
extension AppDelegate {
private static var _orientationLock = UIInterfaceOrientationMask.all
var orientationLock: UIInterfaceOrientationMask {
get {
return AppDelegate._orientationLock
}
set(orientation) {
AppDelegate._orientationLock = orientation
}
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate._orientationLock
}
}
struct KD {
static func getTopViewController() -> UIViewController {
var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
while topController?.presentedViewController != nil {
topController = topController?.presentedViewController
}
return topController!
}
/**
Restrict auto rotate to the passed orientation. Automatically rotates to an appropriate orientation.
In order to ensure an acceptable orientation is ready when a view controller is loaded, this should be called in `viewDidLoad()`, and other view dependent code in `viewWillAppear(_ animated: Bool)`.
Example:
```
override func viewDidLoad() {
super.viewDidLoad()
KD.restrictTo(orientation: .landscapeLeft)
}
override func viewWillAppear(_ animated: Bool) {
makeViews()
}
```
Otherwise, view controllers should override `didRotate(from fromInterfaceOrientation: UIInterfaceOrientation)` in order to ensure drawing code occurs *after* the rotation and will use proper geometry.
*/
static func restrictTo(orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
let lastOrientation = delegate.orientationLock
delegate.orientationLock = orientation
if lastOrientation != orientation {
switch orientation {
case .landscape:
if lastOrientation == .landscapeLeft || lastOrientation == .landscapeRight { break }
rotateTo(orientation: .landscapeLeft)
case .landscapeLeft:
rotateTo(orientation: .landscapeLeft)
case .landscapeRight:
rotateTo(orientation: .landscapeRight)
case .allButUpsideDown:
if lastOrientation == .portraitUpsideDown {
rotateTo(orientation: .portrait)
}
case .portraitUpsideDown:
rotateTo(orientation: .portraitUpsideDown)
default:
break
}
}
}
}
/**
Rotate the current view controller to the passed orientation.
*/
static func rotateTo(orientation: UIInterfaceOrientation) {
UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
}
}
// //////////////////////////////
// MARK: GCD
// //////////////////////////////
func waitFor(duration: Double, then: @escaping Callback) {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
then()
}
}
}
func async(_ function: @escaping Callback) {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
function()
}
}
}
// //////////////////////////////
// MARK: Numbers
// //////////////////////////////
func roundValue(value: Double, places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(value * divisor) / divisor
}
func roundValue(value: Float, places: Int) -> Float {
let divisor = pow(10.0, Float(places))
return round(value * divisor) / divisor
}
func roundValue(value: CGFloat, places: Int) -> CGFloat {
let divisor = pow(10.0, CGFloat(places))
return round(value * divisor) / divisor
}
func roundValue(point: CGPoint, places: Int) -> CGPoint {
let divisor = pow(10.0, CGFloat(places))
return CGPoint(x: round(point.x * divisor) / divisor, y: round(point.y * divisor) / divisor)
}
func roundValue(_ value: Double, _ places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(value * divisor) / divisor
}
func roundValue(_ value: Float, _ places: Int) -> Float {
let divisor = pow(10.0, Float(places))
return round(value * divisor) / divisor
}
func roundValue(_ value: CGFloat, _ places: Int) -> CGFloat {
let divisor = pow(10.0, CGFloat(places))
return round(value * divisor) / divisor
}
func roundValue(_ point: CGPoint, _ places: Int) -> CGPoint {
let divisor = pow(10.0, CGFloat(places))
return CGPoint(x: round(point.x * divisor) / divisor, y: round(point.y * divisor) / divisor)
}
// //////////////////////////////
func clip(value: Int, bounds: (Int, Int)) -> Int {
let (minValue, maxValue) = bounds
return max(minValue, min(value, maxValue))
}
func clip(value: Double, bounds: (Double, Double)) -> Double {
let (minValue, maxValue) = bounds
return max(minValue, min(value, maxValue))
}
func clip(value: Float, bounds: (Float, Float)) -> Float {
let (minValue, maxValue) = bounds
return max(minValue, min(value, maxValue))
}
func clip(value: CGFloat, bounds: (CGFloat, CGFloat)) -> CGFloat {
let (minValue, maxValue) = bounds
return max(minValue, min(value, maxValue))
}
// //////////////////////////////
func scale(input: Int, inputRange: (Int, Int), outputRange: (Int, Int)) -> Int {
let (iLo, iHi) = inputRange
let (oLo, oHi) = outputRange
return ((input - iLo) / (iHi - iLo)) * ((oHi - oLo)) + oLo
}
func scale(input: Double, inputRange: (Double, Double), outputRange: (Double, Double)) -> Double {
let (iLo, iHi) = inputRange
let (oLo, oHi) = outputRange
return ((input - iLo) / (iHi - iLo)) * ((oHi - oLo)) + oLo
}
func scale(input: Float, inputRange: (Float, Float), outputRange: (Float, Float)) -> Float {
let (iLo, iHi) = inputRange
let (oLo, oHi) = outputRange
return ((input - iLo) / (iHi - iLo)) * ((oHi - oLo)) + oLo
}
func scale(input: CGFloat, inputRange: (CGFloat, CGFloat), outputRange: (CGFloat, CGFloat)) -> CGFloat {
let (iLo, iHi) = inputRange
let (oLo, oHi) = outputRange
return ((input - iLo) / (iHi - iLo)) * ((oHi - oLo)) + oLo
}
// //////////////////////////////
// MARK: View Geometry
// //////////////////////////////
/** Returns `view.bounds.size.width`. */
func vw (_ view: UIView) -> CGFloat {
return view.bounds.size.width
}
/** Returns `view.bounds.size.height`. */
func vh (_ view: UIView) -> CGFloat {
return view.bounds.size.height
}
/** Returns `view.frame.origin.x`. */
func vx (_ view: UIView) -> CGFloat {
return view.frame.origin.x
}
/** Returns `view.frame.origin.y`. */
func vy (_ view: UIView) -> CGFloat {
return view.frame.origin.y
}
/** Returns the center point of the passed view in relation to its own bounds `x: view.bounds.width / 2, y: view.bounds.height / 2`. */
func vc (_ view: UIView) -> CGPoint {
return CGPoint(x: view.bounds.size.width / 2, y: view.bounds.size.height / 2)
}
/** Vertically append a view to another. This determines the bottom edge of the upper view and sets the Y coordinate for the appending view. */
func appendView (_ view: UIView, toView: UIView, withMarginY: CGFloat, andIndentX: CGFloat) {
let frame: CGRect = CGRect(x: toView.bounds.origin.x + andIndentX,
y: toView.frame.origin.y + toView.frame.size.height + withMarginY,
width: view.frame.size.width,
height: view.frame.size.height)
view.frame = frame
}
// //////////////////////////////
// MARK: Colors
// //////////////////////////////
/**
Color helper function.
Returns a `UIColor` for the given rgba values. Accepts values scaled (0-1) or (0-255).
*/
func rgba (_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat) -> UIColor {
var components: Array<CGFloat> = [r, g, b, a]
for (index, value) in components.enumerated() {
if value > 1 {
components[index] = value / 255.0
}
}
return UIColor(red: components[0], green: components[1], blue: components[2], alpha: components[3])
}
/**
Color helper function.
Returns a `UIColor` for the given 6-figure hex value. Accepts strings with or without the "#" prefix.
*/
func hex (_ hex: String) throws -> UIColor {
enum HexError: Error {
case mustHaveSixDigits
}
var code: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (code.hasPrefix("#")) {
code.remove(at: code.startIndex)
}
if (code.count != 6) {
throw HexError.mustHaveSixDigits
}
var rgbValue: UInt32 = 0
Scanner(string: code).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
extension UIColor {
/**
UIColor extension. Inverts the rgb values and returns a new color.
*/
func invert () -> UIColor {
guard var components = self.cgColor.components else { return self }
for (index, value) in components.enumerated() {
if index < 3 {
components[index] = 1.0 - value
}
}
return UIColor(red: components[0], green: components[1], blue: components[2], alpha: components[3])
}
}
// //////////////////////////////
// MARK: Gestures
// //////////////////////////////
/**
Struct to hold shadow values for `UIView.layer`. Any `nil` parameters will use the default values as follows:
```
radius = 1.0
offset = CGSize(width: 1.0, height: 2.0)
color = KDColor.grey
opacity = 0.9
```
Defaults are stored as a global value and can be changed.
*/
struct Shadow {
var radius: CGFloat,
offset: CGSize,
color: UIColor,
opacity: Float
static var defaults = (radius: CGFloat(1.0),
offset: CGSize(width: 1.0, height: 2.0),
color: KDColor.grey,
opacity: Float(0.9))
init(radius: CGFloat?, offset: CGSize?, color: UIColor?, opacity: Float?) {
self.radius = radius != nil ? radius! : Shadow.defaults.radius
self.offset = offset != nil ? offset! : Shadow.defaults.offset
self.color = color != nil ? color! : Shadow.defaults.color
self.opacity = opacity != nil ? opacity! : Shadow.defaults.opacity
}
init(radius: CGFloat?, offset: (CGFloat?, CGFloat?), color: UIColor?, opacity: Float?) {
let (xo, yo) = offset
let x = xo != nil ? xo! : Shadow.defaults.offset.width
let y = yo != nil ? yo! : Shadow.defaults.offset.height
self.init(radius: radius, offset: CGSize(width: x, height: y), color: color, opacity: opacity)
}
init(radius: CGFloat?, offset: (CGFloat?, CGFloat?), color: UIColor?) {
self.init(radius: radius, offset: offset, color: color, opacity: nil)
}
init(radius: CGFloat?, offset: (CGFloat?, CGFloat?)) {
self.init(radius: radius, offset: offset, color: nil, opacity: nil)
}
init(radius: CGFloat?) {
self.init(radius: radius, offset: (nil, nil), color: nil, opacity: nil)
}
init(offset: (CGFloat?, CGFloat?)) {
self.init(radius: nil, offset: offset, color: nil, opacity: nil)
}
init() {
self.init(radius: nil, offset: (nil, nil), color: nil, opacity: nil)
}
}
// //////////////////////////////
// MARK: Gestures
// //////////////////////////////
extension UIGestureRecognizer {
// Add a type property. This is set when a KDView gesture calls its callback. This simplifies being able to identify the sender when a view has multiple recognizers.
enum GestureType {
case none
case tap
case longPress
case swipe
case pan
case pinch
}
struct Holder {
static var type: GestureType = .none
}
var type: GestureType {
get {
return Holder.type
}
set(type) {
Holder.type = type
}
}
}
// //////////////////////////////
// MARK: UIImage
// //////////////////////////////
extension UIImage {
func resizeImage(_ scale: CGFloat) -> UIImage? {
return resizeImage(CGSize(width: self.size.width * scale, height: self.size.height * scale))
}
func resizeImage(_ newSize: CGSize) -> UIImage? {
func isSameSize(_ newSize: CGSize) -> Bool {
return size == newSize
}
func scaleImage(_ newSize: CGSize) -> UIImage? {
func getScaledRect(_ newSize: CGSize) -> CGRect {
let ratio = max(newSize.width / size.width, newSize.height / size.height)
let width = size.width * ratio
let height = size.height * ratio
return CGRect(x: 0, y: 0, width: width, height: height)
}
func _scaleImage(_ scaledRect: CGRect) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0);
draw(in: scaledRect)
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
return _scaleImage(getScaledRect(newSize))
}
return isSameSize(newSize) ? self : scaleImage(newSize)!
}
}
// //////////////////////////////
// MARK: Dictionary
// //////////////////////////////
extension Dictionary {
var stringRepresentation: String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted]) else { return nil }
return String(data: data, encoding: .ascii)
}
}
// //////////////////////////////
// MARK: Array
// //////////////////////////////
extension Array {
var stringRepresentation: String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else { return nil }
return String(data: data, encoding: .ascii)
}
}
// //////////////////////////////
// MARK: String
// //////////////////////////////
extension String {
func convertToDictionary() -> [String: Any]? {
if let data = self.data(using: .ascii) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
func convertToArray() -> [String]? {
if let data = self.data(using: .ascii) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
| 31.229965 | 205 | 0.583956 |
5b8843b73cd496aac4e3ea3702ed708f381e6327 | 19,893 | //
// SelectedViewController.swift
// Shoping
//
// Created by qiang.c.fu on 2019/12/25.
// Copyright © 2019 付强. All rights reserved.
//
import UIKit
import ZLCollectionViewFlowLayout
import AlamofireImage
import FSPagerView
let ScreenWidth = UIScreen.main.bounds.width
let ScreenHeight = UIScreen.main.bounds.height
class SelectedViewController: UIViewController {
var collectionView : UICollectionView?
// @IBOutlet weak var collectionView: UICollectionView!
let Identifier = "SelectedImageCollectionViewCell"
let goods = "GoodsListCollectionViewCell"
let headerBannerIdentifier = "CollectionBannerHeaderView"
let headerTypeIdentifier = "CollectionTypeHeaderView"
let height = ScreenWidth/414.0
let FHeig = ScreenHeight/414.0
var data: Home? = nil
var lablesIndex = 0
var didSelectCell: ((Int, IndexPath) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
}
func setView(ehigth: Float) {
let layout = ZLCollectionViewVerticalLayout()
layout.delegate = self
collectionView = UICollectionView.init(frame: CGRect(x:0, y:0, width:view.frame.size.width, height:CGFloat(ehigth)), collectionViewLayout: layout)
collectionView?.backgroundColor = UIColor.white
collectionView?.delegate = self
collectionView?.dataSource = self
self.view.addSubview(collectionView!)
collectionView?.snp.makeConstraints({ (make) in
make.top.left.right.equalToSuperview()
make.bottom.equalToSuperview()
})
// 注册
collectionView?.register(UINib.init(nibName: "SelectedImageCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: Identifier)
collectionView?.register(UINib.init(nibName: "GoodsListCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: goods)
// 注册headerView
collectionView?.register(UINib.init(nibName: "SelectedBannerCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: headerBannerIdentifier)
collectionView?.register(UINib.init(nibName: "SelectedTypeCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: headerTypeIdentifier)
collectionView?.register(UINib.init(nibName: "SelectedFooterCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionFooter", withReuseIdentifier: "footer")
collectionView?.register(UINib.init(nibName: "SelectedHeaderCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "header")
collectionView?.register(UINib.init(nibName: "SelectedMoreCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "headerMore")
}
}
extension SelectedViewController: UICollectionViewDelegate, UICollectionViewDataSource, ZLCollectionViewBaseFlowLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return data?.data.imageLabels.count ?? 0
}
return data?.data.labels[lablesIndex].product.count ?? 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
let cell:GoodsListCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: goods, for: indexPath) as! GoodsListCollectionViewCell
if !(data?.data.labels[lablesIndex].product[indexPath.item].image.isEmpty ?? true) {
cell.goodsImg.af_setImage(withURL: URL(string: (data?.data.labels[lablesIndex].product[indexPath.item].image)!)!)
}
cell.goodsName.text = (data?.data.labels[lablesIndex].product[indexPath.item].name ?? "")
cell.info.text = data?.data.labels[lablesIndex].product[indexPath.item].title
cell.setPri(str: "¥" + (data?.data.labels[lablesIndex].product[indexPath.item].price ?? "0"))
// cell.price.text = "¥" + (data?.data.labels[lablesIndex].product[indexPath.item].price ?? "0")
return cell
}
let cell:SelectedImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier, for: indexPath) as! SelectedImageCollectionViewCell
if indexPath.section == 0 {
cell.name.text = data?.data.imageLabels[indexPath.item].name ?? ""
if data?.data.imageLabels[indexPath.item].image ?? "" != "" {
cell.img.af_setImage(withURL: URL(string: data?.data.imageLabels[indexPath.item].image ?? "")!)
}
// if indexPath.item == 0 {
// cell.img.image = UIImage(named: "新品上新")
// if data?.data.imageLabels.count ?? 0 >= 1 {
// cell.name.text = data?.data.imageLabels[0].name ?? ""
// }
// } else if indexPath.item == 1 {
// cell.img.image = UIImage(named: "Recommend")
// if data?.data.imageLabels.count ?? 0 >= 2 {
// cell.name.text = data?.data.imageLabels[1].name ?? ""
// }
// } else if indexPath.item == 2 {
// cell.img.image = UIImage(named: "food")
// if data?.data.imageLabels.count ?? 0 >= 3 {
// cell.name.text = data?.data.imageLabels[2].name ?? ""
// }
// } else if indexPath.item == 3 {
// cell.img.image = UIImage(named: "international")
// if data?.data.imageLabels.count ?? 0 >= 4 {
// cell.name.text = data?.data.imageLabels[3].name ?? ""
// }
// } else {
// cell.img.image = UIImage(named: "Live")
// if data?.data.imageLabels.count ?? 0 >= 5 {
// cell.name.text = data?.data.imageLabels[4].name ?? ""
// }
// }
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch indexPath.section {
case 0:
return CGSize(width: 90*height, height: 90*height)
default:
let width = 175*height
let heightd = ga_heightForComment(fontSize: 17, width: width, text: data?.data.labels[lablesIndex].product[indexPath.item].name ?? "")
return CGSize(width: 195*height, height: 305)
}
}
func ga_heightForComment(fontSize: CGFloat, width: CGFloat, text: String) -> CGFloat {
let font = UIFont.systemFont(ofSize: fontSize)
let rect = NSString(string: text).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(rect.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
switch section {
case 0:
return UIEdgeInsets.init(top: 0, left: 10*height, bottom: 0, right: 10*height)
case 1:
return UIEdgeInsets.init(top: 0, left: 8*height, bottom: 0, right: 8*height)
default:
return UIEdgeInsets.init(top: 0, left: 15*height, bottom: 0, right: 15*height)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if section == 0 {
return 5*height
} else if section == 1 {
return 14*height
} else if section == 4 {
return 14*height
} else if section == 5 {
return 14*height
} else if section == 6 {
return 14*height
}
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
if section == 0 {
return 8*height
} else if section == 1 {
return 5*height
} else if section == 4 {
return 14*height
} else if section == 5 {
return 14*height
} else if section == 6 {
return 14*height
}
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: 0, height: 200)
} else if section == 1 {
return CGSize(width: 0, height: 180)
} else if section == 3 || section == 4 {
return CGSize(width: 0, height: 70)
} else if section == 5 {
return CGSize(width: 0, height: 40)
}
return CGSize(width: 0, height: 15)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 1 {
return CGSize(width: 0, height: 40)
} else if section == 0 {
return CGSize(width: 0, height: 20)
} else {
return CGSize(width: 0, height: 0)
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader{
if indexPath.section == 1 {
let reusableview: SelectedTypeCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerTypeIdentifier, for: indexPath) as! SelectedTypeCollectionReusableView
if reusableview.typeScrollView.subviews.count < 3 {
setTypeScroView(scroView: reusableview.typeScrollView)
}
let fsPagerView = FSPagerView(frame: CGRect(x: 16, y: 0, width: view.frame.size.width - 32, height: 110))
fsPagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "bannerCell")
fsPagerView.register(FSPagerBannerViewCell.self, forCellWithReuseIdentifier: "gifBannerCell")
// fsPagerView.register(UINib.init(nibName: "FSPagerBannerViewCell", bundle: nil), forCellWithReuseIdentifier: "gifBannerCell")
fsPagerView.delegate = self
fsPagerView.dataSource = self
fsPagerView.isInfinite = true
fsPagerView.backgroundColor = .white
fsPagerView.isScrollEnabled = false
// fsPagerView.layer.cornerRadius = 10
// fsPagerView.layer.masksToBounds = true
fsPagerView.tag = 999
reusableview.addSubview(fsPagerView)
return reusableview
} else if indexPath.section == 0 {
var reusableview:UICollectionReusableView!
reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerBannerIdentifier, for: indexPath) as! SelectedBannerCollectionReusableView
let fsPagerView = FSPagerView(frame: CGRect(x: 15, y: 10, width: view.frame.size.width - 30, height: 165))
fsPagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "bannerCell")
fsPagerView.delegate = self
fsPagerView.dataSource = self
fsPagerView.isInfinite = true
fsPagerView.backgroundColor = .white
fsPagerView.layer.cornerRadius = 10
fsPagerView.layer.masksToBounds = true
reusableview.addSubview(fsPagerView)
return reusableview
} else if indexPath.section == 3 || indexPath.section == 4 {
var reusableview:SelectedMoreCollectionReusableView!
reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerMore", for: indexPath) as! SelectedMoreCollectionReusableView
if indexPath.section == 3 {
reusableview.name.text = "帮帮付"
}
return reusableview
}
var reusableview:UICollectionReusableView!
reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
return reusableview
}else{
let footView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath)
return footView
}
}
func setTypeScroView(scroView: UIScrollView) {
let types = data?.data.labels ?? []
for index in 0..<types.count {
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: index*110, y: 0, width: 110, height: 50)
btn.setTitle(types[index].name, for: .normal)
btn.setTitleColor(.black, for: .normal)
btn.setTitleColor(.red, for: .selected)
btn.tag = index + 1000
btn.addTarget(self, action: #selector(selectType(btn:)), for: .touchUpInside)
if index == 0 {
btn.isSelected = true
btn.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 17)
}
scroView.addSubview(btn)
}
scroView.contentSize = CGSize(width: 110*types.count, height: 50)
scroView.showsHorizontalScrollIndicator = false
let line = UIImageView(frame: CGRect(x: 45, y: 40, width: 20, height: 2))
line.tag = 9000
line.backgroundColor = .red
scroView.addSubview(line)
}
@objc func selectType(btn: UIButton) {
lablesIndex = btn.tag - 1000
setTopBtnNormal(button: btn)
collectionView?.reloadData()
}
func setTopBtnNormal(button: UIButton) {
let types = data?.data.labels ?? []
for index in 1000..<(1000+types.count) {
let btn = view.viewWithTag(index) as! UIButton
btn.isSelected = false
btn.titleLabel?.font = UIFont.PingFangSCLightFont18
}
button.isSelected = true
button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 17)
let line = view.viewWithTag(9000)as! UIImageView
line.center = CGPoint(x: button.center.x, y: line.center.y)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelectCell?(lablesIndex, indexPath)
}
}
extension SelectedViewController: FSPagerViewDataSource,FSPagerViewDelegate {
func numberOfItems(in pagerView: FSPagerView) -> Int {
if pagerView.tag == 999 {
return data?.data.advertMiddle.count ?? 0
}
return data?.data.advertTop.count ?? 0
}
func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
if pagerView.tag == 999 {
if data?.data.advertMiddle[index].type == "1" {
let web = WebViewController()
web.hidesBottomBarWhenPushed = true
web.title = data?.data.advertMiddle[index].name ?? ""
web.uri = data?.data.advertMiddle[index].content ?? "https://www.necesstore.com"
self.navigationController?.viewControllers.last?.navigationController?.pushViewController(web, animated: true)
} else if data?.data.advertMiddle[index].type == "2" {
let list = GoodsListViewController()
list.hidesBottomBarWhenPushed = true
list.title = data?.data.advertMiddle[index].name ?? ""
list.product_ids = data?.data.advertMiddle[index].productIDS ?? ""
self.navigationController?.viewControllers.last?.navigationController?.pushViewController(list, animated: true)
} else if data?.data.advertMiddle[index].type == "3" {
if UserSetting.default.activeUserToken == nil {
let login = LoginViewController()
self.navigationController?.pushViewController(login, animated: true)
return
}
let shop = RenRenFightingWViewController()
shop.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(shop, animated: true)
}
} else {
if data?.data.advertTop[index].type == "1" {
let web = WebViewController()
web.hidesBottomBarWhenPushed = true
web.title = data?.data.advertTop[index].name ?? ""
web.uri = data?.data.advertTop[index].content ?? "https://www.necesstore.com"
self.navigationController?.viewControllers.last?.navigationController?.pushViewController(web, animated: true)
} else if data?.data.advertTop[index].type == "2"{
let list = GoodsListViewController()
list.hidesBottomBarWhenPushed = true
list.title = data?.data.advertTop[index].name ?? ""
list.product_ids = data?.data.advertTop[index].productIDS ?? ""
self.navigationController?.viewControllers.last?.navigationController?.pushViewController(list, animated: true)
} else if data?.data.advertTop[index].type == "3" {
if UserSetting.default.activeUserToken == nil {
let login = LoginViewController()
self.navigationController?.pushViewController(login, animated: true)
return
}
let shop = RenRenFightingWViewController()
shop.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(shop, animated: true)
}
}
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
// cell.imageView?.backgroundColor = UIColor.green
// cell.imageView?.layer.cornerRadius = 10
// cell.imageView?.layer.masksToBounds = true
if pagerView.tag == 999 {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "gifBannerCell", at: index) as!FSPagerBannerViewCell
cell.backgroundColor = .white
let url = URL.init(string: (data?.data.advertMiddle[index].image)!)!
let request = URLRequest(url: url)
//异步加载图片
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler:{ (response, data, error) -> Void in
if (error != nil) {
print(error)
return
}
cell.gif?.gifData = data
cell.gif?.startGif()
})
// cell.imageView?.af_setImage(withURL: URL(string: (data?.data.advertMiddle[index].image)!)!)
return cell
} else {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "bannerCell", at: index)
cell.backgroundColor = .white
cell.imageView?.af_setImage(withURL: URL(string: (data?.data.advertTop[index].image)!)!)
return cell
}
}
}
| 49.982412 | 230 | 0.627557 |
d940ba39d99328e51a440abb3d92b3305099d8bd | 835 | //
// TableViewCell.swift
// Salada
//
// Created by 1amageek on 2017/05/31.
// Copyright © 2017年 Stamp. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var judgmentLabel: UILabel!
@IBOutlet weak var expectLabel: UILabel!
@IBAction func decrementAction(_ sender: Any) {
self.decrement?()
}
@IBAction func incrementAction(_ sender: Any) {
self.increment?()
}
var increment: (() -> Void)?
var decrement: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
}
}
| 19.418605 | 71 | 0.645509 |
56d2df5e6b4167801b6f4df6de4d6cfe2030ac42 | 897 | import Quick
import Nimble
@testable import Cogito
class AppReducerSpec: QuickSpec {
override func spec() {
it("returns initial state when reset") {
let identity = Identity.example
let state = appState(
keyStore: KeyStoreState(keyStore: KeyStore(name: "test", scryptN: 0, scryptP: 0)),
geth: GethState(peersCount: 1, syncProgress: nil),
createIdentity: CreateIdentityState(description: "test", pending: true, newAccount: nil, error: "test"),
diamond: DiamondState(facets: [identity]),
telepath: TelepathState(channels: [TelepathChannel.example: identity.identifier], connectionError: nil)
)
let action = ResetAppState()
let nextState = appReducer(action: action, state: state)
expect(nextState) == initialAppState
}
}
}
| 40.772727 | 120 | 0.619844 |
f582703414e3ba18ce5ee64e4ab8bd362a4287cc | 1,504 | //
// UINavigationController+PopAnimation.swift
// 4billioSDK
//
// Created by Yelyzaveta Kartseva on 10.04.2021.
//
import UIKit
extension UINavigationController {
func pushViewController(_ viewController: UIViewController, transition: CATransition) {
self.view.layer.add(transition, forKey: kCATransition)
self.pushViewController(viewController, animated: false)
}
func popToRootViewController(transition: CATransition) {
self.view.layer.add(transition, forKey: kCATransition)
self.popToRootViewController(animated: false)
}
func popViewController(transition: CATransition) {
self.view.layer.add(transition, forKey: kCATransition)
self.popViewController(animated: false)
}
@discardableResult
func popViewController(toController classController: AnyClass, animated: Bool) -> Bool {
var controller:UIViewController? = nil
for vc in self.viewControllers {
if vc.classForCoder == classController {
controller = vc
}
}
if let controller = controller {
self.popToViewController(controller, animated: animated)
return true
}
return false
}
func contains(controller classController: AnyClass) -> Bool {
for vc in self.viewControllers {
if vc.classForCoder == classController {
return true
}
}
return false
}
}
| 28.377358 | 92 | 0.642952 |
1d3ef9b2bcc03af737239b79fdaadd459ae0029a | 2,895 | //
// YADLSpotAssessmentStep.swift
// sdlrkx
//
// Created by James Kizer on 5/2/16.
// Copyright © 2016 Cornell Tech Foundry. All rights reserved.
//
import ResearchKit
open class YADLSpotAssessmentStep: RKXMultipleImageSelectionSurveyStep {
override open func stepViewControllerClass() -> AnyClass {
return YADLSpotAssessmentStepViewController.self
}
public static func create(identifier: String, propertiesFileName: String, itemIdentifiers: [String]? = nil) throws -> YADLSpotAssessmentStep? {
guard let filePath = Bundle.main.path(forResource: propertiesFileName, ofType: "json")
else {
fatalError("Unable to locate file \(propertiesFileName)")
}
guard let fileContent = try? Data(contentsOf: URL(fileURLWithPath: filePath))
else {
fatalError("Unable to create NSData with file content (YADL Spot Assessment data)")
}
let json = try JSONSerialization.jsonObject(with: fileContent, options: JSONSerialization.ReadingOptions.mutableContainers)
return YADLSpotAssessmentStep.create(identifier: identifier, json: json as AnyObject, itemIdentifiers: itemIdentifiers)
}
public static func create(identifier: String, json: AnyObject, itemIdentifiers: [String]? = nil) -> YADLSpotAssessmentStep? {
guard let completeJSON = json as? [String: AnyObject],
let typeJSON = completeJSON["YADL"] as? [String: AnyObject],
let assessmentJSON = typeJSON["spot"] as? [String: AnyObject],
let itemJSONArray = typeJSON["activities"] as? [AnyObject]
else {
assertionFailure("JSON Parse Error")
return nil
}
let items:[RKXActivityDescriptor] = itemJSONArray.map { (itemJSON: AnyObject) in
guard let itemDictionary = itemJSON as? [String: AnyObject]
else
{
return nil
}
return RKXActivityDescriptor(itemDictionary: itemDictionary)
}.flatMap { $0 }
let imageChoices: [ORKImageChoice] = items
.filter { activity in
if let identifiers = itemIdentifiers {
return identifiers.contains(activity.identifier)
}
else {
return true
}
}
.flatMap(RKXImageDescriptor.imageChoiceForDescriptor())
let assessment = RKXMultipleImageSelectionSurveyDescriptor(assessmentDictionary: assessmentJSON)
let answerFormat = ORKAnswerFormat.choiceAnswerFormat(with: imageChoices)
return YADLSpotAssessmentStep(identifier: identifier, title: assessment.prompt, answerFormat: answerFormat, options: assessment.options)
}
}
| 39.121622 | 147 | 0.627634 |
7104f20b4b5230c1040cfac8094a724680889057 | 168 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(TunesearchMockCoreTests.allTests),
]
}
#endif
| 16.8 | 51 | 0.690476 |
bbdd97074634a5ee5f8e149d36ec6aa69fdd64a6 | 9,198 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// HTTPClientTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension HTTPClientTests {
static var allTests: [(String, (HTTPClientTests) -> () throws -> Void)] {
return [
("testRequestURI", testRequestURI),
("testBadRequestURI", testBadRequestURI),
("testSchemaCasing", testSchemaCasing),
("testURLSocketPathInitializers", testURLSocketPathInitializers),
("testConvenienceExecuteMethods", testConvenienceExecuteMethods),
("testConvenienceExecuteMethodsOverSocket", testConvenienceExecuteMethodsOverSocket),
("testConvenienceExecuteMethodsOverSecureSocket", testConvenienceExecuteMethodsOverSecureSocket),
("testGet", testGet),
("testGetWithDifferentEventLoopBackpressure", testGetWithDifferentEventLoopBackpressure),
("testPost", testPost),
("testGetHttps", testGetHttps),
("testGetHttpsWithIP", testGetHttpsWithIP),
("testGetHTTPSWorksOnMTELGWithIP", testGetHTTPSWorksOnMTELGWithIP),
("testGetHttpsWithIPv6", testGetHttpsWithIPv6),
("testGetHTTPSWorksOnMTELGWithIPv6", testGetHTTPSWorksOnMTELGWithIPv6),
("testPostHttps", testPostHttps),
("testHttpRedirect", testHttpRedirect),
("testHttpHostRedirect", testHttpHostRedirect),
("testPercentEncoded", testPercentEncoded),
("testPercentEncodedBackslash", testPercentEncodedBackslash),
("testMultipleContentLengthHeaders", testMultipleContentLengthHeaders),
("testStreaming", testStreaming),
("testFileDownload", testFileDownload),
("testFileDownloadError", testFileDownloadError),
("testRemoteClose", testRemoteClose),
("testReadTimeout", testReadTimeout),
("testConnectTimeout", testConnectTimeout),
("testDeadline", testDeadline),
("testCancel", testCancel),
("testStressCancel", testStressCancel),
("testHTTPClientAuthorization", testHTTPClientAuthorization),
("testProxyPlaintext", testProxyPlaintext),
("testProxyTLS", testProxyTLS),
("testProxyPlaintextWithCorrectlyAuthorization", testProxyPlaintextWithCorrectlyAuthorization),
("testProxyPlaintextWithIncorrectlyAuthorization", testProxyPlaintextWithIncorrectlyAuthorization),
("testUploadStreaming", testUploadStreaming),
("testEventLoopArgument", testEventLoopArgument),
("testDecompression", testDecompression),
("testDecompressionLimit", testDecompressionLimit),
("testLoopDetectionRedirectLimit", testLoopDetectionRedirectLimit),
("testCountRedirectLimit", testCountRedirectLimit),
("testMultipleConcurrentRequests", testMultipleConcurrentRequests),
("testWorksWith500Error", testWorksWith500Error),
("testWorksWithHTTP10Response", testWorksWithHTTP10Response),
("testWorksWhenServerClosesConnectionAfterReceivingRequest", testWorksWhenServerClosesConnectionAfterReceivingRequest),
("testSubsequentRequestsWorkWithServerSendingConnectionClose", testSubsequentRequestsWorkWithServerSendingConnectionClose),
("testSubsequentRequestsWorkWithServerAlternatingBetweenKeepAliveAndClose", testSubsequentRequestsWorkWithServerAlternatingBetweenKeepAliveAndClose),
("testStressGetHttps", testStressGetHttps),
("testStressGetHttpsSSLError", testStressGetHttpsSSLError),
("testFailingConnectionIsReleased", testFailingConnectionIsReleased),
("testResponseDelayGet", testResponseDelayGet),
("testIdleTimeoutNoReuse", testIdleTimeoutNoReuse),
("testStressGetClose", testStressGetClose),
("testManyConcurrentRequestsWork", testManyConcurrentRequestsWork),
("testRepeatedRequestsWorkWhenServerAlwaysCloses", testRepeatedRequestsWorkWhenServerAlwaysCloses),
("testShutdownBeforeTasksCompletion", testShutdownBeforeTasksCompletion),
("testUncleanShutdownActuallyShutsDown", testUncleanShutdownActuallyShutsDown),
("testUncleanShutdownCancelsTasks", testUncleanShutdownCancelsTasks),
("testDoubleShutdown", testDoubleShutdown),
("testTaskFailsWhenClientIsShutdown", testTaskFailsWhenClientIsShutdown),
("testRaceNewRequestsVsShutdown", testRaceNewRequestsVsShutdown),
("testVaryingLoopPreference", testVaryingLoopPreference),
("testMakeSecondRequestDuringCancelledCallout", testMakeSecondRequestDuringCancelledCallout),
("testMakeSecondRequestDuringSuccessCallout", testMakeSecondRequestDuringSuccessCallout),
("testMakeSecondRequestWhilstFirstIsOngoing", testMakeSecondRequestWhilstFirstIsOngoing),
("testUDSBasic", testUDSBasic),
("testHTTPPlusUNIX", testHTTPPlusUNIX),
("testHTTPSPlusUNIX", testHTTPSPlusUNIX),
("testUseExistingConnectionOnDifferentEL", testUseExistingConnectionOnDifferentEL),
("testWeRecoverFromServerThatClosesTheConnectionOnUs", testWeRecoverFromServerThatClosesTheConnectionOnUs),
("testPoolClosesIdleConnections", testPoolClosesIdleConnections),
("testRacePoolIdleConnectionsAndGet", testRacePoolIdleConnectionsAndGet),
("testAvoidLeakingTLSHandshakeCompletionPromise", testAvoidLeakingTLSHandshakeCompletionPromise),
("testAsyncShutdown", testAsyncShutdown),
("testAsyncShutdownDefaultQueue", testAsyncShutdownDefaultQueue),
("testValidationErrorsAreSurfaced", testValidationErrorsAreSurfaced),
("testUploadsReallyStream", testUploadsReallyStream),
("testUploadStreamingCallinToleratedFromOtsideEL", testUploadStreamingCallinToleratedFromOtsideEL),
("testWeHandleUsSendingACloseHeaderCorrectly", testWeHandleUsSendingACloseHeaderCorrectly),
("testWeHandleUsReceivingACloseHeaderCorrectly", testWeHandleUsReceivingACloseHeaderCorrectly),
("testWeHandleUsSendingACloseHeaderAmongstOtherConnectionHeadersCorrectly", testWeHandleUsSendingACloseHeaderAmongstOtherConnectionHeadersCorrectly),
("testWeHandleUsReceivingACloseHeaderAmongstOtherConnectionHeadersCorrectly", testWeHandleUsReceivingACloseHeaderAmongstOtherConnectionHeadersCorrectly),
("testLoggingCorrectlyAttachesRequestInformation", testLoggingCorrectlyAttachesRequestInformation),
("testNothingIsLoggedAtInfoOrHigher", testNothingIsLoggedAtInfoOrHigher),
("testAllMethodsLog", testAllMethodsLog),
("testClosingIdleConnectionsInPoolLogsInTheBackground", testClosingIdleConnectionsInPoolLogsInTheBackground),
("testUploadStreamingNoLength", testUploadStreamingNoLength),
("testConnectErrorPropagatedToDelegate", testConnectErrorPropagatedToDelegate),
("testDelegateCallinsTolerateRandomEL", testDelegateCallinsTolerateRandomEL),
("testContentLengthTooLongFails", testContentLengthTooLongFails),
("testContentLengthTooShortFails", testContentLengthTooShortFails),
("testBodyUploadAfterEndFails", testBodyUploadAfterEndFails),
("testNoBytesSentOverBodyLimit", testNoBytesSentOverBodyLimit),
("testDoubleError", testDoubleError),
("testSSLHandshakeErrorPropagation", testSSLHandshakeErrorPropagation),
("testSSLHandshakeErrorPropagationDelayedClose", testSSLHandshakeErrorPropagationDelayedClose),
("testWeCloseConnectionsWhenConnectionCloseSetByServer", testWeCloseConnectionsWhenConnectionCloseSetByServer),
("testBiDirectionalStreaming", testBiDirectionalStreaming),
("testSynchronousHandshakeErrorReporting", testSynchronousHandshakeErrorReporting),
("testFileDownloadChunked", testFileDownloadChunked),
("testCloseWhileBackpressureIsExertedIsFine", testCloseWhileBackpressureIsExertedIsFine),
("testErrorAfterCloseWhileBackpressureExerted", testErrorAfterCloseWhileBackpressureExerted),
("testRequestSpecificTLS", testRequestSpecificTLS),
("testConnectionPoolSizeConfigValueIsRespected", testConnectionPoolSizeConfigValueIsRespected),
("testRequestWithHeaderTransferEncodingIdentityDoesNotFail", testRequestWithHeaderTransferEncodingIdentityDoesNotFail),
]
}
}
| 67.632353 | 165 | 0.731246 |
ff5d3c3db10751c345b378e4a57f2f364ab71e3d | 23,103 | //
// PetAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class PetAPI {
/**
Add a new pet to the store
- parameter body: (body) Pet object that needs to be added to the store
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? {
return addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Add a new pet to the store
- POST /pet
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> {
let localVariablePath = "/pet"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Deletes a pet
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? {
return deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Deletes a pet
- DELETE /pet/{petId}
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- returns: RequestBuilder<Void>
*/
open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder<Void> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"api_key": apiKey?.encodeToJSON(),
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
* enum for parameter status
*/
public enum Status_findPetsByStatus: String, CaseIterable {
case available = "available"
case pending = "pending"
case sold = "sold"
}
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], ErrorResponse>) -> Void)) -> URLSessionTask? {
return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(.success(response.body))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Finds Pets by status
- GET /pet/findByStatus
- Multiple status values can be provided with comma separated strings
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter status: (query) Status values that need to be considered for filter
- returns: RequestBuilder<[Pet]>
*/
open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> {
let localVariablePath = "/pet/findByStatus"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"status": status.encodeToJSON(),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Finds Pets by tags
- parameter tags: (query) Tags to filter by
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@available(*, deprecated, message: "This operation is deprecated.")
@discardableResult
open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], ErrorResponse>) -> Void)) -> URLSessionTask? {
return findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(.success(response.body))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Finds Pets by tags
- GET /pet/findByTags
- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter tags: (query) Tags to filter by
- returns: RequestBuilder<[Pet]>
*/
@available(*, deprecated, message: "This operation is deprecated.")
open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> {
let localVariablePath = "/pet/findByTags"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"tags": tags.encodeToJSON(),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Find pet by ID
- parameter petId: (path) ID of pet to return
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Pet, ErrorResponse>) -> Void)) -> URLSessionTask? {
return getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(.success(response.body))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Find pet by ID
- GET /pet/{petId}
- Returns a single pet
- API Key:
- type: apiKey api_key
- name: api_key
- parameter petId: (path) ID of pet to return
- returns: RequestBuilder<Pet>
*/
open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder<Pet> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Update an existing pet
- parameter body: (body) Pet object that needs to be added to the store
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? {
return updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Update an existing pet
- PUT /pet
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> {
let localVariablePath = "/pet"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Updates a pet in the store with form data
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? {
return updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
Updates a pet in the store with form data
- POST /pet/{petId}
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- returns: RequestBuilder<Void>
*/
open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"name": name?.encodeToJSON(),
"status": status?.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/x-www-form-urlencoded",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
uploads an image
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<ApiResponse, ErrorResponse>) -> Void)) -> URLSessionTask? {
return uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(.success(response.body))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
uploads an image
- POST /pet/{petId}/uploadImage
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- returns: RequestBuilder<ApiResponse>
*/
open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder<ApiResponse> {
var localVariablePath = "/pet/{petId}/uploadImage"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"additionalMetadata": additionalMetadata?.encodeToJSON(),
"file": file?.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "multipart/form-data",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
uploads an image (required)
- parameter petId: (path) ID of pet to update
- parameter requiredFile: (form) file to upload
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
@discardableResult
open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<ApiResponse, ErrorResponse>) -> Void)) -> URLSessionTask? {
return uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(.success(response.body))
case let .failure(error):
completion(.failure(error))
}
}
}
/**
uploads an image (required)
- POST /fake/{petId}/uploadImageWithRequiredFile
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet to update
- parameter requiredFile: (form) file to upload
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- returns: RequestBuilder<ApiResponse>
*/
open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder<ApiResponse> {
var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"additionalMetadata": additionalMetadata?.encodeToJSON(),
"requiredFile": requiredFile.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "multipart/form-data",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
}
| 46.578629 | 291 | 0.694325 |
fb065b1172dafb5025958e515078844a6b1c9b8a | 4,771 | //
// SFCategory.swift
//
//
// Created by Richard Witherspoon on 11/15/21.
//
import Foundation
public struct SFCategory: Identifiable, Codable, Equatable, Hashable{
public let icon: String
public let title: String
enum CodingKeys: String, CodingKey {
case icon
case title = "key"
}
public var id: String{
title
}
public var symbols: [SFSymbol]{
if self == .all{
return SFSymbol.allSymbols
} else {
return SFSymbol.allSymbols.filter({$0.categories?.contains(self) ?? false})
}
}
public var plistTitle: String{
switch self{
case .all:
return "all"
case .whatsnew:
return "whatsnew"
case .multicolor:
return "multicolor"
case .communication:
return "communication"
case .weather:
return "weather"
case .objectsandtools:
return "objectsandtools"
case .devices:
return "devices"
case .gaming:
return "gaming"
case .connectivity:
return "connectivity"
case .transportation:
return "transportation"
case .human:
return "human"
case .nature:
return "nature"
case .editing:
return "editing"
case .textformatting:
return "textformatting"
case .media:
return "media"
case .keyboard:
return "keyboard"
case .commerce:
return "commerce"
case .time:
return "time"
case .health:
return "health"
case .shapes:
return "shapes"
case .arrows:
return "arrows"
case .indices:
return "indices"
case .math:
return "math"
default:
fatalError("The should always be an plistTitle")
}
}
//MARK: Static Data
public static let all = SFCategory(icon: "square.grid.2x2", title: "All")
public static let whatsnew = SFCategory(icon: "sparkles", title: "What's New")
public static let multicolor = SFCategory(icon: "eyedropper", title: "Multicolor")
public static let communication = SFCategory(icon: "message", title: "Communication")
public static let weather = SFCategory(icon: "cloud.sun", title: "Weather")
public static let objectsandtools = SFCategory(icon: "folder", title: "Objects & Tools")
public static let devices = SFCategory(icon: "desktopcomputer", title: "Devices")
public static let gaming = SFCategory(icon: "gamecontroller", title: "Gaming")
public static let connectivity = SFCategory(icon: "antenna.radiowaves.left.and.right", title: "Connectivity")
public static let transportation = SFCategory(icon: "car.fill", title: "Transportation")
public static let human = SFCategory(icon: "person.crop.circle", title: "Human")
public static let nature = SFCategory(icon: "flame", title: "Nature")
public static let editing = SFCategory(icon: "slider.horizontal.3", title: "Editing")
public static let textformatting = SFCategory(icon: "textformat.size.smaller", title: "Text Formatting")
public static let media = SFCategory(icon: "playpause", title: "Media")
public static let keyboard = SFCategory(icon: "command", title: "Keyboard")
public static let commerce = SFCategory(icon: "cart", title: "Commerce")
public static let time = SFCategory(icon: "timer", title: "Time")
public static let health = SFCategory(icon: "staroflife", title: "Health")
public static let shapes = SFCategory(icon: "square.on.circle", title: "Shapes")
public static let arrows = SFCategory(icon: "arrow.right", title: "Arrows")
public static let indices = SFCategory(icon: "a.circle", title: "Indices")
public static let math = SFCategory(icon: "x.squareroot", title: "Math")
public static var allCategories: [SFCategory]{
return [
.all,
.whatsnew,
.multicolor,
.communication,
.weather,
.objectsandtools,
.devices,
.gaming,
.connectivity,
.transportation,
.human,
.nature,
.editing,
.textformatting,
.media,
.keyboard,
.commerce,
.time,
.health,
.shapes,
.arrows,
.indices,
.math,
]
}
}
| 33.598592 | 116 | 0.557326 |
9babe3849a5812dc7eb673169ccdfc62fe4d2304 | 846 | //
// SectionHeader.swift
// SideslipTable
//
// Created by Tory on 2021/4/28.
//
import UIKit
class SectionHeader: UICollectionReusableView {
static var headerId = "SectionHeaderId"
lazy var titleLabel: UILabel = {
let label = UILabel()
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUi()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setupTitle(_ title: String) {
self.titleLabel.text = title
}
private func setupUi() {
self.backgroundColor = .white
self.addSubview(self.titleLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.frame = self.bounds
}
}
| 20.142857 | 59 | 0.595745 |
ac932a51da28fa5e9dca77492f57e312c15feb05 | 2,168 | //
// CustomTabbarController.swift
// ProjectSwift
//
// Created by ZJQ on 2016/12/22.
// Copyright © 2016年 ZJQ. All rights reserved.
//
import UIKit
class CustomTabbarController: TabbarViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupSubViews()
}
func setupSubViews() -> Void {
let firstVC = RecommendViewController()
let secondVC = ProgrameViewController()
let thirdVC = LiveViewController()
let fourVC = MineViewController()
/**
* 添加tabbar的主控制器
*
* @param firstVC 子控制器
* @param "first" 标题
* @param "first" 普通状态的图片
* @param "first_select" 选中状态的图片
* @param TabbarHideStyle.TabbarHideWithAnimation 当push到下一界面tabbar的隐藏方式
*/
self.setupChildVC(firstVC, title: "推荐", imageName: "btn_home_normal", selectImageName: "btn_home_selected", isAnimation: TabbarHideStyle.tabbarHideWithNoAnimation)
self.setupChildVC(secondVC, title: "栏目", imageName: "btn_column_normal", selectImageName: "btn_column_selected", isAnimation: TabbarHideStyle.tabbarHideWithNoAnimation)
self.setupChildVC(thirdVC, title: "直播", imageName: "btn_live_normal", selectImageName: "btn_live_selected", isAnimation: TabbarHideStyle.tabbarHideWithNoAnimation)
self.setupChildVC(fourVC, title: "我的", imageName: "btn_user_normal", selectImageName: "btn_user_selected", isAnimation: TabbarHideStyle.tabbarHideWithNoAnimation)
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 36.745763 | 176 | 0.644834 |
dbe8438b298844a25e6077ffede05abf168543fb | 24,190 | //
// Request.swift
//
// Copyright (c) 2014 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 Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
public protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
open class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
open var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
public let session: URLSession
/// The request sent or to be sent to the server.
open var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
open internal(set) var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
open func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
open func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
open func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
open func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
open var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
open var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -v"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(
host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = delegate.credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
#if swift(>=3.2)
components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
#else
components.append("-b \"\(string.substring(to: string.index(before: string.endIndex)))\"")
#endif
}
}
var headers: [AnyHashable: Any] = [:]
session.configuration.httpAdditionalHeaders?.filter { $0.0 != AnyHashable("Cookie") }
.forEach { headers[$0.0] = $0.1 }
request.allHTTPHeaderFields?.filter { $0.0 != "Cookie" }
.forEach { headers[$0.0] = $0.1 }
components += headers.map {
let escapedValue = String(describing: $0.value).replacingOccurrences(of: "\"", with: "\\\"")
return "-H \"\($0.key): \(escapedValue)\""
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
open class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.sync { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let requestable = originalTask as? Requestable { return requestable.urlRequest }
return nil
}
/// The progress of fetching the response data from the server for the request.
open var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
open func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
open class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
public struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
public let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.sync { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
return urlRequest
}
return nil
}
/// The resume data of the underlying download task if available after a failure.
open var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
open var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
open override func cancel() {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
open class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
guard let uploadable = originalTask as? Uploadable else { return nil }
switch uploadable {
case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
return urlRequest
}
}
/// The progress of uploading the payload to the server for the upload request.
open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.sync { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
| 37.215385 | 131 | 0.640967 |
7a80ee2f288d1638116fe032e4763836c1f1647e | 2,153 | //
// URLSession+extensions.swift
// ParseSwift
//
// Original file, URLSession+sync.swift, created by Florent Vilmart on 17-09-24.
// Name change to URLSession+extensions.swift and support for sync/async by Corey Baker on 7/25/20.
// Copyright © 2020 Parse Community. All rights reserved.
//
import Foundation
extension URLSession {
internal func dataTask<U>(
with request: URLRequest,
callbackQueue: DispatchQueue?,
mapper: @escaping (Data) throws -> U,
completion: @escaping(Result<U, ParseError>) -> Void
) {
print("request \(request)")
func makeResult(responseData: Data?, urlResponse: URLResponse?,
responseError: Error?) -> Result<U, ParseError> {
if let responseData = responseData {
do {
let mapped = try mapper(responseData)
return try .success(mapper(responseData))
} catch {
if let str = String(data: responseData, encoding: .utf8) {
print("failed for \(str)")
}
let parseError = try? ParseCoding.jsonDecoder().decode(ParseError.self, from: responseData)
return .failure(parseError ?? ParseError(code: .unknownError, message: "cannot decode error"))
}
} else if let responseError = responseError {
return .failure(ParseError(code: .unknownError, message: "Unable to sync: \(responseError)"))
} else {
return .failure(ParseError(code: .unknownError,
message: "Unable to sync: \(String(describing: urlResponse))."))
}
}
dataTask(with: request) { (responseData, urlResponse, responseError) in
let result = makeResult(responseData: responseData, urlResponse: urlResponse, responseError: responseError)
if let callbackQueue = callbackQueue {
callbackQueue.async { completion(result) }
} else {
completion(result)
}
}.resume()
}
}
| 38.446429 | 119 | 0.572225 |
eb072197878c593f9debd7bf66786549a9dc547c | 1,272 | //
// RRFreeShadowdocksUITests.swift
// RRFreeShadowdocksUITests
//
// Created by Remi Robert on 22/11/15.
// Copyright © 2015 Remi Robert. All rights reserved.
//
import XCTest
class RRFreeShadowdocksUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.378378 | 182 | 0.669811 |
ab5f0ac7e256bedb209de676ec3fa1669e2c6130 | 5,033 | //
// RxViewModel.swift
// RxViewModel
//
// Created by Esteban Torres on 7/14/15.
// Copyright (c) 2015 Esteban Torres. All rights reserved.
//
// Native Frameworks
import Foundation
// Dependencies
import RxSwift
/**
Implements behaviors that drive the UI, and/or adapts a domain model to be
user-presentable.
*/
open class RxViewModel: NSObject {
// MARK: Constants
let throttleTime: DispatchTimeInterval = .seconds(2)
// MARK: Properties
/// Scope dispose to avoid leaking
public private(set) var disposeBag = DisposeBag()
/// Underlying variable that we'll listen to for changes
@objc private dynamic var _active: Bool = false
/// Public «active» variable
@objc public dynamic var active: Bool {
get { return _active }
set {
// Skip KVO notifications when the property hasn't actually changed. This is
// especially important because self.active can have very expensive
// observers attached.
if newValue == _active { return }
_active = newValue
self.activeObservable.on(.next(_active))
}
}
// Private
private lazy var activeObservable: BehaviorSubject<Bool?> = {
let ao = BehaviorSubject(value: Bool?(self.active))
return ao
}()
// MARK: Life cycle
/**
Initializes a `RxViewModel` a attaches to observe changes in the `active` flag.
*/
public override init() {
super.init()
}
/**
Rx `Observable` for the `active` flag. (when it becomes `true`).
Will send messages only to *new* & *different* values.
*/
public lazy var didBecomeActive: Observable<RxViewModel> = { [unowned self] in
return self.activeObservable
.filter { $0 == true }
.map { _ in return self }
}()
/**
Rx `Observable` for the `active` flag. (when it becomes `false`).
Will send messages only to *new* & *different* values.
*/
public lazy var didBecomeInactive: Observable<RxViewModel> = { [unowned self] in
return self.activeObservable
.filter { $0 == false }
.map { _ in return self }
}()
/**
Subscribes (or resubscribes) to the given signal whenever
`didBecomeActiveSignal` fires.
When `didBecomeInactiveSignal` fires, any active subscription to `signal` is
disposed.
Returns a signal which forwards `next`s from the latest subscription to
`signal`, and completes when the receiver is deallocated. If `signal` sends
an error at any point, the returned signal will error out as well.
*/
public func forwardSignalWhileActive<T>(_ observable: Observable<T>) -> Observable<T> {
let signal = self.activeObservable
return Observable.create { (obs: AnyObserver<T>) -> Disposable in
let disposable = CompositeDisposable()
var signalDisposable: Disposable? = nil
var disposeKey: CompositeDisposable.DisposeKey?
let activeDisposable = signal.subscribe( onNext: { active in
if active == true {
signalDisposable = observable.subscribe( onNext: { value in
obs.on(.next(value))
}, onError: { error in
obs.on(.error(error))
}, onCompleted: {})
if let sd = signalDisposable { disposeKey = disposable.insert(sd) }
} else {
if let sd = signalDisposable {
sd.dispose()
if let dk = disposeKey {
disposable.remove(for: dk)
}
}
}
}, onError: { error in
obs.on(.error(error))
}, onCompleted: {
obs.on(.completed)
})
_ = disposable.insert(activeDisposable)
return disposable
}
}
/**
Throttles events on the given `observable` while the receiver is inactive.
Unlike `forwardSignalWhileActive:`, this method will stay subscribed to
`observable` the entire time, except that its events will be throttled when the
receiver becomes inactive.
- parameter observable: The `Observable` to which this method will stay
subscribed the entire time.
- returns: Returns an `observable` which forwards events from `observable` (throttled while the
receiver is inactive), and completes when `observable` completes or the receiver
is deallocated.
*/
public func throttleSignalWhileInactive<T>(_ observable: Observable<T>) -> Observable<T> {
let result = ReplaySubject<T>.create(bufferSize: 1)
let activeSignal = self.activeObservable.takeUntil(Observable.create { (_: AnyObserver<T>) -> Disposable in
observable.subscribe(onCompleted: {
defer { result.dispose() }
result.on(.completed)
})
})
_ = Observable.combineLatest(activeSignal, observable) { (active, obs) -> (Bool?, T) in (active, obs) }
.throttle(throttleTime) { (active: Bool?, _: T) -> Bool in
return active == false
}.subscribe(onNext: { (value: (Bool?, T)) in
result.on(.next(value.1))
}, onError: { _ in }, onCompleted: {
result.on(.completed)
})
return result
}
}
| 30.137725 | 111 | 0.644149 |
d53b9ad9747be3560cacb44626add281b1b11b9e | 4,291 | //
// BlockedUsersViewController.swift
// ChatCampUIKit
//
// Created by Saurabh Gupta on 04/09/18.
// Copyright © 2018 chatcamp. All rights reserved.
//
import UIKit
import ChatCamp
import SDWebImage
import MBProgressHUD
open class BlockedUsersViewController: UIViewController {
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView?.register(UINib(nibName: String(describing: ChatTableViewCell.self), bundle: Bundle(for: ChatTableViewCell.self)), forCellReuseIdentifier: ChatTableViewCell.identifier) }
}
var users: [CCPUser] = []
fileprivate var usersToFetch: Int = 20
fileprivate var loadingUsers = false
var usersQuery: CCPUserListQuery!
override open func viewDidLoad() {
super.viewDidLoad()
title = "Blocked Users"
usersQuery = CCPClient.createBlockedUserListQuery()
loadUsers(limit: usersToFetch)
}
fileprivate func loadUsers(limit: Int) {
let progressHud = MBProgressHUD.showAdded(to: self.view, animated: true)
progressHud.label.text = "Loading..."
progressHud.contentColor = .black
loadingUsers = true
usersQuery.load(limit: limit) { [unowned self] (users, error) in
progressHud.hide(animated: true)
if error == nil {
guard let users = users else { return }
self.users.append(contentsOf: users.filter({ $0.getId() != CCPClient.getCurrentUser().getId() }))
DispatchQueue.main.async {
self.tableView.reloadData()
self.loadingUsers = false
}
} else {
DispatchQueue.main.async {
self.showAlert(title: "Can't Load Users", message: "Unable to load Users right now. Please try later.", actionText: "Ok")
self.loadingUsers = false
}
}
}
}
}
// MARK:- UITableViewDataSource
extension BlockedUsersViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ChatTableViewCell.string(), for: indexPath) as! ChatTableViewCell
cell.nameLabel.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
let user = users[indexPath.row]
cell.nameLabel.text = user.getDisplayName()
cell.messageLabel.text = ""
cell.accessoryLabel.text = "Unblock"
cell.unreadCountLabel.isHidden = true
if let avatarUrl = user.getAvatarUrl() {
cell.avatarImageView?.sd_setImage(with: URL(string: avatarUrl), completed: nil)
} else {
cell.avatarImageView.setImageForName(string: user.getDisplayName() ?? "?", circular: true, textAttributes: nil)
}
return cell
}
}
// MARK:- UITableViewDelegate
extension BlockedUsersViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = users[indexPath.row]
let progressHud = MBProgressHUD.showAdded(to: self.view, animated: true)
CCPClient.unblockUser(userId: user.getId()) { (participant, error) in
progressHud.hide(animated: true)
if error == nil {
self.users.remove(at: indexPath.row)
tableView.reloadData()
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK:- ScrollView Delegate Methods
extension BlockedUsersViewController {
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if (tableView.indexPathsForVisibleRows?.contains([0, users.count - 1]) ?? false) && !loadingUsers && users.count >= (usersToFetch - 1) {
loadUsers(limit: usersToFetch)
}
}
}
| 37.640351 | 199 | 0.638546 |
75ad46d63d0e3e0ec0a197a4186a4318e1cf7bed | 13,351 | //
// UZGPUBroadcastViewController.swift
// UZBroadcast
//
// Created by Nam Kennic on 12/11/21.
// Copyright © 2021 Uiza. All rights reserved.
//
import UIKit
import HaishinKit
import GPUImage
open class UZGPUBroadcastViewController: UIViewController {
/// Current broadcastURL
public private(set) var broadcastURL: URL?
/// Current streamKey
public private(set) var streamKey: String?
/// Set active camera
public var cameraPosition: UZCameraPosition {
get { camera?.cameraPosition().asUZCamerraPosition() ?? .front }
}
/// Toggle torch mode
public var torch: Bool {
get { rtmpStream.torch }
set { rtmpStream.torch = newValue }
}
/// Toggle mirror mode, only apply to front camera
public var isMirror: Bool {
get { camera?.horizontallyMirrorFrontFacingCamera ?? false }
set { camera?.horizontallyMirrorFrontFacingCamera = newValue }
}
/// Toggle auto focus, only apply to back camera
public var isAutoFocus: Bool {
get { (rtmpStream.captureSettings[.continuousAutofocus] as? Bool) ?? false }
set { rtmpStream.captureSettings[.continuousAutofocus] = newValue }
}
/// Toggle auto exposure, only apply to back camera
public var isAutoExposure: Bool {
get { (rtmpStream.captureSettings[.continuousExposure] as? Bool) ?? false }
set { rtmpStream.captureSettings[.continuousExposure] = newValue }
}
/// Toggle audio mute
public var isMuted: Bool {
get { (rtmpStream.audioSettings[.muted] as? Bool) ?? false }
set { rtmpStream.audioSettings[.muted] = newValue }
}
/// Pause or unpause streaming
public var isPaused: Bool {
get { rtmpStream.paused }
set { rtmpStream.paused = newValue }
}
/// Video Bitrate
public var videoBitrate: UInt32? {
get { rtmpStream.videoSettings[.bitrate] as? UInt32 }
set {
rtmpStream.videoSettings[.bitrate] = newValue
if let value = newValue, minVideoBitrate == nil { minVideoBitrate = value / 8 }
}
}
/// Minimum Video Bitrate (is used when `adaptiveBitrate` is `true`)
public var minVideoBitrate: UInt32?
/// Video FPS settings. To get actual FPS, use currentFPS
public var videoFPS: Int32? {
get { camera?.frameRate }
set {
if let value = newValue {
camera?.frameRate = value
}
}
}
/// Current FPS of the stream
public var currentFPS: UInt16 {
get { rtmpStream.currentFPS }
}
/// Audio Bitrate
public var audioBitrate: UInt32? {
get { rtmpStream.audioSettings[.bitrate] as? UInt32 }
set { rtmpStream.audioSettings[.bitrate] = newValue }
}
/// Audio SampleRate
public var audioSampleRate: UInt32? {
get { rtmpStream.audioSettings[.sampleRate] as? UInt32 }
set { rtmpStream.audioSettings[.sampleRate] = newValue }
}
/// `true` if broadcasting
public fileprivate(set)var isBroadcasting = false
/// Current broadcast configuration
public fileprivate(set) var config: UZBroadcastConfig! {
didSet {
videoBitrate = config.videoBitrate.value()
videoFPS = Int32(config.videoFPS.rawValue)
audioBitrate = config.audioBitrate.rawValue
audioSampleRate = config.audioSampleRate.rawValue
// cameraPosition = config.cameraPosition
if let orientation = DeviceUtil.videoOrientation(by: UIApplication.shared.statusBarOrientation) {
rtmpStream.orientation = orientation
}
rtmpStream.captureSettings = [
.sessionPreset: config.videoResolution.sessionPreset,
.continuousAutofocus: true,
.continuousExposure: true
// .preferredVideoStabilizationMode: AVCaptureVideoStabilizationMode.auto
]
rtmpStream.videoSettings = [
.width: config.videoResolution.videoSize.width,
.height: config.videoResolution.videoSize.height,
.scalingMode: ScalingMode.normal
]
}
}
private var rtmpConnection = RTMPConnection()
internal lazy var rtmpStream = RTMPStream(connection: rtmpConnection)
public let outputView = GPUImageView()
public internal(set) var camera: GPUImageVideoCamera?
public let filter = GPUImageBeautyFilter()
// MARK: -
@discardableResult
open func requestCameraAccess() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch status {
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted) in
if granted {
if let url = self.broadcastURL, let key = self.streamKey {
self.startBroadcast(broadcastURL: url, streamKey: key)
}
}
})
case AVAuthorizationStatus.authorized: return true
case AVAuthorizationStatus.denied: break
case AVAuthorizationStatus.restricted: break
@unknown default:break
}
return false
}
@discardableResult
open func requestMicrophoneAccess() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
switch status {
case AVAuthorizationStatus.notDetermined: AVCaptureDevice.requestAccess(for: AVMediaType.audio, completionHandler: { granted in
if granted {
if let url = self.broadcastURL, let key = self.streamKey {
self.startBroadcast(broadcastURL: url, streamKey: key)
}
}
})
case AVAuthorizationStatus.authorized: return true
case AVAuthorizationStatus.denied: break
case AVAuthorizationStatus.restricted: break
@unknown default: break
}
return false
}
/**
Always call this function first to prepare broadcasting with configuration
- parameter config: Broadcast configuration
*/
@discardableResult
open func prepareForBroadcast(config: UZBroadcastConfig) -> RTMPStream {
self.config = config
return rtmpStream
}
/**
Start broadcasting
- parameter broadcastURL: `URL` of broadcast
- parameter streamKey: Stream Key
*/
open func startBroadcast(broadcastURL: URL, streamKey: String) {
guard isBroadcasting == false else { return }
self.broadcastURL = broadcastURL
self.streamKey = streamKey
if requestCameraAccess() && requestMicrophoneAccess() {
startStream()
}
}
private func startStream() {
rtmpStream.delegate = self
rtmpStream.attachAudio(AVCaptureDevice.default(for: .audio)) { error in
print(error)
}
camera = GPUImageVideoCamera(sessionPreset: self.config.videoResolution.sessionPreset.rawValue, cameraPosition: config.cameraPosition.value())
camera?.horizontallyMirrorFrontFacingCamera = true
camera?.outputImageOrientation = .portrait
camera?.addTarget(filter)
rtmpStream.attachGPUImageVideoCamera(camera!)
filter.addTarget(outputView)
filter.addTarget(rtmpStream.rawDataOutput)
// rtmpStream.addObserver(self, forKeyPath: "currentFPS", options: .new, context: nil)
DispatchQueue.main.async {
self.camera?.startCapture()
}
openConnection()
}
private func openConnection() {
guard broadcastURL != nil, streamKey != nil else { return }
isBroadcasting = true
DispatchQueue.main.async {
UIApplication.shared.isIdleTimerDisabled = true
}
rtmpConnection.addEventListener(.rtmpStatus, selector: #selector(rtmpStatusHandler), observer: self)
rtmpConnection.addEventListener(.ioError, selector: #selector(rtmpErrorHandler), observer: self)
rtmpConnection.connect(broadcastURL!.absoluteString)
}
private func closeConnection() {
rtmpConnection.close()
rtmpConnection.removeEventListener(.rtmpStatus, selector: #selector(rtmpStatusHandler), observer: self)
rtmpConnection.removeEventListener(.ioError, selector: #selector(rtmpErrorHandler), observer: self)
}
/**
Stop broadcasting
*/
open func stopBroadcast() {
closeConnection()
isBroadcasting = false
DispatchQueue.main.async {
UIApplication.shared.isIdleTimerDisabled = false
}
}
/**
Switch camera front <> back
*/
public func switchCamera() {
camera?.rotateCamera()
}
// MARK: -
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
view.addSubview(outputView)
NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// rtmpStream.removeObserver(self, forKeyPath: "currentFPS")
rtmpStream.close()
rtmpStream.dispose()
camera?.stopCapture()
UIApplication.shared.isIdleTimerDisabled = false
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if requestCameraAccess() == false { print("[UZBroadcaster] Camera permission is not granted. Please turn it on in Settings. Implement your own permission check to handle this case.") }
if requestMicrophoneAccess() == false { print("[UZBroadcaster] Microphone permission is not granted. Please turn it on in Settings. Implement your own permission check to handle this case.") }
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
outputView.frame = view.bounds
}
// MARK: - StatusBar & Rotation Handler
open override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
open override var shouldAutorotate: Bool {
return config.autoRotate
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return config.autoRotate == true ? .all : (UIDevice.current.userInterfaceIdiom == .phone ? .portrait : .all)
}
open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIDevice.current.userInterfaceIdiom == .pad ? UIApplication.shared.interfaceOrientation ?? .portrait : .portrait
}
// MARK: - Events
var retryCount = 0
var maxRetryCount = 5
@objc private func rtmpStatusHandler(_ notification: Notification) {
let e = Event.from(notification)
guard let data: ASObject = e.data as? ASObject, let code: String = data["code"] as? String else { return }
print("status: \(e)")
switch code {
case RTMPConnection.Code.connectSuccess.rawValue:
retryCount = 0
rtmpStream.publish(streamKey!, type: config.saveToLocal == true ? .localRecord : .live)
case RTMPConnection.Code.connectFailed.rawValue, RTMPConnection.Code.connectClosed.rawValue:
guard retryCount <= maxRetryCount else { return }
Thread.sleep(forTimeInterval: pow(2.0, Double(retryCount)))
rtmpConnection.connect(broadcastURL!.absoluteString)
retryCount += 1
default: break
}
}
@objc private func rtmpErrorHandler(_ notification: Notification) {
print("Error: \(notification)")
}
@objc private func onOrientationChanged(_ notification: Notification) {
guard let orientation = DeviceUtil.videoOrientation(by: UIApplication.shared.statusBarOrientation) else { return }
rtmpStream.orientation = orientation
camera?.outputImageOrientation = UIApplication.shared.statusBarOrientation
if orientation == .landscapeLeft || orientation == .landscapeRight {
rtmpStream.videoSettings = [
.width: config.videoResolution.videoSize.height,
.height: config.videoResolution.videoSize.width,
]
}
else {
rtmpStream.videoSettings = [
.width: config.videoResolution.videoSize.width,
.height: config.videoResolution.videoSize.height,
]
}
}
@objc private func didEnterBackground(_ notification: Notification) {
rtmpStream.receiveVideo = false
}
@objc private func didBecomeActive(_ notification: Notification) {
rtmpStream.receiveVideo = true
}
// open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
// if Thread.isMainThread {
// print("currentFPS: \(rtmpStream.currentFPS)")
// }
// }
func tapScreen(_ gesture: UIGestureRecognizer) {
guard let gestureView = gesture.view, gesture.state == .ended else { return }
let touchPoint = gesture.location(in: gestureView)
let pointOfInterest = CGPoint(x: touchPoint.x / gestureView.bounds.size.width, y: touchPoint.y / gestureView.bounds.size.height)
print("pointOfInterest: \(pointOfInterest)")
rtmpStream.setPointOfInterest(pointOfInterest, exposure: pointOfInterest)
}
// MARK: -
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension UZGPUBroadcastViewController: RTMPStreamDelegate {
open func rtmpStream(_ stream: RTMPStream, didPublishInsufficientBW connection: RTMPConnection) {
guard config.adaptiveBitrate, let currentBitrate = rtmpStream.videoSettings[.bitrate] as? UInt32 else { return }
let value = max(minVideoBitrate ?? currentBitrate, currentBitrate / 2)
guard value != currentBitrate else { return }
stream.videoSettings[.bitrate] = value
print("bitRate decreased: \(value)kps")
}
open func rtmpStream(_ stream: RTMPStream, didPublishSufficientBW connection: RTMPConnection) {
guard config.adaptiveBitrate, let currentBitrate = rtmpStream.videoSettings[.bitrate] as? UInt32 else { return }
let value = min(videoBitrate ?? currentBitrate, currentBitrate * 2)
guard value != currentBitrate else { return }
stream.videoSettings[.bitrate] = value
print("bitRate increased: \(value)kps")
}
open func rtmpStreamDidClear(_ stream: RTMPStream) {
}
}
| 32.563415 | 194 | 0.743615 |
4636273328d883ae88835f68d78ab56a6d85fd1e | 15,745 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Commands
import PackageGraph
import PackageLoading
import PackageModel
import SPMBuildCore
import SPMTestSupport
import TSCBasic
import TSCUtility
import Workspace
import XCTest
struct BuildResult {
let binPath: AbsolutePath
let output: String
let binContents: [String]
}
final class BuildToolTests: XCTestCase {
@discardableResult
private func execute(
_ args: [String],
environment: [String : String]? = nil,
packagePath: AbsolutePath? = nil
) throws -> (stdout: String, stderr: String) {
return try SwiftPMProduct.SwiftBuild.execute(args, packagePath: packagePath, env: environment)
}
func build(_ args: [String], packagePath: AbsolutePath? = nil) throws -> BuildResult {
let (output, _) = try execute(args, packagePath: packagePath)
defer { try! SwiftPMProduct.SwiftPackage.execute(["clean"], packagePath: packagePath) }
let (binPathOutput, _) = try execute(["--show-bin-path"], packagePath: packagePath)
let binPath = AbsolutePath(binPathOutput.trimmingCharacters(in: .whitespacesAndNewlines))
let binContents = try localFileSystem.getDirectoryContents(binPath)
return BuildResult(binPath: binPath, output: output, binContents: binContents)
}
func testUsage() throws {
let stdout = try execute(["-help"]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift build"))
}
func testSeeAlso() throws {
let stdout = try execute(["--help"]).stdout
XCTAssertMatch(stdout, .contains("SEE ALSO: swift run, swift package, swift test"))
}
func testVersion() throws {
let stdout = try execute(["--version"]).stdout
XCTAssertMatch(stdout, .contains("Swift Package Manager"))
}
func testCreatingSanitizers() throws {
for sanitizer in Sanitizer.allCases {
XCTAssertEqual(sanitizer, try Sanitizer(argument: sanitizer.shortName))
}
}
func testInvalidSanitizer() throws {
do {
_ = try Sanitizer(argument: "invalid")
XCTFail("Should have failed to create Sanitizer")
} catch let error as StringError {
XCTAssertEqual(error.description, "valid sanitizers: address, thread, undefined, scudo")
}
}
func testBinPathAndSymlink() throws {
fixture(name: "ValidLayouts/SingleModule/ExecutableNew") { path in
let fullPath = resolveSymlinks(path)
let targetPath = fullPath.appending(components: ".build", UserToolchain.default.triple.tripleString)
let xcbuildTargetPath = fullPath.appending(components: ".build", "apple")
XCTAssertEqual(try execute(["--show-bin-path"], packagePath: fullPath).stdout,
"\(targetPath.appending(component: "debug").pathString)\n")
XCTAssertEqual(try execute(["-c", "release", "--show-bin-path"], packagePath: fullPath).stdout,
"\(targetPath.appending(component: "release").pathString)\n")
// Print correct path when building with XCBuild.
let xcodeDebugOutput = try execute(["--build-system", "xcode", "--show-bin-path"], packagePath: fullPath).stdout
let xcodeReleaseOutput = try execute(["--build-system", "xcode", "-c", "release", "--show-bin-path"], packagePath: fullPath).stdout
#if os(macOS)
XCTAssertEqual(xcodeDebugOutput, "\(xcbuildTargetPath.appending(components: "Products", "Debug").pathString)\n")
XCTAssertEqual(xcodeReleaseOutput, "\(xcbuildTargetPath.appending(components: "Products", "Release").pathString)\n")
#else
XCTAssertEqual(xcodeDebugOutput, "\(targetPath.appending(component: "debug").pathString)\n")
XCTAssertEqual(xcodeReleaseOutput, "\(targetPath.appending(component: "release").pathString)\n")
#endif
// Test symlink.
_ = try execute([], packagePath: fullPath)
XCTAssertEqual(resolveSymlinks(fullPath.appending(components: ".build", "debug")),
targetPath.appending(component: "debug"))
_ = try execute(["-c", "release"], packagePath: fullPath)
XCTAssertEqual(resolveSymlinks(fullPath.appending(components: ".build", "release")),
targetPath.appending(component: "release"))
}
}
func testProductAndTarget() throws {
fixture(name: "Miscellaneous/MultipleExecutables") { path in
let fullPath = resolveSymlinks(path)
do {
let result = try build(["--product", "exec1"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["exec1"])
XCTAssertNoMatch(result.binContents, ["exec2.build"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
do {
let (_, stderr) = try execute(["--product", "lib1"], packagePath: fullPath)
try SwiftPMProduct.SwiftPackage.execute(["clean"], packagePath: fullPath)
XCTAssertMatch(stderr, .contains("'--product' cannot be used with the automatic product 'lib1'; building the default target instead"))
}
do {
let result = try build(["--target", "exec2"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["exec2.build"])
XCTAssertNoMatch(result.binContents, ["exec1"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
do {
_ = try execute(["--product", "exec1", "--target", "exec2"], packagePath: path)
XCTFail("Expected to fail")
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertEqual(stderr, "error: '--product' and '--target' are mutually exclusive\n")
}
do {
_ = try execute(["--product", "exec1", "--build-tests"], packagePath: path)
XCTFail("Expected to fail")
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertEqual(stderr, "error: '--product' and '--build-tests' are mutually exclusive\n")
}
do {
_ = try execute(["--build-tests", "--target", "exec2"], packagePath: path)
XCTFail("Expected to fail")
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertEqual(stderr, "error: '--target' and '--build-tests' are mutually exclusive\n")
}
do {
_ = try execute(["--build-tests", "--target", "exec2", "--product", "exec1"], packagePath: path)
XCTFail("Expected to fail")
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertEqual(stderr, "error: '--product', '--target', and '--build-tests' are mutually exclusive\n")
}
do {
_ = try execute(["--product", "UnkownProduct"], packagePath: path)
XCTFail("Expected to fail")
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertEqual(stderr, "error: no product named 'UnkownProduct'\n")
}
do {
_ = try execute(["--target", "UnkownTarget"], packagePath: path)
XCTFail("Expected to fail")
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertEqual(stderr, "error: no target named 'UnkownTarget'\n")
}
}
}
func testAtMainSupport() {
fixture(name: "Miscellaneous/AtMainSupport") { path in
let fullPath = resolveSymlinks(path)
do {
let result = try build(["--product", "ClangExecSingleFile"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["ClangExecSingleFile"])
} catch SwiftPMProductError.executionFailure(_, let stdout, let stderr) {
XCTFail(stdout + "\n" + stderr)
}
do {
let result = try build(["--product", "SwiftExecSingleFile"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["SwiftExecSingleFile"])
} catch SwiftPMProductError.executionFailure(_, let stdout, let stderr) {
XCTFail(stdout + "\n" + stderr)
}
do {
let result = try build(["--product", "SwiftExecMultiFile"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["SwiftExecMultiFile"])
} catch SwiftPMProductError.executionFailure(_, let stdout, let stderr) {
XCTFail(stdout + "\n" + stderr)
}
}
}
func testNonReachableProductsAndTargetsFunctional() {
fixture(name: "Miscellaneous/UnreachableTargets") { path in
let aPath = path.appending(component: "A")
do {
let result = try build([], packagePath: aPath)
XCTAssertNoMatch(result.binContents, ["bexec"])
XCTAssertNoMatch(result.binContents, ["BTarget2.build"])
XCTAssertNoMatch(result.binContents, ["cexec"])
XCTAssertNoMatch(result.binContents, ["CTarget.build"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
// Dependency contains a dependent product
do {
let result = try build(["--product", "bexec"], packagePath: aPath)
XCTAssertMatch(result.binContents, ["BTarget2.build"])
XCTAssertMatch(result.binContents, ["bexec"])
XCTAssertNoMatch(result.binContents, ["aexec"])
XCTAssertNoMatch(result.binContents, ["ATarget.build"])
XCTAssertNoMatch(result.binContents, ["BLibrary.a"])
// FIXME: We create the modulemap during build planning, hence this uglyness.
let bTargetBuildDir = ((try? localFileSystem.getDirectoryContents(result.binPath.appending(component: "BTarget1.build"))) ?? []).filter{ $0 != moduleMapFilename }
XCTAssertTrue(bTargetBuildDir.isEmpty, "bTargetBuildDir should be empty")
XCTAssertNoMatch(result.binContents, ["cexec"])
XCTAssertNoMatch(result.binContents, ["CTarget.build"])
// Also make sure we didn't emit parseable module interfaces
// (do this here to avoid doing a second build in
// testParseableInterfaces().
XCTAssertNoMatch(result.binContents, ["ATarget.swiftinterface"])
XCTAssertNoMatch(result.binContents, ["BTarget.swiftinterface"])
XCTAssertNoMatch(result.binContents, ["CTarget.swiftinterface"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
}
}
func testParseableInterfaces() {
fixture(name: "Miscellaneous/ParseableInterfaces") { path in
do {
let result = try build(["--enable-parseable-module-interfaces"], packagePath: path)
XCTAssertMatch(result.binContents, ["A.swiftinterface"])
XCTAssertMatch(result.binContents, ["B.swiftinterface"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
}
}
func testAutomaticParseableInterfacesWithLibraryEvolution() {
fixture(name: "Miscellaneous/LibraryEvolution") { path in
do {
let result = try build([], packagePath: path)
XCTAssertMatch(result.binContents, ["A.swiftinterface"])
XCTAssertMatch(result.binContents, ["B.swiftinterface"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
}
}
func testBuildCompleteMessage() {
fixture(name: "DependencyResolution/Internal/Simple") { path in
do {
let result = try execute([], packagePath: path)
// Number of steps must be greater than 0. e.g., [8/8] Build complete!
XCTAssertMatch(result.stdout, .regex("\\[[1-9][0-9]*\\/[1-9][0-9]*\\] Build complete!"))
}
do {
let result = try execute([], packagePath: path)
// test second time, to make sure message is presented even when nothing to build (cached)
XCTAssertMatch(result.stdout, .contains("[0/0] Build complete!"))
}
}
}
func testXcodeBuildSystemDefaultSettings() throws {
#if !os(macOS)
try XCTSkipIf(true, "test requires `xcbuild` and is therefore only supported on macOS")
#endif
fixture(name: "ValidLayouts/SingleModule/ExecutableNew") { path in
// Try building using XCBuild with default parameters. This should succeed. We build verbosely so we get full command lines.
let defaultOutput = try execute(["-c", "debug", "-v"], packagePath: path).stdout
// Look for certain things in the output from XCBuild.
XCTAssertMatch(defaultOutput, .contains("-target \(UserToolchain.default.triple.tripleString)"))
}
}
func testXcodeBuildSystemOverrides() throws {
#if !os(macOS)
try XCTSkipIf(true, "test requires `xcbuild` and is therefore only supported on macOS")
#endif
fixture(name: "ValidLayouts/SingleModule/ExecutableNew") { path in
// Try building using XCBuild without specifying overrides. This should succeed, and should use the default compiler path.
let defaultOutput = try execute(["-c", "debug", "-v"], packagePath: path).stdout
XCTAssertMatch(defaultOutput, .contains(ToolchainConfiguration.default.swiftCompilerPath.pathString))
// Now try building using XCBuild while specifying a faulty compiler override. This should fail. Note that we need to set the executable to use for the manifest itself to the default one, since it defaults to SWIFT_EXEC if not provided.
var overriddenOutput = ""
do {
overriddenOutput = try execute(["-c", "debug", "-v"], environment: ["SWIFT_EXEC": "/usr/bin/false", "SWIFT_EXEC_MANIFEST": ToolchainConfiguration.default.swiftCompilerPath.pathString], packagePath: path).stdout
XCTFail("unexpected success (was SWIFT_EXEC not overridden properly?)")
}
catch SwiftPMProductError.executionFailure(let error, let stdout, _) {
switch error {
case ProcessResult.Error.nonZeroExit(let result) where result.exitStatus != .terminated(code: 0):
overriddenOutput = stdout
break
default:
XCTFail("`swift build' failed in an unexpected manner")
}
}
catch {
XCTFail("`swift build' failed in an unexpected manner")
}
XCTAssertMatch(overriddenOutput, .contains("/usr/bin/false"))
}
}
}
| 47.424699 | 250 | 0.605907 |
9b6e4dc1ea1ba1e18ca0f21c82f81ce5012e65b3 | 1,661 | //
// Card.swift
// GrayOnWhiteKit
//
// Created by Aleksandr Romanov on 05.10.2019.
// Copyright © 2019 Aleksandr Romanov. All rights reserved.
//
import UIKit
@IBDesignable public class Card: UIView {
@IBOutlet var cardView: UIView!
@IBInspectable public var kind: Bool = false {
didSet {
if kind {
}
}
}
@IBInspectable public var elevation: Int {
get {
return 0
}
}
@IBInspectable
public var rounded: Bool = true {
didSet {
if rounded {
view.layer.cornerRadius = 24//DesignSystem.Radius.s
}
}
}
@IBInspectable public var roundedSize: String {
get {
return "x"
}
set(roundedSize) {
}
}
var view: UIView!
var nibName: String = "Card"
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func loadFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
func setup() {
view = loadFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.clipsToBounds = false
view.layer.masksToBounds = false
addSubview(view)
}
}
| 20.012048 | 82 | 0.518964 |
290e4ecd5b080c3f1bd9d8616af0f773b9de2015 | 1,117 | //
// MDLineWidthViewController.swift
// MDPaintBoard
//
// Created by Apple on 15/12/26.
// Copyright © 2015年 mdland. All rights reserved.
//
import UIKit
let MDLineWidthSelectedNotification = "MDLineWidthSelectedNotification"
class MDLineWidthViewController: UIViewController {
@IBOutlet weak var grayView: MDGrayView!
@IBOutlet weak var slider: ASValueTrackingSlider!
override func viewDidLoad() {
super.viewDidLoad()
preferredContentSize = CGSize(width: 250, height: 225)
slider.maximumValue = 20
slider.setMaxFractionDigitsDisplayed(0)
slider.font = UIFont(name: "Futura-CondensedExtraBold", size: 26)
// slider.popUpViewAnimatedColors = [UIColor.purpleColor(), UIColor.redColor(), UIColor.orangeColor()]
}
@IBAction private func sliderValueChange(slider: ASValueTrackingSlider) {
grayView.lineWidth = CGFloat(slider.value)
NSNotificationCenter.defaultCenter().postNotificationName(MDLineWidthSelectedNotification, object: slider.value)
}
}
| 26.595238 | 120 | 0.68487 |
edece5ff1a830a964f8e5182e8194e46b2b80fb1 | 7,364 | import XCTest
@testable import secp256k1_bindings
import secp256k1_implementation
final class secp256k1Tests: XCTestCase {
/// Uncompressed Key pair test
func testUncompressedKeypairCreation() {
// Initialize context
let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))!
// Destory context after execution
defer { secp256k1_context_destroy(context) }
// Setup private and public key variables
var pubkeyLen = 65
var cPubkey = secp256k1_pubkey()
var publicKey = [UInt8](repeating: 0, count: pubkeyLen)
let privateKey = try! "14E4A74438858920D8A35FB2D88677580B6A2EE9BE4E711AE34EC6B396D87B5C".byteArray()
// Verify the context and keys are setup correctly
XCTAssertEqual(secp256k1_context_randomize(context, privateKey), 1)
XCTAssertEqual(secp256k1_ec_pubkey_create(context, &cPubkey, privateKey), 1)
XCTAssertEqual(secp256k1_ec_pubkey_serialize(context, &publicKey, &pubkeyLen, &cPubkey, UInt32(SECP256K1_EC_UNCOMPRESSED)), 1)
let hexString = """
04734B3511150A60FC8CAC329CD5FF804555728740F2F2E98BC4242135EF5D5E4E6C4918116B0866F50C46614F3015D8667FBFB058471D662A642B8EA2C9C78E8A
"""
// Define the expected public key
let expectedPublicKey = try! hexString.byteArray()
// Verify the generated public key matches the expected public key
XCTAssertEqual(expectedPublicKey, publicKey)
XCTAssertEqual(hexString.lowercased(), String(byteArray: publicKey))
}
/// Compressed Key pair test
func testCompressedKeypairCreation() {
// Initialize context
let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))!
// Destory context after execution
defer { secp256k1_context_destroy(context) }
// Setup private and public key variables
var pubkeyLen = 33
var cPubkey = secp256k1_pubkey()
var publicKey = [UInt8](repeating: 0, count: pubkeyLen)
let privateKey = try! "B035FCFC6ABF660856C5F3A6F9AC51FCA897BB4E76AD9ACA3EFD40DA6B9C864B".byteArray()
// Verify the context and keys are setup correctly
XCTAssertEqual(secp256k1_context_randomize(context, privateKey), 1)
XCTAssertEqual(secp256k1_ec_pubkey_create(context, &cPubkey, privateKey), 1)
XCTAssertEqual(secp256k1_ec_pubkey_serialize(context, &publicKey, &pubkeyLen, &cPubkey, UInt32(SECP256K1_EC_COMPRESSED)), 1)
// Define the expected public key
let expectedPublicKey = try! "02EA724B70B48B61FB87E4310871A48C65BF38BF3FDFEFE73C2B90F8F32F9C1794".byteArray()
// Verify the generated public key matches the expected public key
XCTAssertEqual(expectedPublicKey, publicKey)
}
/// Compressed Key pair test
func testCompressedKeypairImplementationWithRaw() {
let expectedPrivateKey = "7da12cc39bb4189ac72d34fc2225df5cf36aaacdcac7e5a43963299bc8d888ed"
let expectedPublicKey = "023521df7b94248ffdf0d37f738a4792cc3932b6b1b89ef71cddde8251383b26e7"
let privateKeyBytes = try! expectedPrivateKey.byteArray()
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateKeyBytes)
// Verify the keys matches the expected keys output
XCTAssertEqual(expectedPrivateKey, String(byteArray: privateKey.rawRepresentation))
XCTAssertEqual(expectedPublicKey, String(byteArray: privateKey.publicKey.rawRepresentation))
}
/// SHA256 test
func testSha256() {
let expectedHashDigest = "f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342"
let data = "For this sample, this 63-byte string will be used as input data".data(using: .utf8)!
let digest = SHA256.hash(data: data)
// Verify the hash digest matches the expected output
XCTAssertEqual(expectedHashDigest, String(byteArray: Array(digest)))
}
func testSigning() {
let expectedDerSignature = "MEQCIGGvTtSQybMOSym7XmH9EofU3LLNaZo4jvFi1ZClPKA5AiBxjmZjAblJ11zKo76o/b4dhDvamwktCerS5SsTdyGqrg=="
let expectedSignature = "OaA8pZDVYvGOOJppzbLc1IcS/WFeuylLDrPJkNROr2GuqiF3Eyvl0uoJLQmb2juEHb79qL6jylzXSbkBY2aOcQ=="
let expectedPrivateKey = "5f6d5afecc677d66fb3d41eee7a8ad8195659ceff588edaf416a9a17daf38fdd"
let privateKeyBytes = try! expectedPrivateKey.byteArray()
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateKeyBytes)
let messageData = "Hello".data(using: .utf8)!
let signature = try! privateKey.signature(for: messageData)
// Verify the signature matches the expected output
XCTAssertEqual(expectedSignature, signature.rawRepresentation.base64EncodedString())
XCTAssertEqual(expectedDerSignature, try! signature.derRepresentation().base64EncodedString())
}
func testVerifying() {
// let expectedDerSignature = "MEQCIGGvTtSQybMOSym7XmH9EofU3LLNaZo4jvFi1ZClPKA5AiBxjmZjAblJ11zKo76o/b4dhDvamwktCerS5SsTdyGqrg=="
// let expectedSignature = "OaA8pZDVYvGOOJppzbLc1IcS/WFeuylLDrPJkNROr2GuqiF3Eyvl0uoJLQmb2juEHb79qL6jylzXSbkBY2aOcQ=="
let expectedPrivateKey = "5f6d5afecc677d66fb3d41eee7a8ad8195659ceff588edaf416a9a17daf38fdd"
let privateKeyBytes = try! expectedPrivateKey.byteArray()
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateKeyBytes)
let messageData = "Hello".data(using: .utf8)!
let signature = try! privateKey.signature(for: messageData)
// Test the verification of the signature output
XCTAssertTrue(privateKey.publicKey.isValidSignature(signature, for: SHA256.hash(data: messageData)))
// XCTAssertEqual(expectedSignature, signature.rawRepresentation.base64EncodedString())
}
func testVerifyingDER() {
let expectedDerSignature = Data(base64Encoded: "MEQCIGGvTtSQybMOSym7XmH9EofU3LLNaZo4jvFi1ZClPKA5AiBxjmZjAblJ11zKo76o/b4dhDvamwktCerS5SsTdyGqrg==", options: .ignoreUnknownCharacters)!
// let expectedSignature = "OaA8pZDVYvGOOJppzbLc1IcS/WFeuylLDrPJkNROr2GuqiF3Eyvl0uoJLQmb2juEHb79qL6jylzXSbkBY2aOcQ=="
let expectedPrivateKey = "5f6d5afecc677d66fb3d41eee7a8ad8195659ceff588edaf416a9a17daf38fdd"
let privateKeyBytes = try! expectedPrivateKey.byteArray()
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateKeyBytes)
let messageData = "Hello".data(using: .utf8)!
let signature = try! secp256k1.Signing.ECDSASignature(derRepresentation: expectedDerSignature)
// Test the verification of the signature output
XCTAssertTrue(privateKey.publicKey.isValidSignature(signature, for: SHA256.hash(data: messageData)))
// XCTAssertEqual(expectedSignature, signature.rawRepresentation.base64EncodedString())
}
static var allTests = [
("testUncompressedKeypairCreation", testUncompressedKeypairCreation),
("testCompressedKeypairCreation", testCompressedKeypairCreation),
("testCompressedKeypairImplementationWithRaw", testCompressedKeypairImplementationWithRaw),
("testSha256", testSha256),
("testSigning", testSigning),
("testVerifying", testVerifying),
("testVerifyingDER", testVerifyingDER),
]
}
| 51.138889 | 190 | 0.749864 |
33f1b478b28cf0ceeb3693a0151cbb14935b9118 | 2,068 | //
// THJGProjectFeeTypeView.swift
// THJG
//
// Created by 大强神 on 2019/8/1.
// Copyright © 2019 中南金融. All rights reserved.
//
import UIKit
fileprivate let THJGProjectFeeTypeCellIdentifier = "THJGProjectFeeTypeCellIdentifier"
typealias THJGProjectFeeTypeCompleteBlock = (SmallTypeBean?)->Void
class THJGProjectFeeTypeView: UIView {
@IBOutlet weak var tableView: UITableView!
var completionBlock: THJGProjectFeeTypeCompleteBlock?
var beans: [SmallTypeBean]! {
didSet {
tableView.reloadData()
}
}
var selectedBean: SmallTypeBean?
override func awakeFromNib() {
super.awakeFromNib()
//注册cell
tableView.register(UINib(nibName: "THJGTProjectFeeTypeCell", bundle: nil), forCellReuseIdentifier: THJGProjectFeeTypeCellIdentifier)
tableView.rowHeight = 45
}
static func showFeeTypeView() -> THJGProjectFeeTypeView {
return Bundle.main.loadNibNamed("THJGProjectFeeTypeView", owner: self, options: nil)?.first as! THJGProjectFeeTypeView
}
}
//MARK: - 方法
extension THJGProjectFeeTypeView {
@IBAction func cancelBtnDidClicked() {
removeFromSuperview()
}
@IBAction func confirmBtnDidClicked() {
completionBlock?(selectedBean)
removeFromSuperview()
}
}
extension THJGProjectFeeTypeView: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard beans != nil, !beans.isEmpty else {
return 0
}
return beans.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: THJGProjectFeeTypeCellIdentifier) as! THJGTProjectFeeTypeCell
cell.bean = beans[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedBean = beans[indexPath.row]
}
}
| 27.210526 | 140 | 0.686654 |
7177cbc5306c0d7f44a3632f1cda872a5d991a1f | 2,137 | //
// ActivityInsertRequest.swift
// YoutubeKit
//
// Created by Ryo Ishikawa on 12/30/2017
//
/// SeeAlso: https://developers.google.com/youtube/v3/docs/activities/insert
public struct ActivityInsertRequest: Requestable {
public typealias Response = ActivityList
public var path: String {
return "activities"
}
public var httpMethod: HTTPMethod {
return .post
}
public var isAuthorizedRequest: Bool {
return true
}
public var queryParameters: [String: Any] {
return ["part": part.toCSV()]
}
public var httpBody: Data? {
var json: [String: Any] = [:]
var snippet: [String: String] = [:]
var contentDetails: [String: Any] = [:]
var bulletin: [String: Any] = [:]
var resource: [String: String] = [:]
snippet["description"] = description
json["snippet"] = snippet
guard let resourceID = resourceID else {
return nil
}
if let kind = resourceID.kind {
resource["kind"] = kind
}
if let channelID = resourceID.channelID {
resource["channelId"] = channelID
}
if let playlistID = resourceID.playlistID {
resource["playlistId"] = playlistID
}
if let videoID = resourceID.videoID {
resource["videoId"] = videoID
}
bulletin["resourceId"] = resource
contentDetails["bulletin"] = bulletin
json["contentDetails"] = contentDetails
let jsonData = try? JSONSerialization.data(withJSONObject: json, options: [])
return jsonData
}
// MARK: - Required parameters
public let part: [Part.ActivityInsert]
// MARK: - Option parameters
public let description: String
public let resourceID: ResourceID.ActivityInsert?
public init(part: [Part.ActivityInsert],
description: String,
resourceID: ResourceID.ActivityInsert?) {
self.part = part
self.description = description
self.resourceID = resourceID
}
}
| 26.060976 | 85 | 0.584932 |
bf545b8ae70f3d40bd09c502508e1678c49f33bb | 1,510 | //
// CustomUITextField.swift
// mme1
//
// Created by Marcus Ronélius on 2015-08-30.
// Copyright (c) 2015 Ronelium Applications. All rights reserved.
//
import Foundation
import UIKit
class DragableUITextField: UITextField {
var textFieldConstraints: NSMutableArray!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
/*
var currentConstraints = self.constraints()
// https://www.cocoanetics.com/2015/06/proportional-layout-with-swift/
for constraint in self.constraints() as! [NSLayoutConstraint] {
}
*/
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
// Removing constraints. Otherwise the element will "pop" back when its becoming first responder. This is due to autolayout. This will throw some errors in the console but still works properly
self.removeConstraints(self.constraints())
self.setTranslatesAutoresizingMaskIntoConstraints(true)
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
// Set our textFields y origin to parent views location
self.center.y = touch.locationInView(self.superview).y
}
}
}
| 30.816327 | 205 | 0.639073 |
4663a59c6da92d8142f699b12a4607e368f687cd | 3,050 | //
// DataStorageProtocol.swift
// App
//
// Created by Daniel Skevarp on 2018-02-02.
//
import Foundation
import FluentProvider
typealias dataStorageRow = [String : Any]
typealias dataStorageACLRow = [String : [DataACL]]
enum DataACL {
case json, row, priv, guest
}
protocol DataStorage : class {
// var JSONData : [String : Any] {get set}
// var RowData : [String : Any] {get set}
// var PrivateData : [String : Any] { get set }
var dataStorage : dataStorageRow {get set}
var dataStorageACL : dataStorageACLRow {get set}
func getData(level : DataACL) throws -> dataStorageRow
func getDataFor<T>(key : String) -> T?
func initDatalevels()
func setDataLevel(key : String, level : DataACL)
func setDataLevel(key : String, levels : [DataACL])
func getJSONFromStorageData(levels : [DataACL]) throws -> JSON
}
extension DataStorage {
func getJSONFromStorageData(levels : [DataACL]) throws -> JSON{
var json = JSON()
for level in levels {
for data in try getData(level: level).enumerated() {
try json.set(data.element.key,data.element.value)
}
}
return json
}
func getDataFor<T>(key : String) -> T? {
guard let row = self.dataStorage[key] as? Row else {
return self.dataStorage[key] as? T
}
let data = row.wrapped
switch data {
case .bool(let b) :
return b as? T
case .number(let num):
switch num {
case .int(let i) :
return i as? T
case .double(let d) :
return d as? T
case .uint(let ui):
return ui as? T
}
case .string(let s):
return s as? T
case .array(let ar):
return ar as? T
case .object(let sd):
return sd as? T
case .null:
return nil
case .bytes(let b):
return b as? T
case .date(let date):
return date as? T
}
}
func getData(level: DataACL) throws -> dataStorageRow {
var aclData = [String : Any]()
for(k,v) in self.dataStorageACL {
if v.contains(level) {
if let value = dataStorage[k] {
aclData[k] = value
}
}
}
return aclData
}
func setDataLevel(key: String, level: DataACL) {
guard self.dataStorageACL[key] != nil else {
self.dataStorageACL[key] = [level]
return
}
self.dataStorageACL[key]?.append(level)
}
func setDataLevel(key: String, levels: [DataACL]) {
for level in levels {
if let dl = self.dataStorageACL[key] {
if !dl.contains(level){
self.dataStorageACL[key]?.append(level)
}
}else{
self.dataStorageACL[key] = [level]
}
}
}
}
| 27.727273 | 67 | 0.521967 |
56ae62c75e5993d218c7c66becc304d251984195 | 15,652 | // NumberTests.swift
//
// Copyright (c) 2014 - 2017 Pinglin Tang
//
// 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 XCTest
import Parcel
class NumberTests: XCTestCase {
func testNumber() {
//getter
var json = Parcel(NSNumber(value: 9876543210.123456789))
XCTAssertEqual(json.number!, 9876543210.123456789)
XCTAssertEqual(json.numberValue, 9876543210.123456789)
XCTAssertEqual(json.stringValue, "9876543210.123457")
json.string = "1000000000000000000000000000.1"
XCTAssertNil(json.number)
XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000.1")
json.string = "1e+27"
XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000")
//setter
json.number = NSNumber(value: 123456789.0987654321)
XCTAssertEqual(json.number!, 123456789.0987654321)
XCTAssertEqual(json.numberValue, 123456789.0987654321)
json.number = nil
XCTAssertEqual(json.numberValue, 0)
XCTAssertEqual(json.object as? NSNull, NSNull())
XCTAssertTrue(json.number == nil)
json.numberValue = 2.9876
XCTAssertEqual(json.number!, 2.9876)
}
func testBool() {
var json = Parcel(true)
XCTAssertEqual(json.bool!, true)
XCTAssertEqual(json.boolValue, true)
XCTAssertEqual(json.numberValue, true as NSNumber)
XCTAssertEqual(json.stringValue, "true")
json.bool = false
XCTAssertEqual(json.bool!, false)
XCTAssertEqual(json.boolValue, false)
XCTAssertEqual(json.numberValue, false as NSNumber)
json.bool = nil
XCTAssertTrue(json.bool == nil)
XCTAssertEqual(json.boolValue, false)
XCTAssertEqual(json.numberValue, 0)
json.boolValue = true
XCTAssertEqual(json.bool!, true)
XCTAssertEqual(json.boolValue, true)
XCTAssertEqual(json.numberValue, true as NSNumber)
}
func testDouble() {
var json = Parcel(9876543210.123456789)
XCTAssertEqual(json.double!, 9876543210.123456789)
XCTAssertEqual(json.doubleValue, 9876543210.123456789)
XCTAssertEqual(json.numberValue, 9876543210.123456789)
XCTAssertEqual(json.stringValue, "9876543210.123457")
json.double = 2.8765432
XCTAssertEqual(json.double!, 2.8765432)
XCTAssertEqual(json.doubleValue, 2.8765432)
XCTAssertEqual(json.numberValue, 2.8765432)
json.doubleValue = 89.0987654
XCTAssertEqual(json.double!, 89.0987654)
XCTAssertEqual(json.doubleValue, 89.0987654)
XCTAssertEqual(json.numberValue, 89.0987654)
json.double = nil
XCTAssertEqual(json.boolValue, false)
XCTAssertEqual(json.doubleValue, 0.0)
XCTAssertEqual(json.numberValue, 0)
}
func testFloat() {
var json = Parcel(54321.12345)
XCTAssertTrue(json.float! == 54321.12345)
XCTAssertTrue(json.floatValue == 54321.12345)
print(json.numberValue.doubleValue)
XCTAssertEqual(json.numberValue, 54321.12345)
XCTAssertEqual(json.stringValue, "54321.12345")
json.double = 23231.65
XCTAssertTrue(json.float! == 23231.65)
XCTAssertTrue(json.floatValue == 23231.65)
XCTAssertEqual(json.numberValue, NSNumber(value:23231.65))
json.double = -98766.23
XCTAssertEqual(json.float!, -98766.23)
XCTAssertEqual(json.floatValue, -98766.23)
XCTAssertEqual(json.numberValue, NSNumber(value:-98766.23))
}
func testInt() {
var json = Parcel(123456789)
XCTAssertEqual(json.int!, 123456789)
XCTAssertEqual(json.intValue, 123456789)
XCTAssertEqual(json.numberValue, NSNumber(value: 123456789))
XCTAssertEqual(json.stringValue, "123456789")
json.int = nil
XCTAssertTrue(json.boolValue == false)
XCTAssertTrue(json.intValue == 0)
XCTAssertEqual(json.numberValue, 0)
XCTAssertEqual(json.object as? NSNull, NSNull())
XCTAssertTrue(json.int == nil)
json.intValue = 76543
XCTAssertEqual(json.int!, 76543)
XCTAssertEqual(json.intValue, 76543)
XCTAssertEqual(json.numberValue, NSNumber(value: 76543))
json.intValue = 98765421
XCTAssertEqual(json.int!, 98765421)
XCTAssertEqual(json.intValue, 98765421)
XCTAssertEqual(json.numberValue, NSNumber(value: 98765421))
}
func testUInt() {
var json = Parcel(123456789)
XCTAssertTrue(json.uInt! == 123456789)
XCTAssertTrue(json.uIntValue == 123456789)
XCTAssertEqual(json.numberValue, NSNumber(value: 123456789))
XCTAssertEqual(json.stringValue, "123456789")
json.uInt = nil
XCTAssertTrue(json.boolValue == false)
XCTAssertTrue(json.uIntValue == 0)
XCTAssertEqual(json.numberValue, 0)
XCTAssertEqual(json.object as? NSNull, NSNull())
XCTAssertTrue(json.uInt == nil)
json.uIntValue = 76543
XCTAssertTrue(json.uInt! == 76543)
XCTAssertTrue(json.uIntValue == 76543)
XCTAssertEqual(json.numberValue, NSNumber(value: 76543))
json.uIntValue = 98765421
XCTAssertTrue(json.uInt! == 98765421)
XCTAssertTrue(json.uIntValue == 98765421)
XCTAssertEqual(json.numberValue, NSNumber(value: 98765421))
}
func testInt8() {
let n127 = NSNumber(value: 127)
var json = Parcel(n127)
XCTAssertTrue(json.int8! == n127.int8Value)
XCTAssertTrue(json.int8Value == n127.int8Value)
XCTAssertTrue(json.number! == n127)
XCTAssertEqual(json.numberValue, n127)
XCTAssertEqual(json.stringValue, "127")
let nm128 = NSNumber(value: -128)
json.int8Value = nm128.int8Value
XCTAssertTrue(json.int8! == nm128.int8Value)
XCTAssertTrue(json.int8Value == nm128.int8Value)
XCTAssertTrue(json.number! == nm128)
XCTAssertEqual(json.numberValue, nm128)
XCTAssertEqual(json.stringValue, "-128")
let n0 = NSNumber(value: 0 as Int8)
json.int8Value = n0.int8Value
XCTAssertTrue(json.int8! == n0.int8Value)
XCTAssertTrue(json.int8Value == n0.int8Value)
XCTAssertTrue(json.number! == n0)
XCTAssertEqual(json.numberValue, n0)
XCTAssertEqual(json.stringValue, "0")
let n1 = NSNumber(value: 1 as Int8)
json.int8Value = n1.int8Value
XCTAssertTrue(json.int8! == n1.int8Value)
XCTAssertTrue(json.int8Value == n1.int8Value)
XCTAssertTrue(json.number! == n1)
XCTAssertEqual(json.numberValue, n1)
XCTAssertEqual(json.stringValue, "1")
}
func testUInt8() {
let n255 = NSNumber(value: 255)
var json = Parcel(n255)
XCTAssertTrue(json.uInt8! == n255.uint8Value)
XCTAssertTrue(json.uInt8Value == n255.uint8Value)
XCTAssertTrue(json.number! == n255)
XCTAssertEqual(json.numberValue, n255)
XCTAssertEqual(json.stringValue, "255")
let nm2 = NSNumber(value: 2)
json.uInt8Value = nm2.uint8Value
XCTAssertTrue(json.uInt8! == nm2.uint8Value)
XCTAssertTrue(json.uInt8Value == nm2.uint8Value)
XCTAssertTrue(json.number! == nm2)
XCTAssertEqual(json.numberValue, nm2)
XCTAssertEqual(json.stringValue, "2")
let nm0 = NSNumber(value: 0)
json.uInt8Value = nm0.uint8Value
XCTAssertTrue(json.uInt8! == nm0.uint8Value)
XCTAssertTrue(json.uInt8Value == nm0.uint8Value)
XCTAssertTrue(json.number! == nm0)
XCTAssertEqual(json.numberValue, nm0)
XCTAssertEqual(json.stringValue, "0")
let nm1 = NSNumber(value: 1)
json.uInt8 = nm1.uint8Value
XCTAssertTrue(json.uInt8! == nm1.uint8Value)
XCTAssertTrue(json.uInt8Value == nm1.uint8Value)
XCTAssertTrue(json.number! == nm1)
XCTAssertEqual(json.numberValue, nm1)
XCTAssertEqual(json.stringValue, "1")
}
func testInt16() {
let n32767 = NSNumber(value: 32767)
var json = Parcel(n32767)
XCTAssertTrue(json.int16! == n32767.int16Value)
XCTAssertTrue(json.int16Value == n32767.int16Value)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let nm32768 = NSNumber(value: -32768)
json.int16Value = nm32768.int16Value
XCTAssertTrue(json.int16! == nm32768.int16Value)
XCTAssertTrue(json.int16Value == nm32768.int16Value)
XCTAssertTrue(json.number! == nm32768)
XCTAssertEqual(json.numberValue, nm32768)
XCTAssertEqual(json.stringValue, "-32768")
let n0 = NSNumber(value: 0)
json.int16Value = n0.int16Value
XCTAssertTrue(json.int16! == n0.int16Value)
XCTAssertTrue(json.int16Value == n0.int16Value)
XCTAssertEqual(json.number, n0)
XCTAssertEqual(json.numberValue, n0)
XCTAssertEqual(json.stringValue, "0")
let n1 = NSNumber(value: 1)
json.int16 = n1.int16Value
XCTAssertTrue(json.int16! == n1.int16Value)
XCTAssertTrue(json.int16Value == n1.int16Value)
XCTAssertTrue(json.number! == n1)
XCTAssertEqual(json.numberValue, n1)
XCTAssertEqual(json.stringValue, "1")
}
func testUInt16() {
let n65535 = NSNumber(value: 65535)
var json = Parcel(n65535)
XCTAssertTrue(json.uInt16! == n65535.uint16Value)
XCTAssertTrue(json.uInt16Value == n65535.uint16Value)
XCTAssertTrue(json.number! == n65535)
XCTAssertEqual(json.numberValue, n65535)
XCTAssertEqual(json.stringValue, "65535")
let n32767 = NSNumber(value: 32767)
json.uInt16 = n32767.uint16Value
XCTAssertTrue(json.uInt16! == n32767.uint16Value)
XCTAssertTrue(json.uInt16Value == n32767.uint16Value)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
}
func testInt32() {
let n2147483647 = NSNumber(value: 2147483647)
var json = Parcel(n2147483647)
XCTAssertTrue(json.int32! == n2147483647.int32Value)
XCTAssertTrue(json.int32Value == n2147483647.int32Value)
XCTAssertTrue(json.number! == n2147483647)
XCTAssertEqual(json.numberValue, n2147483647)
XCTAssertEqual(json.stringValue, "2147483647")
let n32767 = NSNumber(value: 32767)
json.int32 = n32767.int32Value
XCTAssertTrue(json.int32! == n32767.int32Value)
XCTAssertTrue(json.int32Value == n32767.int32Value)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let nm2147483648 = NSNumber(value: -2147483648)
json.int32Value = nm2147483648.int32Value
XCTAssertTrue(json.int32! == nm2147483648.int32Value)
XCTAssertTrue(json.int32Value == nm2147483648.int32Value)
XCTAssertTrue(json.number! == nm2147483648)
XCTAssertEqual(json.numberValue, nm2147483648)
XCTAssertEqual(json.stringValue, "-2147483648")
}
func testUInt32() {
let n2147483648 = NSNumber(value: 2147483648 as UInt32)
var json = Parcel(n2147483648)
XCTAssertTrue(json.uInt32! == n2147483648.uint32Value)
XCTAssertTrue(json.uInt32Value == n2147483648.uint32Value)
XCTAssertTrue(json.number! == n2147483648)
XCTAssertEqual(json.numberValue, n2147483648)
XCTAssertEqual(json.stringValue, "2147483648")
let n32767 = NSNumber(value: 32767 as UInt32)
json.uInt32 = n32767.uint32Value
XCTAssertTrue(json.uInt32! == n32767.uint32Value)
XCTAssertTrue(json.uInt32Value == n32767.uint32Value)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let n0 = NSNumber(value: 0 as UInt32)
json.uInt32Value = n0.uint32Value
XCTAssertTrue(json.uInt32! == n0.uint32Value)
XCTAssertTrue(json.uInt32Value == n0.uint32Value)
XCTAssertTrue(json.number! == n0)
XCTAssertEqual(json.numberValue, n0)
XCTAssertEqual(json.stringValue, "0")
}
func testInt64() {
let int64Max = NSNumber(value: INT64_MAX)
var json = Parcel(int64Max)
XCTAssertTrue(json.int64! == int64Max.int64Value)
XCTAssertTrue(json.int64Value == int64Max.int64Value)
XCTAssertTrue(json.number! == int64Max)
XCTAssertEqual(json.numberValue, int64Max)
XCTAssertEqual(json.stringValue, int64Max.stringValue)
let n32767 = NSNumber(value: 32767)
json.int64 = n32767.int64Value
XCTAssertTrue(json.int64! == n32767.int64Value)
XCTAssertTrue(json.int64Value == n32767.int64Value)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let int64Min = NSNumber(value: (INT64_MAX-1) * -1)
json.int64Value = int64Min.int64Value
XCTAssertTrue(json.int64! == int64Min.int64Value)
XCTAssertTrue(json.int64Value == int64Min.int64Value)
XCTAssertTrue(json.number! == int64Min)
XCTAssertEqual(json.numberValue, int64Min)
XCTAssertEqual(json.stringValue, int64Min.stringValue)
}
func testUInt64() {
let uInt64Max = NSNumber(value: UINT64_MAX)
var json = Parcel(uInt64Max)
XCTAssertTrue(json.uInt64! == uInt64Max.uint64Value)
XCTAssertTrue(json.uInt64Value == uInt64Max.uint64Value)
XCTAssertTrue(json.number! == uInt64Max)
XCTAssertEqual(json.numberValue, uInt64Max)
XCTAssertEqual(json.stringValue, uInt64Max.stringValue)
let n32767 = NSNumber(value: 32767)
json.int64 = n32767.int64Value
XCTAssertTrue(json.int64! == n32767.int64Value)
XCTAssertTrue(json.int64Value == n32767.int64Value)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
}
}
| 40.133333 | 86 | 0.656274 |
3345221e0b9c048fdef0806fdaf7cd864db2de5a | 980 | //
// PostRoutes.swift
// Application
//
// Created by Lam Nguyen on 1/2/22.
//
import Foundation
import KituraContracts
import Pink_Coven
let iso8601Decoder: () -> BodyDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}
let iso8601Encoder: () -> BodyEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return encoder
}
func initializePostRoutes(app: App) {
app.router.get("/api/v1/posts", handler: getPosts)
app.router.post("/api/v1/posts", handler: addPost)
app.router.decoders[.json] = iso8601Decoder
app.router.encoders[.json] = iso8601Encoder
}
func getPosts(completion: @escaping ([Post]?, RequestError?) -> Void) {
Post.findAll(completion)
}
func addPost(post: Post, completion: @escaping (Post?, RequestError?) -> Void) {
var newPost = post
if newPost.id == nil {
newPost.id == UUID()
}
newPost.save(completion)
}
| 21.304348 | 80 | 0.672449 |
9148d9c383624f819854a825c5f65729d7afe1d7 | 968 | //
// YYMusicPlayerTests.swift
// YYMusicPlayerTests
//
// Created by yangyouyong on 15/7/5.
// Copyright © 2015年 yangyouyong. All rights reserved.
//
import XCTest
class YYMusicPlayerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 26.888889 | 111 | 0.635331 |
64559615bc2a6ea29c091140e26ac0421aadb112 | 2,287 | extension ObservableType {
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http:
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
static func create(_ subscribe: @escaping (AnyObserver<Element>) -> Disposable) -> Observable<Element> {
AnonymousObservable(subscribe)
}
}
private final class AnonymousObservableSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = AnonymousObservable<Element>
private let isStopped = AtomicInt(0)
#if DEBUG
private let synchronizationTracker = SynchronizationTracker()
#endif
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
#if DEBUG
synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self.synchronizationTracker.unregister() }
#endif
switch event {
case .next:
if load(isStopped) == 1 {
return
}
forwardOn(event)
case .error, .completed:
if fetchOr(isStopped, 1) == 0 {
forwardOn(event)
dispose()
}
}
}
func run(_ parent: Parent) -> Disposable {
parent.subscribeHandler(AnyObserver(self))
}
}
private final class AnonymousObservable<Element>: Producer<Element> {
typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable
let subscribeHandler: SubscribeHandler
init(_ subscribeHandler: @escaping SubscribeHandler) {
self.subscribeHandler = subscribeHandler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
let subscription = sink.run(self)
return (sink: sink, subscription: subscription)
}
}
| 33.144928 | 171 | 0.669436 |
03a1306e4c1458fb9f7f6606cc8c67e2d2e3b625 | 1,770 | //
// DiagonalGradientView.swift
// OnBeat
//
// Created by Andrew J Wagner on 4/23/16.
// Copyright © 2016 Chronos Interactive. All rights reserved.
//
import UIKit
public class DiagonalGradientView: UIView {
@IBInspectable
public var startColor: UIColor = UIColor.red {
didSet {
self.gradientLayer.colors = self.colors
}
}
@IBInspectable
public var endColor: UIColor = UIColor.blue {
didSet {
self.gradientLayer.colors = self.colors
}
}
public override class var layerClass: AnyClass {
return CAGradientLayer.self
}
var gradientLayer: CAGradientLayer {
return self.layer as! CAGradientLayer
}
private var colors: [CGColor] {
return [startColor.cgColor, endColor.cgColor]
}
public override func awakeFromNib() {
self.gradientLayer.colors = self.colors
self.gradientLayer.startPoint = CGPoint(x: 0, y: 0)
self.gradientLayer.endPoint = CGPoint(x: 1, y: 1)
}
public func animate(toStart startColor: UIColor?, andEnd endColor: UIColor?, withDuration duration: TimeInterval) {
let fromColors = self.gradientLayer.presentation()?.colors ?? self.colors
let toColors = [startColor?.cgColor ?? self.startColor.cgColor, endColor?.cgColor ?? self.endColor.cgColor]
self.gradientLayer.colors = toColors
let animation = CABasicAnimation(keyPath: "colors")
animation.fromValue = fromColors
animation.toValue = toColors
animation.duration = duration
animation.isRemovedOnCompletion = true
animation.fillMode = .forwards
animation.isCumulative = true
self.gradientLayer.add(animation, forKey: "animateColors")
}
}
| 29.016393 | 119 | 0.662712 |
d6b706a807701fe499ead7b42f2dcc32a531e58c | 966 | //
// caf_iosTests.swift
// caf_iosTests
//
// Created by Duy Nguyen on 3/17/17.
// Copyright © 2017 Duy Nguyen. All rights reserved.
//
import XCTest
@testable import caf_ios
class caf_iosTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.108108 | 111 | 0.630435 |
c150d2a8b55f1ae8b2fe3c3f77c400631e6e6d1f | 4,201 | //
// CollectionSource+UICollectionViewDelegate.swift
// PulsarKit
//
// Created by Massimo Oliviero on 10/08/2018.
// Copyright © 2019 Nacoon. All rights reserved.
//
import UIKit
extension CollectionSource: UICollectionViewDelegate {
// MARK: selection
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
dispatch(event: .onDidSelect, container: collectionView, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
dispatch(event: .onDidDeselect, container: collectionView, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
dispatch(event: .onDidHighlight, container: collectionView, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
dispatch(event: .onDidUnhighlight, container: collectionView, indexPath: indexPath)
}
// MARK: should
public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
dispatch(event: .onShouldHighlight, container: collectionView, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
dispatch(event: .onShouldSelect, container: collectionView, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
dispatch(event: .onShouldDeselect, container: collectionView, indexPath: indexPath)
}
// MARK: display
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
dispatch(event: .onWillDisplay, container: collectionView, cell: cell, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
dispatch(event: .onDidEndDisplaying, container: collectionView, cell: cell, indexPath: indexPath)
}
// MARK: menu
public func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
dispatch(event: .onShouldShowMenu, container: collectionView, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
dispatch(event: .onCanPerformAction, container: collectionView, indexPath: indexPath, action: action, sender: sender)
}
public func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
_ = dispatch(event: .onPerformAction, container: collectionView, indexPath: indexPath, action: action, sender: sender)
}
public func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
dispatch(event: .onTargetMove, container: collectionView, originalIndexPath: originalIndexPath, proposedIndexPath: proposedIndexPath)
}
// MARK: layout
public func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
on.dispatch(from: fromLayout, to: toLayout) ?? UICollectionViewTransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)
}
}
// MARK: - UIScrollViewDelegate
public extension CollectionSource {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let context = ScrollContext(container: scrollView)
events.forEach { $0.dispatch(source: self, event: Event.Scroll.onDidScroll, context: context) }
}
}
| 51.864198 | 213 | 0.75601 |
87510346f628b3eee0db525abc9e0bd131de6e13 | 753 | //
// Scaled.swift
// UIImagePickerControllerProject
//
// Created by Ilija Mihajlovic on 3/9/19.
// Copyright © 2019 Ilija Mihajlovic. All rights reserved.
//
import UIKit
class ScaledHeightImageView: UIImageView {
override var intrinsicContentSize: CGSize {
if let myImage = self.image {
let myImageWidth = myImage.size.width
let myImageHeight = myImage.size.height
let myViewWidth = self.frame.size.width
let ratio = myViewWidth/myImageWidth
let scaledHeight = myImageHeight * ratio
return CGSize(width: myViewWidth, height: scaledHeight)
}
return CGSize(width: -1.0, height: -1.0)
}
}
| 25.1 | 67 | 0.60425 |
2218a7a085f0bdcc689d43c8f8e88390a0e89532 | 5,112 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
infix operator >>>
@inline(__always)
fileprivate func >>> (num: UInt32, count: Int) -> UInt32 {
// This implementation assumes without checking that `count` is in the 1...31 range.
return (num >> count) | (num << (32 - count))
}
struct Sha256 {
private static let k: [UInt32] =
[0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2]
static func hash(data: Data) -> [UInt8] {
var h0 = 0x6a09e667 as UInt32
var h1 = 0xbb67ae85 as UInt32
var h2 = 0x3c6ef372 as UInt32
var h3 = 0xa54ff53a as UInt32
var h4 = 0x510e527f as UInt32
var h5 = 0x9b05688c as UInt32
var h6 = 0x1f83d9ab as UInt32
var h7 = 0x5be0cd19 as UInt32
// Padding
var bytes = data.withUnsafeBytes { $0.map { $0 } }
let originalLength = bytes.count
var newLength = originalLength * 8 + 1
while newLength % 512 != 448 {
newLength += 1
}
newLength /= 8
bytes.append(0x80)
for _ in 0..<(newLength - originalLength - 1) {
bytes.append(0x00)
}
// Length
let bitsLength = UInt64(truncatingIfNeeded: originalLength * 8)
for i: UInt64 in 0..<8 {
bytes.append(UInt8(truncatingIfNeeded: (bitsLength & 0xFF << ((7 - i) * 8)) >> ((7 - i) * 8)))
}
for i in stride(from: 0, to: bytes.count, by: 64) {
var w = Array(repeating: 0 as UInt32, count: 64)
for j in 0..<16 {
var word = 0 as UInt32
for k: UInt32 in 0..<4 {
word += UInt32(truncatingIfNeeded: bytes[i + j * 4 + k.toInt()]) << ((3 - k) * 8)
}
w[j] = word
}
for i in 16..<64 {
let s0 = (w[i - 15] >>> 7) ^ (w[i - 15] >>> 18) ^ (w[i - 15] >> 3)
let s1 = (w[i - 2] >>> 17) ^ (w[i - 2] >>> 19) ^ (w[i - 2] >> 10)
w[i] = w[i - 16] &+ s0 &+ w[i - 7] &+ s1
}
var a = h0
var b = h1
var c = h2
var d = h3
var e = h4
var f = h5
var g = h6
var h = h7
for i in 0..<64 {
let s1 = (e >>> 6) ^ (e >>> 11) ^ (e >>> 25)
let ch = (e & f) ^ ((~e) & g)
let temp1 = h &+ s1 &+ ch &+ k[i] &+ w[i]
let s0 = (a >>> 2) ^ (a >>> 13) ^ (a >>> 22)
let maj = (a & b) ^ (a & c) ^ (b & c)
let temp2 = s0 &+ maj
h = g
g = f
f = e
e = d &+ temp1
d = c
c = b
b = a
a = temp1 &+ temp2
}
h0 = h0 &+ a
h1 = h1 &+ b
h2 = h2 &+ c
h3 = h3 &+ d
h4 = h4 &+ e
h5 = h5 &+ f
h6 = h6 &+ g
h7 = h7 &+ h
}
var result = [UInt8]()
result.reserveCapacity(32)
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h0 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h1 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h2 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h3 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h4 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h5 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h6 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
for i: UInt32 in 0..<4 {
result.append(UInt8(truncatingIfNeeded: (h7 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8)))
}
return result
}
}
| 35.255172 | 116 | 0.473396 |
227549648c8d5bf86d34cecac8ae1d46d2b97305 | 2,724 | //
// CalendarPickerViewController.swift
// Calendr
//
// Created by Paker on 28/01/21.
//
import Cocoa
import RxSwift
class CalendarPickerViewController: NSViewController {
private let disposeBag = DisposeBag()
private let viewModel: CalendarPickerViewModel
private let contentStackView = NSStackView(.vertical)
init(viewModel: CalendarPickerViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
setUpAccessibility()
setUpBindings()
}
private func setUpAccessibility() {
guard BuildConfig.isUITesting else { return }
view.setAccessibilityElement(true)
view.setAccessibilityIdentifier(Accessibility.Settings.Calendars.view)
}
override func loadView() {
view = NSView()
view.addSubview(contentStackView)
contentStackView.edges(to: view)
contentStackView.alignment = .left
}
private func setUpBindings() {
viewModel.calendars
.observe(on: MainScheduler.instance)
.compactMap { [weak self] calendars -> [NSView]? in
guard let self = self else { return nil }
return Dictionary(grouping: calendars, by: { $0.account })
.sorted(by: { $0.key < $1.key })
.flatMap { account, calendars in
self.makeCalendarSection(title: account, calendars: calendars)
}
}
.bind(to: contentStackView.rx.arrangedSubviews)
.disposed(by: disposeBag)
}
private func makeCalendarSection(title: String, calendars: [CalendarModel]) -> [NSView] {
let label = Label(text: title, font: .systemFont(ofSize: 11, weight: .semibold))
label.textColor = .secondaryLabelColor
let stackView = NSStackView(
views: calendars.compactMap(makeCalendarItem)
)
.with(orientation: .vertical)
.with(alignment: .left)
return [label, NSStackView(views: [.dummy, stackView])]
}
private func makeCalendarItem(_ calendar: CalendarModel) -> NSView {
let checkbox = Checkbox(title: calendar.title)
checkbox.setTitleColor(color: calendar.color)
viewModel.enabledCalendars
.map { $0.contains(calendar.identifier) ? .on : .off }
.bind(to: checkbox.rx.state)
.disposed(by: disposeBag)
checkbox.rx.tap
.map { calendar.identifier }
.bind(to: viewModel.toggleCalendar)
.disposed(by: disposeBag)
return checkbox
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 26.970297 | 93 | 0.615272 |
711c7f189abd5ac2e89e857c56f7bbacadfdecff | 3,788 | import Foundation
/// This is the element to decorate a target item.
public final class PBXContainerItemProxy: PBXObject {
public enum ProxyType: UInt, Decodable {
case nativeTarget = 1
case reference = 2
case other
}
/// The object is a reference to a PBXProject element.
public var containerPortalReference: PBXObjectReference
/// Element proxy type.
public var proxyType: ProxyType?
/// Element remote global ID reference.
public var remoteGlobalIDReference: PBXObjectReference?
/// Element remote info.
public var remoteInfo: String?
/// Initializes the container item proxy with its attributes.
///
/// - Parameters:
/// - containerPortalReference: reference to the container portal.
/// - remoteGlobalIDReference: reference to the remote global ID.
/// - proxyType: proxy type.
/// - remoteInfo: remote info.
public init(containerPortalReference: PBXObjectReference,
remoteGlobalIDReference: PBXObjectReference? = nil,
proxyType: ProxyType? = nil,
remoteInfo: String? = nil) {
self.containerPortalReference = containerPortalReference
self.remoteGlobalIDReference = remoteGlobalIDReference
self.remoteInfo = remoteInfo
self.proxyType = proxyType
super.init()
}
// MARK: - Decodable
fileprivate enum CodingKeys: String, CodingKey {
case containerPortal
case proxyType
case remoteGlobalIDString
case remoteInfo
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let objects = decoder.context.objects
let objectReferenceRepository = decoder.context.objectReferenceRepository
let containerPortalString: String = try container.decode(.containerPortal)
containerPortalReference = objectReferenceRepository.getOrCreate(reference: containerPortalString,
objects: objects)
proxyType = try container.decodeIntIfPresent(.proxyType).flatMap(ProxyType.init)
if let remoteGlobalIDString: String = try container.decodeIfPresent(.remoteGlobalIDString) {
remoteGlobalIDReference = objectReferenceRepository.getOrCreate(reference: remoteGlobalIDString,
objects: objects)
} else {
remoteGlobalIDReference = nil
}
remoteInfo = try container.decodeIfPresent(.remoteInfo)
try super.init(from: decoder)
}
}
// MARK: - PBXContainerItemProxy Extension (PlistSerializable)
extension PBXContainerItemProxy: PlistSerializable {
func plistKeyAndValue(proj _: PBXProj, reference: String) -> (key: CommentedString, value: PlistValue) {
var dictionary: [CommentedString: PlistValue] = [:]
dictionary["isa"] = .string(CommentedString(PBXContainerItemProxy.isa))
dictionary["containerPortal"] = .string(CommentedString(containerPortalReference.value, comment: "Project object"))
if let proxyType = proxyType {
dictionary["proxyType"] = .string(CommentedString("\(proxyType.rawValue)"))
}
if let remoteGlobalIDReference = remoteGlobalIDReference {
dictionary["remoteGlobalIDString"] = .string(CommentedString(remoteGlobalIDReference.value))
}
if let remoteInfo = remoteInfo {
dictionary["remoteInfo"] = .string(CommentedString(remoteInfo))
}
return (key: CommentedString(reference,
comment: "PBXContainerItemProxy"),
value: .dictionary(dictionary))
}
}
| 42.088889 | 123 | 0.658131 |
22df092cd236a1fff2a72e4b4b526cecf8846017 | 7,266 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#else
import Glibc
#endif
/// A threading lock based on `libpthread` instead of `libdispatch`.
///
/// This object provides a lock on top of a single `pthread_mutex_t`. This kind
/// of lock is safe to use with `libpthread`-based threading models, such as the
/// one used by NIO.
public final class Lock {
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> = UnsafeMutablePointer.allocate(capacity: 1)
/// Create a new lock.
public init() {
var attr = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
let err = pthread_mutex_init(self.mutex, &attr)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
}
deinit {
let err = pthread_mutex_destroy(self.mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
mutex.deallocate()
}
/// Acquire the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
public func lock() {
let err = pthread_mutex_lock(self.mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
}
/// Release the lock.
///
/// Whenver possible, consider using `withLock` instead of this method and
/// `lock`, to simplify lock handling.
public func unlock() {
let err = pthread_mutex_unlock(self.mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
}
}
public extension Lock {
/// Acquire the lock for the duration of the given block.
///
/// This convenience method should be preferred to `lock` and `unlock` in
/// most situations, as it ensures that the lock will be released regardless
/// of how `body` exits.
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
func withLock<T>(_ body: () throws -> T) rethrows -> T {
self.lock()
defer {
self.unlock()
}
return try body()
}
// specialise Void return (for performance)
@inlinable
func withLockVoid(_ body: () throws -> Void) rethrows {
try self.withLock(body)
}
}
/// A `Lock` with a built-in state variable.
///
/// This class provides a convenience addition to `Lock`: it provides the ability to wait
/// until the state variable is set to a specific value to acquire the lock.
public final class ConditionLock<T: Equatable> {
private var _value: T
private let mutex: Lock
private let cond: UnsafeMutablePointer<pthread_cond_t> = UnsafeMutablePointer.allocate(capacity: 1)
/// Create the lock, and initialize the state variable to `value`.
///
/// - Parameter value: The initial value to give the state variable.
public init(value: T) {
self._value = value
self.mutex = Lock()
let err = pthread_cond_init(self.cond, nil)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
}
deinit {
let err = pthread_cond_destroy(self.cond)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
self.cond.deallocate()
}
/// Acquire the lock, regardless of the value of the state variable.
public func lock() {
self.mutex.lock()
}
/// Release the lock, regardless of the value of the state variable.
public func unlock() {
self.mutex.unlock()
}
/// The value of the state variable.
///
/// Obtaining the value of the state variable requires acquiring the lock.
/// This means that it is not safe to access this property while holding the
/// lock: it is only safe to use it when not holding it.
public var value: T {
self.lock()
defer {
self.unlock()
}
return self._value
}
/// Acquire the lock when the state variable is equal to `wantedValue`.
///
/// - Parameter wantedValue: The value to wait for the state variable
/// to have before acquiring the lock.
public func lock(whenValue wantedValue: T) {
self.lock()
while true {
if self._value == wantedValue {
break
}
let err = pthread_cond_wait(self.cond, self.mutex.mutex)
precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)")
}
}
/// Acquire the lock when the state variable is equal to `wantedValue`,
/// waiting no more than `timeoutSeconds` seconds.
///
/// - Parameter wantedValue: The value to wait for the state variable
/// to have before acquiring the lock.
/// - Parameter timeoutSeconds: The number of seconds to wait to acquire
/// the lock before giving up.
/// - Returns: `true` if the lock was acquired, `false` if the wait timed out.
public func lock(whenValue wantedValue: T, timeoutSeconds: Double) -> Bool {
precondition(timeoutSeconds >= 0)
let nsecPerSec: Int64 = 1_000_000_000
self.lock()
/* the timeout as a (seconds, nano seconds) pair */
let timeoutNS = Int64(timeoutSeconds * Double(nsecPerSec))
var curTime = timeval()
gettimeofday(&curTime, nil)
let allNSecs: Int64 = timeoutNS + Int64(curTime.tv_usec) * 1000
var timeoutAbs = timespec(
tv_sec: curTime.tv_sec + Int(allNSecs / nsecPerSec),
tv_nsec: Int(allNSecs % nsecPerSec)
)
assert(timeoutAbs.tv_nsec >= 0 && timeoutAbs.tv_nsec < Int(nsecPerSec))
assert(timeoutAbs.tv_sec >= curTime.tv_sec)
while true {
if self._value == wantedValue {
return true
}
switch pthread_cond_timedwait(self.cond, self.mutex.mutex, &timeoutAbs) {
case 0:
continue
case ETIMEDOUT:
self.unlock()
return false
case let e:
fatalError("caught error \(e) when calling pthread_cond_timedwait")
}
}
}
/// Release the lock, setting the state variable to `newValue`.
///
/// - Parameter newValue: The value to give to the state variable when we
/// release the lock.
public func unlock(withValue newValue: T) {
self._value = newValue
self.unlock()
let err = pthread_cond_broadcast(self.cond)
precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)")
}
}
| 35.443902 | 109 | 0.611891 |
48f579de894423c207c32bfe0227e61fa9c86b9a | 641 | //
// DoubleExtension.swift
// WiggleSDK
//
// Created by mykim on 2018. 9. 14..
// Copyright © 2018년 mykim. All rights reserved.
//
import Foundation
import UIKit
extension Double {
public var toCGFloat: CGFloat { return CGFloat(self) }
public var toString: String { return String(self) }
public func dateToString(_ format: String) -> String {
let date: Date = Date(timeIntervalSince1970: self)
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = NSLocale(localeIdentifier: "ko_KR") as Locale
return formatter.string(from: date)
}
}
| 26.708333 | 72 | 0.680187 |
5d543cdc4832c3678051f4b2d6a13c49a4f07e7a | 9,128 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import AWSMobileClient
class AuthUserServiceAdapter: AuthUserServiceBehavior {
let awsMobileClient: AWSMobileClientBehavior
init(awsMobileClient: AWSMobileClientBehavior) {
self.awsMobileClient = awsMobileClient
}
func fetchAttributes(request: AuthFetchUserAttributesRequest,
completionHandler: @escaping FetchUserAttributesCompletion) {
awsMobileClient.getUserAttributes { result, error in
guard error == nil else {
if let awsMobileClientError = error as? AWSMobileClientError,
case .notSignedIn = awsMobileClientError {
let authError = AuthError.signedOut(
AuthPluginErrorConstants.fetchAttributeSignedOutError.errorDescription,
AuthPluginErrorConstants.fetchAttributeSignedOutError.recoverySuggestion, nil)
completionHandler(.failure(authError))
} else {
let authError = AuthErrorHelper.toAuthError(error!)
completionHandler(.failure(authError))
}
return
}
guard let result = result else {
// This should not happen, return an unknown error.
let error = AuthError.unknown("Could not read result from fetchAttributes operation")
completionHandler(.failure(error))
return
}
let resultList = result.map { AuthUserAttribute(AuthUserAttributeKey(rawValue: $0.key), value: $0.value) }
completionHandler(.success(resultList))
}
}
func updateAttribute(request: AuthUpdateUserAttributeRequest,
completionHandler: @escaping UpdateUserAttributeCompletion) {
let attribuetList = [request.userAttribute]
updateAttributes(attributeList: attribuetList) { result in
switch result {
case .success(let updateAttributeResultDict):
guard let updateResult = updateAttributeResultDict[request.userAttribute.key] else {
let error = AuthError.unknown("Could not read result from updateAttribute operation")
completionHandler(.failure(error))
return
}
completionHandler(.success(updateResult))
case .failure(let error):
completionHandler(.failure(error))
}
}
}
func updateAttributes(request: AuthUpdateUserAttributesRequest,
completionHandler: @escaping UpdateUserAttributesCompletion) {
updateAttributes(attributeList: request.userAttributes, completionHandler: completionHandler)
}
func resendAttributeConfirmationCode(request: AuthAttributeResendConfirmationCodeRequest,
completionHandler: @escaping ResendAttributeConfirmationCodeCompletion) {
awsMobileClient.verifyUserAttribute(attributeName: request.attributeKey.rawValue) { result, error in
guard error == nil else {
if let awsMobileClientError = error as? AWSMobileClientError,
case .notSignedIn = awsMobileClientError {
let authError = AuthError.signedOut(
AuthPluginErrorConstants.resendAttributeCodeSignedOutError.errorDescription,
AuthPluginErrorConstants.resendAttributeCodeSignedOutError.recoverySuggestion, nil)
completionHandler(.failure(authError))
} else {
let authError = AuthErrorHelper.toAuthError(error!)
completionHandler(.failure(authError))
}
return
}
guard let result = result else {
// This should not happen, return an unknown error.
let error = AuthError.unknown("""
Could not read result from resendAttributeConfirmationCode operation
""")
completionHandler(.failure(error))
return
}
let codeDeliveryDetails = result.toAuthCodeDeliveryDetails()
completionHandler(.success(codeDeliveryDetails))
}
}
func confirmAttribute(request: AuthConfirmUserAttributeRequest,
completionHandler: @escaping ConfirmAttributeCompletion) {
awsMobileClient.confirmUpdateUserAttributes(
attributeName: request.attributeKey.rawValue,
code: request.confirmationCode) { error in
guard let error = error else {
completionHandler(.success(()))
return
}
if let awsMobileClientError = error as? AWSMobileClientError,
case .notSignedIn = awsMobileClientError {
let authError = AuthError.signedOut(
AuthPluginErrorConstants.confirmAttributeSignedOutError.errorDescription,
AuthPluginErrorConstants.confirmAttributeSignedOutError.recoverySuggestion, nil)
completionHandler(.failure(authError))
} else {
let authError = AuthErrorHelper.toAuthError(error)
completionHandler(.failure(authError))
}
}
}
func changePassword(request: AuthChangePasswordRequest,
completionHandler: @escaping ChangePasswordCompletion) {
awsMobileClient.changePassword(
currentPassword: request.oldPassword,
proposedPassword: request.newPassword) { error in
guard let error = error else {
completionHandler(.success(()))
return
}
if let awsMobileClientError = error as? AWSMobileClientError,
case .notSignedIn = awsMobileClientError {
let authError = AuthError.signedOut(
AuthPluginErrorConstants.changePasswordSignedOutError.errorDescription,
AuthPluginErrorConstants.changePasswordSignedOutError.recoverySuggestion, nil)
completionHandler(.failure(authError))
} else {
let authError = AuthErrorHelper.toAuthError(error)
completionHandler(.failure(authError))
}
}
}
private func updateAttributes(attributeList: [AuthUserAttribute],
completionHandler: @escaping UpdateUserAttributesCompletion) {
let attributeMap = attributeList.reduce(into: [String: String]()) {
$0[$1.key.rawValue] = $1.value
}
awsMobileClient.updateUserAttributes(attributeMap: attributeMap) { result, error in
guard error == nil else {
if let awsMobileClientError = error as? AWSMobileClientError,
case .notSignedIn = awsMobileClientError {
let authError = AuthError.signedOut(
AuthPluginErrorConstants.updateAttributeSignedOutError.errorDescription,
AuthPluginErrorConstants.updateAttributeSignedOutError.recoverySuggestion, nil)
completionHandler(.failure(authError))
} else {
let authError = AuthErrorHelper.toAuthError(error!)
completionHandler(.failure(authError))
}
return
}
guard let result = result else {
// This should not happen, return an unknown error.
let error = AuthError.unknown("Could not read result from verifyUserAttribute operation")
completionHandler(.failure(error))
return
}
var finalResult = [AuthUserAttributeKey: AuthUpdateAttributeResult]()
for item in result {
if let attribute = item.attributeName {
let authCodeDeliveryDetails = item.toAuthCodeDeliveryDetails()
let nextStep = AuthUpdateAttributeStep.confirmAttributeWithCode(authCodeDeliveryDetails, nil)
let updateAttributeResult = AuthUpdateAttributeResult(isUpdated: false,
nextStep: nextStep)
finalResult[AuthUserAttributeKey(rawValue: attribute)] = updateAttributeResult
}
}
// Check if all items are added to the dictionary
for item in attributeList where finalResult[item.key] == nil {
let updateAttributeResult = AuthUpdateAttributeResult(isUpdated: true, nextStep: .done)
finalResult[item.key] = updateAttributeResult
}
completionHandler(.success(finalResult))
}
}
}
| 46.10101 | 118 | 0.599693 |
228b2b3f6ce6eb95f87386ce3c0b31ec46e6dd5f | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class d<T:a
class a<T protocol A{class a<T:T.T func a
| 31.857143 | 87 | 0.757848 |
21c7ffa3ea15fb2aa1899e21b7763221ee23d479 | 6,020 | //
// CSWorkspacePreferences.swift
// ComponentStudio
//
// Created by devin_abbott on 8/2/17.
// Copyright © 2017 Devin Abbott. All rights reserved.
//
import Foundation
import AppKit
func defaultWorkspaceURL() -> URL {
return preferencesDirectory().appendingPathComponent("LonaWorkspace", isDirectory: true)
}
class CSWorkspacePreferences: CSPreferencesFile {
static let optionalURLType = CSURLType.makeOptional()
enum Keys: String {
case colorsPath
case textStylesPath
case workspaceIcon
case workspaceName
}
static var url: URL {
return CSUserPreferences.workspaceURL.appendingPathComponent("lona.json")
}
static var colorsFileURL: URL {
if let string = colorsFilePathValue.data.get(key: "data").string,
let url = URL(string: string)?.absoluteURLForWorkspaceURL() {
return url
}
return CSUserPreferences.workspaceURL.appendingPathComponent("colors.json")
}
static var textStylesFileURL: URL {
if let string = textStylesFilePathValue.data.get(key: "data").string,
let url = URL(string: string)?.absoluteURLForWorkspaceURL() {
return url
}
return CSUserPreferences.workspaceURL.appendingPathComponent("textStyles.json")
}
static var workspaceIconURL: URL {
if let string = workspaceIconPathValue.data.get(key: "data").string,
let url = URL(string: string)?.absoluteURLForWorkspaceURL() {
return url
}
return Bundle.main.urlForImageResource(NSImage.Name(rawValue: "default-workspace-thumbnail"))!
}
static var colorsFilePathValue: CSValue {
get {
if let path = CSWorkspacePreferences.data[Keys.colorsPath.rawValue] {
return CSValue(type: optionalURLType, data: CSValue.expand(type: optionalURLType, data: path))
} else {
return CSUnitValue.wrap(in: optionalURLType, tagged: "None")
}
}
set {
CSWorkspacePreferences.data[Keys.colorsPath.rawValue] = newValue == CSUnitValue
? nil
: CSValue.compact(type: optionalURLType, data: newValue.data)
}
}
static var textStylesFilePathValue: CSValue {
get {
if let path = CSWorkspacePreferences.data[Keys.textStylesPath.rawValue] {
return CSValue(type: optionalURLType, data: CSValue.expand(type: optionalURLType, data: path))
} else {
return CSUnitValue.wrap(in: optionalURLType, tagged: "None")
}
}
set {
CSWorkspacePreferences.data[Keys.textStylesPath.rawValue] = newValue == CSUnitValue
? nil
: CSValue.compact(type: optionalURLType, data: newValue.data)
}
}
static var workspaceIconPathValue: CSValue {
get {
if let path = CSWorkspacePreferences.data[Keys.workspaceIcon.rawValue] {
return CSValue(type: optionalURLType, data: CSValue.expand(type: optionalURLType, data: path))
} else {
return CSUnitValue.wrap(in: optionalURLType, tagged: "None")
}
}
set {
CSWorkspacePreferences.data[Keys.workspaceIcon.rawValue] = newValue.tag() == "None"
? nil
: CSValue.compact(type: optionalURLType, data: newValue.data)
}
}
static var workspaceNameValue: CSValue {
get {
return CSValue(type: CSType.string, data: CSWorkspacePreferences.data[Keys.workspaceName.rawValue] ?? "".toData())
}
set {
CSWorkspacePreferences.data[Keys.workspaceName.rawValue] = newValue.data.stringValue == ""
? nil
: newValue.data
}
}
static var workspaceName: String {
let customName = workspaceNameValue.data.stringValue
return customName.isEmpty ? LonaModule.current.url.lastPathComponent : customName
}
static var data: CSData = load()
static func reloadAllConfigurationFiles(closeDocuments: Bool) {
if closeDocuments {
NSDocumentController.shared.closeAllDocuments(withDelegate: nil, didCloseAllSelector: nil, contextInfo: nil)
}
CSWorkspacePreferences.reload()
CSUserTypes.reload()
CSColors.reload()
CSTypography.reload()
CSGradients.reload()
CSShadows.reload()
}
private enum CreateWorkspace: String {
case cancel = "Cancel"
case create = "Create"
}
/// Returns true if the url passed is a valid workspace
///
/// A valid workspace is identified by a "lona.json" file in the root of the workspace.
/// This function will warn the user if they attempt to open a non-workspace, but offer
/// the choice of creating a "lona.json" file automatically.
static func validateProposedWorkspace(url: URL) -> Bool {
do {
_ = try Data(contentsOf: url.appendingPathComponent("lona.json"))
return true
} catch {
let alert = Alert(
items: [CreateWorkspace.create, CreateWorkspace.cancel],
messageText: "This doesn't appear to be a Lona workspace!",
informativeText: "There's no 'lona.json' file in \(url.path). If you're sure this is a workspace, we can create a 'lona.json' automatically now. Otherwise, press Cancel and open a different directory.")
guard let response = alert.run() else { return false }
switch response {
case .cancel:
return false
case .create:
let file = VirtualFile(name: "lona.json", data: CSData.Object([:]))
do {
try VirtualFileSystem.write(node: file, relativeTo: url)
} catch {
return false
}
return true
}
}
}
}
| 35.621302 | 218 | 0.611794 |
e53845d9f4457136d257f877681b21ce0fb04e4e | 9,771 | // RUN: %target-swiftc_driver -O -Rpass-missed=sil-assembly-vision-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil %s -o /dev/null -Xfrontend -verify
// REQUIRES: objc_interop
// REQUIRES: optimized_stdlib
// REQUIRES: swift_stdlib_no_asserts
import Foundation
//////////////////
// Generic Code //
//////////////////
public func forcedCast<NS, T>(_ ns: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
return ns as! T // expected-remark @:13 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-3:33 {{of 'ns'}}
}
public func forcedCast2<NS, T>(_ ns: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
let x = ns
return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:34 {{of 'ns'}}
}
public func forcedCast3<NS, T>(_ ns: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
var x = ns // expected-warning {{variable 'x' was never mutated}}
return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:34 {{of 'ns'}}
}
public func forcedCast4<NS, T>(_ ns: NS, _ ns2: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we lose that x was assigned ns2. This is flow sensitive information
// that we might be able to recover. We still emit that a runtime cast
// occurred here, just don't say what the underlying value was.
var x = ns
x = ns2
return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}}
}
public func condCast<NS, T>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
return ns as? T // expected-remark @:13 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-3:31 {{of 'ns'}}
}
public func condCast2<NS, T>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
let x = ns
return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:32 {{of 'ns'}}
}
public func condCast3<NS, T>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
var x = ns // expected-warning {{variable 'x' was never mutated}}
return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:32 {{of 'ns'}}
}
public func condCast4<NS, T>(_ ns: NS, _ ns2: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we lose that x was assigned ns2. This is flow sensitive information
// that we might be able to recover. We still emit that a runtime cast
// occurred here, just don't say what the underlying value was.
var x = ns
x = ns2
return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}}
}
public func condCast5<NS, T>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we lose that x was assigned.
if let x = ns as? T { // expected-remark @:17 {{conditional runtime cast of value with type 'NS' to 'T'}}
return x // expected-note @-5:32 {{of 'ns'}}
}
return nil
}
public func condCast6<NS, T>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we lose that x was assigned.
guard let x = ns as? T else { // expected-remark @:20 {{conditional runtime cast of value with type 'NS' to 'T'}}
return nil // expected-note @-5:32 {{of 'ns'}}
}
return x
}
//////////////////////////////////
// Any Object Constrained Casts //
//////////////////////////////////
public func forcedCast<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
//
// TODO: We should also note the retain as being on 'ns'.
return ns as! T // expected-remark @:13 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-5:55 {{of 'ns'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func forcedCast2<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow. We should also note the retain as being on 'ns'
let x = ns
return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:56 {{of 'ns'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func forcedCast3<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
var x = ns // expected-warning {{variable 'x' was never mutated}}
return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:56 {{of 'ns'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
// Interestingly today, with AnyObject codegen, we do not lose the assignment to
// x and say the cast is on ns2!
public func forcedCast4<NS: AnyObject, T: AnyObject>(_ ns: NS, _ ns2: NS) -> T {
// Make sure the colon info is right so that the arrow is under the a.
var x = ns
x = ns2
return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-5:66 {{of 'ns2'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func condCast<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
return ns as? T // expected-remark @:13 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-3:53 {{of 'ns'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func condCast2<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
let x = ns
return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:54 {{of 'ns'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func condCast3<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we seem to completely eliminate 'x' here in the debug info. TODO:
// Maybe we can recover this info somehow.
var x = ns // expected-warning {{variable 'x' was never mutated}}
return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-7:54 {{of 'ns'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func condCast4<NS: AnyObject, T: AnyObject>(_ ns: NS, _ ns2: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
var x = ns
x = ns2
return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}}
// expected-note @-5:64 {{of 'ns2'}}
// expected-remark @-2 {{retain of type 'NS'}}
}
public func condCast5<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we lose that x was assigned.
if let x = ns as? T { // expected-remark @:17 {{conditional runtime cast of value with type 'NS' to 'T'}}
return x // expected-note @-5:54 {{of 'ns'}}
} // expected-remark @-2 {{retain of type 'NS'}}
return nil
}
public func condCast6<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? {
// Make sure the colon info is right so that the arrow is under the a.
//
// Today, we lose that x was assigned.
guard let x = ns as? T else { // expected-remark @:20 {{conditional runtime cast of value with type 'NS' to 'T'}}
return nil // expected-note @-5:54 {{of 'ns'}}
} // expected-remark @-2 {{retain of type 'NS'}}
return x
}
//////////////////
// String Casts //
//////////////////
// We need to be able to recognize the conformances. We can't do this yet! But
// we will be able to!
@inline(never)
public func testForcedCastNStoSwiftString(_ nsString: NSString) -> String {
let o: String = forcedCast(nsString)
return o
}
@inline(never)
public func testConditionalCastNStoSwiftString(_ nsString: NSString) -> String? {
let o: String? = condCast(nsString)
return o
}
| 42.668122 | 169 | 0.614369 |
fb4d1a83e1a6e9051c23b8e629f9da3c4cb07a13 | 6,747 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// C Primitive Types
//===----------------------------------------------------------------------===//
/// The C 'char' type.
///
/// This will be the same as either `CSignedChar` (in the common
/// case) or `CUnsignedChar`, depending on the platform.
public typealias CChar = Int8
/// The C 'unsigned char' type.
public typealias CUnsignedChar = UInt8
/// The C 'unsigned short' type.
public typealias CUnsignedShort = UInt16
/// The C 'unsigned int' type.
public typealias CUnsignedInt = UInt32
/// The C 'unsigned long' type.
#if os(Windows) && !os(Cygwin) && arch(x86_64)
public typealias CUnsignedLong = UInt32
#else
public typealias CUnsignedLong = UInt
#endif
/// The C 'unsigned long long' type.
#if os(Windows) && !os(Cygwin) && arch(x86_64)
public typealias CUnsignedLongLong = UInt
#else
public typealias CUnsignedLongLong = UInt64
#endif
/// The C 'signed char' type.
public typealias CSignedChar = Int8
/// The C 'short' type.
public typealias CShort = Int16
/// The C 'int' type.
public typealias CInt = Int32
/// The C 'long' type.
#if os(Windows) && !os(Cygwin) && arch(x86_64)
public typealias CLong = Int32
#else
public typealias CLong = Int
#endif
/// The C 'long long' type.
#if os(Windows) && !os(Cygwin) && arch(x86_64)
public typealias CLongLong = Int
#else
public typealias CLongLong = Int64
#endif
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
// FIXME: long double
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = UnicodeScalar
// FIXME: Swift should probably have a UTF-16 type other than UInt16.
//
/// The C++11 'char16_t' type, which has UTF-16 encoding.
public typealias CChar16 = UInt16
/// The C++11 'char32_t' type, which has UTF-32 encoding.
public typealias CChar32 = UnicodeScalar
/// The C '_Bool' and C++ 'bool' type.
public typealias CBool = Bool
/// A wrapper around an opaque C pointer.
///
/// Opaque pointers are used to represent C pointers to types that
/// cannot be represented in Swift, such as incomplete struct types.
@_fixed_layout
public struct OpaquePointer : Hashable {
@_versioned
internal var _rawValue: Builtin.RawPointer
@_versioned
@_transparent
internal init(_ v: Builtin.RawPointer) {
self._rawValue = v
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
@_transparent
public init<T>(_ from: UnsafePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(_ from: UnsafePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
@_transparent
public init<T>(_ from: UnsafeMutablePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(_ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// The pointer's hash value.
///
/// The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(_rawValue))
}
}
extension OpaquePointer : CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension Int {
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension OpaquePointer : Equatable {
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
/// The corresponding Swift type to `va_list` in imported C APIs.
@_fixed_layout
public struct CVaListPointer {
var value: UnsafeMutableRawPointer
public // @testable
init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {
value = from
}
}
extension CVaListPointer : CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return value.debugDescription
}
}
func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeMutableRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*alignment:*/ Int32()._value,
/*volatile:*/ false._value)
}
/// Copy `count` bytes of memory from `src` into `dest`.
///
/// The memory regions `source..<source + count` and
/// `dest..<dest + count` may overlap.
@_versioned
@_inlineable
func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memmove_RawPointer_RawPointer_Int64(
dest, src, size,
/*alignment:*/ Int32()._value,
/*volatile:*/ false._value)
}
@available(*, unavailable, renamed: "OpaquePointer")
public struct COpaquePointer {}
extension OpaquePointer {
@available(*, unavailable,
message:"use 'Unmanaged.toOpaque()' instead")
public init<T>(bitPattern bits: Unmanaged<T>) {
Builtin.unreachable()
}
}
| 27.315789 | 80 | 0.686676 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.