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
|
---|---|---|---|---|---|
f562a15f494c7450fbfdf2f86c2fc8bb0c1ae21f | 17,628 | //
// CommunicationRequest.swift
// HealthSoftware
//
// Generated from FHIR 3.0.1.11917 (http://hl7.org/fhir/StructureDefinition/CommunicationRequest)
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
A request for information to be sent to a receiver.
A request to convey information; e.g. the CDS system proposes that an alert be sent to a responsible provider, the CDS
system proposes that the public health agency be notified about a reportable condition.
*/
open class CommunicationRequest: DomainResource {
override open class var resourceType: ResourceType { return .communicationRequest }
/// All possible types for "occurrence[x]"
public enum OccurrenceX: Hashable {
case dateTime(FHIRPrimitive<DateTime>)
case period(Period)
}
/// Unique identifier
public var identifier: [Identifier]?
/// Fulfills plan or proposal
public var basedOn: [Reference]?
/// Request(s) replaced by this request
public var replaces: [Reference]?
/// Composite request this is part of
public var groupIdentifier: Identifier?
/// The status of the proposal or order.
public var status: FHIRPrimitive<RequestStatus>
/// Message category
public var category: [CodeableConcept]?
/// Characterizes how quickly the proposed act must be initiated. Includes concepts such as stat, urgent, routine.
public var priority: FHIRPrimitive<RequestPriority>?
/// A channel of communication
public var medium: [CodeableConcept]?
/// Focus of message
public var subject: Reference?
/// Message recipient
public var recipient: [Reference]?
/// Focal resources
public var topic: [Reference]?
/// Encounter or episode leading to message
public var context: Reference?
/// Message payload
public var payload: [CommunicationRequestPayload]?
/// When scheduled
/// One of `occurrence[x]`
public var occurrence: OccurrenceX?
/// When request transitioned to being actionable
public var authoredOn: FHIRPrimitive<DateTime>?
/// Message sender
public var sender: Reference?
/// Who/what is requesting service
public var requester: CommunicationRequestRequester?
/// Why is communication needed?
public var reasonCode: [CodeableConcept]?
/// Why is communication needed?
public var reasonReference: [Reference]?
/// Comments made about communication request
public var note: [Annotation]?
/// Designated initializer taking all required properties
public init(status: FHIRPrimitive<RequestStatus>) {
self.status = status
super.init()
}
/// Convenience initializer
public convenience init(
authoredOn: FHIRPrimitive<DateTime>? = nil,
basedOn: [Reference]? = nil,
category: [CodeableConcept]? = nil,
contained: [ResourceProxy]? = nil,
context: Reference? = nil,
`extension`: [Extension]? = nil,
groupIdentifier: Identifier? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
identifier: [Identifier]? = nil,
implicitRules: FHIRPrimitive<FHIRURI>? = nil,
language: FHIRPrimitive<FHIRString>? = nil,
medium: [CodeableConcept]? = nil,
meta: Meta? = nil,
modifierExtension: [Extension]? = nil,
note: [Annotation]? = nil,
occurrence: OccurrenceX? = nil,
payload: [CommunicationRequestPayload]? = nil,
priority: FHIRPrimitive<RequestPriority>? = nil,
reasonCode: [CodeableConcept]? = nil,
reasonReference: [Reference]? = nil,
recipient: [Reference]? = nil,
replaces: [Reference]? = nil,
requester: CommunicationRequestRequester? = nil,
sender: Reference? = nil,
status: FHIRPrimitive<RequestStatus>,
subject: Reference? = nil,
text: Narrative? = nil,
topic: [Reference]? = nil)
{
self.init(status: status)
self.authoredOn = authoredOn
self.basedOn = basedOn
self.category = category
self.contained = contained
self.context = context
self.`extension` = `extension`
self.groupIdentifier = groupIdentifier
self.id = id
self.identifier = identifier
self.implicitRules = implicitRules
self.language = language
self.medium = medium
self.meta = meta
self.modifierExtension = modifierExtension
self.note = note
self.occurrence = occurrence
self.payload = payload
self.priority = priority
self.reasonCode = reasonCode
self.reasonReference = reasonReference
self.recipient = recipient
self.replaces = replaces
self.requester = requester
self.sender = sender
self.subject = subject
self.text = text
self.topic = topic
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case authoredOn; case _authoredOn
case basedOn
case category
case context
case groupIdentifier
case identifier
case medium
case note
case occurrenceDateTime; case _occurrenceDateTime
case occurrencePeriod
case payload
case priority; case _priority
case reasonCode
case reasonReference
case recipient
case replaces
case requester
case sender
case status; case _status
case subject
case topic
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.authoredOn = try FHIRPrimitive<DateTime>(from: _container, forKeyIfPresent: .authoredOn, auxiliaryKey: ._authoredOn)
self.basedOn = try [Reference](from: _container, forKeyIfPresent: .basedOn)
self.category = try [CodeableConcept](from: _container, forKeyIfPresent: .category)
self.context = try Reference(from: _container, forKeyIfPresent: .context)
self.groupIdentifier = try Identifier(from: _container, forKeyIfPresent: .groupIdentifier)
self.identifier = try [Identifier](from: _container, forKeyIfPresent: .identifier)
self.medium = try [CodeableConcept](from: _container, forKeyIfPresent: .medium)
self.note = try [Annotation](from: _container, forKeyIfPresent: .note)
var _t_occurrence: OccurrenceX? = nil
if let occurrenceDateTime = try FHIRPrimitive<DateTime>(from: _container, forKeyIfPresent: .occurrenceDateTime, auxiliaryKey: ._occurrenceDateTime) {
if _t_occurrence != nil {
throw DecodingError.dataCorruptedError(forKey: .occurrenceDateTime, in: _container, debugDescription: "More than one value provided for \"occurrence\"")
}
_t_occurrence = .dateTime(occurrenceDateTime)
}
if let occurrencePeriod = try Period(from: _container, forKeyIfPresent: .occurrencePeriod) {
if _t_occurrence != nil {
throw DecodingError.dataCorruptedError(forKey: .occurrencePeriod, in: _container, debugDescription: "More than one value provided for \"occurrence\"")
}
_t_occurrence = .period(occurrencePeriod)
}
self.occurrence = _t_occurrence
self.payload = try [CommunicationRequestPayload](from: _container, forKeyIfPresent: .payload)
self.priority = try FHIRPrimitive<RequestPriority>(from: _container, forKeyIfPresent: .priority, auxiliaryKey: ._priority)
self.reasonCode = try [CodeableConcept](from: _container, forKeyIfPresent: .reasonCode)
self.reasonReference = try [Reference](from: _container, forKeyIfPresent: .reasonReference)
self.recipient = try [Reference](from: _container, forKeyIfPresent: .recipient)
self.replaces = try [Reference](from: _container, forKeyIfPresent: .replaces)
self.requester = try CommunicationRequestRequester(from: _container, forKeyIfPresent: .requester)
self.sender = try Reference(from: _container, forKeyIfPresent: .sender)
self.status = try FHIRPrimitive<RequestStatus>(from: _container, forKey: .status, auxiliaryKey: ._status)
self.subject = try Reference(from: _container, forKeyIfPresent: .subject)
self.topic = try [Reference](from: _container, forKeyIfPresent: .topic)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try authoredOn?.encode(on: &_container, forKey: .authoredOn, auxiliaryKey: ._authoredOn)
try basedOn?.encode(on: &_container, forKey: .basedOn)
try category?.encode(on: &_container, forKey: .category)
try context?.encode(on: &_container, forKey: .context)
try groupIdentifier?.encode(on: &_container, forKey: .groupIdentifier)
try identifier?.encode(on: &_container, forKey: .identifier)
try medium?.encode(on: &_container, forKey: .medium)
try note?.encode(on: &_container, forKey: .note)
if let _enum = occurrence {
switch _enum {
case .dateTime(let _value):
try _value.encode(on: &_container, forKey: .occurrenceDateTime, auxiliaryKey: ._occurrenceDateTime)
case .period(let _value):
try _value.encode(on: &_container, forKey: .occurrencePeriod)
}
}
try payload?.encode(on: &_container, forKey: .payload)
try priority?.encode(on: &_container, forKey: .priority, auxiliaryKey: ._priority)
try reasonCode?.encode(on: &_container, forKey: .reasonCode)
try reasonReference?.encode(on: &_container, forKey: .reasonReference)
try recipient?.encode(on: &_container, forKey: .recipient)
try replaces?.encode(on: &_container, forKey: .replaces)
try requester?.encode(on: &_container, forKey: .requester)
try sender?.encode(on: &_container, forKey: .sender)
try status.encode(on: &_container, forKey: .status, auxiliaryKey: ._status)
try subject?.encode(on: &_container, forKey: .subject)
try topic?.encode(on: &_container, forKey: .topic)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? CommunicationRequest else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return authoredOn == _other.authoredOn
&& basedOn == _other.basedOn
&& category == _other.category
&& context == _other.context
&& groupIdentifier == _other.groupIdentifier
&& identifier == _other.identifier
&& medium == _other.medium
&& note == _other.note
&& occurrence == _other.occurrence
&& payload == _other.payload
&& priority == _other.priority
&& reasonCode == _other.reasonCode
&& reasonReference == _other.reasonReference
&& recipient == _other.recipient
&& replaces == _other.replaces
&& requester == _other.requester
&& sender == _other.sender
&& status == _other.status
&& subject == _other.subject
&& topic == _other.topic
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(authoredOn)
hasher.combine(basedOn)
hasher.combine(category)
hasher.combine(context)
hasher.combine(groupIdentifier)
hasher.combine(identifier)
hasher.combine(medium)
hasher.combine(note)
hasher.combine(occurrence)
hasher.combine(payload)
hasher.combine(priority)
hasher.combine(reasonCode)
hasher.combine(reasonReference)
hasher.combine(recipient)
hasher.combine(replaces)
hasher.combine(requester)
hasher.combine(sender)
hasher.combine(status)
hasher.combine(subject)
hasher.combine(topic)
}
}
/**
Message payload.
Text, attachment(s), or resource(s) to be communicated to the recipient.
*/
open class CommunicationRequestPayload: BackboneElement {
/// All possible types for "content[x]"
public enum ContentX: Hashable {
case attachment(Attachment)
case reference(Reference)
case string(FHIRPrimitive<FHIRString>)
}
/// Message part content
/// One of `content[x]`
public var content: ContentX
/// Designated initializer taking all required properties
public init(content: ContentX) {
self.content = content
super.init()
}
/// Convenience initializer
public convenience init(
content: ContentX,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
modifierExtension: [Extension]? = nil)
{
self.init(content: content)
self.`extension` = `extension`
self.id = id
self.modifierExtension = modifierExtension
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case contentAttachment
case contentReference
case contentString; case _contentString
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Validate that we have at least one of the mandatory properties for expanded properties
guard _container.contains(CodingKeys.contentAttachment) || _container.contains(CodingKeys.contentReference) || _container.contains(CodingKeys.contentString) else {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: [CodingKeys.contentAttachment, CodingKeys.contentReference, CodingKeys.contentString], debugDescription: "Must have at least one value for \"content\" but have none"))
}
// Decode all our properties
var _t_content: ContentX? = nil
if let contentString = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .contentString, auxiliaryKey: ._contentString) {
if _t_content != nil {
throw DecodingError.dataCorruptedError(forKey: .contentString, in: _container, debugDescription: "More than one value provided for \"content\"")
}
_t_content = .string(contentString)
}
if let contentAttachment = try Attachment(from: _container, forKeyIfPresent: .contentAttachment) {
if _t_content != nil {
throw DecodingError.dataCorruptedError(forKey: .contentAttachment, in: _container, debugDescription: "More than one value provided for \"content\"")
}
_t_content = .attachment(contentAttachment)
}
if let contentReference = try Reference(from: _container, forKeyIfPresent: .contentReference) {
if _t_content != nil {
throw DecodingError.dataCorruptedError(forKey: .contentReference, in: _container, debugDescription: "More than one value provided for \"content\"")
}
_t_content = .reference(contentReference)
}
self.content = _t_content!
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
switch content {
case .string(let _value):
try _value.encode(on: &_container, forKey: .contentString, auxiliaryKey: ._contentString)
case .attachment(let _value):
try _value.encode(on: &_container, forKey: .contentAttachment)
case .reference(let _value):
try _value.encode(on: &_container, forKey: .contentReference)
}
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? CommunicationRequestPayload else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return content == _other.content
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(content)
}
}
/**
Who/what is requesting service.
The individual who initiated the request and has responsibility for its activation.
*/
open class CommunicationRequestRequester: BackboneElement {
/// Individual making the request
public var agent: Reference
/// Organization agent is acting for
public var onBehalfOf: Reference?
/// Designated initializer taking all required properties
public init(agent: Reference) {
self.agent = agent
super.init()
}
/// Convenience initializer
public convenience init(
agent: Reference,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
modifierExtension: [Extension]? = nil,
onBehalfOf: Reference? = nil)
{
self.init(agent: agent)
self.`extension` = `extension`
self.id = id
self.modifierExtension = modifierExtension
self.onBehalfOf = onBehalfOf
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case agent
case onBehalfOf
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.agent = try Reference(from: _container, forKey: .agent)
self.onBehalfOf = try Reference(from: _container, forKeyIfPresent: .onBehalfOf)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try agent.encode(on: &_container, forKey: .agent)
try onBehalfOf?.encode(on: &_container, forKey: .onBehalfOf)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? CommunicationRequestRequester else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return agent == _other.agent
&& onBehalfOf == _other.onBehalfOf
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(agent)
hasher.combine(onBehalfOf)
}
}
| 34.030888 | 248 | 0.726344 |
62acec1503db8455b4c125f39456cf72d62acf40 | 5,004 | //
// PacketTunnelProvider.swift
// PacketTunnel
//
// Created by Aofei Sheng on 2018/3/23.
// Copyright © 2018 Aofei Sheng. All rights reserved.
//
import NetworkExtension
class PacketTunnelProvider: NEPacketTunnelProvider {
var shadowsocks: Shadowsocks?
override func startTunnel(options _: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
let providerConfiguration = (protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration!
let generalHideVPNIcon = providerConfiguration["general_hide_vpn_icon"] as! Bool
let generalPACURL = URL(string: providerConfiguration["general_pac_url"] as! String)!
let generalPACContent = providerConfiguration["general_pac_content"] as! String
let generalPACMaxAge = providerConfiguration["general_pac_max_age"] as! TimeInterval
let shadowsocksServerAddress = lookupIPAddress(hostname: providerConfiguration["shadowsocks_server_address"] as! String)!
let shadowsocksServerPort = providerConfiguration["shadowsocks_server_port"] as! UInt16
let shadowsocksLocalAddress = lookupIPAddress(hostname: providerConfiguration["shadowsocks_local_address"] as! String)!
let shadowsocksLocalPort = providerConfiguration["shadowsocks_local_port"] as! UInt16
let shadowsocksPassword = providerConfiguration["shadowsocks_password"] as! String
let shadowsocksMethod = providerConfiguration["shadowsocks_method"] as! String
let networkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: shadowsocksServerAddress)
networkSettings.dnsSettings = NEDNSSettings(servers: ["8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844"])
networkSettings.proxySettings = NEProxySettings()
networkSettings.proxySettings?.autoProxyConfigurationEnabled = true
if generalPACMaxAge == 0 {
networkSettings.proxySettings?.proxyAutoConfigurationURL = generalPACURL
} else {
networkSettings.proxySettings?.proxyAutoConfigurationJavaScript = generalPACContent
}
networkSettings.proxySettings?.excludeSimpleHostnames = true
networkSettings.proxySettings?.matchDomains = [""]
networkSettings.ipv4Settings = NEIPv4Settings(addresses: generalHideVPNIcon ? [] : ["10.0.0.1"], subnetMasks: generalHideVPNIcon ? [] : ["255.0.0.0"])
networkSettings.ipv6Settings = NEIPv6Settings(addresses: generalHideVPNIcon ? [] : ["::ffff:a00:1"], networkPrefixLengths: generalHideVPNIcon ? [] : [96])
networkSettings.mtu = 1500
setTunnelNetworkSettings(networkSettings) { error in
if error == nil && self.shadowsocks == nil {
do {
self.shadowsocks = Shadowsocks(
serverAddress: shadowsocksServerAddress,
serverPort: shadowsocksServerPort,
localAddress: shadowsocksLocalAddress,
localPort: shadowsocksLocalPort,
password: shadowsocksPassword,
method: shadowsocksMethod
)
try self.shadowsocks?.start()
} catch let error {
completionHandler(error)
return
}
if generalPACMaxAge > 0 {
self.updatePACPeriodically()
}
}
completionHandler(error)
}
}
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
if reason != .none {
shadowsocks?.stop()
}
completionHandler()
}
func updatePACPeriodically() {
var providerConfiguration = (protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration!
let generalPACURL = URL(string: providerConfiguration["general_pac_url"] as! String)!
let generalPACContent = providerConfiguration["general_pac_content"] as! String
let generalPACMaxAge = providerConfiguration["general_pac_max_age"] as! TimeInterval
var urlRequest = URLRequest(url: generalPACURL)
urlRequest.httpMethod = "GET"
let urlSessionTask = URLSession(configuration: .default).downloadTask(with: urlRequest) { tempLocalURL, urlResponse, _ in
if (urlResponse as? HTTPURLResponse)?.statusCode == 200, let tempLocalURL = tempLocalURL, let pacContent = try? String(contentsOf: tempLocalURL, encoding: .utf8), pacContent != generalPACContent {
providerConfiguration["general_pac_content"] = pacContent
self.stopTunnel(with: .none) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.startTunnel(options: nil) { _ in }
}
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + generalPACMaxAge) {
self.updatePACPeriodically()
}
}
urlSessionTask.resume()
}
func lookupIPAddress(hostname: String) -> String? {
let host = CFHostCreateWithName(nil, hostname as CFString).takeRetainedValue()
CFHostStartInfoResolution(host, .addresses, nil)
for address in (CFHostGetAddressing(host, nil)?.takeUnretainedValue() as NSArray?) ?? [] {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if let address = address as? NSData,
getnameinfo(address.bytes.assumingMemoryBound(to: sockaddr.self), socklen_t(address.length), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 {
return String(cString: hostname)
}
}
return nil
}
}
| 42.05042 | 199 | 0.758193 |
4b7f6d3129ab092fafb28ed4da51cd64f127d483 | 65,581 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import TSCBasic
import TSCUtility
import Basics
import PackageModel
import PackageLoading
import PackageGraph
/// The parameters required by `PIFBuilder`.
public struct PIFBuilderParameters {
/// Whether or not build for testability is enabled.
public let enableTestability: Bool
/// Whether to create dylibs for dynamic library products.
public let shouldCreateDylibForDynamicProducts: Bool
/// The path to the library directory of the active toolchain.
public let toolchainLibDir: AbsolutePath
/// Creates a `PIFBuilderParameters` instance.
/// - Parameters:
/// - enableTestability: Whether or not build for testability is enabled.
/// - shouldCreateDylibForDynamicProducts: Whether to create dylibs for dynamic library products.
public init(enableTestability: Bool, shouldCreateDylibForDynamicProducts: Bool, toolchainLibDir: AbsolutePath) {
self.enableTestability = enableTestability
self.shouldCreateDylibForDynamicProducts = shouldCreateDylibForDynamicProducts
self.toolchainLibDir = toolchainLibDir
}
}
/// PIF object builder for a package graph.
public final class PIFBuilder {
/// Name of the PIF target aggregating all targets (excluding tests).
public static let allExcludingTestsTargetName = "AllExcludingTests"
/// Name of the PIF target aggregating all targets (including tests).
public static let allIncludingTestsTargetName = "AllIncludingTests"
/// The package graph to build from.
public let graph: PackageGraph
/// The parameters used to configure the PIF.
public let parameters: PIFBuilderParameters
/// The ObservabilityScope to emit diagnostics to.
public let observabilityScope: ObservabilityScope
/// The file system to read from.
public let fileSystem: FileSystem
private var pif: PIF.TopLevelObject?
/// Creates a `PIFBuilder` instance.
/// - Parameters:
/// - graph: The package graph to build from.
/// - parameters: The parameters used to configure the PIF.
/// - fileSystem: The file system to read from.
/// - observabilityScope: The ObservabilityScope to emit diagnostics to.
public init(
graph: PackageGraph,
parameters: PIFBuilderParameters,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) {
self.graph = graph
self.parameters = parameters
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope.makeChildScope(description: "PIF Builder")
}
/// Generates the PIF representation.
/// - Parameters:
/// - prettyPrint: Whether to return a formatted JSON.
/// - Returns: The package graph in the JSON PIF format.
public func generatePIF(
prettyPrint: Bool = true,
preservePIFModelStructure: Bool = false
) throws -> String {
let encoder = prettyPrint ? JSONEncoder.makeWithDefaults() : JSONEncoder()
if !preservePIFModelStructure {
encoder.userInfo[.encodeForXCBuild] = true
}
let topLevelObject = try self.construct()
// Sign the pif objects before encoding it for XCBuild.
try PIF.sign(topLevelObject.workspace)
let pifData = try encoder.encode(topLevelObject)
return String(data: pifData, encoding: .utf8)!
}
/// Constructs a `PIF.TopLevelObject` representing the package graph.
public func construct() throws -> PIF.TopLevelObject {
try memoize(to: &pif) {
let rootPackage = graph.rootPackages[0]
let sortedPackages = graph.packages.sorted { $0.manifest.displayName < $1.manifest.displayName } // TODO: use identity instead?
var projects: [PIFProjectBuilder] = try sortedPackages.map { package in
try PackagePIFProjectBuilder(
package: package,
parameters: parameters,
fileSystem: self.fileSystem,
observabilityScope: self.observabilityScope
)
}
projects.append(AggregatePIFProjectBuilder(projects: projects))
let workspace = PIF.Workspace(
guid: "Workspace:\(rootPackage.path.pathString)",
name: rootPackage.manifest.displayName, // TODO: use identity instead?
path: rootPackage.path,
projects: try projects.map { try $0.construct() }
)
return PIF.TopLevelObject(workspace: workspace)
}
}
}
class PIFProjectBuilder {
let groupTree: PIFGroupBuilder
private(set) var targets: [PIFBaseTargetBuilder]
private(set) var buildConfigurations: [PIFBuildConfigurationBuilder]
@DelayedImmutable
var guid: PIF.GUID
@DelayedImmutable
var name: String
@DelayedImmutable
var path: AbsolutePath
@DelayedImmutable
var projectDirectory: AbsolutePath
@DelayedImmutable
var developmentRegion: String
fileprivate init() {
groupTree = PIFGroupBuilder(path: "")
targets = []
buildConfigurations = []
}
/// Creates and adds a new empty build configuration, i.e. one that does not initially have any build settings.
/// The name must not be empty and must not be equal to the name of any existing build configuration in the target.
@discardableResult
func addBuildConfiguration(
name: String,
settings: PIF.BuildSettings = PIF.BuildSettings()
) -> PIFBuildConfigurationBuilder {
let builder = PIFBuildConfigurationBuilder(name: name, settings: settings)
buildConfigurations.append(builder)
return builder
}
/// Creates and adds a new empty target, i.e. one that does not initially have any build phases. If provided,
/// the ID must be non-empty and unique within the PIF workspace; if not provided, an arbitrary guaranteed-to-be-
/// unique identifier will be assigned. The name must not be empty and must not be equal to the name of any existing
/// target in the project.
@discardableResult
func addTarget(
guid: PIF.GUID,
name: String,
productType: PIF.Target.ProductType,
productName: String
) -> PIFTargetBuilder {
let target = PIFTargetBuilder(guid: guid, name: name, productType: productType, productName: productName)
targets.append(target)
return target
}
@discardableResult
func addAggregateTarget(guid: PIF.GUID, name: String) -> PIFAggregateTargetBuilder {
let target = PIFAggregateTargetBuilder(guid: guid, name: name)
targets.append(target)
return target
}
func construct() throws -> PIF.Project {
let buildConfigurations = self.buildConfigurations.map { builder -> PIF.BuildConfiguration in
builder.guid = "\(guid)::BUILDCONFIG_\(builder.name)"
return builder.construct()
}
// Construct group tree before targets to make sure file references have GUIDs.
groupTree.guid = "\(guid)::MAINGROUP"
let groupTree = self.groupTree.construct() as! PIF.Group
let targets = try self.targets.map { try $0.construct() }
return PIF.Project(
guid: guid,
name: name,
path: path,
projectDirectory: projectDirectory,
developmentRegion: developmentRegion,
buildConfigurations: buildConfigurations,
targets: targets,
groupTree: groupTree
)
}
}
final class PackagePIFProjectBuilder: PIFProjectBuilder {
private let package: ResolvedPackage
private let parameters: PIFBuilderParameters
private let fileSystem: FileSystem
private let observabilityScope: ObservabilityScope
private var binaryGroup: PIFGroupBuilder!
private let executableTargetProductMap: [ResolvedTarget: ResolvedProduct]
var isRootPackage: Bool { package.manifest.packageKind.isRoot }
init(
package: ResolvedPackage,
parameters: PIFBuilderParameters,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) throws {
self.package = package
self.parameters = parameters
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope.makeChildScope(
description: "Package PIF Builder",
metadata: package.underlyingPackage.diagnosticsMetadata
)
executableTargetProductMap = Dictionary(uniqueKeysWithValues:
package.products.filter { $0.type == .executable }.map { ($0.mainTarget, $0) }
)
super.init()
guid = package.pifProjectGUID
name = package.manifest.displayName // TODO: use identity instead?
path = package.path
projectDirectory = package.path
developmentRegion = package.manifest.defaultLocalization ?? "en"
binaryGroup = groupTree.addGroup(path: "/", sourceTree: .absolute, name: "Binaries")
// Configure the project-wide build settings. First we set those that are in common between the "Debug" and
// "Release" configurations, and then we set those that are different.
var settings = PIF.BuildSettings()
settings[.PRODUCT_NAME] = "$(TARGET_NAME)"
settings[.SUPPORTED_PLATFORMS] = ["$(AVAILABLE_PLATFORMS)"]
settings[.SDKROOT] = "auto"
settings[.SDK_VARIANT] = "auto"
settings[.SKIP_INSTALL] = "YES"
let firstTarget = package.targets.first(where: { $0.type != .test })?.underlyingTarget ?? package.targets.first?.underlyingTarget
settings[.MACOSX_DEPLOYMENT_TARGET] = firstTarget?.deploymentTarget(for: .macOS)
settings[.IPHONEOS_DEPLOYMENT_TARGET] = firstTarget?.deploymentTarget(for: .iOS)
settings[.IPHONEOS_DEPLOYMENT_TARGET, for: .macCatalyst] = firstTarget?.deploymentTarget(for: .macCatalyst)
settings[.TVOS_DEPLOYMENT_TARGET] = firstTarget?.deploymentTarget(for: .tvOS)
settings[.WATCHOS_DEPLOYMENT_TARGET] = firstTarget?.deploymentTarget(for: .watchOS)
settings[.DRIVERKIT_DEPLOYMENT_TARGET] = firstTarget?.deploymentTarget(for: .driverKit)
settings[.DYLIB_INSTALL_NAME_BASE] = "@rpath"
settings[.USE_HEADERMAP] = "NO"
settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS] = ["$(inherited)", "SWIFT_PACKAGE"]
settings[.GCC_PREPROCESSOR_DEFINITIONS] = ["$(inherited)", "SWIFT_PACKAGE"]
settings[.CLANG_ENABLE_OBJC_ARC] = "YES"
settings[.KEEP_PRIVATE_EXTERNS] = "NO"
// We currently deliberately do not support Swift ObjC interface headers.
settings[.SWIFT_INSTALL_OBJC_HEADER] = "NO"
settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME] = ""
settings[.OTHER_LDRFLAGS] = []
// This will add the XCTest related search paths automatically
// (including the Swift overlays).
settings[.ENABLE_TESTING_SEARCH_PATHS] = "YES"
// XCTest search paths should only be specified for certain platforms (watchOS doesn't have XCTest).
for platform: PIF.BuildSettings.Platform in [.macOS, .iOS, .tvOS] {
settings[.FRAMEWORK_SEARCH_PATHS, for: platform, default: ["$(inherited)"]]
.append("$(PLATFORM_DIR)/Developer/Library/Frameworks")
}
PlatformRegistry.default.knownPlatforms.forEach {
guard let platform = PIF.BuildSettings.Platform.from(platform: $0) else { return }
guard let supportedPlatform = firstTarget?.getSupportedPlatform(for: $0) else { return }
if !supportedPlatform.options.isEmpty {
settings[.SPECIALIZATION_SDK_OPTIONS, for: platform] = supportedPlatform.options
}
}
// Disable signing for all the things since there is no way to configure
// signing information in packages right now.
settings[.ENTITLEMENTS_REQUIRED] = "NO"
settings[.CODE_SIGNING_REQUIRED] = "NO"
settings[.CODE_SIGN_IDENTITY] = ""
var debugSettings = settings
debugSettings[.COPY_PHASE_STRIP] = "NO"
debugSettings[.DEBUG_INFORMATION_FORMAT] = "dwarf"
debugSettings[.ENABLE_NS_ASSERTIONS] = "YES"
debugSettings[.GCC_OPTIMIZATION_LEVEL] = "0"
debugSettings[.ONLY_ACTIVE_ARCH] = "YES"
debugSettings[.SWIFT_OPTIMIZATION_LEVEL] = "-Onone"
debugSettings[.ENABLE_TESTABILITY] = "YES"
debugSettings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: []].append("DEBUG")
debugSettings[.GCC_PREPROCESSOR_DEFINITIONS, default: ["$(inherited)"]].append("DEBUG=1")
addBuildConfiguration(name: "Debug", settings: debugSettings)
var releaseSettings = settings
releaseSettings[.COPY_PHASE_STRIP] = "YES"
releaseSettings[.DEBUG_INFORMATION_FORMAT] = "dwarf-with-dsym"
releaseSettings[.GCC_OPTIMIZATION_LEVEL] = "s"
releaseSettings[.SWIFT_OPTIMIZATION_LEVEL] = "-Owholemodule"
if parameters.enableTestability {
releaseSettings[.ENABLE_TESTABILITY] = "YES"
}
addBuildConfiguration(name: "Release", settings: releaseSettings)
for product in package.products.sorted(by: { $0.name < $1.name }) {
addTarget(for: product)
}
for target in package.targets.sorted(by: { $0.name < $1.name }) {
try self.addTarget(for: target)
}
if binaryGroup.children.isEmpty {
groupTree.removeChild(binaryGroup)
}
}
private func addTarget(for product: ResolvedProduct) {
switch product.type {
case .executable, .snippet, .test:
addMainModuleTarget(for: product)
case .library:
addLibraryTarget(for: product)
case .plugin:
return
}
}
private func addTarget(for target: ResolvedTarget) throws {
switch target.type {
case .library:
try self.addLibraryTarget(for: target)
case .systemModule:
try self.addSystemTarget(for: target)
case .executable, .snippet, .test:
// Skip executable module targets and test module targets (they will have been dealt with as part of the
// products to which they belong).
return
case .binary:
// Binary target don't need to be built.
return
case .plugin:
// Package plugin targets.
return
}
}
private func targetName(for product: ResolvedProduct) -> String {
return Self.targetName(for: product.name)
}
static func targetName(for productName: String) -> String {
return "\(productName)_\(String(productName.hash, radix: 16, uppercase: true))_PackageProduct"
}
private func addMainModuleTarget(for product: ResolvedProduct) {
let productType: PIF.Target.ProductType = product.type == .executable ? .executable : .unitTest
let pifTarget = addTarget(
guid: product.pifTargetGUID,
name: targetName(for: product),
productType: productType,
productName: product.name
)
// We'll be infusing the product's main module target into the one for the product itself.
let mainTarget = product.mainTarget
addSources(mainTarget.sources, to: pifTarget)
let dependencies = try! topologicalSort(mainTarget.dependencies) { $0.packageDependencies }.sorted()
for dependency in dependencies {
addDependency(to: dependency, in: pifTarget, linkProduct: true)
}
// Configure the target-wide build settings. The details depend on the kind of product we're building, but are
// in general the ones that are suitable for end-product artifacts such as executables and test bundles.
var settings = PIF.BuildSettings()
settings[.TARGET_NAME] = product.name
settings[.PACKAGE_RESOURCE_TARGET_KIND] = "regular"
settings[.PRODUCT_NAME] = product.name
settings[.PRODUCT_MODULE_NAME] = mainTarget.c99name
settings[.PRODUCT_BUNDLE_IDENTIFIER] = product.name
settings[.EXECUTABLE_NAME] = product.name
settings[.CLANG_ENABLE_MODULES] = "YES"
settings[.DEFINES_MODULE] = "YES"
settings[.SWIFT_FORCE_STATIC_LINK_STDLIB] = "NO"
settings[.SWIFT_FORCE_DYNAMIC_LINK_STDLIB] = "YES"
if product.type == .executable || product.type == .test {
settings[.LIBRARY_SEARCH_PATHS] = ["$(inherited)", "\(parameters.toolchainLibDir.pathString)/swift/macosx"]
}
// Tests can have a custom deployment target based on the minimum supported by XCTest.
if mainTarget.underlyingTarget.type == .test {
settings[.MACOSX_DEPLOYMENT_TARGET] = mainTarget.underlyingTarget.deploymentTarget(for: .macOS)
settings[.IPHONEOS_DEPLOYMENT_TARGET] = mainTarget.underlyingTarget.deploymentTarget(for: .iOS)
settings[.TVOS_DEPLOYMENT_TARGET] = mainTarget.underlyingTarget.deploymentTarget(for: .tvOS)
settings[.WATCHOS_DEPLOYMENT_TARGET] = mainTarget.underlyingTarget.deploymentTarget(for: .watchOS)
}
if product.type == .executable {
// Command-line tools are only supported for the macOS platforms.
settings[.SDKROOT] = "macosx"
settings[.SUPPORTED_PLATFORMS] = ["macosx", "linux"]
// Setup install path for executables if it's in root of a pure Swift package.
if isRootPackage {
settings[.SKIP_INSTALL] = "NO"
settings[.INSTALL_PATH] = "/usr/local/bin"
settings[.LD_RUNPATH_SEARCH_PATHS, default: ["$(inherited)"]].append("@executable_path/../lib")
}
} else {
// FIXME: we shouldn't always include both the deep and shallow bundle paths here, but for that we'll need
// rdar://problem/31867023
settings[.LD_RUNPATH_SEARCH_PATHS, default: ["$(inherited)"]] +=
["@loader_path/Frameworks", "@loader_path/../Frameworks"]
settings[.GENERATE_INFOPLIST_FILE] = "YES"
}
if let clangTarget = mainTarget.underlyingTarget as? ClangTarget {
// Let the target itself find its own headers.
settings[.HEADER_SEARCH_PATHS, default: ["$(inherited)"]].append(clangTarget.includeDir.pathString)
settings[.GCC_C_LANGUAGE_STANDARD] = clangTarget.cLanguageStandard
settings[.CLANG_CXX_LANGUAGE_STANDARD] = clangTarget.cxxLanguageStandard
} else if let swiftTarget = mainTarget.underlyingTarget as? SwiftTarget {
settings[.SWIFT_VERSION] = swiftTarget.swiftVersion.description
}
if let resourceBundle = addResourceBundle(for: mainTarget, in: pifTarget) {
settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle
}
// For targets, we use the common build settings for both the "Debug" and the "Release" configurations (all
// differentiation is at the project level).
var debugSettings = settings
var releaseSettings = settings
var impartedSettings = PIF.BuildSettings()
addManifestBuildSettings(
from: mainTarget.underlyingTarget,
debugSettings: &debugSettings,
releaseSettings: &releaseSettings,
impartedSettings: &impartedSettings
)
pifTarget.addBuildConfiguration(name: "Debug", settings: debugSettings)
pifTarget.addBuildConfiguration(name: "Release", settings: releaseSettings)
}
private func addLibraryTarget(for product: ResolvedProduct) {
let pifTargetProductName: String
let executableName: String
let productType: PIF.Target.ProductType
if product.type == .library(.dynamic) {
if parameters.shouldCreateDylibForDynamicProducts {
pifTargetProductName = "lib\(product.name).dylib"
executableName = pifTargetProductName
productType = .dynamicLibrary
} else {
pifTargetProductName = product.name + ".framework"
executableName = product.name
productType = .framework
}
} else {
pifTargetProductName = "lib\(product.name).a"
executableName = pifTargetProductName
productType = .packageProduct
}
// Create a special kind of .packageProduct PIF target that just "groups" a set of targets for clients to
// depend on. XCBuild will not produce a separate artifact for a package product, but will instead consider any
// dependency on the package product to be a dependency on the whole set of targets on which the package product
// depends.
let pifTarget = addTarget(
guid: product.pifTargetGUID,
name: targetName(for: product),
productType: productType,
productName: pifTargetProductName
)
// Handle the dependencies of the targets in the product (and link against them, which in the case of a package
// product, really just means that clients should link against them).
let dependencies = product.recursivePackageDependencies()
for dependency in dependencies {
switch dependency {
case .target(let target, let conditions):
if target.type != .systemModule {
addDependency(to: target, in: pifTarget, conditions: conditions, linkProduct: true)
}
case .product(let product, let conditions):
addDependency(to: product, in: pifTarget, conditions: conditions, linkProduct: true)
}
}
var settings = PIF.BuildSettings()
let usesUnsafeFlags = dependencies.contains { $0.target?.underlyingTarget.usesUnsafeFlags == true }
settings[.USES_SWIFTPM_UNSAFE_FLAGS] = usesUnsafeFlags ? "YES" : "NO"
// If there are no system modules in the dependency graph, mark the target as extension-safe.
let dependsOnAnySystemModules = dependencies.contains { $0.target?.type == .systemModule }
if !dependsOnAnySystemModules {
settings[.APPLICATION_EXTENSION_API_ONLY] = "YES"
}
// Add other build settings when we're building an actual dylib.
if product.type == .library(.dynamic) {
settings[.TARGET_NAME] = product.name
settings[.PRODUCT_NAME] = executableName
settings[.PRODUCT_MODULE_NAME] = product.name
settings[.PRODUCT_BUNDLE_IDENTIFIER] = product.name
settings[.EXECUTABLE_NAME] = executableName
settings[.CLANG_ENABLE_MODULES] = "YES"
settings[.DEFINES_MODULE] = "YES"
settings[.SKIP_INSTALL] = "NO"
settings[.INSTALL_PATH] = "/usr/local/lib"
settings[.LIBRARY_SEARCH_PATHS] = ["$(inherited)", "\(parameters.toolchainLibDir.pathString)/swift/macosx"]
if !parameters.shouldCreateDylibForDynamicProducts {
settings[.GENERATE_INFOPLIST_FILE] = "YES"
// If the built framework is named same as one of the target in the package, it can be picked up
// automatically during indexing since the build system always adds a -F flag to the built products dir.
// To avoid this problem, we build all package frameworks in a subdirectory.
settings[.BUILT_PRODUCTS_DIR] = "$(BUILT_PRODUCTS_DIR)/PackageFrameworks"
settings[.TARGET_BUILD_DIR] = "$(TARGET_BUILD_DIR)/PackageFrameworks"
// Set the project and marketing version for the framework because the app store requires these to be
// present. The AppStore requires bumping the project version when ingesting new builds but that's for
// top-level apps and not frameworks embedded inside it.
settings[.MARKETING_VERSION] = "1.0" // Version
settings[.CURRENT_PROJECT_VERSION] = "1" // Build
}
pifTarget.addSourcesBuildPhase()
}
pifTarget.addBuildConfiguration(name: "Debug", settings: settings)
pifTarget.addBuildConfiguration(name: "Release", settings: settings)
}
private func addLibraryTarget(for target: ResolvedTarget) throws {
let pifTarget = addTarget(
guid: target.pifTargetGUID,
name: target.name,
productType: .objectFile,
productName: "\(target.name).o"
)
var settings = PIF.BuildSettings()
settings[.TARGET_NAME] = target.name
settings[.PACKAGE_RESOURCE_TARGET_KIND] = "regular"
settings[.PRODUCT_NAME] = "\(target.name).o"
settings[.PRODUCT_MODULE_NAME] = target.c99name
settings[.PRODUCT_BUNDLE_IDENTIFIER] = target.name
settings[.EXECUTABLE_NAME] = "\(target.name).o"
settings[.CLANG_ENABLE_MODULES] = "YES"
settings[.DEFINES_MODULE] = "YES"
settings[.MACH_O_TYPE] = "mh_object"
settings[.GENERATE_MASTER_OBJECT_FILE] = "NO"
// Disable code coverage linker flags since we're producing .o files. Otherwise, we will run into duplicated
// symbols when there are more than one targets that produce .o as their product.
settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS] = "NO"
// Create a set of build settings that will be imparted to any target that depends on this one.
var impartedSettings = PIF.BuildSettings()
let generatedModuleMapDir = "$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)"
let moduleMapFile = "\(generatedModuleMapDir)/\(target.name).modulemap"
let moduleMapFileContents: String?
let shouldImpartModuleMap: Bool
if let clangTarget = target.underlyingTarget as? ClangTarget {
// Let the target itself find its own headers.
settings[.HEADER_SEARCH_PATHS, default: ["$(inherited)"]].append(clangTarget.includeDir.pathString)
settings[.GCC_C_LANGUAGE_STANDARD] = clangTarget.cLanguageStandard
settings[.CLANG_CXX_LANGUAGE_STANDARD] = clangTarget.cxxLanguageStandard
// Also propagate this search path to all direct and indirect clients.
impartedSettings[.HEADER_SEARCH_PATHS, default: ["$(inherited)"]].append(clangTarget.includeDir.pathString)
if !fileSystem.exists(clangTarget.moduleMapPath) {
impartedSettings[.OTHER_SWIFT_FLAGS, default: ["$(inherited)"]] +=
["-Xcc", "-fmodule-map-file=\(moduleMapFile)"]
moduleMapFileContents = """
module \(target.c99name) {
umbrella "\(clangTarget.includeDir.pathString)"
export *
}
"""
shouldImpartModuleMap = true
} else {
moduleMapFileContents = nil
shouldImpartModuleMap = false
}
} else if let swiftTarget = target.underlyingTarget as? SwiftTarget {
settings[.SWIFT_VERSION] = swiftTarget.swiftVersion.description
// Generate ObjC compatibility header for Swift library targets.
settings[.SWIFT_OBJC_INTERFACE_HEADER_DIR] = "$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)"
settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME] = "\(target.name)-Swift.h"
moduleMapFileContents = """
module \(target.c99name) {
header "\(target.name)-Swift.h"
export *
}
"""
shouldImpartModuleMap = true
} else {
throw InternalError("unexpected target")
}
if let moduleMapFileContents = moduleMapFileContents {
settings[.MODULEMAP_PATH] = moduleMapFile
settings[.MODULEMAP_FILE_CONTENTS] = moduleMapFileContents
}
// Pass the path of the module map up to all direct and indirect clients.
if shouldImpartModuleMap {
impartedSettings[.OTHER_CFLAGS, default: ["$(inherited)"]].append("-fmodule-map-file=\(moduleMapFile)")
}
impartedSettings[.OTHER_LDRFLAGS] = []
if target.underlyingTarget.isCxx {
impartedSettings[.OTHER_LDFLAGS, default: ["$(inherited)"]].append("-lc++")
}
addSources(target.sources, to: pifTarget)
// Handle the target's dependencies (but don't link against them).
let dependencies = try! topologicalSort(target.dependencies) { $0.packageDependencies }.sorted()
for dependency in dependencies {
addDependency(to: dependency, in: pifTarget, linkProduct: false)
}
if let resourceBundle = addResourceBundle(for: target, in: pifTarget) {
settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle
impartedSettings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES, default: ["$(inherited)"]].append(resourceBundle)
}
// For targets, we use the common build settings for both the "Debug" and the "Release" configurations (all
// differentiation is at the project level).
var debugSettings = settings
var releaseSettings = settings
addManifestBuildSettings(
from: target.underlyingTarget,
debugSettings: &debugSettings,
releaseSettings: &releaseSettings,
impartedSettings: &impartedSettings
)
pifTarget.addBuildConfiguration(name: "Debug", settings: debugSettings)
pifTarget.addBuildConfiguration(name: "Release", settings: releaseSettings)
pifTarget.impartedBuildSettings = impartedSettings
}
private func addSystemTarget(for target: ResolvedTarget) throws {
guard let systemTarget = target.underlyingTarget as? SystemLibraryTarget else {
throw InternalError("unexpected target type")
}
// Create an aggregate PIF target (which doesn't have an actual product).
let pifTarget = addAggregateTarget(guid: target.pifTargetGUID, name: target.name)
pifTarget.addBuildConfiguration(name: "Debug", settings: PIF.BuildSettings())
pifTarget.addBuildConfiguration(name: "Release", settings: PIF.BuildSettings())
// Impart the header search path to all direct and indirect clients.
var impartedSettings = PIF.BuildSettings()
var cFlags: [String] = []
for result in pkgConfigArgs(for: systemTarget, fileSystem: fileSystem, observabilityScope: self.observabilityScope) {
if let error = result.error {
self.observabilityScope.emit(
warning: "\(error)",
metadata: .pkgConfig(pcFile: result.pkgConfigName, targetName: target.name)
)
} else {
cFlags = result.cFlags
impartedSettings[.OTHER_LDFLAGS, default: ["$(inherited)"]] += result.libs
}
}
impartedSettings[.OTHER_LDRFLAGS] = []
impartedSettings[.OTHER_CFLAGS, default: ["$(inherited)"]] += ["-fmodule-map-file=\(systemTarget.moduleMapPath)"] + cFlags
impartedSettings[.OTHER_SWIFT_FLAGS, default: ["$(inherited)"]] += ["-Xcc", "-fmodule-map-file=\(systemTarget.moduleMapPath)"] + cFlags
pifTarget.impartedBuildSettings = impartedSettings
}
private func addSources(_ sources: Sources, to pifTarget: PIFTargetBuilder) {
// Create a group for the target's source files. For now we use an absolute path for it, but we should really
// make it be container-relative, since it's always inside the package directory.
let targetGroup = groupTree.addGroup(
path: sources.root.relative(to: package.path).pathString,
sourceTree: .group
)
// Add a source file reference for each of the source files, and also an indexable-file URL for each one.
for path in sources.relativePaths {
pifTarget.addSourceFile(targetGroup.addFileReference(path: path.pathString, sourceTree: .group))
}
}
private func addDependency(
to dependency: ResolvedTarget.Dependency,
in pifTarget: PIFTargetBuilder,
linkProduct: Bool
) {
switch dependency {
case .target(let target, let conditions):
addDependency(
to: target,
in: pifTarget,
conditions: conditions,
linkProduct: linkProduct
)
case .product(let product, let conditions):
addDependency(
to: product,
in: pifTarget,
conditions: conditions,
linkProduct: linkProduct
)
}
}
private func addDependency(
to target: ResolvedTarget,
in pifTarget: PIFTargetBuilder,
conditions: [PackageConditionProtocol],
linkProduct: Bool
) {
// Only add the binary target as a library when we want to link against the product.
if let binaryTarget = target.underlyingTarget as? BinaryTarget {
let ref = binaryGroup.addFileReference(path: binaryTarget.artifactPath.pathString)
pifTarget.addLibrary(ref, platformFilters: conditions.toPlatformFilters())
} else {
// If this is an executable target, the dependency should be to the PIF target created from the its
// product, as we don't have PIF targets corresponding to executable targets.
let targetGUID = executableTargetProductMap[target]?.pifTargetGUID ?? target.pifTargetGUID
let linkProduct = linkProduct && target.type != .systemModule && target.type != .executable
pifTarget.addDependency(
toTargetWithGUID: targetGUID,
platformFilters: conditions.toPlatformFilters(),
linkProduct: linkProduct)
}
}
private func addDependency(
to product: ResolvedProduct,
in pifTarget: PIFTargetBuilder,
conditions: [PackageConditionProtocol],
linkProduct: Bool
) {
pifTarget.addDependency(
toTargetWithGUID: product.pifTargetGUID,
platformFilters: conditions.toPlatformFilters(),
linkProduct: linkProduct
)
}
private func addResourceBundle(for target: ResolvedTarget, in pifTarget: PIFTargetBuilder) -> String? {
guard !target.underlyingTarget.resources.isEmpty else {
return nil
}
let bundleName = "\(package.manifest.displayName)_\(target.name)" // TODO: use identity instead?
let resourcesTarget = addTarget(
guid: target.pifResourceTargetGUID,
name: bundleName,
productType: .bundle,
productName: bundleName
)
pifTarget.addDependency(
toTargetWithGUID: resourcesTarget.guid,
platformFilters: [],
linkProduct: false
)
var settings = PIF.BuildSettings()
settings[.TARGET_NAME] = bundleName
settings[.PRODUCT_NAME] = bundleName
settings[.PRODUCT_MODULE_NAME] = bundleName
let bundleIdentifier = "\(package.manifest.displayName).\(target.name).resources".spm_mangledToBundleIdentifier() // TODO: use identity instead?
settings[.PRODUCT_BUNDLE_IDENTIFIER] = bundleIdentifier
settings[.GENERATE_INFOPLIST_FILE] = "YES"
settings[.PACKAGE_RESOURCE_TARGET_KIND] = "resource"
resourcesTarget.addBuildConfiguration(name: "Debug", settings: settings)
resourcesTarget.addBuildConfiguration(name: "Release", settings: settings)
let coreDataFileTypes = [XCBuildFileType.xcdatamodeld, .xcdatamodel].flatMap { $0.fileTypes }
for resource in target.underlyingTarget.resources {
// FIXME: Handle rules here.
let resourceFile = groupTree.addFileReference(
path: resource.path.pathString,
sourceTree: .absolute
)
// CoreData files should also be in the actual target because they can end up generating code during the
// build. The build system will only perform codegen tasks for the main target in this case.
if coreDataFileTypes.contains(resource.path.extension ?? "") {
pifTarget.addSourceFile(resourceFile)
}
resourcesTarget.addResourceFile(resourceFile)
}
return bundleName
}
// Add inferred build settings for a particular value for a manifest setting and value.
private func addInferredBuildSettings(
for setting: PIF.BuildSettings.MultipleValueSetting,
value: [String],
platform: PIF.BuildSettings.Platform? = nil,
configuration: BuildConfiguration,
settings: inout PIF.BuildSettings
) {
// Automatically set SWIFT_EMIT_MODULE_INTERFACE if the package author uses unsafe flags to enable
// library evolution (this is needed until there is a way to specify this in the package manifest).
if setting == .OTHER_SWIFT_FLAGS && value.contains("-enable-library-evolution") {
settings[.SWIFT_EMIT_MODULE_INTERFACE] = "YES"
}
}
// Apply target-specific build settings defined in the manifest.
private func addManifestBuildSettings(
from target: Target,
debugSettings: inout PIF.BuildSettings,
releaseSettings: inout PIF.BuildSettings,
impartedSettings: inout PIF.BuildSettings
) {
for (setting, assignments) in target.buildSettings.pifAssignments {
for assignment in assignments {
var value = assignment.value
if setting == .HEADER_SEARCH_PATHS {
value = value.map { target.sources.root.appending(RelativePath($0)).pathString }
}
if let platforms = assignment.platforms {
for platform in platforms {
for configuration in assignment.configurations {
switch configuration {
case .debug:
debugSettings[setting, for: platform, default: ["$(inherited)"]] += value
addInferredBuildSettings(for: setting, value: value, platform: platform, configuration: .debug, settings: &debugSettings)
case .release:
releaseSettings[setting, for: platform, default: ["$(inherited)"]] += value
addInferredBuildSettings(for: setting, value: value, platform: platform, configuration: .release, settings: &releaseSettings)
}
}
if setting == .OTHER_LDFLAGS {
impartedSettings[setting, for: platform, default: ["$(inherited)"]] += value
}
}
} else {
for configuration in assignment.configurations {
switch configuration {
case .debug:
debugSettings[setting, default: ["$(inherited)"]] += value
addInferredBuildSettings(for: setting, value: value, configuration: .debug, settings: &debugSettings)
case .release:
releaseSettings[setting, default: ["$(inherited)"]] += value
addInferredBuildSettings(for: setting, value: value, configuration: .release, settings: &releaseSettings)
}
}
if setting == .OTHER_LDFLAGS {
impartedSettings[setting, default: ["$(inherited)"]] += value
}
}
}
}
}
}
final class AggregatePIFProjectBuilder: PIFProjectBuilder {
init(projects: [PIFProjectBuilder]) {
super.init()
guid = "AGGREGATE"
name = "Aggregate"
path = projects[0].path
projectDirectory = projects[0].projectDirectory
developmentRegion = "en"
var settings = PIF.BuildSettings()
settings[.PRODUCT_NAME] = "$(TARGET_NAME)"
settings[.SUPPORTED_PLATFORMS] = ["$(AVAILABLE_PLATFORMS)"]
settings[.SDKROOT] = "auto"
settings[.SDK_VARIANT] = "auto"
settings[.SKIP_INSTALL] = "YES"
addBuildConfiguration(name: "Debug", settings: settings)
addBuildConfiguration(name: "Release", settings: settings)
let allExcludingTestsTarget = addAggregateTarget(
guid: "ALL-EXCLUDING-TESTS",
name: PIFBuilder.allExcludingTestsTargetName
)
allExcludingTestsTarget.addBuildConfiguration(name: "Debug")
allExcludingTestsTarget.addBuildConfiguration(name: "Release")
let allIncludingTestsTarget = addAggregateTarget(
guid: "ALL-INCLUDING-TESTS",
name: PIFBuilder.allIncludingTestsTargetName
)
allIncludingTestsTarget.addBuildConfiguration(name: "Debug")
allIncludingTestsTarget.addBuildConfiguration(name: "Release")
for case let project as PackagePIFProjectBuilder in projects where project.isRootPackage {
for case let target as PIFTargetBuilder in project.targets {
if target.productType != .unitTest {
allExcludingTestsTarget.addDependency(toTargetWithGUID: target.guid, platformFilters: [], linkProduct: false)
}
allIncludingTestsTarget.addDependency(toTargetWithGUID: target.guid, platformFilters: [], linkProduct: false)
}
}
}
}
protocol PIFReferenceBuilder: AnyObject {
var guid: String { get set }
func construct() -> PIF.Reference
}
final class PIFFileReferenceBuilder: PIFReferenceBuilder {
let path: String
let sourceTree: PIF.Reference.SourceTree
let name: String?
let fileType: String?
@DelayedImmutable
var guid: String
init(path: String, sourceTree: PIF.Reference.SourceTree, name: String? = nil, fileType: String? = nil) {
self.path = path
self.sourceTree = sourceTree
self.name = name
self.fileType = fileType
}
func construct() -> PIF.Reference {
return PIF.FileReference(
guid: guid,
path: path,
sourceTree: sourceTree,
name: name,
fileType: fileType
)
}
}
final class PIFGroupBuilder: PIFReferenceBuilder {
let path: String
let sourceTree: PIF.Reference.SourceTree
let name: String?
private(set) var children: [PIFReferenceBuilder]
@DelayedImmutable
var guid: PIF.GUID
init(path: String, sourceTree: PIF.Reference.SourceTree = .group, name: String? = nil) {
self.path = path
self.sourceTree = sourceTree
self.name = name
children = []
}
/// Creates and appends a new Group to the list of children. The new group is returned so that it can be configured.
func addGroup(
path: String,
sourceTree: PIF.Reference.SourceTree = .group,
name: String? = nil
) -> PIFGroupBuilder {
let group = PIFGroupBuilder(path: path, sourceTree: sourceTree, name: name)
children.append(group)
return group
}
/// Creates and appends a new FileReference to the list of children.
func addFileReference(
path: String,
sourceTree: PIF.Reference.SourceTree = .group,
name: String? = nil,
fileType: String? = nil
) -> PIFFileReferenceBuilder {
let file = PIFFileReferenceBuilder(path: path, sourceTree: sourceTree, name: name, fileType: fileType)
children.append(file)
return file
}
func removeChild(_ reference: PIFReferenceBuilder) {
children.removeAll { $0 === reference }
}
func construct() -> PIF.Reference {
let children = self.children.enumerated().map { kvp -> PIF.Reference in
let (index, builder) = kvp
builder.guid = "\(guid)::REF_\(index)"
return builder.construct()
}
return PIF.Group(
guid: guid,
path: path,
sourceTree: sourceTree,
name: name,
children: children
)
}
}
class PIFBaseTargetBuilder {
public let guid: PIF.GUID
public let name: String
public fileprivate(set) var buildConfigurations: [PIFBuildConfigurationBuilder]
public fileprivate(set) var buildPhases: [PIFBuildPhaseBuilder]
public fileprivate(set) var dependencies: [PIF.TargetDependency]
public fileprivate(set) var impartedBuildSettings: PIF.BuildSettings
fileprivate init(guid: PIF.GUID, name: String) {
self.guid = guid
self.name = name
self.buildConfigurations = []
self.buildPhases = []
self.dependencies = []
self.impartedBuildSettings = PIF.BuildSettings()
}
/// Creates and adds a new empty build configuration, i.e. one that does not initially have any build settings.
/// The name must not be empty and must not be equal to the name of any existing build configuration in the
/// target.
@discardableResult
public func addBuildConfiguration(
name: String,
settings: PIF.BuildSettings = PIF.BuildSettings()
) -> PIFBuildConfigurationBuilder {
let builder = PIFBuildConfigurationBuilder(name: name, settings: settings)
buildConfigurations.append(builder)
return builder
}
func construct() throws -> PIF.BaseTarget {
throw InternalError("implement in subclass")
}
/// Adds a "headers" build phase, i.e. one that copies headers into a directory of the product, after suitable
/// processing.
@discardableResult
func addHeadersBuildPhase() -> PIFHeadersBuildPhaseBuilder {
let buildPhase = PIFHeadersBuildPhaseBuilder()
buildPhases.append(buildPhase)
return buildPhase
}
/// Adds a "sources" build phase, i.e. one that compiles sources and provides them to be linked into the
/// executable code of the product.
@discardableResult
func addSourcesBuildPhase() -> PIFSourcesBuildPhaseBuilder {
let buildPhase = PIFSourcesBuildPhaseBuilder()
buildPhases.append(buildPhase)
return buildPhase
}
/// Adds a "frameworks" build phase, i.e. one that links compiled code and libraries into the executable of the
/// product.
@discardableResult
func addFrameworksBuildPhase() -> PIFFrameworksBuildPhaseBuilder {
let buildPhase = PIFFrameworksBuildPhaseBuilder()
buildPhases.append(buildPhase)
return buildPhase
}
@discardableResult
func addResourcesBuildPhase() -> PIFResourcesBuildPhaseBuilder {
let buildPhase = PIFResourcesBuildPhaseBuilder()
buildPhases.append(buildPhase)
return buildPhase
}
/// Adds a dependency on another target. It is the caller's responsibility to avoid creating dependency cycles.
/// A dependency of one target on another ensures that the other target is built first. If `linkProduct` is
/// true, the receiver will also be configured to link against the product produced by the other target (this
/// presumes that the product type is one that can be linked against).
func addDependency(toTargetWithGUID targetGUID: String, platformFilters: [PIF.PlatformFilter], linkProduct: Bool) {
dependencies.append(.init(targetGUID: targetGUID, platformFilters: platformFilters))
if linkProduct {
let frameworksPhase = buildPhases.first { $0 is PIFFrameworksBuildPhaseBuilder }
?? addFrameworksBuildPhase()
frameworksPhase.addBuildFile(toTargetWithGUID: targetGUID, platformFilters: platformFilters)
}
}
/// Convenience function to add a file reference to the Headers build phase, after creating it if needed.
@discardableResult
public func addHeaderFile(_ fileReference: PIFFileReferenceBuilder) -> PIFBuildFileBuilder {
let headerPhase = buildPhases.first { $0 is PIFHeadersBuildPhaseBuilder } ?? addHeadersBuildPhase()
return headerPhase.addBuildFile(to: fileReference, platformFilters: [])
}
/// Convenience function to add a file reference to the Sources build phase, after creating it if needed.
@discardableResult
public func addSourceFile(_ fileReference: PIFFileReferenceBuilder) -> PIFBuildFileBuilder {
let sourcesPhase = buildPhases.first { $0 is PIFSourcesBuildPhaseBuilder } ?? addSourcesBuildPhase()
return sourcesPhase.addBuildFile(to: fileReference, platformFilters: [])
}
/// Convenience function to add a file reference to the Frameworks build phase, after creating it if needed.
@discardableResult
public func addLibrary(_ fileReference: PIFFileReferenceBuilder, platformFilters: [PIF.PlatformFilter]) -> PIFBuildFileBuilder {
let frameworksPhase = buildPhases.first { $0 is PIFFrameworksBuildPhaseBuilder } ?? addFrameworksBuildPhase()
return frameworksPhase.addBuildFile(to: fileReference, platformFilters: platformFilters)
}
@discardableResult
public func addResourceFile(_ fileReference: PIFFileReferenceBuilder) -> PIFBuildFileBuilder {
let resourcesPhase = buildPhases.first { $0 is PIFResourcesBuildPhaseBuilder } ?? addResourcesBuildPhase()
return resourcesPhase.addBuildFile(to: fileReference, platformFilters: [])
}
fileprivate func constructBuildConfigurations() -> [PIF.BuildConfiguration] {
buildConfigurations.map { builder -> PIF.BuildConfiguration in
builder.guid = "\(guid)::BUILDCONFIG_\(builder.name)"
return builder.construct()
}
}
fileprivate func constructBuildPhases() throws -> [PIF.BuildPhase] {
try buildPhases.enumerated().map { kvp in
let (index, builder) = kvp
builder.guid = "\(guid)::BUILDPHASE_\(index)"
return try builder.construct()
}
}
}
final class PIFAggregateTargetBuilder: PIFBaseTargetBuilder {
override func construct() throws -> PIF.BaseTarget {
return PIF.AggregateTarget(
guid: guid,
name: name,
buildConfigurations: constructBuildConfigurations(),
buildPhases: try self.constructBuildPhases(),
dependencies: dependencies,
impartedBuildSettings: impartedBuildSettings
)
}
}
final class PIFTargetBuilder: PIFBaseTargetBuilder {
let productType: PIF.Target.ProductType
let productName: String
var productReference: PIF.FileReference? = nil
public init(guid: PIF.GUID, name: String, productType: PIF.Target.ProductType, productName: String) {
self.productType = productType
self.productName = productName
super.init(guid: guid, name: name)
}
override func construct() throws -> PIF.BaseTarget {
return PIF.Target(
guid: guid,
name: name,
productType: productType,
productName: productName,
buildConfigurations: constructBuildConfigurations(),
buildPhases: try self.constructBuildPhases(),
dependencies: dependencies,
impartedBuildSettings: impartedBuildSettings
)
}
}
class PIFBuildPhaseBuilder {
public private(set) var buildFiles: [PIFBuildFileBuilder]
@DelayedImmutable
var guid: PIF.GUID
fileprivate init() {
buildFiles = []
}
/// Adds a new build file builder that refers to a file reference.
/// - Parameters:
/// - file: The builder for the file reference.
@discardableResult
func addBuildFile(to file: PIFFileReferenceBuilder, platformFilters: [PIF.PlatformFilter]) -> PIFBuildFileBuilder {
let builder = PIFBuildFileBuilder(file: file, platformFilters: platformFilters)
buildFiles.append(builder)
return builder
}
/// Adds a new build file builder that refers to a target GUID.
/// - Parameters:
/// - targetGUID: The GIUD referencing the target.
@discardableResult
func addBuildFile(toTargetWithGUID targetGUID: PIF.GUID, platformFilters: [PIF.PlatformFilter]) -> PIFBuildFileBuilder {
let builder = PIFBuildFileBuilder(targetGUID: targetGUID, platformFilters: platformFilters)
buildFiles.append(builder)
return builder
}
func construct() throws -> PIF.BuildPhase {
throw InternalError("implement in subclass")
}
fileprivate func constructBuildFiles() -> [PIF.BuildFile] {
return buildFiles.enumerated().map { kvp -> PIF.BuildFile in
let (index, builder) = kvp
builder.guid = "\(guid)::\(index)"
return builder.construct()
}
}
}
final class PIFHeadersBuildPhaseBuilder: PIFBuildPhaseBuilder {
override func construct() -> PIF.BuildPhase {
PIF.HeadersBuildPhase(guid: guid, buildFiles: constructBuildFiles())
}
}
final class PIFSourcesBuildPhaseBuilder: PIFBuildPhaseBuilder {
override func construct() -> PIF.BuildPhase {
PIF.SourcesBuildPhase(guid: guid, buildFiles: constructBuildFiles())
}
}
final class PIFFrameworksBuildPhaseBuilder: PIFBuildPhaseBuilder {
override func construct() -> PIF.BuildPhase {
PIF.FrameworksBuildPhase(guid: guid, buildFiles: constructBuildFiles())
}
}
final class PIFResourcesBuildPhaseBuilder: PIFBuildPhaseBuilder {
override func construct() -> PIF.BuildPhase {
PIF.ResourcesBuildPhase(guid: guid, buildFiles: constructBuildFiles())
}
}
final class PIFBuildFileBuilder {
private enum Reference {
case file(builder: PIFFileReferenceBuilder)
case target(guid: PIF.GUID)
var pifReference: PIF.BuildFile.Reference {
switch self {
case .file(let builder):
return .file(guid: builder.guid)
case .target(let guid):
return .target(guid: guid)
}
}
}
private let reference: Reference
@DelayedImmutable
var guid: PIF.GUID
let platformFilters: [PIF.PlatformFilter]
fileprivate init(file: PIFFileReferenceBuilder, platformFilters: [PIF.PlatformFilter]) {
reference = .file(builder: file)
self.platformFilters = platformFilters
}
fileprivate init(targetGUID: PIF.GUID, platformFilters: [PIF.PlatformFilter]) {
reference = .target(guid: targetGUID)
self.platformFilters = platformFilters
}
func construct() -> PIF.BuildFile {
return PIF.BuildFile(guid: guid, reference: reference.pifReference, platformFilters: platformFilters)
}
}
final class PIFBuildConfigurationBuilder {
let name: String
let settings: PIF.BuildSettings
@DelayedImmutable
var guid: PIF.GUID
public init(name: String, settings: PIF.BuildSettings) {
precondition(!name.isEmpty)
self.name = name
self.settings = settings
}
func construct() -> PIF.BuildConfiguration {
PIF.BuildConfiguration(guid: guid, name: name, buildSettings: settings)
}
}
// Helper functions to consistently generate a PIF target identifier string for a product/target/resource bundle in a
// package. This format helps make sure that there is no collision with any other PIF targets, and in particular that a
// PIF target and a PIF product can have the same name (as they often do).
extension ResolvedPackage {
var pifProjectGUID: PIF.GUID { "PACKAGE:\(manifest.packageLocation)" }
}
extension ResolvedProduct {
var pifTargetGUID: PIF.GUID { "PACKAGE-PRODUCT:\(name)" }
var mainTarget: ResolvedTarget {
targets.first { $0.type == underlyingProduct.type.targetType }!
}
/// Returns the recursive dependencies, limited to the target's package, which satisfy the input build environment,
/// based on their conditions and in a stable order.
/// - Parameters:
/// - environment: The build environment to use to filter dependencies on.
public func recursivePackageDependencies() -> [ResolvedTarget.Dependency] {
let initialDependencies = targets.map { ResolvedTarget.Dependency.target($0, conditions: []) }
return try! topologicalSort(initialDependencies) { dependency in
return dependency.packageDependencies
}.sorted()
}
}
extension ResolvedTarget {
var pifTargetGUID: PIF.GUID { "PACKAGE-TARGET:\(name)" }
var pifResourceTargetGUID: PIF.GUID { "PACKAGE-RESOURCE:\(name)" }
}
extension Array where Element == ResolvedTarget.Dependency {
/// Sorts to get products first, sorted by name, followed by targets, sorted by name.
func sorted() -> [ResolvedTarget.Dependency] {
sorted { lhsDependency, rhsDependency in
switch (lhsDependency, rhsDependency) {
case (.product, .target):
return true
case (.target, .product):
return false
case (.product(let lhsProduct, _), .product(let rhsProduct, _)):
return lhsProduct.name < rhsProduct.name
case (.target(let lhsTarget, _), .target(let rhsTarget, _)):
return lhsTarget.name < rhsTarget.name
}
}
}
}
extension Target {
func deploymentTarget(for platform: PackageModel.Platform) -> String? {
if let supportedPlatform = getSupportedPlatform(for: platform) {
return supportedPlatform.version.versionString
} else if platform == .macCatalyst {
// If there is no deployment target specified for Mac Catalyst, fall back to the iOS deployment target.
return deploymentTarget(for: .iOS)
} else if platform.oldestSupportedVersion != .unknown {
return platform.oldestSupportedVersion.versionString
} else {
return nil
}
}
var isCxx: Bool {
(self as? ClangTarget)?.isCXX ?? false
}
var usesUnsafeFlags: Bool {
Set(buildSettings.assignments.keys).contains(where: BuildSettings.Declaration.unsafeSettings.contains)
}
}
extension ProductType {
var targetType: Target.Kind {
switch self {
case .executable:
return .executable
case .snippet:
return .snippet
case .test:
return .test
case .library:
return .library
case .plugin:
return .plugin
}
}
}
private struct PIFBuildSettingAssignment {
/// The assignment value.
let value: [String]
/// The configurations this assignment applies to.
let configurations: [BuildConfiguration]
/// The platforms this assignment is restrained to, or nil to apply to all platforms.
let platforms: [PIF.BuildSettings.Platform]?
}
private extension BuildSettings.AssignmentTable {
var pifAssignments: [PIF.BuildSettings.MultipleValueSetting: [PIFBuildSettingAssignment]] {
var pifAssignments: [PIF.BuildSettings.MultipleValueSetting: [PIFBuildSettingAssignment]] = [:]
for (declaration, assignments) in self.assignments {
for assignment in assignments {
let setting: PIF.BuildSettings.MultipleValueSetting
let value: [String]
switch declaration {
case .LINK_LIBRARIES:
setting = .OTHER_LDFLAGS
value = assignment.value.map { "-l\($0)" }
case .LINK_FRAMEWORKS:
setting = .OTHER_LDFLAGS
value = assignment.value.flatMap { ["-framework", $0] }
default:
guard let parsedSetting = PIF.BuildSettings.MultipleValueSetting(rawValue: declaration.name) else {
continue
}
setting = parsedSetting
value = assignment.value
}
let pifAssignment = PIFBuildSettingAssignment(
value: value,
configurations: assignment.configurations,
platforms: assignment.pifPlatforms)
pifAssignments[setting, default: []].append(pifAssignment)
}
}
return pifAssignments
}
}
private extension BuildSettings.Assignment {
var configurations: [BuildConfiguration] {
if let configurationCondition = conditions.lazy.compactMap({ $0 as? ConfigurationCondition }).first {
return [configurationCondition.configuration]
} else {
return BuildConfiguration.allCases
}
}
var pifPlatforms: [PIF.BuildSettings.Platform]? {
if let platformsCondition = conditions.lazy.compactMap({ $0 as? PlatformsCondition }).first {
return platformsCondition.platforms.compactMap { PIF.BuildSettings.Platform(rawValue: $0.name) }
} else {
return nil
}
}
}
@propertyWrapper
public struct DelayedImmutable<Value> {
private var _value: Value? = nil
public init() {
}
public var wrappedValue: Value {
get {
guard let value = _value else {
fatalError("property accessed before being initialized")
}
return value
}
set {
if _value != nil {
fatalError("property initialized twice")
}
_value = newValue
}
}
}
extension Array where Element == PackageConditionProtocol {
func toPlatformFilters() -> [PIF.PlatformFilter] {
var result: [PIF.PlatformFilter] = []
let platformConditions = self.compactMap{ $0 as? PlatformsCondition }.flatMap{ $0.platforms }
for condition in platformConditions {
switch condition {
case .macOS:
result += PIF.PlatformFilter.macOSFilters
case .macCatalyst:
result += PIF.PlatformFilter.macCatalystFilters
case .iOS:
result += PIF.PlatformFilter.iOSFilters
case .tvOS:
result += PIF.PlatformFilter.tvOSFilters
case .watchOS:
result += PIF.PlatformFilter.watchOSFilters
case .linux:
result += PIF.PlatformFilter.linuxFilters
case .android:
result += PIF.PlatformFilter.androidFilters
case .windows:
result += PIF.PlatformFilter.windowsFilters
case .driverKit:
result += PIF.PlatformFilter.driverKitFilters
default:
assertionFailure("Unhandled platform condition: \(condition)")
break
}
}
return result
}
}
extension PIF.PlatformFilter {
/// macOS platform filters.
public static let macOSFilters: [PIF.PlatformFilter] = [.init(platform: "macos")]
/// Mac Catalyst platform filters.
public static let macCatalystFilters: [PIF.PlatformFilter] = [
.init(platform: "ios", environment: "maccatalyst")
]
/// iOS platform filters.
public static let iOSFilters: [PIF.PlatformFilter] = [
.init(platform: "ios"),
.init(platform: "ios", environment: "simulator")
]
/// tvOS platform filters.
public static let tvOSFilters: [PIF.PlatformFilter] = [
.init(platform: "tvos"),
.init(platform: "tvos", environment: "simulator")
]
/// watchOS platform filters.
public static let watchOSFilters: [PIF.PlatformFilter] = [
.init(platform: "watchos"),
.init(platform: "watchos", environment: "simulator")
]
/// DriverKit platform filters.
public static let driverKitFilters: [PIF.PlatformFilter] = [
.init(platform: "driverkit"),
]
/// Windows platform filters.
public static let windowsFilters: [PIF.PlatformFilter] = [
.init(platform: "windows", environment: "msvc"),
.init(platform: "windows", environment: "gnu"),
]
/// Andriod platform filters.
public static let androidFilters: [PIF.PlatformFilter] = [
.init(platform: "linux", environment: "android"),
.init(platform: "linux", environment: "androideabi"),
]
/// Common Linux platform filters.
public static let linuxFilters: [PIF.PlatformFilter] = {
["", "eabi", "gnu", "gnueabi", "gnueabihf"].map {
.init(platform: "linux", environment: $0)
}
}()
}
private extension PIF.BuildSettings.Platform {
static func from(platform: PackageModel.Platform) -> PIF.BuildSettings.Platform? {
switch platform {
case .iOS: return .iOS
case .linux: return .linux
case .macCatalyst: return .macCatalyst
case .macOS: return .macOS
case .tvOS: return .tvOS
case .watchOS: return .watchOS
case .driverKit: return .driverKit
default: return nil
}
}
}
| 40.482099 | 157 | 0.645751 |
c1d197e1d9d429f9f51a7bb22c21a59689276e4f | 952 | //
// ViewVerticalMover.swift
// Velar
//
// Created by Jonathan Samudio on 2/8/17.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
import UIKit
final class ViewVerticalMover: VerticalMovable {
// MARK: - Private Properties
private var view: UIView
private var centerYConstraint: NSLayoutConstraint
private var constraintAnimator: ConstraintAnimatable
// MARK: - Initialization
init(view: UIView, centerYConstraint: NSLayoutConstraint, constraintAnimator: ConstraintAnimatable) {
self.view = view
self.centerYConstraint = centerYConstraint
self.constraintAnimator = constraintAnimator
}
// MARK: - Public Functions
func move(centerYOffset: CGFloat, animate: Bool, completion: (()->())?) {
centerYConstraint.constant = centerYOffset
constraintAnimator.updateConstraints(view: view, animate: animate, completion: completion)
}
}
| 25.72973 | 105 | 0.704832 |
222e0468053ce67fefed51dd88a3bc958f14d0fd | 3,761 | //
// String.swift
// Gloden Palace Casino
//
// Created by albutt on 2018/11/30.
// Copyright © 2018 海创中盈. All rights reserved.
//
import Foundation
extension String {
var base64Encode: String? {
let data = self.data(using: .utf8)
if let base64Str = data?.base64EncodedString(options: .lineLength64Characters) {
return base64Str
} else {
return nil
}
}
var base64Decode: String? {
if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters),
let decodeStr = String(data: data, encoding: .utf8) {
return decodeStr
} else {
return nil
}
}
}
extension String {
/// 金额
var amount: String {
let pattern = "^[\\+\\-]?\\d+\\.?\\d{0,2}" // 保留两位小数
if let result = self.regexMatches(pattern: pattern).first {
return result
}
return ""
}
/// 纯数字
var pureNumber: String {
let pattern = "[^0-9]"
return self.regularReplace(pattern: pattern, with: "")
}
/// 纯字母
var pureLetter: String {
let pattern = "[^A-Za-z]"
return self.regularReplace(pattern: pattern, with: "")
}
/// 正则替换
func regularReplace(pattern: String, with string: String, options: NSRegularExpression.Options = []) -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: options)
return regex.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, self.count), withTemplate: string)
} catch {
return self
}
}
/// 正则提取
func regexMatches(pattern:String) -> [String] {
let regex = try! NSRegularExpression(pattern: pattern, options:[])
let matches = regex.matches(in: self, options: [], range: NSRange(self.startIndex...,in: self))
//解析出子串
return matches.map { m in
let range = self.range(from: m.range)!
return String(self[range])
}
}
private func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location,
limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length,
limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
}
extension String {
/// URL QueryItems
var urlQueryItems: [URLQueryItem]? {
return URLComponents(string: self)?.queryItems
}
var urlQueryDictionary: [String: String]? {
guard let queryItems = URLComponents(string: self)?.queryItems else {
return nil
}
var dict = [String:String]()
for qi in queryItems {
let key = qi.name
let value = qi.value
dict[key] = value
}
return dict
}
}
extension String {
var htmlAttributed: NSAttributedString? {
do {
guard let data = data(using: String.Encoding.utf8) else {
return nil
}
return try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("[ERROR]: \(error)")
return nil
}
}
}
| 28.709924 | 129 | 0.534964 |
4a4fc9c45c83bde0e48839b7dbad5a8e7dd0f0ed | 33,169 | //
// ParameterEncoderTests.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import XCTest
final class JSONParameterEncoderTests: BaseTestCase {
func testThatDataIsProperlyEncodedAndProperContentTypeIsSet() throws {
// Given
let encoder = JSONParameterEncoder()
let request = URLRequest.makeHTTPBinRequest()
// When
let newRequest = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "application/json")
XCTAssertEqual(newRequest.httpBody?.asString, "{\"property\":\"property\"}")
}
func testThatDataIsProperlyEncodedButContentTypeIsNotSetIfRequestAlreadyHasAContentType() throws {
// Given
let encoder = JSONParameterEncoder()
var request = URLRequest.makeHTTPBinRequest()
request.headers.update(.contentType("type"))
// When
let newRequest = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "type")
XCTAssertEqual(newRequest.httpBody?.asString, "{\"property\":\"property\"}")
}
func testThatJSONEncoderCanBeCustomized() throws {
// Given
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
let encoder = JSONParameterEncoder(encoder: jsonEncoder)
let request = URLRequest.makeHTTPBinRequest()
// When
let newRequest = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
let expected = """
{
"property" : "property"
}
"""
XCTAssertEqual(newRequest.httpBody?.asString, expected)
}
func testThatJSONEncoderDefaultWorks() throws {
// Given
let encoder = JSONParameterEncoder.default
let request = URLRequest.makeHTTPBinRequest()
// When
let encoded = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
let expected = """
{"property":"property"}
"""
XCTAssertEqual(encoded.httpBody?.asString, expected)
}
func testThatJSONEncoderPrettyPrintedPrintsPretty() throws {
// Given
let encoder = JSONParameterEncoder.prettyPrinted
let request = URLRequest.makeHTTPBinRequest()
// When
let encoded = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
let expected = """
{
"property" : "property"
}
"""
XCTAssertEqual(encoded.httpBody?.asString, expected)
}
}
final class SortedKeysJSONParameterEncoderTests: BaseTestCase {
func testTestJSONEncoderSortedKeysHasSortedKeys() throws {
guard #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) else { return }
// Given
let encoder = JSONParameterEncoder.sortedKeys
let request = URLRequest.makeHTTPBinRequest()
// When
let encoded = try encoder.encode(["z": "z", "a": "a", "p": "p"], into: request)
// Then
let expected = """
{"a":"a","p":"p","z":"z"}
"""
XCTAssertEqual(encoded.httpBody?.asString, expected)
}
}
final class URLEncodedFormParameterEncoderTests: BaseTestCase {
func testThatQueryIsBodyEncodedAndProperContentTypeIsSetForPOSTRequest() throws {
// Given
let encoder = URLEncodedFormParameterEncoder()
let request = URLRequest.makeHTTPBinRequest(method: .post)
// When
let newRequest = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "application/x-www-form-urlencoded; charset=utf-8")
XCTAssertEqual(newRequest.httpBody?.asString, "property=property")
}
func testThatQueryIsBodyEncodedButContentTypeIsNotSetWhenRequestAlreadyHasContentType() throws {
// Given
let encoder = URLEncodedFormParameterEncoder()
var request = URLRequest.makeHTTPBinRequest(method: .post)
request.headers.update(.contentType("type"))
// When
let newRequest = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "type")
XCTAssertEqual(newRequest.httpBody?.asString, "property=property")
}
func testThatEncoderCanBeCustomized() throws {
// Given
let urlEncoder = URLEncodedFormEncoder(boolEncoding: .literal)
let encoder = URLEncodedFormParameterEncoder(encoder: urlEncoder)
let request = URLRequest.makeHTTPBinRequest()
// When
let newRequest = try encoder.encode(["bool": true], into: request)
// Then
let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false)
XCTAssertEqual(components?.percentEncodedQuery, "bool=true")
}
func testThatQueryIsInURLWhenDestinationIsURLAndMethodIsPOST() throws {
// Given
let encoder = URLEncodedFormParameterEncoder(destination: .queryString)
let request = URLRequest.makeHTTPBinRequest(method: .post)
// When
let newRequest = try encoder.encode(HTTPBinParameters.default, into: request)
// Then
let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false)
XCTAssertEqual(components?.percentEncodedQuery, "property=property")
}
func testThatQueryIsNilWhenEncodableResultsInAnEmptyString() throws {
// Given
let encoder = URLEncodedFormParameterEncoder(destination: .queryString)
let request = URLRequest.makeHTTPBinRequest()
// When
let newRequest = try encoder.encode([String: String](), into: request)
// Then
let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false)
XCTAssertNil(components?.percentEncodedQuery)
}
}
final class URLEncodedFormEncoderTests: BaseTestCase {
func testEncoderThrowsErrorWhenAttemptingToEncodeNilInKeyedContainer() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = FailingOptionalStruct(testedContainer: .keyed)
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
}
func testEncoderThrowsErrorWhenAttemptingToEncodeNilInUnkeyedContainer() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = FailingOptionalStruct(testedContainer: .unkeyed)
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
}
func testEncoderCanEncodeDictionary() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["a": "a"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=a")
}
func testEncoderCanEncodeDecimal() {
// Given
let encoder = URLEncodedFormEncoder()
let decimal: Decimal = 1.0
let parameters = ["a": decimal]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeDecimalWithHighPrecision() {
// Given
let encoder = URLEncodedFormEncoder()
let decimal: Decimal = 1.123456
let parameters = ["a": decimal]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1.123456")
}
func testEncoderCanEncodeDouble() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["a": 1.0]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1.0")
}
func testEncoderCanEncodeFloat() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Float] = ["a": 1.0]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1.0")
}
func testEncoderCanEncodeInt8() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int8] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeInt16() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int16] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeInt32() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int32] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeInt64() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int64] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt8() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt8] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt16() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt16] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt32() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt32] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt64() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt64] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testThatNestedDictionariesHaveBracketedKeys() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["a": ["b": "b"]]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a%5Bb%5D=b")
}
func testThatEncodableStructCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = EncodableStruct()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "five%5Ba%5D=a&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&one=one&seven%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&three=1&two=2"
XCTAssertEqual(result.success, expected)
}
func testThatManuallyEncodableStructCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ManuallyEncodableStruct()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "root%5B%5D%5B%5D%5B%5D=1&root%5B%5D%5B%5D%5B%5D=2&root%5B%5D%5B%5D%5B%5D=3&root%5B%5D%5B%5D=1&root%5B%5D%5B%5D=2&root%5B%5D%5B%5D=3&root%5B%5D%5Ba%5D%5Bstring%5D=string"
XCTAssertEqual(result.success, expected)
}
func testThatEncodableClassWithNoInheritanceCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = EncodableSuperclass()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "one=one&three=1&two=2")
}
func testThatEncodableSubclassCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = EncodableSubclass()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&one=one&three=1&two=2"
XCTAssertEqual(result.success, expected)
}
func testThatEncodableSubclassCanBeEncodedInImplementationOrderWhenAlphabetizeKeysIsFalse() {
// Given
let encoder = URLEncodedFormEncoder(alphabetizeKeyValuePairs: false)
let parameters = EncodableStruct()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "one=one&two=2&three=1&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&five%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&seven%5Ba%5D=a"
XCTAssertEqual(result.success, expected)
}
func testThatManuallyEncodableSubclassCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ManuallyEncodableSubclass()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfive%5D=2&four%5Bfour%5D=one"
XCTAssertEqual(result.success, expected)
}
func testThatARootArrayCannotBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = [1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertFalse(result.isSuccess)
}
func testThatARootValueCannotBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = "string"
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertFalse(result.isSuccess)
}
func testThatOptionalValuesCannotBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: String?] = ["string": nil]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertFalse(result.isSuccess)
}
func testThatArraysCanBeEncodedWithoutBrackets() {
// Given
let encoder = URLEncodedFormEncoder(arrayEncoding: .noBrackets)
let parameters = ["array": [1, 2]]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "array=1&array=2")
}
func testThatBoolsCanBeLiteralEncoded() {
// Given
let encoder = URLEncodedFormEncoder(boolEncoding: .literal)
let parameters = ["bool": true]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "bool=true")
}
func testThatDataCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["data": Data("data".utf8)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "data=ZGF0YQ%3D%3D")
}
func testThatCustomDataEncodingFailsWhenErrorIsThrown() {
// Given
struct DataEncodingError: Error {}
let encoder = URLEncodedFormEncoder(dataEncoding: .custom { _ in throw DataEncodingError() })
let parameters = ["data": Data("data".utf8)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
XCTAssertTrue(result.failure is DataEncodingError)
}
func testThatDatesCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .deferredToDate)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=123.456")
}
func testThatDatesCanBeEncodedAsSecondsSince1970() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .secondsSince1970)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=978307323.456")
}
func testThatDatesCanBeEncodedAsMillisecondsSince1970() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .millisecondsSince1970)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=978307323456.0")
}
func testThatDatesCanBeEncodedAsISO8601Formatted() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .iso8601)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=2001-01-01T00%3A02%3A03Z")
}
func testThatDatesCanBeEncodedAsFormatted() {
// Given
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let encoder = URLEncodedFormEncoder(dateEncoding: .formatted(dateFormatter))
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=2001-01-01%2000%3A02%3A03.4560")
}
func testThatDatesCanBeEncodedAsCustomFormatted() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .custom { "\($0.timeIntervalSinceReferenceDate)" })
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=123.456")
}
func testEncoderThrowsErrorWhenCustomDateEncodingFails() {
// Given
struct DateEncodingError: Error {}
let encoder = URLEncodedFormEncoder(dateEncoding: .custom { _ in throw DateEncodingError() })
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
XCTAssertTrue(result.failure is DateEncodingError)
}
func testThatKeysCanBeEncodedIntoSnakeCase() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .convertToSnakeCase)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "one_two_three=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoKebabCase() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .convertToKebabCase)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "one-two-three=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoACapitalizedString() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .capitalized)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "OneTwoThree=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoALowercasedString() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .lowercased)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "onetwothree=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoAnUppercasedString() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .uppercased)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "ONETWOTHREE=oneTwoThree")
}
func testThatKeysCanBeCustomEncoded() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .custom { _ in "A" })
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "A=oneTwoThree")
}
func testThatSpacesCanBeEncodedAsPluses() {
// Given
let encoder = URLEncodedFormEncoder(spaceEncoding: .plusReplaced)
let parameters = ["spaces": "replace with spaces"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "spaces=replace+with+spaces")
}
func testThatEscapedCharactersCanBeCustomized() {
// Given
var allowed = CharacterSet.afURLQueryAllowed
allowed.remove(charactersIn: "?/")
let encoder = URLEncodedFormEncoder(allowedCharacters: allowed)
let parameters = ["allowed": "?/"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "allowed=%3F%2F")
}
func testThatUnreservedCharactersAreNotPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["lowercase": "abcdefghijklmnopqrstuvwxyz",
"numbers": "0123456789",
"uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "lowercase=abcdefghijklmnopqrstuvwxyz&numbers=0123456789&uppercase=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
XCTAssertEqual(result.success, expected)
}
func testThatReservedCharactersArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let generalDelimiters = ":#[]@"
let subDelimiters = "!$&'()*+,;="
let parameters = ["reserved": "\(generalDelimiters)\(subDelimiters)"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D")
}
func testThatIllegalASCIICharactersArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["illegal": " \"#%<>[]\\^`{}|"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "illegal=%20%22%23%25%3C%3E%5B%5D%5C%5E%60%7B%7D%7C")
}
func testThatAmpersandsInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "foo%26bar=baz%26qux&foobar=bazqux")
}
func testThatQuestionMarksInKeysAndValuesAreNotPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["?foo?": "?bar?"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "?foo?=?bar?")
}
func testThatSlashesInKeysAndValuesAreNotPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["foo": "/bar/baz/qux"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "foo=/bar/baz/qux")
}
func testThatSpacesInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = [" foo ": " bar "]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "%20foo%20=%20bar%20")
}
func testThatPlusesInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["+foo+": "+bar+"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "%2Bfoo%2B=%2Bbar%2B")
}
func testThatPercentsInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["percent%": "%25"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "percent%25=%2525")
}
func testThatNonLatinCharactersArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["french": "français",
"japanese": "日本語",
"arabic": "العربية",
"emoji": "😃"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expectedParameterValues = ["arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9",
"emoji=%F0%9F%98%83",
"french=fran%C3%A7ais",
"japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E"].joined(separator: "&")
XCTAssertEqual(result.success, expectedParameterValues)
}
func testStringWithThousandsOfChineseCharactersIsPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let repeatedCount = 2000
let parameters = ["chinese": String(repeating: "一二三四五六七八九十", count: repeatedCount)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let escaped = String(repeating: "%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%E5%8D%81",
count: repeatedCount)
let expected = "chinese=\(escaped)"
XCTAssertEqual(result.success, expected)
}
}
private struct EncodableStruct: Encodable {
let one = "one"
let two = 2
let three = true
let four = [1, 2, 3]
let five = ["a": "a"]
let six = ["a": ["b": "b"]]
let seven = NestedEncodableStruct()
}
private struct NestedEncodableStruct: Encodable {
let a = "a"
}
private class EncodableSuperclass: Encodable {
let one = "one"
let two = 2
let three = true
}
private final class EncodableSubclass: EncodableSuperclass {
let four = [1, 2, 3]
let five = ["a": "a", "b": "b"]
private enum CodingKeys: String, CodingKey {
case four, five
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(four, forKey: .four)
try container.encode(five, forKey: .five)
}
}
private final class ManuallyEncodableSubclass: EncodableSuperclass {
let four = [1, 2, 3]
let five = ["a": "a", "b": "b"]
private enum CodingKeys: String, CodingKey {
case four, five
}
override func encode(to encoder: Encoder) throws {
var keyedContainer = encoder.container(keyedBy: CodingKeys.self)
try keyedContainer.encode(four, forKey: .four)
try keyedContainer.encode(five, forKey: .five)
let superEncoder = keyedContainer.superEncoder()
var superContainer = superEncoder.container(keyedBy: CodingKeys.self)
try superContainer.encode(one, forKey: .four)
let keyedSuperEncoder = keyedContainer.superEncoder(forKey: .four)
var superKeyedContainer = keyedSuperEncoder.container(keyedBy: CodingKeys.self)
try superKeyedContainer.encode(two, forKey: .five)
var unkeyedContainer = keyedContainer.nestedUnkeyedContainer(forKey: .four)
let unkeyedSuperEncoder = unkeyedContainer.superEncoder()
var keyedUnkeyedSuperContainer = unkeyedSuperEncoder.container(keyedBy: CodingKeys.self)
try keyedUnkeyedSuperContainer.encode(one, forKey: .four)
}
}
private struct ManuallyEncodableStruct: Encodable {
let a = ["string": "string"]
let b = [1, 2, 3]
private enum RootKey: String, CodingKey {
case root
}
private enum TypeKeys: String, CodingKey {
case a, b
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RootKey.self)
var nestedKeyedContainer = container.nestedContainer(keyedBy: TypeKeys.self, forKey: .root)
try nestedKeyedContainer.encode(a, forKey: .a)
var nestedUnkeyedContainer = container.nestedUnkeyedContainer(forKey: .root)
try nestedUnkeyedContainer.encode(b)
var nestedUnkeyedKeyedContainer = nestedUnkeyedContainer.nestedContainer(keyedBy: TypeKeys.self)
try nestedUnkeyedKeyedContainer.encode(a, forKey: .a)
var nestedUnkeyedUnkeyedContainer = nestedUnkeyedContainer.nestedUnkeyedContainer()
try nestedUnkeyedUnkeyedContainer.encode(b)
}
}
private struct FailingOptionalStruct: Encodable {
enum TestedContainer {
case keyed, unkeyed
}
enum CodingKeys: String, CodingKey { case a }
let testedContainer: TestedContainer
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch testedContainer {
case .keyed:
var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .a)
try nested.encodeNil(forKey: .a)
case .unkeyed:
var nested = container.nestedUnkeyedContainer(forKey: .a)
try nested.encodeNil()
}
}
}
| 32.486778 | 193 | 0.633031 |
01c6118a9740bb26e32b9a295bf4bd10bcae7015 | 2,360 | //
// EpisodesAPITests.swift
// MortyTests
//
// Created by George Kye on 2019-07-03.
// Copyright © 2019 georgekye. All rights reserved.
//
import XCTest
@testable import Morty
class EpisodesAPITests: XCTestCase {
let apiService: RickMortyAPIServiceType = RickMortyAPINetworkService()
}
extension EpisodesAPITests {
func testFetchEpisodes() {
let expectation = XCTestExpectation(description: "Test episodes request")
// When
apiService.fetchEpisodes {
// Then
do {
let value = try $0.get()
XCTAssertNotNil(value.info)
XCTAssertFalse(value.info.count == 0)
XCTAssertFalse(value.episodes.isEmpty)
XCTAssertTrue(value.info.pages >= 1)
XCTAssertNotNil(value.episodes)
XCTAssertNotNil(value.episodes.first?.name)
XCTAssertNotNil(value.episodes.first?.airDate)
XCTAssertNotNil(value.episodes.first?.characters)
XCTAssertNotNil(value.episodes.first?.episode)
XCTAssertNotNil(value.episodes.first?.id)
XCTAssertNotNil(value.episodes.first?.created)
// Given
guard let foundEpisode = value.episodes.randomElement() else {
return XCTFail("Failed to find episode")
}
// When
self.apiService.fetch(episode: foundEpisode.id) {
defer {
expectation.fulfill()
}
do {
let episode = try $0.get()
XCTAssertTrue(episode.id == foundEpisode.id)
XCTAssertTrue(episode.name == foundEpisode.name)
XCTAssertTrue(episode.airDate == foundEpisode.airDate)
XCTAssertTrue(episode.characters == foundEpisode.characters)
} catch {
XCTFail(error.localizedDescription)
}
}
} catch {
XCTFail(error.localizedDescription)
}
}
wait(for: [expectation], timeout: 10.0)
}
}
| 32.328767 | 84 | 0.510169 |
d97cf898c76b2a34aa310ee0c746104df9563190 | 1,372 | //
// MainWeatherViewController.swift
//
// Created by Igor Nakonetsnoi on 22/03/2019.
// Copyright © 2019 Igor Nakonetsnoi. All rights reserved.
import UIKit
final class MainWeatherViewController: UIViewController {
// MARK: - Properties
private let configurator = MainWeatherConfiguratorImplementation()
var output: MainWeatherViewOutput!
var router: MainWeatherRouter!
// MARK: - IBOutlets
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var feelTemperatureLabel: UILabel!
@IBOutlet weak var cloudCoverLabel: UILabel!
@IBOutlet weak var conditionLabel: UILabel!
}
// MARK: - View lifecycle
extension MainWeatherViewController {
override func awakeFromNib() {
super.awakeFromNib()
configurator.configureWith(viewController: self)
}
override func viewDidLoad() {
super.viewDidLoad()
output.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
router.prepare(for: segue, sender: sender)
}
}
// MARK: - MainWeatherViewInput
extension MainWeatherViewController: MainWeatherViewInput {
func presentWeather(viewModel: CurrentWeather.ViewModel) {
temperatureLabel.text = viewModel.temperature
feelTemperatureLabel.text = viewModel.feelTemperature
cloudCoverLabel.text = viewModel.cloudCover
conditionLabel.text = viewModel.condition
}
}
| 28 | 71 | 0.752915 |
f8a3f64e2ee8c89cc3eeb9abfa58242b65062401 | 1,821 | //
// Capitalization.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public struct Capitalization: Codable, JSONEncodable, Hashable {
public var smallCamel: String?
public var capitalCamel: String?
public var smallSnake: String?
public var capitalSnake: String?
public var sCAETHFlowPoints: String?
/** Name of the pet */
public var ATT_NAME: String?
public init(smallCamel: String? = nil, capitalCamel: String? = nil, smallSnake: String? = nil, capitalSnake: String? = nil, sCAETHFlowPoints: String? = nil, ATT_NAME: String? = nil) {
self.smallCamel = smallCamel
self.capitalCamel = capitalCamel
self.smallSnake = smallSnake
self.capitalSnake = capitalSnake
self.sCAETHFlowPoints = sCAETHFlowPoints
self.ATT_NAME = ATT_NAME
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case smallCamel
case capitalCamel = "CapitalCamel"
case smallSnake = "small_Snake"
case capitalSnake = "Capital_Snake"
case sCAETHFlowPoints = "SCA_ETH_Flow_Points"
case ATT_NAME
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(smallCamel, forKey: .smallCamel)
try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel)
try container.encodeIfPresent(smallSnake, forKey: .smallSnake)
try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake)
try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints)
try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME)
}
}
| 33.722222 | 187 | 0.705107 |
4a8202e2f2d201353d2d873cdd5b1f4c83f79c18 | 567 | //
// RegionDataHeaderView.swift
// covid-19-graph
//
import UIKit
final class RegionDataHeaderView: UITableViewHeaderFooterView {
@IBOutlet private weak var primaryText: UILabel!
@IBOutlet private weak var secondaryText: UILabel!
@IBOutlet weak var tertiaryText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
primaryText.text = R.string.localizable.totalPositivesTitle()
secondaryText.text = R.string.localizable.currentPositivesTitle()
tertiaryText.text = R.string.localizable.pcrTitle()
}
}
| 27 | 73 | 0.726631 |
e2505cdc8f9a15915427009ecffcaa25dd6a08fd | 5,666 | // Copyright (C) 2019 Parrot Drones SAS
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the Parrot Company nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
import Foundation
/// Device state information.
@objcMembers
@objc(GSDeviceState)
public class DeviceState: NSObject {
/// Connection state.
@objc(GSDeviceConnectionState)
public enum ConnectionState: Int, CustomStringConvertible {
/// Device is not connected.
case disconnected
/// Device is connecting.
case connecting
/// Device is connected.
case connected
/// Device is disconnecting following a user request.
case disconnecting
/// Debug description.
public var description: String {
switch self {
case .disconnected: return "disconnected"
case .connecting: return "connecting"
case .connected: return "connected"
case .disconnecting: return "disconnecting"
}
}
}
/// Detail on connection state cause.
@objc(GSDeviceConnectionStateCause)
public enum ConnectionStateCause: Int, CustomStringConvertible {
/// No specific cause, valid for all states.
case none
/// Due to an explicit user request. Valid on all states.
case userRequest
/// Because the connection with the device has been lost.
/// Valid in `connecting` state when trying to reconnect to the device
/// and in `disconnected` state.
case connectionLost
/// Device refused the connection because it's already connected to a controller.
/// Only in `disconnected` state.
case refused
/// Connection failed due to a bad password.
/// Only in `disconnected` state, when connecting using a `RemoteControl` connector.
case badPassword
/// Connection has failed. Only in `disconnected` state.
case failure
/// Debug description.
public var description: String {
switch self {
case .none: return "none"
case .userRequest: return "userRequest"
case .connectionLost: return "connectionLost"
case .refused: return "refused"
case .badPassword: return "badPassword"
case .failure: return "failure"
}
}
}
/// Device connection state.
public internal(set) var connectionState = ConnectionState.disconnected
/// Device connection state reason.
public internal(set) var connectionStateCause = ConnectionStateCause.none
/// Available connectors.
public var connectors: [DeviceConnector] { return _connectors }
/// Active connector.
public var activeConnector: DeviceConnector? { return _activeConnector }
/// Whether the device can be forgotten.
public internal(set) var canBeForgotten = false
/// Whether the device can be connected.
public internal(set) var canBeConnected = false
/// Whether the device can be disconnected.
public internal(set) var canBeDisconnected = false
/// Gets duration before shutdown.
///
/// - Note: Current duration before shutdown or 0 when no shutdown is planned
public var durationBeforeShutDown: TimeInterval {
if let shutDownDate = _shutDownDate {
return -Date().timeIntervalSince(shutDownDate)
} else {
return 0
}
}
internal var _connectors = [DeviceConnectorCore]()
internal var _activeConnector: DeviceConnectorCore?
internal var _shutDownDate: Date?
/// Debug description.
override public var description: String {
return "[\(connectionState)[\(connectionStateCause)]) \(connectors.debugDescription)]"
}
}
/// Objective-C wrapper of Ref<DroneState>. Required because swift generics can't be used from Objective-C.
/// - Note: This class is for Objective-C only and must not be used in Swift.
@objcMembers
public class GSDeviceStateRef: NSObject {
let ref: Ref<DeviceState>
/// Referenced drone state.
public var value: DeviceState? {
return ref.value
}
init(ref: Ref<DeviceState>) {
self.ref = ref
}
}
| 35.63522 | 107 | 0.672079 |
90964310ed534d9e9c5c8aece69a1b0f8d817695 | 1,950 | //
// ChallengeItemViewModel.swift
// DriveKitChallengeUI
//
// Created by Amine Gahbiche on 03/05/2021.
// Copyright © 2021 DriveQuant. All rights reserved.
//
import Foundation
import DriveKitDBChallengeAccessModule
import DriveKitCommonUI
import UIKit
struct ChallengeItemViewModel {
let startDate: Date
let endDate: Date
let name: String
let image: UIImage?
let identifier: String
let finishedAndNotFilled: Bool
init(challenge: DKChallenge) {
identifier = challenge.id
startDate = challenge.startDate
endDate = challenge.endDate
name = challenge.title
if let challengeImage = UIImage(named: String(format : "%d", challenge.iconCode), in: Bundle.challengeUIBundle, compatibleWith: nil) {
image = challengeImage
} else {
image = UIImage(named: "101", in: Bundle.challengeUIBundle, compatibleWith: nil)
}
if (challenge.isRegistered == false || challenge.conditionsFilled == false) && challenge.endDate.timeIntervalSinceNow < 0 {
finishedAndNotFilled = true
} else {
finishedAndNotFilled = false
}
}
static func formatStartAndEndDates(startDate: Date,
endDate: Date,
tintColor: UIColor,
alignment: NSTextAlignment = NSTextAlignment.left) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
return NSMutableAttributedString(string: "\(startDate.format(pattern: .standardDate)) - \(endDate.format(pattern: .standardDate))",
attributes: [NSAttributedString.Key.font: DKUIFonts.primary.fonts(size: 14),
NSAttributedString.Key.foregroundColor: tintColor, NSAttributedString.Key.paragraphStyle : paragraphStyle])
}
}
| 37.5 | 142 | 0.644103 |
1167a221675a12306a7869e6bb9cdd13da48cd0c | 4,215 | //
// NavigationBar.swift
// Navigator
//
// Created by CIB on 2022/1/21.
//
import Foundation
import UIKit
open class NavigationBar: UINavigationBar {
lazy var fakeView: UIVisualEffectView = getFakeView()
lazy var shadowImageView: UIImageView = getShadowImageView()
lazy var backgroundImageView: UIImageView = getBackgroundImageView()
open override var barTintColor: UIColor? {
didSet(newValue) {
guard let lastView = fakeView.subviews.last else {
return
}
lastView.backgroundColor = newValue
checkFakeView()
}
}
open override var shadowImage: UIImage? {
didSet(newValue) {
guard (newValue != nil) else {
self.shadowImageView.backgroundColor = nil
return
}
self.shadowImageView.image = newValue
self.shadowImageView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 77.0/255)
}
}
}
// MARK: Private Methods
extension NavigationBar {
fileprivate func checkFakeView() {
UIView.setAnimationsEnabled(false)
if fakeView.superview == nil {
subviews.first?.insertSubview(fakeView, at: 0)
fakeView.frame = fakeView.superview?.bounds ?? CGRect(x: 0, y: 0, width: 0, height: 0)
}
if shadowImageView.superview == nil {
subviews.first?.insertSubview(shadowImageView, aboveSubview: fakeView)
shadowImageView.frame = CGRect(x: 0, y: shadowImageView.superview?.bounds.height ?? 0, width: shadowImageView.superview?.bounds.width ?? 0, height: 0.5)
}
if backgroundImageView.superview == nil {
subviews.first?.insertSubview(backgroundImageView, aboveSubview: fakeView)
backgroundImageView.frame = backgroundImageView.superview?.bounds ?? CGRect(x: 0, y: 0, width: 0, height: 0)
}
UIView.setAnimationsEnabled(true)
}
fileprivate func getFakeView() -> UIVisualEffectView {
super.setBackgroundImage(UIImage(), for: .top, barMetrics: .default)
let fakeView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
fakeView.isUserInteractionEnabled = false
fakeView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.subviews.first?.insertSubview(fakeView, at: 0)
return fakeView
}
fileprivate func getShadowImageView() -> UIImageView {
super.shadowImage = UIImage()
let shadowImageView = UIImageView()
shadowImageView.isUserInteractionEnabled = false
shadowImageView.contentScaleFactor = 1
self.subviews.first?.insertSubview(shadowImageView, aboveSubview: fakeView)
return shadowImageView
}
fileprivate func getBackgroundImageView() -> UIImageView {
let backgroundImageView = UIImageView()
backgroundImageView.contentScaleFactor = 1
backgroundImageView.isUserInteractionEnabled = false
backgroundImageView.contentMode = .scaleToFill
backgroundImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.subviews.first?.insertSubview(backgroundImageView, aboveSubview: fakeView)
return backgroundImageView
}
}
extension NavigationBar {
class func navibarHeight(view: UIView) -> CGFloat {
if #available(iOS 11.0, *) {
return 64 + view.safeAreaInsets.top
} else {
return 64
}
}
}
extension NavigationBar {
open override func layoutSubviews() {
super.layoutSubviews()
fakeView.frame = fakeView.superview?.bounds ?? CGRect(x: 0, y: 0, width: 0, height: 0)
shadowImageView.frame = CGRect(x: 0, y: shadowImageView.superview?.bounds.height ?? 0, width: shadowImageView.superview?.bounds.width ?? 0, height: 0.5)
backgroundImageView.frame = backgroundImageView.superview?.bounds ?? CGRect(x: 0, y: 0, width: 0, height: 0)
}
open override func setBackgroundImage(_ backgroundImage: UIImage?, for barMetrics: UIBarMetrics) {
backgroundImageView.image = backgroundImage
checkFakeView()
}
}
| 35.420168 | 164 | 0.651008 |
46e2874bc04a1d38473a36e937189417ef1a6324 | 1,700 | //
// TraktCrewMember.swift
// TraktKit
//
// Created by Maximilian Litteral on 4/13/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
/// Cast member for (show/season/episode)/people API
public struct TVCrewMember: Codable, Hashable {
public let jobs: [String]
@available(*, deprecated, renamed: "jobs")
public let job: String
public let episodeCount: Int
public let person: Person
enum CodingKeys: String, CodingKey {
case jobs
case job
case episodeCount = "episode_count"
case person
}
}
/// Cast member for /movies/.../people API
public struct MovieCrewMember: Codable, Hashable {
public let jobs: [String]
@available(*, deprecated, renamed: "jobs")
public let job: String
public let person: Person
enum CodingKeys: String, CodingKey {
case jobs
case job
case person
}
}
/// Cast member for /people/.../shows API
public struct PeopleTVCrewMember: Codable, Hashable {
public let jobs: [String]
@available(*, deprecated, renamed: "jobs")
public let job: String
public let episodeCount: Int
public let show: TraktShow
enum CodingKeys: String, CodingKey {
case jobs
case job
case episodeCount = "episode_count"
case show
}
}
/// Cast member for /people/.../movies API
public struct PeopleMovieCrewMember: Codable, Hashable {
public let jobs: [String]
@available(*, deprecated, renamed: "jobs")
public let job: String
public let movie: TraktMovie
enum CodingKeys: String, CodingKey {
case jobs
case job
case movie
}
}
| 23.943662 | 62 | 0.645294 |
624fdbec13ae77f6c9b0e9c48c5c5633883ec27a | 766 | //
// PlaylistsView.swift
// MultiplatformProject
//
// Created by Luca Palmese for the Developer Academy on 09/02/22.
//
import SwiftUI
struct PlaylistsView: View {
@StateObject var viewModel = PlaylistStore()
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(viewModel.playlists) { playlist in
EntryCellView(image: playlist.image, title: playlist.name, subtitle: playlist.category)
}
}
.padding([.leading, .trailing], 18)
.padding(.bottom, 25)
}
}
}
struct PlaylistsView_Previews: PreviewProvider {
static var previews: some View {
PlaylistsView()
}
}
| 23.212121 | 107 | 0.5953 |
7685099601c12700b15ca5536e870a0286b31072 | 3,648 | //
// XMLRPCNode.swift
// AlamofireXMLRPC
//
// Created by Jeremy Marchand on 15/08/2016.
// Copyright © 2016 kodlian. All rights reserved.
//
import Foundation
import AEXML
// MARK: - XMLRPCNode
public struct XMLRPCNode {
static var errorNode: XMLRPCNode = {
let xml = AEXMLElement(name: "")
xml.error = .elementNotFound
return XMLRPCNode(xml: xml)
}()
var xml: AEXMLElement
init(xml rootXML: AEXMLElement) {
var xml = rootXML
while (xml.rpcNode == .value || xml.rpcNode == .parameter) && xml.children.count > 0 {
if let child = xml.children.first {
xml = child
}
}
self.xml = xml
}
}
// MARK: - Array
extension XMLRPCNode: Collection {
public func index(after index: Int) -> Int {
return xml.rpcChildren?.index(after: index) ?? 0
}
public var array: [XMLRPCNode]? {
if let children = xml.rpcChildren {
return children.map { element in
if let value = element.children.first {
return XMLRPCNode(xml: value)
}
return type(of: self).errorNode
}
}
return nil
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return xml.rpcChildren?.count ?? 0
}
public subscript(key: Int) -> XMLRPCNode {
guard let children = xml.rpcChildren, (key >= 0 && key < children.count) else {
return type(of: self).errorNode
}
return XMLRPCNode(xml: children[key])
}
}
// MARK: - Struct
extension XMLRPCNode {
public subscript(key: String) -> XMLRPCNode {
guard xml.rpcNode == XMLRPCNodeKind.structure else {
return type(of: self).errorNode
}
for child in xml.children where child[XMLRPCNodeKind.name].value == key {
return XMLRPCNode(xml: child[XMLRPCNodeKind.value])
}
return type(of: self).errorNode
}
public var dictionary: [String: XMLRPCNode]? {
guard xml.rpcNode == XMLRPCNodeKind.structure else {
return nil
}
var dictionary = [String: XMLRPCNode]()
for child in xml.children {
if let key = child[XMLRPCNodeKind.name].value {
dictionary[key] = XMLRPCNode(xml: child[XMLRPCNodeKind.value])
}
}
return dictionary
}
}
// MARK: - Value
extension XMLRPCNode {
public var string: String? { return value() }
public var int: Int? { return value() }
public var int32: Int32? { return value() }
public var double: Double? { return value() }
public var bool: Bool? { return value() }
public func value<V: XMLRPCRawValueRepresentable>() -> V? {
guard let value = xml.value, let nodeKind = XMLRPCValueKind(xml: xml), nodeKind == V.xmlRpcKind else {
return nil
}
return V(xmlRpcRawValue: value)
}
public var date: Date? { return value() }
public var data: Data? { return value() }
public var error: AEXML.AEXMLError? {
return xml.error
}
public var kind: XMLRPCNodeKind? {
return self.xml.rpcNode
}
}
extension XMLRPCNode: CustomStringConvertible {
public var description: String {
return xml.value ?? ""
}
}
// MARK: - Object Value
public protocol XMLRPCInitializable {
init?(xmlRpcNode: XMLRPCNode)
}
extension XMLRPCNode {
public func value<V: XMLRPCInitializable>() -> V? {
if self.error != nil {
return nil
}
return V(xmlRpcNode: self)
}
}
| 23.843137 | 110 | 0.581963 |
d6c0f8a8c8c4e78288170a08b5e5a5a89017118f | 4,463 | struct CircularBuffer<Element>: BidirectionalCollection, CustomStringConvertible {
private var storage: ContiguousArray<Element?>
private var head = 0
private var tail = 0
init(minimumCapacity: Int = 16) {
self.storage = ContiguousArray(repeating: nil, count: minimumCapacity.nextPowerOf2())
}
private func index(advance idx: Int, by n: Int) -> Int {
return (idx + n) & (self.storage.count - 1)
}
private mutating func advanceHead(by n: Int) {
self.head = self.index(advance: self.head, by: n)
}
private mutating func advanceTail(by n: Int) {
self.tail = self.index(advance: self.tail, by: n)
}
// MARK: - Properties
var isEmpty: Bool {
return self.head == self.tail
}
var count: Int {
let d = self.tail - self.head
return d >= 0 ? d : (self.storage.count + d)
}
var capacity: Int {
return self.storage.count
}
// MARK: - Mutating
mutating func append(_ new: Element) {
self.storage[self.tail] = new
self.advanceTail(by: 1)
if self.head == self.tail {
self.increaseCapacity()
}
}
mutating func prepend(_ new: Element) {
self.storage[self.index(advance: self.head, by: -1)] = new
self.advanceHead(by: -1)
if self.head == self.tail {
self.increaseCapacity()
}
}
private mutating func increaseCapacity() {
var newStorage: ContiguousArray<Element?> = []
let oldCapacity = self.storage.count
let newCapacity = Swift.max(16, oldCapacity << 1)
newStorage.reserveCapacity(newCapacity)
newStorage.append(contentsOf: self.storage[self.head..<oldCapacity])
newStorage.append(contentsOf: self.storage[0..<self.head])
let rest = newCapacity - newStorage.count
newStorage.append(contentsOf: repeatElement(nil, count: rest))
self.head = 0
self.tail = oldCapacity
self.storage = newStorage
}
mutating func popFirst() -> Element? {
if self.isEmpty {
return nil
}
let e = self.storage[self.head]
self.storage[self.head] = nil
self.advanceHead(by: 1)
return e
}
mutating func popLast() -> Element? {
if self.isEmpty {
return nil
}
self.advanceTail(by: -1)
let e = self.storage[self.tail]
self.storage[self.tail] = nil
return e
}
// MARK: - Collection
struct Index: Comparable {
fileprivate let distanceToHead: Int
fileprivate init(distanceToHead: Int) {
self.distanceToHead = distanceToHead
}
static func < (a: Index, b: Index) -> Bool {
return a.distanceToHead < b.distanceToHead
}
}
var startIndex: Index {
return Index(distanceToHead: 0)
}
var endIndex: Index {
return Index(distanceToHead: self.count)
}
func index(after i: Index) -> Index {
return Index(distanceToHead: i.distanceToHead + 1)
}
func index(before i: Index) -> Index {
return Index(distanceToHead: i.distanceToHead - 1)
}
subscript(position: Index) -> Element {
assert(self.indices.contains(position), "[CircularBuffer]: CircularBuffer index is out of range.")
let idx = self.index(advance: self.head, by: position.distanceToHead)
return self.storage[idx]!
}
// MARK: - Description
var description: String {
var desc = ""
for (idx, e) in self.storage.enumerated() {
var s = e.map { "\($0)" } ?? "_"
if idx == self.head { s = "<" + s }
if idx == self.index(advance: self.tail, by: -1) { s = s + ">" }
switch idx {
case 0: desc.append("[" + s + ", ")
case self.storage.count - 1: desc.append(s + "]")
default: desc.append(s + ", ")
}
}
return desc
}
}
private extension FixedWidthInteger {
func nextPowerOf2() -> Self {
if self == 0 { return 1 }
return 1 << (Self.bitWidth - (self - 1).leadingZeroBitCount)
}
}
| 27.720497 | 106 | 0.538203 |
8f3cb4f9315421299f68f653862de69447302095 | 1,059 | // ------------------------------------------------------------------------
// Copyright 2020 Dan Waltin
//
// 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.
// ------------------------------------------------------------------------
//
// DocString.swift
// GherkinSwift
//
// Created by Dan Waltin on 2020-07-05.
//
// ------------------------------------------------------------------------
public struct DocString : Equatable {
public let separator: String
public let content: String
public let location: Location
public let mediaType: String?
}
| 35.3 | 75 | 0.582625 |
e4d2c4baf5285a31ff06cd01f6264a54877ca0a5 | 3,764 | //
// ViewController.swift
// ShiggyKit
//
// Created by HanaIsMe on 06/26/2019.
// Copyright (c) 2019 HanaIsMe. All rights reserved.
//
import UIKit
import ShiggyKit
class ViewController: UIViewController {
@IBOutlet weak var previousMonthButton: UIBarButtonItem!
@IBOutlet weak var nextMonthButton: UIBarButtonItem!
@IBOutlet weak var headerView: OneWeekView!
@IBOutlet weak var calendarView: UITableView!
private var oneDate: Date? {
didSet {
if let date = oneDate {
let year = date.shiggy.toYear
let month = date.shiggy.toMonth
self.theDate = "\(year)-\(month)"
}
}
}
private var theDate: String? {
didSet {
self.navigationController?.navigationBar.topItem?.title = theDate
}
}
override func viewDidLoad() {
super.viewDidLoad()
headerView.setUI()
previousMonthButton.accessibilityIdentifier = "PREVIOUS_MONTH_BUTTON"
nextMonthButton.accessibilityIdentifier = "NEXT_MONTH_BUTTON"
calendarView.dataSource = self
calendarView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.oneDate = Date()
}
@IBAction func previousMonthButtonTapped(_ sender: Any) {
guard let date = self.oneDate else { return }
self.oneDate = date.shiggy.oneMonthBefore
self.calendarView.reloadData()
}
@IBAction func nextMonthButtonTapped(_ sender: Any) {
guard let date = self.oneDate else { return }
self.oneDate = date.shiggy.oneMonthAfter
self.calendarView.reloadData()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let theDate = self.oneDate else { return 0 }
return theDate.shiggy.numberOfWeeks ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "oneWeekTableViewCell") as! OneWeekTableViewCell
cell.oneWeekView.delegate = self
cell.oneWeekView.setUI(oneDay: self.oneDate ?? Date(), indexPath: indexPath)
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
}
extension ViewController: OneDayViewDelegate {
func selected(theDayView: OneDayView) {
guard let theDate = theDayView.theDate,
let theDateToString = theDate.shiggy.toStringIgnoreUTC else { return }
self.shiggy.showAlertWithOneButton(title: "Selected day is...!",
message: theDateToString,
firstButtonTitle: "OK",
firstButtonAction: { theDayView.goBackToOriginalFont() },
firstButtonStyle: .destructive)
}
}
extension ViewController: Dependency {
func resolveDate() -> String {
return theDate ?? ""
}
}
class OneWeekTableViewCell: UITableViewCell {
@IBOutlet weak var oneWeekView: OneWeekView!
}
| 30.601626 | 113 | 0.629384 |
f545b6d1dae2cdfd48e9d0c6164009fa6a3f5750 | 746 | import UIKit
import InjectableLoggers
extension UIView {
func pinEdgesToSuperviewEdges() {
guard let superview = superview else { return logger.logError("expected superview") }
translatesAutoresizingMaskIntoConstraints = false
let edges: [NSLayoutConstraint.Attribute] = [.top, .right, .bottom, .left]
for edge in edges {
NSLayoutConstraint(item: self,
attribute: edge,
relatedBy: .equal,
toItem: superview,
attribute: edge,
multiplier: 1,
constant: 0).isActive = true
}
}
}
| 31.083333 | 93 | 0.495979 |
9c2219e8a242f3829a78d0a9708ef262438c05f7 | 1,410 | //
// AppDelegate.swift
// MMetalDemo
//
// Created by maliang on 2020/8/15.
// Copyright © 2020 maliang. 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.105263 | 179 | 0.747518 |
d6de9b48e953f07f6b243082d80259ffd56e68fe | 2,994 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct WorkloadItemResourceData : WorkloadItemResourceProtocol, ResourceProtocol {
public var id: String?
public var name: String?
public var type: String?
public var location: String?
public var tags: [String:String]?
public var eTag: String?
public var properties: WorkloadItemProtocol?
enum CodingKeys: String, CodingKey {case id = "id"
case name = "name"
case type = "type"
case location = "location"
case tags = "tags"
case eTag = "eTag"
case properties = "properties"
}
public init() {
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.id) {
self.id = try container.decode(String?.self, forKey: .id)
}
if container.contains(.name) {
self.name = try container.decode(String?.self, forKey: .name)
}
if container.contains(.type) {
self.type = try container.decode(String?.self, forKey: .type)
}
if container.contains(.location) {
self.location = try container.decode(String?.self, forKey: .location)
}
if container.contains(.tags) {
self.tags = try container.decode([String:String]?.self, forKey: .tags)
}
if container.contains(.eTag) {
self.eTag = try container.decode(String?.self, forKey: .eTag)
}
if container.contains(.properties) {
self.properties = try container.decode(WorkloadItemData?.self, forKey: .properties)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.id != nil {try container.encode(self.id, forKey: .id)}
if self.name != nil {try container.encode(self.name, forKey: .name)}
if self.type != nil {try container.encode(self.type, forKey: .type)}
if self.location != nil {try container.encode(self.location, forKey: .location)}
if self.tags != nil {try container.encode(self.tags, forKey: .tags)}
if self.eTag != nil {try container.encode(self.eTag, forKey: .eTag)}
if self.properties != nil {try container.encode(self.properties as! WorkloadItemData?, forKey: .properties)}
}
}
extension DataFactory {
public static func createWorkloadItemResourceProtocol() -> WorkloadItemResourceProtocol {
return WorkloadItemResourceData()
}
}
| 39.394737 | 119 | 0.664997 |
67c3580145fb2841ef9b2cdcf7aded942175766e | 2,247 | //
// TwoViewController.swift
// JKSwiftExtension_Example
//
// Created by IronMan on 2020/11/11.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
class TwoViewController: UIViewController {
lazy var arrowLableTop: FBArrowLabel = {
let label = FBArrowLabel()
// 设置四个角的圆角值
label.cornerRadius = 8
// 设置箭头大小
label.arrowSize = (6, 14)
// 箭头起始的偏移值
label.arrowOffset = 10
// 箭头位置为在上面
label.arrowPosition = .bottom
// 设置需要阴影
label.isNeedShadow = true
// 设置文本的内边距
label.textOffset = UIEdgeInsets(top: 8, left: 12, bottom: -8, right: -12)
return label
}()
lazy var bgView: UIView = {
let testView = UIView()
testView.backgroundColor = .brown
return testView
}()
lazy var bgView1: UILabel = {
let testView = UILabel()
testView.backgroundColor = .blue
testView.textColor = .white
testView.numberOfLines = 0
return testView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Two"
self.edgesForExtendedLayout = []
self.view.backgroundColor = UIColor.white
arrowLableTop.backgroundColor = .green
view.addSubview(bgView)
view.addSubview(bgView1)
view.addSubview(arrowLableTop)
bgView.snp.makeConstraints {
$0.left.equalTo(40)
$0.width.equalTo(jk_kScreenW - 80)
$0.height.equalTo(80)
$0.centerY.equalToSuperview()
}
bgView1.snp.makeConstraints {
$0.right.equalTo(-40)
$0.width.equalTo(80)
$0.bottom.equalToSuperview().offset(-20)
}
arrowLableTop.snp.makeConstraints {
$0.left.equalTo(20)
$0.bottom.equalTo(-40)
$0.width.equalTo(180)
$0.height.equalTo(180)
}
arrowLableTop.setupText("网络支付反欺诈、套现安全风控措施加强,客户使用微信在线支付,受到不同程度的限制(金额限制或完全无法支付)")
bgView1.text = "网络支付反欺诈、套现安全风控措施加强,客户使用微信在线支付,受到不同程度的限制"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
| 26.75 | 87 | 0.574099 |
e9462bef6ae9830dbc15aa29b1219effa48f9afa | 11,038 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Realm
import Realm.Private
// MARK: - Property Types
extension Int: SchemaDiscoverable {
public static var _rlmType: PropertyType { .int }
}
extension Int8: SchemaDiscoverable {
public static var _rlmType: PropertyType { .int }
}
extension Int16: SchemaDiscoverable {
public static var _rlmType: PropertyType { .int }
}
extension Int32: SchemaDiscoverable {
public static var _rlmType: PropertyType { .int }
}
extension Int64: SchemaDiscoverable {
public static var _rlmType: PropertyType { .int }
}
extension Bool: SchemaDiscoverable {
public static var _rlmType: PropertyType { .bool }
}
extension Float: SchemaDiscoverable {
public static var _rlmType: PropertyType { .float }
}
extension Double: SchemaDiscoverable {
public static var _rlmType: PropertyType { .double }
}
extension String: SchemaDiscoverable {
public static var _rlmType: PropertyType { .string }
}
extension Data: SchemaDiscoverable {
public static var _rlmType: PropertyType { .data }
}
extension ObjectId: SchemaDiscoverable {
public static var _rlmType: PropertyType { .objectId }
}
extension Decimal128: SchemaDiscoverable {
public static var _rlmType: PropertyType { .decimal128 }
}
extension Date: SchemaDiscoverable {
public static var _rlmType: PropertyType { .date }
}
extension UUID: SchemaDiscoverable {
public static var _rlmType: PropertyType { .UUID }
}
extension AnyRealmValue: SchemaDiscoverable {
public static var _rlmType: PropertyType { .any }
public static func _rlmPopulateProperty(_ prop: RLMProperty) {
if prop.optional {
var type = "AnyRealmValue"
if prop.array {
type = "List<AnyRealmValue>"
} else if prop.set {
type = "MutableSet<AnyRealmValue>"
} else if prop.dictionary {
type = "Map<String, AnyRealmValue>"
}
throwRealmException("\(type) property '\(prop.name)' must not be marked as optional: nil values are represented as AnyRealmValue.none")
}
}
}
extension NSString: SchemaDiscoverable {
public static var _rlmType: PropertyType { .string }
}
extension NSData: SchemaDiscoverable {
public static var _rlmType: PropertyType { .data }
}
extension NSDate: SchemaDiscoverable {
public static var _rlmType: PropertyType { .date }
}
// MARK: - Modern property getters/setters
private protocol _Int: BinaryInteger, _PersistableInsideOptional, _DefaultConstructible, _PrimaryKey, _Indexable {
}
extension _Int {
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Self {
return Self(RLMGetSwiftPropertyInt64(obj, key))
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Self? {
var gotValue = false
let ret = RLMGetSwiftPropertyInt64Optional(obj, key, &gotValue)
return gotValue ? Self(ret) : nil
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Self) {
RLMSetSwiftPropertyInt64(obj, key, Int64(value))
}
}
extension Int: _Int {
public typealias PersistedType = Int
}
extension Int8: _Int {
public typealias PersistedType = Int8
}
extension Int16: _Int {
public typealias PersistedType = Int16
}
extension Int32: _Int {
public typealias PersistedType = Int32
}
extension Int64: _Int {
public typealias PersistedType = Int64
}
extension Bool: _PersistableInsideOptional, _DefaultConstructible, _PrimaryKey, _Indexable {
public typealias PersistedType = Bool
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Bool {
return RLMGetSwiftPropertyBool(obj, key)
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Bool? {
var gotValue = false
let ret = RLMGetSwiftPropertyBoolOptional(obj, key, &gotValue)
return gotValue ? ret : nil
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Bool) {
RLMSetSwiftPropertyBool(obj, key, (value))
}
}
extension Float: _PersistableInsideOptional, _DefaultConstructible {
public typealias PersistedType = Float
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Float {
return RLMGetSwiftPropertyFloat(obj, key)
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Float? {
var gotValue = false
let ret = RLMGetSwiftPropertyFloatOptional(obj, key, &gotValue)
return gotValue ? ret : nil
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Float) {
RLMSetSwiftPropertyFloat(obj, key, (value))
}
}
extension Double: _PersistableInsideOptional, _DefaultConstructible {
public typealias PersistedType = Double
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Double {
return RLMGetSwiftPropertyDouble(obj, key)
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Double? {
var gotValue = false
let ret = RLMGetSwiftPropertyDoubleOptional(obj, key, &gotValue)
return gotValue ? ret : nil
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Double) {
RLMSetSwiftPropertyDouble(obj, key, (value))
}
}
extension String: _PersistableInsideOptional, _DefaultConstructible, _PrimaryKey, _Indexable {
public typealias PersistedType = String
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> String {
return RLMGetSwiftPropertyString(obj, key)!
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> String? {
return RLMGetSwiftPropertyString(obj, key)
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: String) {
RLMSetSwiftPropertyString(obj, key, value)
}
}
extension Data: _PersistableInsideOptional, _DefaultConstructible {
public typealias PersistedType = Data
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Data {
return RLMGetSwiftPropertyData(obj, key)!
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Data? {
return RLMGetSwiftPropertyData(obj, key)
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Data) {
RLMSetSwiftPropertyData(obj, key, value)
}
}
extension ObjectId: _PersistableInsideOptional, _DefaultConstructible, _PrimaryKey, _Indexable {
public typealias PersistedType = ObjectId
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> ObjectId {
return RLMGetSwiftPropertyObjectId(obj, key) as! ObjectId
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> ObjectId? {
return RLMGetSwiftPropertyObjectId(obj, key).flatMap(failableStaticBridgeCast)
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: ObjectId) {
RLMSetSwiftPropertyObjectId(obj, key, (value))
}
public static func _rlmDefaultValue() -> ObjectId {
return Self.generate()
}
}
extension Decimal128: _PersistableInsideOptional, _DefaultConstructible {
public typealias PersistedType = Decimal128
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Decimal128 {
return RLMGetSwiftPropertyDecimal128(obj, key) as! Decimal128
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Decimal128? {
return RLMGetSwiftPropertyDecimal128(obj, key).flatMap(failableStaticBridgeCast)
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Decimal128) {
RLMSetSwiftPropertyDecimal128(obj, key, value)
}
}
extension Date: _PersistableInsideOptional, _DefaultConstructible, _Indexable {
public typealias PersistedType = Date
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Date {
return RLMGetSwiftPropertyDate(obj, key)!
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Date? {
return RLMGetSwiftPropertyDate(obj, key)
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Date) {
RLMSetSwiftPropertyDate(obj, key, value)
}
}
extension UUID: _PersistableInsideOptional, _DefaultConstructible, _PrimaryKey, _Indexable {
public typealias PersistedType = UUID
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> UUID {
return RLMGetSwiftPropertyUUID(obj, key)!
}
@inlinable
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> UUID? {
return RLMGetSwiftPropertyUUID(obj, key)
}
@inlinable
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: UUID) {
RLMSetSwiftPropertyUUID(obj, key, value)
}
}
extension AnyRealmValue: _Persistable, _DefaultConstructible {
public typealias PersistedType = AnyRealmValue
@inlinable
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> AnyRealmValue {
return ObjectiveCSupport.convert(value: RLMGetSwiftPropertyAny(obj, key))
}
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: AnyRealmValue) {
RLMSetSwiftPropertyAny(obj, key, value._rlmObjcValue as! RLMValue)
}
public static func _rlmSetAccessor(_ prop: RLMProperty) {
prop.swiftAccessor = BridgedPersistedPropertyAccessor<Self>.self
}
}
| 31.901734 | 147 | 0.70212 |
bf446c00fa94d7a676fb9d520ab73ad231f91f92 | 6,491 | // SettingsViewController.swift
// PlusWallet
//
// Created by Chien Kieu on 2018/07/11.
// Copyright © 2018年 株式会社エンジ. All rights reserved.
import UIKit
import RxCocoa
import RxSwift
class SettingHeader: UIView, GradientDrawable {
override func draw(_ rect: CGRect) {
drawGradient(rect)
}
}
private let constHeaderHeight: CGFloat = 230.0
private let fadeStart: CGFloat = 180.0
private let fadeEnd: CGFloat = 140.0
class SettingsViewController: UIViewController {
var didTapDisplay: (() -> Void)?
// var didTapSupport: (() -> Void)?
var didTapProfile: (() -> Void)?
var didTapSecurity: (() -> Void)?
var didTapAbout : (() -> Void)?
// constant
private let closeButtonSize: CGFloat = 44.0
private let avatarSize: CGFloat = 100.0
fileprivate var headerHeight: NSLayoutConstraint?
fileprivate var didViewAppear = false
// Sub views
private let scrollView = UIScrollView()
private let headerView = SettingHeader()
private let settingListTable = SettingsListTableView()
private let avatarView = AvatarHeaderView()
private let close = UIButton.close
private let disposeBag = DisposeBag()
init() {
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
settingListTable.didTapDisplay = didTapDisplay
settingListTable.didTapProfile = didTapProfile
// settingListTable.didTapSupport = didTapSupport
settingListTable.didTapSecurity = didTapSecurity
settingListTable.didTapAbout = didTapAbout
close.tap = { [weak self] in
self?.dismiss(animated: true, completion: nil)
}
setup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isHidden = true
didViewAppear = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
didViewAppear = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
didViewAppear = false
navigationController?.navigationBar.isHidden = false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
private func setup() {
setupSubscribe()
setupStyles()
addSubviews()
setupConstraints()
}
private func setupSubscribe() {
UserDefaults.standard.rx
.observe(String.self, UDefaultKey.profileName)
.subscribe(onNext: { (value) in
self.avatarView.setText(string: value ?? "", font: UIFont.boldSystemFont(ofSize: 20))
})
.disposed(by: disposeBag)
UserDefaults.standard.rx
.observe(Data.self, UDefaultKey.profileAvatar)
.subscribe(onNext: { (value) in
if let imageData = value {
self.avatarView.setAvatar(UIImage(data: imageData as Data))
}
})
.disposed(by: disposeBag)
}
private func addSubviews() {
view.addSubview(scrollView)
scrollView.addSubview(headerView)
headerView.addSubview(close)
headerView.addSubview(avatarView)
scrollView.addSubview(settingListTable.view)
}
private func setupStyles() {
view.backgroundColor = .white
scrollView.alwaysBounceVertical = true
scrollView.panGestureRecognizer.delaysTouchesBegan = false
scrollView.delegate = self
// Close button
close.tintColor = .white
// Avatar
avatarView.setAvatar(UIImage(data: UserDefaults.profileAvatar as Data ))
}
private func setupConstraints() {
scrollView.constrain([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ])
headerHeight = headerView.heightAnchor.constraint(equalToConstant: constHeaderHeight)
headerView.constrain([
headerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
headerView.topAnchor.constraint(equalTo: view.topAnchor),
headerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
headerView.widthAnchor.constraint(equalTo: view.widthAnchor),
headerHeight])
avatarView.constrain([
avatarView.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
avatarView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
avatarView.widthAnchor.constraint(equalToConstant: avatarSize),
avatarView.heightAnchor.constraint(equalToConstant: avatarSize) ])
close.constrain([
close.topAnchor.constraint(equalTo: headerView.topAnchor, constant: E.isIPhoneX ? 40.0 : 30.0),
close.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10.0),
close.widthAnchor.constraint(equalToConstant: closeButtonSize),
close.heightAnchor.constraint(equalToConstant: closeButtonSize) ])
settingListTable.view.constrain([
settingListTable.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
settingListTable.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
settingListTable.view.topAnchor.constraint(equalTo: headerView.bottomAnchor ),
settingListTable.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension SettingsViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard didViewAppear else { return } //We don't want to be doing an stretchy header stuff during interactive pop gestures
let yOffset = scrollView.contentOffset.y + 20.0
let newHeight = constHeaderHeight - yOffset
headerHeight?.constant = newHeight
if newHeight < fadeStart {
let range = fadeStart - fadeEnd
let alpha = (newHeight - fadeEnd)/range
avatarView.alpha = max(alpha, 0.0)
} else {
avatarView.alpha = 1.0
}
}
}
| 34.897849 | 128 | 0.666461 |
ef9af7a35e3b9220bcae62bb45562caf8e65adef | 3,027 | // swift-tools-version:5.0
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import PackageDescription
let package = Package(
name: "App Center",
platforms: [
.iOS(.v9),
.macOS(.v10_10),
.tvOS(.v11)
],
products: [
.library(
name: "AppCenterAnalytics",
type: .static,
targets: ["AppCenterAnalytics"]),
.library(
name: "AppCenterCrashes",
type: .static,
targets: ["AppCenterCrashes"])
],
dependencies: [
.package(url: "https://github.com/microsoft/plcrashreporter.git", .revision("44b167048312b404f5aeb70381019deb6158f219")),
],
targets: [
.target(
name: "AppCenter",
path: "AppCenter/AppCenter",
exclude: ["Support"],
cSettings: [
.define("APP_CENTER_C_NAME", to: "\"appcenter.ios\"", .when(platforms: [.iOS])),
.define("APP_CENTER_C_NAME", to: "\"appcenter.macos\"", .when(platforms: [.macOS])),
.define("APP_CENTER_C_NAME", to: "\"appcenter.tvos\"", .when(platforms: [.tvOS])),
.define("APP_CENTER_C_VERSION", to:"\"3.1.1\""),
.define("APP_CENTER_C_BUILD", to:"\"1\""),
.headerSearchPath("**"),
],
linkerSettings: [
.linkedLibrary("z"),
.linkedLibrary("sqlite3"),
.linkedFramework("Foundation"),
.linkedFramework("SystemConfiguration"),
.linkedFramework("AppKit", .when(platforms: [.macOS])),
.linkedFramework("UIKit", .when(platforms: [.iOS, .tvOS])),
.linkedFramework("CoreTelephony", .when(platforms: [.iOS])),
]
),
.target(
name: "AppCenterAnalytics",
dependencies: ["AppCenter"],
path: "AppCenterAnalytics/AppCenterAnalytics",
exclude: ["Support"],
cSettings: [
.headerSearchPath("**"),
.headerSearchPath("../../AppCenter/AppCenter/**"),
],
linkerSettings: [
.linkedFramework("Foundation"),
.linkedFramework("UIKit", .when(platforms: [.iOS, .tvOS])),
.linkedFramework("AppKit", .when(platforms: [.macOS])),
]
),
.target(
name: "AppCenterCrashes",
dependencies: ["AppCenter", "CrashReporter"],
path: "AppCenterCrashes/AppCenterCrashes",
exclude: ["Support"],
cSettings: [
.headerSearchPath("**"),
.headerSearchPath("../../AppCenter/AppCenter/**"),
],
linkerSettings: [
.linkedFramework("Foundation"),
.linkedFramework("UIKit", .when(platforms: [.iOS, .tvOS])),
.linkedFramework("AppKit", .when(platforms: [.macOS])),
]
)
]
)
| 36.46988 | 129 | 0.50479 |
fc4fbb7ae6c3f0ae6bb22477874ae61a6636144b | 731 | public struct MyStruct<T> {}
public typealias Alias<T> = MyStruct<T>
public typealias Aliased = Alias
// RUN: %sourcekitd-test -req=cursor -pos=3:18 %s -- %s | %FileCheck %s
// CHECK: source.lang.swift.decl.typealias (3:18-3:25)
// CHECK-NEXT: Aliased
// CHECK-NEXT: s:13rdar_343487767Aliaseda
// CHECK-NEXT: Alias.Type
// CHECK-NEXT: $S13rdar_343487765AliasamD
// CHECK-NEXT: <Declaration>public typealias Aliased = <Type usr="s:13rdar_343487765Aliasa">Alias</Type></Declaration>
// CHECK-NEXT: <decl.typealias><syntaxtype.keyword>public</syntaxtype.keyword> <syntaxtype.keyword>typealias</syntaxtype.keyword> <decl.name>Aliased</decl.name> = <ref.typealias usr="s:13rdar_343487765Aliasa">Alias</ref.typealias></decl.typealias>
| 52.214286 | 247 | 0.753762 |
e99c5b86f553495890b11abec595f348afd7b912 | 1,460 | //
// PreworkUITests.swift
// PreworkUITests
//
// Created by lika on 1/28/22.
// Copyright © 2022 lika. All rights reserved.
//
import XCTest
class PreworkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.181818 | 182 | 0.658219 |
8a6f2a4c0c20d932764324611767f84594765e48 | 383 | import UIKit
class PairingSucceededViewController: PairingBaseViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBAction func setup(_ sender: LoadingButton) {
self.coordinator?.configure()
}
override func viewDidLoad() {
super.viewDidLoad()
self.coordinator!.peripherialName.bind(to: self.nameLabel.rx.text)
}
}
| 23.9375 | 74 | 0.671018 |
fb5f020c32e6eee546cbf17df2b0de8f354c64ed | 525 | //
// AppDelegate.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Conrad Stoll. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let appDependencies = AppDependencies()
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
appDependencies.installRootViewControllerIntoWindow(window!)
return true
}
}
| 22.826087 | 120 | 0.725714 |
b9ee83613a36b15e19382a631830a0f4a555bbcf | 210 | //
// main.swift
// HackSpaceStatusBar
//
// Created by markus on 26.07.14.
// Copyright (c) 2014 grafixmafia.net. All rights reserved.
//
import Cocoa
NSApplicationMain(Process.argc, Process.unsafeArgv)
| 17.5 | 60 | 0.719048 |
e67c2d9a7fe39b8870c3fee375f4aeb6a3d3b637 | 4,415 | import AppKit
//import HoleFillingLib
struct InputValidator {
private let numberFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.decimalSeparator = "."
return numberFormatter
}()
// TODO: it'd be automatically generatad currying ValidInput.init
private let createInput = { (rgbBaseImageAbsolutePath: String) in
{ (rgbHoleMaskImageAbsolutePath: String) in
{ (z: Float) in
{ (epsilon: PositiveNonZeroFloat) in
{ (pixelConnectivity: PixelConnectivity) in
{ (outputImageAbsolutePath: String) in
ValidInput(
rgbBaseImageAbsolutePath: rgbBaseImageAbsolutePath,
rgbHoleMaskImageAbsolutePath: rgbHoleMaskImageAbsolutePath,
z: z,
epsilon: epsilon,
pixelConnectivity: pixelConnectivity,
outputImageAbsolutePath: outputImageAbsolutePath
)
}
}
}
}
}
}
private let genericErrorMessage: ErrorMessage
private let emptyAbsolutePathMessage: ErrorMessage
private let invalidZMessage: ErrorMessage
private let invalidEpsilonMessage: ErrorMessage
private let invalidPixelConnectivityMessage: ErrorMessage
public init(
genericErrorMessage: ErrorMessage,
emptyAbsolutePathMessage: ErrorMessage,
invalidZMessage: ErrorMessage,
invalidEpsilonMessage: ErrorMessage,
invalidPixelConnectivityMessage: ErrorMessage) {
self.genericErrorMessage = genericErrorMessage
self.emptyAbsolutePathMessage = emptyAbsolutePathMessage
self.invalidZMessage = invalidZMessage
self.invalidEpsilonMessage = invalidEpsilonMessage
self.invalidPixelConnectivityMessage = invalidPixelConnectivityMessage
}
}
extension InputValidator: InputValidatorType {
public func validate(arguments: [String]) -> Validation<ErrorMessage, ValidInput> {
guard arguments.count == 6 else { return .invalid(genericErrorMessage) }
return pure(createInput)
.apply(validate(rgbBaseImageAbsolutePath: arguments[0]))
.apply(validate(rgbHoleMaskImageAbsolutePath: arguments[1]))
.apply(validate(z: arguments[2]))
.apply(validate(epsilon: arguments[3]))
.apply(validate(pixelConnectivity: arguments[4]))
.apply(validate(outputImageAbsolutePath: arguments[5]))
}
private func validate(rgbBaseImageAbsolutePath: String) -> Validation<ErrorMessage, String> {
return rgbBaseImageAbsolutePath.isEmpty
? .invalid(emptyAbsolutePathMessage)
: .valid(rgbBaseImageAbsolutePath)
}
private func validate(rgbHoleMaskImageAbsolutePath: String) -> Validation<ErrorMessage, String> {
return rgbHoleMaskImageAbsolutePath.isEmpty
? .invalid(emptyAbsolutePathMessage)
: .valid(rgbHoleMaskImageAbsolutePath)
}
private func validate(z: String) -> Validation<ErrorMessage, Float> {
guard let validZ = numberFormatter.number(from: z)?.floatValue else {
return .invalid(invalidZMessage)
}
return .valid(validZ)
}
private func validate(epsilon: String) -> Validation<ErrorMessage, PositiveNonZeroFloat> {
guard let epsilonFloat = numberFormatter.number(from: epsilon)?.floatValue,
let validEpsilon = PositiveNonZeroFloat(floatValue: epsilonFloat) else {
return .invalid(invalidEpsilonMessage)
}
return .valid(validEpsilon)
}
private func validate(pixelConnectivity: String) -> Validation<ErrorMessage, PixelConnectivity> {
switch pixelConnectivity {
case "4":
return .valid(.fourConnected)
case "8":
return .valid(.eightConnected)
default:
return .invalid(invalidPixelConnectivityMessage)
}
}
private func validate(outputImageAbsolutePath: String) -> Validation<ErrorMessage, String> {
return outputImageAbsolutePath.isEmpty
? .invalid(emptyAbsolutePathMessage)
: .valid(outputImageAbsolutePath)
}
}
| 38.72807 | 101 | 0.644394 |
4adac8d7836678873f111b431e37dbfec82120bb | 1,211 | //
// OptionTableViewCell.swift
// SubscriptionPrompt
//
// Created by Binur Konarbayev on 7/16/16.
//
//
import UIKit
final class OptionTableViewCell: UITableViewCell {
fileprivate var disclosureType: UITableViewCell.AccessoryType?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpViews()
}
fileprivate func setUpViews() {
let backgroundView = UIView()
backgroundView.backgroundColor = .orange
selectedBackgroundView = backgroundView
textLabel?.textAlignment = .center
}
}
extension OptionTableViewCell {
func setUp(withOption option: Option) {
accessoryType = option.checked ? (disclosureType ?? .checkmark) : .none
textLabel?.text = option.title
}
func setUp(withOptionStyle style: OptionStyle) {
backgroundColor = style.backgroundColor
textLabel?.font = style.textFont
textLabel?.textColor = style.textColor
disclosureType = style.accessoryType
}
}
| 26.911111 | 79 | 0.674649 |
487c622066dbd590d3f47c3bd532f3a088e2005d | 546 | //
// Constants.swift
// TwitterClient
//
// Created by Graphic on 3/24/18.
// Copyright © 2018 KarimEbrahem. All rights reserved.
//
import Foundation
class Constants {
struct Keys {
static let consumerKey = "TmOyeB1v0kVHKSzG3VLZWcyYr"
static let consumerSecret = "iuLEnwb6rnbs1vdZFh3jUOw24zNGMu2NcvYCvzgmE1PKYaCL5X"
}
struct UserNumbers {
// if any value == nil, so it will get all of them
static let numberOfFollowers: Int? = nil
static let numberOfTweets: Int? = 10
}
}
| 22.75 | 88 | 0.659341 |
ccfc227250a23de1f925fcbfaa3d623f62a0e4d5 | 6,608 | //
// Date+Extensions.swift
// RewardzCommonComponents
//
// Created by Ankit Sachan on 01/04/21.
//
import Foundation
public enum Weekday: Int {
case Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
public extension Date {
var monthName: String {
let month = self.month
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.calendar = Calendar(identifier: .gregorian)
return dateFormatter.monthSymbols[month-1]
}
var weekDayname: String {
let week = self.day
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.calendar = Calendar(identifier: .gregorian)
return dateFormatter.weekdaySymbols[week-1]
}
func dayOfWeek() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.calendar = Calendar(identifier: .gregorian)
return dateFormatter.string(from: self).capitalized
// or capitalized(with: locale)
}
var year: Int { return Calendar(identifier: .gregorian).component(.year, from: self as Date) }
var month: Int { return Calendar(identifier: .gregorian).component(.month, from: self as Date) }
var day: Int { return Calendar(identifier: .gregorian).component(.day, from: self as Date) }
func dateByAddingUnit(unit: Calendar.Component, value: Int) -> Date? {
return Calendar.current.date(byAdding: unit, value: value, to: self)
}
var today: Date {
return Calendar.current.date(from: DateComponents(year: year, month: month, day: day))!
//return Calendar.gregorian.dateFromComponents(DateComponents(year: year, month: month, day: day))!
}
var tomorrow: Date {
return Calendar.current.date(from: DateComponents(year: year, month: month, day: day+1))!
//return Calendar.gregorian.dateFromComponents(DateComponents(year: year, month: month, day: day+1))!
}
var sevenDays:[Date] {
var result:[Date] = [Date().today.dateByAddingUnit(unit: .day, value: -3)!]
for _ in 1...6 {
result.append(result.last!.tomorrow)
}
return result
}
var sevenDaysOfWeek:[Date] {
//var result:[Date] = [Date().today.dateByAddingUnit(unit: .day, value: -5, options: NSCalendar.Options())]
var result:[Date] = [Date().today.dateByAddingUnit(unit: .day, value: -5)!]
for _ in 1...6 {
result.append(result.last!.tomorrow)
}
return result
}
var sevenDaysForHistory:[Date] {
var result:[Date] = [Date().today.dateByAddingUnit(unit: .day, value: -2)!]
for _ in 1...6 {
result.append(result.last!.tomorrow)
}
return result
}
var sevenMonths:[Int] {
var result:[Date] = [Date().today.dateByAddingUnit(unit: .month, value: -2)!]
for _ in 1...6 {
result.append(result.last!.dateByAddingUnit(unit: .month, value: 1)!)
}
return result.map{$0.month}
}
var sevenMonthsNames:[String] {
var result:[Date] = [Date().today.dateByAddingUnit(unit: .month, value: -2)!]
for _ in 1...6 {
result.append(result.last!.dateByAddingUnit(unit: .month, value: 1)!)
}
return result.map{$0.monthName}
}
var sevenMonthsNameswithDate:[Date] {
var result:[Date] = [Date().today.dateByAddingUnit(unit: .month, value: -2)!]
for _ in 1...6 {
result.append(result.last!.dateByAddingUnit(unit: .month, value: 1)!)
}
return result.map{$0}
}
func following(weekday: Weekday) -> Date {
var components = DateComponents()
components.weekday = weekday.rawValue
guard
let date = Calendar.current.nextDate(after: self, matching: components, matchingPolicy: .nextTime)// Calendar.gregorian.nextDateAfterDate(self, matchingComponents: components, options: .MatchNextTime)
else { return Date.distantFuture }
return date
}
var currentWeekFirstDate: Date {
return following(weekday: .Sunday).dateByAddingUnit(unit: .weekOfYear, value: -1)!
}
var currentWeekDates:[Date] {
var result:[Date] = [Date().today.currentWeekFirstDate]
for _ in 1...6 {
result.append(result.last!.tomorrow)
}
return result
}
var currentWeekDays:[Int] {
return currentWeekDates.map{$0.day}
}
func startOfMonth() -> Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!
}
func endOfMonth() -> Date {
return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())!
}
}
public extension Date {
init?(dateString: String) {
let dateStringFormatter = DateFormatter()
dateStringFormatter.locale = Locale(identifier: "en_US")
dateStringFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
dateStringFormatter.calendar = Calendar(identifier: .gregorian)
dateStringFormatter.timeZone = TimeZone(identifier: "GMT")
if let date = dateStringFormatter.date(from: dateString){
self = date
}else{
return nil
}
}
func getDatePart() -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd"
formatter.timeZone = TimeZone(identifier: "GMT + 5:30")
formatter.calendar = Calendar(identifier: .gregorian)
return formatter.string(from: self as Date)
}
func getTimePart() -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "hh : mm"
formatter.timeZone = TimeZone(identifier: "GMT + 5:30")
formatter.calendar = Calendar(identifier: .gregorian)
return formatter.string(from: self as Date)
}
}
public extension Date {
func dateWithOutTime() -> Date {
let comps = Calendar.current.dateComponents([.day, .month, .year], from: self)
return NSCalendar.current.date(from: comps)!
}
func isBetweeen(startDate date1: Date, endDate date2: Date) -> Bool {
return date1.compare(self as Date) == self.compare(date2 as Date)
}
}
| 37.123596 | 212 | 0.626362 |
08bc0f544ddc12de23ffbc6d526135259c271dd2 | 909 | //
// DateExtensions.swift
// Christmas Fam Duels
//
// Created by Dave Butz on 11/5/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import Foundation
extension NSDate
{
convenience
init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
}
convenience init(dateStringhms:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateStringhms)!
self.init(timeInterval:0, sinceDate:d)
}
} | 31.344828 | 78 | 0.69967 |
6afdd38b15891cd0315fadee16c6f360932572e5 | 1,471 | extension Request {
/// Returns the current `Session` or creates one.
///
/// router.get("session") { req -> String in
/// req.session.data["name"] = "Vapor"
/// return "Session set"
/// }
///
/// - note: `SessionsMiddleware` must be added and enabled.
/// - returns: `Session` for this `Request`.
public var session: Session {
if !self._sessionCache.middlewareFlag {
// No `SessionsMiddleware` was detected on your app.
// Suggested solutions:
// - Add the `SessionsMiddleware` globally to your app using `app.middleware.use`
// - Add the `SessionsMiddleware` to a route group.
assertionFailure("No `SessionsMiddleware` detected.")
}
if let existing = self._sessionCache.session {
return existing
} else {
let new = Session()
self._sessionCache.session = new
return new
}
}
public var hasSession: Bool {
return self._sessionCache.session != nil
}
private struct SessionCacheKey: StorageKey {
typealias Value = SessionCache
}
internal var _sessionCache: SessionCache {
if let existing = self.storage[SessionCacheKey.self] {
return existing
} else {
let new = SessionCache()
self.storage[SessionCacheKey.self] = new
return new
}
}
}
| 31.978261 | 93 | 0.562203 |
d5ed4c61fe744863c3fd102eb3f7e0a70db90859 | 2,625 | import Foundation
/// Provides functioanlity that allows to perform key derivation
public enum TokenDKDF {
public static let deriveKeyMasterKeyWalletId: String = "WALLET_ID"
public static let deriveKeyMasterKeyWalletKey: String = "WALLET_KEY"
public static let supportedEncryptionVersions: [Int] = [1]
/// Errors that may occur while deriving key
public enum DeriveKeyError: Error {
/// Case of unsupported encryption version
case unsupportedEncryptionVersion
/// Case of failed string encoding
case stringEncodingFailed
}
/// Method derives key for given master key
/// - Returns: `Data`
/// - Parameters:
/// - login: User's login
/// - password: User's password
/// - salt: Data which is used to safeguard password
/// - masterKey: Master key
/// - n: Scrypt `n` parameter
/// - r: Scrypt `r` parameter
/// - p: Scrypt `p` parameter
/// - encryptionVersion: Encryption version
/// - keyLength: Length of result key
public static func deriveKey(
login: String,
password: String,
salt: Data,
masterKey: String,
n: UInt64,
r: UInt32,
p: UInt32,
encryptionVersion: Int = 1,
keyLength: Int
) throws -> Data {
guard self.supportedEncryptionVersions.contains(encryptionVersion) else {
throw DeriveKeyError.unsupportedEncryptionVersion
}
guard
let loginData = login.data(using: .utf8),
let passwordData = password.data(using: .utf8),
let masterKeyData = masterKey.data(using: .utf8)
else {
throw DeriveKeyError.stringEncodingFailed
}
let encryptionVersionData = Data.init(repeating: UInt8(encryptionVersion), count: 1)
var composedRawSaltData = Data.init(capacity: encryptionVersionData.count + salt.count + loginData.count)
composedRawSaltData.append(encryptionVersionData)
composedRawSaltData.append(salt)
composedRawSaltData.append(loginData)
let composedSalt = Common.SHA.sha256(data: composedRawSaltData)
let keyScrypted = try Common.SCrypt.scryptSalsa208sha256(
password: passwordData,
salt: composedSalt,
n: n,
r: r,
p: p,
keyLength: keyLength
)
let key = try Common.HMAC.hmacsha256(data: masterKeyData, key: keyScrypted)
return key
}
}
| 33.653846 | 113 | 0.602286 |
eb452b2c4a2e070ee9d1573c90ea12f54dc15d58 | 9,815 | //
// YAxisRendererHorizontalBarChart.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 YAxisRendererHorizontalBarChart: YAxisRenderer
{
public override init(viewPortHandler: ViewPortHandler, axis: YAxis, transformer: Transformer?)
{
super.init(viewPortHandler: viewPortHandler, axis: axis, transformer: transformer)
}
/// Computes the axis values.
open override func computeAxis(min: Double, max: Double, inverted: Bool)
{
var min = min, max = max
// calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds)
if let transformer = transformer,
viewPortHandler.contentHeight > 10.0,
!viewPortHandler.isFullyZoomedOutX
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
min = inverted ? Double(p2.x) : Double(p1.x)
max = inverted ? Double(p1.x) : Double(p2.x)
}
computeAxisValues(min: min, max: max)
}
/// draws the y-axis labels to the screen
open override func renderAxisLabels(context: CGContext)
{
guard
axis.isEnabled,
axis.isDrawLabelsEnabled
else { return }
let lineHeight = axis.labelFont.lineHeight
let baseYOffset: CGFloat = 2.5
let dependency = axis.axisDependency
let labelPosition = axis.labelPosition
let yPos: CGFloat =
{
switch (dependency, labelPosition)
{
case (.left, .outsideChart):
return viewPortHandler.contentTop - baseYOffset - lineHeight
case (.left, .insideChart):
return viewPortHandler.contentTop - baseYOffset - lineHeight
case (.right, .outsideChart):
return viewPortHandler.contentBottom + baseYOffset
case (.right, .insideChart):
return viewPortHandler.contentBottom + baseYOffset
}
}()
drawYLabels(
context: context,
fixedPosition: yPos,
positions: transformedPositions(),
offset: axis.yOffset
)
}
open override func renderAxisLine(context: CGContext)
{
guard
axis.isEnabled,
axis.drawAxisLineEnabled
else { return }
context.saveGState()
defer { context.restoreGState() }
context.setStrokeColor(axis.axisLineColor.cgColor)
context.setLineWidth(axis.axisLineWidth)
if axis.axisLineDashLengths != nil
{
context.setLineDash(phase: axis.axisLineDashPhase, lengths: axis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.beginPath()
if axis.axisDependency == .left
{
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
}
else
{
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
}
context.strokePath()
}
/// draws the y-labels on the specified x-position
@objc open func drawYLabels(
context: CGContext,
fixedPosition: CGFloat,
positions: [CGPoint],
offset: CGFloat)
{
let labelFont = axis.labelFont
let labelTextColor = axis.labelTextColor
let from = axis.isDrawBottomYLabelEntryEnabled ? 0 : 1
let to = axis.isDrawTopYLabelEntryEnabled ? axis.entryCount : (axis.entryCount - 1)
for i in from..<to
{
let text = axis.getFormattedLabel(i)
context.drawText(text,
at: CGPoint(x: positions[i].x, y: fixedPosition - offset),
align: .center,
attributes: [.font: labelFont, .foregroundColor: labelTextColor])
}
}
open override var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dx = self.axis.gridLineWidth
contentRect.origin.x -= dx / 2.0
contentRect.size.width += dx
return contentRect
}
open override func drawGridLine(
context: CGContext,
position: CGPoint)
{
context.beginPath()
context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom))
context.strokePath()
}
open override func transformedPositions() -> [CGPoint]
{
guard let transformer = self.transformer else { return [] }
var positions = axis.entries.map { CGPoint(x: $0, y: 0.0) }
transformer.pointValuesToPixel(&positions)
return positions
}
/// Draws the zero line at the specified position.
open override func drawZeroLine(context: CGContext)
{
guard
let transformer = self.transformer,
let zeroLineColor = axis.zeroLineColor
else { return }
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.x -= axis.zeroLineWidth / 2.0
clippingRect.size.width += axis.zeroLineWidth
context.clip(to: clippingRect)
context.setStrokeColor(zeroLineColor.cgColor)
context.setLineWidth(axis.zeroLineWidth)
let pos = transformer.pixelForValues(x: 0.0, y: 0.0)
if axis.zeroLineDashLengths != nil
{
context.setLineDash(phase: axis.zeroLineDashPhase, lengths: axis.zeroLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.move(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentBottom))
context.drawPath(using: .stroke)
}
open override func renderLimitLines(context: CGContext)
{
guard let transformer = self.transformer else { return }
var limitLines = axis.limitLines
guard !limitLines.isEmpty else { return }
context.saveGState()
defer { context.restoreGState() }
let trans = transformer.valueToPixelMatrix
var position = CGPoint.zero
for l in limitLines where l.isEnabled
{
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.x -= l.lineWidth / 2.0
clippingRect.size.width += l.lineWidth
context.clip(to: clippingRect)
position = CGPoint(x: l.limit, y: 0)
.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled, !label.isEmpty
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset = l.lineWidth + l.xOffset
let yOffset = 2.0 + l.yOffset
let align: NSTextAlignment
let point: CGPoint
switch l.labelPosition
{
case .rightTop:
align = .left
point = CGPoint(x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset)
case .rightBottom:
align = .left
point = CGPoint(x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset)
case .leftTop:
align = .right
point = CGPoint(x: position.x - xOffset,
y: viewPortHandler.contentTop + yOffset)
case .leftBottom:
align = .right
point = CGPoint(x: position.x - xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset)
}
context.drawText(label,
at: point,
align: align,
attributes: [.font: l.valueFont, .foregroundColor: l.valueTextColor])
}
}
}
}
| 33.498294 | 124 | 0.568619 |
f7f7db1a08b6185114a2d09ff7c4eeee1ccd2651 | 340 | //
// UIBarButtonItem.swift
// ReactiveDataDisplayManagerExample_iOS
//
// Created by Artem Kayumov on 19.05.2022.
//
import UIKit
public extension UIBarButtonItem {
static var empty: UIBarButtonItem = {
let button = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
return button
}()
}
| 18.888889 | 92 | 0.679412 |
16291b42193be0bb1ab62f66ff9785762e08779a | 1,086 | //
// Matrix.actual.swift
// Butterfly
//
// Created by Joseph Ivie on 7/16/20.
// Copyright © 2020 Lightning Kite. All rights reserved.
//
import CoreGraphics
extension CGAffineTransform {
public mutating func reset() {
self = CGAffineTransform.identity
}
public mutating func set(_ other: CGAffineTransform) {
self = other
}
public mutating func apply(_ f: (CGAffineTransform)->()->CGAffineTransform) {
self = f(self)()
}
public mutating func apply<A>(_ f: (CGAffineTransform)->(A)->CGAffineTransform, _ a: A) {
self = f(self)(a)
}
public mutating func apply<A, B>(_ f: (CGAffineTransform)->(A, B)->CGAffineTransform, _ a: A, _ b: B) {
self = f(self)(a, b)
}
public mutating func apply<A, B, C>(_ f: (CGAffineTransform)->(A, B, C)->CGAffineTransform, _ a: A, _ b: B, _ c: C) {
self = f(self)(a, b, c)
}
public mutating func apply<A, B, C, D>(_ f: (CGAffineTransform)->(A, B, C, D)->CGAffineTransform, _ a: A, _ b: B, _ c: C, _ d: D) {
self = f(self)(a, b, c, d)
}
}
| 31.941176 | 135 | 0.593002 |
6aaf9df3c6c5f9b3966c26fe8894d59b7188af31 | 612 | //
// LinesAdapter.swift
// QuickSwift
//
// Created by tcui on 28/1/2018.
// Copyright © 2018 LuckyTR. All rights reserved.
//
import Foundation
public class LinesAdapter: HeaderFooterTableAdapter {
public func append(line: String) {
append(lines: [line])
}
public func append(lines: [String]) {
sections.last?.append {
lines.map { OneLineTextCellItem(text: $0)}
}
}
public convenience init(tableView: UITableView, sectionItem: SectionItemProtocol) {
self.init(tableView: tableView)
append(sectionItem: PlainSectionItem())
}
}
| 22.666667 | 87 | 0.648693 |
1c14e5303e4953761e3912e6ae895f0902292ffa | 529 | struct BankCardDataInputModuleInputData {
let cardScanner: CardScanning?
let testModeSettings: TestModeSettings?
let isLoggingEnabled: Bool
}
protocol BankCardDataInputModuleInput: class {
func bankCardDidTokenize(_ error: Error)
}
protocol BankCardDataInputModuleOutput: class {
func didPressCloseBarButtonItem(on module: BankCardDataInputModuleInput)
func bankCardDataInputModule(_ module: BankCardDataInputModuleInput,
didPressConfirmButton bankCardData: CardData)
}
| 33.0625 | 78 | 0.771267 |
acafc9977ef6a9ef88814af288dbbfaaafee2a5c | 682 | //
// SingleMatch.swift
// RockPaperScissors
//
// Created by Jason on 11/14/14.
// Copyright (c) 2014 Gabrielle Miller-Messner. All rights reserved.
//
import Foundation
// The RPSMatch struct stores the results of a match.
// Later in the course we will store multiple matches in an array, so users can track their match history.
struct RPSMatch {
let p1: RPS
let p2: RPS
init(p1: RPS, p2: RPS) {
self.p1 = p1
self.p2 = p2
}
var winner: RPS {
get {
return p1.defeats(p2) ? p1 : p2
}
}
var loser: RPS {
get {
return p1.defeats(p2) ? p2 : p1
}
}
} | 19.485714 | 106 | 0.555718 |
fcc08139ad08865d588b1e2dac16de76fd8324bc | 443 | // RUN: %target-swift-ide-test -code-completion -code-completion-token=COMPLETE -source-filename=%s | %FileCheck %s
// REQUIRES: long_test
// This used to take ~6 min to complete.
// Now it's 2 min: rdar://problem/48818341
func testing() {
return (["a"] + [1].map { String($0) })
.map { $0 + "b" as String }
.filter { $0 != "" } #^COMPLETE^#
}
// CHECK: Decl[InfixOperatorFunction]/{{.*}}: [' ']+ {#[String]#}[#[String]#]; name=+
| 31.642857 | 115 | 0.595937 |
693c491b0da06a3c2771d0681682bc3386d0dda4 | 135 | import Foundation
import Foundation
@objcMembers class FixtureClass25: NSObject {
var someVar: String?
func someMethod() {}
}
| 16.875 | 45 | 0.740741 |
7270aa27a0014d60d0132984b36db0b8330af14c | 2,181 | //
// AppDelegate.swift
// FoodTracer
//
// Created by ddchen on 11/26/15.
// Copyright © 2015 ddchen. 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:.
}
}
| 46.404255 | 286 | 0.737735 |
aba3d51fa234e535ee2b9739c3aa3225c4743517 | 4,509 | // Copyright (c) 2021 Payoneer Germany GmbH
// https://www.payoneer.com
//
// This file is open source and available under the MIT license.
// See the LICENSE file for more information.
import Foundation
protocol InputPaymentControllerDelegate: class {
func paymentController(presentURL url: URL)
func paymentController(route result: Result<OperationResult, ErrorInfo>)
func paymentController(inputShouldBeChanged error: ErrorInfo)
func paymentController(didFailWith error: ErrorInfo)
}
extension Input.ViewController {
class PaymentController {
let paymentServiceFactory: PaymentServicesFactory
weak var delegate: InputPaymentControllerDelegate?
init(paymentServiceFactory: PaymentServicesFactory) {
self.paymentServiceFactory = paymentServiceFactory
}
}
}
extension Input.ViewController.PaymentController {
func submitPayment(for network: Input.Network) {
let service = paymentServiceFactory.createPaymentService(forNetworkCode: network.networkCode, paymentMethod: network.paymentMethod)
service?.delegate = self
let inputFieldsDictionary: [String: String]
do {
inputFieldsDictionary = try createInputFields(from: network)
} catch {
let errorInfo = CustomErrorInfo(resultInfo: error.localizedDescription, interaction: Interaction(code: .ABORT, reason: .CLIENTSIDE_ERROR), underlyingError: error)
delegate?.paymentController(didFailWith: errorInfo)
return
}
let request = PaymentRequest(networkCode: network.networkCode, operationURL: network.operationURL, inputFields: inputFieldsDictionary)
service?.send(paymentRequest: request)
}
private func createInputFields(from network: Input.Network) throws -> [String: String] {
var inputFieldsDictionary = [String: String]()
for element in network.uiModel.inputFields + network.uiModel.separatedCheckboxes {
if element.name == "expiryDate" {
// Transform expiryDate to month and a full year
let dateComponents = try createDateComponents(fromExpiryDateString: element.value)
inputFieldsDictionary["expiryMonth"] = dateComponents.month
inputFieldsDictionary["expiryYear"] = dateComponents.year
} else {
inputFieldsDictionary[element.name] = element.value
}
}
return inputFieldsDictionary
}
/// Create month and full year for short date string
/// - Parameter expiryDate: example `03/30`
/// - Returns: month and full year
private func createDateComponents(fromExpiryDateString expiryDate: String) throws -> (month: String, year: String) {
let expiryMonth = String(expiryDate.prefix(2))
let shortYear = String(expiryDate.suffix(2))
let expiryYear = try DateFormatter.string(fromShortYear: shortYear)
return (month: expiryMonth, year: expiryYear)
}
}
extension Input.ViewController.PaymentController: PaymentServiceDelegate {
func paymentService(didReceiveResponse response: PaymentServiceParsedResponse) {
let serverResponse: Result<OperationResult, ErrorInfo>
switch response {
case .redirect(let url):
DispatchQueue.main.async {
self.delegate?.paymentController(presentURL: url)
}
return
case .result(let result):
serverResponse = result
}
// On retry show an error and leave on that view
if case .RETRY = Interaction.Code(rawValue: serverResponse.interaction.code) {
let errorInfo = ErrorInfo(resultInfo: serverResponse.resultInfo, interaction: serverResponse.interaction)
DispatchQueue.main.async {
self.delegate?.paymentController(inputShouldBeChanged: errorInfo)
}
}
// If a reason is a communication failure, propose to retry
else if case .COMMUNICATION_FAILURE = Interaction.Reason(rawValue: serverResponse.interaction.reason),
case let .failure(errorInfo) = serverResponse {
DispatchQueue.main.async {
self.delegate?.paymentController(didFailWith: errorInfo)
}
}
// In other situations route to a parent view
else {
DispatchQueue.main.async {
self.delegate?.paymentController(route: serverResponse)
}
}
}
}
| 39.902655 | 174 | 0.678643 |
1804453ad2c343ce4d6153820d3b05697682b614 | 221 | //
// Providable.swift
// DiffableNotes
//
// Created by Eilon Krauthammer on 29/11/2020.
//
import Foundation
protocol Providable {
associatedtype ProvidedItem: Hashable
func provide(_ item: ProvidedItem)
}
| 15.785714 | 47 | 0.719457 |
67288a1200e4de02ffed5b4849b764250a44c652 | 11,379 | //
// Types.swift
// ZEGBot
//
// Created by Shane Qi on 5/30/16.
// Copyright © 2016 com.github.shaneqi. All rights reserved.
//
// Licensed under Apache License v2.0
//
import Foundation
public enum Update: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let updateId = try container.decode(Int.self, forKey: .updateId)
if container.contains(.message) {
self = .message(updateId: updateId, message: try container.decode(Message.self, forKey: .message))
} else if container.contains(.editedMessage) {
self = .editedMessage(updateId: updateId, message: try container.decode(Message.self, forKey: .editedMessage))
} else if container.contains(.channelPost) {
self = .channelPost(updateId: updateId, message: try container.decode(Message.self, forKey: .channelPost))
} else if container.contains(.callbackQuery) {
self = .callbackQuery(updateId: updateId, query: try container.decode(CallbackQuery.self, forKey: .callbackQuery))
} else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: """
Failed to find value under keys: \
"\(CodingKeys.message.rawValue)", \
"\(CodingKeys.editedMessage.rawValue)" or \
"\(CodingKeys.channelPost.rawValue)".
"""))
}
}
private enum CodingKeys: String, CodingKey {
case message
case updateId = "update_id"
case editedMessage = "edited_message"
case channelPost = "channel_post"
case callbackQuery = "callback_query"
}
case message(updateId: Int, message: Message)
case editedMessage(updateId: Int, message: Message)
case channelPost(updateId: Int, message: Message)
case callbackQuery(updateId: Int, query: CallbackQuery)
public var message: Message? {
if case .message(_, let message) = self {
return message
} else {
return nil
}
}
public var editedMessage: Message? {
if case .editedMessage(_, let message) = self {
return message
} else {
return nil
}
}
public var channelPost: Message? {
if case .channelPost(_, let message) = self {
return message
} else {
return nil
}
}
public var callbackQuery: CallbackQuery? {
if case .callbackQuery(_, let query) = self {
return query
} else {
return nil
}
}
}
public class Message: Codable {
public let messageId: Int
public let date: Int
public let chat: Chat
/* Optional. */
public let from: User?
public let forwardFrom: User?
public let forwardFromChat: Chat?
public let forwardDate: Int?
public let replyToMessage: Message?
public let editDate: Int?
public let mediaGroupId: String?
public let text: String?
public let entities: [MessageEntity]?
public let audio: Audio?
public let document: Document?
public let photo: [PhotoSize]?
public let sticker: Sticker?
public let video: Video?
public let voice: Voice?
public let caption: String?
public let contact: Contact?
public let location: Location?
public let venue: Venue?
public let newChatMember: User?
public let leftChatMember: User?
public let newChatTitle: String?
public let newChatPhoto: [PhotoSize]?
public let deleteChatPhoto: Bool?
public let groupChatCreated: Bool?
public let supergroupChatCreated: Bool?
public let channelChatCreated: Bool?
public let migrateToChatId: Int?
public let migrateFromChatId: Int?
public let pinnedMessage: Message?
private enum CodingKeys: String, CodingKey {
case date, chat, from, text, entities
case audio, document, photo, sticker, video, voice, caption, contact, location, venue
case messageId = "message_id"
case forwardFrom = "forward_from"
case forwardFromChat = "forward_from_chat"
case forwardDate = "forward_date"
case replyToMessage = "reply_to_message"
case editDate = "edit_date"
case newChatMember = "new_chat_member"
case leftChatMember = "left_chat_member"
case newChatTitle = "new_chat_title"
case newChatPhoto = "new_chat_photo"
case deleteChatPhoto = "delete_chat_photo"
case groupChatCreated = "group_chat_created"
case supergroupChatCreated = "supergroup_chat_created"
case channelChatCreated = "channel_chat_created"
case migrateToChatId = "migrate_to_chat_id"
case migrateFromChatId = "migrate_from_chat_id"
case pinnedMessage = "pinned_message"
case mediaGroupId = "media_group_id"
}
}
public struct Chat: Codable {
public let id: Int
public let type: StructType
/* Optional. */
public let title: String?
public let username: String?
public let firstName: String?
public let lastName: String?
public enum StructType: String, Codable {
case `private`, group, supergroup, channel
}
private enum CodingKeys: String, CodingKey {
case id, type, title, username
case firstName = "first_name"
case lastName = "last_name"
}
}
public struct User: Codable {
public let id: Int
public let firstName: String
public let isBot: Bool
/* OPTIONAL. */
public let lastName: String?
public let username: String?
private enum CodingKeys: String, CodingKey {
case id, username
case firstName = "first_name"
case lastName = "last_name"
case isBot = "is_bot"
}
}
public struct MessageEntity: Codable {
public let type: StructType
public let offset: Int
public let length: Int
/* OPTIONAl. */
public let url: String?
public let user: User?
public enum StructType: String, Codable {
case mention, hashtag, url, email, cashtag
case bold, italic, underline, strikethrough, code, pre
case botCommand = "bot_command"
case textLink = "text_link"
case textMention = "text_mention"
case phoneNumber = "phone_number"
}
}
public struct Audio: Codable {
public let fileId: String
public let duration: Int
/* OPTIONAL. */
public let performer: String?
public let title: String?
public let mimeType: String?
public let fileSize: Int?
private enum CodingKeys: String, CodingKey {
case duration, performer, title
case fileId = "file_id"
case mimeType = "mime_type"
case fileSize = "file_size"
}
}
public struct Document: Codable {
public let fileId: String
/* OPTIONAL. */
public let thumb: PhotoSize?
public let fileName: String?
public let mimeType: String?
public let fileSize: Int?
private enum CodingKeys: String, CodingKey {
case thumb
case fileId = "file_id"
case fileName = "file_name"
case mimeType = "mime_type"
case fileSize = "file_size"
}
}
public struct PhotoSize: Codable {
public let fileId: String
public let width: Int
public let height: Int
/* Optional. */
public let fileSize: Int?
private enum CodingKeys: String, CodingKey {
case width, height
case fileId = "file_id"
case fileSize = "file_size"
}
}
public struct Sticker: Codable {
public let fileId: String
public let width: Int
public let height: Int
/* Optional. */
public let thumb: PhotoSize?
public let emoji: String?
public let fileSize: Int?
private enum CodingKeys: String, CodingKey {
case width, height, thumb, emoji
case fileId = "file_id"
case fileSize = "file_size"
}
}
public struct Video: Codable {
public let fileId: String
public let width: Int
public let height: Int
public let duration: Int
/* OPTIONAL. */
public let thumb: PhotoSize?
public let mimeType: String?
public let fileSize: Int?
private enum CodingKeys: String, CodingKey {
case width, height, duration, thumb
case fileId = "file_id"
case mimeType = "mime_type"
case fileSize = "file_size"
}
}
public struct Voice: Codable {
public let fileId: String
public let duration: Int
/* Optional. */
public let mimeType: String?
public let fileSize: Int?
private enum CodingKeys: String, CodingKey {
case duration
case fileId = "file_id"
case mimeType = "mime_type"
case fileSize = "file_size"
}
}
public struct Contact: Codable {
public let phoneNumber: String
public let firstName: String
/* OPTIONAL. */
public let lastName: String?
public let userId: Int?
private enum CodingKeys: String, CodingKey {
case phoneNumber = "phone_number"
case firstName = "first_name"
case lastName = "last_name"
case userId = "user_id"
}
public init(
phoneNumber: String,
firstName: String,
lastName: String?,
userId: Int?) {
self.phoneNumber = phoneNumber
self.firstName = firstName
self.lastName = lastName
self.userId = userId
}
}
public struct Location: Codable {
public let latitude: Double
public let longitude: Double
public init(
latitude: Double,
longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
}
public struct Venue: Codable {
public let location: Location
public let title: String
public let address: String
/* OPTIONAL. */
public let foursquareId: String?
private enum CodingKeys: String, CodingKey {
case location, title, address
case foursquareId = "foursquare_id"
}
public init(
location: Location,
title: String,
address: String,
foursquareId: String?) {
self.location = location
self.title = title
self.address = address
self.foursquareId = foursquareId
}
}
public struct File: Codable {
public let fileId: String
/* OPTIONAL. */
public let fileSize: Int?
public let filePath: String?
private enum CodingKeys: String, CodingKey {
case fileSize = "file_size"
case fileId = "file_id"
case filePath = "file_path"
}
}
public enum ParseMode: String, Codable {
case markdown
case html
}
public enum ChatAction: String, Codable {
case typing
case uploadPhoto = "upload_photo"
case recordVideo = "record_video"
case uploadVideo = "upload_video"
case recordAudio = "record_audio"
case uploadAudio = "upload_audio"
case uploadDocument = "upload_document"
case findLocation = "find_location"
}
public struct ChatMember: Codable {
public let user: User
}
/// https://core.telegram.org/bots/api#inlinekeyboardbutton
public struct InlineKeyboardButton: Codable {
public let text: String
public let url: String?
public let callbackData: String?
public let switchInlineQuery: String?
public let switchInlineQueryCurrentChat: String?
private enum CodingKeys: String, CodingKey {
case text, url
case callbackData = "callback_data"
case switchInlineQuery = "switch_inline_query"
case switchInlineQueryCurrentChat = "switch_inline_query_current_chat"
}
public init(
text: String,
url: String? = nil,
callbackData: String? = nil,
switchInlineQuery: String? = nil,
switchInlineQueryCurrentChat: String? = nil) {
self.text = text
self.url = url
self.callbackData = callbackData
self.switchInlineQuery = switchInlineQuery
self.switchInlineQueryCurrentChat = switchInlineQueryCurrentChat
}
}
/// https://core.telegram.org/bots/api#inlinekeyboardmarkup
public struct InlineKeyboardMarkup: Codable {
public let inlineKeyboard: [[InlineKeyboardButton]]
private enum CodingKeys: String, CodingKey {
case inlineKeyboard = "inline_keyboard"
}
public init(inlineKeyboard: [[InlineKeyboardButton]]) {
self.inlineKeyboard = inlineKeyboard
}
}
/// https://core.telegram.org/bots/api#callbackquery
public struct CallbackQuery: Decodable {
public let id: String
public let from: User
public let message: Message?
public let inlineMessageId: String?
public let chatInstance: String?
public let data: String?
private enum CodingKeys: String, CodingKey {
case id, from, message, data
case inlineMessageId = "inline_message_id"
case chatInstance = "chat_instance"
}
}
| 22.987879 | 117 | 0.731347 |
114a7914aa45426cd6d50bd3ab53e8cd83250ba8 | 1,323 | //
// BBC_Fruits_App_BBCNewsAPI_Tests.swift
// BBC Fruits AppTests
//
// Created by Jatinder Pal Singh Khera on 03/10/2019.
// Copyright © 2019 Jatinder Pal Singh Khera. All rights reserved.
//
import XCTest
@testable import BBC_Fruits_App
class BBC_Fruits_App_BBCFruitsAPI_Tests: 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 testDownloadFruit() {
// Create an expectation for a API call.
let expectation = XCTestExpectation(description: "Fetch fruit")
BBCFruits.loadFruits { (fruits, error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
else {
// print(fruits)
}
// Fulfill the expectation to indicate that the background task has finished successfully.
expectation.fulfill()
}
// Wait until the expectation is fulfilled, with a timeout of 10 seconds.
wait(for: [expectation], timeout: 10.0)
}
}
| 30.767442 | 111 | 0.621315 |
e4b704352e46232c0b8558debcbb06bd65185e24 | 533 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// ElasticPoolDatabaseActivityProtocol is represents the activity on an elastic pool.
public protocol ElasticPoolDatabaseActivityProtocol : ProxyResourceProtocol {
var location: String? { get set }
var properties: ElasticPoolDatabaseActivityPropertiesProtocol? { get set }
}
| 48.454545 | 96 | 0.778612 |
75ade33d3a77a348be707910fd742cc21917cf0b | 2,177 | //
// AppDelegate.swift
// SpaceInvaders
//
// Created by CoderDream on 2019/3/25.
// Copyright © 2019 CoderDream. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| 46.319149 | 285 | 0.756086 |
e4a57cd052427ffdd9abf90deab78baec17d8c07 | 10,306 | //
// MixpanelPeopleTests.swift
// MixpanelDemo
//
// Created by Yarden Eitan on 6/28/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import XCTest
import Nocilla
@testable import Mixpanel
@testable import MixpanelDemo
class MixpanelPeopleTests: MixpanelBaseTests {
func testPeopleSet() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
waitForTrackingQueue(testMixpanel)
let p: Properties = ["p1": "a"]
testMixpanel.people.set(properties: p)
waitForTrackingQueue(testMixpanel)
sleep(1)
let q = peopleQueue(token: testMixpanel.apiToken).last!["$set"] as! InternalProperties
XCTAssertEqual(q["p1"] as? String, "a", "custom people property not queued")
assertDefaultPeopleProperties(q)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleSetOnce() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
let p: Properties = ["p1": "a"]
testMixpanel.people.setOnce(properties: p)
waitForTrackingQueue(testMixpanel)
sleep(1)
let q = peopleQueue(token: testMixpanel.apiToken).last!["$set_once"] as! InternalProperties
XCTAssertEqual(q["p1"] as? String, "a", "custom people property not queued")
assertDefaultPeopleProperties(q)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleSetReservedProperty() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
let p: Properties = ["$ios_app_version": "override"]
testMixpanel.people.set(properties: p)
waitForTrackingQueue(testMixpanel)
sleep(1)
let q = peopleQueue(token: testMixpanel.apiToken).last!["$set"] as! InternalProperties
XCTAssertEqual(q["$ios_app_version"] as? String,
"override",
"reserved property override failed")
assertDefaultPeopleProperties(q)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleSetTo() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.set(property: "p1", to: "a")
waitForTrackingQueue(testMixpanel)
sleep(1)
let p: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!["$set"] as! InternalProperties
XCTAssertEqual(p["p1"] as? String, "a", "custom people property not queued")
assertDefaultPeopleProperties(p)
removeDBfile(testMixpanel.apiToken)
}
func testDropUnidentifiedPeopleRecords() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
for i in 0..<505 {
testMixpanel.people.set(property: "i", to: i)
}
waitForTrackingQueue(testMixpanel)
sleep(1)
XCTAssertTrue(unIdentifiedPeopleQueue(token: testMixpanel.apiToken).count == 506)
var r: InternalProperties = unIdentifiedPeopleQueue(token: testMixpanel.apiToken)[1]
XCTAssertEqual((r["$set"] as? InternalProperties)?["i"] as? Int, 0)
r = unIdentifiedPeopleQueue(token: testMixpanel.apiToken).last!
XCTAssertEqual((r["$set"] as? InternalProperties)?["i"] as? Int, 504)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleAssertPropertyTypes() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
var p: Properties = ["URL": [Data()]]
XCTExpectAssert("unsupported property type was allowed") {
testMixpanel.people.set(properties: p)
}
XCTExpectAssert("unsupported property type was allowed") {
testMixpanel.people.set(property: "p1", to: [Data()])
}
p = ["p1": "a"]
// increment should require a number
XCTExpectAssert("unsupported property type was allowed") {
testMixpanel.people.increment(properties: p)
}
removeDBfile(testMixpanel.apiToken)
}
func testPeopleIncrement() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
let p: Properties = ["p1": 3]
testMixpanel.people.increment(properties: p)
waitForTrackingQueue(testMixpanel)
sleep(1)
let q = peopleQueue(token: testMixpanel.apiToken).last!["$add"] as! InternalProperties
XCTAssertTrue(q.count == 1, "incorrect people properties: \(p)")
XCTAssertEqual(q["p1"] as? Int, 3, "custom people property not queued")
removeDBfile(testMixpanel.apiToken)
}
func testPeopleIncrementBy() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.increment(property: "p1", by: 3)
waitForTrackingQueue(testMixpanel)
sleep(1)
let p: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!["$add"] as! InternalProperties
XCTAssertTrue(p.count == 1, "incorrect people properties: \(p)")
XCTAssertEqual(p["p1"] as? Double, 3, "custom people property not queued")
removeDBfile(testMixpanel.apiToken)
}
func testPeopleDeleteUser() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.deleteUser()
waitForTrackingQueue(testMixpanel)
sleep(1)
let p: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!["$delete"] as! InternalProperties
XCTAssertTrue(p.isEmpty, "incorrect people properties: \(p)")
removeDBfile(testMixpanel.apiToken)
}
func testPeopleTrackChargeDecimal() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.trackCharge(amount: 25.34)
waitForTrackingQueue(testMixpanel)
sleep(1)
let r: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!
let prop = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$amount"] as? Double
let prop2 = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$time"]
XCTAssertEqual(prop, 25.34)
XCTAssertNotNil(prop2)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleTrackChargeZero() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
waitForTrackingQueue(testMixpanel)
testMixpanel.people.trackCharge(amount: 0)
waitForTrackingQueue(testMixpanel)
sleep(1)
let r: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!
let prop = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$amount"] as? Double
let prop2 = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$time"]
XCTAssertEqual(prop, 0)
XCTAssertNotNil(prop2)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleTrackChargeWithTime() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
let p: Properties = allPropertyTypes()
testMixpanel.people.trackCharge(amount: 25, properties: ["$time": p["date"]!])
waitForTrackingQueue(testMixpanel)
sleep(1)
let r: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!
let prop = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$amount"] as? Double
let prop2 = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$time"] as? String
XCTAssertEqual(prop, 25)
compareDate(dateString: prop2!, dateDate: p["date"] as! Date)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleTrackChargeWithProperties() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.trackCharge(amount: 25, properties: ["p1": "a"])
waitForTrackingQueue(testMixpanel)
sleep(1)
let r: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!
let prop = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$amount"] as? Double
let prop2 = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["p1"]
XCTAssertEqual(prop, 25)
XCTAssertEqual(prop2 as? String, "a")
removeDBfile(testMixpanel.apiToken)
}
func testPeopleTrackCharge() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.trackCharge(amount: 25)
waitForTrackingQueue(testMixpanel)
sleep(1)
let r: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!
let prop = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$amount"] as? Double
let prop2 = ((r["$append"] as? InternalProperties)?["$transactions"] as? InternalProperties)?["$time"]
XCTAssertEqual(prop, 25)
XCTAssertNotNil(prop2)
removeDBfile(testMixpanel.apiToken)
}
func testPeopleClearCharges() {
let testMixpanel = Mixpanel.initialize(token: randomId(), flushInterval: 60)
testMixpanel.identify(distinctId: "d1")
testMixpanel.people.clearCharges()
waitForTrackingQueue(testMixpanel)
sleep(1)
let r: InternalProperties = peopleQueue(token: testMixpanel.apiToken).last!
let transactions = (r["$set"] as? InternalProperties)?["$transactions"] as? [MixpanelType]
XCTAssertEqual(transactions?.count, 0)
removeDBfile(testMixpanel.apiToken)
}
}
| 45.804444 | 122 | 0.667475 |
fcd0a50822daefe59acf848eec93d5db7853ddca | 611 | //
// ViewController.swift
// RPMNetworkLayer
//
// Created by pugaldevan on 09/22/2020.
// Copyright (c) 2020 pugaldevan. All rights reserved.
//
import UIKit
import RPMNetworkLayer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myStr = Service.serviceMethod()
print(myStr)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.366667 | 80 | 0.664484 |
1656224a27e2d01a5e8ad61949355c837aeac3c7 | 1,947 | // Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// SmokeHTTP1HandlerSelector+blockingWithInputWithOutput.swift
// SmokeOperationsHTTP1
//
import Foundation
import LoggerAPI
import SmokeOperations
import NIOHTTP1
public extension SmokeHTTP1HandlerSelector {
/**
Adds a handler for the specified uri and http method.
- Parameters:
- uri: The uri to add the handler for.
- operation: the handler method for the operation.
- allowedErrors: the errors that can be serialized as responses
from the operation and their error codes.
- operationDelegate: optionally an operation-specific delegate to use when
handling the operation
*/
public mutating func addHandlerForUri<InputType: ValidatableCodable, OutputType: ValidatableCodable,
ErrorType: ErrorIdentifiableByDescription>(
_ uri: String,
httpMethod: HTTPMethod,
operation: @escaping ((InputType, ContextType) throws -> OutputType),
allowedErrors: [(ErrorType, Int)],
operationDelegate: OperationDelegateType? = nil) {
let handler = OperationHandler(operation: operation,
allowedErrors: allowedErrors,
operationDelegate: operationDelegate)
addHandlerForUri(uri, httpMethod: httpMethod, handler: handler)
}
}
| 39.734694 | 104 | 0.688238 |
9bdbf77053fdb93028779734c381900a0796bc25 | 4,131 | //
// SKButtons.swift
// SKPhotoBrowser
//
// Created by 鈴木 啓司 on 2016/08/09.
// Copyright © 2016年 suzuki_keishi. All rights reserved.
//
import UIKit
// helpers which often used
private let bundle = Bundle(for: SKPhotoBrowser.self)
class SKButton: UIButton {
internal var showFrame: CGRect!
internal var hideFrame: CGRect!
fileprivate var insets: UIEdgeInsets {
if UIDevice.current.userInterfaceIdiom == .phone {
return UIEdgeInsets(top: 15.25, left: 15.25, bottom: 15.25, right: 15.25)
} else {
return UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
}
}
fileprivate let size: CGSize = CGSize(width: 44, height: 44)
fileprivate var marginX: CGFloat = 0
fileprivate var marginY: CGFloat = 0
fileprivate var extraMarginY: CGFloat = 20 // NOTE: dynamic to static
func setup(_ imageName: String) {
backgroundColor = .clear
imageEdgeInsets = insets
translatesAutoresizingMaskIntoConstraints = true
autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin]
let image = UIImage(named: "SKPhotoBrowser.bundle/images/\(imageName)", in: bundle, compatibleWith: nil) ?? UIImage()
setImage(image, for: .normal)
}
func setFrameSize(_ size: CGSize? = nil) {
guard let size = size else { return }
let newRect = CGRect(x: marginX, y: marginY, width: size.width, height: size.height)
frame = newRect
showFrame = newRect
hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height)
}
func updateFrame(_ frameSize: CGSize) { }
}
class SKImageButton: SKButton {
fileprivate var imageName: String { return "" }
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup(imageName)
showFrame = CGRect(x: marginX, y: marginY, width: size.width, height: size.height)
hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height)
}
}
class SKCloseButton: SKImageButton {
override var imageName: String { return "btn_common_close_wh" }
override var marginX: CGFloat {
get {
return SKPhotoBrowserOptions.swapCloseAndDeleteButtons
? SKMesurement.screenWidth - SKButtonOptions.closeButtonPadding.x - self.size.width
: SKButtonOptions.closeButtonPadding.x
}
set { super.marginX = newValue }
}
override var marginY: CGFloat {
get { return SKButtonOptions.closeButtonPadding.y + extraMarginY }
set { super.marginY = newValue }
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup(imageName)
showFrame = CGRect(x: marginX, y: marginY, width: size.width, height: size.height)
hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height)
}
}
class SKDeleteButton: SKImageButton {
override var imageName: String { return "btn_common_delete_wh" }
override var marginX: CGFloat {
get {
return SKPhotoBrowserOptions.swapCloseAndDeleteButtons
? SKButtonOptions.deleteButtonPadding.x
: SKMesurement.screenWidth - SKButtonOptions.deleteButtonPadding.x - self.size.width
}
set { super.marginX = newValue }
}
override var marginY: CGFloat {
get { return SKButtonOptions.deleteButtonPadding.y + extraMarginY }
set { super.marginY = newValue }
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup(imageName)
showFrame = CGRect(x: marginX, y: marginY, width: size.width, height: size.height)
hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height)
}
}
| 34.425 | 125 | 0.645364 |
cc7631d8ce8192d99512c38218e821b63f82fddc | 390 | //
// ProfileDTO.swift
// HikrNetworking
//
// Created by Jan Bjelicic on 02/02/2021.
//
import Foundation
public struct ProfileDTO: Codable {
public var name: String
public var title: String
public var bio: String
public init(name: String, title: String, bio: String) {
self.name = name
self.title = title
self.bio = bio
}
}
| 16.956522 | 59 | 0.607692 |
e2f2f1bdf675d0172eef60048ae615151686e72e | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for { func c {
let end = [ {
deinit {
class
case ,
| 22 | 87 | 0.727273 |
23c16b6775e4783e7524262d2b596ec5cc942bf7 | 628 | //
// TextDisplayViewController.swift
// Example
//
// Created by Milen Halachev on 24.01.19.
// Copyright © 2019 KoCMoHaBTa. All rights reserved.
//
import Foundation
import UIKit
class TextDisplayViewController: UIViewController, TextDisplaConfigurable, AppVersionConfigurable {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var versionLabel: UILabel!
var appVersion: String?
var textToDisplay: String?
override func viewDidLoad() {
super.viewDidLoad()
self.label.text = self.textToDisplay
self.versionLabel.text = self.appVersion
}
}
| 22.428571 | 99 | 0.683121 |
89b34ae5e78b30befe2d122047f3144fe90674c0 | 3,762 | //
// AppDelegate.swift
// SolarCalculator
//
// Created by Aakash Srivastav on 28/07/18.
// Copyright © 2018 Aakash Srivastav. All rights reserved.
//
import UIKit
import CoreData
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static let shared = UIApplication.shared.delegate as! AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
registerUserNotifications()
return true
}
func registerUserNotifications() {
let center = UNUserNotificationCenter.current()
//center.delegate = self
center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (grant, error) in
if error == nil, grant {
} else if let unwrappedError = error {
print_debug("error: \(unwrappedError.localizedDescription)")
}
})
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "SolarCalculator")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 40.891304 | 199 | 0.644338 |
9070d7340df6d0167814ee32e007c3c468bad79d | 6,729 | //
// ValidationExamplesFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class ValidationExamplesFormViewController : XLFormViewController {
private enum Tags : String {
case ValidationName = "Name"
case ValidationEmail = "Email"
case ValidationPassword = "Password"
case ValidationInteger = "Integer"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeForm()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Text Fields")
section = XLFormSectionDescriptor()
section.title = "Validation Required"
form.addFormSection(section)
// Name
row = XLFormRowDescriptor(tag: Tags.ValidationName.rawValue, rowType: XLFormRowDescriptorTypeText, title:"Name")
row.cellConfigAtConfigure["textField.placeholder"] = "Required..."
row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
row.required = true
row.value = "Martin"
section.addFormRow(row)
section = XLFormSectionDescriptor()
section.title = "Validation Email"
form.addFormSection(section)
// Email
row = XLFormRowDescriptor(tag: Tags.ValidationEmail.rawValue, rowType: XLFormRowDescriptorTypeText, title:"Email")
row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
row.required = false
row.value = "not valid email"
row.addValidator(XLFormValidator.emailValidator())
section.addFormRow(row)
section = XLFormSectionDescriptor()
section.title = "Validation Password"
section.footerTitle = "between 6 and 32 charachers, 1 alphanumeric and 1 numeric"
form.addFormSection(section)
// Password
row = XLFormRowDescriptor(tag: Tags.ValidationPassword.rawValue, rowType: XLFormRowDescriptorTypePassword, title:"Password")
row.cellConfigAtConfigure["textField.placeholder"] = "Required..."
row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
row.required = true
row.addValidator(XLFormRegexValidator(msg: "At least 6, max 32 characters", andRegexString: "^(?=.*\\d)(?=.*[A-Za-z]).{6,32}$"))
section.addFormRow(row)
section = XLFormSectionDescriptor()
section.title = "Validation Numbers"
section.footerTitle = "grather than 50 and less than 100"
form.addFormSection(section)
// Integer
row = XLFormRowDescriptor(tag: Tags.ValidationInteger.rawValue, rowType:XLFormRowDescriptorTypeInteger, title:"Integer")
row.cellConfigAtConfigure["textField.placeholder"] = "Required..."
row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
row.required = true
row.addValidator(XLFormRegexValidator(msg: "grather than 50 and less than 100", andRegexString: "^([5-9][0-9]|100)$"))
section.addFormRow(row)
self.form = form
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem?.target = self
self.navigationItem.rightBarButtonItem?.action = "validateForm:"
}
//MARK: Actions
func validateForm(buttonItem: UIBarButtonItem) {
let array = self.formValidationErrors()
for errorItem in array {
let error = errorItem as! NSError
let validationStatus : XLFormValidationStatus = error.userInfo![XLValidationStatusErrorKey] as! XLFormValidationStatus
if validationStatus.rowDescriptor.tag == Tags.ValidationName.rawValue {
if let cell = self.tableView.cellForRowAtIndexPath(self.form.indexPathOfFormRow(validationStatus.rowDescriptor)) {
cell.backgroundColor = UIColor.orangeColor()
UIView.animateWithDuration(0.3, animations: { () -> Void in
cell.backgroundColor = UIColor.whiteColor()
})
}
}
else if validationStatus.rowDescriptor.tag == Tags.ValidationEmail.rawValue ||
validationStatus.rowDescriptor.tag == Tags.ValidationPassword.rawValue ||
validationStatus.rowDescriptor.tag == Tags.ValidationInteger.rawValue {
if let cell = self.tableView.cellForRowAtIndexPath(self.form.indexPathOfFormRow(validationStatus.rowDescriptor)) {
self.animateCell(cell)
}
}
}
}
//MARK: - Helperph
func animateCell(cell: UITableViewCell) {
let animation = CAKeyframeAnimation()
animation.keyPath = "position.x"
animation.values = [0, 20, -20, 10, 0]
animation.keyTimes = [0, (1 / 6.0), (3 / 6.0), (5 / 6.0), 1]
animation.duration = 0.3
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.additive = true
cell.layer.addAnimation(animation, forKey: "shake")
}
}
| 42.05625 | 136 | 0.661614 |
895707e0383c9c71f219c5115e295de6a9f74d3c | 260 | import Foundation
final class MainActivity: NSObject {
override init() {
super.init()
}
// Synchronous method that was supposed to return a randomly generated number
func generateRandomNumber() -> Int {
return 60
}
}
| 18.571429 | 81 | 0.638462 |
fbcdac895aca937235f16e8014564958787abb32 | 3,311 | //
// XYZPathKit_UserDevicePath.swift
// XYZPathKit
//
// Created by 张子豪 on 2020/4/7.
// Copyright © 2020 张子豪. All rights reserved.
//
import UIKit
//获取系统的路径
public let userDocument = Path.userDocuments
public let userCaches = Path.userCaches
public let userLibrary = Path.userLibrary
public let userDocChildens = Path.userDocuments.children()
public let userInbox = Path.userDocuments + "Inbox"
public let userTemp = Path.userTemporary
//自己生成的路径
public var userMusic:Path{ let userFolderX = Path.userDocuments + "Music" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userFile :Path{ let userFolderX = Path.userDocuments + "File" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userVideo:Path{ let userFolderX = Path.userDocuments + "Video" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userPDF :Path{ let userFolderX = Path.userDocuments + "PDF" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userLMR :Path{ let userFolderX = Path.userDocuments + "LMR" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userZip :Path{ let userFolderX = Path.userDocuments + "Zip" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userPic :Path{ let userFolderX = Path.userDocuments + "Picture" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userInbox1 :Path{
let userFolderX = Path.userDocuments + "Inbox1" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userCookies :Path{
let userFolderX = Path.userDocuments + "Cookies" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userPreferences :Path{
let userFolderX = Path.userDocuments + "Preferences" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userAlreadyUnZip :Path{
let userFolderX = Path.userDocuments + "alreadyUnZip" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userSecretFileFolder :Path{
let userFolderX = Path.userDocuments + "SecretFileFolder" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var AppSupport :Path{
let userFolderX = Path.userDocuments + "Application Support" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userWallPaper :Path{
let userFolderX = Path.userDocuments + "WallPaper" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userRealmDataBase:Path{
let userFolderX = Path.userDocuments + "RealmDataBase" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
public var userRealmFolder :Path{
let userFolderX = Path.userDocuments + "RealmFolder" ;if !userFolderX.exists{try? userFolderX.createDirectory() } ; return userFolderX }
| 67.571429 | 165 | 0.726367 |
f85147cb8a7246c73347c58cb53984f53cd26035 | 7,764 | // Copyright 2020 David Sansome
//
// 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
private func UIColorFromHex(_ hexColor: Int32) -> UIColor {
let red = (CGFloat)((hexColor & 0xFF0000) >> 16) / 255
let green = (CGFloat)((hexColor & 0x00FF00) >> 8) / 255
let blue = (CGFloat)(hexColor & 0x0000FF) / 255
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
private func AdaptiveColor(light: UIColor, dark: UIColor) -> UIColor {
if #available(iOS 13, *) {
return UIColor { (tc: UITraitCollection) -> UIColor in
if tc.userInterfaceStyle == .dark {
return dark
} else {
return light
}
}
} else {
return light
}
}
private func AdaptiveColorHex(light: Int32, dark: Int32) -> UIColor {
AdaptiveColor(light: UIColorFromHex(light), dark: UIColorFromHex(dark))
}
@objc
@objcMembers
class TKMStyle: NSObject {
// MARK: - Shadows
class func addShadowToView(_ view: UIView, offset: Float, opacity: Float, radius: Float) {
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0.0, height: Double(offset))
view.layer.shadowOpacity = opacity
view.layer.shadowRadius = CGFloat(radius)
view.clipsToBounds = false
}
// MARK: - WaniKani colors and gradients
static let defaultTintColor = UIColor(red: 0.0, green: 122.0 / 255.0, blue: 1.0, alpha: 1.0)
static let radicalColor1 = AdaptiveColorHex(light: 0x00AAFF, dark: 0x006090)
static let radicalColor2 = AdaptiveColorHex(light: 0x0093DD, dark: 0x005080)
static let kanjiColor1 = AdaptiveColorHex(light: 0xFF00AA, dark: 0x940060)
static let kanjiColor2 = AdaptiveColorHex(light: 0xDD0093, dark: 0x800050)
static let vocabularyColor1 = AdaptiveColorHex(light: 0xAA00FF, dark: 0x6100AA)
static let vocabularyColor2 = AdaptiveColorHex(light: 0x9300DD, dark: 0x530080)
static let lockedColor1 = UIColorFromHex(0x505050)
static let lockedColor2 = UIColorFromHex(0x484848)
static let readingColor1 = AdaptiveColor(light: UIColor(white: 0.235, alpha: 1),
dark: UIColor(white: 0.235, alpha: 1))
static let readingColor2 = AdaptiveColor(light: UIColor(white: 0.102, alpha: 1),
dark: UIColor(white: 0.102, alpha: 1))
static let meaningColor1 = AdaptiveColor(light: UIColor(white: 0.933, alpha: 1),
dark: UIColor(white: 0.733, alpha: 1))
static let meaningColor2 = AdaptiveColor(light: UIColor(white: 0.882, alpha: 1),
dark: UIColor(white: 0.682, alpha: 1))
// The [Any] types force these to be exposed to objective-C as an untyped NSArray*.
static var radicalGradient: [Any] { [radicalColor1.cgColor, radicalColor2.cgColor] }
static var kanjiGradient: [Any] { [kanjiColor1.cgColor, kanjiColor2.cgColor] }
static var vocabularyGradient: [Any] { [vocabularyColor1.cgColor, vocabularyColor2.cgColor] }
static var lockedGradient: [Any] { [lockedColor1.cgColor, lockedColor2.cgColor] }
static var readingGradient: [Any] { [readingColor1.cgColor, readingColor2.cgColor] }
static var meaningGradient: [Any] { [meaningColor1.cgColor, meaningColor2.cgColor] }
class func color(forSRSStageCategory srsStageCategory: TKMSRSStageCategory) -> UIColor {
switch srsStageCategory {
case .apprentice:
return UIColor(red: 0.87, green: 0.00, blue: 0.58, alpha: 1.0)
case .guru:
return UIColor(red: 0.53, green: 0.17, blue: 0.62, alpha: 1.0)
case .master:
return UIColor(red: 0.16, green: 0.30, blue: 0.86, alpha: 1.0)
case .enlightened:
return UIColor(red: 0.00, green: 0.58, blue: 0.87, alpha: 1.0)
case .burned:
return UIColor(red: 0.26, green: 0.26, blue: 0.26, alpha: 1.0)
default:
return TKMStyle.Color.label
}
}
class func color2(forSubjectType subjectType: TKMSubject_Type) -> UIColor {
switch subjectType {
case .radical:
return radicalColor2
case .kanji:
return kanjiColor2
case .vocabulary:
return vocabularyColor2
@unknown default:
fatalError()
}
}
class func gradient(forAssignment assignment: TKMAssignment) -> [Any] {
switch assignment.subjectType {
case .radical:
return radicalGradient
case .kanji:
return kanjiGradient
case .vocabulary:
return vocabularyGradient
@unknown default:
fatalError()
}
}
class func gradient(forSubject subject: TKMSubject) -> [Any] {
if subject.hasRadical {
return radicalGradient
} else if subject.hasKanji {
return kanjiGradient
} else if subject.hasVocabulary {
return vocabularyGradient
}
return []
}
// MARK: - Japanese fonts
static let japaneseFontName = "Hiragino Sans"
// Tries to load fonts from the list of font names, in order, until one is found.
private class func loadFont(_ names: [String], size: CGFloat) -> UIFont {
for name in names {
if let font = UIFont(name: name, size: size) {
return font
}
}
return UIFont.systemFont(ofSize: size)
}
class func japaneseFont(size: CGFloat) -> UIFont {
UIFont(name: japaneseFontName, size: size)!
}
class func japaneseFontLight(size: CGFloat) -> UIFont {
loadFont(["HiraginoSans-W3",
"HiraginoSans-W2",
"HiraginoSans-W1",
"HiraginoSans-W4",
"HiraginoSans-W5"], size: size)
}
class func japaneseFontBold(size: CGFloat) -> UIFont {
loadFont(["HiraginoSans-W8",
"HiraginoSans-W7",
"HiraginoSans-W6",
"HiraginoSans-W5"], size: size)
}
// MARK: - Dark mode aware UI colors
@objc(TKMStyleColor)
@objcMembers
class Color: NSObject {
static let background = AdaptiveColor(light: UIColor.white, dark: UIColor.black)
static let cellBackground = AdaptiveColorHex(light: 0xFFFFFF, dark: 0x1C1C1E)
static let label = AdaptiveColor(light: UIColor.black, dark: UIColor.white)
static let grey33 = AdaptiveColor(light: UIColor.darkGray, dark: UIColor.lightGray)
static let grey66 = AdaptiveColor(light: UIColor.lightGray, dark: UIColor.darkGray)
static let grey80 = AdaptiveColor(light: UIColor(white: 0.8, alpha: 1.0),
dark: UIColor(white: 0.2, alpha: 1.0))
// Markup colors for mnemonics.
static let markupRadicalForeground = AdaptiveColorHex(light: 0x000000, dark: 0x4AC3FF)
static let markupRadicalBackground = AdaptiveColorHex(light: 0xD6F1FF, dark: 0x1C1C1E)
static let markupKanjiForeground = AdaptiveColorHex(light: 0x000000, dark: 0xFF4AC3)
static let markupKanjiBackground = AdaptiveColorHex(light: 0xFFD6F1, dark: 0x1C1C1E)
static let markupVocabularyForeground = AdaptiveColorHex(light: 0x000000, dark: 0xC34AFF)
static let markupVocabularyBackground = AdaptiveColorHex(light: 0xF1D6FF, dark: 0x1C1C1E)
}
// Wrapper around UITraitCollection.performAsCurrent that just does nothing
// on iOS < 13.
class func withTraitCollection(_ tc: UITraitCollection, f: () -> Void) {
if #available(iOS 13.0, *) {
tc.performAsCurrent {
f()
}
} else {
f()
}
}
}
| 38.058824 | 95 | 0.676455 |
e43c2f406b24b2b4d57ec4c19478d20c5068530f | 199 | //
// Entity.swift
// 33- CryptoViper
//
// Created by Adem Deliaslan on 17.03.2022.
//
import Foundation
//Struct
struct Crypto : Decodable {
let currency : String
let price : String
}
| 13.266667 | 44 | 0.653266 |
90dbf9568bbb557b9262e5a944df0aefed585058 | 404 | //
// 🦠 Corona-Warn-App
//
enum OnboardingPageType: Int, CaseIterable {
case togetherAgainstCoronaPage = 0
case privacyPage = 1
case enableLoggingOfContactsPage = 2
case howDoesDataExchangeWorkPage = 3
case alwaysStayInformedPage = 4
func next() -> OnboardingPageType? {
OnboardingPageType(rawValue: rawValue + 1)
}
func isLast() -> Bool {
(self == OnboardingPageType.allCases.last)
}
}
| 19.238095 | 44 | 0.732673 |
bb377786da237ffc4b2b4dbc0d69ca7482ba2d70 | 2,432 | //
// StoreFront.swift
//
// Created by iJSON Swift model generator on 2021/07/01.
// Copyright © 2021. All rights reserved.
//
import Foundation
struct StoreFrontDataAttributes: Decodable {
var name: String?
var explicitContentPolicy: String?
var supportedLanguageTags: [String] = []
var defaultLanguageTag: String?
enum CodingKeys: String, CodingKey {
case name
case explicitContentPolicy
case supportedLanguageTags
case defaultLanguageTag
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
explicitContentPolicy = try container.decode(String.self, forKey: .explicitContentPolicy)
supportedLanguageTags = try container.decode([String].self, forKey: .supportedLanguageTags)
defaultLanguageTag = try container.decode(String.self, forKey: .defaultLanguageTag)
}
static func toOption(From data: Data) -> StoreFrontDataAttributes? {
return try? JSONDecoder().decode(StoreFrontDataAttributes.self, from: data)
}
}
struct StoreFront: Decodable {
var data: [StoreFrontData] = []
enum CodingKeys: String, CodingKey {
case data
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
data = try container.decode([StoreFrontData].self, forKey: .data)
}
static func toOption(From data: Data) -> StoreFront? {
return try? JSONDecoder().decode(StoreFront.self, from: data)
}
}
struct StoreFrontData: Decodable {
var href: String?
var id: String?
var attributes: StoreFrontDataAttributes?
var type: String?
enum CodingKeys: String, CodingKey {
case href
case id
case attributes
case type
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
href = try container.decode(String.self, forKey: .href)
id = try container.decode(String.self, forKey: .id)
attributes = try container.decode(StoreFrontDataAttributes.self, forKey: .attributes)
type = try container.decode(String.self, forKey: .type)
}
static func toOption(From data: Data) -> StoreFrontData? {
return try? JSONDecoder().decode(StoreFrontData.self, from: data)
}
}
| 30.4 | 99 | 0.678865 |
721328320a04e0d7cc0cddab92d20a0f70174c6f | 359 | // 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
if true{
let a{
{
class A{
struct B<T where g:C{{
}
struct c{
struct c{
class A{
class a
class A{
class A{
class B{
struct B{
class B:a
| 16.318182 | 87 | 0.713092 |
f71b205c13890b2508664e7d9d32b884af41b274 | 1,562 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(windowScene: windowScene)
let samplesViewController = SampleListViewController()
let navigationController = UINavigationController(rootViewController: samplesViewController)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
}
}
| 44.628571 | 143 | 0.768886 |
380ed8cdf475741d8dd52da79c2a063dbb8d2bcc | 3,390 | import UIKit
import XCTest
import Blackhole
import BrightFutures
class ReceivingPromisesTestCase: BlackholeTestCase {
// MARK: - Basic Tests
func testSimpleSendingReceiveSuccess() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let sendExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
let receiveExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
self.session.emit(TestSession.EmitResult(success: true))
let messegeListener = MessageListener { message -> BlackholeMessage? in
guard let value = message["someKey"], value is String, value as! String == "stringValue" else {
XCTAssert(false)
return nil
}
receiveExpectation.fulfill()
return nil
}
receiver.addListener(messegeListener, forIdentifier: identifier)
emitter.promiseSendMessage(message, withIdentifier: identifier)
.onFailure { error in
XCTAssert(false, "Error sending: \(error)")
}
.onSuccess {
sendExpectation.fulfill()
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
func testTripleSendingReceivedSuccess() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let sendExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
let receiveExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
self.session.emit(TestSession.EmitResult(success: true))
self.session.emit(TestSession.EmitResult(success: true))
self.session.emit(TestSession.EmitResult(success: true))
var counter = 3
let messegeListener = MessageListener { message -> BlackholeMessage? in
guard let value = message["someKey"], value is String, value as! String == "stringValue" else {
XCTAssert(false)
return nil
}
counter -= 1
if counter == 0 {
receiveExpectation.fulfill()
}
return nil
}
receiver.addListener(messegeListener, forIdentifier: identifier)
let _ = emitter.promiseSendMessage(message, withIdentifier: identifier)
.flatMap { _ -> Future<Void,BlackholeError> in
return self.emitter.promiseSendMessage(message, withIdentifier: identifier)
}
.flatMap { _ -> Future<Void,BlackholeError> in
return self.emitter.promiseSendMessage(message, withIdentifier: identifier)
}
.onSuccess {
sendExpectation.fulfill()
}
.onFailure { error in
XCTAssert(false, "Error sending: \(error)")
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
}
| 36.451613 | 115 | 0.59646 |
3a09020e76024f69003d166489fecdd0dc293f7c | 296 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "LTHRadioButton",
products: [
.library(
name: "LTHRadioButton",
targets: ["LTHRadioButton"]
),
],
targets: [
.target(
name: "LTHRadioButton",
dependencies: [],
path: "source"
),
]
)
| 14.095238 | 29 | 0.625 |
140b2e49498834391e7b6c8c61502d40dcc9cab0 | 2,739 | //
// SpecialSeriesViewModel.swift
// LoveQiYi
//
// Created by mac on 2019/7/22.
// Copyright © 2019 bingdaohuoshan. All rights reserved.
//
import UIKit
import NicooNetwork
class SpecialSeriesViewModel: NSObject {
private lazy var specialApi: SpecialSerialApi = {
let api = SpecialSerialApi()
api.paramSource = self
api.delegate = self
return api
}()
private lazy var videoListApi: VideoListApi = {
let api = VideoListApi()
api.paramSource = self
api.delegate = self
return api
}()
///精选系列成功失败回调
var successHandler: ((_ model: SpecialSerialListModel, _ page: Int)->())?
var failureHandler: ((_ errorMsg: String) ->())?
///系列详情列表成功失败回调
var seriesDetailListSuccessHandler: ((_ model: VideoListModel, _ page: Int) ->())?
var seriesDetailListFailureHandler: ((_ errorMsg: String) ->())?
var paramDic: [String: Any]?
///精选系列的列表数组
var seriesVideoList: [SpecialSerialModel]?
}
extension SpecialSeriesViewModel {
//MARK: 精选系列的列表数据
func loadSerialVideoListData() {
let _ = specialApi.loadData()
}
func loadNextPage() {
let _ = specialApi.loadNextPage()
}
//MARK:系列详情列表数据
func loadSeriesVideoListData(_ params: [String: Any]?) {
paramDic = params
let _ = videoListApi.loadData()
}
func loadSeriesVideoListNextPage() {
let _ = videoListApi.loadNextPage()
}
}
extension SpecialSeriesViewModel: NicooAPIManagerParamSourceDelegate, NicooAPIManagerCallbackDelegate {
func paramsForAPI(_ manager: NicooBaseAPIManager) -> [String : Any]? {
if manager is VideoListApi {
return paramDic
}
return nil
}
func managerCallAPISuccess(_ manager: NicooBaseAPIManager) {
if manager is SpecialSerialApi {
if let specialSerialList = manager.fetchJSONData(SpecialSerialReformer()) as? SpecialSerialListModel {
self.seriesVideoList = specialSerialList.data
successHandler?(specialSerialList, specialApi.pageNumber)
}
}
if manager is VideoListApi {
if let seriesDetail = manager.fetchJSONData(HotReformer()) as? VideoListModel {
seriesDetailListSuccessHandler?(seriesDetail, videoListApi.pageNumber)
}
}
}
func managerCallAPIFailed(_ manager: NicooBaseAPIManager) {
if manager is SpecialSerialApi {
failureHandler?(manager.errorMessage)
}
if manager is VideoListApi {
seriesDetailListFailureHandler?(manager.errorMessage)
}
}
}
| 26.592233 | 114 | 0.627601 |
87e5bfa1f71c0de9001a309c774efdc4411af069 | 5,791 | // Copyright (c) 2016 Meteor Development Group, Inc.
//
// 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 Apollo
private extension GraphQLQuery {
func parse(data: JSONObject) throws -> Data {
return try Data(map: GraphQLMap(jsonObject: data))
}
}
class ParseQueryResultDataTests: XCTestCase {
func testHeroNameQuery() throws {
let data = ["hero": ["__typename": "Droid", "name": "R2-D2"]]
let query = HeroNameQuery()
let result = try query.parse(data: data)
XCTAssertEqual(result.hero?.name, "R2-D2")
}
func testHeroNameQueryWithMissingValue() {
let data = ["hero": ["__typename": "Droid"]]
let query = HeroNameQuery()
XCTAssertThrowsError(try query.parse(data: data)) { error in
if case JSONDecodingError.missingValue(let key) = error {
XCTAssertEqual(key, "name")
} else {
XCTFail("Unexpected error: \(error)")
}
}
}
func testHeroNameQueryWithWrongType() {
let data = ["hero": ["__typename": "Droid", "name": 10]]
let query = HeroNameQuery()
XCTAssertThrowsError(try query.parse(data: data)) { error in
if case JSONDecodingError.couldNotConvert(let value, let expectedType) = error {
XCTAssertEqual(value as? Int, 10)
XCTAssertTrue(expectedType == String.self)
} else {
XCTFail("Unexpected error: \(error)")
}
}
}
func testHeroAndFriendsNamesQuery() throws {
let data = [
"hero": [
"name": "R2-D2",
"__typename": "Droid",
"friends": [
["__typename": "Human", "name": "Luke Skywalker"],
["__typename": "Human", "name": "Han Solo"],
["__typename": "Human", "name": "Leia Organa"]
]
]
]
let query = HeroAndFriendsNamesQuery(episode: .jedi)
let result = try query.parse(data: data)
XCTAssertEqual(result.hero?.name, "R2-D2")
let friendsNames = result.hero?.friends?.flatMap { $0?.name }
XCTAssertEqual(friendsNames!, ["Luke Skywalker", "Han Solo", "Leia Organa"])
}
func testHeroAppearsInQuery() throws {
let data = ["hero": ["__typename": "Droid", "name": "R2-D2", "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]]]
let query = HeroAppearsInQuery()
let result = try query.parse(data: data)
XCTAssertEqual(result.hero?.name, "R2-D2")
let episodes = result.hero?.appearsIn.flatMap { $0 }
XCTAssertEqual(episodes!, [.newhope, .empire, .jedi])
}
func testTwoHeroesQuery() throws {
let data = ["r2": ["__typename": "Droid", "name": "R2-D2"], "luke": ["__typename": "Human", "name": "Luke Skywalker"]]
let query = TwoHeroesQuery()
let result = try query.parse(data: data)
XCTAssertEqual(result.r2?.name, "R2-D2")
XCTAssertEqual(result.luke?.name, "Luke Skywalker")
}
func testHeroDetailsQueryHuman() throws {
let data = ["hero": ["__typename": "Human", "name": "Luke Skywalker", "height": 1.72]]
let query = HeroDetailsQuery(episode: .empire)
let result = try query.parse(data: data)
guard let human = result.hero?.asHuman else {
XCTFail("Wrong type")
return
}
XCTAssertEqual(human.height, 1.72)
}
func testHeroDetailsQueryDroid() throws {
let data = ["hero": ["__typename": "Droid", "name": "R2-D2", "primaryFunction": "Astromech"]]
let query = HeroDetailsQuery()
let result = try query.parse(data: data)
guard let droid = result.hero?.asDroid else {
XCTFail("Wrong type")
return
}
XCTAssertEqual(droid.primaryFunction, "Astromech")
}
func testHeroDetailsQueryUnknownTypename() throws {
let data = ["hero": ["__typename": "Pokemon", "name": "Charmander"]]
let query = HeroDetailsQuery()
let result = try query.parse(data: data)
XCTAssertEqual(result.hero?.name, "Charmander")
}
func testHeroDetailsQueryMissingTypename() throws {
let data = ["hero": ["name": "Luke Skywalker", "height": 1.72]]
let query = HeroDetailsQuery(episode: .empire)
XCTAssertThrowsError(try query.parse(data: data)) { error in
if case JSONDecodingError.missingValue(let key) = error {
XCTAssertEqual(key, "__typename")
} else {
XCTFail("Unexpected error: \(error)")
}
}
}
func testHeroDetailsFragmentQueryHuman() throws {
let data = ["hero": ["__typename": "Human", "name": "Luke Skywalker", "height": 1.72]]
let query = HeroDetailsWithFragmentQuery()
let result = try query.parse(data: data)
guard let human = result.hero?.fragments.heroDetails.asHuman else {
XCTFail("Wrong type")
return
}
XCTAssertEqual(human.height, 1.72)
}
}
| 33.473988 | 122 | 0.647729 |
e8e2520716974b6a1f849e67d698be0890f375e4 | 4,305 | //
// InteractionPresenterTests.swift
// ApptentiveKit
//
// Created by Frank Schmitt on 8/4/20.
// Copyright © 2020 Apptentive, Inc. All rights reserved.
//
import XCTest
@testable import ApptentiveKit
class InteractionPresenterTests: XCTestCase {
var interactionPresenter: InteractionPresenter?
override func setUp() {
self.interactionPresenter = FakeInteractionPresenter()
self.interactionPresenter?.delegate = SpyInteractionDelegate()
}
func testShowAppleRatingDialog() throws {
let interaction = try InteractionTestHelpers.loadInteraction(named: "AppleRatingDialog")
XCTAssertNoThrow(try self.interactionPresenter?.presentInteraction(interaction))
}
func testPresentEnjoymentDialog() throws {
try self.presentInteraction(try InteractionTestHelpers.loadInteraction(named: "EnjoymentDialog"))
}
func testPresentSurvey() throws {
try self.presentInteraction(try InteractionTestHelpers.loadInteraction(named: "Survey"))
}
func testPresentTextModal() throws {
try self.presentInteraction(try InteractionTestHelpers.loadInteraction(named: "TextModal"))
}
func testPresentUnimplemented() throws {
let fakeInteractionString = """
{
"id": "abc123",
"type": "FakeInteraction",
}
"""
guard let fakeInteractionData = fakeInteractionString.data(using: .utf8) else {
return XCTFail("Unable to encode test fake interaction string")
}
let fakeInteraction = try JSONDecoder().decode(Interaction.self, from: fakeInteractionData)
XCTAssertThrowsError(try self.presentInteraction(fakeInteraction))
}
class FakeInteractionPresenter: InteractionPresenter {
var viewModel: AnyObject?
override func presentSurvey(with viewModel: SurveyViewModel) throws {
self.viewModel = viewModel
let fakeSurveyViewController = UIViewController()
fakeSurveyViewController.view.tag = 333
try self.presentViewController(fakeSurveyViewController)
}
override func presentEnjoymentDialog(with viewModel: EnjoymentDialogViewModel) throws {
self.viewModel = viewModel
let fakeAlertController = UIViewController()
fakeAlertController.view.tag = 333
try self.presentViewController(fakeAlertController)
}
override func presentTextModal(with viewModel: TextModalViewModel) throws {
self.viewModel = viewModel
let fakeAlertController = UIViewController()
fakeAlertController.view.tag = 333
try self.presentViewController(fakeAlertController)
}
}
class FakePresentingViewController: UIViewController {
var fakePresentedViewController: UIViewController?
init() {
super.init(nibName: nil, bundle: nil)
self.view = FakeView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
self.fakePresentedViewController = viewControllerToPresent
}
override var isViewLoaded: Bool {
return true
}
}
class FakeView: UIView {
override var window: UIWindow {
return UIWindow()
}
}
private func presentInteraction(_ interaction: Interaction) throws {
guard let interactionPresenter = self.interactionPresenter as? FakeInteractionPresenter else {
return XCTFail("interactionPresenter is nil or not a FakeInteractionPresenter")
}
XCTAssertThrowsError(try interactionPresenter.presentInteraction(interaction, from: nil))
let viewController = FakePresentingViewController()
try interactionPresenter.presentInteraction(interaction, from: viewController)
XCTAssertNotNil(interactionPresenter.viewModel)
XCTAssertEqual(viewController, interactionPresenter.presentingViewController)
XCTAssertEqual(viewController.fakePresentedViewController?.view.tag, 333)
}
}
| 33.632813 | 130 | 0.681301 |
f9f08f27523c171d170ed7f7c797ca846796f074 | 1,882 | //
// ProfileEditor.swift
// Landmarks
//
// Created by 云飛 on 7/28/20.
// Copyright © 2020 Apple. All rights reserved.
//
import SwiftUI
struct ProfileEditor: View {
@Binding var profile:Profile
var dateRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .year, value: -1, to: profile.goalDate)!
let max = Calendar.current.date(byAdding: .year, value: 1, to: profile.goalDate)!
return min...max
}
var body: some View {
List{
HStack{
Text("Username").bold()
Divider()
TextField("Username",text: $profile.username)
}
Toggle(isOn: $profile.prefersNotifications){
Text("Enable Notifications")
}
VStack(alignment: .leading, spacing: 20) {
Text("Seasonal Photo").bold()
Picker("Seasonal Photo", selection: $profile.seasonalPhoto) {
ForEach(Profile.Season.allCases, id: \.self) { season in
Text(season.rawValue).tag(season)
}
}
.pickerStyle(SegmentedPickerStyle())
}
.padding(.top)
VStack(alignment: .leading, spacing: 20) {
Text("Goal Date").bold()
DatePicker(
"Goal Date",
selection: $profile.goalDate,
in: dateRange,
displayedComponents: .date)
}
.padding(.top)
}
}
}
struct ProfileEditor_Previews: PreviewProvider {
static var previews: some View {
ProfileEditor(profile:.constant(.default))
}
}
| 32.448276 | 90 | 0.47237 |
ed323c790f4379b888c3516f9d8c26d95602d8c0 | 3,450 | //
// DefaultDeviceControllerTests.swift
// AmazonChimeSDK
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
@testable import AmazonChimeSDK
import AmazonChimeSDKMedia
import AVFoundation
import Mockingbird
import XCTest
class DefaultDeviceControllerTests: XCTestCase {
var audioSessionMock: AudioSessionMock!
var videoClientControllerMock: VideoClientControllerMock!
var loggerMock: LoggerMock!
var defaultDeviceController: DefaultDeviceController!
var eventAnalyticsControllerMock: EventAnalyticsControllerMock!
override func setUp() {
videoClientControllerMock = mock(VideoClientController.self)
eventAnalyticsControllerMock = mock(EventAnalyticsController.self)
loggerMock = mock(Logger.self)
let route = AVAudioSession.sharedInstance().currentRoute
audioSessionMock = mock(AudioSession.self)
given(audioSessionMock.getCurrentRoute()).willReturn(route)
defaultDeviceController = DefaultDeviceController(audioSession: audioSessionMock,
videoClientController: videoClientControllerMock,
eventAnalyticsController: eventAnalyticsControllerMock,
logger: loggerMock)
}
func testListAudioDevices() {
let availableInputs = AVAudioSession.sharedInstance().availableInputs
given(audioSessionMock.getAvailableInputs()).willReturn(availableInputs)
let audioDevices = defaultDeviceController.listAudioDevices()
XCTAssertTrue(!audioDevices.isEmpty)
XCTAssertEqual(audioDevices[1].type, MediaDeviceType.audioBuiltInSpeaker)
XCTAssertEqual(audioDevices[1].label, "Built-in Speaker")
}
func testChooseAudioDevice_speaker() {
let speakerDevice = MediaDevice(label: "Built-in Speaker")
defaultDeviceController.chooseAudioDevice(mediaDevice: speakerDevice)
verify(audioSessionMock.overrideOutputAudioPort(.speaker)).wasCalled()
}
func testChooseAudioDevice_nonSpeaker() {
let availableInputs = AVAudioSession.sharedInstance().availableInputs
let nonSpeakerDevice = MediaDevice.fromAVSessionPort(port: (availableInputs?[0])!)
defaultDeviceController.chooseAudioDevice(mediaDevice: nonSpeakerDevice)
verify(audioSessionMock.setPreferredInput(nonSpeakerDevice.port)).wasCalled()
}
func testSwitchCamera() {
defaultDeviceController.switchCamera()
verify(videoClientControllerMock.switchCamera()).wasCalled()
}
func testGetCurrentAudioDevice() {
let currentDevice = defaultDeviceController.getActiveAudioDevice()
let route = AVAudioSession.sharedInstance().currentRoute
var expected: MediaDevice?
if route.outputs.count > 0 {
if route.outputs[0].portType == .builtInSpeaker {
expected = MediaDevice(label: "Built-in Speaker", type: MediaDeviceType.audioBuiltInSpeaker)
} else if route.inputs.count > 0 {
expected = MediaDevice.fromAVSessionPort(port: route.inputs[0])
}
}
verify(audioSessionMock.getCurrentRoute()).wasCalled(2)
XCTAssertEqual(currentDevice?.label, expected?.label)
XCTAssertEqual(currentDevice?.type, expected?.type)
}
}
| 41.071429 | 113 | 0.703188 |
01831e90066e4453b553b74455505607b42673a2 | 2,389 | import RxRelay
import RxSwift
import KeychainAccess
struct AuthenticationRepository {
static var isStoring: Bool { storing.value }
static var storing: BehaviorRelay<Bool> = {
let initialValue = (find() != nil)
return BehaviorRelay<Bool>(value: initialValue)
}()
}
// MARK: - CRUD
extension AuthenticationRepository {
static func find() -> Authentication? {
let accessToken = keychain["access_token"]
if let accessToken = accessToken {
return Authentication(accessToken: accessToken)
}
return nil
}
static func destroy() -> Single<Bool> {
clear()
guard let authentication = find() else {
return Single.just(true)
}
return API
.provider
.rx
.request(.signout(accessToken: authentication.accessToken))
.map { response in
return response.statusCode == 204
}
}
static func save(_ authentication: Authentication) {
keychain["access_token"] = authentication.accessToken
Self.storing.accept(true)
}
}
// MARK: - API
extension AuthenticationRepository {
/// 認証API仕様
/// - Note: https://unsplash.com/documentation#user-authentication
/// - Note: 認証の前段部はSigninViewControllerのSFAuthenticationSession
static func apply(code: String) -> Single<Authentication> {
return API
.provider
.rx
.request(.signin(id: OAuthService.clientId,
secret: OAuthService.clientSecret,
code: code))
.map { response -> Authentication in
if let authentication: Authentication = Authentication.from(data: response.data) {
return authentication
} else {
throw APIError.mappingError
}
}.do(
onSuccess: { authentication in
save(authentication)
},
onError: { error in
Debugger.shared.error("[MINQ][AUTHENTICATION_ERROR] \(error)")
}
)
}
}
// MARK: - MISC
private extension AuthenticationRepository {
static func clear() {
do {
try keychain.remove("access_token")
Self.storing.accept(false)
} catch {
Debugger.shared.error("[MINQ][AUTHENTICATION_ERROR] \(error)")
}
}
static var keychain: Keychain = {
let keychain = Keychain(service: "cptechtask")
.synchronizable(false)
.accessibility(Accessibility.afterFirstUnlockThisDeviceOnly)
return keychain
}()
}
| 25.688172 | 90 | 0.646714 |
72e4c811c402a5e588955e38f8f8e2f0522e40f6 | 4,296 | //
// PTPDeviceInfo.swift
// Rocc
//
// Created by Simon Mitchell on 03/11/2019.
// Copyright © 2019 Simon Mitchell. All rights reserved.
//
import Foundation
extension PTP {
/// A structural representation of a PTP device's info
struct DeviceInfo {
let version: Word
let vendorExtensionId: DWord
let vendorExtensionVersion: Word
let vendorExtensionDescription: String
let functionalMode: Word
var supportedOperations: [CommandCode]
var supportedEventCodes: [EventCode]
var supportedDeviceProperties: [DeviceProperty.Code]
let supportedCaptureFormats: [Word]
let supportedImageFormats: [FileFormat]
let manufacturer: String
let model: String?
let deviceVersion: String?
let serialNumber: String?
/// Allocates device info from a data buffer
///
/// - Note: Credit to [libgphoto2](https://github.com/gphoto/libgphoto2/blob/f55306ff3cc054da193ee1d48c44c95ec283873f/camlibs/ptp2/ptp-pack.c#L369) for breaking down how this works
/// - Parameter data: The data buffer that represents the device info
init?(data: ByteBuffer) {
var offset: UInt = 0
guard let _version: Word = data.read(offset: &offset) else { return nil }
version = _version
guard let _vendorExtensionId: DWord = data.read(offset: &offset) else { return nil }
vendorExtensionId = _vendorExtensionId
guard let _vendorExtensionVersion: Word = data.read(offset: &offset) else { return nil }
vendorExtensionVersion = _vendorExtensionVersion
guard let _vendorExtensionDescription: String = data.read(offset: &offset) else { return nil }
vendorExtensionDescription = _vendorExtensionDescription
guard let _functionalMode: Word = data.read(offset: &offset) else { return nil }
functionalMode = _functionalMode
guard let supportedOperationWords: [Word] = data.read(offset: &offset) else { return nil }
supportedOperations = supportedOperationWords.compactMap({ CommandCode(rawValue: $0) })
guard let supportedEventWords: [Word] = data.read(offset: &offset) else { return nil }
supportedEventCodes = supportedEventWords.compactMap({ EventCode(rawValue: $0) })
guard let _supportedDeviceProperties: [Word] = data.read(offset: &offset) else { return nil }
supportedDeviceProperties = _supportedDeviceProperties.compactMap({ DeviceProperty.Code(rawValue: $0) })
guard let _supportedCaptureFormats: [Word] = data.read(offset: &offset) else { return nil }
supportedCaptureFormats = _supportedCaptureFormats
guard let _supportedImageFormats: [Word] = data.read(offset: &offset) else { return nil }
supportedImageFormats = _supportedImageFormats.compactMap({ FileFormat(rawValue: $0) })
guard let _manufacturer: String = data.read(offset: &offset) else { return nil }
manufacturer = _manufacturer
// Above logic is a bit funny... we don't want to carry on if we can't parse the next element
// because the PTP structure is very highly order-oriented
guard let _model: String = data.read(offset: &offset) else {
model = nil
deviceVersion = nil
serialNumber = nil
return
}
model = _model
guard let _deviceVersion: String = data.read(offset: &offset) else {
deviceVersion = nil
serialNumber = nil
return
}
deviceVersion = _deviceVersion
guard let _serialNumber: String = data.read(offset: &offset) else {
serialNumber = nil
return
}
serialNumber = _serialNumber
}
}
}
| 38.702703 | 188 | 0.585661 |
46b59933043779c0c232ad6d5b757b02414912a6 | 5,522 | //===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// A collection whose element type is `Element` but that is always empty.
@frozen // trivial-implementation
public struct EmptyCollection<Element> {
// no properties
/// Creates an instance.
@inlinable // trivial-implementation
public init() {}
}
extension EmptyCollection {
/// An iterator that never produces an element.
@frozen // trivial-implementation
public struct Iterator {
// no properties
/// Creates an instance.
@inlinable // trivial-implementation
public init() {}
}
}
extension EmptyCollection.Iterator: IteratorProtocol, Sequence {
/// Returns `nil`, indicating that there are no more elements.
@inlinable // trivial-implementation
public mutating func next() -> Element? {
return nil
}
}
extension EmptyCollection: Sequence {
/// Returns an empty iterator.
@inlinable // trivial-implementation
public func makeIterator() -> Iterator {
return Iterator()
}
}
extension EmptyCollection: RandomAccessCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias Indices = Range<Int>
public typealias SubSequence = EmptyCollection<Element>
/// Always zero, just like `endIndex`.
@inlinable // trivial-implementation
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
@inlinable // trivial-implementation
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // trivial-implementation
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // trivial-implementation
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
@inlinable // trivial-implementation
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
@inlinable // trivial-implementation
public subscript(bounds: Range<Index>) -> SubSequence {
get {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
@inlinable // trivial-implementation
public var count: Int {
return 0
}
@inlinable // trivial-implementation
public func index(_ i: Index, offsetBy n: Int) -> Index {
_debugPrecondition(i == startIndex && n == 0, "Index out of range")
return i
}
@inlinable // trivial-implementation
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_debugPrecondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
@inlinable // trivial-implementation
public func distance(from start: Index, to end: Index) -> Int {
_debugPrecondition(start == 0, "From must be startIndex (or endIndex)")
_debugPrecondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
@inlinable // trivial-implementation
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_debugPrecondition(index == 0, "out of bounds")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
@inlinable // trivial-implementation
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_debugPrecondition(range == indices, "invalid range for an empty collection")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
}
extension EmptyCollection: Equatable {
@inlinable // trivial-implementation
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
extension EmptyCollection: ConcurrentValue { }
extension EmptyCollection.Iterator: ConcurrentValue { }
| 31.022472 | 83 | 0.673488 |
03accee150d583707dc62c8edc38ab3d328e5ced | 718 | //
// GherkinSyntax.swift
// CarLensUITests
//
import XCTest
extension XCTest {
func given(_ text: String, step: (() -> Void )? = nil) {
XCTContext.runActivity(named: "Given " + text) { _ in
step?()
}
}
func when(_ text: String, step: (() -> Void )? = nil) {
XCTContext.runActivity(named: "When " + text) { _ in
step?()
}
}
func then(_ text: String, step: (() -> Void )? = nil) {
XCTContext.runActivity(named: "Then " + text) { _ in
step?()
}
}
func and(_ text: String, step: (() -> Void )? = nil) {
XCTContext.runActivity(named: "And " + text) { _ in
step?()
}
}
}
| 21.117647 | 61 | 0.477716 |
7a387fd7c2ea7863b341759f4291ce62c0e0b86b | 6,607 | /*
Copyright 2018 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import Reusable
final class TermsView: UIView, NibOwnerLoadable, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var acceptButton: UIButton!
@objc weak var delegate: MXKAuthInputsViewDelegate?
private var acceptedCallback: (()->Void)?
/// NavigationVC to display a policy content
private var navigationController: RiotNavigationController?
/// The list of policies to be accepted by the end user
private var policies: [MXLoginPolicyData] = []
/// Policies already accepted by the end user
/// Combined with `policies`, this is the view model for `tableView`
private var acceptedPolicies: Set<Int> = []
/// The index of the policy being displayed fullscreen within `navigationController`
private var displayedPolicyIndex: Int?
// MARK: - Setup
convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadNibContent()
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
loadNibContent()
commonInit()
}
override func layoutSubviews() {
super.layoutSubviews()
acceptButton.layer.cornerRadius = 5
}
private func commonInit() {
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(TableViewCellWithCheckBoxAndLabel.nib(), forCellReuseIdentifier: TableViewCellWithCheckBoxAndLabel.defaultReuseIdentifier())
acceptButton.clipsToBounds = true
acceptButton.setTitle(NSLocalizedString("accept", tableName: "Vector", comment: ""), for: .normal)
acceptButton.setTitle(NSLocalizedString("accept", tableName: "Vector", comment: ""), for: .highlighted)
customizeViewRendering()
}
func customizeViewRendering() {
self.backgroundColor = UIColor.clear
self.tableView.backgroundColor = UIColor.clear
acceptButton.backgroundColor = ThemeService.shared().theme.tintColor
}
// MARK: - Public
/// Display a list of policies the end user must accept.
///
/// - Parameters:
/// - terms: Terms data sent by the homeserver.
/// - onAccepted: block called when the user has accepted all of them.
@objc func displayTerms(terms: MXLoginTerms, onAccepted: @escaping () -> Void) {
acceptedCallback = onAccepted
let lang: String? = Bundle.mxk_language()
policies = terms.policiesData(forLanguage: lang, defaultLanguage: "en")
acceptedPolicies.removeAll()
reload()
}
// MARK: - Private
private func reload() {
tableView.reloadData()
// Enable the button only if the user has accepted all policies
acceptButton.isEnabled = (policies.count == acceptedPolicies.count)
acceptButton.alpha = acceptButton.isEnabled ? 1 : 0.5
}
@IBAction func didAcceptButtonTapped(_ sender: Any) {
if policies.count == acceptedPolicies.count {
acceptedCallback?()
}
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return policies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellWithCheckBoxAndLabel.defaultReuseIdentifier(), for: indexPath) as! TableViewCellWithCheckBoxAndLabel
let policy = policies[indexPath.row]
let accepted = acceptedPolicies .contains(indexPath.row)
cell.label.text = policy.name
cell.isEnabled = accepted
cell.accessoryType = .disclosureIndicator
cell.backgroundColor = UIColor.clear
if let checkBox = cell.checkBox, checkBox.gestureRecognizers?.isEmpty ?? true {
let gesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapCheckbox))
gesture.numberOfTapsRequired = 1
gesture.numberOfTouchesRequired = 1
checkBox.isUserInteractionEnabled = true
checkBox.tag = indexPath.row
checkBox.addGestureRecognizer(gesture)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.displayPolicy(policyIndex: indexPath.row)
}
@objc private func didTapCheckbox(sender: UITapGestureRecognizer) {
guard let policyIndex = sender.view?.tag else {
return
}
if acceptedPolicies.contains(policyIndex) {
acceptedPolicies.remove(policyIndex)
} else {
acceptedPolicies.insert(policyIndex)
}
reload()
}
// MARK: - Policy content display
func displayPolicy(policyIndex: Int) {
displayedPolicyIndex = policyIndex
let policy = policies[policyIndex]
// Display the policy webpage into our webview
let webViewViewController: WebViewViewController = WebViewViewController(url: policy.url)
webViewViewController.title = policy.name
let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style: .plain, target: self, action:#selector(didTapCancelOnPolicyScreen))
webViewViewController.navigationItem.leftBarButtonItem = leftBarButtonItem
navigationController = RiotNavigationController()
delegate?.authInputsView?(nil, present: navigationController, animated: false)
navigationController?.pushViewController(webViewViewController, animated: false)
}
@objc private func didTapCancelOnPolicyScreen() {
removePolicyScreen()
}
private func removePolicyScreen() {
displayedPolicyIndex = nil
navigationController?.dismiss(animated: false)
navigationController = nil
}
}
| 31.764423 | 178 | 0.689572 |
233911d16b889a76158a75785483002feb35df75 | 404 | //
// UserAPIMockData.swift
// smartPOS
//
// Created by I Am Focused on 23/05/2021.
// Copyright © 2021 Clean Swift LLC. All rights reserved.
//
import Foundation
extension UserAPI {
var sampleData: Data {
switch self {
case .login:
return stubbedResponse("Login")
case .verifyKey:
return stubbedResponse("VerifyKey")
}
}
}
| 18.363636 | 58 | 0.586634 |
18c3cf59e2721905788d71ea647fc9700178c0d6 | 488 | //
// PendingAPI+CoreDataProperties.swift
//
//
// Created by Subramanian on 07/11/17.
//
//
import Foundation
import CoreData
extension PendingAPI {
@nonobjc public class func fetchRequest() -> NSFetchRequest<PendingAPI> {
return NSFetchRequest<PendingAPI>(entityName: "PendingAPI")
}
@NSManaged public var url: String?
@NSManaged public var requestType: String?
@NSManaged public var postBody: String?
@NSManaged public var timeStamp: Double
}
| 19.52 | 77 | 0.706967 |
ffe8a3086e094731622a7ee5e212982a960eaf0c | 2,359 | //
// ImageSet.swift
// swag
//
// Created by Ken on 2018/12/4.
// Copyright © SWAG. All rights reserved.
//
import Foundation
@objcMembers
public class ImageSet: NSObject {
let pathBuilder: (Int, Int) -> URL
public init(builder: @escaping (_ width: Int, _ height: Int) -> URL) {
self.pathBuilder = builder
super.init()
}
lazy public var thumbnail: URL = pathBuilder(ImageSize.thumbnail.width, ImageSize.thumbnail.height)
lazy public var small: URL = pathBuilder(ImageSize.small.width, ImageSize.small.height)
lazy public var medium: URL = pathBuilder(ImageSize.medium.width, ImageSize.medium.height)
lazy public var large: URL = pathBuilder(ImageSize.large.width, ImageSize.large.height)
lazy public var extraLarge: URL = pathBuilder(ImageSize.extraLarge.width, ImageSize.extraLarge.height)
lazy public var fullscreen: URL = pathBuilder(ImageSize.fullscreen.width, ImageSize.fullscreen.height)
lazy public var all: [URL] = [thumbnail, small, medium, large, fullscreen]
}
public struct ImageSize {
//2^n, 11 => 2^11 = 2048
static private let maximumSupportPowerOfTwo: Int = 11
static private var maximumSupportSizeWidth: Int {
return NSDecimalNumber(decimal: pow(2, maximumSupportPowerOfTwo)).intValue
}
static private var coerceInPowerOfTwo: Int {
let screenMaxWidth = max(Int(UIScreen.main.bounds.size.width),
Int(UIScreen.main.bounds.size.height)) * Int(UIScreen.main.scale)
let coerceInPowerOfTwo = (5...maximumSupportPowerOfTwo)
.map({ NSDecimalNumber(decimal: pow(2, $0)).intValue })
.filter({ Int($0) >= screenMaxWidth })
.first ?? maximumSupportSizeWidth
return min(coerceInPowerOfTwo, maximumSupportSizeWidth)
}
public let width, height: Int
static public let thumbnail = ImageSize(width: 64, height: 64)
static public let small = ImageSize(width: 128, height: 128)
static public let medium = ImageSize(width: 256, height: 256)
static public let large = ImageSize(width: 512, height: 512)
static public let extraLarge = ImageSize(width: 1024, height: 1024)
static public let fullscreen = ImageSize(width: coerceInPowerOfTwo, height: coerceInPowerOfTwo)
}
| 34.691176 | 106 | 0.67783 |
62b1f3d6ebda853a715d995d2655ad74e66b8bfd | 3,154 | //
// RatingHelper.swift
// CriticalMaps
//
// Created by Leonard Thomas on 5/24/19.
// Copyright © 2019 Pokus Labs. All rights reserved.
//
import Foundation
import StoreKit
@available(iOS 10.3, *)
extension SKStoreReviewController: RatingRequest {}
public protocol RatingRequest {
static func requestReview()
}
public class RatingHelper {
public var daysUntilPrompt = 1
public var usesUntilPrompt = 5
private let userDefaults: UserDefaults
private let ratingRequest: RatingRequest.Type
private let currentVersion: String
@available(iOS 10.3, *)
public init(defaults: UserDefaults = UserDefaults.standard,
ratingRequest: RatingRequest.Type = SKStoreReviewController.self,
currentVersion: String = Bundle.main.versionNumber + Bundle.main.buildNumber) {
userDefaults = defaults
self.ratingRequest = ratingRequest
self.currentVersion = currentVersion
}
public func onLaunch() {
onEvent()
}
public func onEnterForeground() {
onEvent()
}
private func onEvent() {
resetCounterIfneeded()
increaseDaysCounterIfNeeded()
usesCounter += 1
rateIfNeeded()
}
private var lastDayUsed: Date? {
set {
userDefaults.set(newValue?.timeIntervalSince1970, forKey: #function)
}
get {
guard userDefaults.value(forKey: #function) != nil else {
return nil
}
let timeInterval = userDefaults.double(forKey: #function)
return Date(timeIntervalSince1970: timeInterval)
}
}
private var daysCounter: Int {
set {
userDefaults.set(newValue, forKey: #function)
}
get {
userDefaults.integer(forKey: #function)
}
}
private var usesCounter: Int {
set {
userDefaults.set(newValue, forKey: #function)
}
get {
userDefaults.integer(forKey: #function)
}
}
private var lastRatedVersion: String? {
set {
userDefaults.set(newValue, forKey: #function)
}
get {
userDefaults.string(forKey: #function)
}
}
private var shouldPromptRatingRequest: Bool {
daysCounter >= daysUntilPrompt &&
usesCounter >= usesUntilPrompt &&
currentVersion != lastRatedVersion
}
private func increaseDaysCounterIfNeeded() {
let now = Date()
if let date = lastDayUsed {
let components = Calendar.current.dateComponents([.day], from: date, to: now)
daysCounter += components.day ?? 0
}
lastDayUsed = now
}
private func rateIfNeeded() {
if shouldPromptRatingRequest {
ratingRequest.requestReview()
lastRatedVersion = currentVersion
}
}
private func resetCounterIfneeded() {
// we set the counter to 0 if we installed a new version
if usesCounter != 0, lastRatedVersion == currentVersion {
usesCounter = 0
daysCounter = 0
}
}
}
| 26.066116 | 95 | 0.602727 |
5b0a72b666bca01e9e91f4feca1a9ac8d17b1215 | 1,292 | import Foundation
extension ApiErrors {
/// Method checks if it is necessary to have two factor authentication
/// to get access to account.
/// - Parameters:
/// - handler: Object that execute TFA initiation
/// - initiateTFA: Flag that defines if initiation of TFA is needed
/// - onCompletion: Completion block that will be executed after the finish of TFA initiation
/// - result: The member of `TFAResult`
/// - onNoTFA: Block of code that will be executed if TFA is not required
public func checkTFARequired(
handler: TFAHandlerProtocol,
initiateTFA: Bool,
onCompletion: @escaping (_ result: TFAResult) -> Void,
onNoTFA: @escaping () -> Void
) {
if let error = self.firstErrorWith(
status: ApiError.Status.forbidden,
code: ApiError.Code.tfaRequired
), let meta = error.tfaMeta {
if initiateTFA {
handler.initiateTFA(
meta: meta,
completion: { tfaResult in
onCompletion(tfaResult)
})
} else {
onCompletion(.failure(self))
}
} else {
onNoTFA()
}
}
}
| 33.128205 | 99 | 0.548762 |
e5a095d935dfbf74ee0f3356b49c83708cef480e | 3,614 | //
// CookiesViewController.swift
// CookieManager
//
// Created by koogawa on 2017/03/25.
// Copyright © 2017 koogawa. All rights reserved.
//
import UIKit
public class CookiesViewController: UITableViewController {
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "Cookie Manager"
let cancelButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel,
target: self,
action: #selector(CookiesViewController.didTapCancelButton))
self.navigationItem.leftBarButtonItem = cancelButtonItem
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Private method
@objc private func didTapCancelButton() {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Table view delegate
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cookies = HTTPCookieStorage.shared.cookies else {
return
}
let cookieViewController = CookieViewController()
cookieViewController.cookie = cookies[indexPath.row]
self.navigationController?.pushViewController(cookieViewController, animated: true)
}
// MARK: - Table view data source
override public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let cookies = HTTPCookieStorage.shared.cookies {
return cookies.count
}
return 0
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "reuseIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
cell?.accessoryType = .disclosureIndicator
}
// Configure the cell...
if let cookies = HTTPCookieStorage.shared.cookies {
let cookie = cookies[indexPath.row]
cell?.textLabel?.text = cookie.domain
cell?.detailTextLabel?.text = "\(cookie.name) = \(cookie.value)"
}
return cell!
}
// Override to support editing the table view.
override public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard let cookies = HTTPCookieStorage.shared.cookies else {
return
}
if editingStyle == .delete {
// Delete the cookie from the cookie storage
let cookie = cookies[indexPath.row]
HTTPCookieStorage.shared.deleteCookie(cookie)
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
| 35.087379 | 143 | 0.653293 |
8946b7ca29fa5a785df7260847f9adeb2588591c | 2,367 | //
// SceneDelegate.swift
// client-chat-application
//
// Created by Sashen Pillay on 2020/04/24.
// Copyright © 2020 Sashen Pillay. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.833333 | 147 | 0.714829 |
1a36eed36770ed6412d66cdd962651a112563ce0 | 875 | //
// HomeViewModel.swift
// APICall-SwiftUI
//
// Created by Keerthi on 27/08/20.
// Copyright © 2020 Hxtreme. All rights reserved.
//
import SwiftUI
class HomeViewModel: ObservableObject {
private let providerProtocol: RequestProviderProtocol!
@Published var albums = [Album]()
init(provider: RequestProviderProtocol) {
self.providerProtocol = provider
}
func getAlbumList() {
let parameters = [String: AnyObject]()
providerProtocol.request(type: [Album].self, service: Request.getPhotos(parameters: parameters)) { (response) in
switch response {
case .success(let result):
DispatchQueue.main.async {
self.albums = result
}
case .failure:
break
}
}
}
}
| 23.648649 | 120 | 0.566857 |
298c8d549d8229fa63fc68f58324c636bb721eca | 1,429 | /*****************************************************************************************************
* Copyright 2016 SPECURE GmbH
*
* 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 UIKit
///
class BasicRequestBuilder: AbstractBasicRequestBuilder {
///
override class func addBasicRequestValues(_ basicRequest: BasicRequest) {
super.addBasicRequestValues(basicRequest)
let currentDevice = UIDevice.current
// basicRequest.device = currentDevice.model
basicRequest.device = UIDeviceHardware.platform()
basicRequest.model = UIDeviceHardware.platform()
basicRequest.osVersion = currentDevice.systemVersion
basicRequest.platform = "iOS"
basicRequest.plattform = "iOS"
basicRequest.clientType = "MOBILE"
}
}
| 36.641026 | 103 | 0.623513 |
f5976069084aec1bc54faf7c312fca3312f21957 | 1,434 | //
// ViewController.swift
// SBPickerSwiftSelectorExample
//
// Created by Santiago Bustamante on 1/25/19.
// Copyright © 2019 Busta. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showPickerAction(_ sender: UIButton) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM"
let date = dateFormatter.date(from: "1989-10")!
SBPickerSwiftSelector(mode: SBPickerSwiftSelector.Mode.text, data: [["hi","there"],["1","2","3"], ["a", "b"]], defaultDate: date, componentForSelectedRows: [0: 1, 1: 1, 2: 1]).cancel {
print("cancel")
}.set { values in
if let values = values as? [String] {
print(values)
sender.setTitle(values[0], for: UIControl.State.normal)
} else if let values = values as? [Date] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM"
print(dateFormatter.string(from: values[0]))
sender.setTitle(values[0].description(with: Locale.current), for: UIControl.State.normal)
}
}.present(into: self)
}
}
| 29.875 | 192 | 0.53417 |
ac30211755e64048f913d0ffe08fe2f4f4928c5b | 446 | //
// SaveMonthCategoryTests.swift
// SwiftYNABTests
//
// Created by Andre Bocchini on 5/4/19.
// Copyright © 2019 Andre Bocchini. All rights reserved.
//
import XCTest
@testable import SwiftYNAB
class SaveMonthCategoryTests: XCTestCase {
func testSaveMonthCategoryEncoding() {
let saveMonthCategory = SaveMonthCategory(budgeted: 0)
XCTAssertNoThrow(try TestingTools.testEncoding(saveMonthCategory))
}
}
| 21.238095 | 74 | 0.724215 |
1efa98ad7355227559139df8febf67adfa00944f | 35,636 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import XCTest // Clang module
import CoreGraphics
/// Returns the current test case, so we can use free functions instead of methods for the overlay.
@_silgen_name("_XCTCurrentTestCaseBridge") func _XCTCurrentTestCaseBridge() -> XCTestCase
// --- Failure Formatting ---
/// Register the failure, expected or unexpected, of the current test case.
func _XCTRegisterFailure(expected: Bool, _ condition: String, _ message: String, _ file: String, _ line: UInt) -> Void {
// Call the real _XCTFailureHandler.
let test = _XCTCurrentTestCaseBridge()
_XCTPreformattedFailureHandler(test, expected, file, line, condition, message)
}
/// Produce a failure description for the given assertion type.
func _XCTFailureDescription(assertionType: _XCTAssertionType, _ formatIndex: UInt, _ expressionStrings: CVarArgType...) -> String {
// In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay,
// we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be
// treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't
// stringify the expressions, only their values.) This way we don't have to introduce a new
// BOOL parameter to this semi-internal function and coordinate that across builds.
//
// Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just
// add the formatIndex adjustment there rather than in all of the individual calls to this
// function.
return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings)
}
// --- Exception Support ---
@_silgen_name("_XCTRunThrowableBlockBridge")
func _XCTRunThrowableBlockBridge(@noescape _: @convention(block) () -> Void) -> NSDictionary
/// The Swift-style result of evaluating a block which may throw an exception.
enum _XCTThrowableBlockResult {
case Success
case FailedWithException(className: String, name: String, reason: String)
case FailedWithUnknownException
}
/// Asks some Objective-C code to evaluate a block which may throw an exception,
/// and if it does consume the exception and return information about it.
func _XCTRunThrowableBlock(@noescape block: () -> Void) -> _XCTThrowableBlockResult {
let d = _XCTRunThrowableBlockBridge(block)
if d.count > 0 {
let t: String = d["type"] as! String
if t == "objc" {
return .FailedWithException(className: d["className"] as! String, name: d["name"] as! String, reason: d["reason"] as! String)
} else {
return .FailedWithUnknownException
}
} else {
return .Success
}
}
// --- Supported Assertions ---
public func XCTFail(message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Fail
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line)
}
public func XCTAssertNil(@autoclosure expression: () -> Any?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Nil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = expression()
}
switch result {
case .Success:
// test both Optional and value to treat .None and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = false
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = true
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotNil(@autoclosure expression: () -> Any?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotNil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = expression()
}
switch result {
case .Success:
// test both Optional and value to treat .None and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = true
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = false
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssert( @autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
// XCTAssert is just a cover for XCTAssertTrue.
XCTAssertTrue(expression, message, file: file, line: line);
}
public func XCTAssertTrue(@autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.True
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = expression().boolValue
}
switch result {
case .Success:
let expressionValue = expressionValueOptional!
if !expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertFalse(@autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.False
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = expression().boolValue
}
switch result {
case .Success:
let expressionValue = expressionValueOptional!
if expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () -> T?, @autoclosure _ expression2: () -> T?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
if expressionValue1Optional != expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1Optional)"
let expressionValueStr2 = "\(expressionValue2Optional)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () -> ArraySlice<T>, @autoclosure _ expression2: () -> ArraySlice<T>, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Equal
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () -> ContiguousArray<T>, @autoclosure _ expression2: () -> ContiguousArray<T>, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Equal
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () -> [T], @autoclosure _ expression2: () -> [T], _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Equal
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T, U : Equatable>(@autoclosure expression1: () -> [T: U], @autoclosure _ expression2: () -> [T: U], _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Equal
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () -> T?, @autoclosure _ expression2: () -> T?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
if expressionValue1Optional == expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1Optional)"
let expressionValueStr2 = "\(expressionValue2Optional)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertNotEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () -> ContiguousArray<T>, @autoclosure _ expression2: () -> ContiguousArray<T>, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotEqual
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () -> ArraySlice<T>, @autoclosure _ expression2: () -> ArraySlice<T>, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotEqual
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () -> [T], @autoclosure _ expression2: () -> [T], _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T, U : Equatable>(@autoclosure expression1: () -> [T: U], @autoclosure _ expression2: () -> [T: U], _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckEqualWithAccuracy_Double(value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_Float(value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_CGFloat(value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
public func XCTAssertEqualWithAccuracy<T : FloatingPointType>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, accuracy: T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.EqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var equalWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertEqualWithAccuracy")
}
if !equalWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckNotEqualWithAccuracy_Double(value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_Float(value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_CGFloat(value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
public func XCTAssertNotEqualWithAccuracy<T : FloatingPointType>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, _ accuracy: T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.NotEqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var notEqualWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqualWithAccuracy")
}
if !notEqualWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThan<T : Comparable>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.GreaterThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 > expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThanOrEqual<T : Comparable>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__)
{
let assertionType = _XCTAssertionType.GreaterThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 >= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThan<T : Comparable>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.LessThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 < expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThanOrEqual<T : Comparable>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__)
{
let assertionType = _XCTAssertionType.LessThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = expression1()
expressionValue2Optional = expression2()
}
switch result {
case .Success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 <= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .FailedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .FailedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
#if XCTEST_ENABLE_EXCEPTION_ASSERTIONS
// --- Currently-Unsupported Assertions ---
public func XCTAssertThrows(@autoclosure expression: () -> Any?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Assertion_Throws
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecific(@autoclosure expression: () -> Any?, _ exception: Any, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Assertion_ThrowsSpecific
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecificNamed(@autoclosure expression: () -> Any?, _ exception: Any, _ name: String, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Assertion_ThrowsSpecificNamed
// FIXME: Unsupported
}
public func XCTAssertNoThrow(@autoclosure expression: () -> Any?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Assertion_NoThrow
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecific(@autoclosure expression: () -> Any?, _ exception: Any, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Assertion_NoThrowSpecific
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecificNamed(@autoclosure expression: () -> Any?, _ exception: Any, _ name: String, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
let assertionType = _XCTAssertionType.Assertion_NoThrowSpecificNamed
// FIXME: Unsupported
}
#endif
| 40.130631 | 233 | 0.72612 |
09a896319997426fba5b69936a06d1e6acb96413 | 2,201 | import Quick
import Nimble
@testable import RInAppMessaging
class UIViewExtensionsSpec: QuickSpec {
override func spec() {
describe("UIView+IAM") {
context("when calling findIAMViewSubview method") {
let iamView = BaseViewTestObject()
it("will find IAM view as a direct subview") {
let testView = UIView()
testView.addSubview(UIView())
testView.addSubview(iamView)
testView.addSubview(UIView())
expect(testView.findIAMViewSubview()).to(beIdenticalTo(iamView))
}
it("will find IAM view as a nested subview") {
let testView = UIView()
testView.addSubview(UIView())
testView.addSubview(UIView())
testView.subviews[0].addSubview(UIView())
testView.subviews[0].addSubview(UIView())
testView.subviews[0].subviews[1].addSubview(iamView)
expect(testView.findIAMViewSubview()).to(beIdenticalTo(iamView))
}
it("will find an instance of FullScreenView") {
let testView = UIView()
let fsView = FullScreenView(presenter: FullViewPresenterMock())
testView.addSubview(fsView)
expect(testView.findIAMViewSubview()).to(beIdenticalTo(fsView))
}
it("will find an instance of SlideUpView") {
let testView = UIView()
let suView = SlideUpView(presenter: SlideUpViewPresenterMock())
testView.addSubview(suView)
expect(testView.findIAMViewSubview()).to(beIdenticalTo(suView))
}
it("will find an instance of ModalView") {
let testView = UIView()
let moView = ModalView(presenter: FullViewPresenterMock())
testView.addSubview(moView)
expect(testView.findIAMViewSubview()).to(beIdenticalTo(moView))
}
}
}
}
}
| 35.5 | 84 | 0.528396 |
38b0033e3fa1b67f9f09ab428b17bfd5ea3e7caa | 648 | //
// Responsable+CoreDataProperties.swift
// PetCent
//
// Created by Infraestructura on 14/10/16.
// Copyright © 2016 Valeriano Lopez. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Responsable {
@NSManaged var nombre: String?
@NSManaged var municipio: String?
@NSManaged var estado: String?
@NSManaged var colonia: String?
@NSManaged var calleyno: String?
@NSManaged var apellidos: String?
@NSManaged var fechaNacimiento: NSDate?
}
| 24.923077 | 76 | 0.729938 |
7a41247e1b82d2cb0d7c9ee4161f67d691fedf2f | 870 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "FancyOldSwiftModel",
platforms: [
.macOS("10.15.4")
],
products: [
.executable(name: "FancyOldSwiftModel", targets: ["FancyOldSwiftModel"])
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0"),
.package(url: "https://github.com/yanagiba/swift-ast.git", from: "0.19.9"),
],
targets: [
.target(
name: "FancyOldSwiftModel",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "SwiftAST+Tooling", package: "swift-ast")
]
),
.testTarget(
name: "FancyOldSwiftModelTests",
dependencies: ["FancyOldSwiftModel"]),
]
)
| 29 | 87 | 0.563218 |
7971a5a98199ee7bc6b2c5418b456da23fdc4113 | 799 | //
// BlePdmDemoUITestsLaunchTests.swift
// BlePdmDemoUITests
//
// Created by Tai on 2021-11-22.
//
import XCTest
class BlePdmDemoUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 24.212121 | 88 | 0.674593 |
dd5d11dda68941363e96126558a7994ff7cf4ca3 | 2,546 | //
// TriangleShapeRenderer.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 UIKit
open class TriangleShapeRenderer : NSObject, IShapeRenderer
{
open func renderShape(
context: CGContext,
dataSet: IScatterChartDataSet,
viewPortHandler: ViewPortHandler,
point: CGPoint,
color: NSUIColor)
{
let shapeSize = dataSet.scatterShapeSize
let shapeHalf = shapeSize / 2.0
let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius
let shapeHoleSize = shapeHoleSizeHalf * 2.0
let shapeHoleColor = dataSet.scatterShapeHoleColor
let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0
context.setFillColor(color.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf))
context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf))
if shapeHoleSize > 0.0
{
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
}
context.closePath()
context.fillPath()
if shapeHoleSize > 0.0 && shapeHoleColor != nil
{
context.setFillColor(shapeHoleColor!.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.closePath()
context.fillPath()
}
}
}
| 38 | 124 | 0.620581 |
ff04aedeb893f01063ec0a6d9645e5cc62fcf837 | 4,586 | //
// TrackingPaths+Events.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 29/10/2018.
//
import Foundation
// MARK: Events
extension TrackingPaths {
internal struct Events {
static func getInitPath() -> String {
return TrackingPaths.pxTrack + "/init"
}
// Use this path for any user friction.
static func getErrorPath() -> String {
return "/friction"
}
static func getCreateTokenPath() -> String {
return TrackingPaths.pxTrack + "/create_esc_token"
}
static func getConfirmPath() -> String {
return TrackingPaths.pxTrack + "/review/confirm"
}
static func getBackPath(screen: String) -> String {
return screen + "/back"
}
static func getAbortPath(screen: String) -> String {
return screen + "/abort"
}
static func getRecognizedCardPath() -> String {
return TrackingPaths.pxTrack + TrackingPaths.addPaymentMethod + "/number" + "/recognized_card"
}
}
}
extension TrackingPaths.Events {
internal struct OneTap {
static func getSwipePath() -> String {
return TrackingPaths.pxTrack + "/review/one_tap/swipe"
}
static func getConfirmPath() -> String {
return TrackingPaths.pxTrack + "/review/confirm"
}
static func getTargetBehaviourPath() -> String {
return TrackingPaths.pxTrack + "/review/one_tap/target_behaviour"
}
static func getOfflineMethodStartKYCPath() -> String {
return TrackingPaths.pxTrack + "/review/one_tap/offline_methods/start_kyc_flow"
}
static func getDialogOpenPath() -> String {
return TrackingPaths.pxTrack + "/dialog/open"
}
static func getDialogDismissPath() -> String {
return TrackingPaths.pxTrack + "/dialog/dismiss"
}
static func getDialogActionPath() -> String {
return TrackingPaths.pxTrack + "/dialog/action"
}
}
}
extension TrackingPaths.Events {
struct SecurityCode {
static func getConfirmPath() -> String {
return TrackingPaths.pxTrack + "/security_code/confirm"
}
static func getTokenFrictionPath() -> String {
return TrackingPaths.pxTrack + "/security_code/token_api_error"
}
static func getPaymentsFrictionPath() -> String {
return TrackingPaths.pxTrack + "/security_code/payments_api_error"
}
}
}
extension TrackingPaths.Events {
internal struct ReviewConfirm {
static func getChangePaymentMethodPath() -> String {
return TrackingPaths.pxTrack + "/review/traditional/change_payment_method"
}
static func getConfirmPath() -> String {
return TrackingPaths.pxTrack + "/review/confirm"
}
}
}
// MARK: Congrats events paths.
enum EventsPaths: String {
case tapScore = "/tap_score"
case tapDiscountItem = "/tap_discount_item"
case tapDownloadApp = "/tap_download_app"
case tapCrossSelling = "/tap_cross_selling"
case tapSeeAllDiscounts = "/tap_see_all_discounts"
case deeplink = "/deep_link"
}
// MARK: Congrats events.
extension TrackingPaths.Events {
internal struct Congrats {
private static let success = "/success"
private static let result = TrackingPaths.pxTrack + "/result"
static func getSuccessPath() -> String {
return result + success
}
static func getSuccessTapScorePath() -> String {
return getSuccessPath() + EventsPaths.tapScore.rawValue
}
static func getSuccessTapDiscountItemPath() -> String {
return getSuccessPath() + EventsPaths.tapDiscountItem.rawValue
}
static func getSuccessTapDownloadAppPath() -> String {
return getSuccessPath() + EventsPaths.tapDownloadApp.rawValue
}
static func getSuccessTapCrossSellingPath() -> String {
return getSuccessPath() + EventsPaths.tapCrossSelling.rawValue
}
static func getSuccessTapSeeAllDiscountsPath() -> String {
return getSuccessPath() + EventsPaths.tapSeeAllDiscounts.rawValue
}
static func getSuccessTapViewReceiptPath() -> String {
return getSuccessPath() + "/tap_view_receipt"
}
static func getSuccessTapDeeplinkPath() -> String {
return getSuccessPath() + EventsPaths.deeplink.rawValue
}
}
}
| 29.210191 | 106 | 0.624727 |