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
|
---|---|---|---|---|---|
5db260c235cba35093b89489fa495f66fc940eba | 28,629 | //
// XMLDecoder.swift
// XMLParsing
//
// Created by Shawn Moore on 11/20/17.
// Copyright © 2017 Shawn Moore. All rights reserved.
//
import Foundation
//===----------------------------------------------------------------------===//
// XML Decoder
//===----------------------------------------------------------------------===//
/// `XMLDecoder` facilitates the decoding of XML into semantic `Decodable` types.
class XMLDecoder {
// MARK: Options
/// The strategy to use for decoding `Date` values.
public enum DateDecodingStrategy {
/// Defer to `Date` for decoding. This is the default strategy.
case deferredToDate
/// Decode the `Date` as a UNIX timestamp from a XML number. This is the default strategy.
case secondsSince1970
/// Decode the `Date` as UNIX millisecond timestamp from a XML number.
case millisecondsSince1970
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decode the `Date` as a string parsed by the given formatter.
case formatted(DateFormatter)
/// Decode the `Date` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Date)
/// Decode the `Date` as a string parsed by the given formatter for the give key.
static func keyFormatted(_ formatterForKey: @escaping (CodingKey) throws -> DateFormatter?) -> XMLDecoder.DateDecodingStrategy {
return .custom({ (decoder) -> Date in
guard let codingKey = decoder.codingPath.last else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "No Coding Path Found"))
}
guard let container = try? decoder.singleValueContainer(),
let text = try? container.decode(String.self) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date text"))
}
guard let dateFormatter = try formatterForKey(codingKey) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "No date formatter for date text")
}
if let date = dateFormatter.date(from: text) {
return date
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(text)")
}
})
}
}
/// The strategy to use for decoding `Data` values.
public enum DataDecodingStrategy {
/// Defer to `Data` for decoding.
case deferredToData
/// Decode the `Data` from a Base64-encoded string. This is the default strategy.
case base64
/// Decode the `Data` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Data)
/// Decode the `Data` as a custom value by the given closure for the give key.
static func keyFormatted(_ formatterForKey: @escaping (CodingKey) throws -> Data?) -> XMLDecoder.DataDecodingStrategy {
return .custom({ (decoder) -> Data in
guard let codingKey = decoder.codingPath.last else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "No Coding Path Found"))
}
guard let container = try? decoder.singleValueContainer(),
let text = try? container.decode(String.self) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date text"))
}
guard let data = try formatterForKey(codingKey) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode data string \(text)")
}
return data
})
}
}
/// The strategy to use for non-XML-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatDecodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Decode the values from the given representation strings.
case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use when decoding lists.
public enum ListDecodingStrategy {
/// Preserves the XML structure, an outer type will contain lists
/// grouped under the tag used for individual items. This is the default strategy.
case preserveStructure
/// Collapse the XML structure to avoid the outer type.
/// Useful when individual items will all be listed under one tag;
/// the outer type will only include one list under this tag and can be
/// omitted.
case collapseListUsingItemTag(String)
}
/// The strategy to use when decoding maps.
public enum MapDecodingStrategy {
/// Preserves the XML structure. Key and Value tags will be retained producing a
/// list of elements with these two attributes. This is the default strategy.
case preserveStructure
/// Collapse the XML structure to avoid key and value tags. For example-
/// <Result>
/// <Tag>
/// <Key>QueueType</Key>
/// <Value>Production</Value>
/// </Tag>
/// <Tag>
/// <Key>Owner</Key>
/// <Value>Developer123</Value>
/// </Tag>
/// </Result>
///
/// will be decoded into
/// struct Result {
/// let tags: [String: String]
/// }
case collapseMapUsingTags(keyTag: String, valueTag: String)
}
/// The strategy to use in decoding dates. Defaults to `.secondsSince1970`.
open var dateDecodingStrategy: DateDecodingStrategy = .secondsSince1970
/// The strategy to use in decoding binary data. Defaults to `.base64`.
open var dataDecodingStrategy: DataDecodingStrategy = .base64
/// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
/// The strategy to use in decoding lists. Defaults to `.preserveStructure`.
open var listDecodingStrategy: ListDecodingStrategy = .preserveStructure
/// The strategy to use in decoding maps. Defaults to `.preserveStructure`.
open var mapDecodingStrategy: MapDecodingStrategy = .preserveStructure
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
internal struct _Options {
let dateDecodingStrategy: DateDecodingStrategy
let dataDecodingStrategy: DataDecodingStrategy
let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
let listDecodingStrategy: ListDecodingStrategy
let mapDecodingStrategy: MapDecodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level decoder.
internal var options: _Options {
return _Options(dateDecodingStrategy: dateDecodingStrategy,
dataDecodingStrategy: dataDecodingStrategy,
nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy,
listDecodingStrategy: listDecodingStrategy,
mapDecodingStrategy: mapDecodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a XML Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given XML representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid XML.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
let topLevel: [String: Any]
do {
topLevel = try _XMLStackParser.parse(with: data)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid XML.", underlyingError: error))
}
let decoder = _XMLDecoder(referencing: topLevel, options: self.options)
guard let value = try decoder.unbox(topLevel, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
}
// MARK: - _XMLDecoder
internal class _XMLDecoder : Decoder {
// MARK: Properties
/// The decoder's storage.
internal var storage: _XMLDecodingStorage
/// Options set on the top-level decoder.
internal let options: XMLDecoder._Options
/// The path to the current point in encoding.
internal(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
internal init(referencing container: Any, at codingPath: [CodingKey] = [], options: XMLDecoder._Options) {
self.storage = _XMLDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
private func getMapFromListOfEntries(entryList: [Any], keyTag: String, valueTag: String) -> [String : Any] {
var newContainer: [String: Any] = [:]
// construct a dictionary from each entry and the key and value tags
entryList.forEach { entry in
if let keyedContainer = entry as? [String : Any],
let key = keyedContainer[keyTag] as? String,
let value = keyedContainer[valueTag] {
newContainer[key] = value
}
}
return newContainer
}
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
let topContainer: [String : Any]
// if this is a dictionary
if let currentContainer = self.storage.topContainer as? [String : Any] {
// if we are combining collapsing lists and maps
if case let .collapseListUsingItemTag(itemTag) = options.listDecodingStrategy,
case let .collapseMapUsingTags(keyTag: keyTag, valueTag: valueTag) = options.mapDecodingStrategy,
let itemList = currentContainer[itemTag] as? [Any] {
topContainer = getMapFromListOfEntries(entryList: itemList, keyTag: keyTag, valueTag: valueTag)
} else {
topContainer = currentContainer
}
// if this is a list and the mapDecodingStrategy is collapseMapUsingTags
} else if let currentContainer = self.storage.topContainer as? [Any],
case let .collapseMapUsingTags(keyTag: keyTag, valueTag: valueTag) = options.mapDecodingStrategy {
topContainer = getMapFromListOfEntries(entryList: currentContainer, keyTag: keyTag, valueTag: valueTag)
} else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
}
let container = _XMLKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
let topContainer: [Any]
if let container = self.storage.topContainer as? [Any] {
topContainer = container
} else if let container = self.storage.topContainer as? [AnyHashable: Any] {
topContainer = [container]
} else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
}
return _XMLUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
extension _XMLDecoder : SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
return self.storage.topContainer is NSNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try self.unbox(self.storage.topContainer, as: Bool.self)!
}
public func decode(_ type: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try self.unbox(self.storage.topContainer, as: Int.self)!
}
public func decode(_ type: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try self.unbox(self.storage.topContainer, as: Int8.self)!
}
public func decode(_ type: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try self.unbox(self.storage.topContainer, as: Int16.self)!
}
public func decode(_ type: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try self.unbox(self.storage.topContainer, as: Int32.self)!
}
public func decode(_ type: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try self.unbox(self.storage.topContainer, as: Int64.self)!
}
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try self.unbox(self.storage.topContainer, as: Double.self)!
}
public func decode(_ type: String.Type) throws -> String {
try expectNonNull(String.self)
return try self.unbox(self.storage.topContainer, as: String.self)!
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(type)
return try self.unbox(self.storage.topContainer, as: type)!
}
}
// MARK: - Concrete Value Representations
extension _XMLDecoder {
/// Returns the given value unboxed from a container.
internal func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
guard !(value is MissingValue) else { return nil }
guard let value = value as? String else {
return nil
}
if value.lowercased() == "true" || value == "1" {
return true
} else if value.lowercased() == "false" || value == "0" {
return false
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
internal func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return Int(exactly: value)
}
internal func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return Int8(exactly: value)
}
internal func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return Int16(exactly: value)
}
internal func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return Int32(exactly: value)
}
internal func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return Int64(exactly: value)
}
internal func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return UInt(exactly: value)
}
internal func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return UInt8(exactly: value)
}
internal func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return UInt16(exactly: value)
}
internal func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return UInt32(exactly: value)
}
internal func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return UInt64(exactly: value)
}
internal func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return value
}
internal func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Double(string) else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: string)
}
return value
}
internal func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard !(value is MissingValue) else { return nil }
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return string
}
internal func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
guard !(value is MissingValue) else {
return nil
}
switch self.options.dateDecodingStrategy {
case .deferredToDate:
self.storage.push(container: value)
let date = try Date(from: self)
self.storage.popContainer()
return date
case .secondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double)
case .millisecondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double / 1000.0)
case .iso8601:
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let string = try self.unbox(value, as: String.self)!
guard let date = _iso8601Formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
}
return date
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
let string = try self.unbox(value, as: String.self)!
guard let date = formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter."))
}
return date
case .custom(let closure):
self.storage.push(container: value)
let date = try closure(self)
self.storage.popContainer()
return date
}
}
internal func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
guard !(value is MissingValue) else { return nil }
switch self.options.dataDecodingStrategy {
case .deferredToData:
self.storage.push(container: value)
let data = try Data(from: self)
self.storage.popContainer()
return data
case .base64:
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
guard let data = Data(base64Encoded: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64."))
}
return data
case .custom(let closure):
self.storage.push(container: value)
let data = try closure(self)
self.storage.popContainer()
return data
}
}
internal func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? {
guard !(value is MissingValue) else { return nil }
// Attempt to bridge from NSDecimalNumber.
let doubleValue = try self.unbox(value, as: Double.self)!
return Decimal(doubleValue)
}
internal func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
let decoded: T
if type == Date.self || type == NSDate.self {
guard let date = try self.unbox(value, as: Date.self) else { return nil }
decoded = date as! T
} else if type == Data.self || type == NSData.self {
guard let data = try self.unbox(value, as: Data.self) else { return nil }
decoded = data as! T
} else if type == URL.self || type == NSURL.self {
guard let urlString = try self.unbox(value, as: String.self) else {
return nil
}
guard let url = URL(string: urlString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Invalid URL string."))
}
decoded = (url as! T)
} else if type == Decimal.self || type == NSDecimalNumber.self {
guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil }
decoded = decimal as! T
} else {
if value is MissingValue {
self.storage.push(container: [:])
} else {
self.storage.push(container: value)
}
decoded = try type.init(from: self)
self.storage.popContainer()
}
return decoded
}
}
| 40.957082 | 179 | 0.600265 |
3ad8a4a9273b1c430d6057fdfdea5b0ec63f903b | 459 | public struct Group<Content> {
public var _content: Content
}
extension Group: View where Content: View {
public typealias Body = Never
public init(@ViewBuilder content: () -> Content) {
self._content = content()
}
public static func _makeViewList(view: _GraphValue<Group<Content>>, inputs: _ViewListInputs) -> _ViewListOutputs {
fatalError()
}
public var body: Never {
fatalError()
}
}
| 22.95 | 118 | 0.633987 |
d742ea7676a0641abe94d0cb13efd64f0ae80ea2 | 349 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{T){{class B<T where B:A{enum B{func g{if true{}}}class a{var f={protocol A{protocol a{struct B{class a{struct d{let:{class d
| 43.625 | 125 | 0.730659 |
20a167ba59bb2b11d67f778256df0b514075d0c1 | 707 | /*
Copyright 2021 Microoled
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
extension String {
var asNullTerminatedUInt8Array: [UInt8] {
return self.utf8CString.map{ UInt8($0) }
}
}
| 29.458333 | 73 | 0.75389 |
509e56ae677f9339d36c5fc560f19d26a9357c10 | 5,079 | //
// Post.swift
// App
//
// Created by Ahmed Raad on 10/13/17.
//
import Foundation
import FluentProvider
import AnyDate
final class Post: Model {
var storage = Storage()
var title: String
var content: String
var user_id: Identifier?
var category_id: Identifier?
var isPublished: Bool = false
var isLikedPost: Int = 0
init(title: String, content: String, user_id: Identifier?, category_id: Identifier?) {
self.title = title
self.content = content
self.user_id = user_id
self.category_id = category_id
}
init(row: Row) throws {
self.title = try row.get(Field.title)
self.content = try row.get(Field.content)
self.user_id = try row.get(Field.user_id)
self.isPublished = try row.get(Field.is_published)
self.category_id = try row.get(Field.category_id)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Field.title, title)
try row.set(Field.content, content)
try row.set(Field.user_id, user_id)
try row.set(Field.category_id, category_id)
try row.set(Field.is_published, isPublished)
return row
}
}
extension Post: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { db in
db.id()
db.string(Field.title)
db.text(Field.content.rawValue)
db.bool(Field.is_published)
db.parent(User.self, optional: false, foreignIdKey: Field.user_id.rawValue)
db.parent(Category.self, optional: false, foreignIdKey: Field.category_id.rawValue)
})
}
static func revert(_ database: Database) throws {
}
}
extension Post: Timestampable {}
extension Array where Element : Post {
func publicRow() throws -> Row {
var result: [Row] = []
for value in self {
try result.append(value.publicRow())
}
return Row(result)
}
}
extension Post: NodeConvertible {
convenience init(node: Node) throws {
try self.init(
title: node.get(Field.title),
content: node.get(Field.content),
user_id: node.get(Field.user_id),
category_id: node.get(Field.category_id)
)
}
func makeNode(in context: Context?) throws -> Node {
var node = Node([:], in: context)
try node.set(Field.id, id)
try node.set(Field.title, title)
try node.set(Field.content, content)
try node.set("isLiked", isLikedPost)
try node.set("isNew", isNew)
try node.set(Field.likes, likes())
try node.set(Field.is_published, isPublished)
try node.set(Field.unlikes, unLikes())
try node.set("author", author.get()?.makeJSON())
try node.set("category", category.get()?.makeRow())
try node.set("createdAt", created_at)
try node.set("updatedAt", updatedAt)
return node
}
}
extension Post {
func publicRow() throws -> Row {
var row = Row()
try row.set(Field.id, id)
try row.set(Field.title, title)
try row.set(Field.content, content)
try row.set("isLiked", isLikedPost)
try row.set("isNew", isNew)
try row.set(Field.likes, likes())
try row.set(Field.unlikes, unLikes())
try row.set("author", author.get()?.makeJSON())
try row.set("category", category.get()?.makeRow())
try row.set("createdAt", created_at)
try row.set("updatedAt", updatedAt)
return row
}
var author: Parent<Post,User> {
return parent(id: user_id)
}
var category: Parent<Post,Category> {
return parent(id: category_id)
}
var created_at: String {
let dateFor = DateFormatter()
dateFor.dateFormat = "yyyy-MM-dd || h:mm a"
return dateFor.string(from: self.createdAt!)
}
var isNew: Bool {
return NSCalendar.current.isDateInToday(createdAt!)
}
func likes() throws -> Int {
let allLikes = try Like.makeQuery().filter("post_id", id).all()
return allLikes.filter { (like) -> Bool in
return like.type == true
}.count
}
func unLikes() throws -> Int {
let allUnLikes = try Like.makeQuery().filter("post_id", id).all()
return allUnLikes.filter { (like) -> Bool in
return like.type == false
}.count
}
}
extension Post {
func isLiked(user: User?) throws {
let likes = try Like.makeQuery().filter("post_id", self.id).filter("user_id", user?.id).first()
if likes == nil {
isLikedPost = 0
} else {
isLikedPost = likes!.type ? 1 : 2
}
}
}
extension Post {
}
extension Post {
enum Field: String {
case id
case title
case content
case user_id
case category_id
case is_published
case likes
case unlikes
}
}
| 27.160428 | 103 | 0.581414 |
265df70506d08bc894c0b3fa9b2ee575b280c50c | 1,520 | //
// MGNetworkDetectUtils.swift
// MGBaseSwift
//
// Created by Magical Water on 2018/3/26.
// Copyright © 2018年 Magical Water. All rights reserved.
//
import Foundation
import Reachability
//網路狀態檢測
public class MGNetworkDetectUtils {
private let reachability = Reachability()!
weak var networkDelegate: MGNetworkDetectDelegate?
//此參數獲取當前網路狀態
public var status: NetworkStatus {
get {
switch reachability.connection {
case .wifi: return .wifi
case .cellular: return .cellular
case .none: return .none
}
}
}
public init() {}
//Cellular: 表示「行動通訊」的功能,也就是擁有 3G 以及 4G 這類的行動上網能力!
public enum NetworkStatus {
case wifi
case cellular
case none
}
//開始檢測, 在得到網路狀態之前會先傳一次當前狀態
public func start() {
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
}
//停止檢測
public func stop() {
NotificationCenter.default.removeObserver(self)
}
deinit {
stop()
}
@objc private func reachabilityChanged() {
networkDelegate?.networkStatusChange(status)
}
}
//網路檢測回調
public protocol MGNetworkDetectDelegate : class {
func networkStatusChange(_ status: MGNetworkDetectUtils.NetworkStatus)
}
| 21.408451 | 144 | 0.638816 |
4813b26b4eb650567504f625b566fcd721ed0f13 | 3,505 | //
// MBProgressHUD+Extension.swift
// Pods
//
// Created by Icy on 2017/1/10.
//
//
import UIKit
import NVActivityIndicatorView
import RxSwift
import RxCocoa
import MBProgressHUD
public enum loadingType {
///自定义loadingview
case customView(loadingView:UIView)
///NVActivityIndicatorType类型的view
case activityIndicatorType(type:NVActivityIndicatorType)
}
extension MBProgressHUD{
/**
加载动画
*/
public static func eme_showHUD(_ view:UIView) -> MBProgressHUD {
let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.mode = .customView
hud.bezelView.color = UIColor.clear
hud.backgroundColor = UIColor.white
return hud
}
public static func eme_showActivityIndicator(_ view:UIView , type:NVActivityIndicatorType = .ballScaleMultiple) -> MBProgressHUD {
let hud = MBProgressHUD.showAdded(to: view, animated: true)
let loading = NVActivityIndicatorView(frame: CGRect(x: view.center.x, y: view.center.y, width: 50, height: 50), type:type ,color:TSwiftCore.loadingBgColor)
loading.startAnimating()
hud.mode = .customView
hud.bezelView.color = UIColor.clear
hud.customView = loading
hud.backgroundColor = UIColor.white
return hud
}
/// 显示自定义的动画
///
/// - Parameters:
/// - view: 在哪个view上显示动画
/// - customView: 自定义的动画
/// - Returns:
public static func eme_showCustomIndicator(_ view:UIView) -> MBProgressHUD {
let hud = MBProgressHUD.showAdded(to: view, animated: true)
switch TSwiftCore.loadingView {
case let .activityIndicatorType(type):
let loading = NVActivityIndicatorView(frame: CGRect(x: view.center.x, y: view.center.y, width: 50, height: 50), type:type ,color:TSwiftCore.loadingBgColor)
loading.startAnimating()
hud.mode = .customView
hud.bezelView.color = UIColor.clear
hud.customView = loading
hud.backgroundColor = UIColor.white
return hud
case let .customView(loading):
let subloading = UIView(frame: CGRect(x: view.center.x, y: view.center.y, width: 50, height: 50))
subloading.addSubview(loading)
hud.mode = .customView
hud.bezelView.color = UIColor.clear
hud.customView = subloading
hud.backgroundColor = TSwiftCore.loadingBgColor
return hud
}
}
/**
隐藏动画
*/
public static func eme_hideHUD(_ view:UIView) -> Bool {
let subViews = view.subviews.reversed()
var hud:MBProgressHUD?
for subView in subViews{
if subView.isKind(of:MBProgressHUD.self){
hud = subView as? MBProgressHUD
}
}
if let hud = hud {
hud.removeFromSuperViewOnHide = true
hud.hide(animated: true)
return true
}else{
return false
}
}
}
extension UIView{
public func showLoading() {
_ = MBProgressHUD.eme_hideHUD(self)
_ = MBProgressHUD.eme_showCustomIndicator(self)
}
public func hideLoading() {
_ = MBProgressHUD.eme_hideHUD(self)
}
/// 绑定显示进度条
public var rx_loading: AnyObserver<Bool> {
return Binder(self) { view, isloading in
if isloading {
view.showLoading()
}else{
view.hideLoading()
}
}.asObserver()
}
}
| 31.576577 | 167 | 0.613409 |
f78dfde47979c58305c344763953e8b0e8597437 | 713 | //
// SettingsViewCell.swift
// Thunderboard
//
// Copyright © 2016 Silicon Labs. All rights reserved.
//
import UIKit
class SettingsViewCell : UITableViewCell {
var drawBottomSeparator: Bool = false
override func draw(_ rect: CGRect) {
super.draw(rect)
if drawBottomSeparator {
let path = UIBezierPath()
let lineWidth: CGFloat = 1.0
path.move(to: CGPoint(x: 15, y: rect.size.height - lineWidth))
path.addLine(to: CGPoint(x: rect.width, y: rect.size.height - lineWidth))
path.lineWidth = lineWidth
StyleColor.lightGray.setStroke()
path.stroke()
}
}
}
| 23.766667 | 85 | 0.576438 |
6213881c7948e6ae46afae9cdbb63a967c97d53a | 1,141 | /*
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Solution {
func isUnivalTree(_ root: TreeNode?) -> Bool {
if root == nil {
return true
}
var result = true
if root?.left != nil {
result = result && (root?.left?.val == root?.val)
}
if root?.right != nil {
result = result && (root?.right?.val == root?.val)
}
return result && isUnivalTree(root?.right) && isUnivalTree(root?.left)
}
}
| 22.372549 | 78 | 0.527607 |
75aadfa2c3e878ca54befcbfc5cbbec973f19faa | 286 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func < {
class A {
struct Q< " " {
struct B
class B : a {
func a<T> : T
deinit {
protocol b {
func T
typealias e : e
| 19.066667 | 87 | 0.699301 |
e51abf12822574c0d2f87ffbdd1572070cc402da | 1,420 | // --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ""Software""), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// --------------------------------------------------------------------------
import Foundation
public protocol TestSettingsProtocol: AnyObject, Codable {
init()
}
| 44.375 | 79 | 0.675352 |
226c25ac73b4d3312e66a5a05cb7bf2717173fd9 | 2,297 | //
// CityFeaturesView.swift
// Weather
//
// Created by Olesya Nikolaeva on 22.12.2021.
// Copyright © 2021 Olesya Nikolaeva. All rights reserved.
//
import SwiftUI
struct CityFeaturesView: View {
@ObservedObject var city: City
var humidity: String {
guard let humidity = city.weather?.current.humidity else {
return "- %"
}
return String(Int(humidity)) + "%"
}
var visibility: String {
guard let visibility = city.weather?.current.visibility else {
return "- km"
}
return String(visibility / 1000) + " km"
}
var feelslike: String {
guard let feelslike = city.weather?.current.feels_like else {
return "-ºC"
}
return feelslike.formattedTemperature
}
var speed: String {
guard let speed = city.weather?.current.wind_speed else {
return "- m/s"
}
return String(speed) + " m/s"
}
var body: some View {
HStack(alignment: .center) {
VStack(alignment: .center, spacing: 5) {
Image(systemName: "drop")
.font(.body)
Text(humidity)
.font(.headline)
Text("Humidity")
.font(.footnote)
}
Spacer()
VStack(alignment: .center, spacing: 5) {
Image(systemName: "thermometer")
.font(.body)
Text(feelslike)
.font(.headline)
Text("Feels Like")
.font(.footnote)
}
Spacer()
VStack(alignment: .center, spacing: 5) {
Image(systemName: "wind")
.font(.body)
Text(speed)
.font(.headline)
Text("Speed")
.font(.footnote)
}
Spacer()
VStack(alignment: .center, spacing: 5) {
Image(systemName: "eye")
.font(.body)
Text(visibility)
.font(.headline)
Text("Visibility")
.font(.footnote)
}
}
.frame(height: 80)
}
}
| 27.023529 | 70 | 0.458424 |
90b228c52ffd2f4ebebc73fac2d3210a22e7812f | 196 | //
// Copyright © 2018 John Crossley. All rights reserved.
//
public typealias Next = (Any...) -> Void
public typealias Middleware = ( IncomingMessage, ServerResponse, @escaping Next ) -> Void
| 24.5 | 89 | 0.704082 |
4b02c1bc5c15ed9122cbe401e0cc4d1ff12a951a | 747 | //
// DataBase.swift
// OneDayOneAnswer
//
// Created by Jaedoo Ko on 2020/04/27.
// Copyright © 2020 JMJ. All rights reserved.
//
import Foundation
struct Article {
let id: Int
let date: Date
let question: String
var answer: String = ""
var imagePath: String = ""
}
protocol DataBase {
static var instance: DataBase { get }
func insertArticle(article: Article) -> Bool
func insertArticles(articles: [Article]) -> Bool
func selectArticle(date: Date) -> Article?
func selectArticles(string: String) -> [Article]
func selectArticles() -> [Article]
func updateArticle(article: Article) -> Bool
func deleteArticle(article: Article) -> Bool
func deleteArticle(id: Int) -> Bool
}
| 23.34375 | 52 | 0.658635 |
f76f8215012dea326f700119a481859156bf5a8d | 520 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path %t/ShadowsConcur.swiftmodule -module-name ShadowsConcur %S/Inputs/ShadowsConcur.swift
// RUN: %target-typecheck-verify-swift -I %t -enable-experimental-concurrency -disable-availability-checking
// REQUIRES: concurrency
import ShadowsConcur
@available(SwiftStdlib 5.5, *)
func f(_ t : UnsafeCurrentTask) -> Bool {
return t.someProperty == "123"
}
@available(SwiftStdlib 5.5, *)
func g(_: _Concurrency.UnsafeCurrentTask) {}
| 32.5 | 147 | 0.751923 |
33a137798be90df8d8d466984648b8c07cc3fc3f | 1,290 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency %import-libdispatch -parse-as-library) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// https://bugs.swift.org/browse/SR-14333
// UNSUPPORTED: OS=windows-msvc
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
protocol Go: Actor {
func go(times: Int) async -> Int
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension Go {
func go(times: Int) async -> Int {
for i in 0...times {
print("\(Self.self) @ \(i)")
await Task.yield()
}
return times
}
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
actor One: Go {}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
actor Two: Go {}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
func yielding() async {
let one = One()
let two = Two()
await withTaskGroup(of: Int.self) { group in
await group.spawn {
await one.go(times: 100)
}
await group.spawn {
await two.go(times: 100)
}
}
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@main struct Main {
static func main() async {
await yielding()
// TODO: No idea for a good test for this... Open to ideas?
// CHECK: Two @ 100
}
}
| 24.807692 | 131 | 0.647287 |
20075637534a47bc3864b30bf66486c4aa004948 | 249 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
protocol A {
typealias b
typealias F = A
protocol A {
typealias e = b
| 22.636364 | 87 | 0.751004 |
f77cf6a29865950cd52e38709809aec6f72bccc6 | 4,484 | //
// KingfisherOptionsInfoTests.swift
// Kingfisher
//
// Created by Wei Wang on 16/1/4.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Kingfisher
class KingfisherOptionsInfoTests: 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 testEmptyOptionsShouldParseCorrectly() {
let options = KingfisherEmptyOptionsInfo
XCTAssertTrue(options.targetCache === ImageCache.default)
XCTAssertTrue(options.downloader === ImageDownloader.default)
#if !os(macOS)
switch options.transition {
case .none: break
default: XCTFail("The transition for empty option should be .None. But \(options.transition)")
}
#endif
XCTAssertEqual(options.downloadPriority, URLSessionTask.defaultPriority)
XCTAssertFalse(options.forceRefresh)
XCTAssertFalse(options.cacheMemoryOnly)
XCTAssertFalse(options.backgroundDecode)
XCTAssertEqual(options.callbackDispatchQueue.label, DispatchQueue.main.label)
XCTAssertEqual(options.scaleFactor, 1.0)
}
func testSetOptionsShouldParseCorrectly() {
let cache = ImageCache(name: "com.onevcat.Kingfisher.KingfisherOptionsInfoTests")
let downloader = ImageDownloader(name: "com.onevcat.Kingfisher.KingfisherOptionsInfoTests")
#if os(macOS)
let transition = ImageTransition.none
#else
let transition = ImageTransition.fade(0.5)
#endif
let queue = DispatchQueue.global(qos: .default)
let testModifier = TestModifier()
let processor = RoundCornerImageProcessor(cornerRadius: 20)
let options: KingfisherOptionsInfo = [
.targetCache(cache),
.downloader(downloader),
.transition(transition),
.downloadPriority(0.8),
.forceRefresh,
.cacheMemoryOnly,
.onlyFromCache,
.backgroundDecode,
.callbackDispatchQueue(queue),
KingfisherOptionsInfoItem.scaleFactor(2.0),
.requestModifier(testModifier),
.processor(processor)
]
XCTAssertTrue(options.targetCache === cache)
XCTAssertTrue(options.downloader === downloader)
#if !os(macOS)
switch options.transition {
case .fade(let duration): XCTAssertEqual(duration, 0.5)
default: XCTFail()
}
#endif
XCTAssertEqual(options.downloadPriority, 0.8)
XCTAssertTrue(options.forceRefresh)
XCTAssertTrue(options.cacheMemoryOnly)
XCTAssertTrue(options.onlyFromCache)
XCTAssertTrue(options.backgroundDecode)
XCTAssertEqual(options.callbackDispatchQueue.label, queue.label)
XCTAssertEqual(options.scaleFactor, 2.0)
XCTAssertTrue(options.modifier is TestModifier)
XCTAssertEqual(options.processor.identifier, processor.identifier)
}
}
class TestModifier: ImageDownloadRequestModifier {
func modified(for request: URLRequest) -> URLRequest? {
return nil
}
}
| 37.057851 | 111 | 0.687333 |
bb146c92293f853d6b280c200c12cc18b229c5b0 | 2,288 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* specDomain: S10733 (C-0-T10720-S10725-S10733-cpt)
*/
public enum EPA_FdV_AUTHZ_GTSAbbreviationHolidaysUSNational:Int,CustomStringConvertible
{
case JHNUS
case JHNUSCLM
case JHNUSIND
case JHNUSIND1
case JHNUSIND5
case JHNUSLBR
case JHNUSMEM
case JHNUSMEM5
case JHNUSMEM6
case JHNUSMLK
case JHNUSPRE
case JHNUSTKS
case JHNUSTKS5
case JHNUSVET
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_GTSAbbreviationHolidaysUSNational?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_GTSAbbreviationHolidaysUSNational?
{
var i = 0
while let item = EPA_FdV_AUTHZ_GTSAbbreviationHolidaysUSNational(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case .JHNUS: return "JHNUS"
case .JHNUSCLM: return "JHNUSCLM"
case .JHNUSIND: return "JHNUSIND"
case .JHNUSIND1: return "JHNUSIND1"
case .JHNUSIND5: return "JHNUSIND5"
case .JHNUSLBR: return "JHNUSLBR"
case .JHNUSMEM: return "JHNUSMEM"
case .JHNUSMEM5: return "JHNUSMEM5"
case .JHNUSMEM6: return "JHNUSMEM6"
case .JHNUSMLK: return "JHNUSMLK"
case .JHNUSPRE: return "JHNUSPRE"
case .JHNUSTKS: return "JHNUSTKS"
case .JHNUSTKS5: return "JHNUSTKS5"
case .JHNUSVET: return "JHNUSVET"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 24.869565 | 99 | 0.542832 |
1ac39cab095254f1da0d66204b9b0474b38b3610 | 948 | import SourceryRuntime
enum EqualityGenerator {
static func generate(for types: Types) -> String {
return types.classes.map { $0.generateEquality() }.joined(separator: "\n")
}
}
extension Class {
func generateEquality() -> String {
let propertyComparisons = variables.map { $0.generateEquality() }.joined(separator: "\n ")
return """
extension \(name): Equatable {}
\(hasAnnotations())
func == (lhs: \(name), rhs: \(name)) -> Bool {
\(propertyComparisons)
return true
}
"""
}
func hasAnnotations() -> String {
guard annotations["showComment"] != nil else {
return ""
}
return """
// \(name) has Annotations
"""
}
}
extension Variable {
func generateEquality() -> String {
return "if lhs.\(name) != rhs.\(name) { return false }"
}
}
| 22.571429 | 101 | 0.524262 |
5de3d7079a471dce6bd8d5bbaee1d412c200925f | 2,006 | //
// UIBarButtonItem.swift
// Yyaoqi
//
// Created by 凑巧 on 2020/10/15.
//
import Foundation
import UIKit
extension UIBarButtonItem {
convenience init(title: String?,
titleColor: UIColor = .white,
titleFont: UIFont = UIFont.systemFont(ofSize: 15),
titleEdgeInsets: UIEdgeInsets = .zero,
target: Any?,
action: Selector?
) {
let button = UIButton(type: .system)
button.setTitle(title, for: .normal)
button.setTitleColor(titleColor, for: .normal)
button.titleLabel?.font = titleFont
button.titleEdgeInsets = titleEdgeInsets
if action != nil {
button.addTarget(target, action: action!, for: .touchUpInside)
}
button.sizeToFit()
if button.bounds.width < 40 || button.bounds.height > 40 {
let width = 40 / button.bounds.height * button.bounds.width;
button.bounds = CGRect(x: 0, y: 0, width: width, height: 40)
}
self.init(customView: button)
}
convenience init(image: UIImage?,
selectImage: UIImage? = nil,
imageEdgeInsets: UIEdgeInsets = .zero,
target: Any?,
action: Selector?) {
let button = UIButton(type: .system)
button.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
button.setImage(selectImage?.withRenderingMode(.alwaysOriginal), for: .selected)
button.imageEdgeInsets = imageEdgeInsets
if action != nil {
button.addTarget(target, action: action!, for: .touchUpInside)
}
button.sizeToFit()
if button.bounds.width < 40 || button.bounds.height > 40 {
let width = 40 / button.bounds.height * button.bounds.width;
button.bounds = CGRect(x: 0, y: 0, width: width, height: 40)
}
self.init(customView: button)
}
}
| 35.192982 | 88 | 0.567298 |
262f125d188bce00ddd33b7702a48d7bec900bb8 | 2,077 | //
// WalletHomeNavViewModel.swift
// ViteBusiness
//
// Created by Stone on 2019/3/5.
//
import ViteWallet
import RxSwift
import RxCocoa
class WalletHomeNavViewModel {
enum InfoType {
case wallet
case viteX
}
let walletNameDriver: Driver<String>
let priceDriver: Driver<(String, String)>
let isHidePriceDriver: Driver<Bool>
var infoTypeBehaviorRelay = BehaviorRelay<InfoType>(value: InfoType.wallet)
init(isHidePriceDriver: Driver<Bool>, walletHomeBalanceInfoTableViewModel: WalletHomeBalanceInfoTableViewModel) {
self.isHidePriceDriver = isHidePriceDriver
walletNameDriver = HDWalletManager.instance.walletDriver.filterNil().map({ $0.name })
priceDriver = Driver.combineLatest(
infoTypeBehaviorRelay.asDriver(),
isHidePriceDriver,
ExchangeRateManager.instance.rateMapDriver,
walletHomeBalanceInfoTableViewModel.balanceInfosDriver,
walletHomeBalanceInfoTableViewModel.viteXBalanceInfosDriver)
.map({ (infoType,isHidePrice, rateMap, balanceInfos, viteXBalanceInfos) -> (String, String) in
if isHidePrice {
return ("****", "****")
} else {
let btcValuation: BigDecimal
switch infoType {
case .wallet:
btcValuation = balanceInfos.map { $0.tokenInfo.btcValuationForBasicUnit(amount: $0.balance)}.reduce(BigDecimal(), +)
case .viteX:
btcValuation = viteXBalanceInfos.map { $0.tokenInfo.btcValuationForBasicUnit(amount: $0.balanceInfo.total)}.reduce(BigDecimal(), +)
}
let btcString = BigDecimalFormatter.format(bigDecimal: btcValuation, style: .decimalRound(8), padding: .none, options: [.groupSeparator])
let priceString = "≈" + ExchangeRateManager.instance.rateMap.btcPriceString(btc: btcValuation)
return (btcString, priceString)
}
})
}
}
| 41.54 | 157 | 0.632162 |
ac8a8ae8ab7c0f56a9ed4fe2a0e11c3653bb0425 | 1,353 | //
// AppDelegate.swift
// WeeklyFinder
//
// Created by Павел Попов on 11.02.2021.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.567568 | 179 | 0.746489 |
269658299654af936676f1f0b28bb8b4124dbb37 | 1,559 | //
// iTunesRequest.swift
// IPATool
//
// Created by Majd Alfhaily on 22.05.21.
//
import ArgumentParser
enum iTunesRequest {
case search(term: String, limit: Int, country: String, deviceFamily: DeviceFamily = .phone)
case lookup(bundleIdentifier: String, country: String, deviceFamily: DeviceFamily = .phone)
}
extension iTunesRequest {
enum DeviceFamily: String, ExpressibleByArgument {
case phone = "iPhone"
case pad = "iPad"
var defaultValueDescription: String {
return rawValue
}
var entity: String {
switch self {
case .phone:
return "software"
case .pad:
return "iPadSoftware"
}
}
}
}
extension iTunesRequest: HTTPRequest {
var method: HTTPMethod {
return .get
}
var endpoint: HTTPEndpoint {
switch self {
case .lookup:
return iTunesEndpoint.lookup
case .search:
return iTunesEndpoint.search
}
}
var payload: HTTPPayload? {
switch self {
case let .lookup(bundleIdentifier, country, deviceFamily):
return .urlEncoding(["media": "software", "bundleId": bundleIdentifier, "limit": "1", "country": country, "entity": deviceFamily.entity])
case let .search(term, limit, country, deviceFamily):
return .urlEncoding(["media": "software", "term": term, "limit": "\(limit)", "country": country, "entity": deviceFamily.entity])
}
}
}
| 26.87931 | 149 | 0.586915 |
fb5c6a65564ff6b58e28aa4994ef764ad688207e | 2,578 | //
// StatefulCollectionController.swift
// StatefulDataViewExample
//
// Created by Sinar Nirmata on 30/09/20.
// Copyright © 2020 Sinar Nirmata. All rights reserved.
//
import StatefulDataView
import UIKit
class StatefulCollectionController: UIViewController {
@IBOutlet private var collectionView: StatefulCollectionView?
private let fetcher = Fetcher()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionView?.errorView = ErrorView(text: "Oops!", button: "Try Again")
collectionView?.emptyView = EmptyView(text: "No Data")
collectionView?.loadingView = LoadingView()
collectionView?.setState(.empty)
collectionView?.register(UINib(nibName: "ItemCollectionCell", bundle: nil), forCellWithReuseIdentifier: "ItemCollectionCell")
collectionView?.cellItemSize = CGSize(width: (collectionView!.frame.width - 12) / 2, height: 200)
collectionView?.cellItemHandler = { indexPath in
let cell = self.collectionView?.dequeueReusableCell(withReuseIdentifier: "ItemCollectionCell", for: indexPath) as! ItemCollectionCell
let item = self.fetcher.items[indexPath.row]
cell.configure(title: item.title,
author: item.author,
date: item.dateTaken,
image: item.media)
return cell
}
collectionView?.cellItemSelectionHandler = { cell, indexPath in
guard let cell = cell as? ItemCollectionCell else { return }
print(cell)
}
collectionView?.setRefreshControl({ rc in
self.fetcher.execute { photos in
let items = photos ?? []
DispatchQueue.main.async {
rc.endRefreshing()
self.collectionView?.setState(.populated(items))
}
}
})
}
@IBAction
func setError() {
collectionView?.setState(.error(nil))
}
@IBAction
func setEmpty() {
collectionView?.setState(.empty)
}
@IBAction
func setPopulated() {
collectionView?.setState(.loading)
fetcher.execute { photos in
let items = photos ?? []
DispatchQueue.main.async {
self.collectionView?.setState(.populated(items))
}
}
}
@IBAction
func setDismiss() {
dismiss(animated: true, completion: nil)
}
}
| 32.225 | 145 | 0.595811 |
eb27c873f50672245020771c0673840e4e91cd70 | 2,467 | //
// WebViewController+UIDelegate.swift
// WKJoint
//
// Created by Mgen on 21/12/17.
// Copyright © 2017 Mgen. All rights reserved.
//
import UIKit
import WebKit
extension WebViewController: WKUIDelegate {
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping () -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
completionHandler()
}))
present(alertController, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(false)
}))
present(alertController, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping (String?) -> Void) {
let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.text = defaultText
}
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
if let text = alertController.textFields?.first?.text {
completionHandler(text)
} else {
completionHandler(defaultText)
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(nil)
}))
present(alertController, animated: true, completion: nil)
}
}
| 36.279412 | 151 | 0.633563 |
fe1510cfbd3cd6864261c2af621b7be4b083aabc | 1,276 | import Foundation
extension WMFArticle {
@objc public var capitalizedWikidataDescriptionOrSnippet: String? {
guard let wikidataDescription = capitalizedWikidataDescription, !wikidataDescription.isEmpty else {
return snippet
}
return wikidataDescription
}
public var hasChangedValuesForCurrentEventThatAffectPreviews: Bool {
let previewKeys: Set<String> = ["wikidataDescription", "snippet", "imageURLString"]
return hasChangedValuesForCurrentEventForKeys(previewKeys)
}
@objc public var hasChangedValuesForCurrentEventThatAffectSavedArticlesFetch: Bool {
let previewKeys: Set<String> = ["savedDate", "isDownloaded"]
return hasChangedValuesForCurrentEventForKeys(previewKeys)
}
@objc public var hasChangedValuesForCurrentEventThatAffectSavedState: Bool {
let previewKeys: Set<String> = ["savedDate"]
return hasChangedValuesForCurrentEventForKeys(previewKeys)
}
public var hasChangedValuesForCurrentEventThatAffectSavedArticlePreviews: Bool {
let previewKeys: Set<String> = ["wikidataDescription", "snippet", "imageURLString", "isDownloaded", "readingLists"]
return hasChangedValuesForCurrentEventForKeys(previewKeys)
}
}
| 41.16129 | 123 | 0.739812 |
f494eb672e3e2a8558b1b2f041890c7b00c84116 | 2,481 | //
// AppDelegate.swift
// Sample
//
// Created by Sam Mejlumyan on 13.08.2020.
// Copyright © 2020 Qonversion Inc. All rights reserved.
//
import UIKit
import Qonversion
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Qonversion.setDebugMode()
Qonversion.launch(withKey: "PV77YHL7qnGvsdmpTs7gimsxUvY-Znl2")
Qonversion.setPromoPurchasesDelegate(self)
Qonversion.setAppleSearchAdsAttributionEnabled(true)
registerForNotifications()
return true
}
func registerForNotifications() {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }
UIApplication.shared.registerForRemoteNotifications()
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("error: \(error)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Qonversion.setNotificationsToken(deviceToken)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let isPushHandled: Bool = Qonversion.handleNotification(response.notification.request.content.userInfo)
if !isPushHandled {
// Qonversion can not handle this push.
}
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}
extension AppDelegate: QNPromoPurchasesDelegate {
func shouldPurchasePromoProduct(withIdentifier productID: String, executionBlock: @escaping Qonversion.PromoPurchaseCompletionHandler) {
// check productID value in case if you want to enable promoted purchase only for specific products
let compeltion: Qonversion.PurchaseCompletionHandler = {result, error, flag in
// handle purchased product or error
}
executionBlock(compeltion)
}
}
| 33.986301 | 205 | 0.76582 |
bf5c0e0dfafc0f8d704cae017542a589c431708a | 978 | //
// DNSQLiteDemoTests.swift
// DNSQLiteDemoTests
//
// Created by mainone on 16/10/26.
// Copyright © 2016年 wjn. All rights reserved.
//
import XCTest
@testable import DNSQLiteDemo
class DNSQLiteDemoTests: 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.432432 | 111 | 0.637014 |
1117b4f35e32027632697101d827e79f4e8f8070 | 1,878 | //
// TextToEmojiMapping.swift
// EmojiTextView
//
// Created by Arkadiusz Holko on 19/07/16.
// Copyright © 2016 Arkadiusz Holko. All rights reserved.
//
import Foundation
// Mapping of the regular text to emoji characters
public typealias TextToEmojiMapping = [String : [String]]
public func defaultTextToEmojiMapping() -> TextToEmojiMapping {
var mapping: TextToEmojiMapping = [:]
func addKey(_ key: String, value: String, atBeginning: Bool) {
// ignore short words because they're non-essential
guard key.lengthOfBytes(using: String.Encoding.utf8) > 2 else {
return
}
if mapping[key] == nil {
mapping[key] = []
}
if atBeginning {
mapping[key]?.insert(value, at: 0)
} else {
mapping[key]?.append(value)
}
}
guard let path = Bundle(for: EmojiController.self).path(forResource: "emojis", ofType: "json"),
let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let jsonDictionary = json as? NSDictionary else {
return [:]
}
for (key, value) in jsonDictionary {
if let key = key as? String,
let dictionary = value as? Dictionary<String, AnyObject>,
let emojiCharacter = dictionary["char"] as? String {
// Dictionary keys from emojis.json have higher priority then keywords.
// That's why they're added at the beginning of the array.
addKey(key, value: emojiCharacter, atBeginning: true)
if let keywords = dictionary["keywords"] as? [String] {
for keyword in keywords {
addKey(keyword, value: emojiCharacter, atBeginning: false)
}
}
}
}
return mapping
}
| 30.786885 | 99 | 0.601704 |
610279e97169da14cfac391b098889876b575d9a | 331 | //: [Previous](@previous)
import Foundation
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var table : [Int : Int] = [:]
for i in nums.indices {
if let j = table[nums[i]] {
return [j,i]
}
table[target-nums[i]] = i
}
return []
}
twoSum([2,7,11,15],9)
//: [Next](@next)
| 17.421053 | 52 | 0.489426 |
dd66ec2ebbb01d1276402174151fe0f409ae61d2 | 4,374 | //
// PopularMoviesInteractorTests.swift
// PopcornHub
//
// Created by Diego Escamilla on 01/08/21.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
@testable import PopcornHub
import XCTest
class PopularMoviesInteractorTests: XCTestCase {
// MARK: Subject under test
var sut: PopularMoviesInteractor!
var presenterSpy: PopularMoviesPresenterSpy!
// MARK: Test lifecycle
override func setUp() {
super.setUp()
setupPopularMoviesInteractor()
}
override func tearDown() {
super.tearDown()
}
// MARK: Test setup
func setupPopularMoviesInteractor() {
sut = PopularMoviesInteractor()
presenterSpy = PopularMoviesPresenterSpy()
sut.presenter = presenterSpy
}
// MARK: Tests
func testFetchPopularMovieSuccess() {
// Given
sut.worker = PopularMoviesWorkerSpy(.Success)
// When
sut.fetchPopularMovies()
// Then
DispatchQueue.main.async {
XCTAssert(self.presenterSpy.presentPopularMoviesCalled)
}
}
func testFetchPopularMovieFailure() {
// Given
sut.worker = PopularMoviesWorkerSpy(.Failure)
// When
sut.fetchPopularMovies()
// Then
DispatchQueue.main.async {
XCTAssert(self.presenterSpy.presentPopularMoviesCalled)
XCTAssertNotNil(self.presenterSpy.presentPopularMoviesResponse?.error)
XCTAssert(self.presenterSpy.presentPopularMoviesResponse?.mediaList.isEmpty ?? false)
}
}
func testFetchMovieSearchSuccess() {
// Given
sut.worker = PopularMoviesWorkerSpy(.Success)
let searchRequest = PopularMoviesModels.SearchMovieDetail.Request(searchString: "searchString")
// When
sut.fetchSearchMovies(request: searchRequest)
// Then
DispatchQueue.main.async {
XCTAssert(self.presenterSpy.presentPopularMoviesCalled)
XCTAssert(!(self.presenterSpy.presentPopularMoviesResponse?.mediaList.isEmpty ?? true))
XCTAssertNil(self.presenterSpy.presentPopularMoviesResponse?.error)
}
}
func testFetchMovieSearchFailure() {
// Given
sut.worker = PopularMoviesWorkerSpy(.Failure)
let searchRequest = PopularMoviesModels.SearchMovieDetail.Request(searchString: "searchString")
// When
sut.fetchSearchMovies(request: searchRequest)
// Then
DispatchQueue.main.async {
XCTAssert(self.presenterSpy.presentPopularMoviesCalled)
XCTAssert(self.presenterSpy.presentPopularMoviesResponse?.mediaList.isEmpty ?? false)
XCTAssertNotNil(self.presenterSpy.presentPopularMoviesResponse?.error)
}
}
}
// MARK: Test doubles
class PopularMoviesPresenterSpy: PopularMoviesPresenterInterface {
var presentPopularMoviesCalled = false
var presentPopularMoviesResponse: PopularMoviesModels.FetchPopularMovies.Response?
func presentPopularMovies(response: PopularMoviesModels.FetchPopularMovies.Response) {
presentPopularMoviesCalled = true
presentPopularMoviesResponse = response
}
var presentMovieDetailCalled = false
func presentMovieDetail() {
presentMovieDetailCalled = true
}
}
class PopularMoviesWorkerSpy: PopularMoviesWorkerInterface {
enum WorkerType {
case Success
case Failure
}
var type: WorkerType
init(_ type: WorkerType) {
self.type = type
}
func fetchPopularMovies(request: PopularMoviesModels.FetchPopularMovies.Request, completion: @escaping (Result<PopularMoviesResponse?, Error>) -> Void) {
switch type {
case .Success:
let response = Dummies.Common.getPopularMoviesResponse()
completion(.success(response))
case .Failure:
completion(.failure(Dummies.Common.error))
}
}
func fetchCachePopularMovies(completion: @escaping ([MediaResult]) -> Void) {
let mediaList = Dummies.Common.getMediaList()
completion(mediaList)
}
func fetchMovieSearch(request: PopularMoviesModels.SearchMovieDetail.Request, completion: @escaping (Result<PopularMoviesResponse?, Error>) -> Void) {
switch type {
case .Success:
let response = Dummies.Common.getPopularMoviesResponse()
completion(.success(response))
case .Failure:
completion(.failure(Dummies.Common.error))
}
}
func savePopularMoviesCache(request: PopularMoviesModels.CachePopularMovies.Request, completion: @escaping (Bool) -> Void) {
completion(true)
}
}
| 27.167702 | 154 | 0.741655 |
03f9b5c493f1a97b730fcd7dca99748ee3d7391c | 4,906 | import Foundation
import XCTest
import FileCheck
@testable import MinSwiftKit
final class Practice7: ParserTestCase {
// 7-1
func testParsingComparisonOperator() {
load("a < b + 20")
// lhs: a
// rhs:
// lhs: b
// rhs: 20
// operator: +
// operator: <
let node = parser.parseExpression()
XCTAssertTrue(node is BinaryExpressionNode)
let comparison = node as! BinaryExpressionNode
XCTAssertTrue(comparison.lhs is VariableNode)
XCTAssertTrue(comparison.rhs is BinaryExpressionNode)
let rhsNode = comparison.rhs as! BinaryExpressionNode
XCTAssertTrue(rhsNode.lhs is VariableNode)
XCTAssertTrue(rhsNode.rhs is NumberNode)
XCTAssertEqual(rhsNode.operator, .addition)
}
// 7-2
func testParsingIfElse() {
load("""
if a < 10 {
foo(a: a)
} else {
foo(a: a + 10)
}
""")
let node = parser.parseIfElse()
let ifNode = node as! IfElseNode
XCTAssertTrue(ifNode.condition is BinaryExpressionNode)
let condition = ifNode.condition as! BinaryExpressionNode
XCTAssertTrue(condition.lhs is VariableNode)
XCTAssertTrue(condition.rhs is NumberNode)
let thenBlock = ifNode.then
XCTAssertTrue(thenBlock is CallExpressionNode)
XCTAssertEqual((thenBlock as! CallExpressionNode).callee, "foo")
let elseBlock = ifNode.else
XCTAssertTrue(elseBlock is CallExpressionNode)
XCTAssertEqual((elseBlock as! CallExpressionNode).callee, "foo")
}
// 7-3
func testGenerateCompOperator() {
let variableNode = VariableNode(identifier: "a")
let numberNode = NumberNode(value: 10)
let body = BinaryExpressionNode(.lessThan, lhs: variableNode, rhs: numberNode)
let node = FunctionNode(name: "main",
arguments: [.init(label: nil, variableName: "a")],
returnType: .double,
body: body)
let buildContext = BuildContext()
build([node], context: buildContext)
XCTAssertTrue(fileCheckOutput(of: .stderr, withPrefixes: ["CompOperator"]) {
// CompOperator: ; ModuleID = 'main'
// CompOperator-NEXT: source_filename = "main"
// CompOperator: define double @main(double) {
// CompOperator-NEXT: entry:
// CompOperator-NEXT: %cmptmp = fcmp olt double %0, 1.000000e+01
// CompOperator-NEXT: %1 = sitofp i1 %cmptmp to double
// CompOperator-NEXT: ret double %1
// CompOperator-NEXT: }
buildContext.dump()
})
}
// 7-4
func testGenerateIfElse() {
let variableNode = VariableNode(identifier: "a")
let numberNode = NumberNode(value: 10)
let condition = BinaryExpressionNode(.lessThan, lhs: variableNode, rhs: numberNode)
let elseBlock = NumberNode(value: 42)
let thenBlock = NumberNode(value: 142)
let ifElseNode = IfElseNode(condition: condition, then: thenBlock, else: elseBlock)
let globalFunctionNode = FunctionNode(name: "main",
arguments: [.init(label: nil, variableName: "a")],
returnType: .double,
body: ifElseNode)
let buildContext = BuildContext()
build([globalFunctionNode], context: buildContext)
XCTAssertTrue(fileCheckOutput(of: .stderr, withPrefixes: ["IfElse"]) {
// IfElse: ; ModuleID = 'main'
// IfElse-NEXT: source_filename = "main"
// IfElse: define double @main(double) {
// IfElse-NEXT: entry:
// IfElse-NEXT: %cmptmp = fcmp olt double %0, 1.000000e+01
// IfElse-NEXT: %1 = sitofp i1 %cmptmp to double
// IfElse-NEXT: %ifcond = fcmp one double %1, 0.000000e+00
// IfElse-NEXT: %local = alloca double
// IfElse-NEXT: br i1 %ifcond, label %then, label %else
//
// IfElse: then: ; preds = %entry
// IfElse-NEXT: br label %merge
//
// IfElse: else: ; preds = %entry
// IfElse-NEXT: br label %merge
//
// IfElse: merge: ; preds = %else, %then
// IfElse-NEXT: %phi = phi double [ 1.420000e+02, %then ], [ 4.200000e+01, %else ]
// IfElse-NEXT: store double %phi, double* %local
// IfElse-NEXT: ret double %phi
// IfElse-NEXT: }
buildContext.dump()
})
}
}
| 39.564516 | 99 | 0.544028 |
87a0d40b78c7734cf0f4f48c2cdeefc85d51a3da | 919 | //
// TwitterAuthAdaper.swift
// AdapterPatternd
//
// Created by Evgeniy Ryshkov on 25/01/2019.
// Copyright © 2019 Evgeniy Ryshkov. All rights reserved.
//
import Foundation
class TwitterAuthAdapter: AuthService {
private var authenticator = TwitterAuth()
public func login(email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void) {
authenticator.login(email: email, password: password) { (currentUser, error) in
guard let currentUser = currentUser else {
failure(error)
return
}
let user = User(email: currentUser.email, password: currentUser.password)
let token = Token(value: currentUser.token)
success(user, token)
}
}
}
| 27.848485 | 87 | 0.558215 |
08495216c882a3efaefa43a9670e5a8340045903 | 1,478 | //
// Tree.swift
// RIBsTreeViewerClient
//
// Created by sondt on 8/10/20.
// Copyright © 2020 minipro. All rights reserved.
//
import Foundation
public class TreeNode<T: Equatable> {
public var value: T
public weak var parent: TreeNode?
public var children = [TreeNode<T>]()
public init(value: T) {
self.value = value
}
public func addChild(_ node: TreeNode<T>) {
children.append(node)
node.parent = self
}
public func detacChild(_ node: TreeNode<T>) {
guard let index = (children.firstIndex { $0.value == node.value }) else { return }
let removedNode = children.remove(at: index)
removedNode.parent = nil
}
public func search(_ value: T) -> TreeNode? {
if value == self.value {
return self
}
for child in children {
if let found = child.search(value) {
return found
}
}
return nil
}
}
extension TreeNode: Encodable where T: RIBNodeType {
enum CodingKeys: String, CodingKey {
case id
case name = "text"
case children
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value.nodeId, forKey: .id)
try container.encode(value.name, forKey: .name)
try container.encode(children, forKey: .children)
}
}
| 24.633333 | 90 | 0.583897 |
71b64d9949e6b9df35ca4df30163a86434e74f22 | 1,587 | import Foundation
let buildPath = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Fixtures/build")
func makeTemporaryFile(suffix: String) -> (URL, FileHandle) {
let tempdir = URL(fileURLWithPath: NSTemporaryDirectory())
let templatePath = tempdir.appendingPathComponent("wasm-transformer.XXXXXX\(suffix)")
var template = [UInt8](templatePath.path.utf8).map { Int8($0) } + [Int8(0)]
let fd = mkstemps(&template, Int32(suffix.utf8.count))
if fd == -1 {
fatalError("Failed to create temp directory")
}
let url = URL(fileURLWithPath: String(cString: template))
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
return (url, handle)
}
let bundleJSPath = buildPath.appendingPathComponent("bundle.js")
func createCheckHtml(embedding binaryPath: URL) throws -> String {
let wasmBytes = try Data(contentsOf: binaryPath)
return try """
<script>
\(String(contentsOf: bundleJSPath))
function base64ToUint8Array(base64Str) {
const raw = atob(base64Str);
return Uint8Array.from(Array.prototype.map.call(raw, (x) => {
return x.charCodeAt(0);
}));
}
const wasmBytes = base64ToUint8Array(\"\(wasmBytes.base64EncodedString())\")
</script>
"""
}
import WasmTransformer
extension InputByteStream {
init(from url: URL) throws {
let bytes = try Array(Data(contentsOf: url))
self.init(bytes: bytes)
}
}
| 32.387755 | 89 | 0.6862 |
4673c0cac9c6e3401c44e25ab90da1e419b763c0 | 995 | //
// PromiseKitDemoTests.swift
// PromiseKitDemoTests
//
// Created by Zsolt Bencze on 31/01/2017.
// Copyright © 2017 iSylva. All rights reserved.
//
import XCTest
@testable import PromiseKitDemo
class PromiseKitDemoTests: 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.891892 | 111 | 0.642211 |
fc3444a0b3ac6fdc83694b49a77d55b952181ce3 | 45,560 | //===----------------------------------------------------------------------===//
//
// 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.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
let crlf: StaticString = "\r\n"
let headerSeparator: StaticString = ": "
/// A representation of the request line and header fields of a HTTP request.
public struct HTTPRequestHead: Equatable {
/// The HTTP method for this request.
public let method: HTTPMethod
// Internal representation of the URI.
private let rawURI: URI
/// The URI used on this request.
public var uri: String {
return String(uri: rawURI)
}
/// The version for this HTTP request.
public let version: HTTPVersion
/// The header fields for this HTTP request.
public var headers: HTTPHeaders
/// Create a `HTTPRequestHead`
///
/// - Parameter version: The version for this HTTP request.
/// - Parameter method: The HTTP method for this request.
/// - Parameter uri: The URI used on this request.
public init(version: HTTPVersion, method: HTTPMethod, uri: String) {
self.init(version: version, method: method, rawURI: .string(uri), headers: HTTPHeaders())
}
/// Create a `HTTPRequestHead`
///
/// - Parameter version: The version for this HTTP request.
/// - Parameter method: The HTTP method for this request.
/// - Parameter rawURI: The URI used on this request.
/// - Parameter headers: The headers for this HTTP request.
init(version: HTTPVersion, method: HTTPMethod, rawURI: URI, headers: HTTPHeaders) {
self.version = version
self.method = method
self.rawURI = rawURI
self.headers = headers
}
public static func ==(lhs: HTTPRequestHead, rhs: HTTPRequestHead) -> Bool {
return lhs.method == rhs.method && lhs.uri == rhs.uri && lhs.version == rhs.version && lhs.headers == rhs.headers
}
}
/// Internal representation of a URI
enum URI {
case string(String)
case byteBuffer(ByteBuffer)
}
private extension String {
init(uri: URI) {
switch uri {
case .string(let string):
self = string
case .byteBuffer(let buffer):
self = buffer.getString(at: buffer.readerIndex, length: buffer.readableBytes)!
}
}
}
/// The parts of a complete HTTP message, either request or response.
///
/// A HTTP message is made up of a request or status line with several headers,
/// encoded by `.head`, zero or more body parts, and optionally some trailers. To
/// indicate that a complete HTTP message has been sent or received, we use `.end`,
/// which may also contain any trailers that make up the mssage.
public enum HTTPPart<HeadT: Equatable, BodyT: Equatable> {
case head(HeadT)
case body(BodyT)
case end(HTTPHeaders?)
}
extension HTTPPart: Equatable {
public static func ==(lhs: HTTPPart, rhs: HTTPPart) -> Bool {
switch (lhs, rhs) {
case (.head(let h1), .head(let h2)):
return h1 == h2
case (.body(let b1), .body(let b2)):
return b1 == b2
case (.end(let h1), .end(let h2)):
return h1 == h2
case (.head, _), (.body, _), (.end, _):
return false
}
}
}
/// The components of a HTTP request from the view of a HTTP client.
public typealias HTTPClientRequestPart = HTTPPart<HTTPRequestHead, IOData>
/// The components of a HTTP request from the view of a HTTP server.
public typealias HTTPServerRequestPart = HTTPPart<HTTPRequestHead, ByteBuffer>
/// The components of a HTTP response from the view of a HTTP client.
public typealias HTTPClientResponsePart = HTTPPart<HTTPResponseHead, ByteBuffer>
/// The components of a HTTP response from the view of a HTTP server.
public typealias HTTPServerResponsePart = HTTPPart<HTTPResponseHead, IOData>
extension HTTPRequestHead {
/// Whether this HTTP request is a keep-alive request: that is, whether the
/// connection should remain open after the request is complete.
public var isKeepAlive: Bool {
guard let connection = headers["connection"].first?.lowercased() else {
// HTTP 1.1 use keep-alive by default if not otherwise told.
return version.major == 1 && version.minor == 1
}
if connection == "close" {
return false
}
return connection == "keep-alive"
}
}
/// A representation of the status line and header fields of a HTTP response.
public struct HTTPResponseHead: Equatable {
/// The HTTP response status.
public let status: HTTPResponseStatus
/// The HTTP version that corresponds to this response.
public let version: HTTPVersion
/// The HTTP headers on this response.
public var headers: HTTPHeaders
/// Create a `HTTPResponseHead`
///
/// - Parameter version: The version for this HTTP response.
/// - Parameter status: The status for this HTTP response.
/// - Parameter headers: The headers for this HTTP response.
public init(version: HTTPVersion, status: HTTPResponseStatus, headers: HTTPHeaders = HTTPHeaders()) {
self.version = version
self.status = status
self.headers = headers
}
public static func ==(lhs: HTTPResponseHead, rhs: HTTPResponseHead) -> Bool {
return lhs.status == rhs.status && lhs.version == rhs.version && lhs.headers == rhs.headers
}
}
/// The Index for a header name or value that points into the underlying `ByteBuffer`.
struct HTTPHeaderIndex {
let start: Int
let length: Int
}
/// Struct which holds name, value pairs.
struct HTTPHeader {
let name: HTTPHeaderIndex
let value: HTTPHeaderIndex
}
private extension ByteBuffer {
func equalCaseInsensitiveASCII(view: String.UTF8View, at index: HTTPHeaderIndex) -> Bool {
guard view.count == index.length else {
return false
}
return withVeryUnsafeBytes { buffer in
// This should never happens as we control when this is called. Adding an assert to ensure this.
assert(index.start <= self.capacity - index.length)
let address = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self)
for (idx, byte) in view.enumerated() {
guard byte.isASCII && address.advanced(by: index.start + idx).pointee & 0xdf == byte & 0xdf else {
return false
}
}
return true
}
}
}
private extension UInt8 {
var isASCII: Bool {
return self <= 127
}
}
/// A representation of a block of HTTP header fields.
///
/// HTTP header fields are a complex data structure. The most natural representation
/// for these is a sequence of two-tuples of field name and field value, both as
/// strings. This structure preserves that representation, but provides a number of
/// convenience features in addition to it.
///
/// For example, this structure enables access to header fields based on the
/// case-insensitive form of the field name, but preserves the original case of the
/// field when needed. It also supports recomposing headers to a maximally joined
/// or split representation, such that header fields that are able to be repeated
/// can be represented appropriately.
public struct HTTPHeaders: CustomStringConvertible {
// Because we use CoW implementations HTTPHeaders is also CoW
fileprivate var buffer: ByteBuffer
fileprivate var headers: [HTTPHeader]
fileprivate var continuous: Bool = true
/// Returns the `String` for the given `HTTPHeaderIndex`.
///
/// - parameters:
/// - idx: The index into the underlying storage.
/// - returns: The value.
private func string(idx: HTTPHeaderIndex) -> String {
return self.buffer.getString(at: idx.start, length: idx.length)!
}
/// Return all names.
fileprivate var names: [HTTPHeaderIndex] {
return self.headers.map { $0.name }
}
public var description: String {
var headersArray: [(String, String)] = []
headersArray.reserveCapacity(self.headers.count)
for h in self.headers {
headersArray.append((self.string(idx: h.name), self.string(idx: h.value)))
}
return headersArray.description
}
/// Constructor used by our decoder to construct headers without the need of converting bytes to string.
init(buffer: ByteBuffer, headers: [HTTPHeader]) {
self.buffer = buffer
self.headers = headers
}
/// Construct a `HTTPHeaders` structure.
///
/// - parameters
/// - headers: An initial set of headers to use to populate the header block.
/// - allocator: The allocator to use to allocate the underlying storage.
public init(_ headers: [(String, String)] = []) {
// Note: this initializer exists becuase of https://bugs.swift.org/browse/SR-7415.
// Otherwise we'd only have the one below with a default argument for `allocator`.
self.init(headers, allocator: ByteBufferAllocator())
}
/// Construct a `HTTPHeaders` structure.
///
/// - parameters
/// - headers: An initial set of headers to use to populate the header block.
/// - allocator: The allocator to use to allocate the underlying storage.
public init(_ headers: [(String, String)] = [], allocator: ByteBufferAllocator) {
// Reserve enough space in the array to hold all indices.
var array: [HTTPHeader] = []
array.reserveCapacity(headers.count)
self.init(buffer: allocator.buffer(capacity: 256), headers: array)
for (key, value) in headers {
self.add(name: key, value: value)
}
}
/// Add a header name/value pair to the block.
///
/// This method is strictly additive: if there are other values for the given header name
/// already in the block, this will add a new entry. `add` performs case-insensitive
/// comparisons on the header field name.
///
/// - Parameter name: The header field name. For maximum compatibility this should be an
/// ASCII string. For future-proofing with HTTP/2 lowercase header names are strongly
// recommended.
/// - Parameter value: The header field value to add for the given name.
public mutating func add(name: String, value: String) {
precondition(!name.utf8.contains(where: { !$0.isASCII }), "name must be ASCII")
let nameStart = self.buffer.writerIndex
let nameLength = self.buffer.write(string: name)!
self.buffer.write(staticString: headerSeparator)
let valueStart = self.buffer.writerIndex
let valueLength = self.buffer.write(string: value)!
self.headers.append(HTTPHeader(name: HTTPHeaderIndex(start: nameStart, length: nameLength), value: HTTPHeaderIndex(start: valueStart, length: valueLength)))
self.buffer.write(staticString: crlf)
}
/// Add a header name/value pair to the block, replacing any previous values for the
/// same header name that are already in the block.
///
/// This is a supplemental method to `add` that essentially combines `remove` and `add`
/// in a single function. It can be used to ensure that a header block is in a
/// well-defined form without having to check whether the value was previously there.
/// Like `add`, this method performs case-insensitive comparisons of the header field
/// names.
///
/// - Parameter name: The header field name. For maximum compatibility this should be an
/// ASCII string. For future-proofing with HTTP/2 lowercase header names are strongly
// recommended.
/// - Parameter value: The header field value to add for the given name.
public mutating func replaceOrAdd(name: String, value: String) {
self.remove(name: name)
self.add(name: name, value: value)
}
/// Remove all values for a given header name from the block.
///
/// This method uses case-insensitive comparisons for the header field name.
///
/// - Parameter name: The name of the header field to remove from the block.
public mutating func remove(name: String) {
guard !self.headers.isEmpty else {
return
}
let utf8 = name.utf8
var array: [Int] = []
// We scan from the back to the front so we can remove the subranges with as less overhead as possible.
for idx in stride(from: self.headers.count - 1, to: -1, by: -1) {
let header = self.headers[idx]
if self.buffer.equalCaseInsensitiveASCII(view: utf8, at: header.name) {
array.append(idx)
}
}
guard !array.isEmpty else {
return
}
array.forEach {
self.headers.remove(at: $0)
}
self.continuous = false
}
/// Retrieve all of the values for a give header field name from the block.
///
/// This method uses case-insensitive comparisons for the header field name. It
/// does not return a maximally-decomposed list of the header fields, but instead
/// returns them in their original representation: that means that a comma-separated
/// header field list may contain more than one entry, some of which contain commas
/// and some do not. If you want a representation of the header fields suitable for
/// performing computation on, consider `getCanonicalForm`.
///
/// - Parameter name: The header field name whose values are to be retrieved.
/// - Returns: A list of the values for that header field name.
public subscript(name: String) -> [String] {
guard !self.headers.isEmpty else {
return []
}
let utf8 = name.utf8
var array: [String] = []
for header in self.headers {
if self.buffer.equalCaseInsensitiveASCII(view: utf8, at: header.name) {
array.append(self.string(idx: header.value))
}
}
return array
}
/// Checks if a header is present
///
/// - parameters:
/// - name: The name of the header
// - returns: `true` if a header with the name (and value) exists, `false` otherwise.
public func contains(name: String) -> Bool {
guard !self.headers.isEmpty else {
return false
}
let utf8 = name.utf8
for header in self.headers {
if self.buffer.equalCaseInsensitiveASCII(view: utf8, at: header.name) {
return true
}
}
return false
}
@available(*, deprecated, message: "getCanonicalForm has been changed to a subscript: headers[canonicalForm: name]")
public func getCanonicalForm(_ name: String) -> [String] {
return self[canonicalForm: name]
}
/// Retrieves the header values for the given header field in "canonical form": that is,
/// splitting them on commas as extensively as possible such that multiple values received on the
/// one line are returned as separate entries. Also respects the fact that Set-Cookie should not
/// be split in this way.
///
/// - Parameter name: The header field name whose values are to be retrieved.
/// - Returns: A list of the values for that header field name.
public subscript(canonicalForm name: String) -> [String] {
let result = self[name]
// It's not safe to split Set-Cookie on comma.
guard name.lowercased() != "set-cookie" else {
return result
}
return result.flatMap { $0.split(separator: ",").map { String($0.trimWhitespace()) } }
}
}
internal extension ByteBuffer {
/// Serializes this HTTP header block to bytes suitable for writing to the wire.
///
/// - Parameter buffer: A buffer to write the serialized bytes into. Will increment
/// the writer index of this buffer.
mutating func write(headers: HTTPHeaders) {
if headers.continuous {
// Declare an extra variable so we not affect the readerIndex of the buffer itself.
var buf = headers.buffer
self.write(buffer: &buf)
} else {
// slow-path....
// TODO: This can still be improved to write as many continuous data as possible and just skip over stuff that was removed.
for header in headers.self.headers {
let fieldLength = (header.value.start + header.value.length) - header.name.start
var header = headers.buffer.getSlice(at: header.name.start, length: fieldLength)!
self.write(buffer: &header)
self.write(staticString: crlf)
}
}
self.write(staticString: crlf)
}
}
extension HTTPHeaders: Sequence {
public typealias Element = (name: String, value: String)
/// An iterator of HTTP header fields.
///
/// This iterator will return each value for a given header name separately. That
/// means that `name` is not guaranteed to be unique in a given block of headers.
public struct Iterator: IteratorProtocol {
private var headerParts: Array<(String, String)>.Iterator
fileprivate init(headerParts: Array<(String, String)>.Iterator) {
self.headerParts = headerParts
}
public mutating func next() -> Element? {
return headerParts.next()
}
}
public func makeIterator() -> Iterator {
return Iterator(headerParts: headers.map { (self.string(idx: $0.name), self.string(idx: $0.value)) }.makeIterator())
}
}
// Dance to ensure that this version of makeIterator(), which returns
// an AnyIterator, is only called when forced through type context.
public protocol _DeprecateHTTPHeaderIterator: Sequence { }
extension HTTPHeaders: _DeprecateHTTPHeaderIterator { }
public extension _DeprecateHTTPHeaderIterator {
@available(*, deprecated, message: "Please use the HTTPHeaders.Iterator type")
public func makeIterator() -> AnyIterator<Element> {
return AnyIterator(makeIterator() as Iterator)
}
}
/* private but tests */ internal extension Character {
var isASCIIWhitespace: Bool {
return self == " " || self == "\t" || self == "\r" || self == "\n" || self == "\r\n"
}
}
/* private but tests */ internal extension String {
func trimASCIIWhitespace() -> Substring {
return self.dropFirst(0).trimWhitespace()
}
}
private extension Substring {
func trimWhitespace() -> Substring {
var me = self
while me.first?.isASCIIWhitespace == .some(true) {
me = me.dropFirst()
}
while me.last?.isASCIIWhitespace == .some(true) {
me = me.dropLast()
}
return me
}
}
extension HTTPHeaders: Equatable {
public static func ==(lhs: HTTPHeaders, rhs: HTTPHeaders) -> Bool {
guard lhs.headers.count == rhs.headers.count else {
return false
}
let lhsNames = Set(lhs.names.map { lhs.string(idx: $0).lowercased() })
let rhsNames = Set(rhs.names.map { rhs.string(idx: $0).lowercased() })
guard lhsNames == rhsNames else {
return false
}
for name in lhsNames {
guard lhs[name].sorted() == rhs[name].sorted() else {
return false
}
}
return true
}
}
public enum HTTPMethod: Equatable {
public enum HasBody {
case yes
case no
case unlikely
}
public static func ==(lhs: HTTPMethod, rhs: HTTPMethod) -> Bool {
switch (lhs, rhs){
case (.GET, .GET):
return true
case (.PUT, .PUT):
return true
case (.ACL, .ACL):
return true
case (.HEAD, .HEAD):
return true
case (.POST, .POST):
return true
case (.COPY, .COPY):
return true
case (.LOCK, .LOCK):
return true
case (.MOVE, .MOVE):
return true
case (.BIND, .BIND):
return true
case (.LINK, .LINK):
return true
case (.PATCH, .PATCH):
return true
case (.TRACE, .TRACE):
return true
case (.MKCOL, .MKCOL):
return true
case (.MERGE, .MERGE):
return true
case (.PURGE, .PURGE):
return true
case (.NOTIFY, .NOTIFY):
return true
case (.SEARCH, .SEARCH):
return true
case (.UNLOCK, .UNLOCK):
return true
case (.REBIND, .REBIND):
return true
case (.UNBIND, .UNBIND):
return true
case (.REPORT, .REPORT):
return true
case (.DELETE, .DELETE):
return true
case (.UNLINK, .UNLINK):
return true
case (.CONNECT, .CONNECT):
return true
case (.MSEARCH, .MSEARCH):
return true
case (.OPTIONS, .OPTIONS):
return true
case (.PROPFIND, .PROPFIND):
return true
case (.CHECKOUT, .CHECKOUT):
return true
case (.PROPPATCH, .PROPPATCH):
return true
case (.SUBSCRIBE, .SUBSCRIBE):
return true
case (.MKCALENDAR, .MKCALENDAR):
return true
case (.MKACTIVITY, .MKACTIVITY):
return true
case (.UNSUBSCRIBE, .UNSUBSCRIBE):
return true
case (.RAW(let l), .RAW(let r)):
return l == r
default:
return false
}
}
case GET
case PUT
case ACL
case HEAD
case POST
case COPY
case LOCK
case MOVE
case BIND
case LINK
case PATCH
case TRACE
case MKCOL
case MERGE
case PURGE
case NOTIFY
case SEARCH
case UNLOCK
case REBIND
case UNBIND
case REPORT
case DELETE
case UNLINK
case CONNECT
case MSEARCH
case OPTIONS
case PROPFIND
case CHECKOUT
case PROPPATCH
case SUBSCRIBE
case MKCALENDAR
case MKACTIVITY
case UNSUBSCRIBE
case RAW(value: String)
/// Whether requests with this verb may have a request body.
public var hasRequestBody: HasBody {
switch self {
case .HEAD, .DELETE, .TRACE:
return .no
case .POST, .PUT, .CONNECT, .PATCH:
return .yes
case .GET, .OPTIONS:
fallthrough
default:
return .unlikely
}
}
}
/// A structure representing a HTTP version.
public struct HTTPVersion: Equatable {
public static func ==(lhs: HTTPVersion, rhs: HTTPVersion) -> Bool {
return lhs.major == rhs.major && lhs.minor == rhs.minor
}
/// Create a HTTP version.
///
/// - Parameter major: The major version number.
/// - Parameter minor: The minor version number.
public init(major: UInt16, minor: UInt16) {
self.major = major
self.minor = minor
}
/// The major version number.
public let major: UInt16
/// The minor version number.
public let minor: UInt16
}
extension HTTPParserError: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .invalidCharactersUsed:
return "illegal characters used in URL/headers"
case .trailingGarbage:
return "trailing garbage bytes"
case .invalidEOFState:
return "stream ended at an unexpected time"
case .headerOverflow:
return "too many header bytes seen; overflow detected"
case .closedConnection:
return "data received after completed connection: close message"
case .invalidVersion:
return "invalid HTTP version"
case .invalidStatus:
return "invalid HTTP status code"
case .invalidMethod:
return "invalid HTTP method"
case .invalidURL:
return "invalid URL"
case .invalidHost:
return "invalid host"
case .invalidPort:
return "invalid port"
case .invalidPath:
return "invalid path"
case .invalidQueryString:
return "invalid query string"
case .invalidFragment:
return "invalid fragment"
case .lfExpected:
return "LF character expected"
case .invalidHeaderToken:
return "invalid character in header"
case .invalidContentLength:
return "invalid character in content-length header"
case .unexpectedContentLength:
return "unexpected content-length header"
case .invalidChunkSize:
return "invalid character in chunk size header"
case .invalidConstant:
return "invalid constant string"
case .invalidInternalState:
return "invalid internal state (swift-http-parser error)"
case .strictModeAssertion:
return "strict mode assertion"
case .paused:
return "paused (swift-http-parser error)"
case .unknown:
return "unknown (http_parser error)"
}
}
}
/// Errors that can be raised while parsing HTTP/1.1.
public enum HTTPParserError: Error {
case invalidCharactersUsed
case trailingGarbage
/* from CHTTPParser */
case invalidEOFState
case headerOverflow
case closedConnection
case invalidVersion
case invalidStatus
case invalidMethod
case invalidURL
case invalidHost
case invalidPort
case invalidPath
case invalidQueryString
case invalidFragment
case lfExpected
case invalidHeaderToken
case invalidContentLength
case unexpectedContentLength
case invalidChunkSize
case invalidConstant
case invalidInternalState
case strictModeAssertion
case paused
case unknown
}
extension HTTPResponseStatus {
/// The numerical status code for a given HTTP response status.
public var code: UInt {
get {
switch self {
case .continue:
return 100
case .switchingProtocols:
return 101
case .processing:
return 102
case .ok:
return 200
case .created:
return 201
case .accepted:
return 202
case .nonAuthoritativeInformation:
return 203
case .noContent:
return 204
case .resetContent:
return 205
case .partialContent:
return 206
case .multiStatus:
return 207
case .alreadyReported:
return 208
case .imUsed:
return 226
case .multipleChoices:
return 300
case .movedPermanently:
return 301
case .found:
return 302
case .seeOther:
return 303
case .notModified:
return 304
case .useProxy:
return 305
case .temporaryRedirect:
return 307
case .permanentRedirect:
return 308
case .badRequest:
return 400
case .unauthorized:
return 401
case .paymentRequired:
return 402
case .forbidden:
return 403
case .notFound:
return 404
case .methodNotAllowed:
return 405
case .notAcceptable:
return 406
case .proxyAuthenticationRequired:
return 407
case .requestTimeout:
return 408
case .conflict:
return 409
case .gone:
return 410
case .lengthRequired:
return 411
case .preconditionFailed:
return 412
case .payloadTooLarge:
return 413
case .uriTooLong:
return 414
case .unsupportedMediaType:
return 415
case .rangeNotSatisfiable:
return 416
case .expectationFailed:
return 417
case .misdirectedRequest:
return 421
case .unprocessableEntity:
return 422
case .locked:
return 423
case .failedDependency:
return 424
case .upgradeRequired:
return 426
case .preconditionRequired:
return 428
case .tooManyRequests:
return 429
case .requestHeaderFieldsTooLarge:
return 431
case .unavailableForLegalReasons:
return 451
case .internalServerError:
return 500
case .notImplemented:
return 501
case .badGateway:
return 502
case .serviceUnavailable:
return 503
case .gatewayTimeout:
return 504
case .httpVersionNotSupported:
return 505
case .variantAlsoNegotiates:
return 506
case .insufficientStorage:
return 507
case .loopDetected:
return 508
case .notExtended:
return 510
case .networkAuthenticationRequired:
return 511
case .custom(code: let code, reasonPhrase: _):
return code
}
}
}
/// The string reason phrase for a given HTTP response status.
public var reasonPhrase: String {
get {
switch self {
case .continue:
return "Continue"
case .switchingProtocols:
return "Switching Protocols"
case .processing:
return "Processing"
case .ok:
return "OK"
case .created:
return "Created"
case .accepted:
return "Accepted"
case .nonAuthoritativeInformation:
return "Non-Authoritative Information"
case .noContent:
return "No Content"
case .resetContent:
return "Reset Content"
case .partialContent:
return "Partial Content"
case .multiStatus:
return "Multi-Status"
case .alreadyReported:
return "Already Reported"
case .imUsed:
return "IM Used"
case .multipleChoices:
return "Multiple Choices"
case .movedPermanently:
return "Moved Permanently"
case .found:
return "Found"
case .seeOther:
return "See Other"
case .notModified:
return "Not Modified"
case .useProxy:
return "Use Proxy"
case .temporaryRedirect:
return "Temporary Redirect"
case .permanentRedirect:
return "Permanent Redirect"
case .badRequest:
return "Bad Request"
case .unauthorized:
return "Unauthorized"
case .paymentRequired:
return "Payment Required"
case .forbidden:
return "Forbidden"
case .notFound:
return "Not Found"
case .methodNotAllowed:
return "Method Not Allowed"
case .notAcceptable:
return "Not Acceptable"
case .proxyAuthenticationRequired:
return "Proxy Authentication Required"
case .requestTimeout:
return "Request Timeout"
case .conflict:
return "Conflict"
case .gone:
return "Gone"
case .lengthRequired:
return "Length Required"
case .preconditionFailed:
return "Precondition Failed"
case .payloadTooLarge:
return "Payload Too Large"
case .uriTooLong:
return "URI Too Long"
case .unsupportedMediaType:
return "Unsupported Media Type"
case .rangeNotSatisfiable:
return "Range Not Satisfiable"
case .expectationFailed:
return "Expectation Failed"
case .misdirectedRequest:
return "Misdirected Request"
case .unprocessableEntity:
return "Unprocessable Entity"
case .locked:
return "Locked"
case .failedDependency:
return "Failed Dependency"
case .upgradeRequired:
return "Upgrade Required"
case .preconditionRequired:
return "Precondition Required"
case .tooManyRequests:
return "Too Many Requests"
case .requestHeaderFieldsTooLarge:
return "Request Header Fields Too Large"
case .unavailableForLegalReasons:
return "Unavailable For Legal Reasons"
case .internalServerError:
return "Internal Server Error"
case .notImplemented:
return "Not Implemented"
case .badGateway:
return "Bad Gateway"
case .serviceUnavailable:
return "Service Unavailable"
case .gatewayTimeout:
return "Gateway Timeout"
case .httpVersionNotSupported:
return "HTTP Version Not Supported"
case .variantAlsoNegotiates:
return "Variant Also Negotiates"
case .insufficientStorage:
return "Insufficient Storage"
case .loopDetected:
return "Loop Detected"
case .notExtended:
return "Not Extended"
case .networkAuthenticationRequired:
return "Network Authentication Required"
case .custom(code: _, reasonPhrase: let phrase):
return phrase
}
}
}
}
/// A HTTP response status code.
public enum HTTPResponseStatus {
/* use custom if you want to use a non-standard response code or
have it available in a (UInt, String) pair from a higher-level web framework. */
case custom(code: UInt, reasonPhrase: String)
/* all the codes from http://www.iana.org/assignments/http-status-codes */
// 1xx
case `continue`
case switchingProtocols
case processing
// 2xx
case ok
case created
case accepted
case nonAuthoritativeInformation
case noContent
case resetContent
case partialContent
// 3xx
case multiStatus
case alreadyReported
case imUsed
case multipleChoices
case movedPermanently
case found
case seeOther
case notModified
case useProxy
case temporaryRedirect
case permanentRedirect
// 4xx
case badRequest
case unauthorized
case paymentRequired
case forbidden
case notFound
case methodNotAllowed
case notAcceptable
case proxyAuthenticationRequired
case requestTimeout
case conflict
case gone
case lengthRequired
case preconditionFailed
case payloadTooLarge
case uriTooLong
case unsupportedMediaType
case rangeNotSatisfiable
case expectationFailed
// 5xx
case misdirectedRequest
case unprocessableEntity
case locked
case failedDependency
case upgradeRequired
case preconditionRequired
case tooManyRequests
case requestHeaderFieldsTooLarge
case unavailableForLegalReasons
case internalServerError
case notImplemented
case badGateway
case serviceUnavailable
case gatewayTimeout
case httpVersionNotSupported
case variantAlsoNegotiates
case insufficientStorage
case loopDetected
case notExtended
case networkAuthenticationRequired
/// Whether responses with this status code may have a response body.
public var mayHaveResponseBody: Bool {
switch self {
case .`continue`,
.switchingProtocols,
.processing,
.noContent,
.custom where (code < 200) && (code >= 100):
return false
default:
return true
}
}
/// Initialize a `HTTPResponseStatus` from a given status and reason.
///
/// - Parameter statusCode: The integer value of the HTTP response status code
/// - Parameter reasonPhrase: The textual reason phrase from the response. This will be
/// discarded in favor of the default if the `statusCode` matches one that we know.
public init(statusCode: Int, reasonPhrase: String = "") {
switch statusCode {
case 100:
self = .`continue`
case 101:
self = .switchingProtocols
case 102:
self = .processing
case 200:
self = .ok
case 201:
self = .created
case 202:
self = .accepted
case 203:
self = .nonAuthoritativeInformation
case 204:
self = .noContent
case 205:
self = .resetContent
case 206:
self = .partialContent
case 207:
self = .multiStatus
case 208:
self = .alreadyReported
case 226:
self = .imUsed
case 300:
self = .multipleChoices
case 301:
self = .movedPermanently
case 302:
self = .found
case 303:
self = .seeOther
case 304:
self = .notModified
case 305:
self = .useProxy
case 307:
self = .temporaryRedirect
case 308:
self = .permanentRedirect
case 400:
self = .badRequest
case 401:
self = .unauthorized
case 402:
self = .paymentRequired
case 403:
self = .forbidden
case 404:
self = .notFound
case 405:
self = .methodNotAllowed
case 406:
self = .notAcceptable
case 407:
self = .proxyAuthenticationRequired
case 408:
self = .requestTimeout
case 409:
self = .conflict
case 410:
self = .gone
case 411:
self = .lengthRequired
case 412:
self = .preconditionFailed
case 413:
self = .payloadTooLarge
case 414:
self = .uriTooLong
case 415:
self = .unsupportedMediaType
case 416:
self = .rangeNotSatisfiable
case 417:
self = .expectationFailed
case 421:
self = .misdirectedRequest
case 422:
self = .unprocessableEntity
case 423:
self = .locked
case 424:
self = .failedDependency
case 426:
self = .upgradeRequired
case 428:
self = .preconditionRequired
case 429:
self = .tooManyRequests
case 431:
self = .requestHeaderFieldsTooLarge
case 451:
self = .unavailableForLegalReasons
case 500:
self = .internalServerError
case 501:
self = .notImplemented
case 502:
self = .badGateway
case 503:
self = .serviceUnavailable
case 504:
self = .gatewayTimeout
case 505:
self = .httpVersionNotSupported
case 506:
self = .variantAlsoNegotiates
case 507:
self = .insufficientStorage
case 508:
self = .loopDetected
case 510:
self = .notExtended
case 511:
self = .networkAuthenticationRequired
default:
self = .custom(code: UInt(statusCode), reasonPhrase: reasonPhrase)
}
}
}
extension HTTPResponseStatus: Equatable {
public static func ==(lhs: HTTPResponseStatus, rhs: HTTPResponseStatus) -> Bool {
switch (lhs, rhs) {
case (.custom(let lcode, let lreason), .custom(let rcode, let rreason)):
return lcode == rcode && lreason == rreason
case (.continue, .continue):
return true
case (.switchingProtocols, .switchingProtocols):
return true
case (.processing, .processing):
return true
case (.ok, .ok):
return true
case (.created, .created):
return true
case (.accepted, .accepted):
return true
case (.nonAuthoritativeInformation, .nonAuthoritativeInformation):
return true
case (.noContent, .noContent):
return true
case (.resetContent, .resetContent):
return true
case (.partialContent, .partialContent):
return true
case (.multiStatus, .multiStatus):
return true
case (.alreadyReported, .alreadyReported):
return true
case (.imUsed, .imUsed):
return true
case (.multipleChoices, .multipleChoices):
return true
case (.movedPermanently, .movedPermanently):
return true
case (.found, .found):
return true
case (.seeOther, .seeOther):
return true
case (.notModified, .notModified):
return true
case (.useProxy, .useProxy):
return true
case (.temporaryRedirect, .temporaryRedirect):
return true
case (.permanentRedirect, .permanentRedirect):
return true
case (.badRequest, .badRequest):
return true
case (.unauthorized, .unauthorized):
return true
case (.paymentRequired, .paymentRequired):
return true
case (.forbidden, .forbidden):
return true
case (.notFound, .notFound):
return true
case (.methodNotAllowed, .methodNotAllowed):
return true
case (.notAcceptable, .notAcceptable):
return true
case (.proxyAuthenticationRequired, .proxyAuthenticationRequired):
return true
case (.requestTimeout, .requestTimeout):
return true
case (.conflict, .conflict):
return true
case (.gone, .gone):
return true
case (.lengthRequired, .lengthRequired):
return true
case (.preconditionFailed, .preconditionFailed):
return true
case (.payloadTooLarge, .payloadTooLarge):
return true
case (.uriTooLong, .uriTooLong):
return true
case (.unsupportedMediaType, .unsupportedMediaType):
return true
case (.rangeNotSatisfiable, .rangeNotSatisfiable):
return true
case (.expectationFailed, .expectationFailed):
return true
case (.misdirectedRequest, .misdirectedRequest):
return true
case (.unprocessableEntity, .unprocessableEntity):
return true
case (.locked, .locked):
return true
case (.failedDependency, .failedDependency):
return true
case (.upgradeRequired, .upgradeRequired):
return true
case (.preconditionRequired, .preconditionRequired):
return true
case (.tooManyRequests, .tooManyRequests):
return true
case (.requestHeaderFieldsTooLarge, .requestHeaderFieldsTooLarge):
return true
case (.unavailableForLegalReasons, .unavailableForLegalReasons):
return true
case (.internalServerError, .internalServerError):
return true
case (.notImplemented, .notImplemented):
return true
case (.badGateway, .badGateway):
return true
case (.serviceUnavailable, .serviceUnavailable):
return true
case (.gatewayTimeout, .gatewayTimeout):
return true
case (.httpVersionNotSupported, .httpVersionNotSupported):
return true
case (.variantAlsoNegotiates, .variantAlsoNegotiates):
return true
case (.insufficientStorage, .insufficientStorage):
return true
case (.loopDetected, .loopDetected):
return true
case (.notExtended, .notExtended):
return true
case (.networkAuthenticationRequired, .networkAuthenticationRequired):
return true
default:
return false
}
}
}
| 33.255474 | 164 | 0.585382 |
793491d279011ce261bd94671e3d419fb46ee3b1 | 1,129 | //
// RegisterRequest.swift
// COpenSSL
//
// Created by Tatiana Tsygankova on 26/06/2019.
//
import Foundation
struct RegisterRequest {
var user: User = User()
init(_ json: [String: AnyObject]) {
if let user_id = json["id"] as? Int {
self.user.id = user_id
}
if let login = json["login"] as? String {
self.user.login = login
}
if let name = json["name"] as? String {
self.user.name = name
}
if let lastname = json["lastname"] as? String {
self.user.lastname = lastname
}
if let password = json["password"] as? String {
self.user.password = password
}
if let email = json["email"] as? String {
self.user.email = email
}
if let gender = json["gender"] as? String {
self.user.gender = gender
}
if let creditCard = json["creditCard"] as? String {
self.user.creditCard = creditCard
}
if let bio = json["bio"] as? String {
self.user.bio = bio
}
}
}
| 24.543478 | 59 | 0.510186 |
647d9dd4fa7eeef99241e305d1f2e6f280f5b6ae | 725 | //
// Endpoint.swift
// primer-checkout-api
//
// Created by Evangelos Pittas on 26/2/21.
//
#if canImport(UIKit)
import Foundation
internal protocol Endpoint {
// var scheme: String { get }
var baseURL: String? { get }
var port: Int? { get }
var path: String { get }
var method: HTTPMethod { get }
var headers: [String: String]? { get }
var queryParameters: [String: String]? { get }
var body: Data? { get }
}
// extension Endpoint {
// var scheme: String {
// return "http"
// }
//
// var port: Int? {
// return nil
// }
// }
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
#endif
| 17.682927 | 50 | 0.566897 |
648c3d515972914c79b013c6ac473f7059c63f96 | 9,942 | //
// EditableMarkdownView.swift
// Issues
//
// Created by Hicham Bouabdallah on 6/11/16.
// Copyright © 2016 SimpleRocket LLC. All rights reserved.
//
import Cocoa
class EditableMarkdownView: BaseView {
fileprivate static let textViewEdgeInset = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
fileprivate var markdownWebView: QIssueMarkdownWebView?
fileprivate let textView = MarkdownEditorTextView()
fileprivate var mardownWebViewContentSize: CGSize?
deinit {
markdownWebView = nil
onFileUploadChange = nil
onHeightChanged = nil
onTextChange = nil
onDragEntered = nil
onDragExited = nil
textView.delegate = nil
ThemeObserverController.sharedInstance.removeThemeObserver(self)
}
var disableScrolling = false {
didSet {
textView.disableScrolling = true
}
}
var isFirstResponder: Bool {
get {
return textView.isFirstResponder
}
}
var string: String? {
get {
guard textView.isFirstResponder else { return commentInfo.commentBody() }
return textView.string
}
set(newValue) {
textView.string = newValue
markdown = newValue ?? ""
}
}
var onTextChange: (()->())?
var onHeightChanged: (()->())? {
didSet {
didSetHeightChanged()
}
}
var didClickImageBlock: ((_ url: URL?) -> ())? {
didSet {
markdownWebView?.didClickImageBlock = didClickImageBlock
}
}
var onEnterKeyPressed: (()->())? {
didSet {
textView.onEnterKeyPressed = onEnterKeyPressed
}
}
var editing: Bool = false {
didSet {
if oldValue != editing {
didSetEditing()
}
}
}
var imageURLs: [URL] {
get {
return markdownWebView?.imageURLs ?? [URL]()
}
}
var currentUploadCount: Int {
get {
return textView.currentUploadCount
}
}
var commentInfo: QIssueCommentInfo {
didSet {
markdown = commentInfo.commentBody()
}
}
var didDoubleClick: (()->())? {
didSet {
markdownWebView?.didDoubleClick = didDoubleClick
}
}
var onFileUploadChange: (()->())? {
didSet {
textView.onFileUploadChange = onFileUploadChange
}
}
var onDragEntered: (()->())? {
didSet {
textView.onDragEntered = onDragEntered
}
}
var onDragExited: (()->())? {
didSet {
textView.onDragExited = onDragExited
}
}
fileprivate(set) var markdown: String {
didSet {
didSetMarkdownString()
}
}
fileprivate(set) var html: String?
required init(commentInfo: QIssueCommentInfo) {
self.commentInfo = commentInfo
self.markdown = commentInfo.commentBody()
super.init(frame: NSRect.zero)
setupTextView()
didSetEditing()
ThemeObserverController.sharedInstance.addThemeObserver(self) { [weak self] (mode) in
guard let strongSelf = self else {
return
}
if strongSelf.disableThemeObserver {
ThemeObserverController.sharedInstance.removeThemeObserver(strongSelf)
return;
}
strongSelf.backgroundColor = CashewColor.backgroundColor()
strongSelf.textView.textColor = CashewColor.foregroundSecondaryColor()
if mode == .dark {
strongSelf.textView.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
} else {
strongSelf.textView.appearance = NSAppearance(named: NSAppearance.Name.vibrantLight)
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func didSetMarkdownString() {
setupMarkdownWebView()
if textView.string != self.markdown {
textView.string = self.markdown
}
}
fileprivate func didSetHeightChanged() {
guard let markdownWebView = markdownWebView else { return }
markdownWebView.didResizeBlock = { [weak self] (rect) in
self?.mardownWebViewContentSize = rect.size
if let onHeightChanged = self?.onHeightChanged {
onHeightChanged()
}
}
}
fileprivate func didSetEditing() {
setupMarkdownWebView()
guard let markdownWebView = markdownWebView else { return }
if editing {
textView.isHidden = false
markdownWebView.isHidden = true
self.textView.collapseToolbar = false
self.textView.activateTextViewConstraints = true
DispatchQueue.main.async(execute: {
//self.window?.makeFirstResponder(self.textView)
self.textView.makeFirstResponder()
});
} else {
textView.isHidden = true
markdownWebView.isHidden = false
self.textView.activateTextViewConstraints = false
}
invalidateIntrinsicContentSize()
if let onHeightChanged = onHeightChanged {
onHeightChanged()
}
}
override var intrinsicContentSize: NSSize {
get {
if editing {
let textSize = textContentSize()
return NSSize(width: bounds.width, height: textSize.height + EditableMarkdownView.textViewEdgeInset.top + EditableMarkdownView.textViewEdgeInset.bottom)
} else {
guard let mardownWebViewContentSize = mardownWebViewContentSize else {
return CGSize.zero
}
return NSSize(width: mardownWebViewContentSize.width, height: max(mardownWebViewContentSize.height, EditableMarkdownView.textViewEdgeInset.top + EditableMarkdownView.textViewEdgeInset.bottom))
}
}
}
fileprivate func textContentSize() -> NSSize {
let containerWidth: CGFloat = bounds.width //- EditableMarkdownView.textViewEdgeInset.left - EditableMarkdownView.textViewEdgeInset.right
//borderColor = NSColor.redColor()
return self.textView.calculatedSizeForWidth(containerWidth)
}
// MARK: General Setup
fileprivate func setupTextView() {
textView.string = self.markdown
addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
textView.drawsBackground = false
textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0).isActive = true
textView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0).isActive = true
textView.topAnchor.constraint(equalTo: topAnchor, constant: EditableMarkdownView.textViewEdgeInset.top).isActive = true
textView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -EditableMarkdownView.textViewEdgeInset.bottom).isActive = true
textView.focusRingType = NSFocusRingType.default
textView.font = NSFont.systemFont(ofSize: 14)
textView.collapseToolbar = false
textView.disableScrollViewBounce = true
textView.registerDragAndDrop()
}
fileprivate func setupMarkdownWebView() {
guard self.editing == false else { return }
if let currentMarkdownWebView = self.markdownWebView {
currentMarkdownWebView.removeFromSuperview()
self.markdownWebView = nil
}
let markdownParser = MarkdownParser()
let html = markdownParser.parse(commentInfo.commentBody(), for: commentInfo.repo())
self.html = html
let markdownWebView = QIssueMarkdownWebView(htmlString: html) { [weak self] (rect) in
self?.mardownWebViewContentSize = rect.size
self?.invalidateIntrinsicContentSize()
if let onHeightChanged = self?.onHeightChanged {
onHeightChanged()
}
}
self.markdownWebView = markdownWebView
markdownWebView?.didDoubleClick = didDoubleClick
addSubview(markdownWebView!)
markdownWebView?.translatesAutoresizingMaskIntoConstraints = false
markdownWebView?.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
markdownWebView?.rightAnchor.constraint(equalTo: rightAnchor, constant: -EditableMarkdownView.textViewEdgeInset.right).isActive = true
markdownWebView?.topAnchor.constraint(equalTo: topAnchor).isActive = true
markdownWebView?.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
didSetHeightChanged()
}
}
extension EditableMarkdownView: NSTextViewDelegate {
// override func controlTextDidChange(obj: NSNotification) {
//
// }
func textDidChange(_ notification: Notification) {
markdown = textView.string ?? ""
invalidateIntrinsicContentSize()
setNeedsDisplay(bounds)
if let onHeightChanged = onHeightChanged {
onHeightChanged()
}
if let onTextChange = onTextChange {
onTextChange()
}
}
func textDidBeginEditing(_ notification: Notification) {
invalidateIntrinsicContentSize()
setNeedsDisplay(bounds)
}
func textDidEndEditing(_ notification: Notification) {
invalidateIntrinsicContentSize()
setNeedsDisplay(bounds)
if !textView.isShowingPopover {
textView.undoManager?.removeAllActions()
}
}
}
| 31.763578 | 209 | 0.607322 |
d9c7c587d4f4d5f5a36b89205befa38e56200d56 | 116 | extension AuthorizedRoot {
final class Builder: BaseModuleBuilder<RootView, ViewModel<Provider>, Provider> {}
}
| 29 | 86 | 0.775862 |
897b5620b330ee218857489fb874be4781c3194c | 239 | //
// Router.swift
// ZalandoFastSearchSwift
//
// Created by Alexander Stolar on 17/07/2018.
// Copyright © 2018 Alexander Stolar. All rights reserved.
//
import Foundation
enum Router {
case articles
case categories
}
| 14.9375 | 59 | 0.686192 |
64a7bacab7240344911a7a042923013665f7084e | 2,925 | //
// TweetReplyViewController.swift
// TwitterClient
//
// Created by Bharath D N on 4/16/17.
// Copyright © 2017 Bharath D N. All rights reserved.
//
import UIKit
@objc protocol TweetReplyViewControllerDelegate {
@objc optional func tweetReplyViewController (tweetReplyViewController: TweetReplyViewController, didPostReply tweet: Tweet)
}
class TweetReplyViewController: UIViewController {
var tweet: Tweet! = nil
weak var delegate: TweetReplyViewControllerDelegate?
var keyBoardHeight: CGFloat?
@IBOutlet weak var replyButton: UIBarButtonItem!
@IBOutlet weak var replyTextView: UITextView!
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userScreenNameLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var charCountBarItem: UIBarButtonItem!
@IBOutlet weak var replyTextViewTopConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
replyTextView.delegate = self
replyTextView.becomeFirstResponder()
userImageView.setImageWith(tweet.userImageUrl!)
userNameLabel.text = tweet.userName
userScreenNameLabel.text = tweet.userScreenName
tweetTextLabel.text = tweet.text
}
@IBAction func onCancelButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func onReplyButton(_ sender: Any) {
print("\n\nYou replied:: \(replyTextView.text)\n\n")
let replyText = replyTextView.text!
TwitterClient.sharedInstance?.replyToTweet(replyMsg: replyText, tweet: tweet, success: { (responseTweet: Tweet) in
print("reply success")
self.delegate?.tweetReplyViewController!(tweetReplyViewController: self, didPostReply: responseTweet)
self.dismiss(animated: true, completion: nil)
}, failure: { (error: Error) in
print("reply failed :(")
})
view.endEditing(true)
replyTextView.text = nil
}
func limitCharacterCount() {
let limit = 140
let replyText = replyTextView.text!
let replyTextCharCount = replyText.characters.count
let remainingCharacters = limit - replyTextCharCount
if remainingCharacters <= 0 {
charCountBarItem.tintColor = UIColor.red
charCountBarItem.title = "0"
let limitedCharactersIndex = replyText.index(replyText.startIndex, offsetBy: limit)
replyTextView.text = replyText.substring(to: limitedCharactersIndex)
}
else {
charCountBarItem.title = String(remainingCharacters)
charCountBarItem.tintColor = UIColor.white
}
}
}
// MARK: - Delegates
extension TweetReplyViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if(replyTextView.text!.characters.count > 0) {
replyButton.isEnabled = true
}
else {
replyButton.isEnabled = false
}
limitCharacterCount()
}
}
| 29.545455 | 126 | 0.722051 |
641ee58cd77d25eeb9d3e839ebdb1994a7b2c9ba | 2,777 | //
// QRScannerFeatureOnboardingViewTests.swift
// SwiftUIExampleTests
//
// Created by Tyler Thompson on 7/15/21.
// Copyright © 2021 WWT and Tyler Thompson. All rights reserved.
//
import XCTest
import SwiftUI
import Swinject
import ViewInspector
@testable import SwiftCurrent_SwiftUI // 🤮 it sucks that this is necessary
@testable import SwiftUIExample
final class QRScannerFeatureOnboardingViewTests: XCTestCase, View {
let defaultsKey = "OnboardedToQRScanningFeature"
override func setUpWithError() throws {
Container.default.removeAll()
}
func testOnboardingInWorkflow() async throws {
let defaults = try XCTUnwrap(UserDefaults(suiteName: #function))
defaults.set(false, forKey: defaultsKey)
Container.default.register(UserDefaults.self) { _ in defaults }
let workflowFinished = expectation(description: "View Proceeded")
let launcher = try await MainActor.run {
WorkflowView {
WorkflowItem(QRScannerFeatureOnboardingView.self)
}.onFinish { _ in
workflowFinished.fulfill()
}
}
.content
.hostAndInspect(with: \.inspection)
.extractWorkflowItemWrapper()
XCTAssertNoThrow(try launcher.find(ViewType.Text.self))
XCTAssertEqual(try launcher.find(ViewType.Text.self).string(), "Learn about our awesome QR scanning feature!")
XCTAssertNoThrow(try launcher.find(ViewType.Button.self).tap())
wait(for: [workflowFinished], timeout: TestConstant.timeout)
}
func testOnboardingViewLoads_WhenNoValueIsInUserDefaults() throws {
let defaults = try XCTUnwrap(UserDefaults(suiteName: #function))
defaults.removeObject(forKey: defaultsKey)
Container.default.register(UserDefaults.self) { _ in defaults }
XCTAssert(QRScannerFeatureOnboardingView().shouldLoad(), "Profile onboarding should show if defaults do not exist")
}
func testOnboardingViewLoads_WhenValueInUserDefaultsIsFalse() throws {
let defaults = try XCTUnwrap(UserDefaults(suiteName: #function))
defaults.set(false, forKey: defaultsKey)
Container.default.register(UserDefaults.self) { _ in defaults }
XCTAssert(QRScannerFeatureOnboardingView().shouldLoad(), "Profile onboarding should show if default is false")
}
func testOnboardingViewDoesNotLoad_WhenValueInUserDefaultsIsTrue() throws {
let defaults = try XCTUnwrap(UserDefaults(suiteName: #function))
defaults.set(true, forKey: defaultsKey)
Container.default.register(UserDefaults.self) { _ in defaults }
XCTAssertFalse(QRScannerFeatureOnboardingView().shouldLoad(), "Profile onboarding should not show if default is true")
}
}
| 41.447761 | 126 | 0.71372 |
76d3cb1d687d622168d05aadfe5c9288c1d76103 | 10,492 | /**
* (C) Copyright IBM Corp. 2016, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Starscream
import IBMSwiftSDKCore
internal class SpeechToTextSocket: WebSocketDelegate {
private(set) internal var results = SpeechRecognitionResults()
private(set) internal var state: SpeechToTextState = .disconnected
internal var onConnect: (() -> Void)?
internal var onListening: (() -> Void)?
internal var onResults: ((SpeechRecognitionResults) -> Void)?
internal var onError: ((WatsonError) -> Void)?
internal var onDisconnect: (() -> Void)?
internal let url: URL
private let authenticator: Authenticator
private let maxConnectAttempts: Int
private var connectAttempts: Int
private let defaultHeaders: [String: String]
private var socket: WebSocket
private let queue: OperationQueue
internal init(
url: URL,
authenticator: Authenticator,
defaultHeaders: [String: String])
{
var request = URLRequest(url: url)
request.timeoutInterval = 30
self.socket = WebSocket(request: request)
self.url = url
self.authenticator = authenticator
self.maxConnectAttempts = 1
self.connectAttempts = 0
self.defaultHeaders = defaultHeaders
self.queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.isSuspended = true
}
internal func connect() {
// ensure the socket is not already connected
guard state == .disconnected || state == .connecting else {
return
}
// flush operation queue
if state == .disconnected {
queue.cancelAllOperations()
}
// update state
state = .connecting
// restrict the number of retries
guard connectAttempts <= maxConnectAttempts else {
let failureReason = "Invalid HTTP upgrade. Check credentials."
let error = WatsonError.http(statusCode: 400, message: failureReason, metadata: ["type": "Websocket"])
onError?(error)
return
}
// create request with headers
var request = URLRequest(url: url)
request.timeoutInterval = 5
if let userAgentHeader = RestRequest.userAgent {
request.setValue(userAgentHeader, forHTTPHeaderField: "User-Agent")
}
for (key, value) in defaultHeaders {
request.addValue(value, forHTTPHeaderField: key)
}
authenticator.authenticate(request: request) {
request, error in
if let request = request {
// initialize socket and connect
self.socket = WebSocket(request: request)
self.socket.delegate = self
self.socket.connect()
} else {
self.onError?(error ?? WatsonError.http(statusCode: 400, message: "Token Manager error", metadata: nil))
}
}
}
internal func writeStart(settings: RecognitionSettings) {
guard state != .disconnected else { return }
guard let data = try? JSONEncoder().encode(settings) else { return }
guard let start = String(data: data, encoding: .utf8) else { return }
queue.addOperation {
self.socket.write(string: start)
self.results = SpeechRecognitionResults()
if self.state != .disconnected {
self.state = .listening
self.onListening?()
}
}
}
internal func writeAudio(audio: Data) {
guard state != .disconnected else { return }
queue.addOperation {
self.socket.write(data: audio)
if self.state == .listening {
self.state = .sentAudio
}
}
}
internal func writeStop() {
guard state != .disconnected else { return }
guard let data = try? JSONEncoder().encode(RecognitionStop()) else { return }
guard let stop = String(data: data, encoding: .utf8) else { return }
queue.addOperation {
self.socket.write(string: stop)
}
}
internal func waitForResults() {
queue.addOperation {
switch self.state {
case .connecting, .connected, .listening, .disconnected:
return // no results to wait for
case .sentAudio, .transcribing:
self.queue.isSuspended = true
let onListeningCache = self.onListening
self.onListening = {
self.onListening = onListeningCache
self.queue.isSuspended = false
}
}
}
}
internal func disconnect(forceTimeout: TimeInterval? = nil) {
queue.addOperation {
self.queue.isSuspended = true
self.queue.cancelAllOperations()
self.socket.disconnect(forceTimeout: forceTimeout)
}
}
internal static func buildURL(
url: String,
model: String?,
baseModelVersion: String?,
languageCustomizationID: String?,
acousticCustomizationID: String?,
endOfPhraseSilenceTime: Double? = nil,
splitTranscriptAtPhraseEnd: Bool? = nil,
learningOptOut: Bool?,
customerID: String?) -> URL?
{
var queryParameters = [URLQueryItem]()
if let model = model {
queryParameters.append(URLQueryItem(name: "model", value: model))
}
if let baseModelVersion = baseModelVersion {
queryParameters.append(URLQueryItem(name: "base_model_version", value: baseModelVersion))
}
if let languageCustomizationID = languageCustomizationID {
queryParameters.append(URLQueryItem(name: "language_customization_id", value: languageCustomizationID))
}
if let acousticCustomizationID = acousticCustomizationID {
queryParameters.append(URLQueryItem(name: "acoustic_customization_id", value: acousticCustomizationID))
}
if let learningOptOut = learningOptOut {
let value = "\(learningOptOut)"
queryParameters.append(URLQueryItem(name: "x-watson-learning-opt-out", value: value))
}
if let endOfPhraseSilenceTime = endOfPhraseSilenceTime {
let queryParameter = URLQueryItem(name: "end_of_phrase_silence_time", value: "\(endOfPhraseSilenceTime)")
queryParameters.append(queryParameter)
}
if let splitTranscriptAtPhraseEnd = splitTranscriptAtPhraseEnd {
let queryParameter = URLQueryItem(name: "split_transcript_at_phrase_end", value: "\(splitTranscriptAtPhraseEnd)")
queryParameters.append(queryParameter)
}
if let customerID = customerID {
let value = "customer_id=\(customerID)"
queryParameters.append(URLQueryItem(name: "x-watson-metadata", value: value))
}
var urlComponents = URLComponents(string: url)
if !queryParameters.isEmpty {
urlComponents?.queryItems = queryParameters
}
return urlComponents?.url
}
private func onStateMessage(state: RecognitionState) {
if state.state == "listening" && self.state == .transcribing {
self.state = .listening
onListening?()
}
}
private func onResultsMessage(results: SpeechRecognitionResults) {
state = .transcribing
onResults?(results)
}
private func onErrorMessage(error: String) {
let error = WatsonError.other(message: error, metadata: nil)
onError?(error)
}
private func isAuthenticationFailure(error: Error) -> Bool {
if let error = error as? WSError {
let matchesCode = (error.code == 400)
let matchesType = (error.type == .upgradeError)
return matchesCode && matchesType
}
return false
}
private func isNormalDisconnect(error: Error) -> Bool {
guard let error = error as? WSError else { return false }
return error.code == Int(CloseCode.normal.rawValue)
}
internal func websocketDidConnect(socket: WebSocketClient) {
state = .connected
connectAttempts = 0
queue.isSuspended = false
results = SpeechRecognitionResults()
onConnect?()
}
internal func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
return // should not receive any binary data from the service
}
internal func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
guard let json = text.data(using: .utf8) else { return }
let decoder = JSONDecoder()
if let state = try? decoder.decode(RecognitionState.self, from: json) {
onStateMessage(state: state)
} else if let object = try? decoder.decode([String: String].self, from: json), let error = object["error"] {
onErrorMessage(error: error)
} else if let results = try? decoder.decode(SpeechRecognitionResults.self, from: json) {
// all properties of `SpeechRecognitionResults` are optional, so this block will always
// execute unless the message has already been parsed as a `RecognitionState` or error
onResultsMessage(results: results)
}
}
internal func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
state = .disconnected
queue.isSuspended = true
guard let error = error else {
onDisconnect?()
return
}
if isNormalDisconnect(error: error) {
onDisconnect?()
return
}
if isAuthenticationFailure(error: error) {
self.connectAttempts += 1
self.connect()
return
}
onError?(WatsonError.other(message: String(describing: error), metadata: nil))
onDisconnect?()
}
}
| 36.814035 | 125 | 0.62114 |
20cf0b934b5acf0345b583f3dba85589a4818c27 | 401 | //
// ThreadViewCell.swift
// Wired iOS
//
// Created by Rafael Warnault on 18/04/2020.
// Copyright © 2020 Read-Write. All rights reserved.
//
import UIKit
class ThreadViewCell: UITableViewCell {
@IBOutlet var subjectTextField: UILabel!
@IBOutlet var nickTextField: UILabel!
@IBOutlet var dateTextField: UILabel!
@IBOutlet var repliesTextField: UILabel!
}
| 23.588235 | 53 | 0.683292 |
8f78e1b1cb855ed95c868397d57e7f54ff255fb6 | 2,283 | //
// UPPhotoLinkURL.swift
// UnsplashProvider
//
// Created by jasu on 2022/01/22.
// Copyright (c) 2022 jasu All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
public enum UPPhotoLinkType: String, Codable {
case api = "self"
case html
case download
case downloadLocation = "download_location"
}
public struct UPPhotoLinkURL: Codable, Equatable {
public var api: URL
public var html: URL
public var download: URL
public var downloadLocation: URL
enum CodingKeys: String, CodingKey {
case api = "self"
case html
case download
case downloadLocation = "download_location"
}
public func type(_ linkType: UPPhotoLinkType) -> URL {
switch linkType {
case .api: return api
case .html: return html
case .download: return download
case .downloadLocation: return downloadLocation
}
}
public static func == (lhs: UPPhotoLinkURL, rhs: UPPhotoLinkURL) -> Bool {
lhs.api == rhs.api &&
lhs.html == rhs.html &&
lhs.download == rhs.download &&
lhs.downloadLocation == rhs.downloadLocation
}
}
| 34.590909 | 88 | 0.681559 |
4a9903a066b896d1cedb9cf8c0f5cadafc3e7c5d | 1,423 | /// Represents the precision used when encoding coordinates.
///
/// The uncertainty for each precision value is:
/// - 1: (veryLow) -- ± 2500km
/// - 3: (low) -- ± 78km
/// - 5: (medium) -- ± 2.4km
/// - 7: (high) -- ± 0.076km
/// - 9: (veryHigh) -- ± 0.0024km
public enum Precision {
/// Encodes coordinates using 1 character.
///
/// Has an uncertainty of ± 2500km.
case veryLow
/// Encodes coordinates using 3 characters.
///
/// Has an uncertainty of ± 78km.
case low
/// Encodes coordinates using 5 characters.
///
/// Has an uncertainty of ± 2.4km.
case medium
/// Encodes coordinates using 7 characters.
///
/// Has an uncertainty of ± 0.076km.
case high
/// Encodes coordinates using 9 characters.
///
/// Has an uncertainty of ± 0.0024km.
case veryHigh
/// Encodes coordinates using a variable number of characters.
///
/// An higher value results in a more accurante encoding at the cost of time and computational power.
case custom(value: Int)
internal var value: Int {
switch self {
case .veryLow:
return 1
case .low:
return 3
case .medium:
return 5
case .high:
return 7
case .veryHigh:
return 9
case .custom(let value):
return value
}
}
}
| 24.964912 | 105 | 0.55376 |
614336c4fda93d52950dcc5847f03c6754a9c22b | 3,405 | //
// UIImage+HiPDA.swift
// HiPDA
//
// Created by leizh007 on 2016/10/16.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import UIKit
import CoreImage
extension UIImage {
/// 取得view的截图
///
/// - parameter view: 待截图的view
/// - parameter frame: 待截图区域(相较于view)
///
/// - returns: 截图
@nonobjc
static func snapshot(of view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
//https://github.com/ibireme/YYWebImage/blob/e8009ae33bb30ac6a1158022fa216a932310c857/YYWebImage/Categories/UIImage%2BYYWebImage.m
func image(roundCornerRadius radius: CGFloat, corners: UIRectCorner, borderWidth: CGFloat, borderColor: UIColor, borderLineJoin: CGLineJoin, size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, C.UI.screenScale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.scaleBy(x: 1, y: -1)
context.translateBy(x: 0, y: -rect.size.height)
let minSize = min(size.width, size.height)
if borderWidth < minSize / 2 {
let path = UIBezierPath(roundedRect: rect.insetBy(dx: borderWidth, dy: borderWidth), byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
path.close()
context.saveGState()
path.addClip()
guard let cgImage = self.cgImage else {
return nil
}
context.draw(cgImage, in: rect)
context.restoreGState()
}
if borderWidth < minSize / 2 && borderWidth > 0 {
let strokeInset = (floor(borderWidth * scale) + 0.5) / scale
let strokeRect = rect.insetBy(dx: strokeInset, dy: strokeInset)
let strokeRadius = radius > scale / 2 ? radius - scale / 2 : 0
let path = UIBezierPath(roundedRect: strokeRect, byRoundingCorners: corners, cornerRadii: CGSize(width: strokeRadius, height: strokeRadius))
path.close()
path.lineWidth = borderWidth
path.lineJoinStyle = borderLineJoin
borderColor.setStroke()
path.stroke()
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func image(roundCornerRadius radius: CGFloat, borderWidth: CGFloat, borderColor: UIColor, size: CGSize) -> UIImage? {
return image(roundCornerRadius: radius, corners: .allCorners, borderWidth: borderWidth, borderColor: borderColor, borderLineJoin: .miter, size: size)
}
var isLongImage: Bool {
return size.width > 0.0 && size.height > 0.0 && size.height / size.width > longImageRatioThreshold
}
func ciImage() -> CoreImage.CIImage? {
if self.ciImage != nil {
return self.ciImage
}
guard let cgImage = self.cgImage else {
return nil
}
return CoreImage.CIImage(cgImage: cgImage)
}
}
private let longImageRatioThreshold = CGFloat(3.0)
| 37.833333 | 176 | 0.628488 |
1dd4f1136a02abe518f08ec93b80d31e2cda424d | 1,260 | //
// ECDH.swift
// ECDHESSwift
//
// Created by MFantcy on 2019/4/16.
//
import Foundation
import JOSESwift
/**
Derive ECDH Key Data
- Parameter ecPrivJwk: EC private JWK
- Parameter ecPubJwk: EC public JWK
- Parameter bitLen: key size
- Throws: ECDHError.deriveKeyFail
- Returns: Result of key exchange operation as a Data
**/
func ecdhDeriveBits(ecPrivJwk: ECPrivateKey, ecPubJwk: ECPublicKey, bitLen: Int = 0) throws -> Data {
if ecPrivJwk.crv != ecPubJwk.crv {
throw ECDHEESError.deriveKeyFail(reason: "Private Key curve and Public Key curve are different")
}
let pubKey = try ecPubJwk.converted(to: SecKey.self)
let eprivKey = try ecPrivJwk.converted(to: SecKey.self)
let parameters = [String: Any]()
var error: Unmanaged<CFError>?
guard let derivedData = SecKeyCopyKeyExchangeResult(
eprivKey,
SecKeyAlgorithm.ecdhKeyExchangeStandard,
pubKey,
parameters as CFDictionary,
&error)
else {
let errStr = error?.takeRetainedValue().localizedDescription ?? "Derive Key Fail"
throw ECDHEESError.deriveKeyFail(reason: errStr)
}
return bitLen > 0 ? truncateBitLen(from: (derivedData as Data), bitLen: bitLen) : (derivedData as Data) as Data
}
| 29.302326 | 115 | 0.696032 |
1d1c09376d1c0f5bb2e238909bbeba36b8d86bcd | 15,346 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
#if compiler(>=5.5.2) && canImport(_Concurrency)
import SotoCore
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension ComprehendMedical {
// MARK: Async API Calls
/// Gets the properties associated with a medical entities detection job. Use this operation to get the status of a detection job.
public func describeEntitiesDetectionV2Job(_ input: DescribeEntitiesDetectionV2JobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeEntitiesDetectionV2JobResponse {
return try await self.client.execute(operation: "DescribeEntitiesDetectionV2Job", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the properties associated with an InferICD10CM job. Use this operation to get the status of an inference job.
public func describeICD10CMInferenceJob(_ input: DescribeICD10CMInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeICD10CMInferenceJobResponse {
return try await self.client.execute(operation: "DescribeICD10CMInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the properties associated with a protected health information (PHI) detection job. Use this operation to get the status of a detection job.
public func describePHIDetectionJob(_ input: DescribePHIDetectionJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribePHIDetectionJobResponse {
return try await self.client.execute(operation: "DescribePHIDetectionJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the properties associated with an InferRxNorm job. Use this operation to get the status of an inference job.
public func describeRxNormInferenceJob(_ input: DescribeRxNormInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeRxNormInferenceJobResponse {
return try await self.client.execute(operation: "DescribeRxNormInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the properties associated with an InferSNOMEDCT job. Use this operation to get the status of an inference job.
public func describeSNOMEDCTInferenceJob(_ input: DescribeSNOMEDCTInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeSNOMEDCTInferenceJobResponse {
return try await self.client.execute(operation: "DescribeSNOMEDCTInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// The DetectEntities operation is deprecated. You should use the DetectEntitiesV2 operation instead. Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information .
@available(*, deprecated, message: "This operation is deprecated, use DetectEntitiesV2 instead.")
public func detectEntities(_ input: DetectEntitiesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DetectEntitiesResponse {
return try await self.client.execute(operation: "DetectEntities", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information. Amazon Comprehend Medical only detects medical entities in English language texts. The DetectEntitiesV2 operation replaces the DetectEntities operation. This new action uses a different model for determining the entities in your medical text and changes the way that some entities are returned in the output. You should use the DetectEntitiesV2 operation in all new applications. The DetectEntitiesV2 operation returns the Acuity and Direction entities as attributes instead of types.
public func detectEntitiesV2(_ input: DetectEntitiesV2Request, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DetectEntitiesV2Response {
return try await self.client.execute(operation: "DetectEntitiesV2", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Inspects the clinical text for protected health information (PHI) entities and returns the entity category, location, and confidence score for each entity. Amazon Comprehend Medical only detects entities in English language texts.
public func detectPHI(_ input: DetectPHIRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DetectPHIResponse {
return try await self.client.execute(operation: "DetectPHI", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// InferICD10CM detects medical conditions as entities listed in a patient record and links those entities to normalized concept identifiers in the ICD-10-CM knowledge base from the Centers for Disease Control. Amazon Comprehend Medical only detects medical entities in English language texts.
public func inferICD10CM(_ input: InferICD10CMRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> InferICD10CMResponse {
return try await self.client.execute(operation: "InferICD10CM", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// InferRxNorm detects medications as entities listed in a patient record and links to the normalized concept identifiers in the RxNorm database from the National Library of Medicine. Amazon Comprehend Medical only detects medical entities in English language texts.
public func inferRxNorm(_ input: InferRxNormRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> InferRxNormResponse {
return try await self.client.execute(operation: "InferRxNorm", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// InferSNOMEDCT detects possible medical concepts as entities and links them to codes from the Systematized Nomenclature of Medicine, Clinical Terms (SNOMED-CT) ontology
public func inferSNOMEDCT(_ input: InferSNOMEDCTRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> InferSNOMEDCTResponse {
return try await self.client.execute(operation: "InferSNOMEDCT", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of medical entity detection jobs that you have submitted.
public func listEntitiesDetectionV2Jobs(_ input: ListEntitiesDetectionV2JobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListEntitiesDetectionV2JobsResponse {
return try await self.client.execute(operation: "ListEntitiesDetectionV2Jobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of InferICD10CM jobs that you have submitted.
public func listICD10CMInferenceJobs(_ input: ListICD10CMInferenceJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListICD10CMInferenceJobsResponse {
return try await self.client.execute(operation: "ListICD10CMInferenceJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of protected health information (PHI) detection jobs that you have submitted.
public func listPHIDetectionJobs(_ input: ListPHIDetectionJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListPHIDetectionJobsResponse {
return try await self.client.execute(operation: "ListPHIDetectionJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of InferRxNorm jobs that you have submitted.
public func listRxNormInferenceJobs(_ input: ListRxNormInferenceJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListRxNormInferenceJobsResponse {
return try await self.client.execute(operation: "ListRxNormInferenceJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of InferSNOMEDCT jobs a user has submitted.
public func listSNOMEDCTInferenceJobs(_ input: ListSNOMEDCTInferenceJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListSNOMEDCTInferenceJobsResponse {
return try await self.client.execute(operation: "ListSNOMEDCTInferenceJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts an asynchronous medical entity detection job for a collection of documents. Use the DescribeEntitiesDetectionV2Job operation to track the status of a job.
public func startEntitiesDetectionV2Job(_ input: StartEntitiesDetectionV2JobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartEntitiesDetectionV2JobResponse {
return try await self.client.execute(operation: "StartEntitiesDetectionV2Job", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts an asynchronous job to detect medical conditions and link them to the ICD-10-CM ontology. Use the DescribeICD10CMInferenceJob operation to track the status of a job.
public func startICD10CMInferenceJob(_ input: StartICD10CMInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartICD10CMInferenceJobResponse {
return try await self.client.execute(operation: "StartICD10CMInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts an asynchronous job to detect protected health information (PHI). Use the DescribePHIDetectionJob operation to track the status of a job.
public func startPHIDetectionJob(_ input: StartPHIDetectionJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartPHIDetectionJobResponse {
return try await self.client.execute(operation: "StartPHIDetectionJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts an asynchronous job to detect medication entities and link them to the RxNorm ontology. Use the DescribeRxNormInferenceJob operation to track the status of a job.
public func startRxNormInferenceJob(_ input: StartRxNormInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartRxNormInferenceJobResponse {
return try await self.client.execute(operation: "StartRxNormInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts an asynchronous job to detect medical concepts and link them to the SNOMED-CT ontology. Use the DescribeSNOMEDCTInferenceJob operation to track the status of a job.
public func startSNOMEDCTInferenceJob(_ input: StartSNOMEDCTInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartSNOMEDCTInferenceJobResponse {
return try await self.client.execute(operation: "StartSNOMEDCTInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Stops a medical entities detection job in progress.
public func stopEntitiesDetectionV2Job(_ input: StopEntitiesDetectionV2JobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StopEntitiesDetectionV2JobResponse {
return try await self.client.execute(operation: "StopEntitiesDetectionV2Job", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Stops an InferICD10CM inference job in progress.
public func stopICD10CMInferenceJob(_ input: StopICD10CMInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StopICD10CMInferenceJobResponse {
return try await self.client.execute(operation: "StopICD10CMInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Stops a protected health information (PHI) detection job in progress.
public func stopPHIDetectionJob(_ input: StopPHIDetectionJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StopPHIDetectionJobResponse {
return try await self.client.execute(operation: "StopPHIDetectionJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Stops an InferRxNorm inference job in progress.
public func stopRxNormInferenceJob(_ input: StopRxNormInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StopRxNormInferenceJobResponse {
return try await self.client.execute(operation: "StopRxNormInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Stops an InferSNOMEDCT inference job in progress.
public func stopSNOMEDCTInferenceJob(_ input: StopSNOMEDCTInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StopSNOMEDCTInferenceJobResponse {
return try await self.client.execute(operation: "StopSNOMEDCTInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
#endif // compiler(>=5.5.2) && canImport(_Concurrency)
| 96.515723 | 674 | 0.76111 |
d65e81913194afd1d3fcbb4e6afdcdcbf859fd41 | 2,475 | //
// ConnectionManager.swift
// Connection
//
// Created by Roderic Linguri <[email protected]>
// License: MIT
// Copyright © 2017 Digices LLC. All rights reserved.
//
import UIKit
protocol ConnectionManagerDelegate {
func connectionManager(_ manager: ConnectionManager, sendStatus status: Bool)
func connectionManager(_ manager: ConnectionManager, didProduceError error: Error)
func connectionManager(_ manager: ConnectionManager, didReceiveData data: Data)
} // ./ConnectionManager
class ConnectionManager {
var delegate: ConnectionManagerDelegate
/**
* Create a ConnectionManager instance with a delegate
* - parameter: delegate to receive notifications
*/
init(delegate: ConnectionManagerDelegate) {
self.delegate = delegate
}
/**
* Receive completion of URLSession Task
* - parameter: optional Data (body of the response)
* - parameter: optional URLResponse (contains response codes, etc.)
* - parameter: optional Error (Server Error, not-found etc.)
*/
func completionHandler(data: Data?, response: URLResponse?, error: Error?) {
if let e = error {
OperationQueue.main.addOperation { [weak self] in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let weakSelf = self {
weakSelf.delegate.connectionManager(weakSelf, didProduceError: e)
} // ./unwrap self
} // ./main queue
} // ./unwrap error
if let d = data {
OperationQueue.main.addOperation { [weak self] in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let weakSelf = self {
weakSelf.delegate.connectionManager(weakSelf, didReceiveData: d)
} // ./unwrap self
} // ./main queue
} // ./unwrap data
} // ./completionHandler
/**
* Send a connection request
* - parameter: a Connection object
*/
func sendRequest(forConnection connection: Connection) {
if let request = connection.request {
let task = URLSession.shared.dataTask(with: request, completionHandler: self.completionHandler)
task.resume()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.delegate.connectionManager(self, sendStatus: true)
} // ./we have a request
else {
self.delegate.connectionManager(self, didProduceError: ConnectionError.requestCreationError)
} // ./request was nil
} // ./sendRequest
} // ./ConnectionManager
| 31.730769 | 101 | 0.690909 |
1c5c520c55783e6735602e1afa0dc14b5dfdd429 | 6,472 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import ArgumentParserTestHelpers
import ArgumentParser
final class NestedCommandEndToEndTests: XCTestCase {
}
// MARK: Single value String
fileprivate struct Foo: ParsableCommand {
static var configuration =
CommandConfiguration(subcommands: [Build.self, Package.self])
@Flag(name: .short)
var verbose: Bool = false
struct Build: ParsableCommand {
@OptionGroup() var foo: Foo
@Argument()
var input: String
}
struct Package: ParsableCommand {
static var configuration =
CommandConfiguration(subcommands: [Clean.self, Config.self])
@Flag(name: .short)
var force: Bool = false
struct Clean: ParsableCommand {
@OptionGroup() var foo: Foo
@OptionGroup() var package: Package
}
struct Config: ParsableCommand {
@OptionGroup() var foo: Foo
@OptionGroup() var package: Package
}
}
}
fileprivate func AssertParseFooCommand<A>(_ type: A.Type, _ arguments: [String], file: StaticString = #file, line: UInt = #line, closure: (A) throws -> Void) where A: ParsableCommand {
AssertParseCommand(Foo.self, type, arguments, file: file, line: line, closure: closure)
}
extension NestedCommandEndToEndTests {
func testParsing_package() throws {
AssertParseFooCommand(Foo.Package.self, ["package"]) { package in
XCTAssertFalse(package.force)
}
AssertParseFooCommand(Foo.Package.Clean.self, ["package", "clean"]) { clean in
XCTAssertEqual(clean.foo.verbose, false)
XCTAssertEqual(clean.package.force, false)
}
AssertParseFooCommand(Foo.Package.Clean.self, ["package", "-f", "clean"]) { clean in
XCTAssertEqual(clean.foo.verbose, false)
XCTAssertEqual(clean.package.force, true)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "-v", "config"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, false)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "config", "-v"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, false)
}
AssertParseFooCommand(Foo.Package.Config.self, ["-v", "package", "config"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, false)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "-f", "config"]) { config in
XCTAssertEqual(config.foo.verbose, false)
XCTAssertEqual(config.package.force, true)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "config", "-f"]) { config in
XCTAssertEqual(config.foo.verbose, false)
XCTAssertEqual(config.package.force, true)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "-v", "config", "-f"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, true)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "-f", "config", "-v"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, true)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "-vf", "config"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, true)
}
AssertParseFooCommand(Foo.Package.Config.self, ["package", "-fv", "config"]) { config in
XCTAssertEqual(config.foo.verbose, true)
XCTAssertEqual(config.package.force, true)
}
}
func testParsing_build() throws {
AssertParseFooCommand(Foo.Build.self, ["build", "file"]) { build in
XCTAssertEqual(build.foo.verbose, false)
XCTAssertEqual(build.input, "file")
}
}
func testParsing_fails() throws {
XCTAssertThrowsError(try Foo.parseAsRoot(["clean", "package"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["config", "package"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["package", "c"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["package", "build"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["package", "build", "clean"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["package", "clean", "foo"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["package", "config", "bar"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["package", "clean", "build"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["build"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["build", "-f"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["build", "--build"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["build", "--build", "12"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["-f", "package", "clean"]))
XCTAssertThrowsError(try Foo.parseAsRoot(["-f", "package", "config"]))
}
}
private struct Options: ParsableArguments {
@Option() var firstName: String?
}
private struct UniqueOptions: ParsableArguments {
@Option() var lastName: String?
}
private struct Super: ParsableCommand {
static var configuration: CommandConfiguration {
.init(subcommands: [Sub1.self, Sub2.self])
}
@OptionGroup() var options: Options
struct Sub1: ParsableCommand {
@OptionGroup() var options: Options
}
struct Sub2: ParsableCommand {
@OptionGroup() var options: UniqueOptions
}
}
extension NestedCommandEndToEndTests {
func testParsing_SharedOptions() throws {
AssertParseCommand(Super.self, Super.self, []) { sup in
XCTAssertNil(sup.options.firstName)
}
AssertParseCommand(Super.self, Super.self, ["--first-name", "Foo"]) { sup in
XCTAssertEqual("Foo", sup.options.firstName)
}
AssertParseCommand(Super.self, Super.Sub1.self, ["sub1"]) { sub1 in
XCTAssertNil(sub1.options.firstName)
}
AssertParseCommand(Super.self, Super.Sub1.self, ["sub1", "--first-name", "Foo"]) { sub1 in
XCTAssertEqual("Foo", sub1.options.firstName)
}
AssertParseCommand(Super.self, Super.Sub2.self, ["sub2", "--last-name", "Foo"]) { sub2 in
XCTAssertEqual("Foo", sub2.options.lastName)
}
}
}
| 33.533679 | 184 | 0.675989 |
e0cd760e33ca51901680d39395dbfe897ba25a8a | 2,130 | //
// ViewController.swift
// BSupermanNetworkKit
//
// Created by gemini2100 on 03/22/2018.
// Copyright (c) 2018 gemini2100. All rights reserved.
//
import UIKit
import RxSwift
import BSupermanNetworkKit
class ViewController: UIViewController {
//let manager = BSupermanNetworkManager<BSupermanNetworkAPI>()
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let endpoint = BSupermanNetworkAPI.userLogin(name: "11223344553", password: "123456")
let resultObservable: Observable<(String?,LoginEntity?)> = networkKitRequest(endPoint: endpoint)
_ = resultObservable.subscribe(onNext: { ( result:(responseError:String?,data:LoginEntity?)) in
print("get result: \(result)")
},
onError: { (error:Error) in print(" Get error:\(error)")},
onCompleted: {print("onCompleted!!")},
onDisposed: {print("onDisposed!!")})
// BSupermanNetworkManager<BSupermanNetworkAPI>.requestAPI(endPoint: endpoint , isUserSampleFile: false).subscribe { (result:Event<ResponseResult<LoginEntity>>) in
// print("\(result)")
// }
// .subscribe(onNext: { ( result:ResponseResult<LoginEntity>) in
// print("get result: \(result)")
//
//// switch result {
////
//// case let .succeed(data):
////
//// //self.storeAppConfigure(Cfg: data.cfg!)
////
//// //self.getAppConfigure()
//// print(data)
////
//// }
//
//
//
// })//,
// onError: { print(" Get error:\($0)")},
// onCompleted: {print("onCompleted!!")},
// onDisposed: {print("onDisposed!!")})
//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 29.178082 | 170 | 0.538967 |
9bbe07a479d488319a4cc4136881051d3231dc76 | 1,710 | //
// ClientView.swift
// Realtime
//
// Created by Andrew Levy on 9/30/20.
// Copyright © 2020 Rootstrap. All rights reserved.
//
import SwiftUI
struct ClientView: View {
func getAgentData() -> Void {
}
var body: some View {
VStack {
VStack(alignment: .leading, spacing: 10){
HStack {
NavigationLink(destination: StatusBarView(client: "name here")) {
Text("Client Name")
.font(.system(size: 15))
.fontWeight(.heavy)
.foregroundColor(.primary)
}
Spacer()
Button(action: {}) {
Image(systemName: "doc.on.doc")
}
Button(action: {}) {
Image(systemName: "square.and.pencil")
}
Button(action: {}) {
Image(systemName: "trash")
}
}
Text("Property")
.font(.system(size: 15))
.foregroundColor(.primary)
Text("100%")
.font(.system(size: 15))
.foregroundColor(.primary)
StatusBarView(client: "name here")
}.padding(.all, 30)
}
.background(Color(UIColor.systemGray6))
.padding(.all, 10)
.cornerRadius(45.0)
.onAppear(perform: getAgentData)
}
}
struct ClientView_Previews: PreviewProvider {
static var previews: some View {
ClientView()
}
}
| 28.5 | 85 | 0.426316 |
50aa975e5c3be3854abecc264d57d2fd25366258 | 776 | // swift-tools-version:4.2
// Managed by ice
import PackageDescription
let package = Package(
name: "SwiftBinarySearch",
products: [
.library(name: "SwiftBinarySearch",
targets: ["SwiftBinarySearch"]),
.library(name: "SwiftBinarySearchExtensions",
targets: ["SwiftBinarySearchExtensions"]),
],
targets: [
.target(name: "SwiftBinarySearch",
dependencies: []),
.target(name: "SwiftBinarySearchExtensions",
dependencies: ["SwiftBinarySearch"]),
.testTarget(name: "SwiftBinarySearchTests",
dependencies: ["SwiftBinarySearch"]),
.testTarget(name: "ExtensionsBinarySearchTests",
dependencies: ["SwiftBinarySearchExtensions"]),
],
swiftLanguageVersions: [.v4, .v4_2]
)
| 20.421053 | 56 | 0.655928 |
626c2ff7a437c14bb35a25c805707422ec5a36a3 | 3,895 | //
// ViewController.swift
// Tipper
//
// Created by Alex V Phan on 1/21/20.
// Copyright © 2020 Alex V Phan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var numberOnScreen:Double = 0
@IBOutlet weak var roundButton1: UIButton!
@IBOutlet weak var roundButton2: UIButton!
@IBOutlet weak var roundButton3: UIButton!
@IBOutlet weak var roundButton4: UIButton!
@IBOutlet weak var roundButton5: UIButton!
@IBOutlet weak var roundButton6: UIButton!
@IBOutlet weak var roundButton7: UIButton!
@IBOutlet weak var roundButton8: UIButton!
@IBOutlet weak var roundButton9: UIButton!
@IBOutlet weak var roundButtonDecimal: UIButton!
@IBOutlet weak var roundButton0: UIButton!
@IBOutlet weak var roundButtonBackspace: UIButton!
@IBOutlet weak var roundButtonAC: UIButton!
@IBOutlet weak var billAmount: UILabel!
@IBOutlet weak var tipAmount: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.applyRoundCorner(roundButton1)
self.applyRoundCorner(roundButton2)
self.applyRoundCorner(roundButton3)
self.applyRoundCorner(roundButton4)
self.applyRoundCorner(roundButton5)
self.applyRoundCorner(roundButton6)
self.applyRoundCorner(roundButton7)
self.applyRoundCorner(roundButton8)
self.applyRoundCorner(roundButton9)
self.applyRoundCorner(roundButtonDecimal)
self.applyRoundCorner(roundButtonAC)
roundButton0.layer.cornerRadius = 35
roundButtonBackspace.layer.cornerRadius = 30
tipControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: (145 / 255.0), blue: (147 / 255.0), alpha: 1.0)], for: .normal)
}
func applyRoundCorner(_ object:AnyObject) {
object.layer.cornerRadius = object.frame.size.width / 2
object.layer.masksToBounds = true
}
@IBAction func numbers(_ sender: UIButton) {
billAmount.text = billAmount.text! + String(sender.tag - 1)
numberOnScreen = Double(billAmount.text!)!
}
@IBAction func clear(_ sender: UIButton) {
// AC button
if sender.tag == 11 {
billAmount.text = ""
numberOnScreen = 0.0
}
// Backspace button
else if sender.tag == 12 {
let temp = (billAmount.text!)
billAmount.text = String(temp.dropLast())
}
}
@IBAction func decimal(_ sender: UIButton) {
let temp = billAmount.text!
if billAmount.text == "" {
billAmount.text = "0."
}
else if billAmount.text!.contains(".") {
billAmount.text = temp;
}
else {
billAmount.text = String(temp) + "."
}
}
@IBAction func calculateTip(_ sender: Any) {
// Get the bill amount
// let bill = Double(billField.text!) ?? 0
// Calculate the tip and total
let tipPercentages = [0.15, 0.18, 0.2]
let tip = numberOnScreen * tipPercentages[tipControl.selectedSegmentIndex]
let total = numberOnScreen + tip
// Update the tip and total labels
// tipAmount.text = "$\(tip)"
tipAmount.text = String(format: "$%.2f", tip)
//total.text = "$\(total)"
totalLabel.text = String(format: "$%.2f", total)
}
}
/*
class BillLabel: UILabel {
override var text: String? {
didSet {
if let text = text {
print("Text changed.")
}
else {
print("Text not changed.")
}
}
}
}
*/
| 30.912698 | 165 | 0.609243 |
0a85b7fd06a883180d29a1178d774d178b50fea8 | 311 | //
// AddedCitiesReadService.swift
// WeatherLookup
//
// Created by Alexander Smyshlaev on 16/07/2019.
// Copyright © 2019 Alexander Smyshlaev. All rights reserved.
//
import Foundation
protocol AddedCitiesReadService {
func allAddedCities() -> [AddedCity]
func allNonAddedCities() -> [String]
}
| 20.733333 | 62 | 0.723473 |
fb7db91e0063c0a9421a88a25a138d5631cc08fc | 2,138 | import Foundation
import UIKit
import Caravel
import WebKit
class BenchmarkController: UIViewController {
@IBOutlet weak var webView: UIWebView!
fileprivate weak var bus: EventBus?
fileprivate var wkWebView: WKWebView?
fileprivate var draftForBenchmarking: EventBus.Draft?
override func viewDidLoad() {
super.viewDidLoad()
let request = URLRequest(url: Bundle.main.url(forResource: "benchmark", withExtension: "html")!)
let action = {(bus: EventBus) in
self.bus = bus
}
if BaseController.isUsingWKWebView {
let config = WKWebViewConfiguration()
let draft = Caravel.getDraft(config)
self.draftForBenchmarking = Caravel.getDraft(config)
self.wkWebView = WKWebView(frame: webView.frame, configuration: config)
webView.removeFromSuperview()
self.view.addSubview(self.wkWebView!)
Caravel.getDefaultReady(self, wkWebView: self.wkWebView!, draft: draft, whenReady: action)
self.wkWebView!.load(request)
} else {
Caravel.getDefault(self, webView: webView, whenReady: action)
webView.loadRequest(request)
}
}
@IBAction func onStart(_ sender: AnyObject) {
let name = UUID().uuidString
let action = {(bus: EventBus) in
for i in 0..<1000 {
bus.register("Background-\(i)") {name, _ in
bus.post("\(name)-confirmation")
}
bus.registerOnMain("Main-\(i)") {name, _ in
bus.post("\(name)-confirmation")
}
}
bus.post("Ready")
}
if BaseController.isUsingWKWebView {
Caravel.get(self, name: name, wkWebView: self.wkWebView!, draft: self.draftForBenchmarking!, whenReady: action)
} else {
Caravel.get(self, name: name, webView: webView, whenReady: action)
}
self.bus!.post("BusName", data: name)
}
}
| 33.40625 | 123 | 0.565482 |
1cac41ff2e18056df38861507d9138b1d3c23f2a | 5,393 | // Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import TrustWalletCore
import XCTest
class BitcoinAddressTests: XCTestCase {
func testInvalid() {
XCTAssertNil(BitcoinAddress(string: "abc"))
XCTAssertNil(BitcoinAddress(string: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"))
XCTAssertNil(BitcoinAddress(string: "175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"))
}
func testInitWithString() {
let address = BitcoinAddress(string: "1AC4gh14wwZPULVPCdxUkgqbtPvC92PQPN")
XCTAssertNotNil(address)
XCTAssertEqual(address!.description, "1AC4gh14wwZPULVPCdxUkgqbtPvC92PQPN")
}
func testFromPrivateKey() {
let data = Data(hexString: "f7b5f7a8090c5c93cd2d6d01383c9286b221ea78d8bef3e482f0c5cdde653e68")!
let privateKey = PrivateKey(data: data)!
let publicKey = privateKey.getPublicKeySecp256k1(compressed: true)
let address = BitcoinAddress.compatibleAddress(publicKey: publicKey, prefix: P2SHPrefix.bitcoin.rawValue)
XCTAssertEqual(address.description, "3Hv6oV8BYCoocW4eqZaEXsaR5tHhCxiMSk")
}
func testFromPrivateKeyUncompressed() {
let data = Data(hexString: "f7b5f7a8090c5c93cd2d6d01383c9286b221ea78d8bef3e482f0c5cdde653e68")!
let privateKey = PrivateKey(data: data)!
let publicKey = privateKey.getPublicKeySecp256k1(compressed: false)
let address = BitcoinAddress.compatibleAddress(publicKey: publicKey, prefix: P2SHPrefix.bitcoin.rawValue)
XCTAssertEqual(address.description, "3Hv6oV8BYCoocW4eqZaEXsaR5tHhCxiMSk")
}
func testFromPrivateKeySegwitAddress() {
let data = Data(hexString: "28071bf4e2b0340db41b807ed8a5514139e5d6427ff9d58dbd22b7ed187103a4")!
let privateKey = PrivateKey(data: data)!
let publicKey = privateKey.getPublicKeySecp256k1(compressed: true)
let address = BitcoinAddress(publicKey: publicKey, prefix: P2PKHPrefix.bitcoin.rawValue)!
XCTAssertEqual(address.description, BitcoinAddress(string: "1PeUvjuxyf31aJKX6kCXuaqxhmG78ZUdL1")!.description)
}
func testIsValid() {
XCTAssertFalse(BitcoinAddress.isValidString(string: "abc"))
XCTAssertFalse(BitcoinAddress.isValidString(string: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"))
XCTAssertFalse(BitcoinAddress.isValidString(string: "175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"))
XCTAssertTrue(BitcoinAddress.isValidString(string: "1AC4gh14wwZPULVPCdxUkgqbtPvC92PQPN"))
}
func testCompressedPublicKey() {
// compressed public key starting with 0x03 (greater than midpoint of curve)
let compressedPK = PublicKey(data: Data(hexString: "030589ee559348bd6a7325994f9c8eff12bd5d73cc683142bd0dd1a17abc99b0dc")!, type: .secp256k1)!
XCTAssertTrue(compressedPK.isCompressed)
XCTAssertEqual(BitcoinAddress(publicKey: compressedPK, prefix: 0)!.description, "1KbUJ4x8epz6QqxkmZbTc4f79JbWWz6g37")
}
func testPublicKeyToSegwitAddress() {
let publicKey = PublicKey(data: Data(hexString: "0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798")!, type: .secp256k1)!
let expect = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"
XCTAssertTrue(SegwitAddress.isValidString(string: expect))
let address = SegwitAddress(hrp: .bitcoin, publicKey: publicKey)
XCTAssertEqual(address.description, expect)
let addressFromString = SegwitAddress(string: expect)
XCTAssertEqual(address.description, addressFromString?.description)
}
func testInvalidSegwitAddresses() {
let addresses = [
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5",
"bc1rw5uspcuh",
"bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90",
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7",
"bc1zw508d6qejxtdg4y5r3zarvaryvqyzf3du",
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv",
"bc1gmk9yu",
]
for invalid in addresses {
XCTAssertFalse(SegwitAddress.isValidString(string: invalid), "'\(invalid)' should not be a valid Bech32 address")
}
}
func testValidDigiByteAddress() {
let addressString = "DTPQ92zp96TwpG2pRuUB3oEA3kWGRZPGhg"
XCTAssertEqual(P2PKHPrefix.d.rawValue, BitcoinAddress(string: addressString)?.prefix)
XCTAssertTrue(BitcoinAddress.isValidString(string: addressString),
"'\(addressString)' should be a valid DigiByte address")
let addressString2 = "SUngTA1vaC2E62mbnc81Mdos3TcvZHwsVo"
XCTAssertEqual(P2SHPrefix.s.rawValue, BitcoinAddress(string: addressString2)?.prefix)
XCTAssertTrue(BitcoinAddress.isValidString(string: addressString2),
"'\(addressString2)' should be a valid DigiByte address")
let addressString3 = "dgb1qtjgmerfqwdffyf8ghcrkgy52cghsqptynmyswu"
XCTAssertEqual(HRP.digiByte, SegwitAddress(string: addressString3)?.hrp)
XCTAssertTrue(SegwitAddress.isValidString(string: addressString3),
"'\(addressString3)' should be a valid DigiByte Bech32 address")
}
}
| 47.307018 | 149 | 0.739292 |
1e1bd95369a284d17d5fe0df04b51e05c7982581 | 1,843 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallClipRotate: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.75
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
// Draw circle
let circle = ActivityIndicatorShape.ringThirdFour.makeLayer(size: CGSize(width: size.width, height: size.height), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallClipRotate {
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.6, 1]
return scaleAnimation
}
var rotateAnimation: CAKeyframeAnimation {
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
return rotateAnimation
}
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| 30.213115 | 131 | 0.712968 |
c13a55b00b8b53ee5d881606ab7ae8b704f12aa5 | 1,535 | // Copyright DEXON Org. All rights reserved.
import UIKit
import DexonWalletSDK
class SignTypedMessageViewController: SignMessageViewController {
override var defaultMessage: String {
return """
{"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Person":[{"name":"name","type":"string"},{"name":"wallet","type":"address"}],"Mail":[{"name":"from","type":"Person"},{"name":"to","type":"Person"},{"name":"contents","type":"string"}]},"primaryType":"Mail","domain":{"name":"Ether Mail","version":"1","chainId":238,"verifyingContract":"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},"message":{"from":{"name":"Cow","wallet":"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},"to":{"name":"Bob","wallet":"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"},"contents":"Hello, Bob!"}}
"""
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func signMessage(fromAddress: String?, messageData: Data) {
let method = SignTypedMessageMethod(
message: messageData,
fromAddress: fromAddress) { [weak self] (result) in
switch result {
case .success(let signature):
self?.resultLabel.text = "signature: \(signature)"
case .failure(let error):
self?.resultLabel.text = "error: \(error)"
}
}
dexonWalletSDK.run(method: method)
}
}
| 46.515152 | 694 | 0.623453 |
39febc42380aefda834b61a8673d854e93c08563 | 364 | //
// Created by 和泉田 領一 on 2016/02/25.
// Copyright (c) 2016 CAPH TECH. All rights reserved.
//
import Foundation
public protocol TransitionPayloadType: class {
var payloadValue: Any? { get }
}
public class TransitionPayload: TransitionPayloadType {
public var payloadValue: Any?
public init(value: Any?) {
payloadValue = value
}
}
| 15.826087 | 55 | 0.681319 |
7ada56642e1e40f60c07a4b561b92a2a9db94c8e | 1,838 | //
// LocationManager.swift
// Vens
//
// Created by Albert on 12/04/2020.
// Copyright © 2020 Aina Cuxart. All rights reserved.
//
import Foundation
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject {
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
@Published var locationStatus: CLAuthorizationStatus? {
willSet {
objectWillChange.send()
}
}
@Published var lastLocation: CLLocation? {
willSet {
objectWillChange.send()
}
}
var statusString: String {
guard let status = locationStatus else {
return "unknown"
}
switch status {
case .notDetermined: return "notDetermined"
case .authorizedWhenInUse: return "authorizedWhenInUse"
case .authorizedAlways: return "authorizedAlways"
case .restricted: return "restricted"
case .denied: return "denied"
default: return "unknown"
}
}
let objectWillChange = PassthroughSubject<Void, Never>()
private let locationManager = CLLocationManager()
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.locationStatus = status
print(#function, statusString)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
self.lastLocation = location
print(#function, location)
}
}
| 26.257143 | 110 | 0.670294 |
ef5bfc0852a7c3dc684495ab563dca5b0daa94d0 | 19,227 | //
// Models.swift
// FetLife
//
// Created by Jose Cortinas on 2/24/16.
// Copyright © 2016 BitLove Inc. All rights reserved.
//
import RealmSwift
import Freddy
import DateTools
import HTMLEntities
private let dateFormatter: DateFormatter = DateFormatter()
// MARK: - Member
class Member: Object, JSONDecodable {
static let defaultAvatarURL = "https://ass3.fetlife.com/images/avatar_missing_200x200.gif"
@objc dynamic var id = ""
@objc dynamic var nickname = ""
@objc dynamic var metaLine = ""
@objc dynamic var avatarURL = ""
@objc dynamic var avatarImageData: Data?
@objc dynamic var orientation = ""
@objc dynamic var aboutMe = ""
@objc dynamic var age: Int = 0
@objc dynamic var city = ""
@objc dynamic var state = ""
@objc dynamic var country = ""
@objc dynamic var genderName = ""
@objc dynamic var canFollow = true
@objc dynamic var contentType = ""
@objc dynamic var fetProfileURL = ""
@objc dynamic var isSupporter = false
@objc dynamic var relationWithMe = ""
@objc dynamic var friendCount: Int = 0
@objc dynamic var blocked = false
@objc dynamic var lookingFor: [String] { // we're using this complicated mess because Realm doesn't support primitive arrays 😑
get {
return _lookingFor.map { $0.stringValue }
}
set {
_lookingFor.removeAll()
_lookingFor.append(objectsIn: newValue.map({ RealmString(value: [$0]) }))
}
}
private let _lookingFor = List<RealmString>()
@objc dynamic var notificationToken = ""
var additionalInfoRetrieved: Bool { get { guard orientation != "" && contentType != "" && country != "" else { return false }; return true } }
@objc var lastUpdated: Date = Date()
override static func ignoredProperties() -> [String] {
return ["lookingFor", "additionalInfoRetrieved", "blocked"]
}
override static func primaryKey() -> String? {
return "id"
}
required convenience init(json: JSON) throws {
self.init()
id = try json.getString(at: "id")
nickname = try json.getString(at: "nickname")
metaLine = try json.getString(at: "meta_line")
do {
avatarURL = try json.getString(at: "avatar", "variants", "medium", or: Member.defaultAvatarURL)
if let aURL = URL(string: avatarURL) {
avatarImageData = try? Data(contentsOf: aURL)
}
} catch {
avatarURL = Member.defaultAvatarURL
}
orientation = (try? json.getString(at: "sexual_orientation")) ?? ""
aboutMe = (try? json.getString(at: "about")) ?? ""
age = (try? json.getInt(at: "age")) ?? 0
city = (try? json.getString(at: "city")) ?? ""
state = (try? json.getString(at: "administrative_area")) ?? ""
country = (try? json.getString(at: "country")) ?? ""
genderName = (try? json.getString(at: "gender", "name")) ?? ""
canFollow = (try? json.getBool(at: "is_followable")) ?? true
contentType = (try? json.getString(at: "content_type")) ?? ""
fetProfileURL = (try? json.getString(at: "url")) ?? ""
isSupporter = (try? json.getBool(at: "is_supporter")) ?? false
relationWithMe = (try? json.getString(at: "relation_with_me")) ?? ""
friendCount = (try? json.getInt(at: "friend_count")) ?? 0
var lf: [String] = []
if let ljson = try? json.getArray(at: "looking_for") as [AnyObject] {
for j in ljson {
lf.append((j.description) ?? "")
}
}
notificationToken = (try? json.getString(at: "notification_token")) ?? "" // only for logged-in user
lookingFor = lf
}
private static var addlInfoAttempts = 0
static func getAdditionalUserInfo(_ member: Member, _ completion: ((Bool, Member?) -> Void)?) {
let oldMember = try! Realm().objects(Member.self).filter("id == %@", member.id).first ?? member
print("Old member \(member.nickname) == member? \(oldMember == member)")
print("Additional info retrieved: \(oldMember.additionalInfoRetrieved)")
print("Old member last updated \(oldMember.lastUpdated.description(with: Locale.current))")
if !oldMember.additionalInfoRetrieved || oldMember != member {
print("Getting additional user info for \(member.nickname)...")
let realm = try! Realm()
if realm.isInWriteTransaction { // we can't add a change notification while in a write transaction, so we have to wait...
if addlInfoAttempts <= 10 {
addlInfoAttempts += 1
print("Unable to get additional user info for \(member.nickname). Will try again in ~\(addlInfoAttempts)s...")
Dispatch.delay(Double(addlInfoAttempts) * (2 * drand48())) { // randomized to prevent collisions with other cells
self.getAdditionalUserInfo(member, completion)
}
return
} else {
print("Getting additional user info for \(member.nickname) failed too many times!")
}
} else {
Dispatch.delay(drand48() * 2) {
// get a more detailed Member object from the API and replace when possible
let sd = Date()
API.sharedInstance.getFetUser(member.id, completion: { (userInfo, err) in
if err == nil && userInfo != nil {
do {
if let u = userInfo {
try member.updateMemberInfo(u) { m in
self.addlInfoAttempts = 0
print("Successfully updated user info for \(m.nickname)")
let fd = Date()
print("time elapsed: \(fd.timeIntervalSince(sd))\n---")
completion?(true, m)
}
}
} catch let e {
print("Error updating info for \(member.nickname): \(e.localizedDescription)")
completion?(false, nil)
return
}
} else if err != nil {
completion?(false, nil)
}
})
addlInfoAttempts = 0
}
}
} else {
completion?(true, member)
}
}
private var updateAttempts: Int = 0
func updateMemberInfo(_ json: JSON, completion: @escaping ((Member) throws -> Void)) throws {
let realm = try! Realm()
if realm.isInWriteTransaction { // we can't add a change notification while in a write transaction, so we have to wait...
if updateAttempts <= 10 {
updateAttempts += 1
let updateDelay: Double = Double(updateAttempts) * (drand48() + drand48())
print("Unable to update member info. Will try again in ~\(updateDelay)s...")
Dispatch.delay(updateDelay) { // randomized to prevent collisions with other cells
try? self.updateMemberInfo(json, completion: completion)
}
} else {
print("Updating member info failed too many times!")
}
} else {
realm.beginWrite()
if let err = try? json.getString(at: "error") {
if err == "Forbidden" {
blocked = true
try! realm.commitWrite()
throw APIError.Forbidden
} else {
try! realm.commitWrite()
throw APIError.General(description: err)
}
} else {
blocked = false
}
nickname = (try? json.getString(at: "nickname")) ?? nickname
metaLine = (try? json.getString(at: "meta_line")) ?? metaLine
do {
avatarURL = try json.getString(at: "avatar", "variants", "medium", or: Member.defaultAvatarURL)
if let aURL = URL(string: avatarURL) {
avatarImageData = try? Data(contentsOf: aURL)
}
} catch {
avatarURL = Member.defaultAvatarURL
}
orientation = (try? json.getString(at: "sexual_orientation")) ?? ""
aboutMe = (try? json.getString(at: "about")) ?? ""
age = (try? json.getInt(at: "age")) ?? 0
city = (try? json.getString(at: "city")) ?? ""
state = (try? json.getString(at: "administrative_area")) ?? ""
country = (try? json.getString(at: "country")) ?? ""
genderName = (try? json.getString(at: "gender", "name")) ?? ""
canFollow = (try? json.getBool(at: "is_followable")) ?? true
contentType = (try? json.getString(at: "content_type")) ?? ""
fetProfileURL = (try? json.getString(at: "url")) ?? ""
isSupporter = (try? json.getBool(at: "is_supporter")) ?? false
relationWithMe = (try? json.getString(at: "relation_with_me")) ?? "self"
friendCount = (try? json.getInt(at: "friend_count")) ?? 0
var lf: [String] = []
if let ljson = try? json.getArray(at: "looking_for") as [AnyObject] {
for j in ljson {
lf.append((j.description) ?? "")
}
}
lookingFor = lf
notificationToken = (try? json.getString(at: "notification_token")) ?? "" // only for current logged-in user
realm.add(self, update: true)
try! realm.commitWrite()
lastUpdated = Date()
try completion(self)
updateAttempts = 0
}
}
static func getMemberFromURL(_ url: URL) -> Member? {
guard url.absoluteString.matches(CommonRegexes.profileURL) else { return nil }
return try! Realm().objects(Member.self).filter("fetProfileURL == %@", url.absoluteString.lowercased()).first
}
static func getMemberFromString(_ url: String) -> Member? {
guard url.matches(CommonRegexes.profileURL) else { return nil }
return try! Realm().objects(Member.self).filter("fetProfileURL == %@", url.lowercased()).first
}
static func ==(a: Member, b: Member) -> Bool {
guard a.id == b.id else { return false }
guard a.metaLine == b.metaLine else { return false }
guard a.nickname == b.nickname else { return false }
return true
}
static func !=(a: Member, b: Member) -> Bool {
return !(a == b)
}
/// Determines if all the properties of two members are the same
static func ===(a: Member, b: Member) -> Bool {
guard a.id == b.id else { return false }
guard a.aboutMe == b.aboutMe else { return false }
guard a.age == b.age else { return false }
guard a.avatarURL == b.avatarURL else { return false }
guard a.canFollow == b.canFollow else { return false }
guard a.city == b.city else { return false }
guard a.contentType == b.contentType else { return false }
guard a.country == b.country else { return false }
guard a.friendCount == b.friendCount else { return false }
guard a.genderName == b.genderName else { return false }
guard a.isSupporter == b.isSupporter else { return false }
guard a.lookingFor == b.lookingFor else { return false }
guard a.metaLine == b.metaLine else { return false }
guard a.nickname == b.nickname else { return false }
guard a.notificationToken == b.notificationToken else { return false }
guard a.orientation == b.orientation else { return false }
guard a.state == b.state else { return false }
return true
}
static func !==(a: Member, b: Member) -> Bool {
return !(a === b)
}
}
// MARK: - Conversation
class Conversation: Object, JSONDecodable {
@objc dynamic var id = ""
@objc dynamic var updatedAt = Date()
@objc dynamic var member: Member?
@objc dynamic var hasNewMessages = false
@objc dynamic var isArchived = false
@objc dynamic var subject = ""
@objc dynamic var lastMessageBody = ""
@objc dynamic var lastMessageCreated = Date()
@objc dynamic var lastMessageIsIncoming = false
private var json: JSON!
override static func primaryKey() -> String? {
return "id"
}
override static func ignoredProperties() -> [String] {
return ["json"]
}
required convenience init(json: JSON) throws {
self.init()
self.json = json
id = try json.getString(at: "id")
updatedAt = try dateStringToNSDate(json.getString(at: "updated_at"))!
if let mID = try? json.getString(at: "member", "id"), let m = try! Realm().objects(Member.self).filter("id == %@", mID).first {
self.member = m
} else {
self.member = try? json.decode(at: "member", type: Member.self)
}
hasNewMessages = try json.getBool(at: "has_new_messages")
isArchived = try json.getBool(at: "is_archived")
if let lastMessage = json["last_message"] {
lastMessageBody = try decodeHTML(lastMessage.getString(at: "body"))
lastMessageCreated = try dateStringToNSDate(lastMessage.getString(at: "created_at"))!
let lastMessageMemberID: String = try lastMessage.getString(at: "member", "id")
let memberID: String = try json.getString(at: "member", "id")
lastMessageIsIncoming = (lastMessageMemberID == memberID)
}
subject = (try? json.getString(at: "subject")) ?? ""
Dispatch.asyncOnUserInitiatedQueue {
guard self.member != nil else { return }
if self.member!.lastUpdated.hoursFromNow >= 24 { // every 24 hours update the user profile information
Member.getAdditionalUserInfo(self.member!, nil)
}
}
}
private var attempts: Int = 0
func updateMember() {
let realm: Realm = (self.realm != nil) ? self.realm! : try! Realm()
if realm.isInWriteTransaction {
if attempts <= 10 {
attempts += 1
print("Unable to create member. Will try again in ~\(attempts)s...")
Dispatch.delay(Double(attempts) * (2 * drand48())) { // randomized to prevent collisions with other cells
self.updateMember()
}
} else {
print("Creating member failed too many times!")
}
} else {
let _m = self.member
do {
try realm.write {
if let id = _m?.id, let m = try! Realm().objects(Member.self).filter("id == %@", id).first {
self.member = m
} else {
self.member = _m
}
guard self.member != nil else { return }
realm.add(self.member!, update: true)
}
// get existing conversation in realm if possible
if let c = try! Realm().objects(Conversation.self).filter("id == %@", self.id).first, let m = self.member {
// create thread-safe reference to conversation
let wrappedConvo = ThreadSafeReference(to: c)
let threadSafeMember = realm.resolve(wrappedConvo)?.member ?? m
try realm.write {
realm.add(threadSafeMember, update: true)
}
} else if self.member == nil {
print("Member is still nil")
} else {
print("Could not find conversation in Realm!")
}
} catch let e {
print("Error updating conversation in Realm: \(e.localizedDescription)")
}
attempts = 0
}
}
func summary() -> String {
return lastMessageBody
}
func timeAgo() -> String {
return (lastMessageCreated as NSDate).shortTimeAgoSinceNow()
}
}
// MARK: - Message
class Message: Object {
@objc dynamic var id = ""
@objc dynamic var body = ""
@objc dynamic var createdAt = Date()
@objc dynamic var memberId = ""
@objc dynamic var memberNickname = ""
@objc dynamic var isNew = false
@objc dynamic var isSending = false
@objc dynamic var conversationId = ""
override static func primaryKey() -> String? {
return "id"
}
required convenience init(json: JSON) throws {
self.init()
if let error = try? json.getString(at: "error") {
print(error)
if error == "Forbidden" {
throw APIError.Forbidden
} else {
throw APIError.General(description: error)
}
}
id = try json.getString(at: "id")
if let msg = try! Realm().objects(Message.self).filter("id == %@", self.id).first as Message? {
body = msg.body
} else {
body = try decodeHTML(json.getString(at: "body"))
}
createdAt = try dateStringToNSDate(json.getString(at: "created_at"))!
memberId = try json.getString(at: "member", "id")
memberNickname = try json.getString(at: "member", "nickname")
isNew = try json.getBool(at: "is_new")
}
}
// MARK: - Requests
class FriendRequest: Object {
@objc dynamic var id = ""
@objc dynamic var createdAt = Date()
@objc dynamic var member: Member?
override static func primaryKey() -> String? {
return "id"
}
required convenience init(json: JSON) throws {
self.init()
id = try json.getString(at: "id")
createdAt = try dateStringToNSDate(json.getString(at: "created_at"))!
member = try json.decode(at: "member", type: Member.self)
}
}
// MARK: - Util
class RealmString: Object { // using this to be able to store arrays of strings
@objc dynamic var stringValue = ""
}
// Convert from a JSON format datastring to an NSDate instance.
private func dateStringToNSDate(_ jsonString: String!) -> Date? {
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.date(from: jsonString)
}
// Decode html encoded strings. Not recommended to be used at runtime as this this is heavyweight,
// the output should be precomputed and cached.
private func decodeHTML(_ htmlEncodedString: String) -> String {
// remove extraneous tabs after newlines
let str = htmlEncodedString.replacingOccurrences(of: "\n ", with: "\n")
return str.htmlUnescape()
}
| 41.616883 | 146 | 0.549696 |
20d864ecace17c9d1743ec35b6ce0178d951887d | 1,421 | //
// RTCPeerConnection.swift
// Callstats
//
// Created by Amornchai Kanokpullwad on 10/6/18.
// Copyright © 2018 callstats. All rights reserved.
//
import Foundation
import WebRTC
/**
Convert RTCIceConnectionState to string value
*/
extension RTCIceConnectionState {
func toString() -> String {
switch self {
case .new: return "new"
case .checking: return "checking"
case .completed: return "completed"
case .connected: return "connected"
case .disconnected: return "disconnected"
case .failed: return "failed"
case .closed: return "closed"
case .count: return "count"
}
}
}
/**
Convert RTCIceGatheringState to string value
*/
extension RTCIceGatheringState {
func toString() -> String {
switch self {
case .new: return "new"
case .gathering: return "gathering"
case .complete: return "complete"
}
}
}
/**
Convert RTCSignalingState to string value
*/
extension RTCSignalingState {
func toString() -> String {
switch self {
case .stable: return "stable"
case .haveLocalOffer: return "have-local-offer"
case .haveRemoteOffer: return "have-remote-offer"
case .haveLocalPrAnswer: return "have-local-pranswer"
case .haveRemotePrAnswer: return "have-remote-pranswer"
case .closed: return "closed"
}
}
}
| 24.5 | 63 | 0.633357 |
212f46e13f1b8cc3fc516c3ff425081dd2c72d01 | 15,590 | //
// ViewController.swift
// Simplifier for Facebook
//
// Created by Patrick Botros on 4/23/20.
// Copyright © 2020 Patrick Botros. All rights reserved
//
import Cocoa
import SafariServices
let defaults = UserDefaults.standard
let appGroupID: String = "L27L4K8SQU.shockerella.Simplifier-for-Facebook"
let contentBlockerID: String = "shockerella.Simplifier-for-Facebook.Content-Blocker"
typealias SwiftyJSON = [SwiftyRule]
class BlockableElement {
let elementName: String
let rules: [BlockerRule]
var blocked: Bool
init(withName name: String, andRules rules: [BlockerRule], isBlockedByDefault blocked: Bool) {
self.elementName = name
self.rules = rules
self.blocked = blocked
}
convenience init(withName name: String, andRule rule: BlockerRule, isBlockedByDefault blocked: Bool) {
self.init(withName: name, andRules: [rule], isBlockedByDefault: blocked)
}
}
// Manually ensure these default block properties match the defaultBlockList.json.
var blockableElements: [BlockableElement] = [
BlockableElement(withName: "Newsfeed", andRules: [
BlockerRule(selector: "div.pedkr2u6.tn0ko95a.pnx7fd3z"),
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='www.facebook.com/?sk=h_chr']")
], isBlockedByDefault: false),
BlockableElement(withName: "Stories", andRule: BlockerRule(selector: "div.d2edcug0.e3xpq0al"), isBlockedByDefault: false),
BlockableElement(withName: "Create Post", andRule: BlockerRule(selector: "div.tr9rh885.k4urcfbm div.sjgh65i0 div.j83agx80.k4urcfbm.l9j0dhe7 div[aria-label='Create a post']"), isBlockedByDefault: false),
BlockableElement(withName: "Rooms", andRule: BlockerRule(selector: "div[data-pagelet='VideoChatHomeUnit']"), isBlockedByDefault: true),
BlockableElement(withName: "Friends", andRules: [
BlockerRule(selector: "li.buofh1pr a[href='/friends/']"),
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='/friends/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/friends/.*"], actionType: .block)
], isBlockedByDefault: false),
BlockableElement(withName: "Watch", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='facebook.com/watch/']"),
BlockerRule(selector: "li.buofh1pr.to382e16.o5zgeu5y.jrc8bbd0.dawyy4b1.h676nmdw.hw7htvoc a[href='/watch/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/watch.*"], actionType: .block)
], isBlockedByDefault: false),
BlockableElement(withName: "Marketplace", andRules: [
BlockerRule(selector: "li a[href$='/marketplace/?ref=bookmark']"),
BlockerRule(selector: "li.buofh1pr.to382e16.o5zgeu5y.jrc8bbd0.dawyy4b1.h676nmdw.hw7htvoc a[href='/marketplace/?ref=app_tab']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/marketplace.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Groups", andRules: [
BlockerRule(selector: "li a[href$='/groups/?ref=bookmarks']"),
BlockerRule(selector: "li.buofh1pr.h676nmdw a[href*='/groups/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/groups.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Messenger", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='www.facebook.com/messages/t/']"),
BlockerRule(selector: "div.bp9cbjyn.j83agx80.datstx6m div[aria-label='Messenger']")
], isBlockedByDefault: false),
BlockableElement(withName: "Right Sidebar", andRule: BlockerRule(selector: "div[data-pagelet='RightRail']"), isBlockedByDefault: false),
BlockableElement(withName: "Left Sidebar", andRule: BlockerRule(selector: "div[data-pagelet='LeftRail']"), isBlockedByDefault: false),
BlockableElement(withName: "Legal Footer", andRule: BlockerRule(selector: "footer[role='contentinfo']"), isBlockedByDefault: true),
BlockableElement(withName: "Events", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/events']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/events/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Pages", andRule: BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='facebook.com/pages/']"), isBlockedByDefault: true),
BlockableElement(withName: "Memories", andRule: BlockerRule(selector: "a[href$='/memories/?source=bookmark']"), isBlockedByDefault: true),
BlockableElement(withName: "Jobs", andRules: [
BlockerRule(selector: "a[href$='facebook.com/jobs/?source=bookmark']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/jobs.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Oculus", andRules: [
BlockerRule(selector: "a[href='https://www.facebook.com/270208243080697/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/Oculusvr/"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Blood Donations", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/blooddonations/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/blooddonations/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Ads", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/ads/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/ads/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Campus", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='www.facebook.com/campus/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/campus/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Community Help", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href='/community_help/?page_source=facebook_bookmark']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/community_help/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Facebook Pay", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='secure.facebook.com/facebook_pay/']"),
BlockerRule(triggers: [.urlFilter: "https?://secure.facebook.com/facebook_pay/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Weather", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/weather/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/weather/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "COVID-19 Information Center", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href='https://www.facebook.com/coronavirus_info/?page_source=bookmark']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/coronavirus_info/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Favorites", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href='https://www.facebook.com/?sk=favorites']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/?sk=favorites"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Friend Lists", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href='https://www.facebook.com/bookmarks/lists/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/bookmarks/lists/"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Fundraisers", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href='https://www.facebook.com/fundraisers/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/fundraisers/.*"], actionType: .block),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/donate/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Climate Science Information Center", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/climatescienceinfo/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/climatescienceinfo/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Games", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/games/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/games/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Gaming Video", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/gaming/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/gaming/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Lift Black Voices", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='/liftblackvoices/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/liftblackvoices/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Live", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='www.facebook.com/watch/live/?ref=live_bookmark']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/watch/live/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Messenger Kids", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='www.facebook.com/messenger_kids/?referrer=bookmark']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/messenger_kids/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Most Recent", andRule: BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='www.facebook.com/?sk=h_chr']"), isBlockedByDefault: true),
BlockableElement(withName: "Movies", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='www.facebook.com/movies/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/messenger_kids/.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Offers", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='/wallet']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/offers/v2/wallet.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Saved", andRule: BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='facebook.com/saved/']"), isBlockedByDefault: true),
BlockableElement(withName: "Town Hall", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href$='/townhall/?ref=bookmarks']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/townhall.*"], actionType: .block)
], isBlockedByDefault: true),
BlockableElement(withName: "Voting Information Center", andRules: [
BlockerRule(selector: "div[data-pagelet='LeftRail'] a[href*='/votinginformationcenter/']"),
BlockerRule(triggers: [.urlFilter: "https?://www.facebook.com/votinginformationcenter.*"], actionType: .block)
], isBlockedByDefault: true)
]
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, DOMElementCellDelegate {
@IBOutlet weak var tableView: NSTableView!
@IBAction func openIssuePage(_ sender: Any) {
NSWorkspace.shared.open(NSURL(string: "https://github.com/patrickshox/Simplifier-for-Facebook/issues")! as URL)
}
@IBAction func openSafariExtensionPreferences(_ sender: Any) {
SFSafariApplication.showPreferencesForExtension(withIdentifier: contentBlockerID)
}
override func viewDidLoad() {
super.viewDidLoad()
// reload with user's custom block preferences.
for blockListitem in blockableElements where defaults.object(forKey: blockListitem.elementName) != nil {
blockListitem.blocked = defaults.bool(forKey: blockListitem.elementName)
}
tableView.reloadData()
}
var activeBlockingRules = [SwiftyRule]()
func updateDataSource(blocked: Bool, index: Int) {
blockableElements[index].blocked = blocked
activeBlockingRules = [SwiftyRule]()
for elementIndex in 0...blockableElements.count-1 where blockableElements[elementIndex].blocked {
for rule in blockableElements[elementIndex].rules {
activeBlockingRules.append(rule.asSwiftyRule())
}
}
tableView.reloadData()
}
func updateBlockListJSON() {
let blockListJSON = try? JSONSerialization.data(withJSONObject: activeBlockingRules, options: .prettyPrinted)
let appGroupPathname = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupID)!
let blockListJSONfileLocation = appGroupPathname.appendingPathComponent("blockList.json")
try? blockListJSON!.write(to: blockListJSONfileLocation)
SFContentBlockerManager.reloadContentBlocker(withIdentifier: contentBlockerID, completionHandler: { error in
print(error ?? "🔄 Blocker reload success.")
})
}
}
// Basic tableView set up functions.
extension ViewController {
func numberOfRows(in tableView: NSTableView) -> Int {
return blockableElements.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let domElementReuseID = NSUserInterfaceItemIdentifier(rawValue: "domElementIdentifier")
if let cell = tableView.makeView(withIdentifier: domElementReuseID, owner: nil) as? ChecklistRow {
cell.elementName = blockableElements[row].elementName
if blockableElements[row].blocked {
cell.setAccessibilityLabel("Checked checkbox for \(cell.elementName ?? "element")")
cell.checkBoxImage.image = NSImage(named: "checked")
} else {
cell.setAccessibilityLabel("Unchecked checkbox for \(cell.elementName ?? "element")")
cell.checkBoxImage.image = NSImage(named: "unchecked")
}
cell.elementNameLabel?.stringValue = blockableElements[row].elementName
cell.containingViewController = self
cell.rowNumber = row
cell.blockableElements = blockableElements
return cell
}
return nil
}
}
// aesthetics 👨🏻🎨
class ColoredView: NSView {
override func updateLayer() {
self.layer?.backgroundColor = NSColor(named: "background_color")?.cgColor
}
}
// aesthetics 👨🏻🎨
extension ViewController {
override func viewWillAppear() {
super.viewWillAppear()
self.view.window?.isMovableByWindowBackground = true
tableView.rowHeight = 33
tableView.headerView = nil
tableView.selectionHighlightStyle = .none
}
}
| 51.452145 | 206 | 0.689801 |
fcb9084bdfa8c51c6c1c1f0615f6cfd3c51e7ff7 | 3,433 | //
// GCDTimer.swift
// GCDTimer
//
// Created by Hemanta Sapkota on 4/06/2015.
// Copyright (c) 2015 Hemanta Sapkota. All rights reserved.
//
import Foundation
/**
* GCD Timer.
*/
open class GCDTimer {
// Swift 3 has removed support for dispatch_once. This class does the same thing ( roughly )
class Once {
private var _onceTracker = [String]()
// From: http://stackoverflow.com/questions/37886994/dispatch-once-in-swift-3
public func doIt(token: String, block:() -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
public func reset(token: String) {
if let tokenIndex = _onceTracker.index(of: token) {
_onceTracker.remove(at: tokenIndex)
}
}
}
/// A serial queue for processing our timer tasks
fileprivate static let gcdTimerQueue = DispatchQueue(label: "gcdTimerQueue", attributes: [])
/// Timer Source
open let timerSource = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: GCDTimer.gcdTimerQueue)
/// Default internal: 1 second
fileprivate var interval:Double = 1
/// dispatch_once alternative
fileprivate let once = Once()
/// Event that is executed repeatedly
fileprivate var event: (() -> Void)!
open var Event: (() -> Void) {
get {
return event
}
set {
event = newValue
let time = DispatchTimeInterval.milliseconds(Int(interval * 1000.0))
#if swift(>=4.0)
self.timerSource.schedule(deadline: DispatchTime.now(), repeating: time)
#else
self.timerSource.scheduleRepeating(deadline: DispatchTime.now(), interval: time)
#endif
self.timerSource.setEventHandler { [weak self] in
self?.event()
}
}
}
/**
Init a GCD timer in a paused state.
- parameter intervalInSecs: Time interval in seconds
- returns: self
*/
public init(intervalInSecs: Double) {
self.interval = intervalInSecs
}
/**
Start the timer.
*/
open func start() {
once.doIt(token: "com.laex.GCDTimer") {
self.timerSource.resume()
}
}
/**
Pause the timer.
*/
open func pause() {
timerSource.suspend()
once.reset(token: "com.laex.GCDTimer")
}
/**
Executes a block after a delay on the main thread.
*/
open class func delay(_ afterSecs: Double, block: @escaping ()->()) {
let delayTime = DispatchTime.now() + Double(Int64(afterSecs * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: block)
}
/**
Executes a block after a delay on a specified queue.
*/
open class func delay(_ afterSecs: Double, queue: DispatchQueue, block: @escaping ()->()) {
let delayTime = DispatchTime.now() + Double(Int64(afterSecs * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: delayTime, execute: block)
}
}
| 28.848739 | 141 | 0.572968 |
fb28c51c6c6fd45ca2e31b3ef53b68e301d793b1 | 2,124 | //
// ViewController.swift
// Calculator
//
// Created by Jon Hoffman on 12/24/15.
// Copyright © 2015 Jon Hoffman. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var display: UILabel!
var calculator = Calculator()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func commandEntered(_ sender: UIButton) {
if let text = display.text, let num = Double(text) {
var clearDisplay = true
switch sender.tag {
case 0:
calculator.commandEntered(num, nextCommand: nil)
display.text = "\(calculator.currentValue)"
clearDisplay = false
case 1:
calculator.commandEntered(num, nextCommand: AddCommand())
case 2:
calculator.commandEntered(num, nextCommand: SubCommand())
case 3:
calculator.commandEntered(num, nextCommand: MultiplyCommand())
case 4:
calculator.commandEntered(num, nextCommand: DivideCommand())
case 5:
calculator.clear()
case 6:
if let text = display.text {
let newText = text.substring(to: text.characters.index(before: text.endIndex))
display.text = newText
}
clearDisplay = false
default:
break
}
if clearDisplay {
display.text = "0"
}
}
}
@IBAction func numberEntered(_ sender: UIButton) {
if let text = display.text {
let tag = sender.tag
if tag < 10 {
display.text = "\(text)\(tag)"
} else {
display.text = "\(text)."
}
}
}
}
| 29.09589 | 98 | 0.524011 |
e4fe8e20d932de1d4cc3cd2cc06f1c89d392ad28 | 561 | import Routing
import Vapor
/// Register your application's routes here.
///
/// [Learn More →](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift)
public func routes(_ router: Router) throws {
router.get("name") { req in
return "Ethan Hunt"
}
router.get("age") { req in
return 23
}
router.get("json") { req in
return Person(name: "Martin J. Lasek", age: 26)
}
}
// Important: your class or struct conforms to Content
struct Person: Content {
var name: String
var age: Int
}
| 20.777778 | 87 | 0.623886 |
6aa748cf0892f561f859e88ad93c75eb5900d7ab | 1,419 | //
// AppDelegate.swift
// Kiwi
//
// Created by Muhammad Zahid Imran on 1/18/20.
// Copyright © 2020 Zahid Imran. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.342105 | 179 | 0.747005 |
fb87407b3ac1fadd765b1a0e2e494d493be4bab5 | 4,112 | #if !(os(iOS) && (arch(i386) || arch(arm)))
import Combine
import Foundation
/// A publisher that eventually produces one value and then finishes or fails.
///
/// Like a Combine.Future wrapped in Combine.Deferred, OnDemandFuture starts
/// producing its value on demand.
///
/// Unlike Combine.Future wrapped in Combine.Deferred, OnDemandFuture guarantees
/// that it starts producing its value on demand, **synchronously**, and that
/// it produces its value on promise completion, **synchronously**.
///
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
init(_ attemptToFulfill: @escaping (@escaping Promise) -> Void) {
self.attemptToFulfill = attemptToFulfill
}
/// :nodoc:
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
subscriber.receive(subscription: subscription)
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
case waitingForFulfillment(downstream: Downstream)
case finished
}
private var state: State
private let lock = NSRecursiveLock() // Allow re-entrancy
init(
attemptToFulfill: @escaping (@escaping Promise) -> Void,
downstream: Downstream)
{
self.state = .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill)
}
func request(_ demand: Subscribers.Demand) {
lock.synchronized {
switch state {
case let .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill):
guard demand > 0 else {
return
}
state = .waitingForFulfillment(downstream: downstream)
attemptToFulfill { result in
switch result {
case let .success(value):
self.receive(value)
case let .failure(error):
self.receive(completion: .failure(error))
}
}
case .waitingForFulfillment, .finished:
break
}
}
}
func cancel() {
lock.synchronized {
state = .finished
}
}
private func receive(_ value: Downstream.Input) {
lock.synchronized { sideEffect in
switch state {
case let .waitingForFulfillment(downstream: downstream):
state = .finished
sideEffect = {
_ = downstream.receive(value)
downstream.receive(completion: .finished)
}
case .waitingForDemand, .finished:
break
}
}
}
private func receive(completion: Subscribers.Completion<Downstream.Failure>) {
lock.synchronized { sideEffect in
switch state {
case let .waitingForFulfillment(downstream: downstream):
state = .finished
sideEffect = {
downstream.receive(completion: completion)
}
case .waitingForDemand, .finished:
break
}
}
}
}
#endif
| 34.847458 | 100 | 0.593385 |
2f54b20abd0f15fa231356776ec23fcea8e17636 | 2,427 | //
// NetworkHelper.swift
// FourCubed
//
// Created by Pritesh Nadiadhara on 2/8/19.
// Copyright © 2019 Pritesh Nadiadhara. All rights reserved.
//
import Foundation
public final class NetworkHelper {
private init() {
let cache = URLCache(memoryCapacity: 10 * 1024 * 1024, diskCapacity: 10 * 1024 * 1024, diskPath: nil)
URLCache.shared = cache
}
public static let shared = NetworkHelper()
public func performDataTask(endpointURLString: String,
httpMethod: String,
httpBody: Data?,
completionHandler: @escaping (AppError?, Data?, HTTPURLResponse?) ->Void) {
guard let url = URL(string: endpointURLString) else {
completionHandler(AppError.badURL("\(endpointURLString)"), nil, nil)
return
}
var request = URLRequest(url: url)
request.httpMethod = httpMethod
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
completionHandler(AppError.networkError(error), nil, response as? HTTPURLResponse)
return
} else if let data = data {
completionHandler(nil, data, response as? HTTPURLResponse)
}
}
task.resume()
}
public func performUploadTask(endpointURLString: String,
httpMethod: String,
httpBody: Data?,
completionHandler: @escaping (AppError?, Data?, HTTPURLResponse?) ->Void) {
guard let url = URL(string: endpointURLString) else {
completionHandler(AppError.badURL("\(endpointURLString)"), nil, nil)
return
}
var request = URLRequest(url: url)
request.httpMethod = httpMethod
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.uploadTask(with: request, from: httpBody) { (data, response, error) in
if let error = error {
completionHandler(AppError.networkError(error), nil, response as? HTTPURLResponse)
return
} else if let data = data {
completionHandler(nil, data, response as? HTTPURLResponse)
}
}
task.resume()
}
}
| 39.145161 | 109 | 0.573136 |
71564d0a9996b2df41fb397ecea479d01d18c433 | 533 | //
// SearchUserListUseCase.swift
// CleanArchitectureSampleCode
//
// Created by Victor on 2021/2/23.
//
import Foundation
import RxSwift
import RxCocoa
class SearchUserListUseCase {
private let userListRepository: UserListRepositoryInterface
init(userListRepository: UserListRepositoryInterface) {
self.userListRepository = userListRepository
}
func execute(userQuery: UserQuery) -> Single<UserList> {
return userListRepository.fetchUserList(userQuery: userQuery)
}
}
| 19.740741 | 69 | 0.726079 |
1e20f4b78f06ec415052c18e6a2bda2f7aaade6b | 4,009 | //
// HelperConnect.swift
// Nudge
//
// Created by Abraham Tarverdi on 2/11/21.
//
import ServiceManagement
import Cocoa
import Foundation
class HelperConnection: NSObject, HelperConnectProtocol {
// MARK: -
// MARK: AppProtocol Methods
func log(stdOut: String) {
guard !stdOut.isEmpty else { return }
OperationQueue.main.addOperation {
debugPrint(stdOut)
}
}
func log(stdErr: String) {
guard !stdErr.isEmpty else { return }
OperationQueue.main.addOperation {
debugPrint(stdErr)
}
}
func log(exitCode: Int32) {
//guard exitCode != nil else { return }
OperationQueue.main.addOperation {
debugPrint(exitCode)
}
}
// MARK: -
// MARK: Variables
private var currentHelperConnection: NSXPCConnection?
@objc dynamic private var currentHelperAuthData: NSData?
private var currentHelperAuthDataKeyPath: String = ""
@objc dynamic private var helperIsInstalled = false
private var helperIsInstalledKeyPath: String = ""
override init() {
self.currentHelperAuthDataKeyPath = NSStringFromSelector(#selector(getter: self.currentHelperAuthData))
// self.helperIsInstalledKeyPath = NSStringFromSelector(#selector(getter: self.helperIsInstalled))
super.init()
}
// MARK: -
// MARK: Helper Connection Methods
func helperConnection() -> NSXPCConnection? {
guard self.currentHelperConnection == nil else {
return self.currentHelperConnection
}
let connection = NSXPCConnection(machServiceName: HelperConstants.machServiceName, options: .privileged)
connection.exportedInterface = NSXPCInterface(with: HelperConnectProtocol.self)
connection.exportedObject = self
connection.remoteObjectInterface = NSXPCInterface(with: HelperProtocol.self)
connection.invalidationHandler = {
self.currentHelperConnection?.invalidationHandler = nil
OperationQueue.main.addOperation {
self.currentHelperConnection = nil
}
}
self.currentHelperConnection = connection
self.currentHelperConnection?.resume()
return self.currentHelperConnection
}
func helper(_ completion: ((Bool) -> Void)?) -> HelperProtocol? {
// Get the current helper connection and return the remote object (Helper.swift) as a proxy object to call functions on.
guard let helper = self.helperConnection()?.remoteObjectProxyWithErrorHandler({ error in
debugPrint("Error from helper: \(error)")
if let onCompletion = completion { onCompletion(false) }
}) as? HelperProtocol else { return nil }
return helper
}
func helperInstall() throws -> Bool {
debugPrint("Attempting to Install")
// Install and activate the helper inside our application bundle to disk.
var cfError: Unmanaged<CFError>?
var authItem = AuthorizationItem(name: kSMRightBlessPrivilegedHelper, valueLength: 0, value:UnsafeMutableRawPointer(bitPattern: 0), flags: 0)
var authRights = AuthorizationRights(count: 1, items: &authItem)
guard
let authRef = try HelperAuthorization.authorizationRef(&authRights, nil, [.interactionAllowed, .extendRights, .preAuthorize]),
SMJobBless(kSMDomainSystemLaunchd, HelperConstants.machServiceName as CFString, authRef, &cfError) else {
if let error = cfError?.takeRetainedValue() {
debugPrint("Error in installing: \(error)")
throw error }
return false
}
self.currentHelperConnection?.invalidate()
self.currentHelperConnection = nil
return true
}
}
var helperConnection = HelperConnection() //HelperConnection().helper(nil)
| 33.689076 | 149 | 0.645548 |
761e9a2c6fbb4b112503d9837315eeeb96aaf93b | 259 | // 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 {
{
}
class b: BooleanType
class a<T where T : a {
let t: Int -> {
let f = [Void{
| 21.583333 | 87 | 0.706564 |
d50ada47121da723bc4e0d646ff751b8c47e18a1 | 2,149 | //
// AppDelegate.swift
// FunnySnap
//
// Created by Anak Mirasing on 1/31/2559 BE.
// Copyright © 2559 iGROOMGRiM. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.723404 | 285 | 0.754304 |
21861bf7a71ea80e2bb1d688cb41011fe0fe74c2 | 1,064 | //
// GGKeychainService.swift
// GGQ
//
// Created by 宋宋 on 5/2/16.
// Copyright © 2016 org.dianqk. All rights reserved.
//
import Foundation
import Locksmith
typealias Token = String
enum TokenType {
case GitHub
case Weibo
}
extension TokenType {
var userAccount: String {
switch self {
case .GitHub:
return "gg.swift.github"
case .Weibo:
return "gg.swift.weibo"
}
}
}
class KeychainService {
static func save(type: TokenType, token: Token) {
try! Locksmith.updateData(["token": token], forUserAccount: type.userAccount)
}
static func read(type: TokenType) -> Token? {
let data = Locksmith.loadDataForUserAccount(type.userAccount)
return data?["token"] as? Token
}
static func exist(type: TokenType) -> Bool {
return Locksmith.loadDataForUserAccount(type.userAccount) != nil
}
static func delete(type: TokenType) throws {
try Locksmith.deleteDataForUserAccount(type.userAccount)
}
}
| 20.862745 | 85 | 0.62594 |
89e86e299c0ec3e47fb085df8ff6ed4fb3499483 | 1,035 | //
// VolumeSliderCell.swift
// Aural
//
// Copyright © 2021 Kartik Venugopal. All rights reserved.
//
// This software is licensed under the MIT software license.
// See the file "LICENSE" in the project root directory for license terms.
//
import Cocoa
// Cell for volume slider
class VolumeSliderCell: HorizontalSliderCell {
override var barInsetY: CGFloat {SystemUtils.isBigSur ? 0 : 0.5}
override var knobWidth: CGFloat {6}
override var knobRadius: CGFloat {0.5}
override var knobHeightOutsideBar: CGFloat {1.5}
override func knobRect(flipped: Bool) -> NSRect {
let bar = barRect(flipped: flipped)
let val = CGFloat(self.doubleValue)
let startX = bar.minX + (val * bar.width / 100)
let xOffset = -(val * knobWidth / 100)
let newX = startX + xOffset
let newY = bar.minY - knobHeightOutsideBar
return NSRect(x: newX, y: newY, width: knobWidth, height: knobHeightOutsideBar * 2 + bar.height)
}
}
| 29.571429 | 104 | 0.644444 |
1c644eac9b114aaab77b12b0a1276101e12604f6 | 907 | //
// MapView.swift
// SwiftUI Demo
//
// Created by Sebastian Abarca on 4/24/20.
// Copyright © 2020 Sebastian Abarca. All rights reserved.
//
import SwiftUI
import MapKit
struct MapView : UIViewRepresentable {
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
MKMapView()
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {
//Adding some code to get theexact coordinates
let coordinate = CLLocationCoordinate2D(latitude: 34.011286, longitude: -116.166868)
let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
let region = MKCoordinateRegion(center: coordinate, span: span)
uiView.setRegion(region, animated: true)
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
| 22.675 | 92 | 0.676957 |
4646b9c951d794b463a4e7f9374c50b37c937b87 | 3,004 | //
// ItemContenView.swift
// AdForMerchant
//
// Created by lieon on 2016/10/26.
// Copyright © 2016年 Windward. All rights reserved.
//
import UIKit
private let cellID = "ItemContentCollectionViewCellID"
class ItemContenView: UIView {
fileprivate var childVCs: [UIViewController]
fileprivate weak var parentVC: UIViewController?
fileprivate lazy var collectionView: UICollectionView = { [weak self] in
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
collectionView.isScrollEnabled = false
return collectionView
}()
init(frame: CGRect, childVCs: [UIViewController], parentVC: UIViewController?) {
self.childVCs = childVCs
self.parentVC = parentVC
super.init(frame: frame)
setupUI()
}
override func layoutSubviews() {
super.layoutSubviews()
guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
layout.itemSize = bounds.size
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ItemContenView {
func selectedPage(_ index: Int) {
let offsetX = CGFloat(index) * collectionView.bounds.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
extension ItemContenView {
func setupUI() {
addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
make.center.equalTo(self.snp.center)
make.size.equalTo(self.snp.size)
}
for childVC in childVCs {
if let parentVC = parentVC {
parentVC.addChildViewController(childVC)
}
}
}
}
extension ItemContenView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVC = childVCs[indexPath.item]
childVC.view.frame = bounds
cell.contentView.addSubview(childVC.view)
cell.backgroundColor = UIColor.randomColor()
return cell
}
}
| 33.752809 | 121 | 0.678762 |
87cea7a35d08e1135281e630a592dc2511b881d9 | 259 | import Foundation
extension String {
/**
If the receiver represents a path, returns its file name with a file extension.
*/
var fileName: String? {
return NSURL(string: self)?.URLByDeletingPathExtension?.lastPathComponent
}
}
| 19.923077 | 84 | 0.679537 |
913c6072a58422aaaa3e3b4a88db1672e1a0e714 | 3,006 | //
// ReactorMessageViewController.swift
// RxStateDemo
//
// Created by LZephyr on 2018/4/4.
// Copyright © 2018年 LZephyr. All rights reserved.
//
import UIKit
import ReactorKit
import RxSwift
import RxCocoa
import RxViewController
import RxDataSources
class ReactorMessageViewController: UIViewController, ReactorKit.View {
var disposeBag: DisposeBag = DisposeBag()
let dataSource = RxTableViewSectionedReloadDataSource<MessageTableSectionModel>(configureCell: { dataSource, tableView, indexPath, item in
return item.cell(in: tableView)
}, canEditRowAtIndexPath: { _, _ in true })
@IBOutlet weak var tableView: UITableView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
reactor = MessageReactor(service: MessageService())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "刷新", style: .plain, target: nil, action: nil)
/*
<1>.
reactor变量不能在视图的内部初始化,否则它就无法接收到与视图生命周期相关的事件(比如说下面用到的self.rx.viewDidLoad)
<2>.
Reactor并没有提供类似Redux中`reactor.dispatch(action)`这样的操作,View层向Reactor传递消息完全通过`reactor.action`类型来进行。
reactor.action是一个Subject类型,可以直接通过`reactor.action.on(.next(action))`来传递消息,但是显然ReactorKit并不建议这种方式。
而是通过RxCocoa提供的能力,将视图层的事件流绑定到Action上,通过action的这一层限制使得代码必须通过更加**函数式**的方式来编写
*/
}
/// 在这里进行绑定
func bind(reactor: MessageReactor) {
loadViewIfNeeded()
self.rx.viewDidAppear
.map { _ in Reactor.Action.request } // 1. 将事件流转换成Action
.bind(to: reactor.action) // 2. 然后绑定到reactor.action上, 在ReactorKit中所有的 UI操作 -> 事件 都是这样完成的
.disposed(by: self.disposeBag)
/// 观察保存在Reactor中的状态
reactor.state
.map({ $0.loadingState })
.subscribe(onNext: { value in
if value == .loading {
self.startLoading()
} else if value == .normal {
self.stopLoading()
}
})
.disposed(by: disposeBag)
/// TableView
reactor.state
.map({ $0.msgSections })
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: self.disposeBag)
// 删除某项
tableView.rx.itemDeleted
.map { Reactor.Action.removeItem($0) }
.bind(to: reactor.action)
.disposed(by: self.disposeBag)
// 点击刷新
self.navigationItem.rightBarButtonItem?.rx
.tap
.map { Reactor.Action.request }
.bind(to: reactor.action)
.disposed(by: self.disposeBag)
}
}
| 31.978723 | 142 | 0.604458 |
db59820e3dd9e13d4fd7a37bbcd6fce9254fdd98 | 2,978 | //
// EmojiMemoryGameView.swift
// Memorize
//
// Created by Jacob Mannix on 5/31/20.
// Copyright © 2020 Jacob Mannix. All rights reserved.
//
import SwiftUI
struct EmojiMemoryGameView: View {
@ObservedObject var viewModel: EmojiMemoryGame
var body: some View {
VStack {
Grid(items: viewModel.cards) { card in
CardView(card: card).onTapGesture {
withAnimation(.linear(duration: 0.65)) {
self.viewModel.choose(card: card)
}
}
.padding(5)
}
.padding()
.foregroundColor(Color.orange)
Button(action: {
withAnimation(.easeInOut) {
self.viewModel.resetGame()
}
}, label: { Text("New Game")}) // for text we want to research "localized string key" so it works in any language
}
}
}
struct CardView: View {
var card: MemoryGame<String>.Card
var body: some View {
GeometryReader { geometry in
self.body(for: geometry.size)
}
}
@State private var animatedBonusRemaining: Double = 0
private func startBonusTimeAnimation() {
animatedBonusRemaining = card.bonusRemaining
withAnimation(.linear(duration: card.bonusTimeRemaining)) {
animatedBonusRemaining = 0
}
}
@ViewBuilder
private func body(for size: CGSize) -> some View {
if card.isFaceUp || !card.isMatched {
ZStack {
Group {
if card.isConsumingBonusTime {
Pie(startAngle: Angle.degrees(0-90), endAngle: Angle.degrees(-animatedBonusRemaining*360-90), clockwise: true)
.onAppear {
self.startBonusTimeAnimation()
}
} else {
Pie(startAngle: Angle.degrees(0-90), endAngle: Angle.degrees(-card.bonusRemaining*360-90), clockwise: true)
}
}
.padding(5).opacity(0.5)
Text(card.content) // emoji
.font(Font.system(size: fontSize (for: size)))
.rotationEffect(Angle.degrees(card.isMatched ? 360 :0))
.animation(card.isMatched ? Animation.linear(duration: 1).repeatForever(autoreverses: false) : .default)
}
.cardify(isFaceUp: card.isFaceUp)
.transition(AnyTransition.scale)
}
}
// MARK: - Drawing Constants
private func fontSize(for size: CGSize) -> CGFloat {
min(size.width, size.width) * 0.68
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let game = EmojiMemoryGame()
game.choose(card: game.cards[0])
return EmojiMemoryGameView(viewModel: game)
}
}
| 32.021505 | 134 | 0.536266 |
d9e5ef4149c8bd4ca04271e203ff13ab38fc2ebe | 433 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func a{struct c{enum B{class
case,
| 39.363636 | 79 | 0.755196 |
76dd243fea1b198c69b8dda28b9011f4267e0b0b | 310 | //
// UINavigationController.swift
// musiclist
//
// Created by Artem Shuba on 06/06/2019.
// Copyright © 2019 ashuba. All rights reserved.
//
import UIKit
extension UINavigationController {
override open var childForStatusBarStyle: UIViewController? {
return self.topViewController
}
}
| 19.375 | 65 | 0.719355 |
879fdbff9c4e1aab9b42497ef14e7321a47a31cb | 1,287 | //
// CreateEventMaster.swift
// events
//
// Created by Skyler Ruesga on 7/19/17.
// Copyright © 2017 fbu-rsx. All rights reserved.
//
import Foundation
class CreateEventMaster {
static var shared = CreateEventMaster()
var event: [String: Any]
var guestlist: [String: Int]
init() {
self.event = [EventKey.id: FirebaseDatabaseManager.shared.getNewEventID(),
EventKey.organizerID: AppUser.current.uid,
EventKey.radius: 50.0,
EventKey.orgURLString: AppUser.current.photoURLString,
EventKey.orgName: AppUser.current.name]
self.guestlist = [:]
}
func clear() {
self.event = [EventKey.id: FirebaseDatabaseManager.shared.getNewEventID(),
EventKey.organizerID: AppUser.current.uid,
EventKey.radius: 50.0,
EventKey.orgURLString: AppUser.current.photoURLString,
EventKey.orgName: AppUser.current.name]
self.guestlist = [:]
}
func createNewEvent() -> Event {
print("CREATING NEW EVENT")
let event = AppUser.current.createEvent(self.event)
CreateEventMaster.shared.clear()
return event
}
}
| 29.25 | 82 | 0.585859 |
21cba30f2fad546748cc1c1089e46e7cae2a7777 | 3,395 | //
// DO NOT EDIT.
//
// Generated by the protocol buffer compiler.
// Source: helloworld.proto
//
//
// Copyright 2018, gRPC Authors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import GRPC
import NIO
import NIOHTTP1
import SwiftProtobuf
/// Usage: instantiate Helloworld_GreeterClient, then call methods of this protocol to make API calls.
public protocol Helloworld_GreeterClientProtocol {
func sayHello(_ request: Helloworld_HelloRequest, callOptions: CallOptions?) -> UnaryCall<Helloworld_HelloRequest, Helloworld_HelloReply>
}
public final class Helloworld_GreeterClient: GRPCClient, Helloworld_GreeterClientProtocol {
public let channel: GRPCChannel
public var defaultCallOptions: CallOptions
/// Creates a client for the helloworld.Greeter service.
///
/// - Parameters:
/// - channel: `GRPCChannel` to the service host.
/// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.
public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) {
self.channel = channel
self.defaultCallOptions = defaultCallOptions
}
/// Sends a greeting.
///
/// - Parameters:
/// - request: Request to send to SayHello.
/// - callOptions: Call options; `self.defaultCallOptions` is used if `nil`.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
public func sayHello(_ request: Helloworld_HelloRequest, callOptions: CallOptions? = nil) -> UnaryCall<Helloworld_HelloRequest, Helloworld_HelloReply> {
return self.makeUnaryCall(path: "/helloworld.Greeter/SayHello",
request: request,
callOptions: callOptions ?? self.defaultCallOptions)
}
}
/// To build a server, implement a class that conforms to this protocol.
public protocol Helloworld_GreeterProvider: CallHandlerProvider {
/// Sends a greeting.
func sayHello(request: Helloworld_HelloRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Helloworld_HelloReply>
}
extension Helloworld_GreeterProvider {
public var serviceName: String { return "helloworld.Greeter" }
/// Determines, calls and returns the appropriate request handler, depending on the request's method.
/// Returns nil for methods not handled by this service.
public func handleMethod(_ methodName: String, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
switch methodName {
case "SayHello":
return UnaryCallHandler(callHandlerContext: callHandlerContext) { context in
return { request in
self.sayHello(request: request, context: context)
}
}
default: return nil
}
}
}
// Provides conformance to `GRPCPayload`
extension Helloworld_HelloRequest: GRPCProtobufPayload {}
extension Helloworld_HelloReply: GRPCProtobufPayload {}
| 36.902174 | 154 | 0.738733 |
e2c34f291743fec1d3989e9e470b1f5abe17e470 | 2,601 | //
// winViewController.swift
// Dooro Learinng
//
// Created by Beryl Zhang on 6/24/21.
//
import UIKit
class winViewController: UIViewController {
var currentCard: Wordcards?
var userID: String?
@IBAction func redirect(_ sender: Any) {
let displayVC : explanViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "explanViewController") as! explanViewController
displayVC.currentCard = self.currentCard
displayVC.userID = self.userID!
displayVC.modalPresentationStyle = .fullScreen
self.present(displayVC, animated:true, completion:nil)
}
@IBAction func tapNewWord(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "hangmanGameController") as! hangmanGameController
nextViewController.userID = self.userID!
nextViewController.modalPresentationStyle = .fullScreen
self.present(nextViewController, animated:true, completion:nil)
}
@IBAction func tapExit(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ChooseModeViewController") as! ChooseModeViewController
nextViewController.userID = self.userID!
nextViewController.modalPresentationStyle = .fullScreen
self.present(nextViewController, animated:true, completion:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
print("you win")
guard let unwrappedID = userID else {
print("no value")
return
}
print(unwrappedID )
// Do any additional setup after loading the view.
}
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 35.148649 | 177 | 0.677432 |
f7dbb303dbd5a1e8caa50e3c536ec3af5560b367 | 3,857 | //
// SearchCourtViewController.swift
// Elite
//
// Created by Leandro Wauters on 11/1/19.
// Copyright © 2019 Pritesh Nadiadhara. All rights reserved.
//
import UIKit
class SearchCourtViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var gameName = String()
var basketBallCourts = [BasketBall]()
var handBallCourts = [HandBall]()
var selectedBasketBallCourt: BasketBall?
var selectedHandBallCourt: HandBall?
var basketBallResults = [BasketBall]() {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
var handBallResult = [HandBall] () {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "ParkInfoCell", bundle: nil), forCellReuseIdentifier: "ParkInfoCell")
}
}
extension SearchCourtViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if gameName == GameName.basketball.rawValue {
basketBallResults = basketBallCourts.filter{($0.nameOfPlayground?.lowercased().contains(searchText.lowercased()))!}
}
if gameName == GameName.handball.rawValue {
handBallResult = handBallCourts.filter{($0.nameOfPlayground?.lowercased().contains(searchText.lowercased()))!}
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
dismissKeyboard()
}
}
extension SearchCourtViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if gameName == GameName.basketball.rawValue {
return basketBallResults.count
}
if gameName == GameName.handball.rawValue {
return handBallResult.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ParkInfoCell", for: indexPath) as? ParkInfoCell else {
fatalError()
}
if gameName == GameName.basketball.rawValue {
let bbCourt = basketBallResults[indexPath.row]
cell.parkNameLabel.text = bbCourt.nameOfPlayground
cell.parkAddressLabel.text = bbCourt.location
}
if gameName == GameName.handball.rawValue {
let hbCourt = handBallResult[indexPath.row]
cell.parkNameLabel.text = hbCourt.nameOfPlayground
cell.parkAddressLabel.text = hbCourt.location
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if gameName == GameName.basketball.rawValue {
selectedBasketBallCourt = basketBallResults[indexPath.row]
}
if gameName == GameName.handball.rawValue {
selectedHandBallCourt = handBallResult[indexPath.row]
}
let optionVC = OptionsViewController()
optionVC.delegate = self
optionVC.modalPresentationStyle = .overCurrentContext
present(optionVC, animated: true)
}
}
extension SearchCourtViewController: OptionsViewDelegate {
func leaderboardPressed() {
}
func playPressed() {
}
}
| 30.132813 | 127 | 0.640913 |
e2b3808ccd1f7c8471a660214c12e4a425e84ab3 | 421 | import AppKit
struct Color {
// MARK: - Properties
static let darkBackground = NSColor(srgbRed: 0.129, green: 0.125, blue: 0.141, alpha: 1)
static let yellow = NSColor(srgbRed: 0.965, green: 0.773, blue: 0.180, alpha: 1)
static let red = NSColor(srgbRed: 0.847, green: 0.227, blue: 0.286, alpha: 1)
static let white = NSColor.white
static let black = NSColor.black
// MARK - Initializers
private init() {}
}
| 24.764706 | 89 | 0.686461 |
dbab48014771fb46db7e6d3da0097b3e8c759b76 | 426 | //
// CLBeaconRegionExtension.swift
// iBOfficeBeacon
//
// Created by Mohammed Binsabbar on 20/02/2016.
// Copyright © 2016 Binsabbar. All rights reserved.
//
import Foundation
extension CLBeaconRegion {
public func isEqualTo(_ region:CLBeaconRegion) -> Bool{
return region.proximityUUID == self.proximityUUID
&& region.major == self.major
&& region.minor == self.minor
}
}
| 22.421053 | 59 | 0.661972 |
ef4c61abf1d0e2cab3c68bc987553494daccf8f1 | 3,137 | //
// FileDescriptor.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 8/10/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux)
import Glibc
import CStatfs
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// POSIX File Descriptor
public typealias FileDescriptor = CInt
public extension FileDescriptor {
// MARK: - Singletons
/// Returns the file handle associated with the standard input file.
/// Conventionally this is a terminal device on which the user enters a stream of data.
/// There is one standard input file handle per process; it is a shared instance.
/// When using this method to create a file handle object, the file handle owns its associated
/// file descriptor and is responsible for closing it.
///
/// - returns: The shared file handle associated with the standard input file.
///
public static let standardInput: FileDescriptor = 0
/// Returns the file handle associated with the standard output file.
/// Conventionally this is a terminal device that receives a stream of data from a program.
/// There is one standard output file handle per process; it is a shared instance.
/// When using this method to create a file handle object, the file handle owns its associated
/// file descriptor and is responsible for closing it.
///
/// - returns: The shared file handle associated with the standard output file.
///
public static let standardOutput: FileDescriptor = 1
/// Returns the file handle associated with the standard error file.
/// Conventionally this is a terminal device to which error messages are sent.
/// There is one standard error file handle per process; it is a shared instance.
/// When using this method to create a file handle object, the file handle owns its associated file
/// descriptor and is responsible for closing it.
///
/// - returns: The shared file handle associated with the standard error file.
///
public static let standardError: FileDescriptor = 2
/// Returns a file handle associated with a null device.
/// You can use null-device file handles as “placeholders” for standard-device file handles
/// or in collection objects to avoid exceptions and other errors resulting from messages being
/// sent to invalid file handles. Read messages sent to a null-device file handle return an
/// end-of-file indicator (empty Data) rather than raise an exception.
/// Write messages are no-ops, whereas fileDescriptor returns an illegal value.
/// Other methods are no-ops or return “sensible” values.
/// When using this method to create a file handle object,
/// the file handle owns its associated file descriptor and is responsible for closing it.
///
/// - returns: A file handle associated with a null device.
///
public static let nullDevice: FileDescriptor = open("/dev/null", O_RDWR | O_BINARY)
}
public let O_BINARY: Int32 = 0
#endif
| 42.391892 | 103 | 0.700669 |
03498ea9b88370bacf454600ef2b7ee7085ace30 | 12,987 | //
// BaseDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class ChartBaseDataSet: NSObject, IChartDataSet, NSCopying
{
public required override init()
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
valueColors.append(.labelOrBlack)
}
@objc public init(label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
valueColors.append(.labelOrBlack)
self.label = label
}
// MARK: - Data functions and accessors
/// Use this method to tell the data set that the underlying data has changed
open func notifyDataSetChanged()
{
calcMinMax()
}
open func calcMinMax()
{
fatalError("calcMinMax is not implemented in ChartBaseDataSet")
}
open func calcMinMaxY(fromX: Double, toX: Double)
{
fatalError("calcMinMaxY(fromX:, toX:) is not implemented in ChartBaseDataSet")
}
open var yMin: Double
{
fatalError("yMin is not implemented in ChartBaseDataSet")
}
open var yMax: Double
{
fatalError("yMax is not implemented in ChartBaseDataSet")
}
open var xMin: Double
{
fatalError("xMin is not implemented in ChartBaseDataSet")
}
open var xMax: Double
{
fatalError("xMax is not implemented in ChartBaseDataSet")
}
open var entryCount: Int
{
fatalError("entryCount is not implemented in ChartBaseDataSet")
}
open func entryForIndex(_ i: Int) -> ChartDataEntry?
{
fatalError("entryForIndex is not implemented in ChartBaseDataSet")
}
open func entryForXValue(
_ x: Double,
closestToY y: Double,
rounding: ChartDataSetRounding) -> ChartDataEntry?
{
fatalError("entryForXValue(x, closestToY, rounding) is not implemented in ChartBaseDataSet")
}
open func entryForXValue(
_ x: Double,
closestToY y: Double) -> ChartDataEntry?
{
fatalError("entryForXValue(x, closestToY) is not implemented in ChartBaseDataSet")
}
open func entriesForXValue(_ x: Double) -> [ChartDataEntry]
{
fatalError("entriesForXValue is not implemented in ChartBaseDataSet")
}
open func entryIndex(
x xValue: Double,
closestToY y: Double,
rounding: ChartDataSetRounding) -> Int
{
fatalError("entryIndex(x, closestToY, rounding) is not implemented in ChartBaseDataSet")
}
open func entryIndex(entry e: ChartDataEntry) -> Int
{
fatalError("entryIndex(entry) is not implemented in ChartBaseDataSet")
}
open func addEntry(_ e: ChartDataEntry) -> Bool
{
fatalError("addEntry is not implemented in ChartBaseDataSet")
}
open func addEntryOrdered(_ e: ChartDataEntry) -> Bool
{
fatalError("addEntryOrdered is not implemented in ChartBaseDataSet")
}
@discardableResult open func removeEntry(_ entry: ChartDataEntry) -> Bool
{
fatalError("removeEntry is not implemented in ChartBaseDataSet")
}
@discardableResult open func removeEntry(index: Int) -> Bool
{
if let entry = entryForIndex(index)
{
return removeEntry(entry)
}
return false
}
@discardableResult open func removeEntry(x: Double) -> Bool
{
if let entry = entryForXValue(x, closestToY: Double.nan)
{
return removeEntry(entry)
}
return false
}
@discardableResult open func removeFirst() -> Bool
{
if entryCount > 0
{
if let entry = entryForIndex(0)
{
return removeEntry(entry)
}
}
return false
}
@discardableResult open func removeLast() -> Bool
{
if entryCount > 0
{
if let entry = entryForIndex(entryCount - 1)
{
return removeEntry(entry)
}
}
return false
}
open func contains(_ e: ChartDataEntry) -> Bool
{
fatalError("removeEntry is not implemented in ChartBaseDataSet")
}
open func clear()
{
fatalError("clear is not implemented in ChartBaseDataSet")
}
// MARK: - Styling functions and accessors
/// All the colors that are used for this DataSet.
/// Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array.
open var colors = [NSUIColor]()
/// List representing all colors that are used for drawing the actual values for this DataSet
open var valueColors = [NSUIColor]()
/// The label string that describes the DataSet.
open var label: String? = "DataSet"
/// The axis this DataSet should be plotted against.
open var axisDependency = YAxis.AxisDependency.left
/// - Returns: The color at the given index of the DataSet's color array.
/// This prevents out-of-bounds by performing a modulus on the color index, so colours will repeat themselves.
open func color(atIndex index: Int) -> NSUIColor
{
var index = index
if index < 0
{
index = 0
}
return colors[index % colors.count]
}
/// Resets all colors of this DataSet and recreates the colors array.
open func resetColors()
{
colors.removeAll(keepingCapacity: false)
}
/// Adds a new color to the colors array of the DataSet.
///
/// - Parameters:
/// - color: the color to add
open func addColor(_ color: NSUIColor)
{
colors.append(color)
}
/// Sets the one and **only** color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
///
/// - Parameters:
/// - color: the color to set
open func setColor(_ color: NSUIColor)
{
colors.removeAll(keepingCapacity: false)
colors.append(color)
}
/// Sets colors to a single color a specific alpha value.
///
/// - Parameters:
/// - color: the color to set
/// - alpha: alpha to apply to the set `color`
@objc open func setColor(_ color: NSUIColor, alpha: CGFloat)
{
setColor(color.withAlphaComponent(alpha))
}
/// Sets colors with a specific alpha value.
///
/// - Parameters:
/// - colors: the colors to set
/// - alpha: alpha to apply to the set `colors`
@objc open func setColors(_ colors: [NSUIColor], alpha: CGFloat)
{
self.colors = colors.map { $0.withAlphaComponent(alpha) }
}
/// Sets colors with a specific alpha value.
///
/// - Parameters:
/// - colors: the colors to set
/// - alpha: alpha to apply to the set `colors`
open func setColors(_ colors: NSUIColor...)
{
self.colors = colors
}
/// if true, value highlighting is enabled
open var highlightEnabled = true
/// `true` if value highlighting is enabled for this dataset
open var isHighlightEnabled: Bool { return highlightEnabled }
/// Custom formatter that is used instead of the auto-formatter if set
internal var _valueFormatter: IValueFormatter?
/// Custom formatter that is used instead of the auto-formatter if set
open var valueFormatter: IValueFormatter?
{
get
{
if needsFormatter
{
return ChartUtils.defaultValueFormatter()
}
return _valueFormatter
}
set
{
if newValue == nil { return }
_valueFormatter = newValue
}
}
open var needsFormatter: Bool
{
return _valueFormatter == nil
}
/// Sets/get a single color for value text.
/// Setting the color clears the colors array and adds a single color.
/// Getting will return the first color in the array.
open var valueTextColor: NSUIColor
{
get
{
return valueColors[0]
}
set
{
valueColors.removeAll(keepingCapacity: false)
valueColors.append(newValue)
}
}
/// - Returns: The color at the specified index that is used for drawing the values inside the chart. Uses modulus internally.
open func valueTextColorAt(_ index: Int) -> NSUIColor
{
var index = index
if index < 0
{
index = 0
}
return valueColors[index % valueColors.count]
}
/// the font for the value-text labels
open var valueFont: NSUIFont = NSUIFont.systemFont(ofSize: 7.0)
/// The form to draw for this dataset in the legend.
open var form = Legend.Form.default
/// The form size to draw for this dataset in the legend.
///
/// Return `NaN` to use the default legend form size.
open var formSize: CGFloat = CGFloat.nan
/// The line width for drawing the form of this dataset in the legend
///
/// Return `NaN` to use the default legend form line width.
open var formLineWidth: CGFloat = CGFloat.nan
/// Line dash configuration for legend shapes that consist of lines.
///
/// This is how much (in pixels) into the dash pattern are we starting from.
open var formLineDashPhase: CGFloat = 0.0
/// Line dash configuration for legend shapes that consist of lines.
///
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
open var formLineDashLengths: [CGFloat]? = nil
/// Set this to true to draw y-values on the chart.
///
/// - Note: For bar and line charts: if `maxVisibleCount` is reached, no values will be drawn even if this is enabled.
open var drawValuesEnabled = true
/// `true` if y-value drawing is enabled, `false` ifnot
open var isDrawValuesEnabled: Bool
{
return drawValuesEnabled
}
/// Set this to true to draw y-icons on the chart.
///
/// - Note: For bar and line charts: if `maxVisibleCount` is reached, no icons will be drawn even if this is enabled.
open var drawIconsEnabled = true
/// Returns true if y-icon drawing is enabled, false if not
open var isDrawIconsEnabled: Bool
{
return drawIconsEnabled
}
/// Offset of icons drawn on the chart.
///
/// For all charts except Pie and Radar it will be ordinary (x offset, y offset).
///
/// For Pie and Radar chart it will be (y offset, distance from center offset); so if you want icon to be rendered under value, you should increase X component of CGPoint, and if you want icon to be rendered closet to center, you should decrease height component of CGPoint.
open var iconsOffset = CGPoint(x: 0, y: 0)
/// Set the visibility of this DataSet. If not visible, the DataSet will not be drawn to the chart upon refreshing it.
open var visible = true
/// `true` if this DataSet is visible inside the chart, or `false` ifit is currently hidden.
open var isVisible: Bool
{
return visible
}
// MARK: - NSObject
open override var description: String
{
return String(format: "%@, label: %@, %i entries", arguments: [NSStringFromClass(type(of: self)), self.label ?? "", self.entryCount])
}
open override var debugDescription: String
{
return (0..<entryCount).reduce(description + ":") {
"\($0)\n\(self.entryForIndex($1)?.description ?? "")"
}
}
// MARK: - NSCopying
open func copy(with zone: NSZone? = nil) -> Any
{
let copy = type(of: self).init()
copy.colors = colors
copy.valueColors = valueColors
copy.label = label
copy.axisDependency = axisDependency
copy.highlightEnabled = highlightEnabled
copy._valueFormatter = _valueFormatter
copy.valueFont = valueFont
copy.form = form
copy.formSize = formSize
copy.formLineWidth = formLineWidth
copy.formLineDashPhase = formLineDashPhase
copy.formLineDashLengths = formLineDashLengths
copy.drawValuesEnabled = drawValuesEnabled
copy.drawValuesEnabled = drawValuesEnabled
copy.iconsOffset = iconsOffset
copy.visible = visible
return copy
}
}
| 29.786697 | 278 | 0.606992 |
014191d2e461ff8c573aa10b922b25f87d2c254a | 941 | //
// JSONPlaceholderTestTests.swift
// JSONPlaceholderTestTests
//
// Created by Gujgiczer Máté on 19/09/16.
// Copyright © 2016 gujci. All rights reserved.
//
import XCTest
class JSONPlaceholderTestTests: XCTestCase {
var loader: DataLoader = App.sharedInstance.request()
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testLoadingPosts() {
let expectation = self.expectation(description: "loadin posts")
loader.on(LoaderEvent.postsLoaded) { [weak self] in
XCTAssertNotNil(self?.loader.posts, "error during loading posts")
expectation.fulfill()
}
loader.loadPosts()
waitForExpectations(timeout: 20) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
}
| 23.525 | 77 | 0.588735 |
264a593e0fd46e75caf4aa8fe7b3011e1a1dc545 | 1,057 | //
// DetailViewController.swift
// GameOfThrones
//
// Created by Maitree Bain on 11/24/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var seasonLabel: UILabel!
@IBOutlet weak var episodeLabel: UILabel!
@IBOutlet weak var runtimeLabel: UILabel!
@IBOutlet weak var airdateLabel: UILabel!
var episode: GOTEpisode?
override func viewDidLoad() {
super.viewDidLoad()
seasonLabel.text = "Season: \(String(describing: episode!.season))"
episodeLabel.text = "Episode: \(String(describing: episode!.number))"
runtimeLabel.text = "Runtime: \(String(describing: episode!.runtime)) minutes"
airdateLabel.text = "AirDate: \(String(describing: episode!.airdate))"
imageView.image = UIImage(named: episode!.originalImageID.description)
textView.text = episode!.summary
}
}
| 29.361111 | 86 | 0.678335 |
69924167a40b7411f93458548e9ba6a6dba34bb0 | 4,182 | //
// Fetcher.swift
// MySmove
//
// Created by Leonardo Parro on 9/7/18.
// Copyright © 2018 Leonardo Parro. All rights reserved.
//
import Foundation
class Fetcher {
static let sharedInstance = Fetcher()
fileprivate let HOST_API_URL = "challenge.smove.sg"
fileprivate let HTTP_SCHEME = "https"
enum Result<Value> {
case success(Value)
case failure(Error)
}
enum APIEndpoint: String {
case Locations = "/locations"
case BookingAvailability = "/availability"
}
let defaultSession = URLSession(configuration: .default)
// MARK: - GET Car Locations
func getAllCarLocations(completion: ((Result<[CarLocation]>) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = HTTP_SCHEME
urlComponents.host = HOST_API_URL
urlComponents.path = APIEndpoint.Locations.rawValue
guard let url = urlComponents.url else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = defaultSession.dataTask(with: request) { responseData, response, responseError in
DispatchQueue.main.async {
if let error = responseError {
completion?(.failure(error))
} else if let jsonData = responseData,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
let decoder = JSONDecoder()
do {
#if DEBUG
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
debugPrint(jsonObject)
#endif
let locationList = try decoder.decode(CarLocationList.self, from: jsonData)
completion?(.success(locationList.locations))
} catch {
completion?(.failure(error))
}
}
}
}
task.resume()
}
// MARK: - GET Booking Availability
func getBookingAvailability(startTime: TimeInterval, endTime: TimeInterval, completion: ((Result<[Booking]>) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = HTTP_SCHEME
urlComponents.host = HOST_API_URL
urlComponents.path = APIEndpoint.BookingAvailability.rawValue
let startTimeItem = URLQueryItem(name: "startTime", value: "\(String(format: "%.f", Double(startTime)))")
let endTimeItem = URLQueryItem(name: "endTime", value: "\(String(format: "%.f", Double(endTime)))")
urlComponents.queryItems = [startTimeItem, endTimeItem]
guard let url = urlComponents.url else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = defaultSession.dataTask(with: request) { responseData, response, responseError in
DispatchQueue.main.async {
if let error = responseError {
completion?(.failure(error))
} else if let jsonData = responseData,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
let decoder = JSONDecoder()
do {
#if DEBUG
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
debugPrint(jsonObject)
#endif
let bookingList = try decoder.decode(BookingList.self, from: jsonData)
completion?(.success(bookingList.bookings))
} catch {
completion?(.failure(error))
}
}
}
}
task.resume()
}
}
| 36.051724 | 125 | 0.51913 |
0ad891f80b7854896cb7367602681b8c73e2eb7b | 244 | //
// S2LatitudeLongitudeTests.swift
// S2Geometry
//
// Created by Marc Rollin on 4/28/17.
// Copyright © 2017 Marc Rollin. All rights reserved.
//
@testable import S2Geometry
import XCTest
class S2LatitudeLongitudeTests: XCTestCase {
}
| 17.428571 | 54 | 0.737705 |
5064e5244c6f19c81314f47349e59dbb48914665 | 937 | import ProjectDescription
let dependencies = Dependencies(
swiftPackageManager: .init(
[
.package(url: "https://github.com/adjust/ios_sdk/", .upToNextMajor(from: "4.0.0")),
.package(url: "https://github.com/facebook/facebook-ios-sdk", .upToNextMajor(from: "11.0.0")),
.package(url: "https://github.com/firebase/firebase-ios-sdk", .upToNextMajor(from: "8.0.0")),
.package(url: "https://github.com/Alamofire/Alamofire", .upToNextMajor(from: "5.0.0")),
.package(url: "https://github.com/pointfreeco/swift-composable-architecture", .upToNextMinor(from: "0.22.0")),
.package(url: "https://github.com/Quick/Quick", .upToNextMajor(from: "4.0.0")),
.package(url: "https://github.com/Quick/Nimble", .upToNextMajor(from: "9.0.0")),
],
deploymentTargets: [.iOS(targetVersion: "9.0", devices: [.iphone])]
),
platforms: [.iOS]
)
| 52.055556 | 122 | 0.616862 |
Subsets and Splits