repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
khizkhiz/swift | validation-test/compiler_crashers_fixed/01696-getselftypeforcontainer.swift | 1 | 431 | // RUN: not %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
var f : AnyObject, AnyObject, range: a {
e where B {
return m: String {
func g<c) -> T -> Int {
}
}
}
print() -> {
}
protocol a {
protocol A {
typealias A : a: Sequence where T>("
func a
return x in x }
func a: A, g
| apache-2.0 |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/PresentationLayer/Popup/View/PopupViewOutput.swift | 1 | 209 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
protocol PopupViewOutput: class {
func viewIsReady()
func didConfirmPressed()
func didSkipPressed()
}
| gpl-3.0 |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CodeDeploy/CodeDeploy_API.swift | 1 | 31043 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/*
Client object for interacting with AWS CodeDeploy service.
AWS CodeDeploy AWS CodeDeploy is a deployment service that automates application deployments to Amazon EC2 instances, on-premises instances running in your own facility, serverless AWS Lambda functions, or applications in an Amazon ECS service. You can deploy a nearly unlimited variety of application content, such as an updated Lambda function, updated applications in an Amazon ECS service, code, web and configuration files, executables, packages, scripts, multimedia files, and so on. AWS CodeDeploy can deploy application content stored in Amazon S3 buckets, GitHub repositories, or Bitbucket repositories. You do not need to make changes to your existing code before you can use AWS CodeDeploy. AWS CodeDeploy makes it easier for you to rapidly release new features, helps you avoid downtime during application deployment, and handles the complexity of updating your applications, without many of the risks associated with error-prone manual deployments. AWS CodeDeploy Components Use the information in this guide to help you work with the following AWS CodeDeploy components: Application: A name that uniquely identifies the application you want to deploy. AWS CodeDeploy uses this name, which functions as a container, to ensure the correct combination of revision, deployment configuration, and deployment group are referenced during a deployment. Deployment group: A set of individual instances, CodeDeploy Lambda deployment configuration settings, or an Amazon ECS service and network details. A Lambda deployment group specifies how to route traffic to a new version of a Lambda function. An Amazon ECS deployment group specifies the service created in Amazon ECS to deploy, a load balancer, and a listener to reroute production traffic to an updated containerized application. An EC2/On-premises deployment group contains individually tagged instances, Amazon EC2 instances in Amazon EC2 Auto Scaling groups, or both. All deployment groups can specify optional trigger, alarm, and rollback settings. Deployment configuration: A set of deployment rules and deployment success and failure conditions used by AWS CodeDeploy during a deployment. Deployment: The process and the components used when updating a Lambda function, a containerized application in an Amazon ECS service, or of installing content on one or more instances. Application revisions: For an AWS Lambda deployment, this is an AppSpec file that specifies the Lambda function to be updated and one or more functions to validate deployment lifecycle events. For an Amazon ECS deployment, this is an AppSpec file that specifies the Amazon ECS task definition, container, and port where production traffic is rerouted. For an EC2/On-premises deployment, this is an archive file that contains source content—source code, webpages, executable files, and deployment scripts—along with an AppSpec file. Revisions are stored in Amazon S3 buckets or GitHub repositories. For Amazon S3, a revision is uniquely identified by its Amazon S3 object key and its ETag, version, or both. For GitHub, a revision is uniquely identified by its commit ID. This guide also contains information to help you get details about the instances in your deployments, to make on-premises instances available for AWS CodeDeploy deployments, to get details about a Lambda function deployment, and to get details about Amazon ECS service deployments. AWS CodeDeploy Information Resources AWS CodeDeploy User Guide AWS CodeDeploy API Reference Guide AWS CLI Reference for AWS CodeDeploy AWS CodeDeploy Developer Forum
*/
public struct CodeDeploy: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the CodeDeploy client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
amzTarget: "CodeDeploy_20141006",
service: "codedeploy",
serviceProtocol: .json(version: "1.1"),
apiVersion: "2014-10-06",
endpoint: endpoint,
errorType: CodeDeployErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Adds tags to on-premises instances.
@discardableResult public func addTagsToOnPremisesInstances(_ input: AddTagsToOnPremisesInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "AddTagsToOnPremisesInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about one or more application revisions. The maximum number of application revisions that can be returned is 25.
public func batchGetApplicationRevisions(_ input: BatchGetApplicationRevisionsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetApplicationRevisionsOutput> {
return self.client.execute(operation: "BatchGetApplicationRevisions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about one or more applications. The maximum number of applications that can be returned is 100.
public func batchGetApplications(_ input: BatchGetApplicationsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetApplicationsOutput> {
return self.client.execute(operation: "BatchGetApplications", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about one or more deployment groups.
public func batchGetDeploymentGroups(_ input: BatchGetDeploymentGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetDeploymentGroupsOutput> {
return self.client.execute(operation: "BatchGetDeploymentGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// This method works, but is deprecated. Use BatchGetDeploymentTargets instead. Returns an array of one or more instances associated with a deployment. This method works with EC2/On-premises and AWS Lambda compute platforms. The newer BatchGetDeploymentTargets works with all compute platforms. The maximum number of instances that can be returned is 25.
@available(*, deprecated, message: "This operation is deprecated, use BatchGetDeploymentTargets instead.")
public func batchGetDeploymentInstances(_ input: BatchGetDeploymentInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetDeploymentInstancesOutput> {
return self.client.execute(operation: "BatchGetDeploymentInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns an array of one or more targets associated with a deployment. This method works with all compute types and should be used instead of the deprecated BatchGetDeploymentInstances. The maximum number of targets that can be returned is 25. The type of targets returned depends on the deployment's compute platform or deployment method: EC2/On-premises: Information about EC2 instance targets. AWS Lambda: Information about Lambda functions targets. Amazon ECS: Information about Amazon ECS service targets. CloudFormation: Information about targets of blue/green deployments initiated by a CloudFormation stack update.
public func batchGetDeploymentTargets(_ input: BatchGetDeploymentTargetsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetDeploymentTargetsOutput> {
return self.client.execute(operation: "BatchGetDeploymentTargets", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about one or more deployments. The maximum number of deployments that can be returned is 25.
public func batchGetDeployments(_ input: BatchGetDeploymentsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetDeploymentsOutput> {
return self.client.execute(operation: "BatchGetDeployments", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about one or more on-premises instances. The maximum number of on-premises instances that can be returned is 25.
public func batchGetOnPremisesInstances(_ input: BatchGetOnPremisesInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetOnPremisesInstancesOutput> {
return self.client.execute(operation: "BatchGetOnPremisesInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// For a blue/green deployment, starts the process of rerouting traffic from instances in the original environment to instances in the replacement environment without waiting for a specified wait time to elapse. (Traffic rerouting, which is achieved by registering instances in the replacement environment with the load balancer, can start as soon as all instances have a status of Ready.)
@discardableResult public func continueDeployment(_ input: ContinueDeploymentInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "ContinueDeployment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates an application.
public func createApplication(_ input: CreateApplicationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateApplicationOutput> {
return self.client.execute(operation: "CreateApplication", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deploys an application revision through the specified deployment group.
public func createDeployment(_ input: CreateDeploymentInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDeploymentOutput> {
return self.client.execute(operation: "CreateDeployment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a deployment configuration.
public func createDeploymentConfig(_ input: CreateDeploymentConfigInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDeploymentConfigOutput> {
return self.client.execute(operation: "CreateDeploymentConfig", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a deployment group to which application revisions are deployed.
public func createDeploymentGroup(_ input: CreateDeploymentGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDeploymentGroupOutput> {
return self.client.execute(operation: "CreateDeploymentGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes an application.
@discardableResult public func deleteApplication(_ input: DeleteApplicationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteApplication", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a deployment configuration. A deployment configuration cannot be deleted if it is currently in use. Predefined configurations cannot be deleted.
@discardableResult public func deleteDeploymentConfig(_ input: DeleteDeploymentConfigInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteDeploymentConfig", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a deployment group.
public func deleteDeploymentGroup(_ input: DeleteDeploymentGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteDeploymentGroupOutput> {
return self.client.execute(operation: "DeleteDeploymentGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a GitHub account connection.
public func deleteGitHubAccountToken(_ input: DeleteGitHubAccountTokenInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteGitHubAccountTokenOutput> {
return self.client.execute(operation: "DeleteGitHubAccountToken", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes resources linked to an external ID.
public func deleteResourcesByExternalId(_ input: DeleteResourcesByExternalIdInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteResourcesByExternalIdOutput> {
return self.client.execute(operation: "DeleteResourcesByExternalId", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deregisters an on-premises instance.
@discardableResult public func deregisterOnPremisesInstance(_ input: DeregisterOnPremisesInstanceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeregisterOnPremisesInstance", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about an application.
public func getApplication(_ input: GetApplicationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetApplicationOutput> {
return self.client.execute(operation: "GetApplication", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about an application revision.
public func getApplicationRevision(_ input: GetApplicationRevisionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetApplicationRevisionOutput> {
return self.client.execute(operation: "GetApplicationRevision", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about a deployment. The content property of the appSpecContent object in the returned revision is always null. Use GetApplicationRevision and the sha256 property of the returned appSpecContent object to get the content of the deployment’s AppSpec file.
public func getDeployment(_ input: GetDeploymentInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDeploymentOutput> {
return self.client.execute(operation: "GetDeployment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about a deployment configuration.
public func getDeploymentConfig(_ input: GetDeploymentConfigInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDeploymentConfigOutput> {
return self.client.execute(operation: "GetDeploymentConfig", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about a deployment group.
public func getDeploymentGroup(_ input: GetDeploymentGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDeploymentGroupOutput> {
return self.client.execute(operation: "GetDeploymentGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about an instance as part of a deployment.
@available(*, deprecated, message: "This operation is deprecated, use GetDeploymentTarget instead.")
public func getDeploymentInstance(_ input: GetDeploymentInstanceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDeploymentInstanceOutput> {
return self.client.execute(operation: "GetDeploymentInstance", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns information about a deployment target.
public func getDeploymentTarget(_ input: GetDeploymentTargetInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDeploymentTargetOutput> {
return self.client.execute(operation: "GetDeploymentTarget", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about an on-premises instance.
public func getOnPremisesInstance(_ input: GetOnPremisesInstanceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetOnPremisesInstanceOutput> {
return self.client.execute(operation: "GetOnPremisesInstance", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists information about revisions for an application.
public func listApplicationRevisions(_ input: ListApplicationRevisionsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListApplicationRevisionsOutput> {
return self.client.execute(operation: "ListApplicationRevisions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the applications registered with the IAM user or AWS account.
public func listApplications(_ input: ListApplicationsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListApplicationsOutput> {
return self.client.execute(operation: "ListApplications", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the deployment configurations with the IAM user or AWS account.
public func listDeploymentConfigs(_ input: ListDeploymentConfigsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDeploymentConfigsOutput> {
return self.client.execute(operation: "ListDeploymentConfigs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the deployment groups for an application registered with the IAM user or AWS account.
public func listDeploymentGroups(_ input: ListDeploymentGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDeploymentGroupsOutput> {
return self.client.execute(operation: "ListDeploymentGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// The newer BatchGetDeploymentTargets should be used instead because it works with all compute types. ListDeploymentInstances throws an exception if it is used with a compute platform other than EC2/On-premises or AWS Lambda. Lists the instance for a deployment associated with the IAM user or AWS account.
@available(*, deprecated, message: "This operation is deprecated, use ListDeploymentTargets instead.")
public func listDeploymentInstances(_ input: ListDeploymentInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDeploymentInstancesOutput> {
return self.client.execute(operation: "ListDeploymentInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns an array of target IDs that are associated a deployment.
public func listDeploymentTargets(_ input: ListDeploymentTargetsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDeploymentTargetsOutput> {
return self.client.execute(operation: "ListDeploymentTargets", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the deployments in a deployment group for an application registered with the IAM user or AWS account.
public func listDeployments(_ input: ListDeploymentsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDeploymentsOutput> {
return self.client.execute(operation: "ListDeployments", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the names of stored connections to GitHub accounts.
public func listGitHubAccountTokenNames(_ input: ListGitHubAccountTokenNamesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListGitHubAccountTokenNamesOutput> {
return self.client.execute(operation: "ListGitHubAccountTokenNames", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of names for one or more on-premises instances. Unless otherwise specified, both registered and deregistered on-premises instance names are listed. To list only registered or deregistered on-premises instance names, use the registration status parameter.
public func listOnPremisesInstances(_ input: ListOnPremisesInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListOnPremisesInstancesOutput> {
return self.client.execute(operation: "ListOnPremisesInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of tags for the resource identified by a specified Amazon Resource Name (ARN). Tags are used to organize and categorize your CodeDeploy resources.
public func listTagsForResource(_ input: ListTagsForResourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceOutput> {
return self.client.execute(operation: "ListTagsForResource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Sets the result of a Lambda validation function. The function validates lifecycle hooks during a deployment that uses the AWS Lambda or Amazon ECS compute platform. For AWS Lambda deployments, the available lifecycle hooks are BeforeAllowTraffic and AfterAllowTraffic. For Amazon ECS deployments, the available lifecycle hooks are BeforeInstall, AfterInstall, AfterAllowTestTraffic, BeforeAllowTraffic, and AfterAllowTraffic. Lambda validation functions return Succeeded or Failed. For more information, see AppSpec 'hooks' Section for an AWS Lambda Deployment and AppSpec 'hooks' Section for an Amazon ECS Deployment.
public func putLifecycleEventHookExecutionStatus(_ input: PutLifecycleEventHookExecutionStatusInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutLifecycleEventHookExecutionStatusOutput> {
return self.client.execute(operation: "PutLifecycleEventHookExecutionStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Registers with AWS CodeDeploy a revision for the specified application.
@discardableResult public func registerApplicationRevision(_ input: RegisterApplicationRevisionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "RegisterApplicationRevision", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Registers an on-premises instance. Only one IAM ARN (an IAM session ARN or IAM user ARN) is supported in the request. You cannot use both.
@discardableResult public func registerOnPremisesInstance(_ input: RegisterOnPremisesInstanceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "RegisterOnPremisesInstance", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes one or more tags from one or more on-premises instances.
@discardableResult public func removeTagsFromOnPremisesInstances(_ input: RemoveTagsFromOnPremisesInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "RemoveTagsFromOnPremisesInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// In a blue/green deployment, overrides any specified wait time and starts terminating instances immediately after the traffic routing is complete.
@available(*, deprecated, message: "This operation is deprecated, use ContinueDeployment with DeploymentWaitType instead.")
@discardableResult public func skipWaitTimeForInstanceTermination(_ input: SkipWaitTimeForInstanceTerminationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "SkipWaitTimeForInstanceTermination", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Attempts to stop an ongoing deployment.
public func stopDeployment(_ input: StopDeploymentInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StopDeploymentOutput> {
return self.client.execute(operation: "StopDeployment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Associates the list of tags in the input Tags parameter with the resource identified by the ResourceArn input parameter.
public func tagResource(_ input: TagResourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceOutput> {
return self.client.execute(operation: "TagResource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disassociates a resource from a list of tags. The resource is identified by the ResourceArn input parameter. The tags are identified by the list of keys in the TagKeys input parameter.
public func untagResource(_ input: UntagResourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceOutput> {
return self.client.execute(operation: "UntagResource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Changes the name of an application.
@discardableResult public func updateApplication(_ input: UpdateApplicationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "UpdateApplication", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Changes information about a deployment group.
public func updateDeploymentGroup(_ input: UpdateDeploymentGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateDeploymentGroupOutput> {
return self.client.execute(operation: "UpdateDeploymentGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension CodeDeploy {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: CodeDeploy, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| apache-2.0 |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Neptune/Neptune_Shapes.swift | 1 | 264316 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension Neptune {
// MARK: Enums
public enum ApplyMethod: String, CustomStringConvertible, Codable {
case immediate
case pendingReboot = "pending-reboot"
public var description: String { return self.rawValue }
}
public enum SourceType: String, CustomStringConvertible, Codable {
case dbCluster = "db-cluster"
case dbClusterSnapshot = "db-cluster-snapshot"
case dbInstance = "db-instance"
case dbParameterGroup = "db-parameter-group"
case dbSecurityGroup = "db-security-group"
case dbSnapshot = "db-snapshot"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AddRoleToDBClusterMessage: AWSEncodableShape {
/// The name of the DB cluster to associate the IAM role with.
public let dBClusterIdentifier: String
/// The Amazon Resource Name (ARN) of the IAM role to associate with the Neptune DB cluster, for example arn:aws:iam::123456789012:role/NeptuneAccessRole.
public let roleArn: String
public init(dBClusterIdentifier: String, roleArn: String) {
self.dBClusterIdentifier = dBClusterIdentifier
self.roleArn = roleArn
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case roleArn = "RoleArn"
}
}
public struct AddSourceIdentifierToSubscriptionMessage: AWSEncodableShape {
/// The identifier of the event source to be added. Constraints: If the source type is a DB instance, then a DBInstanceIdentifier must be supplied. If the source type is a DB security group, a DBSecurityGroupName must be supplied. If the source type is a DB parameter group, a DBParameterGroupName must be supplied. If the source type is a DB snapshot, a DBSnapshotIdentifier must be supplied.
public let sourceIdentifier: String
/// The name of the event notification subscription you want to add a source identifier to.
public let subscriptionName: String
public init(sourceIdentifier: String, subscriptionName: String) {
self.sourceIdentifier = sourceIdentifier
self.subscriptionName = subscriptionName
}
private enum CodingKeys: String, CodingKey {
case sourceIdentifier = "SourceIdentifier"
case subscriptionName = "SubscriptionName"
}
}
public struct AddSourceIdentifierToSubscriptionResult: AWSDecodableShape {
public let eventSubscription: EventSubscription?
public init(eventSubscription: EventSubscription? = nil) {
self.eventSubscription = eventSubscription
}
private enum CodingKeys: String, CodingKey {
case eventSubscription = "EventSubscription"
}
}
public struct AddTagsToResourceMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The Amazon Neptune resource that the tags are added to. This value is an Amazon Resource Name (ARN). For information about creating an ARN, see Constructing an Amazon Resource Name (ARN).
public let resourceName: String
/// The tags to be assigned to the Amazon Neptune resource.
@CustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]
public init(resourceName: String, tags: [Tag]) {
self.resourceName = resourceName
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case resourceName = "ResourceName"
case tags = "Tags"
}
}
public struct ApplyPendingMaintenanceActionMessage: AWSEncodableShape {
/// The pending maintenance action to apply to this resource. Valid values: system-update, db-upgrade
public let applyAction: String
/// A value that specifies the type of opt-in request, or undoes an opt-in request. An opt-in request of type immediate can't be undone. Valid values: immediate - Apply the maintenance action immediately. next-maintenance - Apply the maintenance action during the next maintenance window for the resource. undo-opt-in - Cancel any existing next-maintenance opt-in requests.
public let optInType: String
/// The Amazon Resource Name (ARN) of the resource that the pending maintenance action applies to. For information about creating an ARN, see Constructing an Amazon Resource Name (ARN).
public let resourceIdentifier: String
public init(applyAction: String, optInType: String, resourceIdentifier: String) {
self.applyAction = applyAction
self.optInType = optInType
self.resourceIdentifier = resourceIdentifier
}
private enum CodingKeys: String, CodingKey {
case applyAction = "ApplyAction"
case optInType = "OptInType"
case resourceIdentifier = "ResourceIdentifier"
}
}
public struct ApplyPendingMaintenanceActionResult: AWSDecodableShape {
public let resourcePendingMaintenanceActions: ResourcePendingMaintenanceActions?
public init(resourcePendingMaintenanceActions: ResourcePendingMaintenanceActions? = nil) {
self.resourcePendingMaintenanceActions = resourcePendingMaintenanceActions
}
private enum CodingKeys: String, CodingKey {
case resourcePendingMaintenanceActions = "ResourcePendingMaintenanceActions"
}
}
public struct AvailabilityZone: AWSDecodableShape {
/// The name of the availability zone.
public let name: String?
public init(name: String? = nil) {
self.name = name
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
}
}
public struct CharacterSet: AWSDecodableShape {
/// The description of the character set.
public let characterSetDescription: String?
/// The name of the character set.
public let characterSetName: String?
public init(characterSetDescription: String? = nil, characterSetName: String? = nil) {
self.characterSetDescription = characterSetDescription
self.characterSetName = characterSetName
}
private enum CodingKeys: String, CodingKey {
case characterSetDescription = "CharacterSetDescription"
case characterSetName = "CharacterSetName"
}
}
public struct CloudwatchLogsExportConfiguration: AWSEncodableShape {
/// The list of log types to disable.
@OptionalCustomCoding<StandardArrayCoder>
public var disableLogTypes: [String]?
/// The list of log types to enable.
@OptionalCustomCoding<StandardArrayCoder>
public var enableLogTypes: [String]?
public init(disableLogTypes: [String]? = nil, enableLogTypes: [String]? = nil) {
self.disableLogTypes = disableLogTypes
self.enableLogTypes = enableLogTypes
}
private enum CodingKeys: String, CodingKey {
case disableLogTypes = "DisableLogTypes"
case enableLogTypes = "EnableLogTypes"
}
}
public struct CopyDBClusterParameterGroupMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The identifier or Amazon Resource Name (ARN) for the source DB cluster parameter group. For information about creating an ARN, see Constructing an Amazon Resource Name (ARN). Constraints: Must specify a valid DB cluster parameter group. If the source DB cluster parameter group is in the same AWS Region as the copy, specify a valid DB parameter group identifier, for example my-db-cluster-param-group, or a valid ARN. If the source DB parameter group is in a different AWS Region than the copy, specify a valid DB cluster parameter group ARN, for example arn:aws:rds:us-east-1:123456789012:cluster-pg:custom-cluster-group1.
public let sourceDBClusterParameterGroupIdentifier: String
/// The tags to be assigned to the copied DB cluster parameter group.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// A description for the copied DB cluster parameter group.
public let targetDBClusterParameterGroupDescription: String
/// The identifier for the copied DB cluster parameter group. Constraints: Cannot be null, empty, or blank Must contain from 1 to 255 letters, numbers, or hyphens First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens Example: my-cluster-param-group1
public let targetDBClusterParameterGroupIdentifier: String
public init(sourceDBClusterParameterGroupIdentifier: String, tags: [Tag]? = nil, targetDBClusterParameterGroupDescription: String, targetDBClusterParameterGroupIdentifier: String) {
self.sourceDBClusterParameterGroupIdentifier = sourceDBClusterParameterGroupIdentifier
self.tags = tags
self.targetDBClusterParameterGroupDescription = targetDBClusterParameterGroupDescription
self.targetDBClusterParameterGroupIdentifier = targetDBClusterParameterGroupIdentifier
}
private enum CodingKeys: String, CodingKey {
case sourceDBClusterParameterGroupIdentifier = "SourceDBClusterParameterGroupIdentifier"
case tags = "Tags"
case targetDBClusterParameterGroupDescription = "TargetDBClusterParameterGroupDescription"
case targetDBClusterParameterGroupIdentifier = "TargetDBClusterParameterGroupIdentifier"
}
}
public struct CopyDBClusterParameterGroupResult: AWSDecodableShape {
public let dBClusterParameterGroup: DBClusterParameterGroup?
public init(dBClusterParameterGroup: DBClusterParameterGroup? = nil) {
self.dBClusterParameterGroup = dBClusterParameterGroup
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroup = "DBClusterParameterGroup"
}
}
public struct CopyDBClusterSnapshotMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// True to copy all tags from the source DB cluster snapshot to the target DB cluster snapshot, and otherwise false. The default is false.
public let copyTags: Bool?
/// The AWS AWS KMS key ID for an encrypted DB cluster snapshot. The KMS key ID is the Amazon Resource Name (ARN), KMS key identifier, or the KMS key alias for the KMS encryption key. If you copy an encrypted DB cluster snapshot from your AWS account, you can specify a value for KmsKeyId to encrypt the copy with a new KMS encryption key. If you don't specify a value for KmsKeyId, then the copy of the DB cluster snapshot is encrypted with the same KMS key as the source DB cluster snapshot. If you copy an encrypted DB cluster snapshot that is shared from another AWS account, then you must specify a value for KmsKeyId. KMS encryption keys are specific to the AWS Region that they are created in, and you can't use encryption keys from one AWS Region in another AWS Region. You cannot encrypt an unencrypted DB cluster snapshot when you copy it. If you try to copy an unencrypted DB cluster snapshot and specify a value for the KmsKeyId parameter, an error is returned.
public let kmsKeyId: String?
/// Not currently supported.
public let preSignedUrl: String?
/// The identifier of the DB cluster snapshot to copy. This parameter is not case-sensitive. You can't copy from one AWS Region to another. Constraints: Must specify a valid system snapshot in the "available" state. Specify a valid DB snapshot identifier. Example: my-cluster-snapshot1
public let sourceDBClusterSnapshotIdentifier: String
/// The tags to assign to the new DB cluster snapshot copy.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// The identifier of the new DB cluster snapshot to create from the source DB cluster snapshot. This parameter is not case-sensitive. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens. First character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens. Example: my-cluster-snapshot2
public let targetDBClusterSnapshotIdentifier: String
public init(copyTags: Bool? = nil, kmsKeyId: String? = nil, preSignedUrl: String? = nil, sourceDBClusterSnapshotIdentifier: String, tags: [Tag]? = nil, targetDBClusterSnapshotIdentifier: String) {
self.copyTags = copyTags
self.kmsKeyId = kmsKeyId
self.preSignedUrl = preSignedUrl
self.sourceDBClusterSnapshotIdentifier = sourceDBClusterSnapshotIdentifier
self.tags = tags
self.targetDBClusterSnapshotIdentifier = targetDBClusterSnapshotIdentifier
}
private enum CodingKeys: String, CodingKey {
case copyTags = "CopyTags"
case kmsKeyId = "KmsKeyId"
case preSignedUrl = "PreSignedUrl"
case sourceDBClusterSnapshotIdentifier = "SourceDBClusterSnapshotIdentifier"
case tags = "Tags"
case targetDBClusterSnapshotIdentifier = "TargetDBClusterSnapshotIdentifier"
}
}
public struct CopyDBClusterSnapshotResult: AWSDecodableShape {
public let dBClusterSnapshot: DBClusterSnapshot?
public init(dBClusterSnapshot: DBClusterSnapshot? = nil) {
self.dBClusterSnapshot = dBClusterSnapshot
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshot = "DBClusterSnapshot"
}
}
public struct CopyDBParameterGroupMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The identifier or ARN for the source DB parameter group. For information about creating an ARN, see Constructing an Amazon Resource Name (ARN). Constraints: Must specify a valid DB parameter group. Must specify a valid DB parameter group identifier, for example my-db-param-group, or a valid ARN.
public let sourceDBParameterGroupIdentifier: String
/// The tags to be assigned to the copied DB parameter group.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// A description for the copied DB parameter group.
public let targetDBParameterGroupDescription: String
/// The identifier for the copied DB parameter group. Constraints: Cannot be null, empty, or blank. Must contain from 1 to 255 letters, numbers, or hyphens. First character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens. Example: my-db-parameter-group
public let targetDBParameterGroupIdentifier: String
public init(sourceDBParameterGroupIdentifier: String, tags: [Tag]? = nil, targetDBParameterGroupDescription: String, targetDBParameterGroupIdentifier: String) {
self.sourceDBParameterGroupIdentifier = sourceDBParameterGroupIdentifier
self.tags = tags
self.targetDBParameterGroupDescription = targetDBParameterGroupDescription
self.targetDBParameterGroupIdentifier = targetDBParameterGroupIdentifier
}
private enum CodingKeys: String, CodingKey {
case sourceDBParameterGroupIdentifier = "SourceDBParameterGroupIdentifier"
case tags = "Tags"
case targetDBParameterGroupDescription = "TargetDBParameterGroupDescription"
case targetDBParameterGroupIdentifier = "TargetDBParameterGroupIdentifier"
}
}
public struct CopyDBParameterGroupResult: AWSDecodableShape {
public let dBParameterGroup: DBParameterGroup?
public init(dBParameterGroup: DBParameterGroup? = nil) {
self.dBParameterGroup = dBParameterGroup
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroup = "DBParameterGroup"
}
}
public struct CreateDBClusterMessage: AWSEncodableShape {
public struct _AvailabilityZonesEncoding: ArrayCoderProperties { public static let member = "AvailabilityZone" }
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
public struct _VpcSecurityGroupIdsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupId" }
/// A list of EC2 Availability Zones that instances in the DB cluster can be created in.
@OptionalCustomCoding<ArrayCoder<_AvailabilityZonesEncoding, String>>
public var availabilityZones: [String]?
/// The number of days for which automated backups are retained. You must specify a minimum value of 1. Default: 1 Constraints: Must be a value from 1 to 35
public let backupRetentionPeriod: Int?
/// (Not supported by Neptune)
public let characterSetName: String?
/// The name for your database of up to 64 alpha-numeric characters. If you do not provide a name, Amazon Neptune will not create a database in the DB cluster you are creating.
public let databaseName: String?
/// The DB cluster identifier. This parameter is stored as a lowercase string. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens. First character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens. Example: my-cluster1
public let dBClusterIdentifier: String
/// The name of the DB cluster parameter group to associate with this DB cluster. If this argument is omitted, the default is used. Constraints: If supplied, must match the name of an existing DBClusterParameterGroup.
public let dBClusterParameterGroupName: String?
/// A DB subnet group to associate with this DB cluster. Constraints: Must match the name of an existing DBSubnetGroup. Must not be default. Example: mySubnetgroup
public let dBSubnetGroupName: String?
/// A value that indicates whether the DB cluster has deletion protection enabled. The database can't be deleted when deletion protection is enabled. By default, deletion protection is enabled.
public let deletionProtection: Bool?
/// The list of log types that need to be enabled for exporting to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var enableCloudwatchLogsExports: [String]?
/// True to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts, and otherwise false. Default: false
public let enableIAMDatabaseAuthentication: Bool?
/// The name of the database engine to be used for this DB cluster. Valid Values: neptune
public let engine: String
/// The version number of the database engine to use. Currently, setting this parameter has no effect. Example: 1.0.1
public let engineVersion: String?
/// The AWS KMS key identifier for an encrypted DB cluster. The KMS key identifier is the Amazon Resource Name (ARN) for the KMS encryption key. If you are creating a DB cluster with the same AWS account that owns the KMS encryption key used to encrypt the new DB cluster, then you can use the KMS key alias instead of the ARN for the KMS encryption key. If an encryption key is not specified in KmsKeyId: If ReplicationSourceIdentifier identifies an encrypted source, then Amazon Neptune will use the encryption key used to encrypt the source. Otherwise, Amazon Neptune will use your default encryption key. If the StorageEncrypted parameter is true and ReplicationSourceIdentifier is not specified, then Amazon Neptune will use your default encryption key. AWS KMS creates the default encryption key for your AWS account. Your AWS account has a different default encryption key for each AWS Region. If you create a Read Replica of an encrypted DB cluster in another AWS Region, you must set KmsKeyId to a KMS key ID that is valid in the destination AWS Region. This key is used to encrypt the Read Replica in that AWS Region.
public let kmsKeyId: String?
/// The name of the master user for the DB cluster. Constraints: Must be 1 to 16 letters or numbers. First character must be a letter. Cannot be a reserved word for the chosen database engine.
public let masterUsername: String?
/// The password for the master database user. This password can contain any printable ASCII character except "/", """, or "@". Constraints: Must contain from 8 to 41 characters.
public let masterUserPassword: String?
/// (Not supported by Neptune)
public let optionGroupName: String?
/// The port number on which the instances in the DB cluster accept connections. Default: 8182
public let port: Int?
/// The daily time range during which automated backups are created if automated backups are enabled using the BackupRetentionPeriod parameter. The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region. To see the time blocks available, see Adjusting the Preferred Maintenance Window in the Amazon Neptune User Guide. Constraints: Must be in the format hh24:mi-hh24:mi. Must be in Universal Coordinated Time (UTC). Must not conflict with the preferred maintenance window. Must be at least 30 minutes.
public let preferredBackupWindow: String?
/// The weekly time range during which system maintenance can occur, in Universal Coordinated Time (UTC). Format: ddd:hh24:mi-ddd:hh24:mi The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region, occurring on a random day of the week. To see the time blocks available, see Adjusting the Preferred Maintenance Window in the Amazon Neptune User Guide. Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun. Constraints: Minimum 30-minute window.
public let preferredMaintenanceWindow: String?
/// This parameter is not currently supported.
public let preSignedUrl: String?
/// The Amazon Resource Name (ARN) of the source DB instance or DB cluster if this DB cluster is created as a Read Replica.
public let replicationSourceIdentifier: String?
/// Specifies whether the DB cluster is encrypted.
public let storageEncrypted: Bool?
/// The tags to assign to the new DB cluster.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// A list of EC2 VPC security groups to associate with this DB cluster.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupIdsEncoding, String>>
public var vpcSecurityGroupIds: [String]?
public init(availabilityZones: [String]? = nil, backupRetentionPeriod: Int? = nil, characterSetName: String? = nil, databaseName: String? = nil, dBClusterIdentifier: String, dBClusterParameterGroupName: String? = nil, dBSubnetGroupName: String? = nil, deletionProtection: Bool? = nil, enableCloudwatchLogsExports: [String]? = nil, enableIAMDatabaseAuthentication: Bool? = nil, engine: String, engineVersion: String? = nil, kmsKeyId: String? = nil, masterUsername: String? = nil, masterUserPassword: String? = nil, optionGroupName: String? = nil, port: Int? = nil, preferredBackupWindow: String? = nil, preferredMaintenanceWindow: String? = nil, preSignedUrl: String? = nil, replicationSourceIdentifier: String? = nil, storageEncrypted: Bool? = nil, tags: [Tag]? = nil, vpcSecurityGroupIds: [String]? = nil) {
self.availabilityZones = availabilityZones
self.backupRetentionPeriod = backupRetentionPeriod
self.characterSetName = characterSetName
self.databaseName = databaseName
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.dBSubnetGroupName = dBSubnetGroupName
self.deletionProtection = deletionProtection
self.enableCloudwatchLogsExports = enableCloudwatchLogsExports
self.enableIAMDatabaseAuthentication = enableIAMDatabaseAuthentication
self.engine = engine
self.engineVersion = engineVersion
self.kmsKeyId = kmsKeyId
self.masterUsername = masterUsername
self.masterUserPassword = masterUserPassword
self.optionGroupName = optionGroupName
self.port = port
self.preferredBackupWindow = preferredBackupWindow
self.preferredMaintenanceWindow = preferredMaintenanceWindow
self.preSignedUrl = preSignedUrl
self.replicationSourceIdentifier = replicationSourceIdentifier
self.storageEncrypted = storageEncrypted
self.tags = tags
self.vpcSecurityGroupIds = vpcSecurityGroupIds
}
private enum CodingKeys: String, CodingKey {
case availabilityZones = "AvailabilityZones"
case backupRetentionPeriod = "BackupRetentionPeriod"
case characterSetName = "CharacterSetName"
case databaseName = "DatabaseName"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case dBSubnetGroupName = "DBSubnetGroupName"
case deletionProtection = "DeletionProtection"
case enableCloudwatchLogsExports = "EnableCloudwatchLogsExports"
case enableIAMDatabaseAuthentication = "EnableIAMDatabaseAuthentication"
case engine = "Engine"
case engineVersion = "EngineVersion"
case kmsKeyId = "KmsKeyId"
case masterUsername = "MasterUsername"
case masterUserPassword = "MasterUserPassword"
case optionGroupName = "OptionGroupName"
case port = "Port"
case preferredBackupWindow = "PreferredBackupWindow"
case preferredMaintenanceWindow = "PreferredMaintenanceWindow"
case preSignedUrl = "PreSignedUrl"
case replicationSourceIdentifier = "ReplicationSourceIdentifier"
case storageEncrypted = "StorageEncrypted"
case tags = "Tags"
case vpcSecurityGroupIds = "VpcSecurityGroupIds"
}
}
public struct CreateDBClusterParameterGroupMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The name of the DB cluster parameter group. Constraints: Must match the name of an existing DBClusterParameterGroup. This value is stored as a lowercase string.
public let dBClusterParameterGroupName: String
/// The DB cluster parameter group family name. A DB cluster parameter group can be associated with one and only one DB cluster parameter group family, and can be applied only to a DB cluster running a database engine and engine version compatible with that DB cluster parameter group family.
public let dBParameterGroupFamily: String
/// The description for the DB cluster parameter group.
public let description: String
/// The tags to be assigned to the new DB cluster parameter group.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
public init(dBClusterParameterGroupName: String, dBParameterGroupFamily: String, description: String, tags: [Tag]? = nil) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.dBParameterGroupFamily = dBParameterGroupFamily
self.description = description
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case dBParameterGroupFamily = "DBParameterGroupFamily"
case description = "Description"
case tags = "Tags"
}
}
public struct CreateDBClusterParameterGroupResult: AWSDecodableShape {
public let dBClusterParameterGroup: DBClusterParameterGroup?
public init(dBClusterParameterGroup: DBClusterParameterGroup? = nil) {
self.dBClusterParameterGroup = dBClusterParameterGroup
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroup = "DBClusterParameterGroup"
}
}
public struct CreateDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct CreateDBClusterSnapshotMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The identifier of the DB cluster to create a snapshot for. This parameter is not case-sensitive. Constraints: Must match the identifier of an existing DBCluster. Example: my-cluster1
public let dBClusterIdentifier: String
/// The identifier of the DB cluster snapshot. This parameter is stored as a lowercase string. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens. First character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens. Example: my-cluster1-snapshot1
public let dBClusterSnapshotIdentifier: String
/// The tags to be assigned to the DB cluster snapshot.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
public init(dBClusterIdentifier: String, dBClusterSnapshotIdentifier: String, tags: [Tag]? = nil) {
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
case tags = "Tags"
}
}
public struct CreateDBClusterSnapshotResult: AWSDecodableShape {
public let dBClusterSnapshot: DBClusterSnapshot?
public init(dBClusterSnapshot: DBClusterSnapshot? = nil) {
self.dBClusterSnapshot = dBClusterSnapshot
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshot = "DBClusterSnapshot"
}
}
public struct CreateDBInstanceMessage: AWSEncodableShape {
public struct _DBSecurityGroupsEncoding: ArrayCoderProperties { public static let member = "DBSecurityGroupName" }
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
public struct _VpcSecurityGroupIdsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupId" }
/// The amount of storage (in gibibytes) to allocate for the DB instance. Type: Integer Not applicable. Neptune cluster volumes automatically grow as the amount of data in your database increases, though you are only charged for the space that you use in a Neptune cluster volume.
public let allocatedStorage: Int?
/// Indicates that minor engine upgrades are applied automatically to the DB instance during the maintenance window. Default: true
public let autoMinorVersionUpgrade: Bool?
/// The EC2 Availability Zone that the DB instance is created in Default: A random, system-chosen Availability Zone in the endpoint's AWS Region. Example: us-east-1d Constraint: The AvailabilityZone parameter can't be specified if the MultiAZ parameter is set to true. The specified Availability Zone must be in the same AWS Region as the current endpoint.
public let availabilityZone: String?
/// The number of days for which automated backups are retained. Not applicable. The retention period for automated backups is managed by the DB cluster. For more information, see CreateDBCluster. Default: 1 Constraints: Must be a value from 0 to 35 Cannot be set to 0 if the DB instance is a source to Read Replicas
public let backupRetentionPeriod: Int?
/// (Not supported by Neptune)
public let characterSetName: String?
/// True to copy all tags from the DB instance to snapshots of the DB instance, and otherwise false. The default is false.
public let copyTagsToSnapshot: Bool?
/// The identifier of the DB cluster that the instance will belong to. For information on creating a DB cluster, see CreateDBCluster. Type: String
public let dBClusterIdentifier: String?
/// The compute and memory capacity of the DB instance, for example, db.m4.large. Not all DB instance classes are available in all AWS Regions.
public let dBInstanceClass: String
/// The DB instance identifier. This parameter is stored as a lowercase string. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens. First character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens. Example: mydbinstance
public let dBInstanceIdentifier: String
/// Not supported.
public let dBName: String?
/// The name of the DB parameter group to associate with this DB instance. If this argument is omitted, the default DBParameterGroup for the specified engine is used. Constraints: Must be 1 to 255 letters, numbers, or hyphens. First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
public let dBParameterGroupName: String?
/// A list of DB security groups to associate with this DB instance. Default: The default DB security group for the database engine.
@OptionalCustomCoding<ArrayCoder<_DBSecurityGroupsEncoding, String>>
public var dBSecurityGroups: [String]?
/// A DB subnet group to associate with this DB instance. If there is no DB subnet group, then it is a non-VPC DB instance.
public let dBSubnetGroupName: String?
/// A value that indicates whether the DB instance has deletion protection enabled. The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled. See Deleting a DB Instance. DB instances in a DB cluster can be deleted even when deletion protection is enabled in their parent DB cluster.
public let deletionProtection: Bool?
/// Specify the Active Directory Domain to create the instance in.
public let domain: String?
/// Specify the name of the IAM role to be used when making API calls to the Directory Service.
public let domainIAMRoleName: String?
/// The list of log types that need to be enabled for exporting to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var enableCloudwatchLogsExports: [String]?
/// True to enable AWS Identity and Access Management (IAM) authentication for Neptune. Default: false
public let enableIAMDatabaseAuthentication: Bool?
/// (Not supported by Neptune)
public let enablePerformanceInsights: Bool?
/// The name of the database engine to be used for this instance. Valid Values: neptune
public let engine: String
/// The version number of the database engine to use. Currently, setting this parameter has no effect.
public let engineVersion: String?
/// The amount of Provisioned IOPS (input/output operations per second) to be initially allocated for the DB instance.
public let iops: Int?
/// The AWS KMS key identifier for an encrypted DB instance. The KMS key identifier is the Amazon Resource Name (ARN) for the KMS encryption key. If you are creating a DB instance with the same AWS account that owns the KMS encryption key used to encrypt the new DB instance, then you can use the KMS key alias instead of the ARN for the KM encryption key. Not applicable. The KMS key identifier is managed by the DB cluster. For more information, see CreateDBCluster. If the StorageEncrypted parameter is true, and you do not specify a value for the KmsKeyId parameter, then Amazon Neptune will use your default encryption key. AWS KMS creates the default encryption key for your AWS account. Your AWS account has a different default encryption key for each AWS Region.
public let kmsKeyId: String?
/// License model information for this DB instance. Valid values: license-included | bring-your-own-license | general-public-license
public let licenseModel: String?
/// The name for the master user. Not used.
public let masterUsername: String?
/// The password for the master user. The password can include any printable ASCII character except "/", """, or "@". Not used.
public let masterUserPassword: String?
/// The interval, in seconds, between points when Enhanced Monitoring metrics are collected for the DB instance. To disable collecting Enhanced Monitoring metrics, specify 0. The default is 0. If MonitoringRoleArn is specified, then you must also set MonitoringInterval to a value other than 0. Valid Values: 0, 1, 5, 10, 15, 30, 60
public let monitoringInterval: Int?
/// The ARN for the IAM role that permits Neptune to send enhanced monitoring metrics to Amazon CloudWatch Logs. For example, arn:aws:iam:123456789012:role/emaccess. If MonitoringInterval is set to a value other than 0, then you must supply a MonitoringRoleArn value.
public let monitoringRoleArn: String?
/// Specifies if the DB instance is a Multi-AZ deployment. You can't set the AvailabilityZone parameter if the MultiAZ parameter is set to true.
public let multiAZ: Bool?
/// (Not supported by Neptune)
public let optionGroupName: String?
/// (Not supported by Neptune)
public let performanceInsightsKMSKeyId: String?
/// The port number on which the database accepts connections. Not applicable. The port is managed by the DB cluster. For more information, see CreateDBCluster. Default: 8182 Type: Integer
public let port: Int?
/// The daily time range during which automated backups are created. Not applicable. The daily time range for creating automated backups is managed by the DB cluster. For more information, see CreateDBCluster.
public let preferredBackupWindow: String?
/// The time range each week during which system maintenance can occur, in Universal Coordinated Time (UTC). Format: ddd:hh24:mi-ddd:hh24:mi The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region, occurring on a random day of the week. Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun. Constraints: Minimum 30-minute window.
public let preferredMaintenanceWindow: String?
/// A value that specifies the order in which an Read Replica is promoted to the primary instance after a failure of the existing primary instance. Default: 1 Valid Values: 0 - 15
public let promotionTier: Int?
/// Specifies whether the DB instance is encrypted. Not applicable. The encryption for DB instances is managed by the DB cluster. For more information, see CreateDBCluster. Default: false
public let storageEncrypted: Bool?
/// Specifies the storage type to be associated with the DB instance. Not applicable. Storage is managed by the DB Cluster.
public let storageType: String?
/// The tags to assign to the new instance.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// The ARN from the key store with which to associate the instance for TDE encryption.
public let tdeCredentialArn: String?
/// The password for the given ARN from the key store in order to access the device.
public let tdeCredentialPassword: String?
/// The time zone of the DB instance.
public let timezone: String?
/// A list of EC2 VPC security groups to associate with this DB instance. Not applicable. The associated list of EC2 VPC security groups is managed by the DB cluster. For more information, see CreateDBCluster. Default: The default EC2 VPC security group for the DB subnet group's VPC.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupIdsEncoding, String>>
public var vpcSecurityGroupIds: [String]?
public init(allocatedStorage: Int? = nil, autoMinorVersionUpgrade: Bool? = nil, availabilityZone: String? = nil, backupRetentionPeriod: Int? = nil, characterSetName: String? = nil, copyTagsToSnapshot: Bool? = nil, dBClusterIdentifier: String? = nil, dBInstanceClass: String, dBInstanceIdentifier: String, dBName: String? = nil, dBParameterGroupName: String? = nil, dBSecurityGroups: [String]? = nil, dBSubnetGroupName: String? = nil, deletionProtection: Bool? = nil, domain: String? = nil, domainIAMRoleName: String? = nil, enableCloudwatchLogsExports: [String]? = nil, enableIAMDatabaseAuthentication: Bool? = nil, enablePerformanceInsights: Bool? = nil, engine: String, engineVersion: String? = nil, iops: Int? = nil, kmsKeyId: String? = nil, licenseModel: String? = nil, masterUsername: String? = nil, masterUserPassword: String? = nil, monitoringInterval: Int? = nil, monitoringRoleArn: String? = nil, multiAZ: Bool? = nil, optionGroupName: String? = nil, performanceInsightsKMSKeyId: String? = nil, port: Int? = nil, preferredBackupWindow: String? = nil, preferredMaintenanceWindow: String? = nil, promotionTier: Int? = nil, storageEncrypted: Bool? = nil, storageType: String? = nil, tags: [Tag]? = nil, tdeCredentialArn: String? = nil, tdeCredentialPassword: String? = nil, timezone: String? = nil, vpcSecurityGroupIds: [String]? = nil) {
self.allocatedStorage = allocatedStorage
self.autoMinorVersionUpgrade = autoMinorVersionUpgrade
self.availabilityZone = availabilityZone
self.backupRetentionPeriod = backupRetentionPeriod
self.characterSetName = characterSetName
self.copyTagsToSnapshot = copyTagsToSnapshot
self.dBClusterIdentifier = dBClusterIdentifier
self.dBInstanceClass = dBInstanceClass
self.dBInstanceIdentifier = dBInstanceIdentifier
self.dBName = dBName
self.dBParameterGroupName = dBParameterGroupName
self.dBSecurityGroups = dBSecurityGroups
self.dBSubnetGroupName = dBSubnetGroupName
self.deletionProtection = deletionProtection
self.domain = domain
self.domainIAMRoleName = domainIAMRoleName
self.enableCloudwatchLogsExports = enableCloudwatchLogsExports
self.enableIAMDatabaseAuthentication = enableIAMDatabaseAuthentication
self.enablePerformanceInsights = enablePerformanceInsights
self.engine = engine
self.engineVersion = engineVersion
self.iops = iops
self.kmsKeyId = kmsKeyId
self.licenseModel = licenseModel
self.masterUsername = masterUsername
self.masterUserPassword = masterUserPassword
self.monitoringInterval = monitoringInterval
self.monitoringRoleArn = monitoringRoleArn
self.multiAZ = multiAZ
self.optionGroupName = optionGroupName
self.performanceInsightsKMSKeyId = performanceInsightsKMSKeyId
self.port = port
self.preferredBackupWindow = preferredBackupWindow
self.preferredMaintenanceWindow = preferredMaintenanceWindow
self.promotionTier = promotionTier
self.storageEncrypted = storageEncrypted
self.storageType = storageType
self.tags = tags
self.tdeCredentialArn = tdeCredentialArn
self.tdeCredentialPassword = tdeCredentialPassword
self.timezone = timezone
self.vpcSecurityGroupIds = vpcSecurityGroupIds
}
private enum CodingKeys: String, CodingKey {
case allocatedStorage = "AllocatedStorage"
case autoMinorVersionUpgrade = "AutoMinorVersionUpgrade"
case availabilityZone = "AvailabilityZone"
case backupRetentionPeriod = "BackupRetentionPeriod"
case characterSetName = "CharacterSetName"
case copyTagsToSnapshot = "CopyTagsToSnapshot"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBInstanceClass = "DBInstanceClass"
case dBInstanceIdentifier = "DBInstanceIdentifier"
case dBName = "DBName"
case dBParameterGroupName = "DBParameterGroupName"
case dBSecurityGroups = "DBSecurityGroups"
case dBSubnetGroupName = "DBSubnetGroupName"
case deletionProtection = "DeletionProtection"
case domain = "Domain"
case domainIAMRoleName = "DomainIAMRoleName"
case enableCloudwatchLogsExports = "EnableCloudwatchLogsExports"
case enableIAMDatabaseAuthentication = "EnableIAMDatabaseAuthentication"
case enablePerformanceInsights = "EnablePerformanceInsights"
case engine = "Engine"
case engineVersion = "EngineVersion"
case iops = "Iops"
case kmsKeyId = "KmsKeyId"
case licenseModel = "LicenseModel"
case masterUsername = "MasterUsername"
case masterUserPassword = "MasterUserPassword"
case monitoringInterval = "MonitoringInterval"
case monitoringRoleArn = "MonitoringRoleArn"
case multiAZ = "MultiAZ"
case optionGroupName = "OptionGroupName"
case performanceInsightsKMSKeyId = "PerformanceInsightsKMSKeyId"
case port = "Port"
case preferredBackupWindow = "PreferredBackupWindow"
case preferredMaintenanceWindow = "PreferredMaintenanceWindow"
case promotionTier = "PromotionTier"
case storageEncrypted = "StorageEncrypted"
case storageType = "StorageType"
case tags = "Tags"
case tdeCredentialArn = "TdeCredentialArn"
case tdeCredentialPassword = "TdeCredentialPassword"
case timezone = "Timezone"
case vpcSecurityGroupIds = "VpcSecurityGroupIds"
}
}
public struct CreateDBInstanceResult: AWSDecodableShape {
public let dBInstance: DBInstance?
public init(dBInstance: DBInstance? = nil) {
self.dBInstance = dBInstance
}
private enum CodingKeys: String, CodingKey {
case dBInstance = "DBInstance"
}
}
public struct CreateDBParameterGroupMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The DB parameter group family name. A DB parameter group can be associated with one and only one DB parameter group family, and can be applied only to a DB instance running a database engine and engine version compatible with that DB parameter group family.
public let dBParameterGroupFamily: String
/// The name of the DB parameter group. Constraints: Must be 1 to 255 letters, numbers, or hyphens. First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens This value is stored as a lowercase string.
public let dBParameterGroupName: String
/// The description for the DB parameter group.
public let description: String
/// The tags to be assigned to the new DB parameter group.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
public init(dBParameterGroupFamily: String, dBParameterGroupName: String, description: String, tags: [Tag]? = nil) {
self.dBParameterGroupFamily = dBParameterGroupFamily
self.dBParameterGroupName = dBParameterGroupName
self.description = description
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupFamily = "DBParameterGroupFamily"
case dBParameterGroupName = "DBParameterGroupName"
case description = "Description"
case tags = "Tags"
}
}
public struct CreateDBParameterGroupResult: AWSDecodableShape {
public let dBParameterGroup: DBParameterGroup?
public init(dBParameterGroup: DBParameterGroup? = nil) {
self.dBParameterGroup = dBParameterGroup
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroup = "DBParameterGroup"
}
}
public struct CreateDBSubnetGroupMessage: AWSEncodableShape {
public struct _SubnetIdsEncoding: ArrayCoderProperties { public static let member = "SubnetIdentifier" }
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// The description for the DB subnet group.
public let dBSubnetGroupDescription: String
/// The name for the DB subnet group. This value is stored as a lowercase string. Constraints: Must contain no more than 255 letters, numbers, periods, underscores, spaces, or hyphens. Must not be default. Example: mySubnetgroup
public let dBSubnetGroupName: String
/// The EC2 Subnet IDs for the DB subnet group.
@CustomCoding<ArrayCoder<_SubnetIdsEncoding, String>>
public var subnetIds: [String]
/// The tags to be assigned to the new DB subnet group.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
public init(dBSubnetGroupDescription: String, dBSubnetGroupName: String, subnetIds: [String], tags: [Tag]? = nil) {
self.dBSubnetGroupDescription = dBSubnetGroupDescription
self.dBSubnetGroupName = dBSubnetGroupName
self.subnetIds = subnetIds
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroupDescription = "DBSubnetGroupDescription"
case dBSubnetGroupName = "DBSubnetGroupName"
case subnetIds = "SubnetIds"
case tags = "Tags"
}
}
public struct CreateDBSubnetGroupResult: AWSDecodableShape {
public let dBSubnetGroup: DBSubnetGroup?
public init(dBSubnetGroup: DBSubnetGroup? = nil) {
self.dBSubnetGroup = dBSubnetGroup
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroup = "DBSubnetGroup"
}
}
public struct CreateEventSubscriptionMessage: AWSEncodableShape {
public struct _EventCategoriesEncoding: ArrayCoderProperties { public static let member = "EventCategory" }
public struct _SourceIdsEncoding: ArrayCoderProperties { public static let member = "SourceId" }
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// A Boolean value; set to true to activate the subscription, set to false to create the subscription but not active it.
public let enabled: Bool?
/// A list of event categories for a SourceType that you want to subscribe to. You can see a list of the categories for a given SourceType by using the DescribeEventCategories action.
@OptionalCustomCoding<ArrayCoder<_EventCategoriesEncoding, String>>
public var eventCategories: [String]?
/// The Amazon Resource Name (ARN) of the SNS topic created for event notification. The ARN is created by Amazon SNS when you create a topic and subscribe to it.
public let snsTopicArn: String
/// The list of identifiers of the event sources for which events are returned. If not specified, then all sources are included in the response. An identifier must begin with a letter and must contain only ASCII letters, digits, and hyphens; it can't end with a hyphen or contain two consecutive hyphens. Constraints: If SourceIds are supplied, SourceType must also be provided. If the source type is a DB instance, then a DBInstanceIdentifier must be supplied. If the source type is a DB security group, a DBSecurityGroupName must be supplied. If the source type is a DB parameter group, a DBParameterGroupName must be supplied. If the source type is a DB snapshot, a DBSnapshotIdentifier must be supplied.
@OptionalCustomCoding<ArrayCoder<_SourceIdsEncoding, String>>
public var sourceIds: [String]?
/// The type of source that is generating the events. For example, if you want to be notified of events generated by a DB instance, you would set this parameter to db-instance. if this value is not specified, all events are returned. Valid values: db-instance | db-cluster | db-parameter-group | db-security-group | db-snapshot | db-cluster-snapshot
public let sourceType: String?
/// The name of the subscription. Constraints: The name must be less than 255 characters.
public let subscriptionName: String
/// The tags to be applied to the new event subscription.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
public init(enabled: Bool? = nil, eventCategories: [String]? = nil, snsTopicArn: String, sourceIds: [String]? = nil, sourceType: String? = nil, subscriptionName: String, tags: [Tag]? = nil) {
self.enabled = enabled
self.eventCategories = eventCategories
self.snsTopicArn = snsTopicArn
self.sourceIds = sourceIds
self.sourceType = sourceType
self.subscriptionName = subscriptionName
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case enabled = "Enabled"
case eventCategories = "EventCategories"
case snsTopicArn = "SnsTopicArn"
case sourceIds = "SourceIds"
case sourceType = "SourceType"
case subscriptionName = "SubscriptionName"
case tags = "Tags"
}
}
public struct CreateEventSubscriptionResult: AWSDecodableShape {
public let eventSubscription: EventSubscription?
public init(eventSubscription: EventSubscription? = nil) {
self.eventSubscription = eventSubscription
}
private enum CodingKeys: String, CodingKey {
case eventSubscription = "EventSubscription"
}
}
public struct DBCluster: AWSDecodableShape {
public struct _AssociatedRolesEncoding: ArrayCoderProperties { public static let member = "DBClusterRole" }
public struct _AvailabilityZonesEncoding: ArrayCoderProperties { public static let member = "AvailabilityZone" }
public struct _DBClusterMembersEncoding: ArrayCoderProperties { public static let member = "DBClusterMember" }
public struct _DBClusterOptionGroupMembershipsEncoding: ArrayCoderProperties { public static let member = "DBClusterOptionGroup" }
public struct _ReadReplicaIdentifiersEncoding: ArrayCoderProperties { public static let member = "ReadReplicaIdentifier" }
public struct _VpcSecurityGroupsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupMembership" }
/// AllocatedStorage always returns 1, because Neptune DB cluster storage size is not fixed, but instead automatically adjusts as needed.
public let allocatedStorage: Int?
/// Provides a list of the AWS Identity and Access Management (IAM) roles that are associated with the DB cluster. IAM roles that are associated with a DB cluster grant permission for the DB cluster to access other AWS services on your behalf.
@OptionalCustomCoding<ArrayCoder<_AssociatedRolesEncoding, DBClusterRole>>
public var associatedRoles: [DBClusterRole]?
/// Provides the list of EC2 Availability Zones that instances in the DB cluster can be created in.
@OptionalCustomCoding<ArrayCoder<_AvailabilityZonesEncoding, String>>
public var availabilityZones: [String]?
/// Specifies the number of days for which automatic DB snapshots are retained.
public let backupRetentionPeriod: Int?
/// (Not supported by Neptune)
public let characterSetName: String?
/// Identifies the clone group to which the DB cluster is associated.
public let cloneGroupId: String?
/// Specifies the time when the DB cluster was created, in Universal Coordinated Time (UTC).
public let clusterCreateTime: Date?
/// Contains the name of the initial database of this DB cluster that was provided at create time, if one was specified when the DB cluster was created. This same name is returned for the life of the DB cluster.
public let databaseName: String?
/// The Amazon Resource Name (ARN) for the DB cluster.
public let dBClusterArn: String?
/// Contains a user-supplied DB cluster identifier. This identifier is the unique key that identifies a DB cluster.
public let dBClusterIdentifier: String?
/// Provides the list of instances that make up the DB cluster.
@OptionalCustomCoding<ArrayCoder<_DBClusterMembersEncoding, DBClusterMember>>
public var dBClusterMembers: [DBClusterMember]?
/// (Not supported by Neptune)
@OptionalCustomCoding<ArrayCoder<_DBClusterOptionGroupMembershipsEncoding, DBClusterOptionGroupStatus>>
public var dBClusterOptionGroupMemberships: [DBClusterOptionGroupStatus]?
/// Specifies the name of the DB cluster parameter group for the DB cluster.
public let dBClusterParameterGroup: String?
/// The AWS Region-unique, immutable identifier for the DB cluster. This identifier is found in AWS CloudTrail log entries whenever the AWS KMS key for the DB cluster is accessed.
public let dbClusterResourceId: String?
/// Specifies information on the subnet group associated with the DB cluster, including the name, description, and subnets in the subnet group.
public let dBSubnetGroup: String?
/// Indicates whether or not the DB cluster has deletion protection enabled. The database can't be deleted when deletion protection is enabled.
public let deletionProtection: Bool?
/// Specifies the earliest time to which a database can be restored with point-in-time restore.
public let earliestRestorableTime: Date?
/// A list of log types that this DB cluster is configured to export to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var enabledCloudwatchLogsExports: [String]?
/// Specifies the connection endpoint for the primary instance of the DB cluster.
public let endpoint: String?
/// Provides the name of the database engine to be used for this DB cluster.
public let engine: String?
/// Indicates the database engine version.
public let engineVersion: String?
/// Specifies the ID that Amazon Route 53 assigns when you create a hosted zone.
public let hostedZoneId: String?
/// True if mapping of AWS Identity and Access Management (IAM) accounts to database accounts is enabled, and otherwise false.
public let iAMDatabaseAuthenticationEnabled: Bool?
/// If StorageEncrypted is true, the AWS KMS key identifier for the encrypted DB cluster.
public let kmsKeyId: String?
/// Specifies the latest time to which a database can be restored with point-in-time restore.
public let latestRestorableTime: Date?
/// Contains the master username for the DB cluster.
public let masterUsername: String?
/// Specifies whether the DB cluster has instances in multiple Availability Zones.
public let multiAZ: Bool?
/// Specifies the progress of the operation as a percentage.
public let percentProgress: String?
/// Specifies the port that the database engine is listening on.
public let port: Int?
/// Specifies the daily time range during which automated backups are created if automated backups are enabled, as determined by the BackupRetentionPeriod.
public let preferredBackupWindow: String?
/// Specifies the weekly time range during which system maintenance can occur, in Universal Coordinated Time (UTC).
public let preferredMaintenanceWindow: String?
/// The reader endpoint for the DB cluster. The reader endpoint for a DB cluster load-balances connections across the Read Replicas that are available in a DB cluster. As clients request new connections to the reader endpoint, Neptune distributes the connection requests among the Read Replicas in the DB cluster. This functionality can help balance your read workload across multiple Read Replicas in your DB cluster. If a failover occurs, and the Read Replica that you are connected to is promoted to be the primary instance, your connection is dropped. To continue sending your read workload to other Read Replicas in the cluster, you can then reconnect to the reader endpoint.
public let readerEndpoint: String?
/// Contains one or more identifiers of the Read Replicas associated with this DB cluster.
@OptionalCustomCoding<ArrayCoder<_ReadReplicaIdentifiersEncoding, String>>
public var readReplicaIdentifiers: [String]?
/// Not supported by Neptune.
public let replicationSourceIdentifier: String?
/// Specifies the current state of this DB cluster.
public let status: String?
/// Specifies whether the DB cluster is encrypted.
public let storageEncrypted: Bool?
/// Provides a list of VPC security groups that the DB cluster belongs to.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupsEncoding, VpcSecurityGroupMembership>>
public var vpcSecurityGroups: [VpcSecurityGroupMembership]?
public init(allocatedStorage: Int? = nil, associatedRoles: [DBClusterRole]? = nil, availabilityZones: [String]? = nil, backupRetentionPeriod: Int? = nil, characterSetName: String? = nil, cloneGroupId: String? = nil, clusterCreateTime: Date? = nil, databaseName: String? = nil, dBClusterArn: String? = nil, dBClusterIdentifier: String? = nil, dBClusterMembers: [DBClusterMember]? = nil, dBClusterOptionGroupMemberships: [DBClusterOptionGroupStatus]? = nil, dBClusterParameterGroup: String? = nil, dbClusterResourceId: String? = nil, dBSubnetGroup: String? = nil, deletionProtection: Bool? = nil, earliestRestorableTime: Date? = nil, enabledCloudwatchLogsExports: [String]? = nil, endpoint: String? = nil, engine: String? = nil, engineVersion: String? = nil, hostedZoneId: String? = nil, iAMDatabaseAuthenticationEnabled: Bool? = nil, kmsKeyId: String? = nil, latestRestorableTime: Date? = nil, masterUsername: String? = nil, multiAZ: Bool? = nil, percentProgress: String? = nil, port: Int? = nil, preferredBackupWindow: String? = nil, preferredMaintenanceWindow: String? = nil, readerEndpoint: String? = nil, readReplicaIdentifiers: [String]? = nil, replicationSourceIdentifier: String? = nil, status: String? = nil, storageEncrypted: Bool? = nil, vpcSecurityGroups: [VpcSecurityGroupMembership]? = nil) {
self.allocatedStorage = allocatedStorage
self.associatedRoles = associatedRoles
self.availabilityZones = availabilityZones
self.backupRetentionPeriod = backupRetentionPeriod
self.characterSetName = characterSetName
self.cloneGroupId = cloneGroupId
self.clusterCreateTime = clusterCreateTime
self.databaseName = databaseName
self.dBClusterArn = dBClusterArn
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterMembers = dBClusterMembers
self.dBClusterOptionGroupMemberships = dBClusterOptionGroupMemberships
self.dBClusterParameterGroup = dBClusterParameterGroup
self.dbClusterResourceId = dbClusterResourceId
self.dBSubnetGroup = dBSubnetGroup
self.deletionProtection = deletionProtection
self.earliestRestorableTime = earliestRestorableTime
self.enabledCloudwatchLogsExports = enabledCloudwatchLogsExports
self.endpoint = endpoint
self.engine = engine
self.engineVersion = engineVersion
self.hostedZoneId = hostedZoneId
self.iAMDatabaseAuthenticationEnabled = iAMDatabaseAuthenticationEnabled
self.kmsKeyId = kmsKeyId
self.latestRestorableTime = latestRestorableTime
self.masterUsername = masterUsername
self.multiAZ = multiAZ
self.percentProgress = percentProgress
self.port = port
self.preferredBackupWindow = preferredBackupWindow
self.preferredMaintenanceWindow = preferredMaintenanceWindow
self.readerEndpoint = readerEndpoint
self.readReplicaIdentifiers = readReplicaIdentifiers
self.replicationSourceIdentifier = replicationSourceIdentifier
self.status = status
self.storageEncrypted = storageEncrypted
self.vpcSecurityGroups = vpcSecurityGroups
}
private enum CodingKeys: String, CodingKey {
case allocatedStorage = "AllocatedStorage"
case associatedRoles = "AssociatedRoles"
case availabilityZones = "AvailabilityZones"
case backupRetentionPeriod = "BackupRetentionPeriod"
case characterSetName = "CharacterSetName"
case cloneGroupId = "CloneGroupId"
case clusterCreateTime = "ClusterCreateTime"
case databaseName = "DatabaseName"
case dBClusterArn = "DBClusterArn"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterMembers = "DBClusterMembers"
case dBClusterOptionGroupMemberships = "DBClusterOptionGroupMemberships"
case dBClusterParameterGroup = "DBClusterParameterGroup"
case dbClusterResourceId = "DbClusterResourceId"
case dBSubnetGroup = "DBSubnetGroup"
case deletionProtection = "DeletionProtection"
case earliestRestorableTime = "EarliestRestorableTime"
case enabledCloudwatchLogsExports = "EnabledCloudwatchLogsExports"
case endpoint = "Endpoint"
case engine = "Engine"
case engineVersion = "EngineVersion"
case hostedZoneId = "HostedZoneId"
case iAMDatabaseAuthenticationEnabled = "IAMDatabaseAuthenticationEnabled"
case kmsKeyId = "KmsKeyId"
case latestRestorableTime = "LatestRestorableTime"
case masterUsername = "MasterUsername"
case multiAZ = "MultiAZ"
case percentProgress = "PercentProgress"
case port = "Port"
case preferredBackupWindow = "PreferredBackupWindow"
case preferredMaintenanceWindow = "PreferredMaintenanceWindow"
case readerEndpoint = "ReaderEndpoint"
case readReplicaIdentifiers = "ReadReplicaIdentifiers"
case replicationSourceIdentifier = "ReplicationSourceIdentifier"
case status = "Status"
case storageEncrypted = "StorageEncrypted"
case vpcSecurityGroups = "VpcSecurityGroups"
}
}
public struct DBClusterMember: AWSDecodableShape {
/// Specifies the status of the DB cluster parameter group for this member of the DB cluster.
public let dBClusterParameterGroupStatus: String?
/// Specifies the instance identifier for this member of the DB cluster.
public let dBInstanceIdentifier: String?
/// Value that is true if the cluster member is the primary instance for the DB cluster and false otherwise.
public let isClusterWriter: Bool?
/// A value that specifies the order in which a Read Replica is promoted to the primary instance after a failure of the existing primary instance.
public let promotionTier: Int?
public init(dBClusterParameterGroupStatus: String? = nil, dBInstanceIdentifier: String? = nil, isClusterWriter: Bool? = nil, promotionTier: Int? = nil) {
self.dBClusterParameterGroupStatus = dBClusterParameterGroupStatus
self.dBInstanceIdentifier = dBInstanceIdentifier
self.isClusterWriter = isClusterWriter
self.promotionTier = promotionTier
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupStatus = "DBClusterParameterGroupStatus"
case dBInstanceIdentifier = "DBInstanceIdentifier"
case isClusterWriter = "IsClusterWriter"
case promotionTier = "PromotionTier"
}
}
public struct DBClusterMessage: AWSDecodableShape {
public struct _DBClustersEncoding: ArrayCoderProperties { public static let member = "DBCluster" }
/// Contains a list of DB clusters for the user.
@OptionalCustomCoding<ArrayCoder<_DBClustersEncoding, DBCluster>>
public var dBClusters: [DBCluster]?
/// A pagination token that can be used in a subsequent DescribeDBClusters request.
public let marker: String?
public init(dBClusters: [DBCluster]? = nil, marker: String? = nil) {
self.dBClusters = dBClusters
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBClusters = "DBClusters"
case marker = "Marker"
}
}
public struct DBClusterOptionGroupStatus: AWSDecodableShape {
/// Specifies the name of the DB cluster option group.
public let dBClusterOptionGroupName: String?
/// Specifies the status of the DB cluster option group.
public let status: String?
public init(dBClusterOptionGroupName: String? = nil, status: String? = nil) {
self.dBClusterOptionGroupName = dBClusterOptionGroupName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case dBClusterOptionGroupName = "DBClusterOptionGroupName"
case status = "Status"
}
}
public struct DBClusterParameterGroup: AWSDecodableShape {
/// The Amazon Resource Name (ARN) for the DB cluster parameter group.
public let dBClusterParameterGroupArn: String?
/// Provides the name of the DB cluster parameter group.
public let dBClusterParameterGroupName: String?
/// Provides the name of the DB parameter group family that this DB cluster parameter group is compatible with.
public let dBParameterGroupFamily: String?
/// Provides the customer-specified description for this DB cluster parameter group.
public let description: String?
public init(dBClusterParameterGroupArn: String? = nil, dBClusterParameterGroupName: String? = nil, dBParameterGroupFamily: String? = nil, description: String? = nil) {
self.dBClusterParameterGroupArn = dBClusterParameterGroupArn
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.dBParameterGroupFamily = dBParameterGroupFamily
self.description = description
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupArn = "DBClusterParameterGroupArn"
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case dBParameterGroupFamily = "DBParameterGroupFamily"
case description = "Description"
}
}
public struct DBClusterParameterGroupDetails: AWSDecodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// An optional pagination token provided by a previous DescribeDBClusterParameters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
/// Provides a list of parameters for the DB cluster parameter group.
@OptionalCustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]?
public init(marker: String? = nil, parameters: [Parameter]? = nil) {
self.marker = marker
self.parameters = parameters
}
private enum CodingKeys: String, CodingKey {
case marker = "Marker"
case parameters = "Parameters"
}
}
public struct DBClusterParameterGroupNameMessage: AWSDecodableShape {
/// The name of the DB cluster parameter group. Constraints: Must be 1 to 255 letters or numbers. First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens This value is stored as a lowercase string.
public let dBClusterParameterGroupName: String?
public init(dBClusterParameterGroupName: String? = nil) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
}
}
public struct DBClusterParameterGroupsMessage: AWSDecodableShape {
public struct _DBClusterParameterGroupsEncoding: ArrayCoderProperties { public static let member = "DBClusterParameterGroup" }
/// A list of DB cluster parameter groups.
@OptionalCustomCoding<ArrayCoder<_DBClusterParameterGroupsEncoding, DBClusterParameterGroup>>
public var dBClusterParameterGroups: [DBClusterParameterGroup]?
/// An optional pagination token provided by a previous DescribeDBClusterParameterGroups request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
public init(dBClusterParameterGroups: [DBClusterParameterGroup]? = nil, marker: String? = nil) {
self.dBClusterParameterGroups = dBClusterParameterGroups
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroups = "DBClusterParameterGroups"
case marker = "Marker"
}
}
public struct DBClusterRole: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the IAM role that is associated with the DB cluster.
public let roleArn: String?
/// Describes the state of association between the IAM role and the DB cluster. The Status property returns one of the following values: ACTIVE - the IAM role ARN is associated with the DB cluster and can be used to access other AWS services on your behalf. PENDING - the IAM role ARN is being associated with the DB cluster. INVALID - the IAM role ARN is associated with the DB cluster, but the DB cluster is unable to assume the IAM role in order to access other AWS services on your behalf.
public let status: String?
public init(roleArn: String? = nil, status: String? = nil) {
self.roleArn = roleArn
self.status = status
}
private enum CodingKeys: String, CodingKey {
case roleArn = "RoleArn"
case status = "Status"
}
}
public struct DBClusterSnapshot: AWSDecodableShape {
public struct _AvailabilityZonesEncoding: ArrayCoderProperties { public static let member = "AvailabilityZone" }
/// Specifies the allocated storage size in gibibytes (GiB).
public let allocatedStorage: Int?
/// Provides the list of EC2 Availability Zones that instances in the DB cluster snapshot can be restored in.
@OptionalCustomCoding<ArrayCoder<_AvailabilityZonesEncoding, String>>
public var availabilityZones: [String]?
/// Specifies the time when the DB cluster was created, in Universal Coordinated Time (UTC).
public let clusterCreateTime: Date?
/// Specifies the DB cluster identifier of the DB cluster that this DB cluster snapshot was created from.
public let dBClusterIdentifier: String?
/// The Amazon Resource Name (ARN) for the DB cluster snapshot.
public let dBClusterSnapshotArn: String?
/// Specifies the identifier for a DB cluster snapshot. Must match the identifier of an existing snapshot. After you restore a DB cluster using a DBClusterSnapshotIdentifier, you must specify the same DBClusterSnapshotIdentifier for any future updates to the DB cluster. When you specify this property for an update, the DB cluster is not restored from the snapshot again, and the data in the database is not changed. However, if you don't specify the DBClusterSnapshotIdentifier, an empty DB cluster is created, and the original DB cluster is deleted. If you specify a property that is different from the previous snapshot restore property, the DB cluster is restored from the snapshot specified by the DBClusterSnapshotIdentifier, and the original DB cluster is deleted.
public let dBClusterSnapshotIdentifier: String?
/// Specifies the name of the database engine.
public let engine: String?
/// Provides the version of the database engine for this DB cluster snapshot.
public let engineVersion: String?
/// True if mapping of AWS Identity and Access Management (IAM) accounts to database accounts is enabled, and otherwise false.
public let iAMDatabaseAuthenticationEnabled: Bool?
/// If StorageEncrypted is true, the AWS KMS key identifier for the encrypted DB cluster snapshot.
public let kmsKeyId: String?
/// Provides the license model information for this DB cluster snapshot.
public let licenseModel: String?
/// Provides the master username for the DB cluster snapshot.
public let masterUsername: String?
/// Specifies the percentage of the estimated data that has been transferred.
public let percentProgress: Int?
/// Specifies the port that the DB cluster was listening on at the time of the snapshot.
public let port: Int?
/// Provides the time when the snapshot was taken, in Universal Coordinated Time (UTC).
public let snapshotCreateTime: Date?
/// Provides the type of the DB cluster snapshot.
public let snapshotType: String?
/// If the DB cluster snapshot was copied from a source DB cluster snapshot, the Amazon Resource Name (ARN) for the source DB cluster snapshot, otherwise, a null value.
public let sourceDBClusterSnapshotArn: String?
/// Specifies the status of this DB cluster snapshot.
public let status: String?
/// Specifies whether the DB cluster snapshot is encrypted.
public let storageEncrypted: Bool?
/// Provides the VPC ID associated with the DB cluster snapshot.
public let vpcId: String?
public init(allocatedStorage: Int? = nil, availabilityZones: [String]? = nil, clusterCreateTime: Date? = nil, dBClusterIdentifier: String? = nil, dBClusterSnapshotArn: String? = nil, dBClusterSnapshotIdentifier: String? = nil, engine: String? = nil, engineVersion: String? = nil, iAMDatabaseAuthenticationEnabled: Bool? = nil, kmsKeyId: String? = nil, licenseModel: String? = nil, masterUsername: String? = nil, percentProgress: Int? = nil, port: Int? = nil, snapshotCreateTime: Date? = nil, snapshotType: String? = nil, sourceDBClusterSnapshotArn: String? = nil, status: String? = nil, storageEncrypted: Bool? = nil, vpcId: String? = nil) {
self.allocatedStorage = allocatedStorage
self.availabilityZones = availabilityZones
self.clusterCreateTime = clusterCreateTime
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterSnapshotArn = dBClusterSnapshotArn
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
self.engine = engine
self.engineVersion = engineVersion
self.iAMDatabaseAuthenticationEnabled = iAMDatabaseAuthenticationEnabled
self.kmsKeyId = kmsKeyId
self.licenseModel = licenseModel
self.masterUsername = masterUsername
self.percentProgress = percentProgress
self.port = port
self.snapshotCreateTime = snapshotCreateTime
self.snapshotType = snapshotType
self.sourceDBClusterSnapshotArn = sourceDBClusterSnapshotArn
self.status = status
self.storageEncrypted = storageEncrypted
self.vpcId = vpcId
}
private enum CodingKeys: String, CodingKey {
case allocatedStorage = "AllocatedStorage"
case availabilityZones = "AvailabilityZones"
case clusterCreateTime = "ClusterCreateTime"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterSnapshotArn = "DBClusterSnapshotArn"
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
case engine = "Engine"
case engineVersion = "EngineVersion"
case iAMDatabaseAuthenticationEnabled = "IAMDatabaseAuthenticationEnabled"
case kmsKeyId = "KmsKeyId"
case licenseModel = "LicenseModel"
case masterUsername = "MasterUsername"
case percentProgress = "PercentProgress"
case port = "Port"
case snapshotCreateTime = "SnapshotCreateTime"
case snapshotType = "SnapshotType"
case sourceDBClusterSnapshotArn = "SourceDBClusterSnapshotArn"
case status = "Status"
case storageEncrypted = "StorageEncrypted"
case vpcId = "VpcId"
}
}
public struct DBClusterSnapshotAttribute: AWSDecodableShape {
public struct _AttributeValuesEncoding: ArrayCoderProperties { public static let member = "AttributeValue" }
/// The name of the manual DB cluster snapshot attribute. The attribute named restore refers to the list of AWS accounts that have permission to copy or restore the manual DB cluster snapshot. For more information, see the ModifyDBClusterSnapshotAttribute API action.
public let attributeName: String?
/// The value(s) for the manual DB cluster snapshot attribute. If the AttributeName field is set to restore, then this element returns a list of IDs of the AWS accounts that are authorized to copy or restore the manual DB cluster snapshot. If a value of all is in the list, then the manual DB cluster snapshot is public and available for any AWS account to copy or restore.
@OptionalCustomCoding<ArrayCoder<_AttributeValuesEncoding, String>>
public var attributeValues: [String]?
public init(attributeName: String? = nil, attributeValues: [String]? = nil) {
self.attributeName = attributeName
self.attributeValues = attributeValues
}
private enum CodingKeys: String, CodingKey {
case attributeName = "AttributeName"
case attributeValues = "AttributeValues"
}
}
public struct DBClusterSnapshotAttributesResult: AWSDecodableShape {
public struct _DBClusterSnapshotAttributesEncoding: ArrayCoderProperties { public static let member = "DBClusterSnapshotAttribute" }
/// The list of attributes and values for the manual DB cluster snapshot.
@OptionalCustomCoding<ArrayCoder<_DBClusterSnapshotAttributesEncoding, DBClusterSnapshotAttribute>>
public var dBClusterSnapshotAttributes: [DBClusterSnapshotAttribute]?
/// The identifier of the manual DB cluster snapshot that the attributes apply to.
public let dBClusterSnapshotIdentifier: String?
public init(dBClusterSnapshotAttributes: [DBClusterSnapshotAttribute]? = nil, dBClusterSnapshotIdentifier: String? = nil) {
self.dBClusterSnapshotAttributes = dBClusterSnapshotAttributes
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshotAttributes = "DBClusterSnapshotAttributes"
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
}
}
public struct DBClusterSnapshotMessage: AWSDecodableShape {
public struct _DBClusterSnapshotsEncoding: ArrayCoderProperties { public static let member = "DBClusterSnapshot" }
/// Provides a list of DB cluster snapshots for the user.
@OptionalCustomCoding<ArrayCoder<_DBClusterSnapshotsEncoding, DBClusterSnapshot>>
public var dBClusterSnapshots: [DBClusterSnapshot]?
/// An optional pagination token provided by a previous DescribeDBClusterSnapshots request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
public init(dBClusterSnapshots: [DBClusterSnapshot]? = nil, marker: String? = nil) {
self.dBClusterSnapshots = dBClusterSnapshots
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshots = "DBClusterSnapshots"
case marker = "Marker"
}
}
public struct DBEngineVersion: AWSDecodableShape {
public struct _SupportedCharacterSetsEncoding: ArrayCoderProperties { public static let member = "CharacterSet" }
public struct _SupportedTimezonesEncoding: ArrayCoderProperties { public static let member = "Timezone" }
public struct _ValidUpgradeTargetEncoding: ArrayCoderProperties { public static let member = "UpgradeTarget" }
/// The description of the database engine.
public let dBEngineDescription: String?
/// The description of the database engine version.
public let dBEngineVersionDescription: String?
/// The name of the DB parameter group family for the database engine.
public let dBParameterGroupFamily: String?
/// (Not supported by Neptune)
public let defaultCharacterSet: CharacterSet?
/// The name of the database engine.
public let engine: String?
/// The version number of the database engine.
public let engineVersion: String?
/// The types of logs that the database engine has available for export to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var exportableLogTypes: [String]?
/// (Not supported by Neptune)
@OptionalCustomCoding<ArrayCoder<_SupportedCharacterSetsEncoding, CharacterSet>>
public var supportedCharacterSets: [CharacterSet]?
/// A list of the time zones supported by this engine for the Timezone parameter of the CreateDBInstance action.
@OptionalCustomCoding<ArrayCoder<_SupportedTimezonesEncoding, Timezone>>
public var supportedTimezones: [Timezone]?
/// A value that indicates whether the engine version supports exporting the log types specified by ExportableLogTypes to CloudWatch Logs.
public let supportsLogExportsToCloudwatchLogs: Bool?
/// Indicates whether the database engine version supports read replicas.
public let supportsReadReplica: Bool?
/// A list of engine versions that this database engine version can be upgraded to.
@OptionalCustomCoding<ArrayCoder<_ValidUpgradeTargetEncoding, UpgradeTarget>>
public var validUpgradeTarget: [UpgradeTarget]?
public init(dBEngineDescription: String? = nil, dBEngineVersionDescription: String? = nil, dBParameterGroupFamily: String? = nil, defaultCharacterSet: CharacterSet? = nil, engine: String? = nil, engineVersion: String? = nil, exportableLogTypes: [String]? = nil, supportedCharacterSets: [CharacterSet]? = nil, supportedTimezones: [Timezone]? = nil, supportsLogExportsToCloudwatchLogs: Bool? = nil, supportsReadReplica: Bool? = nil, validUpgradeTarget: [UpgradeTarget]? = nil) {
self.dBEngineDescription = dBEngineDescription
self.dBEngineVersionDescription = dBEngineVersionDescription
self.dBParameterGroupFamily = dBParameterGroupFamily
self.defaultCharacterSet = defaultCharacterSet
self.engine = engine
self.engineVersion = engineVersion
self.exportableLogTypes = exportableLogTypes
self.supportedCharacterSets = supportedCharacterSets
self.supportedTimezones = supportedTimezones
self.supportsLogExportsToCloudwatchLogs = supportsLogExportsToCloudwatchLogs
self.supportsReadReplica = supportsReadReplica
self.validUpgradeTarget = validUpgradeTarget
}
private enum CodingKeys: String, CodingKey {
case dBEngineDescription = "DBEngineDescription"
case dBEngineVersionDescription = "DBEngineVersionDescription"
case dBParameterGroupFamily = "DBParameterGroupFamily"
case defaultCharacterSet = "DefaultCharacterSet"
case engine = "Engine"
case engineVersion = "EngineVersion"
case exportableLogTypes = "ExportableLogTypes"
case supportedCharacterSets = "SupportedCharacterSets"
case supportedTimezones = "SupportedTimezones"
case supportsLogExportsToCloudwatchLogs = "SupportsLogExportsToCloudwatchLogs"
case supportsReadReplica = "SupportsReadReplica"
case validUpgradeTarget = "ValidUpgradeTarget"
}
}
public struct DBEngineVersionMessage: AWSDecodableShape {
public struct _DBEngineVersionsEncoding: ArrayCoderProperties { public static let member = "DBEngineVersion" }
/// A list of DBEngineVersion elements.
@OptionalCustomCoding<ArrayCoder<_DBEngineVersionsEncoding, DBEngineVersion>>
public var dBEngineVersions: [DBEngineVersion]?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
public init(dBEngineVersions: [DBEngineVersion]? = nil, marker: String? = nil) {
self.dBEngineVersions = dBEngineVersions
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBEngineVersions = "DBEngineVersions"
case marker = "Marker"
}
}
public struct DBInstance: AWSDecodableShape {
public struct _DBParameterGroupsEncoding: ArrayCoderProperties { public static let member = "DBParameterGroup" }
public struct _DBSecurityGroupsEncoding: ArrayCoderProperties { public static let member = "DBSecurityGroup" }
public struct _DomainMembershipsEncoding: ArrayCoderProperties { public static let member = "DomainMembership" }
public struct _OptionGroupMembershipsEncoding: ArrayCoderProperties { public static let member = "OptionGroupMembership" }
public struct _ReadReplicaDBClusterIdentifiersEncoding: ArrayCoderProperties { public static let member = "ReadReplicaDBClusterIdentifier" }
public struct _ReadReplicaDBInstanceIdentifiersEncoding: ArrayCoderProperties { public static let member = "ReadReplicaDBInstanceIdentifier" }
public struct _StatusInfosEncoding: ArrayCoderProperties { public static let member = "DBInstanceStatusInfo" }
public struct _VpcSecurityGroupsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupMembership" }
/// Specifies the allocated storage size specified in gibibytes.
public let allocatedStorage: Int?
/// Indicates that minor version patches are applied automatically.
public let autoMinorVersionUpgrade: Bool?
/// Specifies the name of the Availability Zone the DB instance is located in.
public let availabilityZone: String?
/// Specifies the number of days for which automatic DB snapshots are retained.
public let backupRetentionPeriod: Int?
/// The identifier of the CA certificate for this DB instance.
public let cACertificateIdentifier: String?
/// (Not supported by Neptune)
public let characterSetName: String?
/// Specifies whether tags are copied from the DB instance to snapshots of the DB instance.
public let copyTagsToSnapshot: Bool?
/// If the DB instance is a member of a DB cluster, contains the name of the DB cluster that the DB instance is a member of.
public let dBClusterIdentifier: String?
/// The Amazon Resource Name (ARN) for the DB instance.
public let dBInstanceArn: String?
/// Contains the name of the compute and memory capacity class of the DB instance.
public let dBInstanceClass: String?
/// Contains a user-supplied database identifier. This identifier is the unique key that identifies a DB instance.
public let dBInstanceIdentifier: String?
/// Specifies the port that the DB instance listens on. If the DB instance is part of a DB cluster, this can be a different port than the DB cluster port.
public let dbInstancePort: Int?
/// Specifies the current state of this database.
public let dBInstanceStatus: String?
/// The AWS Region-unique, immutable identifier for the DB instance. This identifier is found in AWS CloudTrail log entries whenever the AWS KMS key for the DB instance is accessed.
public let dbiResourceId: String?
/// The database name.
public let dBName: String?
/// Provides the list of DB parameter groups applied to this DB instance.
@OptionalCustomCoding<ArrayCoder<_DBParameterGroupsEncoding, DBParameterGroupStatus>>
public var dBParameterGroups: [DBParameterGroupStatus]?
/// Provides List of DB security group elements containing only DBSecurityGroup.Name and DBSecurityGroup.Status subelements.
@OptionalCustomCoding<ArrayCoder<_DBSecurityGroupsEncoding, DBSecurityGroupMembership>>
public var dBSecurityGroups: [DBSecurityGroupMembership]?
/// Specifies information on the subnet group associated with the DB instance, including the name, description, and subnets in the subnet group.
public let dBSubnetGroup: DBSubnetGroup?
/// Indicates whether or not the DB instance has deletion protection enabled. The instance can't be deleted when deletion protection is enabled. See Deleting a DB Instance.
public let deletionProtection: Bool?
/// Not supported
@OptionalCustomCoding<ArrayCoder<_DomainMembershipsEncoding, DomainMembership>>
public var domainMemberships: [DomainMembership]?
/// A list of log types that this DB instance is configured to export to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var enabledCloudwatchLogsExports: [String]?
/// Specifies the connection endpoint.
public let endpoint: Endpoint?
/// Provides the name of the database engine to be used for this DB instance.
public let engine: String?
/// Indicates the database engine version.
public let engineVersion: String?
/// The Amazon Resource Name (ARN) of the Amazon CloudWatch Logs log stream that receives the Enhanced Monitoring metrics data for the DB instance.
public let enhancedMonitoringResourceArn: String?
/// True if AWS Identity and Access Management (IAM) authentication is enabled, and otherwise false.
public let iAMDatabaseAuthenticationEnabled: Bool?
/// Provides the date and time the DB instance was created.
public let instanceCreateTime: Date?
/// Specifies the Provisioned IOPS (I/O operations per second) value.
public let iops: Int?
/// Not supported: The encryption for DB instances is managed by the DB cluster.
public let kmsKeyId: String?
/// Specifies the latest time to which a database can be restored with point-in-time restore.
public let latestRestorableTime: Date?
/// License model information for this DB instance.
public let licenseModel: String?
/// Contains the master username for the DB instance.
public let masterUsername: String?
/// The interval, in seconds, between points when Enhanced Monitoring metrics are collected for the DB instance.
public let monitoringInterval: Int?
/// The ARN for the IAM role that permits Neptune to send Enhanced Monitoring metrics to Amazon CloudWatch Logs.
public let monitoringRoleArn: String?
/// Specifies if the DB instance is a Multi-AZ deployment.
public let multiAZ: Bool?
/// (Not supported by Neptune)
@OptionalCustomCoding<ArrayCoder<_OptionGroupMembershipsEncoding, OptionGroupMembership>>
public var optionGroupMemberships: [OptionGroupMembership]?
/// Specifies that changes to the DB instance are pending. This element is only included when changes are pending. Specific changes are identified by subelements.
public let pendingModifiedValues: PendingModifiedValues?
/// (Not supported by Neptune)
public let performanceInsightsEnabled: Bool?
/// (Not supported by Neptune)
public let performanceInsightsKMSKeyId: String?
/// Specifies the daily time range during which automated backups are created if automated backups are enabled, as determined by the BackupRetentionPeriod.
public let preferredBackupWindow: String?
/// Specifies the weekly time range during which system maintenance can occur, in Universal Coordinated Time (UTC).
public let preferredMaintenanceWindow: String?
/// A value that specifies the order in which a Read Replica is promoted to the primary instance after a failure of the existing primary instance.
public let promotionTier: Int?
/// Contains one or more identifiers of DB clusters that are Read Replicas of this DB instance.
@OptionalCustomCoding<ArrayCoder<_ReadReplicaDBClusterIdentifiersEncoding, String>>
public var readReplicaDBClusterIdentifiers: [String]?
/// Contains one or more identifiers of the Read Replicas associated with this DB instance.
@OptionalCustomCoding<ArrayCoder<_ReadReplicaDBInstanceIdentifiersEncoding, String>>
public var readReplicaDBInstanceIdentifiers: [String]?
/// Contains the identifier of the source DB instance if this DB instance is a Read Replica.
public let readReplicaSourceDBInstanceIdentifier: String?
/// If present, specifies the name of the secondary Availability Zone for a DB instance with multi-AZ support.
public let secondaryAvailabilityZone: String?
/// The status of a Read Replica. If the instance is not a Read Replica, this is blank.
@OptionalCustomCoding<ArrayCoder<_StatusInfosEncoding, DBInstanceStatusInfo>>
public var statusInfos: [DBInstanceStatusInfo]?
/// Not supported: The encryption for DB instances is managed by the DB cluster.
public let storageEncrypted: Bool?
/// Specifies the storage type associated with DB instance.
public let storageType: String?
/// The ARN from the key store with which the instance is associated for TDE encryption.
public let tdeCredentialArn: String?
/// Not supported.
public let timezone: String?
/// Provides a list of VPC security group elements that the DB instance belongs to.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupsEncoding, VpcSecurityGroupMembership>>
public var vpcSecurityGroups: [VpcSecurityGroupMembership]?
public init(allocatedStorage: Int? = nil, autoMinorVersionUpgrade: Bool? = nil, availabilityZone: String? = nil, backupRetentionPeriod: Int? = nil, cACertificateIdentifier: String? = nil, characterSetName: String? = nil, copyTagsToSnapshot: Bool? = nil, dBClusterIdentifier: String? = nil, dBInstanceArn: String? = nil, dBInstanceClass: String? = nil, dBInstanceIdentifier: String? = nil, dbInstancePort: Int? = nil, dBInstanceStatus: String? = nil, dbiResourceId: String? = nil, dBName: String? = nil, dBParameterGroups: [DBParameterGroupStatus]? = nil, dBSecurityGroups: [DBSecurityGroupMembership]? = nil, dBSubnetGroup: DBSubnetGroup? = nil, deletionProtection: Bool? = nil, domainMemberships: [DomainMembership]? = nil, enabledCloudwatchLogsExports: [String]? = nil, endpoint: Endpoint? = nil, engine: String? = nil, engineVersion: String? = nil, enhancedMonitoringResourceArn: String? = nil, iAMDatabaseAuthenticationEnabled: Bool? = nil, instanceCreateTime: Date? = nil, iops: Int? = nil, kmsKeyId: String? = nil, latestRestorableTime: Date? = nil, licenseModel: String? = nil, masterUsername: String? = nil, monitoringInterval: Int? = nil, monitoringRoleArn: String? = nil, multiAZ: Bool? = nil, optionGroupMemberships: [OptionGroupMembership]? = nil, pendingModifiedValues: PendingModifiedValues? = nil, performanceInsightsEnabled: Bool? = nil, performanceInsightsKMSKeyId: String? = nil, preferredBackupWindow: String? = nil, preferredMaintenanceWindow: String? = nil, promotionTier: Int? = nil, readReplicaDBClusterIdentifiers: [String]? = nil, readReplicaDBInstanceIdentifiers: [String]? = nil, readReplicaSourceDBInstanceIdentifier: String? = nil, secondaryAvailabilityZone: String? = nil, statusInfos: [DBInstanceStatusInfo]? = nil, storageEncrypted: Bool? = nil, storageType: String? = nil, tdeCredentialArn: String? = nil, timezone: String? = nil, vpcSecurityGroups: [VpcSecurityGroupMembership]? = nil) {
self.allocatedStorage = allocatedStorage
self.autoMinorVersionUpgrade = autoMinorVersionUpgrade
self.availabilityZone = availabilityZone
self.backupRetentionPeriod = backupRetentionPeriod
self.cACertificateIdentifier = cACertificateIdentifier
self.characterSetName = characterSetName
self.copyTagsToSnapshot = copyTagsToSnapshot
self.dBClusterIdentifier = dBClusterIdentifier
self.dBInstanceArn = dBInstanceArn
self.dBInstanceClass = dBInstanceClass
self.dBInstanceIdentifier = dBInstanceIdentifier
self.dbInstancePort = dbInstancePort
self.dBInstanceStatus = dBInstanceStatus
self.dbiResourceId = dbiResourceId
self.dBName = dBName
self.dBParameterGroups = dBParameterGroups
self.dBSecurityGroups = dBSecurityGroups
self.dBSubnetGroup = dBSubnetGroup
self.deletionProtection = deletionProtection
self.domainMemberships = domainMemberships
self.enabledCloudwatchLogsExports = enabledCloudwatchLogsExports
self.endpoint = endpoint
self.engine = engine
self.engineVersion = engineVersion
self.enhancedMonitoringResourceArn = enhancedMonitoringResourceArn
self.iAMDatabaseAuthenticationEnabled = iAMDatabaseAuthenticationEnabled
self.instanceCreateTime = instanceCreateTime
self.iops = iops
self.kmsKeyId = kmsKeyId
self.latestRestorableTime = latestRestorableTime
self.licenseModel = licenseModel
self.masterUsername = masterUsername
self.monitoringInterval = monitoringInterval
self.monitoringRoleArn = monitoringRoleArn
self.multiAZ = multiAZ
self.optionGroupMemberships = optionGroupMemberships
self.pendingModifiedValues = pendingModifiedValues
self.performanceInsightsEnabled = performanceInsightsEnabled
self.performanceInsightsKMSKeyId = performanceInsightsKMSKeyId
self.preferredBackupWindow = preferredBackupWindow
self.preferredMaintenanceWindow = preferredMaintenanceWindow
self.promotionTier = promotionTier
self.readReplicaDBClusterIdentifiers = readReplicaDBClusterIdentifiers
self.readReplicaDBInstanceIdentifiers = readReplicaDBInstanceIdentifiers
self.readReplicaSourceDBInstanceIdentifier = readReplicaSourceDBInstanceIdentifier
self.secondaryAvailabilityZone = secondaryAvailabilityZone
self.statusInfos = statusInfos
self.storageEncrypted = storageEncrypted
self.storageType = storageType
self.tdeCredentialArn = tdeCredentialArn
self.timezone = timezone
self.vpcSecurityGroups = vpcSecurityGroups
}
private enum CodingKeys: String, CodingKey {
case allocatedStorage = "AllocatedStorage"
case autoMinorVersionUpgrade = "AutoMinorVersionUpgrade"
case availabilityZone = "AvailabilityZone"
case backupRetentionPeriod = "BackupRetentionPeriod"
case cACertificateIdentifier = "CACertificateIdentifier"
case characterSetName = "CharacterSetName"
case copyTagsToSnapshot = "CopyTagsToSnapshot"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBInstanceArn = "DBInstanceArn"
case dBInstanceClass = "DBInstanceClass"
case dBInstanceIdentifier = "DBInstanceIdentifier"
case dbInstancePort = "DbInstancePort"
case dBInstanceStatus = "DBInstanceStatus"
case dbiResourceId = "DbiResourceId"
case dBName = "DBName"
case dBParameterGroups = "DBParameterGroups"
case dBSecurityGroups = "DBSecurityGroups"
case dBSubnetGroup = "DBSubnetGroup"
case deletionProtection = "DeletionProtection"
case domainMemberships = "DomainMemberships"
case enabledCloudwatchLogsExports = "EnabledCloudwatchLogsExports"
case endpoint = "Endpoint"
case engine = "Engine"
case engineVersion = "EngineVersion"
case enhancedMonitoringResourceArn = "EnhancedMonitoringResourceArn"
case iAMDatabaseAuthenticationEnabled = "IAMDatabaseAuthenticationEnabled"
case instanceCreateTime = "InstanceCreateTime"
case iops = "Iops"
case kmsKeyId = "KmsKeyId"
case latestRestorableTime = "LatestRestorableTime"
case licenseModel = "LicenseModel"
case masterUsername = "MasterUsername"
case monitoringInterval = "MonitoringInterval"
case monitoringRoleArn = "MonitoringRoleArn"
case multiAZ = "MultiAZ"
case optionGroupMemberships = "OptionGroupMemberships"
case pendingModifiedValues = "PendingModifiedValues"
case performanceInsightsEnabled = "PerformanceInsightsEnabled"
case performanceInsightsKMSKeyId = "PerformanceInsightsKMSKeyId"
case preferredBackupWindow = "PreferredBackupWindow"
case preferredMaintenanceWindow = "PreferredMaintenanceWindow"
case promotionTier = "PromotionTier"
case readReplicaDBClusterIdentifiers = "ReadReplicaDBClusterIdentifiers"
case readReplicaDBInstanceIdentifiers = "ReadReplicaDBInstanceIdentifiers"
case readReplicaSourceDBInstanceIdentifier = "ReadReplicaSourceDBInstanceIdentifier"
case secondaryAvailabilityZone = "SecondaryAvailabilityZone"
case statusInfos = "StatusInfos"
case storageEncrypted = "StorageEncrypted"
case storageType = "StorageType"
case tdeCredentialArn = "TdeCredentialArn"
case timezone = "Timezone"
case vpcSecurityGroups = "VpcSecurityGroups"
}
}
public struct DBInstanceMessage: AWSDecodableShape {
public struct _DBInstancesEncoding: ArrayCoderProperties { public static let member = "DBInstance" }
/// A list of DBInstance instances.
@OptionalCustomCoding<ArrayCoder<_DBInstancesEncoding, DBInstance>>
public var dBInstances: [DBInstance]?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
public init(dBInstances: [DBInstance]? = nil, marker: String? = nil) {
self.dBInstances = dBInstances
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBInstances = "DBInstances"
case marker = "Marker"
}
}
public struct DBInstanceStatusInfo: AWSDecodableShape {
/// Details of the error if there is an error for the instance. If the instance is not in an error state, this value is blank.
public let message: String?
/// Boolean value that is true if the instance is operating normally, or false if the instance is in an error state.
public let normal: Bool?
/// Status of the DB instance. For a StatusType of read replica, the values can be replicating, error, stopped, or terminated.
public let status: String?
/// This value is currently "read replication."
public let statusType: String?
public init(message: String? = nil, normal: Bool? = nil, status: String? = nil, statusType: String? = nil) {
self.message = message
self.normal = normal
self.status = status
self.statusType = statusType
}
private enum CodingKeys: String, CodingKey {
case message = "Message"
case normal = "Normal"
case status = "Status"
case statusType = "StatusType"
}
}
public struct DBParameterGroup: AWSDecodableShape {
/// The Amazon Resource Name (ARN) for the DB parameter group.
public let dBParameterGroupArn: String?
/// Provides the name of the DB parameter group family that this DB parameter group is compatible with.
public let dBParameterGroupFamily: String?
/// Provides the name of the DB parameter group.
public let dBParameterGroupName: String?
/// Provides the customer-specified description for this DB parameter group.
public let description: String?
public init(dBParameterGroupArn: String? = nil, dBParameterGroupFamily: String? = nil, dBParameterGroupName: String? = nil, description: String? = nil) {
self.dBParameterGroupArn = dBParameterGroupArn
self.dBParameterGroupFamily = dBParameterGroupFamily
self.dBParameterGroupName = dBParameterGroupName
self.description = description
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupArn = "DBParameterGroupArn"
case dBParameterGroupFamily = "DBParameterGroupFamily"
case dBParameterGroupName = "DBParameterGroupName"
case description = "Description"
}
}
public struct DBParameterGroupDetails: AWSDecodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// A list of Parameter values.
@OptionalCustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]?
public init(marker: String? = nil, parameters: [Parameter]? = nil) {
self.marker = marker
self.parameters = parameters
}
private enum CodingKeys: String, CodingKey {
case marker = "Marker"
case parameters = "Parameters"
}
}
public struct DBParameterGroupNameMessage: AWSDecodableShape {
/// Provides the name of the DB parameter group.
public let dBParameterGroupName: String?
public init(dBParameterGroupName: String? = nil) {
self.dBParameterGroupName = dBParameterGroupName
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
}
}
public struct DBParameterGroupStatus: AWSDecodableShape {
/// The name of the DP parameter group.
public let dBParameterGroupName: String?
/// The status of parameter updates.
public let parameterApplyStatus: String?
public init(dBParameterGroupName: String? = nil, parameterApplyStatus: String? = nil) {
self.dBParameterGroupName = dBParameterGroupName
self.parameterApplyStatus = parameterApplyStatus
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
case parameterApplyStatus = "ParameterApplyStatus"
}
}
public struct DBParameterGroupsMessage: AWSDecodableShape {
public struct _DBParameterGroupsEncoding: ArrayCoderProperties { public static let member = "DBParameterGroup" }
/// A list of DBParameterGroup instances.
@OptionalCustomCoding<ArrayCoder<_DBParameterGroupsEncoding, DBParameterGroup>>
public var dBParameterGroups: [DBParameterGroup]?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
public init(dBParameterGroups: [DBParameterGroup]? = nil, marker: String? = nil) {
self.dBParameterGroups = dBParameterGroups
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroups = "DBParameterGroups"
case marker = "Marker"
}
}
public struct DBSecurityGroupMembership: AWSDecodableShape {
/// The name of the DB security group.
public let dBSecurityGroupName: String?
/// The status of the DB security group.
public let status: String?
public init(dBSecurityGroupName: String? = nil, status: String? = nil) {
self.dBSecurityGroupName = dBSecurityGroupName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case dBSecurityGroupName = "DBSecurityGroupName"
case status = "Status"
}
}
public struct DBSubnetGroup: AWSDecodableShape {
public struct _SubnetsEncoding: ArrayCoderProperties { public static let member = "Subnet" }
/// The Amazon Resource Name (ARN) for the DB subnet group.
public let dBSubnetGroupArn: String?
/// Provides the description of the DB subnet group.
public let dBSubnetGroupDescription: String?
/// The name of the DB subnet group.
public let dBSubnetGroupName: String?
/// Provides the status of the DB subnet group.
public let subnetGroupStatus: String?
/// Contains a list of Subnet elements.
@OptionalCustomCoding<ArrayCoder<_SubnetsEncoding, Subnet>>
public var subnets: [Subnet]?
/// Provides the VpcId of the DB subnet group.
public let vpcId: String?
public init(dBSubnetGroupArn: String? = nil, dBSubnetGroupDescription: String? = nil, dBSubnetGroupName: String? = nil, subnetGroupStatus: String? = nil, subnets: [Subnet]? = nil, vpcId: String? = nil) {
self.dBSubnetGroupArn = dBSubnetGroupArn
self.dBSubnetGroupDescription = dBSubnetGroupDescription
self.dBSubnetGroupName = dBSubnetGroupName
self.subnetGroupStatus = subnetGroupStatus
self.subnets = subnets
self.vpcId = vpcId
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroupArn = "DBSubnetGroupArn"
case dBSubnetGroupDescription = "DBSubnetGroupDescription"
case dBSubnetGroupName = "DBSubnetGroupName"
case subnetGroupStatus = "SubnetGroupStatus"
case subnets = "Subnets"
case vpcId = "VpcId"
}
}
public struct DBSubnetGroupMessage: AWSDecodableShape {
public struct _DBSubnetGroupsEncoding: ArrayCoderProperties { public static let member = "DBSubnetGroup" }
/// A list of DBSubnetGroup instances.
@OptionalCustomCoding<ArrayCoder<_DBSubnetGroupsEncoding, DBSubnetGroup>>
public var dBSubnetGroups: [DBSubnetGroup]?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
public init(dBSubnetGroups: [DBSubnetGroup]? = nil, marker: String? = nil) {
self.dBSubnetGroups = dBSubnetGroups
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroups = "DBSubnetGroups"
case marker = "Marker"
}
}
public struct DeleteDBClusterMessage: AWSEncodableShape {
/// The DB cluster identifier for the DB cluster to be deleted. This parameter isn't case-sensitive. Constraints: Must match an existing DBClusterIdentifier.
public let dBClusterIdentifier: String
/// The DB cluster snapshot identifier of the new DB cluster snapshot created when SkipFinalSnapshot is set to false. Specifying this parameter and also setting the SkipFinalShapshot parameter to true results in an error. Constraints: Must be 1 to 255 letters, numbers, or hyphens. First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
public let finalDBSnapshotIdentifier: String?
/// Determines whether a final DB cluster snapshot is created before the DB cluster is deleted. If true is specified, no DB cluster snapshot is created. If false is specified, a DB cluster snapshot is created before the DB cluster is deleted. You must specify a FinalDBSnapshotIdentifier parameter if SkipFinalSnapshot is false. Default: false
public let skipFinalSnapshot: Bool?
public init(dBClusterIdentifier: String, finalDBSnapshotIdentifier: String? = nil, skipFinalSnapshot: Bool? = nil) {
self.dBClusterIdentifier = dBClusterIdentifier
self.finalDBSnapshotIdentifier = finalDBSnapshotIdentifier
self.skipFinalSnapshot = skipFinalSnapshot
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case finalDBSnapshotIdentifier = "FinalDBSnapshotIdentifier"
case skipFinalSnapshot = "SkipFinalSnapshot"
}
}
public struct DeleteDBClusterParameterGroupMessage: AWSEncodableShape {
/// The name of the DB cluster parameter group. Constraints: Must be the name of an existing DB cluster parameter group. You can't delete a default DB cluster parameter group. Cannot be associated with any DB clusters.
public let dBClusterParameterGroupName: String
public init(dBClusterParameterGroupName: String) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
}
}
public struct DeleteDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct DeleteDBClusterSnapshotMessage: AWSEncodableShape {
/// The identifier of the DB cluster snapshot to delete. Constraints: Must be the name of an existing DB cluster snapshot in the available state.
public let dBClusterSnapshotIdentifier: String
public init(dBClusterSnapshotIdentifier: String) {
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
}
}
public struct DeleteDBClusterSnapshotResult: AWSDecodableShape {
public let dBClusterSnapshot: DBClusterSnapshot?
public init(dBClusterSnapshot: DBClusterSnapshot? = nil) {
self.dBClusterSnapshot = dBClusterSnapshot
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshot = "DBClusterSnapshot"
}
}
public struct DeleteDBInstanceMessage: AWSEncodableShape {
/// The DB instance identifier for the DB instance to be deleted. This parameter isn't case-sensitive. Constraints: Must match the name of an existing DB instance.
public let dBInstanceIdentifier: String
/// The DBSnapshotIdentifier of the new DBSnapshot created when SkipFinalSnapshot is set to false. Specifying this parameter and also setting the SkipFinalShapshot parameter to true results in an error. Constraints: Must be 1 to 255 letters or numbers. First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens Cannot be specified when deleting a Read Replica.
public let finalDBSnapshotIdentifier: String?
/// Determines whether a final DB snapshot is created before the DB instance is deleted. If true is specified, no DBSnapshot is created. If false is specified, a DB snapshot is created before the DB instance is deleted. Note that when a DB instance is in a failure state and has a status of 'failed', 'incompatible-restore', or 'incompatible-network', it can only be deleted when the SkipFinalSnapshot parameter is set to "true". Specify true when deleting a Read Replica. The FinalDBSnapshotIdentifier parameter must be specified if SkipFinalSnapshot is false. Default: false
public let skipFinalSnapshot: Bool?
public init(dBInstanceIdentifier: String, finalDBSnapshotIdentifier: String? = nil, skipFinalSnapshot: Bool? = nil) {
self.dBInstanceIdentifier = dBInstanceIdentifier
self.finalDBSnapshotIdentifier = finalDBSnapshotIdentifier
self.skipFinalSnapshot = skipFinalSnapshot
}
private enum CodingKeys: String, CodingKey {
case dBInstanceIdentifier = "DBInstanceIdentifier"
case finalDBSnapshotIdentifier = "FinalDBSnapshotIdentifier"
case skipFinalSnapshot = "SkipFinalSnapshot"
}
}
public struct DeleteDBInstanceResult: AWSDecodableShape {
public let dBInstance: DBInstance?
public init(dBInstance: DBInstance? = nil) {
self.dBInstance = dBInstance
}
private enum CodingKeys: String, CodingKey {
case dBInstance = "DBInstance"
}
}
public struct DeleteDBParameterGroupMessage: AWSEncodableShape {
/// The name of the DB parameter group. Constraints: Must be the name of an existing DB parameter group You can't delete a default DB parameter group Cannot be associated with any DB instances
public let dBParameterGroupName: String
public init(dBParameterGroupName: String) {
self.dBParameterGroupName = dBParameterGroupName
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
}
}
public struct DeleteDBSubnetGroupMessage: AWSEncodableShape {
/// The name of the database subnet group to delete. You can't delete the default subnet group. Constraints: Constraints: Must match the name of an existing DBSubnetGroup. Must not be default. Example: mySubnetgroup
public let dBSubnetGroupName: String
public init(dBSubnetGroupName: String) {
self.dBSubnetGroupName = dBSubnetGroupName
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroupName = "DBSubnetGroupName"
}
}
public struct DeleteEventSubscriptionMessage: AWSEncodableShape {
/// The name of the event notification subscription you want to delete.
public let subscriptionName: String
public init(subscriptionName: String) {
self.subscriptionName = subscriptionName
}
private enum CodingKeys: String, CodingKey {
case subscriptionName = "SubscriptionName"
}
}
public struct DeleteEventSubscriptionResult: AWSDecodableShape {
public let eventSubscription: EventSubscription?
public init(eventSubscription: EventSubscription? = nil) {
self.eventSubscription = eventSubscription
}
private enum CodingKeys: String, CodingKey {
case eventSubscription = "EventSubscription"
}
}
public struct DescribeDBClusterParameterGroupsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of a specific DB cluster parameter group to return details for. Constraints: If supplied, must match the name of an existing DBClusterParameterGroup.
public let dBClusterParameterGroupName: String?
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBClusterParameterGroups request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBClusterParameterGroupName: String? = nil, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeDBClusterParametersMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of a specific DB cluster parameter group to return parameter details for. Constraints: If supplied, must match the name of an existing DBClusterParameterGroup.
public let dBClusterParameterGroupName: String
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBClusterParameters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// A value that indicates to return only parameters for a specific source. Parameter sources can be engine, service, or customer.
public let source: String?
public init(dBClusterParameterGroupName: String, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil, source: String? = nil) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
self.source = source
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
case source = "Source"
}
}
public struct DescribeDBClusterSnapshotAttributesMessage: AWSEncodableShape {
/// The identifier for the DB cluster snapshot to describe the attributes for.
public let dBClusterSnapshotIdentifier: String
public init(dBClusterSnapshotIdentifier: String) {
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
}
}
public struct DescribeDBClusterSnapshotAttributesResult: AWSDecodableShape {
public let dBClusterSnapshotAttributesResult: DBClusterSnapshotAttributesResult?
public init(dBClusterSnapshotAttributesResult: DBClusterSnapshotAttributesResult? = nil) {
self.dBClusterSnapshotAttributesResult = dBClusterSnapshotAttributesResult
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshotAttributesResult = "DBClusterSnapshotAttributesResult"
}
}
public struct DescribeDBClusterSnapshotsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The ID of the DB cluster to retrieve the list of DB cluster snapshots for. This parameter can't be used in conjunction with the DBClusterSnapshotIdentifier parameter. This parameter is not case-sensitive. Constraints: If supplied, must match the identifier of an existing DBCluster.
public let dBClusterIdentifier: String?
/// A specific DB cluster snapshot identifier to describe. This parameter can't be used in conjunction with the DBClusterIdentifier parameter. This value is stored as a lowercase string. Constraints: If supplied, must match the identifier of an existing DBClusterSnapshot. If this identifier is for an automated snapshot, the SnapshotType parameter must also be specified.
public let dBClusterSnapshotIdentifier: String?
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// True to include manual DB cluster snapshots that are public and can be copied or restored by any AWS account, and otherwise false. The default is false. The default is false. You can share a manual DB cluster snapshot as public by using the ModifyDBClusterSnapshotAttribute API action.
public let includePublic: Bool?
/// True to include shared manual DB cluster snapshots from other AWS accounts that this AWS account has been given permission to copy or restore, and otherwise false. The default is false. You can give an AWS account permission to restore a manual DB cluster snapshot from another AWS account by the ModifyDBClusterSnapshotAttribute API action.
public let includeShared: Bool?
/// An optional pagination token provided by a previous DescribeDBClusterSnapshots request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// The type of DB cluster snapshots to be returned. You can specify one of the following values: automated - Return all DB cluster snapshots that have been automatically taken by Amazon Neptune for my AWS account. manual - Return all DB cluster snapshots that have been taken by my AWS account. shared - Return all manual DB cluster snapshots that have been shared to my AWS account. public - Return all DB cluster snapshots that have been marked as public. If you don't specify a SnapshotType value, then both automated and manual DB cluster snapshots are returned. You can include shared DB cluster snapshots with these results by setting the IncludeShared parameter to true. You can include public DB cluster snapshots with these results by setting the IncludePublic parameter to true. The IncludeShared and IncludePublic parameters don't apply for SnapshotType values of manual or automated. The IncludePublic parameter doesn't apply when SnapshotType is set to shared. The IncludeShared parameter doesn't apply when SnapshotType is set to public.
public let snapshotType: String?
public init(dBClusterIdentifier: String? = nil, dBClusterSnapshotIdentifier: String? = nil, filters: [Filter]? = nil, includePublic: Bool? = nil, includeShared: Bool? = nil, marker: String? = nil, maxRecords: Int? = nil, snapshotType: String? = nil) {
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
self.filters = filters
self.includePublic = includePublic
self.includeShared = includeShared
self.marker = marker
self.maxRecords = maxRecords
self.snapshotType = snapshotType
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
case filters = "Filters"
case includePublic = "IncludePublic"
case includeShared = "IncludeShared"
case marker = "Marker"
case maxRecords = "MaxRecords"
case snapshotType = "SnapshotType"
}
}
public struct DescribeDBClustersMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The user-supplied DB cluster identifier. If this parameter is specified, information from only the specific DB cluster is returned. This parameter isn't case-sensitive. Constraints: If supplied, must match an existing DBClusterIdentifier.
public let dBClusterIdentifier: String?
/// A filter that specifies one or more DB clusters to describe. Supported filters: db-cluster-id - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The results list will only include information about the DB clusters identified by these ARNs. engine - Accepts an engine name (such as neptune), and restricts the results list to DB clusters created by that engine. For example, to invoke this API from the AWS CLI and filter so that only Neptune DB clusters are returned, you could use the following command:
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBClusters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBClusterIdentifier: String? = nil, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBClusterIdentifier = dBClusterIdentifier
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeDBEngineVersionsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of a specific DB parameter group family to return details for. Constraints: If supplied, must match an existing DBParameterGroupFamily.
public let dBParameterGroupFamily: String?
/// Indicates that only the default version of the specified engine or engine and major version combination is returned.
public let defaultOnly: Bool?
/// The database engine to return.
public let engine: String?
/// The database engine version to return. Example: 5.1.49
public let engineVersion: String?
/// Not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// If this parameter is specified and the requested engine supports the CharacterSetName parameter for CreateDBInstance, the response includes a list of supported character sets for each engine version.
public let listSupportedCharacterSets: Bool?
/// If this parameter is specified and the requested engine supports the TimeZone parameter for CreateDBInstance, the response includes a list of supported time zones for each engine version.
public let listSupportedTimezones: Bool?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more than the MaxRecords value is available, a pagination token called a marker is included in the response so that the following results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBParameterGroupFamily: String? = nil, defaultOnly: Bool? = nil, engine: String? = nil, engineVersion: String? = nil, filters: [Filter]? = nil, listSupportedCharacterSets: Bool? = nil, listSupportedTimezones: Bool? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBParameterGroupFamily = dBParameterGroupFamily
self.defaultOnly = defaultOnly
self.engine = engine
self.engineVersion = engineVersion
self.filters = filters
self.listSupportedCharacterSets = listSupportedCharacterSets
self.listSupportedTimezones = listSupportedTimezones
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupFamily = "DBParameterGroupFamily"
case defaultOnly = "DefaultOnly"
case engine = "Engine"
case engineVersion = "EngineVersion"
case filters = "Filters"
case listSupportedCharacterSets = "ListSupportedCharacterSets"
case listSupportedTimezones = "ListSupportedTimezones"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeDBInstancesMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The user-supplied instance identifier. If this parameter is specified, information from only the specific DB instance is returned. This parameter isn't case-sensitive. Constraints: If supplied, must match the identifier of an existing DBInstance.
public let dBInstanceIdentifier: String?
/// A filter that specifies one or more DB instances to describe. Supported filters: db-cluster-id - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The results list will only include information about the DB instances associated with the DB clusters identified by these ARNs. engine - Accepts an engine name (such as neptune), and restricts the results list to DB instances created by that engine. For example, to invoke this API from the AWS CLI and filter so that only Neptune DB instances are returned, you could use the following command:
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBInstances request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBInstanceIdentifier: String? = nil, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBInstanceIdentifier = dBInstanceIdentifier
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBInstanceIdentifier = "DBInstanceIdentifier"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeDBParameterGroupsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of a specific DB parameter group to return details for. Constraints: If supplied, must match the name of an existing DBClusterParameterGroup.
public let dBParameterGroupName: String?
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBParameterGroups request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBParameterGroupName: String? = nil, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBParameterGroupName = dBParameterGroupName
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeDBParametersMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of a specific DB parameter group to return details for. Constraints: If supplied, must match the name of an existing DBParameterGroup.
public let dBParameterGroupName: String
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBParameters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// The parameter types to return. Default: All parameter types returned Valid Values: user | system | engine-default
public let source: String?
public init(dBParameterGroupName: String, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil, source: String? = nil) {
self.dBParameterGroupName = dBParameterGroupName
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
self.source = source
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
case source = "Source"
}
}
public struct DescribeDBSubnetGroupsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of the DB subnet group to return details for.
public let dBSubnetGroupName: String?
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeDBSubnetGroups request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBSubnetGroupName: String? = nil, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBSubnetGroupName = dBSubnetGroupName
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroupName = "DBSubnetGroupName"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeEngineDefaultClusterParametersMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of the DB cluster parameter group family to return engine parameter information for.
public let dBParameterGroupFamily: String
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeEngineDefaultClusterParameters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBParameterGroupFamily: String, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBParameterGroupFamily = dBParameterGroupFamily
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupFamily = "DBParameterGroupFamily"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeEngineDefaultClusterParametersResult: AWSDecodableShape {
public let engineDefaults: EngineDefaults?
public init(engineDefaults: EngineDefaults? = nil) {
self.engineDefaults = engineDefaults
}
private enum CodingKeys: String, CodingKey {
case engineDefaults = "EngineDefaults"
}
}
public struct DescribeEngineDefaultParametersMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The name of the DB parameter group family.
public let dBParameterGroupFamily: String
/// Not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeEngineDefaultParameters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
public init(dBParameterGroupFamily: String, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil) {
self.dBParameterGroupFamily = dBParameterGroupFamily
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupFamily = "DBParameterGroupFamily"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
}
}
public struct DescribeEngineDefaultParametersResult: AWSDecodableShape {
public let engineDefaults: EngineDefaults?
public init(engineDefaults: EngineDefaults? = nil) {
self.engineDefaults = engineDefaults
}
private enum CodingKeys: String, CodingKey {
case engineDefaults = "EngineDefaults"
}
}
public struct DescribeEventCategoriesMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// The type of source that is generating the events. Valid values: db-instance | db-parameter-group | db-security-group | db-snapshot
public let sourceType: String?
public init(filters: [Filter]? = nil, sourceType: String? = nil) {
self.filters = filters
self.sourceType = sourceType
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case sourceType = "SourceType"
}
}
public struct DescribeEventSubscriptionsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeOrderableDBInstanceOptions request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// The name of the event notification subscription you want to describe.
public let subscriptionName: String?
public init(filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil, subscriptionName: String? = nil) {
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
self.subscriptionName = subscriptionName
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
case subscriptionName = "SubscriptionName"
}
}
public struct DescribeEventsMessage: AWSEncodableShape {
public struct _EventCategoriesEncoding: ArrayCoderProperties { public static let member = "EventCategory" }
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The number of minutes to retrieve events for. Default: 60
public let duration: Int?
/// The end of the time interval for which to retrieve events, specified in ISO 8601 format. For more information about ISO 8601, go to the ISO8601 Wikipedia page. Example: 2009-07-08T18:00Z
public let endTime: Date?
/// A list of event categories that trigger notifications for a event notification subscription.
@OptionalCustomCoding<ArrayCoder<_EventCategoriesEncoding, String>>
public var eventCategories: [String]?
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribeEvents request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// The identifier of the event source for which events are returned. If not specified, then all sources are included in the response. Constraints: If SourceIdentifier is supplied, SourceType must also be provided. If the source type is DBInstance, then a DBInstanceIdentifier must be supplied. If the source type is DBSecurityGroup, a DBSecurityGroupName must be supplied. If the source type is DBParameterGroup, a DBParameterGroupName must be supplied. If the source type is DBSnapshot, a DBSnapshotIdentifier must be supplied. Cannot end with a hyphen or contain two consecutive hyphens.
public let sourceIdentifier: String?
/// The event source to retrieve events for. If no value is specified, all events are returned.
public let sourceType: SourceType?
/// The beginning of the time interval to retrieve events for, specified in ISO 8601 format. For more information about ISO 8601, go to the ISO8601 Wikipedia page. Example: 2009-07-08T18:00Z
public let startTime: Date?
public init(duration: Int? = nil, endTime: Date? = nil, eventCategories: [String]? = nil, filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil, sourceIdentifier: String? = nil, sourceType: SourceType? = nil, startTime: Date? = nil) {
self.duration = duration
self.endTime = endTime
self.eventCategories = eventCategories
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
self.sourceIdentifier = sourceIdentifier
self.sourceType = sourceType
self.startTime = startTime
}
private enum CodingKeys: String, CodingKey {
case duration = "Duration"
case endTime = "EndTime"
case eventCategories = "EventCategories"
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
case sourceIdentifier = "SourceIdentifier"
case sourceType = "SourceType"
case startTime = "StartTime"
}
}
public struct DescribeOrderableDBInstanceOptionsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// The DB instance class filter value. Specify this parameter to show only the available offerings matching the specified DB instance class.
public let dBInstanceClass: String?
/// The name of the engine to retrieve DB instance options for.
public let engine: String
/// The engine version filter value. Specify this parameter to show only the available offerings matching the specified engine version.
public let engineVersion: String?
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// The license model filter value. Specify this parameter to show only the available offerings matching the specified license model.
public let licenseModel: String?
/// An optional pagination token provided by a previous DescribeOrderableDBInstanceOptions request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// The VPC filter value. Specify this parameter to show only the available VPC or non-VPC offerings.
public let vpc: Bool?
public init(dBInstanceClass: String? = nil, engine: String, engineVersion: String? = nil, filters: [Filter]? = nil, licenseModel: String? = nil, marker: String? = nil, maxRecords: Int? = nil, vpc: Bool? = nil) {
self.dBInstanceClass = dBInstanceClass
self.engine = engine
self.engineVersion = engineVersion
self.filters = filters
self.licenseModel = licenseModel
self.marker = marker
self.maxRecords = maxRecords
self.vpc = vpc
}
private enum CodingKeys: String, CodingKey {
case dBInstanceClass = "DBInstanceClass"
case engine = "Engine"
case engineVersion = "EngineVersion"
case filters = "Filters"
case licenseModel = "LicenseModel"
case marker = "Marker"
case maxRecords = "MaxRecords"
case vpc = "Vpc"
}
}
public struct DescribePendingMaintenanceActionsMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// A filter that specifies one or more resources to return pending maintenance actions for. Supported filters: db-cluster-id - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The results list will only include pending maintenance actions for the DB clusters identified by these ARNs. db-instance-id - Accepts DB instance identifiers and DB instance ARNs. The results list will only include pending maintenance actions for the DB instances identified by these ARNs.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// An optional pagination token provided by a previous DescribePendingMaintenanceActions request. If this parameter is specified, the response includes only records beyond the marker, up to a number of records specified by MaxRecords.
public let marker: String?
/// The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100.
public let maxRecords: Int?
/// The ARN of a resource to return pending maintenance actions for.
public let resourceIdentifier: String?
public init(filters: [Filter]? = nil, marker: String? = nil, maxRecords: Int? = nil, resourceIdentifier: String? = nil) {
self.filters = filters
self.marker = marker
self.maxRecords = maxRecords
self.resourceIdentifier = resourceIdentifier
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case marker = "Marker"
case maxRecords = "MaxRecords"
case resourceIdentifier = "ResourceIdentifier"
}
}
public struct DescribeValidDBInstanceModificationsMessage: AWSEncodableShape {
/// The customer identifier or the ARN of your DB instance.
public let dBInstanceIdentifier: String
public init(dBInstanceIdentifier: String) {
self.dBInstanceIdentifier = dBInstanceIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBInstanceIdentifier = "DBInstanceIdentifier"
}
}
public struct DescribeValidDBInstanceModificationsResult: AWSDecodableShape {
public let validDBInstanceModificationsMessage: ValidDBInstanceModificationsMessage?
public init(validDBInstanceModificationsMessage: ValidDBInstanceModificationsMessage? = nil) {
self.validDBInstanceModificationsMessage = validDBInstanceModificationsMessage
}
private enum CodingKeys: String, CodingKey {
case validDBInstanceModificationsMessage = "ValidDBInstanceModificationsMessage"
}
}
public struct DomainMembership: AWSDecodableShape {
/// The identifier of the Active Directory Domain.
public let domain: String?
/// The fully qualified domain name of the Active Directory Domain.
public let fqdn: String?
/// The name of the IAM role to be used when making API calls to the Directory Service.
public let iAMRoleName: String?
/// The status of the DB instance's Active Directory Domain membership, such as joined, pending-join, failed etc).
public let status: String?
public init(domain: String? = nil, fqdn: String? = nil, iAMRoleName: String? = nil, status: String? = nil) {
self.domain = domain
self.fqdn = fqdn
self.iAMRoleName = iAMRoleName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case domain = "Domain"
case fqdn = "FQDN"
case iAMRoleName = "IAMRoleName"
case status = "Status"
}
}
public struct DoubleRange: AWSDecodableShape {
/// The minimum value in the range.
public let from: Double?
/// The maximum value in the range.
public let to: Double?
public init(from: Double? = nil, to: Double? = nil) {
self.from = from
self.to = to
}
private enum CodingKeys: String, CodingKey {
case from = "From"
case to = "To"
}
}
public struct Endpoint: AWSDecodableShape {
/// Specifies the DNS address of the DB instance.
public let address: String?
/// Specifies the ID that Amazon Route 53 assigns when you create a hosted zone.
public let hostedZoneId: String?
/// Specifies the port that the database engine is listening on.
public let port: Int?
public init(address: String? = nil, hostedZoneId: String? = nil, port: Int? = nil) {
self.address = address
self.hostedZoneId = hostedZoneId
self.port = port
}
private enum CodingKeys: String, CodingKey {
case address = "Address"
case hostedZoneId = "HostedZoneId"
case port = "Port"
}
}
public struct EngineDefaults: AWSDecodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// Specifies the name of the DB parameter group family that the engine default parameters apply to.
public let dBParameterGroupFamily: String?
/// An optional pagination token provided by a previous EngineDefaults request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
/// Contains a list of engine default parameters.
@OptionalCustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]?
public init(dBParameterGroupFamily: String? = nil, marker: String? = nil, parameters: [Parameter]? = nil) {
self.dBParameterGroupFamily = dBParameterGroupFamily
self.marker = marker
self.parameters = parameters
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupFamily = "DBParameterGroupFamily"
case marker = "Marker"
case parameters = "Parameters"
}
}
public struct Event: AWSDecodableShape {
public struct _EventCategoriesEncoding: ArrayCoderProperties { public static let member = "EventCategory" }
/// Specifies the date and time of the event.
public let date: Date?
/// Specifies the category for the event.
@OptionalCustomCoding<ArrayCoder<_EventCategoriesEncoding, String>>
public var eventCategories: [String]?
/// Provides the text of this event.
public let message: String?
/// The Amazon Resource Name (ARN) for the event.
public let sourceArn: String?
/// Provides the identifier for the source of the event.
public let sourceIdentifier: String?
/// Specifies the source type for this event.
public let sourceType: SourceType?
public init(date: Date? = nil, eventCategories: [String]? = nil, message: String? = nil, sourceArn: String? = nil, sourceIdentifier: String? = nil, sourceType: SourceType? = nil) {
self.date = date
self.eventCategories = eventCategories
self.message = message
self.sourceArn = sourceArn
self.sourceIdentifier = sourceIdentifier
self.sourceType = sourceType
}
private enum CodingKeys: String, CodingKey {
case date = "Date"
case eventCategories = "EventCategories"
case message = "Message"
case sourceArn = "SourceArn"
case sourceIdentifier = "SourceIdentifier"
case sourceType = "SourceType"
}
}
public struct EventCategoriesMap: AWSDecodableShape {
public struct _EventCategoriesEncoding: ArrayCoderProperties { public static let member = "EventCategory" }
/// The event categories for the specified source type
@OptionalCustomCoding<ArrayCoder<_EventCategoriesEncoding, String>>
public var eventCategories: [String]?
/// The source type that the returned categories belong to
public let sourceType: String?
public init(eventCategories: [String]? = nil, sourceType: String? = nil) {
self.eventCategories = eventCategories
self.sourceType = sourceType
}
private enum CodingKeys: String, CodingKey {
case eventCategories = "EventCategories"
case sourceType = "SourceType"
}
}
public struct EventCategoriesMessage: AWSDecodableShape {
public struct _EventCategoriesMapListEncoding: ArrayCoderProperties { public static let member = "EventCategoriesMap" }
/// A list of EventCategoriesMap data types.
@OptionalCustomCoding<ArrayCoder<_EventCategoriesMapListEncoding, EventCategoriesMap>>
public var eventCategoriesMapList: [EventCategoriesMap]?
public init(eventCategoriesMapList: [EventCategoriesMap]? = nil) {
self.eventCategoriesMapList = eventCategoriesMapList
}
private enum CodingKeys: String, CodingKey {
case eventCategoriesMapList = "EventCategoriesMapList"
}
}
public struct EventSubscription: AWSDecodableShape {
public struct _EventCategoriesListEncoding: ArrayCoderProperties { public static let member = "EventCategory" }
public struct _SourceIdsListEncoding: ArrayCoderProperties { public static let member = "SourceId" }
/// The AWS customer account associated with the event notification subscription.
public let customerAwsId: String?
/// The event notification subscription Id.
public let custSubscriptionId: String?
/// A Boolean value indicating if the subscription is enabled. True indicates the subscription is enabled.
public let enabled: Bool?
/// A list of event categories for the event notification subscription.
@OptionalCustomCoding<ArrayCoder<_EventCategoriesListEncoding, String>>
public var eventCategoriesList: [String]?
/// The Amazon Resource Name (ARN) for the event subscription.
public let eventSubscriptionArn: String?
/// The topic ARN of the event notification subscription.
public let snsTopicArn: String?
/// A list of source IDs for the event notification subscription.
@OptionalCustomCoding<ArrayCoder<_SourceIdsListEncoding, String>>
public var sourceIdsList: [String]?
/// The source type for the event notification subscription.
public let sourceType: String?
/// The status of the event notification subscription. Constraints: Can be one of the following: creating | modifying | deleting | active | no-permission | topic-not-exist The status "no-permission" indicates that Neptune no longer has permission to post to the SNS topic. The status "topic-not-exist" indicates that the topic was deleted after the subscription was created.
public let status: String?
/// The time the event notification subscription was created.
public let subscriptionCreationTime: String?
public init(customerAwsId: String? = nil, custSubscriptionId: String? = nil, enabled: Bool? = nil, eventCategoriesList: [String]? = nil, eventSubscriptionArn: String? = nil, snsTopicArn: String? = nil, sourceIdsList: [String]? = nil, sourceType: String? = nil, status: String? = nil, subscriptionCreationTime: String? = nil) {
self.customerAwsId = customerAwsId
self.custSubscriptionId = custSubscriptionId
self.enabled = enabled
self.eventCategoriesList = eventCategoriesList
self.eventSubscriptionArn = eventSubscriptionArn
self.snsTopicArn = snsTopicArn
self.sourceIdsList = sourceIdsList
self.sourceType = sourceType
self.status = status
self.subscriptionCreationTime = subscriptionCreationTime
}
private enum CodingKeys: String, CodingKey {
case customerAwsId = "CustomerAwsId"
case custSubscriptionId = "CustSubscriptionId"
case enabled = "Enabled"
case eventCategoriesList = "EventCategoriesList"
case eventSubscriptionArn = "EventSubscriptionArn"
case snsTopicArn = "SnsTopicArn"
case sourceIdsList = "SourceIdsList"
case sourceType = "SourceType"
case status = "Status"
case subscriptionCreationTime = "SubscriptionCreationTime"
}
}
public struct EventSubscriptionsMessage: AWSDecodableShape {
public struct _EventSubscriptionsListEncoding: ArrayCoderProperties { public static let member = "EventSubscription" }
/// A list of EventSubscriptions data types.
@OptionalCustomCoding<ArrayCoder<_EventSubscriptionsListEncoding, EventSubscription>>
public var eventSubscriptionsList: [EventSubscription]?
/// An optional pagination token provided by a previous DescribeOrderableDBInstanceOptions request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords.
public let marker: String?
public init(eventSubscriptionsList: [EventSubscription]? = nil, marker: String? = nil) {
self.eventSubscriptionsList = eventSubscriptionsList
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case eventSubscriptionsList = "EventSubscriptionsList"
case marker = "Marker"
}
}
public struct EventsMessage: AWSDecodableShape {
public struct _EventsEncoding: ArrayCoderProperties { public static let member = "Event" }
/// A list of Event instances.
@OptionalCustomCoding<ArrayCoder<_EventsEncoding, Event>>
public var events: [Event]?
/// An optional pagination token provided by a previous Events request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
public init(events: [Event]? = nil, marker: String? = nil) {
self.events = events
self.marker = marker
}
private enum CodingKeys: String, CodingKey {
case events = "Events"
case marker = "Marker"
}
}
public struct FailoverDBClusterMessage: AWSEncodableShape {
/// A DB cluster identifier to force a failover for. This parameter is not case-sensitive. Constraints: Must match the identifier of an existing DBCluster.
public let dBClusterIdentifier: String?
/// The name of the instance to promote to the primary instance. You must specify the instance identifier for an Read Replica in the DB cluster. For example, mydbcluster-replica1.
public let targetDBInstanceIdentifier: String?
public init(dBClusterIdentifier: String? = nil, targetDBInstanceIdentifier: String? = nil) {
self.dBClusterIdentifier = dBClusterIdentifier
self.targetDBInstanceIdentifier = targetDBInstanceIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case targetDBInstanceIdentifier = "TargetDBInstanceIdentifier"
}
}
public struct FailoverDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct Filter: AWSEncodableShape {
public struct _ValuesEncoding: ArrayCoderProperties { public static let member = "Value" }
/// This parameter is not currently supported.
public let name: String
/// This parameter is not currently supported.
@CustomCoding<ArrayCoder<_ValuesEncoding, String>>
public var values: [String]
public init(name: String, values: [String]) {
self.name = name
self.values = values
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case values = "Values"
}
}
public struct ListTagsForResourceMessage: AWSEncodableShape {
public struct _FiltersEncoding: ArrayCoderProperties { public static let member = "Filter" }
/// This parameter is not currently supported.
@OptionalCustomCoding<ArrayCoder<_FiltersEncoding, Filter>>
public var filters: [Filter]?
/// The Amazon Neptune resource with tags to be listed. This value is an Amazon Resource Name (ARN). For information about creating an ARN, see Constructing an Amazon Resource Name (ARN).
public let resourceName: String
public init(filters: [Filter]? = nil, resourceName: String) {
self.filters = filters
self.resourceName = resourceName
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case resourceName = "ResourceName"
}
}
public struct ModifyDBClusterMessage: AWSEncodableShape {
public struct _VpcSecurityGroupIdsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupId" }
/// A value that specifies whether the modifications in this request and any pending modifications are asynchronously applied as soon as possible, regardless of the PreferredMaintenanceWindow setting for the DB cluster. If this parameter is set to false, changes to the DB cluster are applied during the next maintenance window. The ApplyImmediately parameter only affects the NewDBClusterIdentifier and MasterUserPassword values. If you set the ApplyImmediately parameter value to false, then changes to the NewDBClusterIdentifier and MasterUserPassword values are applied during the next maintenance window. All other changes are applied immediately, regardless of the value of the ApplyImmediately parameter. Default: false
public let applyImmediately: Bool?
/// The number of days for which automated backups are retained. You must specify a minimum value of 1. Default: 1 Constraints: Must be a value from 1 to 35
public let backupRetentionPeriod: Int?
/// The configuration setting for the log types to be enabled for export to CloudWatch Logs for a specific DB cluster.
public let cloudwatchLogsExportConfiguration: CloudwatchLogsExportConfiguration?
/// The DB cluster identifier for the cluster being modified. This parameter is not case-sensitive. Constraints: Must match the identifier of an existing DBCluster.
public let dBClusterIdentifier: String
/// The name of the DB cluster parameter group to use for the DB cluster.
public let dBClusterParameterGroupName: String?
/// A value that indicates whether the DB cluster has deletion protection enabled. The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled.
public let deletionProtection: Bool?
/// True to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts, and otherwise false. Default: false
public let enableIAMDatabaseAuthentication: Bool?
/// The version number of the database engine. Currently, setting this parameter has no effect. To upgrade your database engine to the most recent release, use the ApplyPendingMaintenanceAction API. For a list of valid engine versions, see CreateDBInstance, or call DescribeDBEngineVersions.
public let engineVersion: String?
/// The new password for the master database user. This password can contain any printable ASCII character except "/", """, or "@". Constraints: Must contain from 8 to 41 characters.
public let masterUserPassword: String?
/// The new DB cluster identifier for the DB cluster when renaming a DB cluster. This value is stored as a lowercase string. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens The first character must be a letter Cannot end with a hyphen or contain two consecutive hyphens Example: my-cluster2
public let newDBClusterIdentifier: String?
/// (Not supported by Neptune)
public let optionGroupName: String?
/// The port number on which the DB cluster accepts connections. Constraints: Value must be 1150-65535 Default: The same port as the original DB cluster.
public let port: Int?
/// The daily time range during which automated backups are created if automated backups are enabled, using the BackupRetentionPeriod parameter. The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region. Constraints: Must be in the format hh24:mi-hh24:mi. Must be in Universal Coordinated Time (UTC). Must not conflict with the preferred maintenance window. Must be at least 30 minutes.
public let preferredBackupWindow: String?
/// The weekly time range during which system maintenance can occur, in Universal Coordinated Time (UTC). Format: ddd:hh24:mi-ddd:hh24:mi The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region, occurring on a random day of the week. Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun. Constraints: Minimum 30-minute window.
public let preferredMaintenanceWindow: String?
/// A list of VPC security groups that the DB cluster will belong to.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupIdsEncoding, String>>
public var vpcSecurityGroupIds: [String]?
public init(applyImmediately: Bool? = nil, backupRetentionPeriod: Int? = nil, cloudwatchLogsExportConfiguration: CloudwatchLogsExportConfiguration? = nil, dBClusterIdentifier: String, dBClusterParameterGroupName: String? = nil, deletionProtection: Bool? = nil, enableIAMDatabaseAuthentication: Bool? = nil, engineVersion: String? = nil, masterUserPassword: String? = nil, newDBClusterIdentifier: String? = nil, optionGroupName: String? = nil, port: Int? = nil, preferredBackupWindow: String? = nil, preferredMaintenanceWindow: String? = nil, vpcSecurityGroupIds: [String]? = nil) {
self.applyImmediately = applyImmediately
self.backupRetentionPeriod = backupRetentionPeriod
self.cloudwatchLogsExportConfiguration = cloudwatchLogsExportConfiguration
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.deletionProtection = deletionProtection
self.enableIAMDatabaseAuthentication = enableIAMDatabaseAuthentication
self.engineVersion = engineVersion
self.masterUserPassword = masterUserPassword
self.newDBClusterIdentifier = newDBClusterIdentifier
self.optionGroupName = optionGroupName
self.port = port
self.preferredBackupWindow = preferredBackupWindow
self.preferredMaintenanceWindow = preferredMaintenanceWindow
self.vpcSecurityGroupIds = vpcSecurityGroupIds
}
private enum CodingKeys: String, CodingKey {
case applyImmediately = "ApplyImmediately"
case backupRetentionPeriod = "BackupRetentionPeriod"
case cloudwatchLogsExportConfiguration = "CloudwatchLogsExportConfiguration"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case deletionProtection = "DeletionProtection"
case enableIAMDatabaseAuthentication = "EnableIAMDatabaseAuthentication"
case engineVersion = "EngineVersion"
case masterUserPassword = "MasterUserPassword"
case newDBClusterIdentifier = "NewDBClusterIdentifier"
case optionGroupName = "OptionGroupName"
case port = "Port"
case preferredBackupWindow = "PreferredBackupWindow"
case preferredMaintenanceWindow = "PreferredMaintenanceWindow"
case vpcSecurityGroupIds = "VpcSecurityGroupIds"
}
}
public struct ModifyDBClusterParameterGroupMessage: AWSEncodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// The name of the DB cluster parameter group to modify.
public let dBClusterParameterGroupName: String
/// A list of parameters in the DB cluster parameter group to modify.
@CustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]
public init(dBClusterParameterGroupName: String, parameters: [Parameter]) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.parameters = parameters
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case parameters = "Parameters"
}
}
public struct ModifyDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct ModifyDBClusterSnapshotAttributeMessage: AWSEncodableShape {
public struct _ValuesToAddEncoding: ArrayCoderProperties { public static let member = "AttributeValue" }
public struct _ValuesToRemoveEncoding: ArrayCoderProperties { public static let member = "AttributeValue" }
/// The name of the DB cluster snapshot attribute to modify. To manage authorization for other AWS accounts to copy or restore a manual DB cluster snapshot, set this value to restore.
public let attributeName: String
/// The identifier for the DB cluster snapshot to modify the attributes for.
public let dBClusterSnapshotIdentifier: String
/// A list of DB cluster snapshot attributes to add to the attribute specified by AttributeName. To authorize other AWS accounts to copy or restore a manual DB cluster snapshot, set this list to include one or more AWS account IDs, or all to make the manual DB cluster snapshot restorable by any AWS account. Do not add the all value for any manual DB cluster snapshots that contain private information that you don't want available to all AWS accounts.
@OptionalCustomCoding<ArrayCoder<_ValuesToAddEncoding, String>>
public var valuesToAdd: [String]?
/// A list of DB cluster snapshot attributes to remove from the attribute specified by AttributeName. To remove authorization for other AWS accounts to copy or restore a manual DB cluster snapshot, set this list to include one or more AWS account identifiers, or all to remove authorization for any AWS account to copy or restore the DB cluster snapshot. If you specify all, an AWS account whose account ID is explicitly added to the restore attribute can still copy or restore a manual DB cluster snapshot.
@OptionalCustomCoding<ArrayCoder<_ValuesToRemoveEncoding, String>>
public var valuesToRemove: [String]?
public init(attributeName: String, dBClusterSnapshotIdentifier: String, valuesToAdd: [String]? = nil, valuesToRemove: [String]? = nil) {
self.attributeName = attributeName
self.dBClusterSnapshotIdentifier = dBClusterSnapshotIdentifier
self.valuesToAdd = valuesToAdd
self.valuesToRemove = valuesToRemove
}
private enum CodingKeys: String, CodingKey {
case attributeName = "AttributeName"
case dBClusterSnapshotIdentifier = "DBClusterSnapshotIdentifier"
case valuesToAdd = "ValuesToAdd"
case valuesToRemove = "ValuesToRemove"
}
}
public struct ModifyDBClusterSnapshotAttributeResult: AWSDecodableShape {
public let dBClusterSnapshotAttributesResult: DBClusterSnapshotAttributesResult?
public init(dBClusterSnapshotAttributesResult: DBClusterSnapshotAttributesResult? = nil) {
self.dBClusterSnapshotAttributesResult = dBClusterSnapshotAttributesResult
}
private enum CodingKeys: String, CodingKey {
case dBClusterSnapshotAttributesResult = "DBClusterSnapshotAttributesResult"
}
}
public struct ModifyDBInstanceMessage: AWSEncodableShape {
public struct _DBSecurityGroupsEncoding: ArrayCoderProperties { public static let member = "DBSecurityGroupName" }
public struct _VpcSecurityGroupIdsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupId" }
/// The new amount of storage (in gibibytes) to allocate for the DB instance. Not applicable. Storage is managed by the DB Cluster.
public let allocatedStorage: Int?
/// Indicates that major version upgrades are allowed. Changing this parameter doesn't result in an outage and the change is asynchronously applied as soon as possible.
public let allowMajorVersionUpgrade: Bool?
/// Specifies whether the modifications in this request and any pending modifications are asynchronously applied as soon as possible, regardless of the PreferredMaintenanceWindow setting for the DB instance. If this parameter is set to false, changes to the DB instance are applied during the next maintenance window. Some parameter changes can cause an outage and are applied on the next call to RebootDBInstance, or the next failure reboot. Default: false
public let applyImmediately: Bool?
/// Indicates that minor version upgrades are applied automatically to the DB instance during the maintenance window. Changing this parameter doesn't result in an outage except in the following case and the change is asynchronously applied as soon as possible. An outage will result if this parameter is set to true during the maintenance window, and a newer minor version is available, and Neptune has enabled auto patching for that engine version.
public let autoMinorVersionUpgrade: Bool?
/// Not applicable. The retention period for automated backups is managed by the DB cluster. For more information, see ModifyDBCluster. Default: Uses existing setting
public let backupRetentionPeriod: Int?
/// Indicates the certificate that needs to be associated with the instance.
public let cACertificateIdentifier: String?
/// The configuration setting for the log types to be enabled for export to CloudWatch Logs for a specific DB instance or DB cluster.
public let cloudwatchLogsExportConfiguration: CloudwatchLogsExportConfiguration?
/// True to copy all tags from the DB instance to snapshots of the DB instance, and otherwise false. The default is false.
public let copyTagsToSnapshot: Bool?
/// The new compute and memory capacity of the DB instance, for example, db.m4.large. Not all DB instance classes are available in all AWS Regions. If you modify the DB instance class, an outage occurs during the change. The change is applied during the next maintenance window, unless ApplyImmediately is specified as true for this request. Default: Uses existing setting
public let dBInstanceClass: String?
/// The DB instance identifier. This value is stored as a lowercase string. Constraints: Must match the identifier of an existing DBInstance.
public let dBInstanceIdentifier: String
/// The name of the DB parameter group to apply to the DB instance. Changing this setting doesn't result in an outage. The parameter group name itself is changed immediately, but the actual parameter changes are not applied until you reboot the instance without failover. The db instance will NOT be rebooted automatically and the parameter changes will NOT be applied during the next maintenance window. Default: Uses existing setting Constraints: The DB parameter group must be in the same DB parameter group family as this DB instance.
public let dBParameterGroupName: String?
/// The port number on which the database accepts connections. The value of the DBPortNumber parameter must not match any of the port values specified for options in the option group for the DB instance. Your database will restart when you change the DBPortNumber value regardless of the value of the ApplyImmediately parameter. Default: 8182
public let dBPortNumber: Int?
/// A list of DB security groups to authorize on this DB instance. Changing this setting doesn't result in an outage and the change is asynchronously applied as soon as possible. Constraints: If supplied, must match existing DBSecurityGroups.
@OptionalCustomCoding<ArrayCoder<_DBSecurityGroupsEncoding, String>>
public var dBSecurityGroups: [String]?
/// The new DB subnet group for the DB instance. You can use this parameter to move your DB instance to a different VPC. Changing the subnet group causes an outage during the change. The change is applied during the next maintenance window, unless you specify true for the ApplyImmediately parameter. Constraints: If supplied, must match the name of an existing DBSubnetGroup. Example: mySubnetGroup
public let dBSubnetGroupName: String?
/// A value that indicates whether the DB instance has deletion protection enabled. The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled. See Deleting a DB Instance.
public let deletionProtection: Bool?
/// Not supported.
public let domain: String?
/// Not supported
public let domainIAMRoleName: String?
/// True to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts, and otherwise false. You can enable IAM database authentication for the following database engines Not applicable. Mapping AWS IAM accounts to database accounts is managed by the DB cluster. For more information, see ModifyDBCluster. Default: false
public let enableIAMDatabaseAuthentication: Bool?
/// (Not supported by Neptune)
public let enablePerformanceInsights: Bool?
/// The version number of the database engine to upgrade to. Currently, setting this parameter has no effect. To upgrade your database engine to the most recent release, use the ApplyPendingMaintenanceAction API.
public let engineVersion: String?
/// The new Provisioned IOPS (I/O operations per second) value for the instance. Changing this setting doesn't result in an outage and the change is applied during the next maintenance window unless the ApplyImmediately parameter is set to true for this request. Default: Uses existing setting
public let iops: Int?
/// Not supported.
public let licenseModel: String?
/// Not applicable.
public let masterUserPassword: String?
/// The interval, in seconds, between points when Enhanced Monitoring metrics are collected for the DB instance. To disable collecting Enhanced Monitoring metrics, specify 0. The default is 0. If MonitoringRoleArn is specified, then you must also set MonitoringInterval to a value other than 0. Valid Values: 0, 1, 5, 10, 15, 30, 60
public let monitoringInterval: Int?
/// The ARN for the IAM role that permits Neptune to send enhanced monitoring metrics to Amazon CloudWatch Logs. For example, arn:aws:iam:123456789012:role/emaccess. If MonitoringInterval is set to a value other than 0, then you must supply a MonitoringRoleArn value.
public let monitoringRoleArn: String?
/// Specifies if the DB instance is a Multi-AZ deployment. Changing this parameter doesn't result in an outage and the change is applied during the next maintenance window unless the ApplyImmediately parameter is set to true for this request.
public let multiAZ: Bool?
/// The new DB instance identifier for the DB instance when renaming a DB instance. When you change the DB instance identifier, an instance reboot will occur immediately if you set Apply Immediately to true, or will occur during the next maintenance window if Apply Immediately to false. This value is stored as a lowercase string. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens. The first character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens. Example: mydbinstance
public let newDBInstanceIdentifier: String?
/// (Not supported by Neptune)
public let optionGroupName: String?
/// (Not supported by Neptune)
public let performanceInsightsKMSKeyId: String?
/// The daily time range during which automated backups are created if automated backups are enabled. Not applicable. The daily time range for creating automated backups is managed by the DB cluster. For more information, see ModifyDBCluster. Constraints: Must be in the format hh24:mi-hh24:mi Must be in Universal Time Coordinated (UTC) Must not conflict with the preferred maintenance window Must be at least 30 minutes
public let preferredBackupWindow: String?
/// The weekly time range (in UTC) during which system maintenance can occur, which might result in an outage. Changing this parameter doesn't result in an outage, except in the following situation, and the change is asynchronously applied as soon as possible. If there are pending actions that cause a reboot, and the maintenance window is changed to include the current time, then changing this parameter will cause a reboot of the DB instance. If moving this window to the current time, there must be at least 30 minutes between the current time and end of the window to ensure pending changes are applied. Default: Uses existing setting Format: ddd:hh24:mi-ddd:hh24:mi Valid Days: Mon | Tue | Wed | Thu | Fri | Sat | Sun Constraints: Must be at least 30 minutes
public let preferredMaintenanceWindow: String?
/// A value that specifies the order in which a Read Replica is promoted to the primary instance after a failure of the existing primary instance. Default: 1 Valid Values: 0 - 15
public let promotionTier: Int?
/// Not supported.
public let storageType: String?
/// The ARN from the key store with which to associate the instance for TDE encryption.
public let tdeCredentialArn: String?
/// The password for the given ARN from the key store in order to access the device.
public let tdeCredentialPassword: String?
/// A list of EC2 VPC security groups to authorize on this DB instance. This change is asynchronously applied as soon as possible. Not applicable. The associated list of EC2 VPC security groups is managed by the DB cluster. For more information, see ModifyDBCluster. Constraints: If supplied, must match existing VpcSecurityGroupIds.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupIdsEncoding, String>>
public var vpcSecurityGroupIds: [String]?
public init(allocatedStorage: Int? = nil, allowMajorVersionUpgrade: Bool? = nil, applyImmediately: Bool? = nil, autoMinorVersionUpgrade: Bool? = nil, backupRetentionPeriod: Int? = nil, cACertificateIdentifier: String? = nil, cloudwatchLogsExportConfiguration: CloudwatchLogsExportConfiguration? = nil, copyTagsToSnapshot: Bool? = nil, dBInstanceClass: String? = nil, dBInstanceIdentifier: String, dBParameterGroupName: String? = nil, dBPortNumber: Int? = nil, dBSecurityGroups: [String]? = nil, dBSubnetGroupName: String? = nil, deletionProtection: Bool? = nil, domain: String? = nil, domainIAMRoleName: String? = nil, enableIAMDatabaseAuthentication: Bool? = nil, enablePerformanceInsights: Bool? = nil, engineVersion: String? = nil, iops: Int? = nil, licenseModel: String? = nil, masterUserPassword: String? = nil, monitoringInterval: Int? = nil, monitoringRoleArn: String? = nil, multiAZ: Bool? = nil, newDBInstanceIdentifier: String? = nil, optionGroupName: String? = nil, performanceInsightsKMSKeyId: String? = nil, preferredBackupWindow: String? = nil, preferredMaintenanceWindow: String? = nil, promotionTier: Int? = nil, storageType: String? = nil, tdeCredentialArn: String? = nil, tdeCredentialPassword: String? = nil, vpcSecurityGroupIds: [String]? = nil) {
self.allocatedStorage = allocatedStorage
self.allowMajorVersionUpgrade = allowMajorVersionUpgrade
self.applyImmediately = applyImmediately
self.autoMinorVersionUpgrade = autoMinorVersionUpgrade
self.backupRetentionPeriod = backupRetentionPeriod
self.cACertificateIdentifier = cACertificateIdentifier
self.cloudwatchLogsExportConfiguration = cloudwatchLogsExportConfiguration
self.copyTagsToSnapshot = copyTagsToSnapshot
self.dBInstanceClass = dBInstanceClass
self.dBInstanceIdentifier = dBInstanceIdentifier
self.dBParameterGroupName = dBParameterGroupName
self.dBPortNumber = dBPortNumber
self.dBSecurityGroups = dBSecurityGroups
self.dBSubnetGroupName = dBSubnetGroupName
self.deletionProtection = deletionProtection
self.domain = domain
self.domainIAMRoleName = domainIAMRoleName
self.enableIAMDatabaseAuthentication = enableIAMDatabaseAuthentication
self.enablePerformanceInsights = enablePerformanceInsights
self.engineVersion = engineVersion
self.iops = iops
self.licenseModel = licenseModel
self.masterUserPassword = masterUserPassword
self.monitoringInterval = monitoringInterval
self.monitoringRoleArn = monitoringRoleArn
self.multiAZ = multiAZ
self.newDBInstanceIdentifier = newDBInstanceIdentifier
self.optionGroupName = optionGroupName
self.performanceInsightsKMSKeyId = performanceInsightsKMSKeyId
self.preferredBackupWindow = preferredBackupWindow
self.preferredMaintenanceWindow = preferredMaintenanceWindow
self.promotionTier = promotionTier
self.storageType = storageType
self.tdeCredentialArn = tdeCredentialArn
self.tdeCredentialPassword = tdeCredentialPassword
self.vpcSecurityGroupIds = vpcSecurityGroupIds
}
private enum CodingKeys: String, CodingKey {
case allocatedStorage = "AllocatedStorage"
case allowMajorVersionUpgrade = "AllowMajorVersionUpgrade"
case applyImmediately = "ApplyImmediately"
case autoMinorVersionUpgrade = "AutoMinorVersionUpgrade"
case backupRetentionPeriod = "BackupRetentionPeriod"
case cACertificateIdentifier = "CACertificateIdentifier"
case cloudwatchLogsExportConfiguration = "CloudwatchLogsExportConfiguration"
case copyTagsToSnapshot = "CopyTagsToSnapshot"
case dBInstanceClass = "DBInstanceClass"
case dBInstanceIdentifier = "DBInstanceIdentifier"
case dBParameterGroupName = "DBParameterGroupName"
case dBPortNumber = "DBPortNumber"
case dBSecurityGroups = "DBSecurityGroups"
case dBSubnetGroupName = "DBSubnetGroupName"
case deletionProtection = "DeletionProtection"
case domain = "Domain"
case domainIAMRoleName = "DomainIAMRoleName"
case enableIAMDatabaseAuthentication = "EnableIAMDatabaseAuthentication"
case enablePerformanceInsights = "EnablePerformanceInsights"
case engineVersion = "EngineVersion"
case iops = "Iops"
case licenseModel = "LicenseModel"
case masterUserPassword = "MasterUserPassword"
case monitoringInterval = "MonitoringInterval"
case monitoringRoleArn = "MonitoringRoleArn"
case multiAZ = "MultiAZ"
case newDBInstanceIdentifier = "NewDBInstanceIdentifier"
case optionGroupName = "OptionGroupName"
case performanceInsightsKMSKeyId = "PerformanceInsightsKMSKeyId"
case preferredBackupWindow = "PreferredBackupWindow"
case preferredMaintenanceWindow = "PreferredMaintenanceWindow"
case promotionTier = "PromotionTier"
case storageType = "StorageType"
case tdeCredentialArn = "TdeCredentialArn"
case tdeCredentialPassword = "TdeCredentialPassword"
case vpcSecurityGroupIds = "VpcSecurityGroupIds"
}
}
public struct ModifyDBInstanceResult: AWSDecodableShape {
public let dBInstance: DBInstance?
public init(dBInstance: DBInstance? = nil) {
self.dBInstance = dBInstance
}
private enum CodingKeys: String, CodingKey {
case dBInstance = "DBInstance"
}
}
public struct ModifyDBParameterGroupMessage: AWSEncodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// The name of the DB parameter group. Constraints: If supplied, must match the name of an existing DBParameterGroup.
public let dBParameterGroupName: String
/// An array of parameter names, values, and the apply method for the parameter update. At least one parameter name, value, and apply method must be supplied; subsequent arguments are optional. A maximum of 20 parameters can be modified in a single request. Valid Values (for the application method): immediate | pending-reboot You can use the immediate value with dynamic parameters only. You can use the pending-reboot value for both dynamic and static parameters, and changes are applied when you reboot the DB instance without failover.
@CustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]
public init(dBParameterGroupName: String, parameters: [Parameter]) {
self.dBParameterGroupName = dBParameterGroupName
self.parameters = parameters
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
case parameters = "Parameters"
}
}
public struct ModifyDBSubnetGroupMessage: AWSEncodableShape {
public struct _SubnetIdsEncoding: ArrayCoderProperties { public static let member = "SubnetIdentifier" }
/// The description for the DB subnet group.
public let dBSubnetGroupDescription: String?
/// The name for the DB subnet group. This value is stored as a lowercase string. You can't modify the default subnet group. Constraints: Must match the name of an existing DBSubnetGroup. Must not be default. Example: mySubnetgroup
public let dBSubnetGroupName: String
/// The EC2 subnet IDs for the DB subnet group.
@CustomCoding<ArrayCoder<_SubnetIdsEncoding, String>>
public var subnetIds: [String]
public init(dBSubnetGroupDescription: String? = nil, dBSubnetGroupName: String, subnetIds: [String]) {
self.dBSubnetGroupDescription = dBSubnetGroupDescription
self.dBSubnetGroupName = dBSubnetGroupName
self.subnetIds = subnetIds
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroupDescription = "DBSubnetGroupDescription"
case dBSubnetGroupName = "DBSubnetGroupName"
case subnetIds = "SubnetIds"
}
}
public struct ModifyDBSubnetGroupResult: AWSDecodableShape {
public let dBSubnetGroup: DBSubnetGroup?
public init(dBSubnetGroup: DBSubnetGroup? = nil) {
self.dBSubnetGroup = dBSubnetGroup
}
private enum CodingKeys: String, CodingKey {
case dBSubnetGroup = "DBSubnetGroup"
}
}
public struct ModifyEventSubscriptionMessage: AWSEncodableShape {
public struct _EventCategoriesEncoding: ArrayCoderProperties { public static let member = "EventCategory" }
/// A Boolean value; set to true to activate the subscription.
public let enabled: Bool?
/// A list of event categories for a SourceType that you want to subscribe to. You can see a list of the categories for a given SourceType by using the DescribeEventCategories action.
@OptionalCustomCoding<ArrayCoder<_EventCategoriesEncoding, String>>
public var eventCategories: [String]?
/// The Amazon Resource Name (ARN) of the SNS topic created for event notification. The ARN is created by Amazon SNS when you create a topic and subscribe to it.
public let snsTopicArn: String?
/// The type of source that is generating the events. For example, if you want to be notified of events generated by a DB instance, you would set this parameter to db-instance. if this value is not specified, all events are returned. Valid values: db-instance | db-parameter-group | db-security-group | db-snapshot
public let sourceType: String?
/// The name of the event notification subscription.
public let subscriptionName: String
public init(enabled: Bool? = nil, eventCategories: [String]? = nil, snsTopicArn: String? = nil, sourceType: String? = nil, subscriptionName: String) {
self.enabled = enabled
self.eventCategories = eventCategories
self.snsTopicArn = snsTopicArn
self.sourceType = sourceType
self.subscriptionName = subscriptionName
}
private enum CodingKeys: String, CodingKey {
case enabled = "Enabled"
case eventCategories = "EventCategories"
case snsTopicArn = "SnsTopicArn"
case sourceType = "SourceType"
case subscriptionName = "SubscriptionName"
}
}
public struct ModifyEventSubscriptionResult: AWSDecodableShape {
public let eventSubscription: EventSubscription?
public init(eventSubscription: EventSubscription? = nil) {
self.eventSubscription = eventSubscription
}
private enum CodingKeys: String, CodingKey {
case eventSubscription = "EventSubscription"
}
}
public struct OptionGroupMembership: AWSDecodableShape {
/// The name of the option group that the instance belongs to.
public let optionGroupName: String?
/// The status of the DB instance's option group membership. Valid values are: in-sync, pending-apply, pending-removal, pending-maintenance-apply, pending-maintenance-removal, applying, removing, and failed.
public let status: String?
public init(optionGroupName: String? = nil, status: String? = nil) {
self.optionGroupName = optionGroupName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case optionGroupName = "OptionGroupName"
case status = "Status"
}
}
public struct OrderableDBInstanceOption: AWSDecodableShape {
public struct _AvailabilityZonesEncoding: ArrayCoderProperties { public static let member = "AvailabilityZone" }
/// A list of Availability Zones for a DB instance.
@OptionalCustomCoding<ArrayCoder<_AvailabilityZonesEncoding, AvailabilityZone>>
public var availabilityZones: [AvailabilityZone]?
/// The DB instance class for a DB instance.
public let dBInstanceClass: String?
/// The engine type of a DB instance.
public let engine: String?
/// The engine version of a DB instance.
public let engineVersion: String?
/// The license model for a DB instance.
public let licenseModel: String?
/// Maximum total provisioned IOPS for a DB instance.
public let maxIopsPerDbInstance: Int?
/// Maximum provisioned IOPS per GiB for a DB instance.
public let maxIopsPerGib: Double?
/// Maximum storage size for a DB instance.
public let maxStorageSize: Int?
/// Minimum total provisioned IOPS for a DB instance.
public let minIopsPerDbInstance: Int?
/// Minimum provisioned IOPS per GiB for a DB instance.
public let minIopsPerGib: Double?
/// Minimum storage size for a DB instance.
public let minStorageSize: Int?
/// Indicates whether a DB instance is Multi-AZ capable.
public let multiAZCapable: Bool?
/// Indicates whether a DB instance can have a Read Replica.
public let readReplicaCapable: Bool?
/// Indicates the storage type for a DB instance.
public let storageType: String?
/// Indicates whether a DB instance supports Enhanced Monitoring at intervals from 1 to 60 seconds.
public let supportsEnhancedMonitoring: Bool?
/// Indicates whether a DB instance supports IAM database authentication.
public let supportsIAMDatabaseAuthentication: Bool?
/// Indicates whether a DB instance supports provisioned IOPS.
public let supportsIops: Bool?
/// (Not supported by Neptune)
public let supportsPerformanceInsights: Bool?
/// Indicates whether a DB instance supports encrypted storage.
public let supportsStorageEncryption: Bool?
/// Indicates whether a DB instance is in a VPC.
public let vpc: Bool?
public init(availabilityZones: [AvailabilityZone]? = nil, dBInstanceClass: String? = nil, engine: String? = nil, engineVersion: String? = nil, licenseModel: String? = nil, maxIopsPerDbInstance: Int? = nil, maxIopsPerGib: Double? = nil, maxStorageSize: Int? = nil, minIopsPerDbInstance: Int? = nil, minIopsPerGib: Double? = nil, minStorageSize: Int? = nil, multiAZCapable: Bool? = nil, readReplicaCapable: Bool? = nil, storageType: String? = nil, supportsEnhancedMonitoring: Bool? = nil, supportsIAMDatabaseAuthentication: Bool? = nil, supportsIops: Bool? = nil, supportsPerformanceInsights: Bool? = nil, supportsStorageEncryption: Bool? = nil, vpc: Bool? = nil) {
self.availabilityZones = availabilityZones
self.dBInstanceClass = dBInstanceClass
self.engine = engine
self.engineVersion = engineVersion
self.licenseModel = licenseModel
self.maxIopsPerDbInstance = maxIopsPerDbInstance
self.maxIopsPerGib = maxIopsPerGib
self.maxStorageSize = maxStorageSize
self.minIopsPerDbInstance = minIopsPerDbInstance
self.minIopsPerGib = minIopsPerGib
self.minStorageSize = minStorageSize
self.multiAZCapable = multiAZCapable
self.readReplicaCapable = readReplicaCapable
self.storageType = storageType
self.supportsEnhancedMonitoring = supportsEnhancedMonitoring
self.supportsIAMDatabaseAuthentication = supportsIAMDatabaseAuthentication
self.supportsIops = supportsIops
self.supportsPerformanceInsights = supportsPerformanceInsights
self.supportsStorageEncryption = supportsStorageEncryption
self.vpc = vpc
}
private enum CodingKeys: String, CodingKey {
case availabilityZones = "AvailabilityZones"
case dBInstanceClass = "DBInstanceClass"
case engine = "Engine"
case engineVersion = "EngineVersion"
case licenseModel = "LicenseModel"
case maxIopsPerDbInstance = "MaxIopsPerDbInstance"
case maxIopsPerGib = "MaxIopsPerGib"
case maxStorageSize = "MaxStorageSize"
case minIopsPerDbInstance = "MinIopsPerDbInstance"
case minIopsPerGib = "MinIopsPerGib"
case minStorageSize = "MinStorageSize"
case multiAZCapable = "MultiAZCapable"
case readReplicaCapable = "ReadReplicaCapable"
case storageType = "StorageType"
case supportsEnhancedMonitoring = "SupportsEnhancedMonitoring"
case supportsIAMDatabaseAuthentication = "SupportsIAMDatabaseAuthentication"
case supportsIops = "SupportsIops"
case supportsPerformanceInsights = "SupportsPerformanceInsights"
case supportsStorageEncryption = "SupportsStorageEncryption"
case vpc = "Vpc"
}
}
public struct OrderableDBInstanceOptionsMessage: AWSDecodableShape {
public struct _OrderableDBInstanceOptionsEncoding: ArrayCoderProperties { public static let member = "OrderableDBInstanceOption" }
/// An optional pagination token provided by a previous OrderableDBInstanceOptions request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .
public let marker: String?
/// An OrderableDBInstanceOption structure containing information about orderable options for the DB instance.
@OptionalCustomCoding<ArrayCoder<_OrderableDBInstanceOptionsEncoding, OrderableDBInstanceOption>>
public var orderableDBInstanceOptions: [OrderableDBInstanceOption]?
public init(marker: String? = nil, orderableDBInstanceOptions: [OrderableDBInstanceOption]? = nil) {
self.marker = marker
self.orderableDBInstanceOptions = orderableDBInstanceOptions
}
private enum CodingKeys: String, CodingKey {
case marker = "Marker"
case orderableDBInstanceOptions = "OrderableDBInstanceOptions"
}
}
public struct Parameter: AWSEncodableShape & AWSDecodableShape {
/// Specifies the valid range of values for the parameter.
public let allowedValues: String?
/// Indicates when to apply parameter updates.
public let applyMethod: ApplyMethod?
/// Specifies the engine specific parameters type.
public let applyType: String?
/// Specifies the valid data type for the parameter.
public let dataType: String?
/// Provides a description of the parameter.
public let description: String?
/// Indicates whether (true) or not (false) the parameter can be modified. Some parameters have security or operational implications that prevent them from being changed.
public let isModifiable: Bool?
/// The earliest engine version to which the parameter can apply.
public let minimumEngineVersion: String?
/// Specifies the name of the parameter.
public let parameterName: String?
/// Specifies the value of the parameter.
public let parameterValue: String?
/// Indicates the source of the parameter value.
public let source: String?
public init(allowedValues: String? = nil, applyMethod: ApplyMethod? = nil, applyType: String? = nil, dataType: String? = nil, description: String? = nil, isModifiable: Bool? = nil, minimumEngineVersion: String? = nil, parameterName: String? = nil, parameterValue: String? = nil, source: String? = nil) {
self.allowedValues = allowedValues
self.applyMethod = applyMethod
self.applyType = applyType
self.dataType = dataType
self.description = description
self.isModifiable = isModifiable
self.minimumEngineVersion = minimumEngineVersion
self.parameterName = parameterName
self.parameterValue = parameterValue
self.source = source
}
private enum CodingKeys: String, CodingKey {
case allowedValues = "AllowedValues"
case applyMethod = "ApplyMethod"
case applyType = "ApplyType"
case dataType = "DataType"
case description = "Description"
case isModifiable = "IsModifiable"
case minimumEngineVersion = "MinimumEngineVersion"
case parameterName = "ParameterName"
case parameterValue = "ParameterValue"
case source = "Source"
}
}
public struct PendingCloudwatchLogsExports: AWSDecodableShape {
/// Log types that are in the process of being enabled. After they are enabled, these log types are exported to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var logTypesToDisable: [String]?
/// Log types that are in the process of being deactivated. After they are deactivated, these log types aren't exported to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var logTypesToEnable: [String]?
public init(logTypesToDisable: [String]? = nil, logTypesToEnable: [String]? = nil) {
self.logTypesToDisable = logTypesToDisable
self.logTypesToEnable = logTypesToEnable
}
private enum CodingKeys: String, CodingKey {
case logTypesToDisable = "LogTypesToDisable"
case logTypesToEnable = "LogTypesToEnable"
}
}
public struct PendingMaintenanceAction: AWSDecodableShape {
/// The type of pending maintenance action that is available for the resource.
public let action: String?
/// The date of the maintenance window when the action is applied. The maintenance action is applied to the resource during its first maintenance window after this date. If this date is specified, any next-maintenance opt-in requests are ignored.
public let autoAppliedAfterDate: Date?
/// The effective date when the pending maintenance action is applied to the resource. This date takes into account opt-in requests received from the ApplyPendingMaintenanceAction API, the AutoAppliedAfterDate, and the ForcedApplyDate. This value is blank if an opt-in request has not been received and nothing has been specified as AutoAppliedAfterDate or ForcedApplyDate.
public let currentApplyDate: Date?
/// A description providing more detail about the maintenance action.
public let description: String?
/// The date when the maintenance action is automatically applied. The maintenance action is applied to the resource on this date regardless of the maintenance window for the resource. If this date is specified, any immediate opt-in requests are ignored.
public let forcedApplyDate: Date?
/// Indicates the type of opt-in request that has been received for the resource.
public let optInStatus: String?
public init(action: String? = nil, autoAppliedAfterDate: Date? = nil, currentApplyDate: Date? = nil, description: String? = nil, forcedApplyDate: Date? = nil, optInStatus: String? = nil) {
self.action = action
self.autoAppliedAfterDate = autoAppliedAfterDate
self.currentApplyDate = currentApplyDate
self.description = description
self.forcedApplyDate = forcedApplyDate
self.optInStatus = optInStatus
}
private enum CodingKeys: String, CodingKey {
case action = "Action"
case autoAppliedAfterDate = "AutoAppliedAfterDate"
case currentApplyDate = "CurrentApplyDate"
case description = "Description"
case forcedApplyDate = "ForcedApplyDate"
case optInStatus = "OptInStatus"
}
}
public struct PendingMaintenanceActionsMessage: AWSDecodableShape {
public struct _PendingMaintenanceActionsEncoding: ArrayCoderProperties { public static let member = "ResourcePendingMaintenanceActions" }
/// An optional pagination token provided by a previous DescribePendingMaintenanceActions request. If this parameter is specified, the response includes only records beyond the marker, up to a number of records specified by MaxRecords.
public let marker: String?
/// A list of the pending maintenance actions for the resource.
@OptionalCustomCoding<ArrayCoder<_PendingMaintenanceActionsEncoding, ResourcePendingMaintenanceActions>>
public var pendingMaintenanceActions: [ResourcePendingMaintenanceActions]?
public init(marker: String? = nil, pendingMaintenanceActions: [ResourcePendingMaintenanceActions]? = nil) {
self.marker = marker
self.pendingMaintenanceActions = pendingMaintenanceActions
}
private enum CodingKeys: String, CodingKey {
case marker = "Marker"
case pendingMaintenanceActions = "PendingMaintenanceActions"
}
}
public struct PendingModifiedValues: AWSDecodableShape {
/// Contains the new AllocatedStorage size for the DB instance that will be applied or is currently being applied.
public let allocatedStorage: Int?
/// Specifies the pending number of days for which automated backups are retained.
public let backupRetentionPeriod: Int?
/// Specifies the identifier of the CA certificate for the DB instance.
public let cACertificateIdentifier: String?
/// Contains the new DBInstanceClass for the DB instance that will be applied or is currently being applied.
public let dBInstanceClass: String?
/// Contains the new DBInstanceIdentifier for the DB instance that will be applied or is currently being applied.
public let dBInstanceIdentifier: String?
/// The new DB subnet group for the DB instance.
public let dBSubnetGroupName: String?
/// Indicates the database engine version.
public let engineVersion: String?
/// Specifies the new Provisioned IOPS value for the DB instance that will be applied or is currently being applied.
public let iops: Int?
/// The license model for the DB instance. Valid values: license-included | bring-your-own-license | general-public-license
public let licenseModel: String?
/// Contains the pending or currently-in-progress change of the master credentials for the DB instance.
public let masterUserPassword: String?
/// Indicates that the Single-AZ DB instance is to change to a Multi-AZ deployment.
public let multiAZ: Bool?
/// This PendingCloudwatchLogsExports structure specifies pending changes to which CloudWatch logs are enabled and which are disabled.
public let pendingCloudwatchLogsExports: PendingCloudwatchLogsExports?
/// Specifies the pending port for the DB instance.
public let port: Int?
/// Specifies the storage type to be associated with the DB instance.
public let storageType: String?
public init(allocatedStorage: Int? = nil, backupRetentionPeriod: Int? = nil, cACertificateIdentifier: String? = nil, dBInstanceClass: String? = nil, dBInstanceIdentifier: String? = nil, dBSubnetGroupName: String? = nil, engineVersion: String? = nil, iops: Int? = nil, licenseModel: String? = nil, masterUserPassword: String? = nil, multiAZ: Bool? = nil, pendingCloudwatchLogsExports: PendingCloudwatchLogsExports? = nil, port: Int? = nil, storageType: String? = nil) {
self.allocatedStorage = allocatedStorage
self.backupRetentionPeriod = backupRetentionPeriod
self.cACertificateIdentifier = cACertificateIdentifier
self.dBInstanceClass = dBInstanceClass
self.dBInstanceIdentifier = dBInstanceIdentifier
self.dBSubnetGroupName = dBSubnetGroupName
self.engineVersion = engineVersion
self.iops = iops
self.licenseModel = licenseModel
self.masterUserPassword = masterUserPassword
self.multiAZ = multiAZ
self.pendingCloudwatchLogsExports = pendingCloudwatchLogsExports
self.port = port
self.storageType = storageType
}
private enum CodingKeys: String, CodingKey {
case allocatedStorage = "AllocatedStorage"
case backupRetentionPeriod = "BackupRetentionPeriod"
case cACertificateIdentifier = "CACertificateIdentifier"
case dBInstanceClass = "DBInstanceClass"
case dBInstanceIdentifier = "DBInstanceIdentifier"
case dBSubnetGroupName = "DBSubnetGroupName"
case engineVersion = "EngineVersion"
case iops = "Iops"
case licenseModel = "LicenseModel"
case masterUserPassword = "MasterUserPassword"
case multiAZ = "MultiAZ"
case pendingCloudwatchLogsExports = "PendingCloudwatchLogsExports"
case port = "Port"
case storageType = "StorageType"
}
}
public struct PromoteReadReplicaDBClusterMessage: AWSEncodableShape {
/// Not supported.
public let dBClusterIdentifier: String
public init(dBClusterIdentifier: String) {
self.dBClusterIdentifier = dBClusterIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
}
}
public struct PromoteReadReplicaDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct Range: AWSDecodableShape {
/// The minimum value in the range.
public let from: Int?
/// The step value for the range. For example, if you have a range of 5,000 to 10,000, with a step value of 1,000, the valid values start at 5,000 and step up by 1,000. Even though 7,500 is within the range, it isn't a valid value for the range. The valid values are 5,000, 6,000, 7,000, 8,000...
public let step: Int?
/// The maximum value in the range.
public let to: Int?
public init(from: Int? = nil, step: Int? = nil, to: Int? = nil) {
self.from = from
self.step = step
self.to = to
}
private enum CodingKeys: String, CodingKey {
case from = "From"
case step = "Step"
case to = "To"
}
}
public struct RebootDBInstanceMessage: AWSEncodableShape {
/// The DB instance identifier. This parameter is stored as a lowercase string. Constraints: Must match the identifier of an existing DBInstance.
public let dBInstanceIdentifier: String
/// When true, the reboot is conducted through a MultiAZ failover. Constraint: You can't specify true if the instance is not configured for MultiAZ.
public let forceFailover: Bool?
public init(dBInstanceIdentifier: String, forceFailover: Bool? = nil) {
self.dBInstanceIdentifier = dBInstanceIdentifier
self.forceFailover = forceFailover
}
private enum CodingKeys: String, CodingKey {
case dBInstanceIdentifier = "DBInstanceIdentifier"
case forceFailover = "ForceFailover"
}
}
public struct RebootDBInstanceResult: AWSDecodableShape {
public let dBInstance: DBInstance?
public init(dBInstance: DBInstance? = nil) {
self.dBInstance = dBInstance
}
private enum CodingKeys: String, CodingKey {
case dBInstance = "DBInstance"
}
}
public struct RemoveRoleFromDBClusterMessage: AWSEncodableShape {
/// The name of the DB cluster to disassociate the IAM role from.
public let dBClusterIdentifier: String
/// The Amazon Resource Name (ARN) of the IAM role to disassociate from the DB cluster, for example arn:aws:iam::123456789012:role/NeptuneAccessRole.
public let roleArn: String
public init(dBClusterIdentifier: String, roleArn: String) {
self.dBClusterIdentifier = dBClusterIdentifier
self.roleArn = roleArn
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case roleArn = "RoleArn"
}
}
public struct RemoveSourceIdentifierFromSubscriptionMessage: AWSEncodableShape {
/// The source identifier to be removed from the subscription, such as the DB instance identifier for a DB instance or the name of a security group.
public let sourceIdentifier: String
/// The name of the event notification subscription you want to remove a source identifier from.
public let subscriptionName: String
public init(sourceIdentifier: String, subscriptionName: String) {
self.sourceIdentifier = sourceIdentifier
self.subscriptionName = subscriptionName
}
private enum CodingKeys: String, CodingKey {
case sourceIdentifier = "SourceIdentifier"
case subscriptionName = "SubscriptionName"
}
}
public struct RemoveSourceIdentifierFromSubscriptionResult: AWSDecodableShape {
public let eventSubscription: EventSubscription?
public init(eventSubscription: EventSubscription? = nil) {
self.eventSubscription = eventSubscription
}
private enum CodingKeys: String, CodingKey {
case eventSubscription = "EventSubscription"
}
}
public struct RemoveTagsFromResourceMessage: AWSEncodableShape {
/// The Amazon Neptune resource that the tags are removed from. This value is an Amazon Resource Name (ARN). For information about creating an ARN, see Constructing an Amazon Resource Name (ARN).
public let resourceName: String
/// The tag key (name) of the tag to be removed.
@CustomCoding<StandardArrayCoder>
public var tagKeys: [String]
public init(resourceName: String, tagKeys: [String]) {
self.resourceName = resourceName
self.tagKeys = tagKeys
}
private enum CodingKeys: String, CodingKey {
case resourceName = "ResourceName"
case tagKeys = "TagKeys"
}
}
public struct ResetDBClusterParameterGroupMessage: AWSEncodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// The name of the DB cluster parameter group to reset.
public let dBClusterParameterGroupName: String
/// A list of parameter names in the DB cluster parameter group to reset to the default values. You can't use this parameter if the ResetAllParameters parameter is set to true.
@OptionalCustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]?
/// A value that is set to true to reset all parameters in the DB cluster parameter group to their default values, and false otherwise. You can't use this parameter if there is a list of parameter names specified for the Parameters parameter.
public let resetAllParameters: Bool?
public init(dBClusterParameterGroupName: String, parameters: [Parameter]? = nil, resetAllParameters: Bool? = nil) {
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.parameters = parameters
self.resetAllParameters = resetAllParameters
}
private enum CodingKeys: String, CodingKey {
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case parameters = "Parameters"
case resetAllParameters = "ResetAllParameters"
}
}
public struct ResetDBParameterGroupMessage: AWSEncodableShape {
public struct _ParametersEncoding: ArrayCoderProperties { public static let member = "Parameter" }
/// The name of the DB parameter group. Constraints: Must match the name of an existing DBParameterGroup.
public let dBParameterGroupName: String
/// To reset the entire DB parameter group, specify the DBParameterGroup name and ResetAllParameters parameters. To reset specific parameters, provide a list of the following: ParameterName and ApplyMethod. A maximum of 20 parameters can be modified in a single request. Valid Values (for Apply method): pending-reboot
@OptionalCustomCoding<ArrayCoder<_ParametersEncoding, Parameter>>
public var parameters: [Parameter]?
/// Specifies whether (true) or not (false) to reset all parameters in the DB parameter group to default values. Default: true
public let resetAllParameters: Bool?
public init(dBParameterGroupName: String, parameters: [Parameter]? = nil, resetAllParameters: Bool? = nil) {
self.dBParameterGroupName = dBParameterGroupName
self.parameters = parameters
self.resetAllParameters = resetAllParameters
}
private enum CodingKeys: String, CodingKey {
case dBParameterGroupName = "DBParameterGroupName"
case parameters = "Parameters"
case resetAllParameters = "ResetAllParameters"
}
}
public struct ResourcePendingMaintenanceActions: AWSDecodableShape {
public struct _PendingMaintenanceActionDetailsEncoding: ArrayCoderProperties { public static let member = "PendingMaintenanceAction" }
/// A list that provides details about the pending maintenance actions for the resource.
@OptionalCustomCoding<ArrayCoder<_PendingMaintenanceActionDetailsEncoding, PendingMaintenanceAction>>
public var pendingMaintenanceActionDetails: [PendingMaintenanceAction]?
/// The ARN of the resource that has pending maintenance actions.
public let resourceIdentifier: String?
public init(pendingMaintenanceActionDetails: [PendingMaintenanceAction]? = nil, resourceIdentifier: String? = nil) {
self.pendingMaintenanceActionDetails = pendingMaintenanceActionDetails
self.resourceIdentifier = resourceIdentifier
}
private enum CodingKeys: String, CodingKey {
case pendingMaintenanceActionDetails = "PendingMaintenanceActionDetails"
case resourceIdentifier = "ResourceIdentifier"
}
}
public struct RestoreDBClusterFromSnapshotMessage: AWSEncodableShape {
public struct _AvailabilityZonesEncoding: ArrayCoderProperties { public static let member = "AvailabilityZone" }
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
public struct _VpcSecurityGroupIdsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupId" }
/// Provides the list of EC2 Availability Zones that instances in the restored DB cluster can be created in.
@OptionalCustomCoding<ArrayCoder<_AvailabilityZonesEncoding, String>>
public var availabilityZones: [String]?
/// Not supported.
public let databaseName: String?
/// The name of the DB cluster to create from the DB snapshot or DB cluster snapshot. This parameter isn't case-sensitive. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens Example: my-snapshot-id
public let dBClusterIdentifier: String
/// The name of the DB cluster parameter group to associate with the new DB cluster. Constraints: If supplied, must match the name of an existing DBClusterParameterGroup.
public let dBClusterParameterGroupName: String?
/// The name of the DB subnet group to use for the new DB cluster. Constraints: If supplied, must match the name of an existing DBSubnetGroup. Example: mySubnetgroup
public let dBSubnetGroupName: String?
/// A value that indicates whether the DB cluster has deletion protection enabled. The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled.
public let deletionProtection: Bool?
/// The list of logs that the restored DB cluster is to export to Amazon CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var enableCloudwatchLogsExports: [String]?
/// True to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts, and otherwise false. Default: false
public let enableIAMDatabaseAuthentication: Bool?
/// The database engine to use for the new DB cluster. Default: The same as source Constraint: Must be compatible with the engine of the source
public let engine: String
/// The version of the database engine to use for the new DB cluster.
public let engineVersion: String?
/// The AWS KMS key identifier to use when restoring an encrypted DB cluster from a DB snapshot or DB cluster snapshot. The KMS key identifier is the Amazon Resource Name (ARN) for the KMS encryption key. If you are restoring a DB cluster with the same AWS account that owns the KMS encryption key used to encrypt the new DB cluster, then you can use the KMS key alias instead of the ARN for the KMS encryption key. If you do not specify a value for the KmsKeyId parameter, then the following will occur: If the DB snapshot or DB cluster snapshot in SnapshotIdentifier is encrypted, then the restored DB cluster is encrypted using the KMS key that was used to encrypt the DB snapshot or DB cluster snapshot. If the DB snapshot or DB cluster snapshot in SnapshotIdentifier is not encrypted, then the restored DB cluster is not encrypted.
public let kmsKeyId: String?
/// (Not supported by Neptune)
public let optionGroupName: String?
/// The port number on which the new DB cluster accepts connections. Constraints: Value must be 1150-65535 Default: The same port as the original DB cluster.
public let port: Int?
/// The identifier for the DB snapshot or DB cluster snapshot to restore from. You can use either the name or the Amazon Resource Name (ARN) to specify a DB cluster snapshot. However, you can use only the ARN to specify a DB snapshot. Constraints: Must match the identifier of an existing Snapshot.
public let snapshotIdentifier: String
/// The tags to be assigned to the restored DB cluster.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// A list of VPC security groups that the new DB cluster will belong to.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupIdsEncoding, String>>
public var vpcSecurityGroupIds: [String]?
public init(availabilityZones: [String]? = nil, databaseName: String? = nil, dBClusterIdentifier: String, dBClusterParameterGroupName: String? = nil, dBSubnetGroupName: String? = nil, deletionProtection: Bool? = nil, enableCloudwatchLogsExports: [String]? = nil, enableIAMDatabaseAuthentication: Bool? = nil, engine: String, engineVersion: String? = nil, kmsKeyId: String? = nil, optionGroupName: String? = nil, port: Int? = nil, snapshotIdentifier: String, tags: [Tag]? = nil, vpcSecurityGroupIds: [String]? = nil) {
self.availabilityZones = availabilityZones
self.databaseName = databaseName
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.dBSubnetGroupName = dBSubnetGroupName
self.deletionProtection = deletionProtection
self.enableCloudwatchLogsExports = enableCloudwatchLogsExports
self.enableIAMDatabaseAuthentication = enableIAMDatabaseAuthentication
self.engine = engine
self.engineVersion = engineVersion
self.kmsKeyId = kmsKeyId
self.optionGroupName = optionGroupName
self.port = port
self.snapshotIdentifier = snapshotIdentifier
self.tags = tags
self.vpcSecurityGroupIds = vpcSecurityGroupIds
}
private enum CodingKeys: String, CodingKey {
case availabilityZones = "AvailabilityZones"
case databaseName = "DatabaseName"
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case dBSubnetGroupName = "DBSubnetGroupName"
case deletionProtection = "DeletionProtection"
case enableCloudwatchLogsExports = "EnableCloudwatchLogsExports"
case enableIAMDatabaseAuthentication = "EnableIAMDatabaseAuthentication"
case engine = "Engine"
case engineVersion = "EngineVersion"
case kmsKeyId = "KmsKeyId"
case optionGroupName = "OptionGroupName"
case port = "Port"
case snapshotIdentifier = "SnapshotIdentifier"
case tags = "Tags"
case vpcSecurityGroupIds = "VpcSecurityGroupIds"
}
}
public struct RestoreDBClusterFromSnapshotResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct RestoreDBClusterToPointInTimeMessage: AWSEncodableShape {
public struct _TagsEncoding: ArrayCoderProperties { public static let member = "Tag" }
public struct _VpcSecurityGroupIdsEncoding: ArrayCoderProperties { public static let member = "VpcSecurityGroupId" }
/// The name of the new DB cluster to be created. Constraints: Must contain from 1 to 63 letters, numbers, or hyphens First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
public let dBClusterIdentifier: String
/// The name of the DB cluster parameter group to associate with the new DB cluster. Constraints: If supplied, must match the name of an existing DBClusterParameterGroup.
public let dBClusterParameterGroupName: String?
/// The DB subnet group name to use for the new DB cluster. Constraints: If supplied, must match the name of an existing DBSubnetGroup. Example: mySubnetgroup
public let dBSubnetGroupName: String?
/// A value that indicates whether the DB cluster has deletion protection enabled. The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled.
public let deletionProtection: Bool?
/// The list of logs that the restored DB cluster is to export to CloudWatch Logs.
@OptionalCustomCoding<StandardArrayCoder>
public var enableCloudwatchLogsExports: [String]?
/// True to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts, and otherwise false. Default: false
public let enableIAMDatabaseAuthentication: Bool?
/// The AWS KMS key identifier to use when restoring an encrypted DB cluster from an encrypted DB cluster. The KMS key identifier is the Amazon Resource Name (ARN) for the KMS encryption key. If you are restoring a DB cluster with the same AWS account that owns the KMS encryption key used to encrypt the new DB cluster, then you can use the KMS key alias instead of the ARN for the KMS encryption key. You can restore to a new DB cluster and encrypt the new DB cluster with a KMS key that is different than the KMS key used to encrypt the source DB cluster. The new DB cluster is encrypted with the KMS key identified by the KmsKeyId parameter. If you do not specify a value for the KmsKeyId parameter, then the following will occur: If the DB cluster is encrypted, then the restored DB cluster is encrypted using the KMS key that was used to encrypt the source DB cluster. If the DB cluster is not encrypted, then the restored DB cluster is not encrypted. If DBClusterIdentifier refers to a DB cluster that is not encrypted, then the restore request is rejected.
public let kmsKeyId: String?
/// (Not supported by Neptune)
public let optionGroupName: String?
/// The port number on which the new DB cluster accepts connections. Constraints: Value must be 1150-65535 Default: The same port as the original DB cluster.
public let port: Int?
/// The date and time to restore the DB cluster to. Valid Values: Value must be a time in Universal Coordinated Time (UTC) format Constraints: Must be before the latest restorable time for the DB instance Must be specified if UseLatestRestorableTime parameter is not provided Cannot be specified if UseLatestRestorableTime parameter is true Cannot be specified if RestoreType parameter is copy-on-write Example: 2015-03-07T23:45:00Z
public let restoreToTime: Date?
/// The type of restore to be performed. You can specify one of the following values: full-copy - The new DB cluster is restored as a full copy of the source DB cluster. copy-on-write - The new DB cluster is restored as a clone of the source DB cluster. If you don't specify a RestoreType value, then the new DB cluster is restored as a full copy of the source DB cluster.
public let restoreType: String?
/// The identifier of the source DB cluster from which to restore. Constraints: Must match the identifier of an existing DBCluster.
public let sourceDBClusterIdentifier: String
/// The tags to be applied to the restored DB cluster.
@OptionalCustomCoding<ArrayCoder<_TagsEncoding, Tag>>
public var tags: [Tag]?
/// A value that is set to true to restore the DB cluster to the latest restorable backup time, and false otherwise. Default: false Constraints: Cannot be specified if RestoreToTime parameter is provided.
public let useLatestRestorableTime: Bool?
/// A list of VPC security groups that the new DB cluster belongs to.
@OptionalCustomCoding<ArrayCoder<_VpcSecurityGroupIdsEncoding, String>>
public var vpcSecurityGroupIds: [String]?
public init(dBClusterIdentifier: String, dBClusterParameterGroupName: String? = nil, dBSubnetGroupName: String? = nil, deletionProtection: Bool? = nil, enableCloudwatchLogsExports: [String]? = nil, enableIAMDatabaseAuthentication: Bool? = nil, kmsKeyId: String? = nil, optionGroupName: String? = nil, port: Int? = nil, restoreToTime: Date? = nil, restoreType: String? = nil, sourceDBClusterIdentifier: String, tags: [Tag]? = nil, useLatestRestorableTime: Bool? = nil, vpcSecurityGroupIds: [String]? = nil) {
self.dBClusterIdentifier = dBClusterIdentifier
self.dBClusterParameterGroupName = dBClusterParameterGroupName
self.dBSubnetGroupName = dBSubnetGroupName
self.deletionProtection = deletionProtection
self.enableCloudwatchLogsExports = enableCloudwatchLogsExports
self.enableIAMDatabaseAuthentication = enableIAMDatabaseAuthentication
self.kmsKeyId = kmsKeyId
self.optionGroupName = optionGroupName
self.port = port
self.restoreToTime = restoreToTime
self.restoreType = restoreType
self.sourceDBClusterIdentifier = sourceDBClusterIdentifier
self.tags = tags
self.useLatestRestorableTime = useLatestRestorableTime
self.vpcSecurityGroupIds = vpcSecurityGroupIds
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
case dBClusterParameterGroupName = "DBClusterParameterGroupName"
case dBSubnetGroupName = "DBSubnetGroupName"
case deletionProtection = "DeletionProtection"
case enableCloudwatchLogsExports = "EnableCloudwatchLogsExports"
case enableIAMDatabaseAuthentication = "EnableIAMDatabaseAuthentication"
case kmsKeyId = "KmsKeyId"
case optionGroupName = "OptionGroupName"
case port = "Port"
case restoreToTime = "RestoreToTime"
case restoreType = "RestoreType"
case sourceDBClusterIdentifier = "SourceDBClusterIdentifier"
case tags = "Tags"
case useLatestRestorableTime = "UseLatestRestorableTime"
case vpcSecurityGroupIds = "VpcSecurityGroupIds"
}
}
public struct RestoreDBClusterToPointInTimeResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct StartDBClusterMessage: AWSEncodableShape {
/// The DB cluster identifier of the Neptune DB cluster to be started. This parameter is stored as a lowercase string.
public let dBClusterIdentifier: String
public init(dBClusterIdentifier: String) {
self.dBClusterIdentifier = dBClusterIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
}
}
public struct StartDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct StopDBClusterMessage: AWSEncodableShape {
/// The DB cluster identifier of the Neptune DB cluster to be stopped. This parameter is stored as a lowercase string.
public let dBClusterIdentifier: String
public init(dBClusterIdentifier: String) {
self.dBClusterIdentifier = dBClusterIdentifier
}
private enum CodingKeys: String, CodingKey {
case dBClusterIdentifier = "DBClusterIdentifier"
}
}
public struct StopDBClusterResult: AWSDecodableShape {
public let dBCluster: DBCluster?
public init(dBCluster: DBCluster? = nil) {
self.dBCluster = dBCluster
}
private enum CodingKeys: String, CodingKey {
case dBCluster = "DBCluster"
}
}
public struct Subnet: AWSDecodableShape {
/// Specifies the EC2 Availability Zone that the subnet is in.
public let subnetAvailabilityZone: AvailabilityZone?
/// Specifies the identifier of the subnet.
public let subnetIdentifier: String?
/// Specifies the status of the subnet.
public let subnetStatus: String?
public init(subnetAvailabilityZone: AvailabilityZone? = nil, subnetIdentifier: String? = nil, subnetStatus: String? = nil) {
self.subnetAvailabilityZone = subnetAvailabilityZone
self.subnetIdentifier = subnetIdentifier
self.subnetStatus = subnetStatus
}
private enum CodingKeys: String, CodingKey {
case subnetAvailabilityZone = "SubnetAvailabilityZone"
case subnetIdentifier = "SubnetIdentifier"
case subnetStatus = "SubnetStatus"
}
}
public struct Tag: AWSEncodableShape & AWSDecodableShape {
/// A key is the required name of the tag. The string value can be from 1 to 128 Unicode characters in length and can't be prefixed with "aws:" or "rds:". The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").
public let key: String?
/// A value is the optional value of the tag. The string value can be from 1 to 256 Unicode characters in length and can't be prefixed with "aws:" or "rds:". The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").
public let value: String?
public init(key: String? = nil, value: String? = nil) {
self.key = key
self.value = value
}
private enum CodingKeys: String, CodingKey {
case key = "Key"
case value = "Value"
}
}
public struct TagListMessage: AWSDecodableShape {
public struct _TagListEncoding: ArrayCoderProperties { public static let member = "Tag" }
/// List of tags returned by the ListTagsForResource operation.
@OptionalCustomCoding<ArrayCoder<_TagListEncoding, Tag>>
public var tagList: [Tag]?
public init(tagList: [Tag]? = nil) {
self.tagList = tagList
}
private enum CodingKeys: String, CodingKey {
case tagList = "TagList"
}
}
public struct Timezone: AWSDecodableShape {
/// The name of the time zone.
public let timezoneName: String?
public init(timezoneName: String? = nil) {
self.timezoneName = timezoneName
}
private enum CodingKeys: String, CodingKey {
case timezoneName = "TimezoneName"
}
}
public struct UpgradeTarget: AWSDecodableShape {
/// A value that indicates whether the target version is applied to any source DB instances that have AutoMinorVersionUpgrade set to true.
public let autoUpgrade: Bool?
/// The version of the database engine that a DB instance can be upgraded to.
public let description: String?
/// The name of the upgrade target database engine.
public let engine: String?
/// The version number of the upgrade target database engine.
public let engineVersion: String?
/// A value that indicates whether a database engine is upgraded to a major version.
public let isMajorVersionUpgrade: Bool?
public init(autoUpgrade: Bool? = nil, description: String? = nil, engine: String? = nil, engineVersion: String? = nil, isMajorVersionUpgrade: Bool? = nil) {
self.autoUpgrade = autoUpgrade
self.description = description
self.engine = engine
self.engineVersion = engineVersion
self.isMajorVersionUpgrade = isMajorVersionUpgrade
}
private enum CodingKeys: String, CodingKey {
case autoUpgrade = "AutoUpgrade"
case description = "Description"
case engine = "Engine"
case engineVersion = "EngineVersion"
case isMajorVersionUpgrade = "IsMajorVersionUpgrade"
}
}
public struct ValidDBInstanceModificationsMessage: AWSDecodableShape {
public struct _StorageEncoding: ArrayCoderProperties { public static let member = "ValidStorageOptions" }
/// Valid storage options for your DB instance.
@OptionalCustomCoding<ArrayCoder<_StorageEncoding, ValidStorageOptions>>
public var storage: [ValidStorageOptions]?
public init(storage: [ValidStorageOptions]? = nil) {
self.storage = storage
}
private enum CodingKeys: String, CodingKey {
case storage = "Storage"
}
}
public struct ValidStorageOptions: AWSDecodableShape {
public struct _IopsToStorageRatioEncoding: ArrayCoderProperties { public static let member = "DoubleRange" }
public struct _ProvisionedIopsEncoding: ArrayCoderProperties { public static let member = "Range" }
public struct _StorageSizeEncoding: ArrayCoderProperties { public static let member = "Range" }
/// The valid range of Provisioned IOPS to gibibytes of storage multiplier. For example, 3-10, which means that provisioned IOPS can be between 3 and 10 times storage.
@OptionalCustomCoding<ArrayCoder<_IopsToStorageRatioEncoding, DoubleRange>>
public var iopsToStorageRatio: [DoubleRange]?
/// The valid range of provisioned IOPS. For example, 1000-20000.
@OptionalCustomCoding<ArrayCoder<_ProvisionedIopsEncoding, Range>>
public var provisionedIops: [Range]?
/// The valid range of storage in gibibytes. For example, 100 to 16384.
@OptionalCustomCoding<ArrayCoder<_StorageSizeEncoding, Range>>
public var storageSize: [Range]?
/// The valid storage types for your DB instance. For example, gp2, io1.
public let storageType: String?
public init(iopsToStorageRatio: [DoubleRange]? = nil, provisionedIops: [Range]? = nil, storageSize: [Range]? = nil, storageType: String? = nil) {
self.iopsToStorageRatio = iopsToStorageRatio
self.provisionedIops = provisionedIops
self.storageSize = storageSize
self.storageType = storageType
}
private enum CodingKeys: String, CodingKey {
case iopsToStorageRatio = "IopsToStorageRatio"
case provisionedIops = "ProvisionedIops"
case storageSize = "StorageSize"
case storageType = "StorageType"
}
}
public struct VpcSecurityGroupMembership: AWSDecodableShape {
/// The status of the VPC security group.
public let status: String?
/// The name of the VPC security group.
public let vpcSecurityGroupId: String?
public init(status: String? = nil, vpcSecurityGroupId: String? = nil) {
self.status = status
self.vpcSecurityGroupId = vpcSecurityGroupId
}
private enum CodingKeys: String, CodingKey {
case status = "Status"
case vpcSecurityGroupId = "VpcSecurityGroupId"
}
}
}
| apache-2.0 |
programersun/HiChongSwift | HiChongSwift/SquareCommentViewController.swift | 1 | 6971 | //
// SquareCommentViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/15.
// Copyright (c) 2014年 Duostec. All rights reserved.
//
import UIKit
class SquareCommentViewController: UITableViewController {
var businessID: String?
var businessName: String?
weak var delegate: SquareCommentDelegate?
private var cellOnceToken: dispatch_once_t = 0
private weak var starCell: SquareAddStarCell?
private weak var icyTextView: UITextView?
override func viewDidLoad() {
super.viewDidLoad()
// 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()
self.tableView.hideExtraSeprator()
self.tableView.backgroundColor = UIColor.LCYThemeColor()
self.title = "评价"
if businessID == nil {
alert("无法加载商家信息,请退回重试")
} else {
// 添加一个确定按钮
self.addRightButton("确定", action: "rightButtonPressed:")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func rightButtonPressed(sender: AnyObject) {
if let textView = icyTextView {
if count(textView.text) == 0 {
alert("请填写评论内容")
return
} else {
if let starCell = starCell {
if let scoreText = starCell.scoreLabel.text {
let parameter: [String: String] = [
"user_id": LCYCommon.sharedInstance.userName!,
"business_id": businessID!,
"content": textView.text,
"score": scoreText
]
LCYNetworking.sharedInstance.POST(LCYApi.SquareCommentAdd, parameters: parameter, success: { [weak self](object) -> Void in
if let result = object["result"] as? NSNumber {
if result.boolValue {
self?.alertWithDelegate("评论成功", tag: 2001, delegate: self)
} else {
self?.alert("评论失败")
}
} else {
self?.alert("评论解析失败")
}
return
}, failure: { [weak self](error) -> Void in
self?.alert("网络连接异常,请检查网络状态")
return
})
} else {
// 这条语句应该不会执行
alert("请打分,丷丷")
}
} else {
alert("内部错误,无法加载评论分数,请尝试重新打开评论页面")
}
}
} else {
alert("内部错误,无法加载评论内容,请尝试重新打开评论页面")
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
switch indexPath.row {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("title") as! UITableViewCell
dispatch_once(&cellOnceToken)
{ () -> Void in
cell.textLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = UIColor.LCYThemeColor()
return
}
if let name = businessName {
cell.textLabel?.text = name
} else {
cell.textLabel?.textColor = UIColor.lightGrayColor()
cell.textLabel?.text = "未能获取商家名称"
}
case 1:
cell = tableView.dequeueReusableCellWithIdentifier(SquareAddStarCell.identifier()) as! SquareAddStarCell
let cell = cell as! SquareAddStarCell
self.starCell = cell
case 2:
cell = tableView.dequeueReusableCellWithIdentifier(SquareAddCommentCell.identifier()) as! UITableViewCell
let cell = cell as! SquareAddCommentCell
icyTextView = cell.icyTextView
default:
break
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.row {
case 0:
return 44.0
case 1:
return 44.0
case 2:
return 170.0
default:
return 44.0
}
}
}
extension SquareCommentViewController: UIGestureRecognizerDelegate {
@IBAction func panGestureHandler(sender: UIPanGestureRecognizer) {
let xInView = sender.locationInView(sender.view).x
if (xInView < 14.0) || (xInView > 180.0) {
return
}
if xInView > 144.0 {
self.starCell?.imageWidth = 144.0
} else {
self.starCell?.imageWidth = xInView
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
let xInView = touch.locationInView(gestureRecognizer.view).x
if (xInView < 14.0) || (xInView > 180.0) {
if xInView < 14.0 {
self.starCell?.imageWidth = 16.0
}
return true
}
if xInView > 144.0 {
self.starCell?.imageWidth = 144.0
} else {
self.starCell?.imageWidth = xInView
}
return true
}
}
extension SquareCommentViewController: UIAlertViewDelegate {
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if alertView.tag == 2001 {
delegate?.squareDidAddComment()
navigationController?.popViewControllerAnimated(true)
}
}
}
protocol SquareCommentDelegate: class {
func squareDidAddComment()
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/10048-swift-printingdiagnosticconsumer-handlediagnostic.swift | 11 | 240 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum k{
{
}
class A{
func c
class c<c{
}
let a{
struct S<T where T:c<T> | mit |
notbenoit/tvOS-Twitch | Code/tvOS/Controllers/Home/TwitchHomeViewController.swift | 1 | 1990 | // Copyright (c) 2015 Benoit Layer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import AVKit
import ReactiveSwift
class TwitchHomeViewController: UIViewController {
var gameController: GamesViewController?
var streamsController: StreamsViewController?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch (segue.destination) {
case (let controller as GamesViewController):
gameController = controller
gameController?.onGameSelected = onGameSelected()
case (let controller as StreamsViewController):
streamsController = controller
default:
super.prepare(for: segue, sender: sender)
}
}
func selectGame(_ gameName: String) {
self.streamsController?.viewModel.value = StreamList.ViewModelType(
.streams(gameName: gameName, page: 0), transform: StreamList.streamToViewModel)
}
func onGameSelected() -> (Game) -> () {
return {
[weak self] game in
self?.selectGame(game.name)
}
}
}
| bsd-3-clause |
Mattmlm/codepathtwitter | Codepath Twitter/Codepath Twitter/TweetDateFormatter.swift | 1 | 850 | //
// TweetDateFormatter.swift
// Codepath Twitter
//
// Created by admin on 10/2/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class TweetDateFormatter : NSObject {
class var sharedInstance : NSDateFormatter {
struct Static {
static var token : dispatch_once_t = 0
static var instance : NSDateFormatter? = nil
}
dispatch_once(&Static.token) {
Static.instance = NSDateFormatter()
Static.instance!.dateFormat = "EEE MMM d HH:mm:ss Z y"
}
return Static.instance!
}
class func setDateFormatterForInterpretingJSON() {
sharedInstance.dateFormat = "EEE MMM d HH:mm:ss Z y"
}
class func setDateFormatterForTweetDetails() {
sharedInstance.dateFormat = "M/d/yy, h:mm a"
}
} | mit |
sayheyrickjames/codepath-dev | week1/week1-class2-lab-facebook/week1-class2-lab-facebookTests/week1_class2_lab_facebookTests.swift | 2 | 955 | //
// week1_class2_lab_facebookTests.swift
// week1-class2-lab-facebookTests
//
// Created by Rick James! Chatas on 5/6/15.
// Copyright (c) 2015 SayHey. All rights reserved.
//
import UIKit
import XCTest
class week1_class2_lab_facebookTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
imxieyi/iosu | iosu/StoryBoard/Renderer/Commands/SBRotate.swift | 1 | 835 | //
// SBRotate.swift
// iosu
//
// Created by xieyi on 2017/5/16.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import SpriteKit
import SpriteKitEasingSwift
class SBRotate:SBCommand,SBCAction {
//Both in radians
var startr:Double
var endr:Double
init(easing:Int,starttime:Int,endtime:Int,startr:Double,endr:Double) {
self.startr = -startr
self.endr = -endr
super.init(type: .rotate, easing: easing, starttime: starttime, endtime: endtime)
}
func toAction() -> SKAction {
if starttime==endtime {
return SKAction.rotate(toAngle: CGFloat(endr), duration: 0)
}
return SKEase.rotate(easeFunction: easing.function, easeType: easing.type, time: duration, from: CGFloat(startr), to: CGFloat(endr))
}
}
| mit |
Cleverlance/Pyramid | Sources/Common/Testing/DummyCreatable.swift | 1 | 200 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
public protocol DummyCreatable {
static var dummy: Self { get }
}
extension Int: DummyCreatable {
public static let dummy = 0
}
| mit |
chinlam91/edx-app-ios | Source/UIView+LayoutDirection.swift | 4 | 688 | //
// UIView+LayoutDirection.swift
// edX
//
// Created by Akiva Leffert on 7/20/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
extension UIView {
var isRightToLeft : Bool {
// TODO: When we pick up iOS 9, pick up the new semantic content attribute stuff
return UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft
}
}
extension UIButton {
var naturalHorizontalAlignment : UIControlContentHorizontalAlignment {
if isRightToLeft {
return UIControlContentHorizontalAlignment.Right
}
else {
return UIControlContentHorizontalAlignment.Left
}
}
} | apache-2.0 |
kickstarter/ios-oss | Kickstarter-iOS/Features/Toggle/Controller/ToggleViewControllerTests.swift | 1 | 1597 | @testable import Kickstarter_Framework
@testable import Library
import UIKit
final class ToggleViewControllerTests: TestCase {
override func setUp() {
super.setUp()
AppEnvironment.pushEnvironment(mainBundle: Bundle.framework)
UIView.setAnimationsEnabled(false)
}
override func tearDown() {
AppEnvironment.popEnvironment()
UIView.setAnimationsEnabled(true)
super.tearDown()
}
func testView() {
let devices = [Device.phone4_7inch, Device.pad]
combos([Language.en], devices).forEach { language, device in
withEnvironment(language: language) {
let controller = ToggleViewController.instantiate()
controller.titleLabel.text = "Title for testing purposes only"
controller.toggle.setOn(true, animated: false)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = 60
FBSnapshotVerifyView(parent.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testView_LargerText() {
UITraitCollection.allCases.forEach { additionalTraits in
let controller = ToggleViewController.instantiate()
controller.titleLabel.text = "Title for testing purposes only"
controller.toggle.setOn(true, animated: false)
let (parent, _) = traitControllers(child: controller, additionalTraits: additionalTraits)
parent.view.frame.size.height = 300
FBSnapshotVerifyView(
parent.view, identifier: "trait_\(additionalTraits.preferredContentSizeCategory.rawValue)"
)
}
}
}
| apache-2.0 |
rdlester/simply-giphy | Pods/ReactiveSwift/Sources/Observer.swift | 1 | 2740 | //
// Observer.swift
// ReactiveSwift
//
// Created by Andy Matuschak on 10/2/15.
// Copyright © 2015 GitHub. All rights reserved.
//
/// A protocol for type-constrained extensions of `Observer`.
@available(*, deprecated, message: "The protocol will be removed in a future version of ReactiveSwift. Use Observer directly.")
public protocol ObserverProtocol {
associatedtype Value
associatedtype Error: Swift.Error
/// Puts a `value` event into `self`.
func send(value: Value)
/// Puts a failed event into `self`.
func send(error: Error)
/// Puts a `completed` event into `self`.
func sendCompleted()
/// Puts an `interrupted` event into `self`.
func sendInterrupted()
}
/// An Observer is a simple wrapper around a function which can receive Events
/// (typically from a Signal).
public final class Observer<Value, Error: Swift.Error> {
public typealias Action = (Event<Value, Error>) -> Void
/// An action that will be performed upon arrival of the event.
public let action: Action
/// An initializer that accepts a closure accepting an event for the
/// observer.
///
/// - parameters:
/// - action: A closure to lift over received event.
public init(_ action: @escaping Action) {
self.action = action
}
/// An initializer that accepts closures for different event types.
///
/// - parameters:
/// - value: Optional closure executed when a `value` event is observed.
/// - failed: Optional closure that accepts an `Error` parameter when a
/// failed event is observed.
/// - completed: Optional closure executed when a `completed` event is
/// observed.
/// - interruped: Optional closure executed when an `interrupted` event is
/// observed.
public convenience init(
value: ((Value) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil
) {
self.init { event in
switch event {
case let .value(v):
value?(v)
case let .failed(error):
failed?(error)
case .completed:
completed?()
case .interrupted:
interrupted?()
}
}
}
/// Puts a `value` event into `self`.
///
/// - parameters:
/// - value: A value sent with the `value` event.
public func send(value: Value) {
action(.value(value))
}
/// Puts a failed event into `self`.
///
/// - parameters:
/// - error: An error object sent with failed event.
public func send(error: Error) {
action(.failed(error))
}
/// Puts a `completed` event into `self`.
public func sendCompleted() {
action(.completed)
}
/// Puts an `interrupted` event into `self`.
public func sendInterrupted() {
action(.interrupted)
}
}
extension Observer: ObserverProtocol {}
| apache-2.0 |
apple/swift-nio | IntegrationTests/tests_04_performance/test_01_resources/test_1000_copying_circularbuffer_to_array.swift | 1 | 805 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
func run(identifier: String) {
let data = CircularBuffer(repeating: UInt8(0xfe), count: 1024)
measure(identifier: identifier) {
var count = 0
for _ in 0..<1_000 {
let copy = Array(data)
count &+= copy.count
}
return count
}
}
| apache-2.0 |
kjantzer/FolioReaderKit | Source/FolioReaderAudioPlayer.swift | 1 | 16544 | //
// FolioReaderAudioPlayer.swift
// FolioReaderKit
//
// Created by Kevin Jantzer on 1/4/16.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
public class FolioReaderAudioPlayer: NSObject {
var isTextToSpeech = false
var synthesizer: AVSpeechSynthesizer!
var playing = false
var player: AVAudioPlayer?
var currentHref: String!
var currentFragment: String!
var currentSmilFile: FRSmilFile!
var currentAudioFile: String!
var currentBeginTime: Double!
var currentEndTime: Double!
var playingTimer: NSTimer!
var registeredCommands = false
var completionHandler: () -> Void = {}
var utteranceRate: Float = 0
// MARK: Init
override init() {
super.init()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
// this is needed to the audio can play even when the "silent/vibrate" toggle is on
let session:AVAudioSession = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)
try! session.setActive(true)
updateNowPlayingInfo()
}
deinit {
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
}
// MARK: Reading speed
func setRate(rate: Int) {
if let player = player {
switch rate {
case 0:
player.rate = 0.5
break
case 1:
player.rate = 1.0
break
case 2:
player.rate = 1.5
break
case 3:
player.rate = 2
break
default:
break
}
updateNowPlayingInfo()
}
if synthesizer != nil {
// Need to change between version IOS
// http://stackoverflow.com/questions/32761786/ios9-avspeechutterance-rate-for-avspeechsynthesizer-issue
if #available(iOS 9, *) {
switch rate {
case 0:
utteranceRate = 0.42
break
case 1:
utteranceRate = 0.5
break
case 2:
utteranceRate = 0.53
break
case 3:
utteranceRate = 0.56
break
default:
break
}
} else {
switch rate {
case 0:
utteranceRate = 0
break
case 1:
utteranceRate = 0.06
break
case 2:
utteranceRate = 0.15
break
case 3:
utteranceRate = 0.23
break
default:
break
}
}
updateNowPlayingInfo()
}
}
// MARK: Play, Pause, Stop controls
func stop(immediate immediate: Bool = false) {
playing = false
if !isTextToSpeech {
if let player = player where player.playing {
player.stop()
}
} else {
stopSynthesizer(immediate: immediate, completion: nil)
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func stopSynthesizer(immediate immediate: Bool = false, completion: (() -> Void)? = nil) {
synthesizer.stopSpeakingAtBoundary(immediate ? .Immediate : .Word)
completion?()
}
func pause() {
playing = false
if !isTextToSpeech {
if let player = player where player.playing {
player.pause()
}
} else {
if synthesizer.speaking {
synthesizer.pauseSpeakingAtBoundary(.Word)
}
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func togglePlay() {
isPlaying() ? pause() : play()
}
func play() {
if book.hasAudio() {
guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return }
currentPage.webView.js("playAudio()")
} else {
readCurrentSentence()
}
// UIApplication.sharedApplication().idleTimerDisabled = true
}
func isPlaying() -> Bool {
return playing
}
/**
Play Audio (href/fragmentID)
Begins to play audio for the given chapter (href) and text fragment.
If this chapter does not have audio, it will delay for a second, then attempt to play the next chapter
*/
func playAudio(href: String, fragmentID: String) {
isTextToSpeech = false
stop()
let smilFile = book.smilFileForHref(href)
// if no smil file for this href and the same href is being requested, we've hit the end. stop playing
if smilFile == nil && currentHref != nil && href == currentHref {
return
}
playing = true
currentHref = href
currentFragment = "#"+fragmentID
currentSmilFile = smilFile
// if no smil file, delay for a second, then move on to the next chapter
if smilFile == nil {
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(_autoPlayNextChapter), userInfo: nil, repeats: false)
return
}
let fragment = smilFile.parallelAudioForFragment(currentFragment)
if fragment != nil {
if _playFragment(fragment) {
startPlayerTimer()
}
}
}
func _autoPlayNextChapter() {
// if user has stopped playing, dont play the next chapter
if isPlaying() == false { return }
playNextChapter()
}
func playPrevChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter.changePageToPrevious {
if self.isPlaying() {
self.play()
} else {
self.pause()
}
}
}
func playNextChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter.changePageToNext {
if self.isPlaying() {
self.play()
}
}
}
/**
Play Fragment of audio
Once an audio fragment begins playing, the audio clip will continue playing until the player timer detects
the audio is out of the fragment timeframe.
*/
private func _playFragment(smil: FRSmilElement!) -> Bool {
if smil == nil {
print("no more parallel audio to play")
stop()
return false
}
let textFragment = smil.textElement().attributes["src"]
let audioFile = smil.audioElement().attributes["src"]
currentBeginTime = smil.clipBegin()
currentEndTime = smil.clipEnd()
// new audio file to play, create the audio player
if player == nil || (audioFile != nil && audioFile != currentAudioFile) {
currentAudioFile = audioFile
let fileURL = currentSmilFile.resource.basePath().stringByAppendingString("/"+audioFile!)
let audioData = NSData(contentsOfFile: fileURL)
do {
player = try AVAudioPlayer(data: audioData!)
guard let player = player else { return false }
setRate(FolioReader.currentAudioRate)
player.enableRate = true
player.prepareToPlay()
player.delegate = self
updateNowPlayingInfo()
} catch {
print("could not read audio file:", audioFile)
return false
}
}
// if player is initialized properly, begin playing
guard let player = player else { return false }
// the audio may be playing already, so only set the player time if it is NOT already within the fragment timeframe
// this is done to mitigate milisecond skips in the audio when changing fragments
if player.currentTime < currentBeginTime || ( currentEndTime > 0 && player.currentTime > currentEndTime) {
player.currentTime = currentBeginTime;
updateNowPlayingInfo()
}
player.play()
// get the fragment ID so we can "mark" it in the webview
let textParts = textFragment!.componentsSeparatedByString("#")
let fragmentID = textParts[1];
FolioReader.sharedInstance.readerCenter.audioMark(href: currentHref, fragmentID: fragmentID)
return true
}
/**
Next Audio Fragment
Gets the next audio fragment in the current smil file, or moves on to the next smil file
*/
private func nextAudioFragment() -> FRSmilElement! {
let smilFile = book.smilFileForHref(currentHref)
if smilFile == nil { return nil }
let smil = currentFragment == nil ? smilFile.parallelAudioForFragment(nil) : smilFile.nextParallelAudioForFragment(currentFragment)
if smil != nil {
currentFragment = smil.textElement().attributes["src"]
return smil
}
currentHref = book.spine.nextChapter(currentHref)!.href
currentFragment = nil
currentSmilFile = smilFile
if currentHref == nil {
return nil
}
return nextAudioFragment()
}
func playText(href: String, text: String) {
isTextToSpeech = true
playing = true
currentHref = href
if synthesizer == nil {
synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self
setRate(FolioReader.currentAudioRate)
}
let utterance = AVSpeechUtterance(string: text)
utterance.rate = utteranceRate
utterance.voice = AVSpeechSynthesisVoice(language: book.metadata.language)
if synthesizer.speaking {
stopSynthesizer()
}
synthesizer.speakUtterance(utterance)
updateNowPlayingInfo()
}
// MARK: TTS Sentence
func speakSentence() {
guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return }
let sentence = currentPage.webView.js("getSentenceWithIndex('\(book.playbackActiveClass())')")
if sentence != nil {
let chapter = FolioReader.sharedInstance.readerCenter.getCurrentChapter()
let href = chapter != nil ? chapter!.href : "";
playText(href, text: sentence!)
} else {
if FolioReader.sharedInstance.readerCenter.isLastPage() {
stop()
} else {
FolioReader.sharedInstance.readerCenter.changePageToNext()
}
}
}
func readCurrentSentence() {
guard synthesizer != nil else { return speakSentence() }
if synthesizer.paused {
playing = true
synthesizer.continueSpeaking()
} else {
if synthesizer.speaking {
stopSynthesizer(immediate: false, completion: {
if let currentPage = FolioReader.sharedInstance.readerCenter.currentPage {
currentPage.webView.js("resetCurrentSentenceIndex()")
}
self.speakSentence()
})
} else {
speakSentence()
}
}
}
// MARK: - Audio timing events
private func startPlayerTimer() {
// we must add the timer in this mode in order for it to continue working even when the user is scrolling a webview
playingTimer = NSTimer(timeInterval: 0.01, target: self, selector: #selector(playerTimerObserver), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(playingTimer, forMode: NSRunLoopCommonModes)
}
private func stopPlayerTimer() {
if playingTimer != nil {
playingTimer.invalidate()
playingTimer = nil
}
}
func playerTimerObserver() {
guard let player = player else { return }
if currentEndTime != nil && currentEndTime > 0 && player.currentTime > currentEndTime {
_playFragment(nextAudioFragment())
}
}
// MARK: - Now Playing Info and Controls
/**
Update Now Playing info
Gets the book and audio information and updates on Now Playing Center
*/
func updateNowPlayingInfo() {
var songInfo = [String: AnyObject]()
// Get book Artwork
if let coverImage = book.coverImage, let artwork = UIImage(contentsOfFile: coverImage.fullHref) {
let albumArt = MPMediaItemArtwork(image: artwork)
songInfo[MPMediaItemPropertyArtwork] = albumArt
}
// Get book title
if let title = book.title() {
songInfo[MPMediaItemPropertyAlbumTitle] = title
}
// Get chapter name
if let chapter = getCurrentChapterName() {
songInfo[MPMediaItemPropertyTitle] = chapter
}
// Get author name
if let author = book.metadata.creators.first {
songInfo[MPMediaItemPropertyArtist] = author.name
}
// Set player times
if let player = player where !isTextToSpeech {
songInfo[MPMediaItemPropertyPlaybackDuration] = player.duration
songInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
songInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime ] = player.currentTime
}
// Set Audio Player info
MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo
registerCommandsIfNeeded()
}
/**
Get Current Chapter Name
This is done here and not in ReaderCenter because even though `currentHref` is accurate,
the `currentPage` in ReaderCenter may not have updated just yet
*/
func getCurrentChapterName() -> String? {
guard let chapter = FolioReader.sharedInstance.readerCenter.getCurrentChapter() else {
return nil
}
currentHref = chapter.href
for item in book.flatTableOfContents {
if let resource = item.resource where resource.href == currentHref {
return item.title
}
}
return nil
}
/**
Register commands if needed, check if it's registered to avoid register twice.
*/
func registerCommandsIfNeeded() {
guard !registeredCommands else { return }
let command = MPRemoteCommandCenter.sharedCommandCenter()
command.previousTrackCommand.enabled = true
command.previousTrackCommand.addTarget(self, action: #selector(playPrevChapter))
command.nextTrackCommand.enabled = true
command.nextTrackCommand.addTarget(self, action: #selector(playNextChapter))
command.pauseCommand.enabled = true
command.pauseCommand.addTarget(self, action: #selector(pause))
command.playCommand.enabled = true
command.playCommand.addTarget(self, action: #selector(play))
command.togglePlayPauseCommand.enabled = true
command.togglePlayPauseCommand.addTarget(self, action: #selector(togglePlay))
registeredCommands = true
}
}
// MARK: AVSpeechSynthesizerDelegate
extension FolioReaderAudioPlayer: AVSpeechSynthesizerDelegate {
public func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didCancelSpeechUtterance utterance: AVSpeechUtterance) {
completionHandler()
}
public func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
if isPlaying() {
readCurrentSentence()
}
}
}
// MARK: AVAudioPlayerDelegate
extension FolioReaderAudioPlayer: AVAudioPlayerDelegate {
public func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
_playFragment(nextAudioFragment())
}
} | bsd-3-clause |
scihant/CTShowcase | Example/Example/ViewController.swift | 1 | 882 | //
// ViewController.swift
// CTShowcase
//
// Created by Cihan Tek on 17/12/15.
// Copyright © 2015 Cihan Tek. All rights reserved.
//
import UIKit
import CTShowcase
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidAppear(_ animated: Bool) {
let showcase = CTShowcaseView(title: "New Feature!", message: "Here's a brand new button you can tap!", key: nil) { () -> Void in
print("dismissed")
}
let highlighter = CTDynamicGlowHighlighter()
highlighter.highlightColor = UIColor.yellow
highlighter.animDuration = 0.5
highlighter.glowSize = 5
highlighter.maxOffset = 10
showcase.highlighter = highlighter
showcase.setup(for: self.button, offset: CGPoint.zero, margin: 0)
showcase.show()
}
}
| mit |
milseman/swift | test/SILGen/opaque_ownership.swift | 4 | 4974 | // RUN: %target-swift-frontend -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
public protocol UnkeyedDecodingContainer {
var isAtEnd: Builtin.Int1 { get }
}
public protocol Decoder {
func unkeyedContainer() throws -> UnkeyedDecodingContainer
}
// Test open_existential_value ownership
// ---
// CHECK-LABEL: sil @_T0s11takeDecoderBi1_s0B0_p4from_tKF : $@convention(thin) (@in Decoder) -> (Builtin.Int1, @error Builtin.NativeObject) {
// CHECK: bb0(%0 : @owned $Decoder):
// CHECK: [[BORROW1:%.*]] = begin_borrow %0 : $Decoder
// CHECK: [[OPENED:%.*]] = open_existential_value [[BORROW1]] : $Decoder to $@opened("{{.*}}") Decoder
// CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") Decoder, #Decoder.unkeyedContainer!1 : <Self where Self : Decoder> (Self) -> () throws -> UnkeyedDecodingContainer, %4 : $@opened("{{.*}}") Decoder : $@convention(witness_method) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Builtin.NativeObject)
// CHECK: try_apply [[WT]]<@opened("{{.*}}") Decoder>([[OPENED]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Builtin.NativeObject), normal bb2, error bb1
//
// CHECK:bb{{.*}}([[RET1:%.*]] : @owned $UnkeyedDecodingContainer):
// CHECK: end_borrow [[BORROW1]] from %0 : $Decoder, $Decoder
// CHECK: [[BORROW2:%.*]] = begin_borrow [[RET1]] : $UnkeyedDecodingContainer
// CHECK: [[OPENED2:%.*]] = open_existential_value [[BORROW2]] : $UnkeyedDecodingContainer to $@opened("{{.*}}") UnkeyedDecodingContainer
// CHECK: [[WT2:%.*]] = witness_method $@opened("{{.*}}") UnkeyedDecodingContainer, #UnkeyedDecodingContainer.isAtEnd!getter.1 : <Self where Self : UnkeyedDecodingContainer> (Self) -> () -> Builtin.Int1, [[OPENED2]] : $@opened("{{.*}}") UnkeyedDecodingContainer : $@convention(witness_method) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1
// CHECK: [[RET2:%.*]] = apply [[WT2]]<@opened("{{.*}}") UnkeyedDecodingContainer>([[OPENED2]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1
// CHECK: end_borrow [[BORROW2]] from [[RET1]] : $UnkeyedDecodingContainer, $UnkeyedDecodingContainer
// CHECK: destroy_value [[RET1]] : $UnkeyedDecodingContainer
// CHECK: destroy_value %0 : $Decoder
// CHECK: return [[RET2]] : $Builtin.Int1
// CHECK-LABEL: } // end sil function '_T0s11takeDecoderBi1_s0B0_p4from_tKF'
public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 {
let container = try decoder.unkeyedContainer()
return container.isAtEnd
}
public enum Optional<Wrapped> {
case none
case some(Wrapped)
}
public protocol IP {}
public protocol Seq {
associatedtype Iterator : IP
func makeIterator() -> Iterator
}
extension Seq where Self.Iterator == Self {
public func makeIterator() -> Self {
return self
}
}
public struct EnumIter<Base : IP> : IP, Seq {
internal var _base: Base
public typealias Iterator = EnumIter<Base>
}
// Test passing a +1 RValue to @in_guaranteed.
// ---
// CHECK-LABEL: sil @_T0s7EnumSeqV12makeIterators0A4IterVy0D0QzGyF : $@convention(method) <Base where Base : Seq> (@in_guaranteed EnumSeq<Base>) -> @out EnumIter<Base.Iterator> {
// CHECK: bb0(%0 : @guaranteed $EnumSeq<Base>):
// CHECK: [[FN:%.*]] = function_ref @_T0s8EnumIterVAByxGx5_base_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
// CHECK: [[MT:%.*]] = metatype $@thin EnumIter<Base.Iterator>.Type
// CHECK: [[WT:%.*]] = witness_method $Base, #Seq.makeIterator!1 : <Self where Self : Seq> (Self) -> () -> Self.Iterator : $@convention(witness_method) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
// CHECK: [[FIELD:%.*]] = struct_extract %0 : $EnumSeq<Base>, #EnumSeq._base
// CHECK: [[COPY:%.*]] = copy_value [[FIELD]] : $Base
// CHECK: [[BORROW:%.*]] = begin_borrow [[COPY]] : $Base
// CHECK: [[ITER:%.*]] = apply [[WT]]<Base>([[BORROW]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
// CHECK: end_borrow [[BORROW]] from [[COPY]] : $Base, $Base
// CHECK: destroy_value [[COPY]] : $Base
// CHECK: [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
// CHECK: return [[RET]] : $EnumIter<Base.Iterator>
// CHECK-LABEL: } // end sil function '_T0s7EnumSeqV12makeIterators0A4IterVy0D0QzGyF'
public struct EnumSeq<Base : Seq> : Seq {
public typealias Iterator = EnumIter<Base.Iterator>
internal var _base: Base
public func makeIterator() -> Iterator {
return EnumIter(_base: _base.makeIterator())
}
}
| apache-2.0 |
eBardX/XestiMonitors | Sources/Core/DependencyInjection/FileManagerInjection.swift | 1 | 471 | //
// FileManagerInjection.swift
// XestiMonitors
//
// Created by J. G. Pusey on 2018-03-14.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
import Foundation
internal protocol FileManagerProtocol: AnyObject {
var ubiquityIdentityToken: (NSCoding & NSCopying & NSObjectProtocol)? { get }
}
extension FileManager: FileManagerProtocol {}
internal enum FileManagerInjector {
internal static var inject: () -> FileManagerProtocol = { FileManager.`default` }
}
| mit |
eBardX/XestiMonitors | Tests/Foundation/UndoManagerMonitorTests.swift | 1 | 9527 | //
// UndoManagerMonitorTests.swift
// XestiMonitorsTests
//
// Created by Rose Maina on 2018-04-30.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
import XCTest
@testable import XestiMonitors
internal class UndoManagerMonitorTests: XCTestCase {
let notificationCenter = MockNotificationCenter()
let undoManager = UndoManager()
override func setUp() {
super.setUp()
NotificationCenterInjector.inject = { self.notificationCenter }
}
func testMonitor_checkpoint() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .checkpoint,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateCheckpoint()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .checkpoint(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
func testMonitor_didCloseUndoGroup() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: undoManager,
options: .didCloseUndoGroup,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidCloseUndoGroup()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didCloseUndoGroup(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didOpenUndoGroup() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .didOpenUndoGroup,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidOpenUndoGroup()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didOpenUndoGroup(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
func testMonitor_didRedoChange() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .didRedoChange,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidRedoChange()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didRedoChange(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
func testMonitor_didUndoChange() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .didUndoChange,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidUndoChange()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didUndoChange(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
func testMonitor_willCloseUndoGroup() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .willCloseUndoGroup,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillCloseUndoGroup()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willCloseUndoGroup(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
func testMonitor_willRedoChange() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .willRedoChange,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillRedoChange()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willRedoChange(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
func testMonitor_willUndoChange() {
let expectation = self.expectation(description: "Handler called")
var expectedEvent: UndoManagerMonitor.Event?
let monitor = UndoManagerMonitor(undoManager: self.undoManager,
options: .willUndoChange,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillUndoChange()
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willUndoChange(test) = event {
XCTAssertEqual(test, undoManager)
} else {
XCTFail("Unexpected Event")
}
}
private func simulateCheckpoint() {
notificationCenter.post(name: .NSUndoManagerCheckpoint,
object: undoManager)
}
private func simulateDidCloseUndoGroup() {
notificationCenter.post(name: .NSUndoManagerDidCloseUndoGroup,
object: undoManager)
}
private func simulateDidOpenUndoGroup() {
notificationCenter.post(name: .NSUndoManagerDidOpenUndoGroup,
object: undoManager)
}
private func simulateDidRedoChange() {
notificationCenter.post(name: .NSUndoManagerDidRedoChange,
object: undoManager)
}
private func simulateDidUndoChange() {
notificationCenter.post(name: .NSUndoManagerDidUndoChange,
object: undoManager)
}
private func simulateWillCloseUndoGroup() {
notificationCenter.post(name: .NSUndoManagerWillCloseUndoGroup,
object: undoManager)
}
private func simulateWillRedoChange() {
notificationCenter.post(name: .NSUndoManagerWillRedoChange,
object: undoManager)
}
private func simulateWillUndoChange() {
notificationCenter.post(name: .NSUndoManagerWillUndoChange,
object: undoManager)
}
}
| mit |
jianghongfei/HidingNavigationBar | HidingNavigationBarSample/HidingNavigationBarSample/HidingNavToolbarViewController.swift | 3 | 2492 | //
// TableViewController.swift
// HidingNavigationBarSample
//
// Created by Tristan Himmelman on 2015-05-01.
// Copyright (c) 2015 Tristan Himmelman. All rights reserved.
//
import UIKit
class HidingNavToolbarViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let identifier = "cell"
var hidingNavBarManager: HidingNavigationBarManager?
var tableView: UITableView!
var toolbar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier)
view.addSubview(tableView)
toolbar = UIToolbar(frame: CGRectMake(0, view.bounds.size.height - 44, view.bounds.width, 44))
toolbar.barTintColor = UIColor(white: 230/255, alpha: 1)
view.addSubview(toolbar)
hidingNavBarManager = HidingNavigationBarManager(viewController: self, scrollView: tableView)
hidingNavBarManager?.manageBottomBar(toolbar)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
hidingNavBarManager?.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hidingNavBarManager?.viewDidLayoutSubviews()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
hidingNavBarManager?.viewWillDisappear(animated)
}
// MARK: UITableViewDelegate
func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
hidingNavBarManager?.shouldScrollToTop()
return true
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 100
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = "row \(indexPath.row)"
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
| mit |
OldBulls/swift-weibo | ZNWeibo/ZNWeibo/Classes/Compose/PicPickerCollectionView/PicPickerViewCell.swift | 1 | 1139 | //
// PicPickerViewCell.swift
// ZNWeibo
//
// Created by 金宝和信 on 16/7/14.
// Copyright © 2016年 zn. All rights reserved.
//
import UIKit
class PicPickerViewCell: UICollectionViewCell {
// MARK:- 控件的属性
@IBOutlet weak var addPhotoBtn: UIButton!
@IBOutlet weak var removePhotoBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
var image : UIImage? {
didSet {
if image != nil {
imageView.image = image
addPhotoBtn.userInteractionEnabled = false
removePhotoBtn.hidden = false
} else {
imageView.image = nil
addPhotoBtn.userInteractionEnabled = true
removePhotoBtn.hidden = true
}
}
}
// MARK:- 事件监听
@IBAction func addPhotoClick() {
NSNotificationCenter.defaultCenter().postNotificationName(PicPickerAddPhotoNote, object: nil)
}
@IBAction func removePhotoClick() {
NSNotificationCenter.defaultCenter().postNotificationName(PicPickerRemovePhotoNote, object: imageView.image)
}
}
| mit |
gegeburu3308119/ZCweb | ZCwebo/ZCwebo/Classes/Tools/Extensions/String+Extensions.swift | 1 | 1068 | //
// String+Extensions.swift
// 002-正则表达式
//
// Created by apple on 16/7/10.
// Copyright © 2016年 itcast. All rights reserved.
//
import Foundation
extension String {
/// 从当前字符串中,提取链接和文本
/// Swift 提供了`元组`,同时返回多个值
/// 如果是 OC,可以返回字典/自定义对象/指针的指针
func cz_href() -> (link: String, text: String)? {
// 0. 匹配方案
let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
// 1. 创建正则表达式,并且匹配第一项
guard let regx = try? NSRegularExpression(pattern: pattern, options: []),
let result = regx.firstMatch(in: self, options: [], range: NSRange(location: 0, length: characters.count))
else {
return nil
}
// 2. 获取结果
let link = (self as NSString).substring(with: result.range)
let text = (self as NSString).substring(with: result.range)
return (link, text)
}
}
| apache-2.0 |
yeziahehe/Gank | Gank/Extensions/UIImage+Named.swift | 1 | 1075 | //
// UIImage+Gank.swift
// Gank
//
// Created by 叶帆 on 2016/10/30.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
extension UIImage {
static var gank_navBg: UIImage {
return UIImage(named: "nav_bg")!
}
static var gank_dateBg: UIImage {
return UIImage(named: "date_bg")!
}
static var gank_meiziLoadingBg: UIImage {
return UIImage(named: "meizi_loading_bg")!
}
static var gank_dateLoadingBg: UIImage {
return UIImage(named: "date_loading_bg")!
}
static var gank_navBack: UIImage {
return UIImage(named: "nav_back")!
}
static var gank_meiziLoading: UIImage {
return UIImage(named: "meizi_loading")!
}
static var gank_navClose: UIImage {
return UIImage(named: "nav_close")!
}
static var gank_navSave: UIImage {
return UIImage(named: "nav_save")!
}
static var gank_logo: UIImage {
return UIImage(named: "logo")!
}
}
| gpl-3.0 |
juancruzmdq/LocationRequestManager | Example/Tests/Tests.swift | 1 | 3783 | // https://github.com/Quick/Quick
import Quick
import Nimble
import LocationRequestManager
class LocationRequestManagerSpec: QuickSpec {
override func spec() {
describe("LocationRequestManager") {
it("Constructor") {
let lm = LocationRequestManager()
expect(lm).toNot(beNil())
}
}
describe("LocationRequest") {
it("Constructor") {
let lr = LocationRequest({ (currentLocation, error) in
print("empty")
})
expect(lr).toNot(beNil())
expect(lr.status == .Pending).to(beTruthy())
}
}
describe("ManageRequests") {
var locationManager:LocationRequestManager!
beforeEach{
locationManager = LocationRequestManager()
}
it("Simple Add") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
locationManager.addRequest(request: lr1)
locationManager.addRequest(request: lr2)
expect(locationManager.requests.count).to(equal(2))
// Should avoid duplication of references
locationManager.addRequest(request: lr1)
locationManager.addRequest(request: lr2)
expect(locationManager.requests.count).to(equal(2))
}
it("Multiple Add") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
locationManager.addRequests(requests: [lr1,lr2])
expect(locationManager.requests.count).to(equal(2))
// Should avoid duplication of references
locationManager.addRequests(requests: [lr1,lr2])
expect(locationManager.requests.count).to(equal(2))
}
it("Simple Remove") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
locationManager.addRequest(request: lr1)
locationManager.addRequest(request: lr2)
expect(locationManager.requests.count).to(equal(2))
locationManager.removeRequest(request: lr2)
expect(locationManager.requests.count).to(equal(1))
}
it("Multiple Remove") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
let lr3 = LocationRequest(nil)
locationManager.addRequests(requests: [lr1,lr2,lr3])
expect(locationManager.requests.count).to(equal(3))
// Should avoid duplication of references
locationManager.removeRequests(requests: [lr1,lr3])
expect(locationManager.requests.count).to(equal(1))
}
it("Remove all") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
let lr3 = LocationRequest(nil)
locationManager.addRequests(requests: [lr1,lr2,lr3])
expect(locationManager.requests.count).to(equal(3))
// Should avoid duplication of references
locationManager.removeAllRequests()
expect(locationManager.requests.count).to(equal(0))
}
}
}
}
| mit |
KimDarren/allkfb | Allkdic/Models/KeyBinding.swift | 1 | 3661 | // The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (http://xoul.kr)
//
// 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.
private let _dictionaryKeys = ["keyCode", "shift", "control", "option", "command"]
public func ==(left: KeyBinding, right: KeyBinding) -> Bool {
for key in _dictionaryKeys {
if left.valueForKey(key) as? Int != right.valueForKey(key) as? Int {
return false
}
}
return true
}
@objc public class KeyBinding: NSObject {
var keyCode: Int = 0
var shift: Bool = false
var control: Bool = false
var option: Bool = false
var command: Bool = false
override public var description: String {
var keys = [String]()
if self.shift {
keys.append("Shift")
}
if self.control {
keys.append("Control")
}
if self.option {
keys.append("Option")
}
if self.command {
keys.append("Command")
}
if let keyString = self.dynamicType.keyStringFormKeyCode(self.keyCode) {
keys.append(keyString.capitalizedString)
}
return " + ".join(keys)
}
@objc public override init() {
super.init()
}
@objc public init(keyCode: Int, flags: Int) {
super.init()
self.keyCode = keyCode
for i in 0...6 {
if flags & (1 << i) != 0 {
if i == 0 {
self.control = true
} else if i == 1 {
self.shift = true
} else if i == 3 {
self.command = true
} else if i == 5 {
self.option = true
}
}
}
}
@objc public init(dictionary: [NSObject: AnyObject]?) {
super.init()
if dictionary == nil {
return
}
for key in _dictionaryKeys {
if let value = dictionary![key] as? Int {
self.setValue(value, forKey: key)
}
}
}
public func toDictionary() -> [String: Int] {
var dictionary = [String: Int]()
for key in _dictionaryKeys {
dictionary[key] = self.valueForKey(key)!.integerValue
}
return dictionary
}
public class func keyStringFormKeyCode(keyCode: Int) -> String? {
return keyMap[keyCode]
}
public class func keyCodeFormKeyString(string: String) -> Int {
for (keyCode, keyString) in keyMap {
if keyString == string {
return keyCode
}
}
return NSNotFound
}
}
| mit |
skylib/SnapImagePicker | SnapImagePicker/Categories/UIScrollView+fakeBounce.swift | 1 | 1520 | import UIKit
extension UIScrollView {
fileprivate func calculateOffsetFromVelocity(_ velocity: CGPoint) -> CGPoint {
var offset = CGPoint.zero
let x = Double(velocity.x / abs(velocity.x)) * pow(Double(28 * log(abs(velocity.x)) + 25), 1.2) * 0.6
let y = Double(velocity.y / abs(velocity.y)) * pow(Double(28 * log(abs(velocity.y)) + 25), 1.2) * 0.6
if !x.isNaN {
offset.x = CGFloat(x)
}
if !y.isNaN {
offset.y = CGFloat(y)
}
return offset
}
func manuallyBounceBasedOnVelocity(_ velocity: CGPoint, withAnimationDuration duration: Double = 0.2) {
let originalOffset = contentOffset
let offset = calculateOffsetFromVelocity(velocity)
UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
[weak self] in
if let strongSelf = self {
strongSelf.setContentOffset(CGPoint(x: originalOffset.x + offset.x, y: originalOffset.y + offset.y), animated: false)
}
}, completion: {
[weak self] (_) in
UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions(), animations: {
if let strongSelf = self {
strongSelf.setContentOffset(originalOffset, animated: false)
}
}, completion: nil)
})
}
}
| bsd-3-clause |
Touchwonders/Transition | Examples/NavigationTransitionsExample/Transition/Convenience.swift | 1 | 1729 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension UIView {
func snapshot() -> UIImageView {
return UIImageView(image: asImage())
}
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
extension CGPoint {
var vector: CGVector {
return CGVector(dx: x, dy: y)
}
}
extension CGVector {
var magnitude: CGFloat {
return sqrt(dx*dx + dy*dy)
}
}
| mit |
groue/GRDB.swift | Tests/GRDBTests/RowFromDictionaryLiteralTests.swift | 1 | 10558 | import XCTest
import GRDB
private enum CustomValue : Int, DatabaseValueConvertible, Equatable {
case a = 0
case b = 1
case c = 2
}
class RowFromDictionaryLiteralTests : RowTestCase {
func testRowAsSequence() {
let row: Row = ["a": 0, "b": 1, "c": 2]
var columnNames = Set<String>()
var ints = Set<Int>()
var bools = Set<Bool>()
for (columnName, dbValue) in row {
columnNames.insert(columnName)
ints.insert(Int.fromDatabaseValue(dbValue)!)
bools.insert(Bool.fromDatabaseValue(dbValue)!)
}
XCTAssertEqual(columnNames, ["a", "b", "c"])
XCTAssertEqual(ints, [0, 1, 2])
XCTAssertEqual(bools, [false, true, true])
}
func testColumnOrderIsPreserved() {
// Paramount for tests
let row: Row = ["a": 0, "i": 8, "b": 1, "h": 7, "c": 2, "g": 6, "d": 3, "f": 5, "e": 4]
XCTAssertEqual(Array(row.columnNames), ["a", "i", "b", "h", "c", "g", "d", "f", "e"])
}
func testDuplicateColumnNames() {
// Paramount for tests
let row: Row = ["a": 0, "a": 1]
XCTAssertEqual(Array(row.columnNames), ["a", "a"])
XCTAssertEqual(row["a"] as Int, 0)
}
func testRowValueAtIndex() {
let row: Row = ["a": 0, "b": 1, "c": 2]
let aIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "a" })!)
let bIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "b" })!)
let cIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "c" })!)
// Raw extraction
assertRowRawValueEqual(row, index: aIndex, value: 0 as Int64)
assertRowRawValueEqual(row, index: bIndex, value: 1 as Int64)
assertRowRawValueEqual(row, index: cIndex, value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, index: aIndex, value: 0 as Int)
assertRowConvertedValueEqual(row, index: bIndex, value: 1 as Int)
assertRowConvertedValueEqual(row, index: cIndex, value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, index: aIndex, value: CustomValue.a)
assertRowConvertedValueEqual(row, index: bIndex, value: CustomValue.b)
assertRowConvertedValueEqual(row, index: cIndex, value: CustomValue.c)
// Expect fatal error:
//
// row[-1]
// row[3]
}
func testRowValueNamed() {
let row: Row = ["a": 0, "b": 1, "c": 2]
// Raw extraction
assertRowRawValueEqual(row, name: "a", value: 0 as Int64)
assertRowRawValueEqual(row, name: "b", value: 1 as Int64)
assertRowRawValueEqual(row, name: "c", value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, name: "a", value: 0 as Int)
assertRowConvertedValueEqual(row, name: "b", value: 1 as Int)
assertRowConvertedValueEqual(row, name: "c", value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a)
assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b)
assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c)
}
func testRowValueFromColumn() {
let row: Row = ["a": 0, "b": 1, "c": 2]
// Raw extraction
assertRowRawValueEqual(row, column: Column("a"), value: 0 as Int64)
assertRowRawValueEqual(row, column: Column("b"), value: 1 as Int64)
assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64)
// DatabaseValueConvertible & StatementColumnConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int)
assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int)
assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int)
// DatabaseValueConvertible
assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a)
assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b)
assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c)
}
func testWithUnsafeData() throws {
do {
let data = "foo".data(using: .utf8)!
let row: Row = ["a": data]
try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) }
try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) }
try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) }
try row.withUnsafeData(named: "missing") { XCTAssertNil($0) }
try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) }
}
do {
let emptyData = Data()
let row: Row = ["a": emptyData]
try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, emptyData) }
try row.withUnsafeData(named: "a") { XCTAssertEqual($0, emptyData) }
try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, emptyData) }
}
do {
let row: Row = ["a": nil]
try row.withUnsafeData(atIndex: 0) { XCTAssertNil($0) }
try row.withUnsafeData(named: "a") { XCTAssertNil($0) }
try row.withUnsafeData(at: Column("a")) { XCTAssertNil($0) }
}
}
func testRowDatabaseValueAtIndex() throws {
let row: Row = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
let nullIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "null" })!)
let int64Index = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "int64" })!)
let doubleIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "double" })!)
let stringIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "string" })!)
let blobIndex = row.distance(from: row.startIndex, to: row.firstIndex(where: { (column, value) in column == "blob" })!)
guard case .null = (row[nullIndex] as DatabaseValue).storage else { XCTFail(); return }
guard case .int64(let int64) = (row[int64Index] as DatabaseValue).storage, int64 == 1 else { XCTFail(); return }
guard case .double(let double) = (row[doubleIndex] as DatabaseValue).storage, double == 1.1 else { XCTFail(); return }
guard case .string(let string) = (row[stringIndex] as DatabaseValue).storage, string == "foo" else { XCTFail(); return }
guard case .blob(let data) = (row[blobIndex] as DatabaseValue).storage, data == "SQLite".data(using: .utf8) else { XCTFail(); return }
}
func testRowDatabaseValueNamed() throws {
let row: Row = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
guard case .null = (row["null"] as DatabaseValue).storage else { XCTFail(); return }
guard case .int64(let int64) = (row["int64"] as DatabaseValue).storage, int64 == 1 else { XCTFail(); return }
guard case .double(let double) = (row["double"] as DatabaseValue).storage, double == 1.1 else { XCTFail(); return }
guard case .string(let string) = (row["string"] as DatabaseValue).storage, string == "foo" else { XCTFail(); return }
guard case .blob(let data) = (row["blob"] as DatabaseValue).storage, data == "SQLite".data(using: .utf8) else { XCTFail(); return }
}
func testRowCount() {
let row: Row = ["a": 0, "b": 1, "c": 2]
XCTAssertEqual(row.count, 3)
}
func testRowColumnNames() {
let row: Row = ["a": 0, "b": 1, "c": 2]
XCTAssertEqual(Array(row.columnNames).sorted(), ["a", "b", "c"])
}
func testRowDatabaseValues() {
let row: Row = ["a": 0, "b": 1, "c": 2]
XCTAssertEqual(row.databaseValues.sorted { Int.fromDatabaseValue($0)! < Int.fromDatabaseValue($1)! }, [0.databaseValue, 1.databaseValue, 2.databaseValue])
}
func testRowIsCaseInsensitive() {
let row: Row = ["name": "foo"]
XCTAssertEqual(row["name"] as DatabaseValue, "foo".databaseValue)
XCTAssertEqual(row["NAME"] as DatabaseValue, "foo".databaseValue)
XCTAssertEqual(row["NaMe"] as DatabaseValue, "foo".databaseValue)
XCTAssertEqual(row["name"] as String, "foo")
XCTAssertEqual(row["NAME"] as String, "foo")
XCTAssertEqual(row["NaMe"] as String, "foo")
}
func testMissingColumn() {
let row: Row = ["name": "foo"]
XCTAssertFalse(row.hasColumn("missing"))
XCTAssertTrue(row["missing"] as DatabaseValue? == nil)
XCTAssertTrue(row["missing"] == nil)
}
func testRowHasColumnIsCaseInsensitive() {
let row: Row = ["nAmE": "foo", "foo": 1]
XCTAssertTrue(row.hasColumn("name"))
XCTAssertTrue(row.hasColumn("NAME"))
XCTAssertTrue(row.hasColumn("Name"))
XCTAssertTrue(row.hasColumn("NaMe"))
XCTAssertTrue(row.hasColumn("foo"))
XCTAssertTrue(row.hasColumn("Foo"))
XCTAssertTrue(row.hasColumn("FOO"))
}
func testScopes() {
let row: Row = ["a": 0, "b": 1, "c": 2]
XCTAssertTrue(row.scopes.isEmpty)
XCTAssertTrue(row.scopes["missing"] == nil)
XCTAssertTrue(row.scopesTree["missing"] == nil)
}
func testCopy() {
let row: Row = ["a": 0, "b": 1, "c": 2]
let copiedRow = row.copy()
XCTAssertEqual(copiedRow.count, 3)
XCTAssertEqual(copiedRow["a"] as Int, 0)
XCTAssertEqual(copiedRow["b"] as Int, 1)
XCTAssertEqual(copiedRow["c"] as Int, 2)
}
func testEqualityWithCopy() {
let row: Row = ["a": 0, "b": 1, "c": 2]
let copiedRow = row.copy()
XCTAssertEqual(row, copiedRow)
}
func testDescription() throws {
let row: Row = ["a": 0, "b": 1, "c": 2]
XCTAssertEqual(row.description, "[a:0 b:1 c:2]")
XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]")
}
}
| mit |
SparrowTek/LittleManComputer | LittleManComputer/Modules/Help/HelpView.swift | 1 | 2055 | //
// HelpView.swift
// LittleManComputer
//
// Created by Thomas J. Rademaker on 9/17/20.
// Copyright © 2020 SparrowTek LLC. All rights reserved.
//
import SwiftUI
struct HelpView: View {
@EnvironmentObject var appState: AppState
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@State private var showWiki = false
private var appVersion: String? {
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
}
private var isIpadAndRegularWidth: Bool {
appState.isIpad && horizontalSizeClass == .regular }
var body: some View {
VStack {
if isIpadAndRegularWidth {
SheetTopClose()
} else {
SheetTopBar()
}
Spacer()
LMCButton(title: "instructions", maxHeight: 50, maxWidth: .infinity, action: { showWiki.toggle() })
.padding()
Spacer()
Text("settingsTitle")
.font(.system(size: 20, weight: .bold))
HStack {
VStack {
HStack {
Text("version")
Text(appVersion ?? "")
}
Button(action: {
guard let url = URL(string: "https://sparrowtek.com") else { return }
UIApplication.shared.open(url)
}) {
Text("SparrowTek")
.font(.system(size: 14, weight: .bold))
}
}
.padding(.leading)
Spacer()
Image("sparrowtek")
.resizable()
.frame(width: 100, height: 100)
.padding()
}
}
.background(Color(Colors.launchScreen))
.sheet(isPresented: $showWiki) {
WikiView()
}
}
}
struct HelpView_Previews: PreviewProvider {
static var previews: some View {
HelpView()
}
}
| mit |
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind | newsApp 1.9/newsApp/DetalleArticuloViewController.swift | 1 | 6554 | //
// DetalleArticuloViewController.swift
// newsApp
//
// Created by Miguel Gutiérrez Moreno on 23/1/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
// v 1.8: permite compartir por email y Twitter
import UIKit
import MessageUI
import Social
class DetalleArticuloViewController: UIViewController, MFMailComposeViewControllerDelegate, UISplitViewControllerDelegate {
// MARK: properties
@IBOutlet weak var articuloTextView: UITextView!
var articulo : Articulo? {
didSet {
// Update the view.
if isViewLoaded() {
muestraInformacion()
}
}
}
weak var delegate : ArticulosTableViewController?
weak var masterPopoverController : UIPopoverController?
// MARK: life cicle
override func viewDidLoad() {
super.viewDidLoad()
muestraInformacion()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - eventos
@IBAction func compartir(sender: UIButton) {
let titulo = NSLocalizedString("Compártelo", comment: "")
let mailButtonTitle = NSLocalizedString("Mail", comment: "")
let twitterButtonTitle = NSLocalizedString("Twitter", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let alertController = UIAlertController(title: titulo, message: nil, preferredStyle: .ActionSheet)
// Create the action.
let mailAction = UIAlertAction(title: mailButtonTitle, style: .Default) {
[unowned self]
action in
self.enviarMail()
}
let twitterAction = UIAlertAction(title: twitterButtonTitle, style: .Default) {
[unowned self]
action in
self.compartirTwitter()
}
let destructiveAction = UIAlertAction(title: cancelButtonTitle, style: .Destructive, handler: nil)
// Add the action.
alertController.addAction(mailAction)
alertController.addAction(twitterAction)
alertController.addAction(destructiveAction)
// necesario para el iPAD
if let popover = alertController.popoverPresentationController{
popover.sourceView = sender
popover.sourceRect = sender.bounds
popover.permittedArrowDirections = UIPopoverArrowDirection.Any
}
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - UISplitViewControllerDelegate
// sustituir están deprecated en iOS 8
/*
func splitViewController(svc: UISplitViewController, willHideViewController aViewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController pc: UIPopoverController) {
barButtonItem.title = "Artículos"
navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
masterPopoverController = pc
}
func splitViewController(svc: UISplitViewController, willShowViewController aViewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
navigationItem.setLeftBarButtonItem(nil, animated: true)
masterPopoverController = nil
}
func splitViewController(svc: UISplitViewController, shouldHideViewController vc: UIViewController, inOrientation orientation: UIInterfaceOrientation) -> Bool {
if orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight {
return false
}
else {
return true
}
}
*/
func muestraInformacion() {
if let articulo = self.articulo {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = FormatoFecha.formatoGeneral
if let fecha = articulo.fecha {
let fechaStr = dateFormatter.stringFromDate(fecha)
if let nombre = articulo.nombre {
navigationItem.title = "Artículo de \(nombre)"
if let texto = articulo.texto{
articuloTextView.text = "Nombre: \(nombre)\n Fecha: \(fechaStr)\n Texto: \(texto)"
}
}
}
}
if let masterPopoverController = masterPopoverController {
masterPopoverController.dismissPopoverAnimated(true)
}
}
// MARK: - funciones auxiliares
private func enviarMail() {
if MFMailComposeViewController.canSendMail() {
if let articulo = articulo {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
if let nombre=articulo.nombre, texto=articulo.texto, fecha=articulo.fecha { mailComposer.setToRecipients(["miguel.gutierrez.moreno@gmail.com","otro.correo@gmail.com"])
let asunto = NSString(format: "Escritor: %@ Fecha: %@ \n Artículo: %@", nombre,fecha,texto)
mailComposer.setSubject("Artículo de " + articulo.nombre!)
mailComposer.setMessageBody(asunto as String, isHTML: false)
mailComposer.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
presentViewController(mailComposer, animated: true, completion: nil)
}
}
}
}
private func compartirTwitter() {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
if let articulo = articulo {
let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
tweetSheet.setInitialText("Lee el artículo de: "+articulo.nombre!)
presentViewController(tweetSheet, animated: true, completion: nil)
}
}
}
}
| mit |
CaiMiao/CGSSGuide | DereGuide/Card/Detail/Controller/GalleryImageItemBaseController.swift | 1 | 1471 | //
// GalleryImageItemBaseController.swift
// DereGuide
//
// Created by zzk on 2017/8/29.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import ImageViewer
import AudioToolbox
class GalleryImageItemBaseController: ItemBaseController<UIImageView> {
override func viewDidLoad() {
super.viewDidLoad()
itemView.isUserInteractionEnabled = true
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
itemView.addGestureRecognizer(longPress)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let size = itemView.image?.size {
if size.width < view.bounds.width && size.height < view.bounds.height {
itemView.contentMode = .center
} else {
itemView.contentMode = .scaleAspectFit
}
}
}
@objc func handleLongPressGesture(_ longPress: UILongPressGestureRecognizer) {
guard let image = itemView.image else {
return
}
switch longPress.state {
case .began:
let point = longPress.location(in: itemView)
// play sound like pop(3d touch)
AudioServicesPlaySystemSound(1520)
UIActivityViewController.show(images: [image], pointTo: itemView, rect: CGRect(origin: point, size: .zero), in: self)
default:
break
}
}
}
| mit |
ploden/viral-bible-ios | Viral-Bible-Ios/Viral-Bible-IosTests/Viral_Bible_IosTests.swift | 1 | 928 | //
// Viral_Bible_IosTests.swift
// Viral-Bible-IosTests
//
// Created by Alan Young Admin on 10/3/15.
// Copyright (c) 2015 Alan Young. All rights reserved.
//
import UIKit
import XCTest
class Viral_Bible_IosTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
eramdam/WallbaseDirectDownloader | safari/Wallhaven Direct Downloader/Wallhaven Direct Downloader/AppDelegate.swift | 1 | 570 | //
// AppDelegate.swift
// Wallhaven Direct Downloader
//
// Created by Damien Erambert on 2/28/21.
//
import Cocoa
@main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ notification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
| gpl-2.0 |
frankeh/swift-corelibs-libdispatch | src/swift/Queue.swift | 1 | 11219 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// dispatch/queue.h
import CDispatch
public final class DispatchSpecificKey<T> {
public init() {}
}
internal class _DispatchSpecificValue<T> {
internal let value: T
internal init(value: T) { self.value = value }
}
public extension DispatchQueue {
public struct Attributes : OptionSet {
public let rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
public static let concurrent = Attributes(rawValue: 1<<1)
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static let initiallyInactive = Attributes(rawValue: 1<<2)
fileprivate func _attr() -> dispatch_queue_attr_t? {
var attr: dispatch_queue_attr_t? = nil
if self.contains(.concurrent) {
attr = _swift_dispatch_queue_concurrent()
}
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
if self.contains(.initiallyInactive) {
attr = CDispatch.dispatch_queue_attr_make_initially_inactive(attr)
}
}
return attr
}
}
public enum GlobalQueuePriority {
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case high
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case `default`
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case low
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case background
internal var _translatedValue: Int {
switch self {
case .high: return 2 // DISPATCH_QUEUE_PRIORITY_HIGH
case .default: return 0 // DISPATCH_QUEUE_PRIORITY_DEFAULT
case .low: return -2 // DISPATCH_QUEUE_PRIORITY_LOW
case .background: return Int(Int16.min) // DISPATCH_QUEUE_PRIORITY_BACKGROUND
}
}
}
public enum AutoreleaseFrequency {
case inherit
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
case workItem
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
case never
internal func _attr(attr: dispatch_queue_attr_t?) -> dispatch_queue_attr_t? {
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
switch self {
case .inherit:
// DISPATCH_AUTORELEASE_FREQUENCY_INHERIT
return CDispatch.dispatch_queue_attr_make_with_autorelease_frequency(attr, dispatch_autorelease_frequency_t(0))
case .workItem:
// DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM
return CDispatch.dispatch_queue_attr_make_with_autorelease_frequency(attr, dispatch_autorelease_frequency_t(1))
case .never:
// DISPATCH_AUTORELEASE_FREQUENCY_NEVER
return CDispatch.dispatch_queue_attr_make_with_autorelease_frequency(attr, dispatch_autorelease_frequency_t(2))
}
} else {
return attr
}
}
}
public class func concurrentPerform(iterations: Int, execute work: (Int) -> Void) {
_swift_dispatch_apply_current(iterations, work)
}
public class var main: DispatchQueue {
return DispatchQueue(queue: _swift_dispatch_get_main_queue())
}
@available(OSX, deprecated: 10.10, message: "")
@available(*, deprecated: 8.0, message: "")
public class func global(priority: GlobalQueuePriority) -> DispatchQueue {
return DispatchQueue(queue: CDispatch.dispatch_get_global_queue(priority._translatedValue, 0))
}
@available(OSX 10.10, iOS 8.0, *)
public class func global(qos: DispatchQoS.QoSClass = .default) -> DispatchQueue {
return DispatchQueue(queue: CDispatch.dispatch_get_global_queue(Int(qos.rawValue.rawValue), 0))
}
public class func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? {
let k = Unmanaged.passUnretained(key).toOpaque()
if let p = CDispatch.dispatch_get_specific(k) {
let v = Unmanaged<_DispatchSpecificValue<T>>
.fromOpaque(p)
.takeUnretainedValue()
return v.value
}
return nil
}
public convenience init(
label: String,
qos: DispatchQoS = .unspecified,
attributes: Attributes = [],
autoreleaseFrequency: AutoreleaseFrequency = .inherit,
target: DispatchQueue? = nil)
{
var attr = attributes._attr()
if autoreleaseFrequency != .inherit {
attr = autoreleaseFrequency._attr(attr: attr)
}
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified {
attr = CDispatch.dispatch_queue_attr_make_with_qos_class(attr, qos.qosClass.rawValue.rawValue, Int32(qos.relativePriority))
}
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
self.init(__label: label, attr: attr, queue: target)
} else {
self.init(__label: label, attr: attr)
if let tq = target { self.setTarget(queue: tq) }
}
}
public var label: String {
return String(validatingUTF8: dispatch_queue_get_label(self.__wrapped))!
}
@available(OSX 10.10, iOS 8.0, *)
public func sync(execute workItem: DispatchWorkItem) {
CDispatch.dispatch_sync(self.__wrapped, workItem._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func async(execute workItem: DispatchWorkItem) {
CDispatch.dispatch_async(self.__wrapped, workItem._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func async(group: DispatchGroup, execute workItem: DispatchWorkItem) {
CDispatch.dispatch_group_async(group.__wrapped, self.__wrapped, workItem._block)
}
public func async(
group: DispatchGroup? = nil,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void)
{
if group == nil && qos == .unspecified && flags.isEmpty {
// Fast-path route for the most common API usage
CDispatch.dispatch_async(self.__wrapped, work)
return
}
var block: @convention(block) () -> Void = work
if #available(OSX 10.10, iOS 8.0, *), (qos != .unspecified || !flags.isEmpty) {
let workItem = DispatchWorkItem(qos: qos, flags: flags, block: work)
block = workItem._block
}
if let g = group {
CDispatch.dispatch_group_async(g.__wrapped, self.__wrapped, block)
} else {
CDispatch.dispatch_async(self.__wrapped, block)
}
}
private func _syncBarrier(block: () -> ()) {
CDispatch.dispatch_barrier_sync(self.__wrapped, block)
}
private func _syncHelper<T>(
fn: (() -> ()) -> (),
execute work: () throws -> T,
rescue: ((Swift.Error) throws -> (T))) rethrows -> T
{
var result: T?
var error: Swift.Error?
fn {
do {
result = try work()
} catch let e {
error = e
}
}
if let e = error {
return try rescue(e)
} else {
return result!
}
}
@available(OSX 10.10, iOS 8.0, *)
private func _syncHelper<T>(
fn: (DispatchWorkItem) -> (),
flags: DispatchWorkItemFlags,
execute work: () throws -> T,
rescue: @escaping ((Swift.Error) throws -> (T))) rethrows -> T
{
var result: T?
var error: Swift.Error?
let workItem = DispatchWorkItem(flags: flags, noescapeBlock: {
do {
result = try work()
} catch let e {
error = e
}
})
fn(workItem)
if let e = error {
return try rescue(e)
} else {
return result!
}
}
public func sync<T>(execute work: () throws -> T) rethrows -> T {
return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
}
public func sync<T>(flags: DispatchWorkItemFlags, execute work: () throws -> T) rethrows -> T {
if flags == .barrier {
return try self._syncHelper(fn: _syncBarrier, execute: work, rescue: { throw $0 })
} else if #available(OSX 10.10, iOS 8.0, *), !flags.isEmpty {
return try self._syncHelper(fn: sync, flags: flags, execute: work, rescue: { throw $0 })
} else {
return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
}
}
public func asyncAfter(
deadline: DispatchTime,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void)
{
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: work)
CDispatch.dispatch_after(deadline.rawValue, self.__wrapped, item._block)
} else {
CDispatch.dispatch_after(deadline.rawValue, self.__wrapped, work)
}
}
public func asyncAfter(
wallDeadline: DispatchWallTime,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void)
{
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: work)
CDispatch.dispatch_after(wallDeadline.rawValue, self.__wrapped, item._block)
} else {
CDispatch.dispatch_after(wallDeadline.rawValue, self.__wrapped, work)
}
}
@available(OSX 10.10, iOS 8.0, *)
public func asyncAfter(deadline: DispatchTime, execute: DispatchWorkItem) {
CDispatch.dispatch_after(deadline.rawValue, self.__wrapped, execute._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func asyncAfter(wallDeadline: DispatchWallTime, execute: DispatchWorkItem) {
CDispatch.dispatch_after(wallDeadline.rawValue, self.__wrapped, execute._block)
}
@available(OSX 10.10, iOS 8.0, *)
public var qos: DispatchQoS {
var relPri: Int32 = 0
let cls = DispatchQoS.QoSClass(rawValue: _OSQoSClass(qosClass: dispatch_queue_get_qos_class(self.__wrapped, &relPri))!)!
return DispatchQoS(qosClass: cls, relativePriority: Int(relPri))
}
public func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? {
let k = Unmanaged.passUnretained(key).toOpaque()
if let p = dispatch_queue_get_specific(self.__wrapped, k) {
let v = Unmanaged<_DispatchSpecificValue<T>>
.fromOpaque(p)
.takeUnretainedValue()
return v.value
}
return nil
}
public func setSpecific<T>(key: DispatchSpecificKey<T>, value: T) {
let v = _DispatchSpecificValue(value: value)
let k = Unmanaged.passUnretained(key).toOpaque()
let p = Unmanaged.passRetained(v).toOpaque()
dispatch_queue_set_specific(self.__wrapped, k, p, _destructDispatchSpecificValue)
}
}
private func _destructDispatchSpecificValue(ptr: UnsafeMutableRawPointer?) {
if let p = ptr {
Unmanaged<AnyObject>.fromOpaque(p).release()
}
}
@_silgen_name("_swift_dispatch_queue_concurrent")
internal func _swift_dispatch_queue_concurrent() -> dispatch_queue_attr_t
@_silgen_name("_swift_dispatch_get_main_queue")
internal func _swift_dispatch_get_main_queue() -> dispatch_queue_t
@_silgen_name("_swift_dispatch_apply_current_root_queue")
internal func _swift_dispatch_apply_current_root_queue() -> dispatch_queue_t
@_silgen_name("_swift_dispatch_apply_current")
internal func _swift_dispatch_apply_current(_ iterations: Int, _ block: @convention(block) (Int) -> Void)
| apache-2.0 |
guillermo-ag-95/App-Development-with-Swift-for-Students | 4 - Tables and Persistence/7 - Saving Data/lab/EmojiDictionary/EmojiDictionary/EmojiTableViewController.swift | 1 | 5023 |
import UIKit
class EmojiTableViewController: UITableViewController {
var emojis = [Emoji(symbol: "😀", name: "Grinning Face", detailDescription: "A typical smiley face.", usage: "happiness"),
Emoji(symbol: "😕", name: "Confused Face", detailDescription: "A confused, puzzled face.", usage: "unsure what to think; displeasure"),
Emoji(symbol: "😍", name: "Heart Eyes", detailDescription: "A smiley face with hearts for eyes.", usage: "love of something; attractive"),
Emoji(symbol: "👮", name: "Police Officer", detailDescription: "A police officer wearing a blue cap with a gold badge. He is smiling, and eager to help.", usage: "person of authority"),
Emoji(symbol: "🐢", name: "Turtle", detailDescription: "A cute turtle.", usage: "Something slow"),
Emoji(symbol: "🐘", name: "Elephant", detailDescription: "A gray elephant.", usage: "good memory"),
Emoji(symbol: "🍝", name: "Spaghetti", detailDescription: "A plate of spaghetti.", usage: "spaghetti"),
Emoji(symbol: "🎲", name: "Die", detailDescription: "A single die.", usage: "taking a risk, chance; game"),
Emoji(symbol: "⛺️", name: "Tent", detailDescription: "A small tent.", usage: "camping"),
Emoji(symbol: "📚", name: "Stack of Books", detailDescription: "Three colored books stacked on each other.", usage: "homework, studying"),
Emoji(symbol: "💔", name: "Broken Heart", detailDescription: "A red, broken heart.", usage: "extreme sadness"),
Emoji(symbol: "💤", name: "Snore", detailDescription: "Three blue \'z\'s.", usage: "tired, sleepiness"),
Emoji(symbol: "🏁", name: "Checkered Flag", detailDescription: "A black and white checkered flag.", usage: "completion")]
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emojis.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EmojiCell", for: indexPath) as! EmojiTableViewCell
let emoji = emojis[indexPath.row]
cell.update(with: emoji)
cell.showsReorderControl = true
return cell
}
@IBAction func editButtonTapped(_ sender: UIBarButtonItem) {
let tableViewEditingMode = tableView.isEditing
tableView.setEditing(!tableViewEditingMode, animated: true)
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
emojis.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let movedEmoji = emojis.remove(at: fromIndexPath.row)
emojis.insert(movedEmoji, at: to.row)
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
}
// MARK: - Navigation
@IBAction func unwindToEmojiTableView(segue: UIStoryboardSegue) {
guard segue.identifier == "saveUnwind" else { return }
let sourceViewController = segue.source as! AddEditEmojiTableViewController
if let emoji = sourceViewController.emoji {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
emojis[selectedIndexPath.row] = emoji
tableView.reloadRows(at: [selectedIndexPath], with: .none)
} else {
let newIndexPath = IndexPath(row: emojis.count, section: 0)
emojis.append(emoji)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditEmoji" {
let indexPath = tableView.indexPathForSelectedRow!
let emoji = emojis[indexPath.row]
let navController = segue.destination as! UINavigationController
let addEditEmojiTableViewController = navController.topViewController as! AddEditEmojiTableViewController
addEditEmojiTableViewController.emoji = emoji
}
}
}
| mit |
huonw/swift | validation-test/IDE/crashers_fixed/102-swift-typechecker-gettypeofrvalue.swift | 66 | 173 | // RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
protocol B
let a{
protocol A{extension{
func b{func a:B
extension{var _=a{#^A^#
| apache-2.0 |
Bizzi-Body/ParseTutorialPart8---CompleteSolution | ParseTutorial/SignUpInViewController.swift | 1 | 6631 | //
// SignUpInViewController.swift
// ParseTutorial
//
// Created by Ian Bradbury on 10/02/2015.
// Copyright (c) 2015 bizzi-body. All rights reserved.
//
import UIKit
class SignUpInViewController: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var message: UILabel!
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var password: UITextField!
@IBAction func forgottenPassword(sender: AnyObject) {
let targetEmailAddress = emailAddress.text.lowercaseString
// Create an alert - tell the user they need to provide an email address
if targetEmailAddress == "" {
let alertController = UIAlertController(title: "Missing Email Address",
message: "Please provide an email address so that we can process your password request.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: nil)
)
self.presentViewController(
alertController,
animated: true,
completion: nil
)
} else {
// We have an email address - attempt to initiate a password reset request on the parse platform
// For security - We do not let the user know if the request to reset their password was successful or not
let didSendForgottenEmail = PFUser.requestPasswordResetForEmail(targetEmailAddress)
// Create an alert - tell the user an email has been sent - maybe
let alertController = UIAlertController(title: "Password Reset",
message: "If an account with that email address exists - we have sent an email containing instructions on how to complete your request.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: nil)
)
self.presentViewController(
alertController,
animated: true,
completion: nil
)
}
}
@IBAction func signUp(sender: AnyObject) {
// Build the terms and conditions alert
let alertController = UIAlertController(title: "Agree to terms and conditions",
message: "Click I AGREE to signal that you agree to the End User Licence Agreement.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "I AGREE",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignUp()})
)
alertController.addAction(UIAlertAction(title: "I do NOT agree",
style: UIAlertActionStyle.Default,
handler: nil)
)
// Display alert
self.presentViewController(alertController, animated: true, completion: nil)
}
@IBAction func signIn(sender: AnyObject) {
activityIndicator.hidden = false
activityIndicator.startAnimating()
// Clear an previous sign in message
message.text = ""
var userEmailAddress = emailAddress.text
userEmailAddress = userEmailAddress.lowercaseString
var userPassword = password.text
PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) {
(user: PFUser?, error: NSError?) -> Void in
// If there is a user
if let user = user {
if user["emailVerified"] as! Bool == true {
// Update last signed in value
user["lastSignIn"] = NSDate()
user.saveEventually()
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier(
"signInToNavigation",
sender: self
)
}
} else {
// User needs to verify email address before continuing
let alertController = UIAlertController(
title: "Email address verification",
message: "We have sent you an email that contains a link - you must click this link before you can continue.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "OKAY",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignOut()})
)
// Display alert
self.presentViewController(
alertController,
animated: true,
completion: nil
)
}
} else {
// User authentication failed, present message to the user
self.message.text = "Sign In failed. The email address and password combination were not recognised."
// Remove the activity indicator
self.activityIndicator.hidden = true
self.activityIndicator.stopAnimating()
}
}
}
// Main viewDidLoad method
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.hidden = true
activityIndicator.hidesWhenStopped = true
}
// Sign the current user OUT of the app
func processSignOut() {
// // Sign out
PFUser.logOut()
// Display sign in / up view controller
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpInViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
// Sign UP method that is called when once a user has accepted the terms and conditions
func processSignUp() {
var userEmailAddress = emailAddress.text
var userPassword = password.text
// Ensure username is lowercase
userEmailAddress = userEmailAddress.lowercaseString
// Add email address validation
// Start activity indicator
activityIndicator.hidden = false
activityIndicator.startAnimating()
// Create the user
var user = PFUser()
user.username = userEmailAddress
user.password = userPassword
user.email = userEmailAddress
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if error == nil {
// User needs to verify email address before continuing
let alertController = UIAlertController(title: "Email address verification",
message: "We have sent you an email that contains a link - you must click this link before you can continue.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "OKAY",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignOut()})
)
// Display alert
self.presentViewController(alertController, animated: true, completion: nil)
} else {
self.activityIndicator.stopAnimating()
if let message: AnyObject = error!.userInfo!["error"] {
self.message.text = "\(message)"
}
}
}
}
}
| mit |
muenzpraeger/salesforce-einstein-vision-swift | SalesforceEinsteinVision/Classes/http/parts/MultiPartPrediction.swift | 1 | 1677 | //
// MultiPartPrediction.swift
// Pods
//
// Created by René Winkelmeyer on 02/28/2017.
//
//
import Alamofire
import Foundation
public enum SourceType {
case file
case base64
case url
}
public struct MultiPartPrediction : MultiPart {
private var _modelId:String?
private var _data:String?
private var _sampleId:String?
private var _sourceType:SourceType?
public init() {}
public mutating func build(modelId: String, data: String, sampleId: String?, type: SourceType) {
_modelId = modelId
_data = data
if let sampleId = sampleId, !sampleId.isEmpty {
_sampleId = sampleId
}
_sourceType = type
}
public func form(multipart: MultipartFormData) {
let modelId = _modelId?.data(using: String.Encoding.utf8)
multipart.append(modelId!, withName: "modelId")
if let id = _sampleId, !id.isEmpty {
let sampleId = id.data(using: String.Encoding.utf8)!
multipart.append(sampleId, withName: "sampleId")
}
switch(_sourceType!) {
case .base64:
let dataPrediction = _data?.data(using: String.Encoding.utf8)
multipart.append(dataPrediction!, withName: "sampleBase64Content")
break
case .file:
let url = URL(string: _data!)
multipart.append(url!, withName: "sampleContent")
break
case .url:
let dataPrediction = _data?.data(using: String.Encoding.utf8)
multipart.append(dataPrediction!, withName: "sampleLocation")
}
}
}
| apache-2.0 |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/DataAccess/QuestRenditionDA.swift | 1 | 3959 | //
// QuestRenditionDA.swift
// AwesomeCore
//
// Created by Antonio on 12/19/17.
//
//import Foundation
//
//class QuestRenditionDA {
//
// // MARK: - Parser
//
// public func parseToCoreData(_ questRendition: QuestRendition, completion: @escaping (CDAssetRendition) -> Void) {
// AwesomeCoreDataAccess.shared.backgroundContext.perform {
// let cdRendition = self.parseToCoreData(questRendition)
// completion(cdRendition)
// }
// }
//
// private func parseToCoreData(_ questRendition: QuestRendition) -> CDAssetRendition {
//
// guard let renditionId = questRendition.id else {
// fatalError("CDAssetRendition object can't be created without id.")
// }
// let p = predicate(renditionId, questRendition.assetId ?? "")
// let cdRendition = CDAssetRendition.getObjectAC(predicate: p, createIfNil: true) as! CDAssetRendition
//
// cdRendition.contentType = questRendition.contentType
// cdRendition.duration = questRendition.duration ?? 0
// cdRendition.edgeUrl = questRendition.edgeUrl
// cdRendition.filesize = Int64(questRendition.filesize ?? 0)
// cdRendition.id = questRendition.id
// cdRendition.name = questRendition.name
// cdRendition.overmindId = questRendition.overmindId
// cdRendition.secure = questRendition.secure ?? false
// cdRendition.status = questRendition.status
// cdRendition.thumbnailUrl = questRendition.thumbnailUrl
// cdRendition.url = questRendition.url
// return cdRendition
// }
//
// func parseFromCoreData(_ cdAssetRendition: CDAssetRendition) -> QuestRendition {
// return QuestRendition(
// contentType: cdAssetRendition.contentType,
// duration: cdAssetRendition.duration,
// edgeUrl: cdAssetRendition.edgeUrl,
// filesize: Int(cdAssetRendition.filesize),
// id: cdAssetRendition.id,
// name: cdAssetRendition.name,
// overmindId: cdAssetRendition.overmindId,
// secure: cdAssetRendition.secure,
// status: cdAssetRendition.status,
// thumbnailUrl: cdAssetRendition.thumbnailUrl,
// url: cdAssetRendition.url,
// assetId: cdAssetRendition.asset?.id
// )
// }
//
// // MARK: - Fetch
//
// func loadBy(renditionId: String, assetId: String, completion: @escaping (CDAssetRendition?) -> Void) {
// func perform() {
// let p = predicate(renditionId, assetId)
// guard let cdMarker = CDAssetRendition.listAC(predicate: p).first as? CDAssetRendition else {
// completion(nil)
// return
// }
// completion(cdMarker)
// }
// AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in
// perform()
// })
// }
//
// // MARK: - Helpers
//
// func extractQuestRenditions(_ questRenditions: [QuestRendition]?) -> NSSet {
// var renditions = NSSet()
// guard let questRenditions = questRenditions else {
// return renditions
// }
// for qr in questRenditions {
// renditions = renditions.adding(parseToCoreData(qr)) as NSSet
// }
// return renditions
// }
//
// func extractCDAssetRendition(_ questRenditions: NSSet?) -> [QuestRendition]? {
// guard let questRenditions = questRenditions else {
// return nil
// }
// var renditions = [QuestRendition]()
// for qr in questRenditions {
// renditions.append(parseFromCoreData(qr as! CDAssetRendition))
// }
// return renditions
// }
//
// private func predicate(_ markerId: String, _ assetId: String) -> NSPredicate {
// return NSPredicate(format: "id == %@ AND asset.id == %@", markerId, assetId)
// }
//}
| mit |
the-grid/Portal | Portal/Networking/Resources/Item/GetItems.swift | 1 | 451 | import struct Alamofire.Response
import Result
private let url = baseUrl + "/item"
extension APIClient {
/// Get all items for the current user.
public func getItems(completionHandler: Result<[Item], NSError> -> Void) {
manager
.request(.GET, url, token: token)
.responseDecodable { (response: Response<[Item], NSError>) in
completionHandler(response.result.proxy.value)
}
}
}
| mit |
louchu0604/algorithm-swift | TestAPP/TestAPP/ViewController.swift | 1 | 917 | //
// ViewController.swift
// TestAPP
//
// Created by louchu on 2017/8/24.
// Copyright © 2017年 Cy Lou. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func testqueue(object:Int) -> Int {
let queue = Queue.init()
queue.push(object)
// queue.push(object: object)
return 0
}
func teststack(object:Int) -> Int {
return 0
}
func teststackbyqueue(object:Int) -> Int {
return 0
}
func testlist(object:Int)->Int
{
let list = LinkedList.init()
list.insertToindex(0, val: 1)
return list.getSize()
}
}
| mit |
zmian/xcore.swift | Sources/Xcore/SwiftUI/Components/Popup/View+Popup.swift | 1 | 9043 | //
// Xcore
// Copyright © 2021 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
// MARK: - View Extension
extension View {
/// Presents a popup when a binding to a Boolean value that you provide is
/// `true`.
///
/// Use this method when you want to present a popup view to the user when a
/// Boolean value you provide is `true`. The example below displays a popup view
/// of the mockup for a software license agreement when the user toggles the
/// `isShowingPopup` variable by clicking or tapping on the "Show License
/// Agreement" button:
///
/// ```swift
/// struct ShowLicenseAgreement: View {
/// @State private var isShowingPopup = false
///
/// var body: some View {
/// Button {
/// isShowingPopup.toggle()
/// } label: {
/// Text("Show License Agreement")
/// }
/// .popup(isPresented: $isShowingPopup) {
/// VStack {
/// Text("License Agreement")
/// Text("Terms and conditions go here.")
/// Button("Dismiss") {
/// isShowingPopup.toggle()
/// }
/// }
/// }
/// }
/// }
/// ```
///
/// - Parameters:
/// - isPresented: A binding to a Boolean value that determines whether to
/// present the popup that you create in the modifier's `content` closure.
/// - style: The style of the popup.
/// - dismissMethods: An option set specifying the dismissal methods for the
/// popup.
/// - content: A closure returning the content of the popup.
public func popup<Content>(
isPresented: Binding<Bool>,
style: Popup.Style = .alert,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder content: @escaping () -> Content
) -> some View where Content: View {
modifier(PopupViewModifier(
isPresented: isPresented,
style: style,
dismissMethods: dismissMethods,
content: content
))
}
/// Presents a popup using the given item as a data source for the popup's
/// content.
///
/// Use this method when you need to present a popup view with content from a
/// custom data source. The example below shows a custom data source
/// `InventoryItem` that the `content` closure uses to populate the display the
/// action popup shows to the user:
///
/// ```swift
/// struct ShowPartDetail: View {
/// @State var popupDetail: InventoryItem?
///
/// var body: some View {
/// Button("Show Part Details") {
/// popupDetail = InventoryItem(
/// id: "0123456789",
/// partNumber: "Z-1234A",
/// quantity: 100,
/// name: "Widget"
/// )
/// }
/// .popup(item: $popupDetail) { detail in
/// VStack(alignment: .leading, spacing: 20) {
/// Text("Part Number: \(detail.partNumber)")
/// Text("Name: \(detail.name)")
/// Text("Quantity On-Hand: \(detail.quantity)")
/// }
/// .onTapGesture {
/// popupDetail = nil
/// }
/// }
/// }
/// }
///
/// struct InventoryItem: Identifiable {
/// var id: String
/// let partNumber: String
/// let quantity: Int
/// let name: String
/// }
/// ```
///
/// - Parameters:
/// - item: A binding to an optional source of truth for the popup. When
/// `item` is non-`nil`, the system passes the item's content to the
/// modifier's closure. You display this content in a popup that you create
/// that the system displays to the user. If `item` changes, the system
/// dismisses the popup and replaces it with a new one using the same
/// process.
/// - style: The style of the popup.
/// - dismissMethods: An option set specifying the dismissal methods for the
/// popup.
/// - content: A closure returning the content of the popup.
public func popup<Item, Content>(
item: Binding<Item?>,
style: Popup.Style = .alert,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder content: @escaping (Item) -> Content
) -> some View where Content: View {
modifier(PopupViewModifier(
isPresented: .init {
item.wrappedValue != nil
} set: { isPresented in
if !isPresented {
item.wrappedValue = nil
}
},
style: style,
dismissMethods: dismissMethods,
content: {
if let item = item.wrappedValue {
content(item)
}
}
))
}
public func popup<F>(
_ title: Text,
message: Text?,
isPresented: Binding<Bool>,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder footer: @escaping () -> F
) -> some View where F: View {
popup(
isPresented: isPresented,
style: .alert,
dismissMethods: dismissMethods,
content: {
StandardPopupAlert(title, message: message, footer: footer)
}
)
}
public func popup<F, S1, S2>(
_ title: S1,
message: S2?,
isPresented: Binding<Bool>,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder footer: @escaping () -> F
) -> some View where F: View, S1: StringProtocol, S2: StringProtocol {
popup(
Text(title),
message: message.map { Text($0) },
isPresented: isPresented,
dismissMethods: dismissMethods,
footer: footer
)
}
}
// MARK: - View Modifier
private struct PopupViewModifier<PopupContent>: ViewModifier where PopupContent: View {
init(
isPresented: Binding<Bool>,
style: Popup.Style,
dismissMethods: Popup.DismissMethods,
@ViewBuilder content: @escaping () -> PopupContent
) {
self._isPresented = isPresented
self.style = style
self.dismissMethods = dismissMethods
self.content = content
}
@State private var workItem: DispatchWorkItem?
/// A Boolean value that indicates whether the popup associated with this
/// environment is currently being presented.
@Binding private var isPresented: Bool
/// A property indicating the popup style.
private let style: Popup.Style
/// A closure containing the content of popup.
private let content: () -> PopupContent
/// A property indicating all of the ways popup can be dismissed.
private let dismissMethods: Popup.DismissMethods
func body(content: Content) -> some View {
content
.window(isPresented: $isPresented, style: style.windowStyle) {
popupContent
}
.onChange(of: isPresented) { isPresented in
if isPresented {
setupAutomaticDismissalIfNeeded()
}
}
}
private var popupContent: some View {
ZStack {
if isPresented {
if style.allowDimming {
// Host Content Dim Overlay
Color(white: 0, opacity: 0.20)
.frame(max: .infinity)
.ignoresSafeArea()
.onTapGestureIf(dismissMethods.contains(.tapOutside)) {
isPresented = false
}
.zIndex(1)
.transition(.opacity)
}
content()
.frame(max: .infinity, alignment: style.alignment)
.ignoresSafeArea(edges: style.ignoresSafeAreaEdges)
.onTapGestureIf(dismissMethods.contains(.tapInside)) {
isPresented = false
}
.zIndex(2)
.transition(style.transition)
}
}
.animation(style.animation, value: isPresented)
.popupDismissAction(
dismissMethods.contains(.xmark) ? PopupDismissAction { isPresented = false } : nil
)
}
private func setupAutomaticDismissalIfNeeded() {
guard let duration = style.dismissAfter else {
return
}
workItem?.cancel()
workItem = DispatchWorkItem {
isPresented = false
}
if isPresented, let work = workItem {
DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: work)
}
}
}
| mit |
SeriousChoice/SCSwift | Example/Pods/Cache/Source/Shared/Storage/SyncStorage.swift | 1 | 1528 | import Foundation
import Dispatch
/// Manipulate storage in a "all sync" manner.
/// Block the current queue until the operation completes.
public class SyncStorage<Key: Hashable, Value> {
public let innerStorage: HybridStorage<Key, Value>
public let serialQueue: DispatchQueue
public init(storage: HybridStorage<Key, Value>, serialQueue: DispatchQueue) {
self.innerStorage = storage
self.serialQueue = serialQueue
}
}
extension SyncStorage: StorageAware {
public func entry(forKey key: Key) throws -> Entry<Value> {
var entry: Entry<Value>!
try serialQueue.sync {
entry = try innerStorage.entry(forKey: key)
}
return entry
}
public func removeObject(forKey key: Key) throws {
try serialQueue.sync {
try self.innerStorage.removeObject(forKey: key)
}
}
public func setObject(_ object: Value, forKey key: Key, expiry: Expiry? = nil) throws {
try serialQueue.sync {
try innerStorage.setObject(object, forKey: key, expiry: expiry)
}
}
public func removeAll() throws {
try serialQueue.sync {
try innerStorage.removeAll()
}
}
public func removeExpiredObjects() throws {
try serialQueue.sync {
try innerStorage.removeExpiredObjects()
}
}
}
public extension SyncStorage {
func transform<U>(transformer: Transformer<U>) -> SyncStorage<Key, U> {
let storage = SyncStorage<Key, U>(
storage: innerStorage.transform(transformer: transformer),
serialQueue: serialQueue
)
return storage
}
}
| mit |
maxoly/PulsarKit | PulsarKitExample/PulsarKitExample/Models/Header.swift | 1 | 215 | //
// Header.swift
// PulsarKitExample
//
// Created by Massimo Oliviero on 28/02/2019.
// Copyright © 2019 Nacoon. All rights reserved.
//
import Foundation
struct Header: Hashable {
let title: String
}
| mit |
cscalcucci/Swift_Life | Swift_LifeTests/Swift_LifeTests.swift | 1 | 1006 | //
// Swift_LifeTests.swift
// Swift_LifeTests
//
// Created by Christopher Scalcucci on 2/11/16.
// Copyright © 2016 Christopher Scalcucci. All rights reserved.
//
import XCTest
@testable import Swift_Life
class Swift_LifeTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
YuAo/WAKeyValuePersistenceStore | WAKeyValuePersistenceStoreDemo/WAKeyValuePersistenceStoreDemo/ViewController.swift | 1 | 1021 | //
// ViewController.swift
// WAKeyValuePersistenceStoreDemo
//
// Created by YuAo on 5/22/15.
// Copyright (c) 2015 YuAo. All rights reserved.
//
import UIKit
import WAKeyValuePersistenceStore
private let ViewControllerTextCacheKey = "ViewControllerTextCacheKey"
class ViewController: UIViewController {
private let cacheStore = WAKeyValuePersistenceStore(directory: NSSearchPathDirectory.CachesDirectory, name: "CacheStore", objectSerializer: WAPersistenceObjectSerializer.keyedArchiveSerializer())
@IBOutlet private weak var textField: UITextField!
@IBOutlet private weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.text = self.cacheStore[ViewControllerTextCacheKey] as? String
}
@IBAction private func textFieldChanged(sender: UITextField) {
self.cacheStore[ViewControllerTextCacheKey] = sender.text
self.label.text = "Saved! See WAKeyValuePersistenceStoreDemoTests for more usage."
}
}
| mit |
64characters/Telephone | UseCases/CallHistoryFactory.swift | 2 | 638 | //
// CallHistoryFactory.swift
// Telephone
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
public protocol CallHistoryFactory {
func make(uuid: String) -> CallHistory
}
| gpl-3.0 |
J4awesome/vaporChatServer | Package.swift | 1 | 330 | import PackageDescription
let package = Package(
name: "ChatServer",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 3)
],
exclude: [
"Config",
"Database",
"Localization",
"Public",
"Resources",
"Tests",
]
)
| mit |
WebAPIKit/WebAPIKit | Package.swift | 1 | 74 | import PackageDescription
let package = Package(
name: "WebAPIKit"
)
| mit |
matsprea/omim | iphone/Maps/UI/Downloader/DownloadMapsViewController.swift | 1 | 18868 | @objc(MWMDownloadMapsViewController)
class DownloadMapsViewController: MWMViewController {
// MARK: - Types
private enum NodeAction {
case showOnMap
case download
case update
case cancelDownload
case retryDownload
case delete
}
private enum AllMapsButtonState {
case none
case download(String)
case cancel(String)
}
// MARK: - Outlets
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var statusBarBackground: UIView!
@IBOutlet var noMapsContainer: UIView!
@IBOutlet var searchBarTopOffset: NSLayoutConstraint!
@IBOutlet var downloadAllViewContainer: UIView!
// MARK: - Properties
var dataSource: IDownloaderDataSource!
@objc var mode: MWMMapDownloaderMode = .downloaded
private var skipCountryEvent = false
private var hasAddMapSection: Bool { dataSource.isRoot && mode == .downloaded }
private let allMapsViewBottomOffsetConstant: CGFloat = 64
lazy var noSerchResultViewController: SearchNoResultsViewController = {
let vc = storyboard!.instantiateViewController(ofType: SearchNoResultsViewController.self)
view.insertSubview(vc.view, belowSubview: statusBarBackground)
vc.view.alignToSuperview()
vc.view.isHidden = true
addChild(vc)
vc.didMove(toParent: self)
return vc
}()
lazy var downloadAllView: DownloadAllView = {
let view = Bundle.main.load(viewClass: DownloadAllView.self)?.first as! DownloadAllView
view.delegate = self
downloadAllViewContainer.addSubview(view)
view.alignToSuperview()
return view
}()
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
if dataSource == nil {
switch mode {
case .downloaded:
dataSource = DownloadedMapsDataSource()
case .available:
dataSource = AvailableMapsDataSource(location: MWMLocationManager.lastLocation()?.coordinate)
@unknown default:
fatalError()
}
}
tableView.registerNib(cell: MWMMapDownloaderTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderPlaceTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderLargeCountryTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderSubplaceTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderButtonTableViewCell.self)
title = dataSource.title
if mode == .downloaded {
let addMapsButton = button(with: UIImage(named: "ic_nav_bar_add"), action: #selector(onAddMaps))
navigationItem.rightBarButtonItem = addMapsButton
}
Storage.shared().add(self)
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
if !dataSource.isRoot {
searchBarTopOffset.constant = -searchBar.frame.height
} else {
searchBar.placeholder = L("downloader_search_field_hint")
}
configButtons()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configButtons()
}
fileprivate func showChildren(_ nodeAttrs: MapNodeAttributes) {
let vc = storyboard!.instantiateViewController(ofType: DownloadMapsViewController.self)
vc.mode = mode
vc.dataSource = dataSource.dataSourceFor(nodeAttrs.countryId)
navigationController?.pushViewController(vc, animated: true)
}
fileprivate func showActions(_ nodeAttrs: MapNodeAttributes, in cell: UITableViewCell) {
let menuTitle = nodeAttrs.nodeName
let multiparent = nodeAttrs.parentInfo.count > 1
let message = dataSource.isRoot || multiparent ? nil : nodeAttrs.parentInfo.first?.countryName
let actionSheet = UIAlertController(title: menuTitle, message: message, preferredStyle: .actionSheet)
actionSheet.popoverPresentationController?.sourceView = cell
actionSheet.popoverPresentationController?.sourceRect = cell.bounds
let actions: [NodeAction]
switch nodeAttrs.nodeStatus {
case .undefined:
actions = []
case .downloading, .applying, .inQueue:
actions = [.cancelDownload]
case .error:
actions = nodeAttrs.downloadedMwmCount > 0 ? [.retryDownload, .delete] : [.retryDownload]
case .onDiskOutOfDate:
actions = [.showOnMap, .update, .delete]
case .onDisk:
actions = [.showOnMap, .delete]
case .notDownloaded:
actions = [.download]
case .partly:
actions = [.download, .delete]
@unknown default:
fatalError()
}
addActions(actions, for: nodeAttrs, to: actionSheet)
actionSheet.addAction(UIAlertAction(title: L("cancel"), style: .cancel))
present(actionSheet, animated: true)
}
private func addActions(_ actions: [NodeAction], for nodeAttrs: MapNodeAttributes, to actionSheet: UIAlertController) {
actions.forEach { [unowned self] in
let action: UIAlertAction
switch $0 {
case .showOnMap:
action = UIAlertAction(title: L("zoom_to_country"), style: .default, handler: { _ in
Storage.shared().showNode(nodeAttrs.countryId)
self.navigationController?.popToRootViewController(animated: true)
})
case .download:
let prefix = nodeAttrs.totalMwmCount == 1 ? L("downloader_download_map") : L("downloader_download_all_button")
action = UIAlertAction(title: "\(prefix) (\(formattedSize(nodeAttrs.totalSize)))",
style: .default,
handler: { _ in
Storage.shared().downloadNode(nodeAttrs.countryId)
})
case .update:
let size = formattedSize(nodeAttrs.totalUpdateSizeBytes)
let title = "\(L("downloader_status_outdated")) \(size)"
action = UIAlertAction(title: title, style: .default, handler: { _ in
Storage.shared().updateNode(nodeAttrs.countryId)
})
case .cancelDownload:
action = UIAlertAction(title: L("cancel_download"), style: .destructive, handler: { _ in
Storage.shared().cancelDownloadNode(nodeAttrs.countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
})
case .retryDownload:
action = UIAlertAction(title: L("downloader_retry"), style: .destructive, handler: { _ in
Storage.shared().retryDownloadNode(nodeAttrs.countryId)
})
case .delete:
action = UIAlertAction(title: L("downloader_delete_map"), style: .destructive, handler: { _ in
Storage.shared().deleteNode(nodeAttrs.countryId)
})
}
actionSheet.addAction(action)
}
}
fileprivate func reloadData() {
tableView.reloadData()
configButtons()
}
fileprivate func configButtons() {
downloadAllView.state = .none
downloadAllView.isSizeHidden = false
let parentAttributes = dataSource.parentAttributes()
let error = parentAttributes.nodeStatus == .error || parentAttributes.nodeStatus == .undefined
let downloading = parentAttributes.nodeStatus == .downloading || parentAttributes.nodeStatus == .inQueue || parentAttributes.nodeStatus == .applying
switch mode {
case .available:
if dataSource.isRoot {
break
}
if error {
downloadAllView.state = .error
} else if downloading {
downloadAllView.state = .dowloading
} else if parentAttributes.downloadedMwmCount < parentAttributes.totalMwmCount {
downloadAllView.state = .ready
downloadAllView.style = .download
downloadAllView.downloadSize = parentAttributes.totalSize - parentAttributes.downloadedSize
}
case .downloaded:
let isUpdate = parentAttributes.totalUpdateSizeBytes > 0
let size = isUpdate ? parentAttributes.totalUpdateSizeBytes : parentAttributes.downloadingSize
if error {
downloadAllView.state = dataSource.isRoot ? .none : .error
downloadAllView.downloadSize = parentAttributes.downloadingSize
} else if downloading && dataSource is DownloadedMapsDataSource {
downloadAllView.state = .dowloading
if dataSource.isRoot {
downloadAllView.style = .download
downloadAllView.isSizeHidden = true
}
} else if isUpdate {
downloadAllView.state = .ready
downloadAllView.style = .update
downloadAllView.downloadSize = size
}
@unknown default:
fatalError()
}
}
@objc func onAddMaps() {
let vc = storyboard!.instantiateViewController(ofType: DownloadMapsViewController.self)
if !dataSource.isRoot {
vc.dataSource = AvailableMapsDataSource(dataSource.parentAttributes().countryId)
}
vc.mode = .available
navigationController?.pushViewController(vc, animated: true)
}
}
// MARK: - UITableViewDataSource
extension DownloadMapsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
dataSource.numberOfSections() + (hasAddMapSection ? 1 : 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hasAddMapSection && section == dataSource.numberOfSections() {
return 1
}
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if hasAddMapSection && indexPath.section == dataSource.numberOfSections() {
let cellType = MWMMapDownloaderButtonTableViewCell.self
let buttonCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
return buttonCell
}
let nodeAttrs = dataSource.item(at: indexPath)
let cell: MWMMapDownloaderTableViewCell
if nodeAttrs.hasChildren {
let cellType = MWMMapDownloaderLargeCountryTableViewCell.self
let largeCountryCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = largeCountryCell
} else if let matchedName = dataSource.matchedName(at: indexPath), matchedName != nodeAttrs.nodeName {
let cellType = MWMMapDownloaderSubplaceTableViewCell.self
let subplaceCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
subplaceCell.setSubplaceText(matchedName)
cell = subplaceCell
} else if !nodeAttrs.hasParent {
let cellType = MWMMapDownloaderTableViewCell.self
let downloaderCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = downloaderCell
} else {
let cellType = MWMMapDownloaderPlaceTableViewCell.self
let placeCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = placeCell
}
cell.mode = dataSource.isSearching ? .available : mode
cell.config(nodeAttrs, searchQuery: searchBar.text)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
dataSource.title(for: section)
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
dataSource.indexTitles()
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
index
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == dataSource.numberOfSections() {
return false
}
let nodeAttrs = dataSource.item(at: indexPath)
switch nodeAttrs.nodeStatus {
case .onDisk, .onDiskOutOfDate, .partly:
return true
default:
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let nodeAttrs = dataSource.item(at: indexPath)
Storage.shared().deleteNode(nodeAttrs.countryId)
}
}
}
// MARK: - UITableViewDelegate
extension DownloadMapsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = MWMMapDownloaderCellHeader()
if section != dataSource.numberOfSections() {
headerView.text = dataSource.title(for: section)
}
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
28
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
section == dataSource.numberOfSections() - 1 ? 68 : 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == dataSource.numberOfSections() {
onAddMaps()
return
}
let nodeAttrs = dataSource.item(at: indexPath)
if nodeAttrs.hasChildren {
showChildren(dataSource.item(at: indexPath))
return
}
showActions(nodeAttrs, in: tableView.cellForRow(at: indexPath)!)
}
}
// MARK: - UIScrollViewDelegate
extension DownloadMapsViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
}
// MARK: - MWMMapDownloaderTableViewCellDelegate
extension DownloadMapsViewController: MWMMapDownloaderTableViewCellDelegate {
func mapDownloaderCellDidPressProgress(_ cell: MWMMapDownloaderTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let nodeAttrs = dataSource.item(at: indexPath)
switch nodeAttrs.nodeStatus {
case .undefined, .error:
Storage.shared().retryDownloadNode(nodeAttrs.countryId)
case .downloading, .applying, .inQueue:
Storage.shared().cancelDownloadNode(nodeAttrs.countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
case .onDiskOutOfDate:
Storage.shared().updateNode(nodeAttrs.countryId)
case .onDisk:
// do nothing
break
case .notDownloaded, .partly:
if nodeAttrs.hasChildren {
showChildren(nodeAttrs)
} else {
Storage.shared().downloadNode(nodeAttrs.countryId)
}
@unknown default:
fatalError()
}
}
func mapDownloaderCellDidLongPress(_ cell: MWMMapDownloaderTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let nodeAttrs = dataSource.item(at: indexPath)
showActions(nodeAttrs, in: cell)
}
}
// MARK: - StorageObserver
extension DownloadMapsViewController: StorageObserver {
func processCountryEvent(_ countryId: String) {
if skipCountryEvent && countryId == dataSource.parentAttributes().countryId {
return
}
dataSource.reload {
reloadData()
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
}
if countryId == dataSource.parentAttributes().countryId {
configButtons()
}
for cell in tableView.visibleCells {
guard let downloaderCell = cell as? MWMMapDownloaderTableViewCell else { continue }
if downloaderCell.nodeAttrs.countryId != countryId { continue }
guard let indexPath = tableView.indexPath(for: downloaderCell) else { return }
downloaderCell.config(dataSource.item(at: indexPath), searchQuery: searchBar.text)
}
}
func processCountry(_ countryId: String, downloadedBytes: UInt64, totalBytes: UInt64) {
for cell in tableView.visibleCells {
guard let downloaderCell = cell as? MWMMapDownloaderTableViewCell else { continue }
if downloaderCell.nodeAttrs.countryId != countryId { continue }
downloaderCell.setDownloadProgress(CGFloat(downloadedBytes) / CGFloat(totalBytes))
}
let parentAttributes = dataSource.parentAttributes()
if countryId == parentAttributes.countryId {
downloadAllView.downloadProgress = CGFloat(downloadedBytes) / CGFloat(totalBytes)
downloadAllView.downloadSize = totalBytes
} else if dataSource.isRoot && dataSource is DownloadedMapsDataSource {
downloadAllView.state = .dowloading
downloadAllView.isSizeHidden = true
}
}
}
// MARK: - UISearchBarDelegate
extension DownloadMapsViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
navigationController?.setNavigationBarHidden(true, animated: true)
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(false, animated: true)
navigationController?.setNavigationBarHidden(false, animated: true)
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.resignFirstResponder()
dataSource.cancelSearch()
reloadData()
noSerchResultViewController.view.isHidden = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let locale = searchBar.textInputMode?.primaryLanguage
dataSource.search(searchText, locale: locale ?? "") { [weak self] finished in
guard let self = self else { return }
self.reloadData()
self.noSerchResultViewController.view.isHidden = !self.dataSource.isEmpty
}
}
}
// MARK: - UIBarPositioningDelegate
extension DownloadMapsViewController: UIBarPositioningDelegate {
func position(for bar: UIBarPositioning) -> UIBarPosition {
.topAttached
}
}
// MARK: - DownloadAllViewDelegate
extension DownloadMapsViewController: DownloadAllViewDelegate {
func onStateChanged(state: DownloadAllView.State) {
if state == .none {
downloadAllViewContainer.isHidden = true
tableView.contentInset = UIEdgeInsets.zero
} else {
downloadAllViewContainer.isHidden = false
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: allMapsViewBottomOffsetConstant, right: 0)
}
}
func onDownloadButtonPressed() {
skipCountryEvent = true
if mode == .downloaded {
Storage.shared().updateNode(dataSource.parentAttributes().countryId)
} else {
Storage.shared().downloadNode(dataSource.parentAttributes().countryId)
}
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
}
func onRetryButtonPressed() {
skipCountryEvent = true
Storage.shared().retryDownloadNode(dataSource.parentAttributes().countryId)
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
}
func onCancelButtonPressed() {
skipCountryEvent = true
Storage.shared().cancelDownloadNode(dataSource.parentAttributes().countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
reloadData()
}
}
| apache-2.0 |
Unipagos/UnipagosIntegrationIOSSwift | UnipagosIntegrationTestTests/UnipagosIntegrationTestTests.swift | 1 | 947 | //
// UnipagosIntegrationTestTests.swift
// UnipagosIntegrationTestTests
//
// Created by Leonardo Cid on 22/09/14.
// Copyright (c) 2014 Unipagos. All rights reserved.
//
import UIKit
import XCTest
class UnipagosIntegrationTestTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
TeamGlobalApps/peace-corps-iOS | PeaceCorps Openings/PeaceCorps Openings/ListTableController.swift | 2 | 6775 | //
// ListTableController.swift
// PeaceCorps Openings
//
// Created by Patrick Crawford on 5/13/15.
// Copyright (c) 2015 GAI. All rights reserved.
//
import UIKit
let single = Singleton()
//class ListTable: UIViewController, UITableViewDelegate, UITableViewDataSource {
class ListTableController: UITableViewController {
// getting data from segue
var urlString:String!
var showingOnlyFavorites:Bool!
// at first, cap the number of responses to return for faster viewing
var loadLimited = false
var temp: Job!
var tempIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
if self.showingOnlyFavorites == false{
loadLimited=true
// show a "load all button", only when pulling from website / when something has loaded
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refreshButton")
// this actually grabs the results! And can be SLOW (hence initially limiting to 25)
single.filter(self.urlString, limitload: loadLimited)
}
else{
single.showFavorites()
}
//println("it's loaded...kinda b")
}
// pressing the icon to refresh all
func refreshButton() {
loadLimited = false
single.filter(self.urlString, limitload: loadLimited)
self.tableView.reloadData()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refreshButton")
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//let shared = single.numOfElements()
if self.showingOnlyFavorites == false{
if single.numOfElements()==0{
self.title = "No results found"
}
else if (single.numOfElements()==25 && loadLimited){
self.title = "25+ openings"
if self.showingOnlyFavorites == false{
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Load All", style: UIBarButtonItemStyle.Plain, target: self, action: "refreshButton")
}
}
else if single.numOfElements()==1{
self.title = "Found \(single.numOfElements()) opening"
}
// else if single.numOfElements()==99{
// self.title = "Found \(single.numOfElements())+ openings"
// }
else{
self.title = "Found \(single.numOfElements()) openings"
}
if Reachability.isConnectedToNetwork()==false{
self.title="No connection"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refreshButton")
}
}
else{
self.title = "Stored Favorites"
}
return single.numOfElements()
}
override func viewWillAppear(animated: Bool) {
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: tempIndex, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// set the type of cell based on the storyboard cell prototype and associated class
let cell:resultsCellView = tableView.dequeueReusableCellWithIdentifier("ResultsCell", forIndexPath: indexPath) as! resultsCellView
if single.numOfElements()==0{
cell.titleLabel!.text = "No results found"
return cell
}
temp = single.getJobFromIndex(indexPath.row) //jobArray[indexPath.row]
//
// HERE we should take the information for the ith back end element of the list (i=indexPath.row)
// and set the following elements to show this.
//
// set fields from passed in data
cell.titleLabel!.text = temp.title
cell.sectorLabel!.text = temp.sector
cell.countryRegionLabel!.text = (temp.country+", "+temp.region).capitalizedString
cell.departByLabel!.text = "Departs: "+temp.staging_start_date
cell.index = indexPath.row
if temp.favorited{
cell.favButton.setImage(UIImage(named:"Star-Favorites"), forState: .Normal)
}
else{
cell.favButton.setImage(UIImage(named:"star_none"), forState: .Normal)
}
cell.backgroundColor = UIColor(red:225/256, green:223/256,blue:198/256,alpha:1)
// temporary test variable, should read from the passed in data
// also set the favorites button state.
// arrays for checking and setting which image to use
let sectormatcharray = ["Agriculture","Community","Education","Environment","Health","Youth","Youth in Development","Community Economic Development"]
let sectorimgsarray = ["sectoragriculture.jpg","sectorcommunity.jpg","sectoreducation.jpg","sectorenvironment.jpg","sectorhealth.jpg","sectoryouth.jpg","sectoryouth.jpg","sectorcommunity.jpg"]
// make similar arrays for the region.. then make background of cell colored and the actual
// image be the region
// set the correct sector image icon
for i in 0...(sectormatcharray.count-1){
//println(i)
if temp.sector == sectormatcharray[i]{
cell.imgView.image = UIImage(named:sectorimgsarray[i])
}
}
// default case = no image, if there isn't a match
return cell
}
// run the segue transition on tapping an entry
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tempIndex = indexPath.row // set this so we know how many in the linked list to move through // was before
self.performSegueWithIdentifier("toResult", sender: indexPath);
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "toResult") {
// Assign the variable to the value from the node here
// instead of all this.. just pass the job INDEX in the singleton.
var destinationVC:ResultEntryController = ResultEntryController()
destinationVC = segue.destinationViewController as! ResultEntryController
destinationVC.indexRow = tempIndex
}
}
}
| mit |
bouwman/LayoutResearch | LayoutResearch/Model/Study/StudyService.swift | 1 | 18659 | //
// StudyService.swift
// LayoutResearch
//
// Created by Tassilo Bouwman on 25.07.17.
// Copyright © 2017 Tassilo Bouwman. All rights reserved.
//
import ResearchKit
import GameplayKit
enum OrganisationType {
case random, stable
}
class SearchItem: NSObject, SearchItemProtocol, NSCoding {
var identifier: String
var colorId: Int
var shapeId: Int
var sharedColorCount: Int
init(identifier: String, colorId: Int, shapeId: Int, sharedColorCount: Int) {
self.identifier = identifier
self.colorId = colorId
self.shapeId = shapeId
self.sharedColorCount = sharedColorCount
super.init()
}
override var description: String {
return identifier
}
// MARK: - NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(identifier, forKey: "identifier")
aCoder.encode(colorId, forKey: "colorId")
aCoder.encode(shapeId, forKey: "shapeId")
aCoder.encode(sharedColorCount, forKey: "sharedColorCount")
}
required init?(coder aDecoder: NSCoder) {
identifier = aDecoder.decodeObject(forKey: "identifier") as! String
colorId = aDecoder.decodeInteger(forKey: "colorId")
shapeId = aDecoder.decodeInteger(forKey: "shapeId")
sharedColorCount = aDecoder.decodeInteger(forKey: "sharedColorCount")
super.init()
}
}
class StudyService {
var steps: [ORKStep] = []
var activityNumber: Int
var settings: StudySettings
private var searchItems: [[SearchItemProtocol]] = []
private var targetItems: [SearchItemProtocol] = []
init(settings: StudySettings, activityNumber: Int) {
self.settings = settings
self.activityNumber = activityNumber
// Random shapes
var shapeIDs: [Int] = []
if activityNumber == 0 || settings.group.organisation == .random {
for i in 1...24 {
shapeIDs.append(i)
}
shapeIDs.shuffle()
UserDefaults.standard.set(shapeIDs, forKey: SettingsString.lastUsedShapeIDs.rawValue)
} else {
shapeIDs = UserDefaults.standard.array(forKey: SettingsString.lastUsedShapeIDs.rawValue) as! [Int]
}
// Create base item array
var counter = 1
for row in 0..<settings.rowCount {
var rowItems: [SearchItemProtocol] = []
for column in 0..<settings.columnCount {
let colorId = staticColors[row][column]
let shapeId = shapeIDs[counter-1]
let sharedColorCount = countColorsIn(colorArray: staticColors, colorId: colorId)
let item = SearchItem(identifier: "\(counter)", colorId: colorId, shapeId: shapeId, sharedColorCount: sharedColorCount)
rowItems.append(item)
targetItems.append(item)
// Counters
counter += 1
}
searchItems.append(rowItems)
}
// Create targets
targetItems = settings.group.targetItemsFrom(searchItems: searchItems)
// Shuffle if not using designed layout
if settings.group.isDesignedLayout == false {
if activityNumber == 0 || settings.group.organisation == .random {
searchItems.shuffle()
store(searchItems: searchItems)
} else {
searchItems = loadSearchItems(rowCount: settings.rowCount, columnCount: settings.columnCount)
}
}
// Create intro step
var trialCounter = 0
let layouts = settings.group.layouts
let randomGen = GKShuffledDistribution(lowestValue: 0, highestValue: 2)
let introStep = ORKInstructionStep(identifier: "IntroStep")
introStep.title = "Introduction"
introStep.text = "Please read this carefully.\n\nTry to find an icon as quickly as possible.\n\nAt the start of each trial, you are told which icon you are looking for.\n\nYou start a trial by clicking on the 'Next' button shown under the description. The 'Next' button will appear after 1 second. On pressing the button, the icon image will disappear, and the menu appears.\nTry to locate the item as quickly as possible and click on it.\n\nAs soon as you select the correct item you are taken to the next trial. If you selected the wrong trial, the description of the item will be shown again."
steps.append(introStep)
// Practice steps
// Create practice intro step
let practiceIntroStep = ORKActiveStep(identifier: "PracticeIntroStep")
practiceIntroStep.title = "Practice"
practiceIntroStep.text = "Use the next few trials to become familiar with the search task. Press next to begin."
steps.append(practiceIntroStep)
// Create practice steps
let practiceTargets = settings.group.practiceTargetItemsFrom(searchItems: searchItems)
for i in 0..<settings.practiceTrialCount {
addTrialStepsFor(index: trialCounter, layout: layouts.first!, target: practiceTargets[i], targetDescriptionPosition: randomGen.nextInt(), isPractice: true)
trialCounter += 1
}
// Create experiment start step
let normalIntroStep = ORKActiveStep(identifier: "NormalIntroStep")
normalIntroStep.title = "Start of Experiment"
normalIntroStep.text = "You have completed the practice trials. Press next to begin the experiment."
steps.append(normalIntroStep)
// Create normal steps
for (i, layout) in layouts.enumerated() {
// Not add layout intro after intro
if i != 0 {
// Take a break
// let waitStep = ORKCountdownStep(identifier: "CountdownStep\(layouts.count + i)")
// waitStep.title = "Break"
// waitStep.text = "Take a short break before you continue."
// waitStep.stepDuration = 15
// waitStep.shouldStartTimerAutomatically = true
// waitStep.shouldShowDefaultTimer = true
// steps.append(waitStep)
// Introduce new layout
let itemDistance = itemDistanceWithEqualWhiteSpaceFor(layout: layout, itemDiameter: settings.itemDiameter, itemDistance: settings.group.itemDistance)
let newLayoutStep = LayoutIntroStep(identifier: "NewLayoutStep\(layouts.count + i)", layout: layout, itemDiameter: settings.itemDiameter, itemDistance: itemDistance)
newLayoutStep.title = "New Layout"
newLayoutStep.text = "The next layout will be different but the task is the same: Locate the target as quickly as possible."
steps.append(newLayoutStep)
}
// Create steps for every target
for i in 0..<targetItems.count {
addTrialStepsFor(index: trialCounter, layout: layout, target: targetItems[i], targetDescriptionPosition: randomGen.nextInt(), isPractice: false)
trialCounter += 1
}
}
// Add thank you step
let completionStep = ORKCompletionStep(identifier: "CompletionStep")
completionStep.title = "Thank you!"
completionStep.text = "Thank you for completing the task."
steps.append(completionStep)
}
private func addTrialStepsFor(index: Int, layout: LayoutType, target: SearchItemProtocol, targetDescriptionPosition: Int, isPractice: Bool) {
// Shuffle layout for every trial if random
if settings.group.organisation == .random {
if settings.group.isDesignedLayout == false {
shuffle2dArray(&searchItems)
} else {
shuffle2dArrayMaintainingColorDistance(&searchItems)
// Shuffle again if target has not the distance it should have
shuffleSearchItemsIfNeededFor(target: target)
}
}
let targetsBeforeIndex = targetItems[0...(index % targetItems.count)]
let targetsOfTargetType = targetsBeforeIndex.filter { $0.colorId == target.colorId && $0.shapeId == target.shapeId }
let targetTrialNumber = targetsOfTargetType.count
let searchStepIdentifier = "\(index)"
let itemDistance = itemDistanceWithEqualWhiteSpaceFor(layout: layout, itemDiameter: settings.itemDiameter, itemDistance: settings.group.itemDistance)
let stepSettings = StepSettings(activityNumber: activityNumber, trialNumber: index, targetItem: target, targetDescriptionPosition: targetDescriptionPosition, targetTrialNumber: targetTrialNumber, layout: layout, organisation: settings.group.organisation, participantGroup: settings.group, itemCount: settings.rowCount * settings.columnCount, itemDiameter: settings.itemDiameter, itemDistance: itemDistance, isPractice: isPractice)
let descriptionStep = SearchDescriptionStep(identifier: "SearchDescription\(searchStepIdentifier)", settings: stepSettings)
let searchStep = SearchStep(identifier: searchStepIdentifier, participantIdentifier: settings.participant, items: searchItems, targetFrequency: countFrequencyOf(target: target), settings: stepSettings)
steps.append(descriptionStep)
steps.append(searchStep)
}
private func shuffle2dArrayMaintainingColorDistance(_ array: inout [[SearchItemProtocol]]) {
// Rows must be even
guard array.count % 2 == 0 else { return }
let half = array.count / 2
// Swap first half with second half
for i in 0..<half {
array.swapAt(i, half + i)
// TODO: Xcode 9
// array.swapAt(i, half + i)
}
// Shuffle all rows
for (row, rowItems) in array.enumerated() {
let shuffledRow = rowItems.shuffled()
array[row] = shuffledRow
}
var middleRowItemsGrouped = false
repeat {
let middleUpperRow = array[half - 1]
let middleLowerRow = array[half]
// Make sure two items are grouped in the middle
let upperItemColumn = middleUpperRow.firstIndex(where: { $0.sharedColorCount == settings.distractorColorLowCount })
let lowerItemColumn = middleLowerRow.firstIndex(where: { $0.sharedColorCount == settings.distractorColorLowCount })
// Stop if on top of each other
if upperItemColumn == lowerItemColumn {
middleRowItemsGrouped = true
} else { // Shuffle a
array[half - 1] = middleUpperRow.shuffled()
array[half] = middleLowerRow.shuffled()
}
} while (middleRowItemsGrouped == false)
var apartItemsUpOnSameColumn = true
var apartItemsDownOnSameColumn = true
repeat {
let apartId = Const.StudyParameters.colorIdApartCondition
let itemIndexRow1 = array[0].firstIndex(where: { $0.colorId == apartId })
let itemIndexRow2 = array[1].firstIndex(where: { $0.colorId == apartId })
let itemIndexRow3 = array[2].firstIndex(where: { $0.colorId == apartId })
let itemIndexRowLast3 = array[array.count - 3].firstIndex(where: { $0.colorId == apartId })
let itemIndexRowLast2 = array[array.count - 2].firstIndex(where: { $0.colorId == apartId })
let itemIndexRowLast1 = array[array.count - 1].firstIndex(where: { $0.colorId == apartId })
if itemIndexRow2 == itemIndexRow1 || itemIndexRow2 == itemIndexRow3 {
array[1].shuffle()
apartItemsUpOnSameColumn = true
} else {
apartItemsUpOnSameColumn = false
}
if itemIndexRowLast2 == itemIndexRowLast3 || itemIndexRowLast2 == itemIndexRowLast1 {
array[array.count - 2].shuffle()
apartItemsDownOnSameColumn = true
} else {
apartItemsDownOnSameColumn = false
}
} while (apartItemsUpOnSameColumn || apartItemsDownOnSameColumn)
}
private func shuffle2dArray(_ array: inout [[SearchItemProtocol]]) {
let flatMap = array.flatMap { $0 }
let itemsShuffled = flatMap.shuffled()
var itemCounter = 0
for (row, rowItems) in array.enumerated() {
for (column, _) in rowItems.enumerated() {
array[row][column] = itemsShuffled[itemCounter]
itemCounter += 1
}
}
}
var isColorFarApartCondition1LastFarApart = false
var isColorFarApartCondition2LastFarApart = false
private func countFrequencyOf(target: SearchItemProtocol) -> Int {
return (targetItems.filter { $0.colorId == target.colorId && $0.shapeId == target.shapeId }).count * settings.group.layouts.count
}
private func shuffleSearchItemsIfNeededFor(target: SearchItemProtocol) {
if target.sharedColorCount == settings.distractorColorLowCount {
for (row, rowItems) in searchItems.enumerated() {
for item in rowItems {
// Found the target item
if item.colorId == target.colorId {
let isFarApart = row == 0
let isGrouped = row == (searchItems.count / 2 - 1)
let isColorCondition1 = target.colorId == Const.StudyParameters.colorIdFarApartCondition1
let isColorCondition2 = target.colorId == Const.StudyParameters.colorIdFarApartCondition2
if isColorCondition1 {
if isGrouped && isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = false
} else if isGrouped && !isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = true
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = false
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && !isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = true
}
} else if isColorCondition2 {
if isGrouped && isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = false
} else if isGrouped && !isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = true
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = false
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && !isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = true
}
}
break
}
}
}
}
}
private func otherColorDistractorCountLowId(colorId: Int) -> Int {
if colorId == Const.StudyParameters.colorIdFarApartCondition1 {
return Const.StudyParameters.colorIdFarApartCondition2
} else {
return Const.StudyParameters.colorIdFarApartCondition1
}
}
private var staticColors: [[Int]] {
var colors: [[Int]] = []
let c = Const.StudyParameters.colorIdFarApartCondition1 // 5
let d = Const.StudyParameters.colorIdFarApartCondition2 // 6
let a = Const.StudyParameters.colorIdApartCondition // 2
let colorRow1 = [1, 1, c, a, 0, 0, 0, 0, 0, 0]
let colorRow2 = [1, a, 3, 1, 0, 0, 0, 0, 0, 0]
let colorRow3 = [a, 1, d, 1, 0, 0, 0, 0, 0, 0]
let colorRow4 = [4, a, d, 4, 0, 0, 0, 0, 0, 0]
let colorRow5 = [4, 3, 4, a, 0, 0, 0, 0, 0, 0]
let colorRow6 = [a, c, 4, 4, 0, 0, 0, 0, 0, 0]
let colorRow7 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let colorRow8 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let colorRow9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let colorRow10 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
colors.append(colorRow1)
colors.append(colorRow2)
colors.append(colorRow3)
colors.append(colorRow4)
colors.append(colorRow5)
colors.append(colorRow6)
colors.append(colorRow7)
colors.append(colorRow8)
colors.append(colorRow9)
colors.append(colorRow10)
return colors
}
private func countColorsIn(colorArray: [[Int]], colorId: Int) -> Int {
var counter = 0
for itemRow in colorArray {
for item in itemRow {
if item == colorId {
counter += 1
}
}
}
return counter
}
private func store(searchItems: [[SearchItemProtocol]]) {
for (i, row) in searchItems.enumerated() {
for (j, column) in row.enumerated() {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: column)
UserDefaults.standard.set(encodedData, forKey: SettingsString.lastUsedSearchItems.rawValue + "\(i)\(j)")
}
}
}
private func loadSearchItems(rowCount: Int, columnCount: Int) -> [[SearchItemProtocol]] {
var searchItems: [[SearchItemProtocol]] = []
for i in 0..<rowCount {
var row: [SearchItemProtocol] = []
for j in 0..<columnCount {
let encodedData = UserDefaults.standard.object(forKey: SettingsString.lastUsedSearchItems.rawValue + "\(i)\(j)") as! Data
let searchItem = NSKeyedUnarchiver.unarchiveObject(with: encodedData) as! SearchItemProtocol
row.append(searchItem)
}
searchItems.append(row)
}
return searchItems
}
}
| mit |
lstanii-magnet/ChatKitSample-iOS | ChatMessenger/Pods/ChatKit/ChatKit/source/ChatKit/DefaultChatListControllerDatasource.swift | 1 | 5173 | /*
* Copyright (c) 2016 Magnet Systems, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import CocoaLumberjack
import MagnetMax
public class DefaultChatListControllerDatasource : NSObject, ChatListControllerDatasource {
//MARK : Public Variables
public weak var controller : MMXChatListViewController?
public var hasMoreUsers : Bool = true
public private(set) var channels : [MMXChannel] = []
public let limit = 30
// Public Functions
public func createChat(from subscribers : [MMUser]) {
let id = NSUUID().UUIDString
MMXChannel.createWithName(id, summary: id, isPublic: false, publishPermissions: .Anyone, subscribers: Set(subscribers), success: { (channel) -> Void in
self.controller?.reloadData()
DDLogVerbose("[Channel Created] - (\(channel.name))")
}) { (error) -> Void in
DDLogError("[Error] - \(error.localizedDescription)")
}
}
public func subscribedChannels(completion : ((channels : [MMXChannel]) -> Void)) {
MMXChannel.subscribedChannelsWithSuccess({ ch in
self.channels = ch
completion(channels: self.channels)
DDLogVerbose("[Retireved] - Channels (\(self.channels.count))")
}) { error in
completion(channels: [])
DDLogError("[Error] - \(error.localizedDescription)")
}
}
//Mark: ChatListControllerDatasource
public func mmxControllerHasMore() -> Bool {
return self.hasMoreUsers
}
public func mmxControllerSearchUpdatesContinuously() ->Bool {
return true
}
public func mmxControllerLoadMore(searchText : String?, offset : Int) {
self.hasMoreUsers = offset == 0 ? true : self.hasMoreUsers
//get request context
let loadingContext = controller?.loadingContext()
subscribedChannels({ channels in
if loadingContext != self.controller?.loadingContext() {
return
}
var offsetChannels : [MMXChannel] = []
if offset < channels.count {
offsetChannels = Array(channels[offset..<min((offset + self.limit), channels.count)])
} else {
self.hasMoreUsers = false
}
self.controller?.append(offsetChannels)
})
}
public func mmxListImageForChannelDetails(imageView: UIImageView, channelDetails: MMXChannelDetailResponse) {
if channelDetails.subscriberCount > 2 {
let image = UIImage(named: "user_group_clear.png", inBundle: NSBundle(forClass: DefaultChatListControllerDatasource.self), compatibleWithTraitCollection: nil)
imageView.backgroundColor = controller?.appearance.tintColor
imageView.image = image
} else {
var subscribers = channelDetails.subscribers.filter({$0.userId != MMUser.currentUser()?.userID})
if subscribers.count == 0 {
subscribers = channelDetails.subscribers
}
if let userProfile = subscribers.first {
let tmpUser = MMUser()
tmpUser.extras = ["hasAvatar" : "true"]
var fName : String?
var lName : String?
let nameComponents = userProfile.displayName.componentsSeparatedByString(" ")
if let lastName = nameComponents.last where nameComponents.count > 1 {
lName = lastName
}
if let firstName = nameComponents.first {
fName = firstName
}
tmpUser.firstName = ""
tmpUser.lastName = ""
tmpUser.userName = userProfile.displayName
tmpUser.userID = userProfile.userId
let defaultImage = Utils.noAvatarImageForUser(fName, lastName: lName)
Utils.loadImageWithUrl(tmpUser.avatarURL(), toImageView: imageView, placeholderImage:defaultImage)
}
}
}
public func mmxListCellForMMXChannel(tableView : UITableView,channel : MMXChannel, channelDetails : MMXChannelDetailResponse, row : Int) -> UITableViewCell? {
return nil
}
public func mmxListCellHeightForMMXChannel(channel : MMXChannel, channelDetails : MMXChannelDetailResponse, row : Int) -> CGFloat {
return 80
}
public func mmxListRegisterCells(tableView : UITableView) {
//using standard cells
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/25875-swift-valuedecl-overwritetype.swift | 7 | 235 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a{protocol c:a}struct a{class a{struct A{class a)let a{:
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19079-no-stacktrace.swift | 11 | 260 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[ ]
class a {
protocol A {
class B {
func f {
for c : {
class B { func d {
class
case c,
{
| mit |
austinzheng/swift-compiler-crashes | fixed/01999-swift-lexer-leximpl.swift | 11 | 227 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
let a{
{
{
:["
}
}
}
}
protocol B:SequenceType,b{
func b | mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/24222-swift-genericparamlist-deriveallarchetypes.swift | 9 | 234 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B{
func a{class d{
let a{
class a{
enum k{
class
case c,
{
| mit |
plivesey/SwiftGen | Pods/PathKit/Sources/PathKit.swift | 2 | 19773 | // PathKit - Effortless path operations
#if os(Linux)
import Glibc
let system_glob = Glibc.glob
#else
import Darwin
let system_glob = Darwin.glob
#endif
import Foundation
/// Represents a filesystem path.
public struct Path {
/// The character used by the OS to separate two path elements
public static let separator = "/"
/// The underlying string representation
internal var path: String
internal static var fileManager = FileManager.default
// MARK: Init
public init() {
self.path = ""
}
/// Create a Path from a given String
public init(_ path: String) {
self.path = path
}
/// Create a Path by joining multiple path components together
public init<S : Collection>(components: S) where S.Iterator.Element == String {
if components.isEmpty {
path = "."
} else if components.first == Path.separator && components.count > 1 {
let p = components.joined(separator: Path.separator)
path = p.substring(from: p.characters.index(after: p.startIndex))
} else {
path = components.joined(separator: Path.separator)
}
}
}
// MARK: StringLiteralConvertible
extension Path : ExpressibleByStringLiteral {
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(unicodeScalarLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(stringLiteral value: StringLiteralType) {
self.path = value
}
}
// MARK: CustomStringConvertible
extension Path : CustomStringConvertible {
public var description: String {
return self.path
}
}
// MARK: Hashable
extension Path : Hashable {
public var hashValue: Int {
return path.hashValue
}
}
// MARK: Path Info
extension Path {
/// Test whether a path is absolute.
///
/// - Returns: `true` iff the path begings with a slash
///
public var isAbsolute: Bool {
return path.hasPrefix(Path.separator)
}
/// Test whether a path is relative.
///
/// - Returns: `true` iff a path is relative (not absolute)
///
public var isRelative: Bool {
return !isAbsolute
}
/// Concatenates relative paths to the current directory and derives the normalized path
///
/// - Returns: the absolute path in the actual filesystem
///
public func absolute() -> Path {
if isAbsolute {
return normalize()
}
return (Path.current + self).normalize()
}
/// Normalizes the path, this cleans up redundant ".." and ".", double slashes
/// and resolves "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func normalize() -> Path {
return Path(NSString(string: self.path).standardizingPath)
}
/// De-normalizes the path, by replacing the current user home directory with "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func abbreviate() -> Path {
#if os(Linux)
// TODO: actually de-normalize the path
return self
#else
return Path(NSString(string: self.path).abbreviatingWithTildeInPath)
#endif
}
/// Returns the path of the item pointed to by a symbolic link.
///
/// - Returns: the path of directory or file to which the symbolic link refers
///
public func symlinkDestination() throws -> Path {
let symlinkDestination = try Path.fileManager.destinationOfSymbolicLink(atPath: path)
let symlinkPath = Path(symlinkDestination)
if symlinkPath.isRelative {
return self + ".." + symlinkPath
} else {
return symlinkPath
}
}
}
// MARK: Path Components
extension Path {
/// The last path component
///
/// - Returns: the last path component
///
public var lastComponent: String {
return NSString(string: path).lastPathComponent
}
/// The last path component without file extension
///
/// - Note: This returns "." for "..".
///
/// - Returns: the last path component without file extension
///
public var lastComponentWithoutExtension: String {
return NSString(string: lastComponent).deletingPathExtension
}
/// Splits the string representation on the directory separator.
/// Absolute paths remain the leading slash as first component.
///
/// - Returns: all path components
///
public var components: [String] {
return NSString(string: path).pathComponents
}
/// The file extension behind the last dot of the last component.
///
/// - Returns: the file extension
///
public var `extension`: String? {
let pathExtension = NSString(string: path).pathExtension
if pathExtension.isEmpty {
return nil
}
return pathExtension
}
}
// MARK: File Info
extension Path {
/// Test whether a file or directory exists at a specified path
///
/// - Returns: `false` iff the path doesn't exist on disk or its existence could not be
/// determined
///
public var exists: Bool {
return Path.fileManager.fileExists(atPath: self.path)
}
/// Test whether a path is a directory.
///
/// - Returns: `true` if the path is a directory or a symbolic link that points to a directory;
/// `false` if the path is not a directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isDirectory: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else {
return false
}
#if os(Linux)
return directory
#else
return directory.boolValue
#endif
}
/// Test whether a path is a regular file.
///
/// - Returns: `true` if the path is neither a directory nor a symbolic link that points to a
/// directory; `false` if the path is a directory or a symbolic link that points to a
/// directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isFile: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else {
return false
}
#if os(Linux)
return !directory
#else
return !directory.boolValue
#endif
}
/// Test whether a path is a symbolic link.
///
/// - Returns: `true` if the path is a symbolic link; `false` if the path doesn't exist on disk
/// or its existence could not be determined
///
public var isSymlink: Bool {
do {
let _ = try Path.fileManager.destinationOfSymbolicLink(atPath: path)
return true
} catch {
return false
}
}
/// Test whether a path is readable
///
/// - Returns: `true` if the current process has read privileges for the file at path;
/// otherwise `false` if the process does not have read privileges or the existence of the
/// file could not be determined.
///
public var isReadable: Bool {
return Path.fileManager.isReadableFile(atPath: self.path)
}
/// Test whether a path is writeable
///
/// - Returns: `true` if the current process has write privileges for the file at path;
/// otherwise `false` if the process does not have write privileges or the existence of the
/// file could not be determined.
///
public var isWritable: Bool {
return Path.fileManager.isWritableFile(atPath: self.path)
}
/// Test whether a path is executable
///
/// - Returns: `true` if the current process has execute privileges for the file at path;
/// otherwise `false` if the process does not have execute privileges or the existence of the
/// file could not be determined.
///
public var isExecutable: Bool {
return Path.fileManager.isExecutableFile(atPath: self.path)
}
/// Test whether a path is deletable
///
/// - Returns: `true` if the current process has delete privileges for the file at path;
/// otherwise `false` if the process does not have delete privileges or the existence of the
/// file could not be determined.
///
public var isDeletable: Bool {
return Path.fileManager.isDeletableFile(atPath: self.path)
}
}
// MARK: File Manipulation
extension Path {
/// Create the directory.
///
/// - Note: This method fails if any of the intermediate parent directories does not exist.
/// This method also fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkdir() throws -> () {
try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: false, attributes: nil)
}
/// Create the directory and any intermediate parent directories that do not exist.
///
/// - Note: This method fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkpath() throws -> () {
try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: true, attributes: nil)
}
/// Delete the file or directory.
///
/// - Note: If the path specifies a directory, the contents of that directory are recursively
/// removed.
///
public func delete() throws -> () {
try Path.fileManager.removeItem(atPath: self.path)
}
/// Move the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func move(_ destination: Path) throws -> () {
try Path.fileManager.moveItem(atPath: self.path, toPath: destination.path)
}
/// Copy the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func copy(_ destination: Path) throws -> () {
try Path.fileManager.copyItem(atPath: self.path, toPath: destination.path)
}
/// Creates a hard link at a new destination.
///
/// - Parameter destination: The location where the link will be created.
///
public func link(_ destination: Path) throws -> () {
try Path.fileManager.linkItem(atPath: self.path, toPath: destination.path)
}
/// Creates a symbolic link at a new destination.
///
/// - Parameter destintation: The location where the link will be created.
///
public func symlink(_ destination: Path) throws -> () {
try Path.fileManager.createSymbolicLink(atPath: self.path, withDestinationPath: destination.path)
}
}
// MARK: Current Directory
extension Path {
/// The current working directory of the process
///
/// - Returns: the current working directory of the process
///
public static var current: Path {
get {
return self.init(Path.fileManager.currentDirectoryPath)
}
set {
_ = Path.fileManager.changeCurrentDirectoryPath(newValue.description)
}
}
/// Changes the current working directory of the process to the path during the execution of the
/// given block.
///
/// - Note: The original working directory is restored when the block returns or throws.
/// - Parameter closure: A closure to be executed while the current directory is configured to
/// the path.
///
public func chdir(closure: () throws -> ()) rethrows {
let previous = Path.current
Path.current = self
defer { Path.current = previous }
try closure()
}
}
// MARK: Temporary
extension Path {
/// - Returns: the path to either the user’s or application’s home directory,
/// depending on the platform.
///
public static var home: Path {
return Path(NSHomeDirectory())
}
/// - Returns: the path of the temporary directory for the current user.
///
public static var temporary: Path {
return Path(NSTemporaryDirectory())
}
/// - Returns: the path of a temporary directory unique for the process.
/// - Note: Based on `NSProcessInfo.globallyUniqueString`.
///
public static func processUniqueTemporary() throws -> Path {
let path = temporary + ProcessInfo.processInfo.globallyUniqueString
if !path.exists {
try path.mkdir()
}
return path
}
/// - Returns: the path of a temporary directory unique for each call.
/// - Note: Based on `NSUUID`.
///
public static func uniqueTemporary() throws -> Path {
let path = try processUniqueTemporary() + UUID().uuidString
try path.mkdir()
return path
}
}
// MARK: Contents
extension Path {
/// Reads the file.
///
/// - Returns: the contents of the file at the specified path.
///
public func read() throws -> Data {
return try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions(rawValue: 0))
}
/// Reads the file contents and encoded its bytes to string applying the given encoding.
///
/// - Parameter encoding: the encoding which should be used to decode the data.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func read(_ encoding: String.Encoding = String.Encoding.utf8) throws -> String {
return try NSString(contentsOfFile: path, encoding: encoding.rawValue).substring(from: 0) as String
}
/// Write a file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter data: the contents to write to file.
///
public func write(_ data: Data) throws {
try data.write(to: URL(fileURLWithPath: normalize().path), options: .atomic)
}
/// Reads the file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter string: the string to write to file.
///
/// - Parameter encoding: the encoding which should be used to represent the string as bytes.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8) throws {
try string.write(toFile: normalize().path, atomically: true, encoding: encoding)
}
}
// MARK: Traversing
extension Path {
/// Get the parent directory
///
/// - Returns: the normalized path of the parent directory
///
public func parent() -> Path {
return self + ".."
}
/// Performs a shallow enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory
///
public func children() throws -> [Path] {
return try Path.fileManager.contentsOfDirectory(atPath: path).map {
self + Path($0)
}
}
/// Performs a deep enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory or
/// any subdirectory.
///
public func recursiveChildren() throws -> [Path] {
return try Path.fileManager.subpathsOfDirectory(atPath: path).map {
self + Path($0)
}
}
}
// MARK: Globbing
extension Path {
public static func glob(_ pattern: String) -> [Path] {
var gt = glob_t()
let cPattern = strdup(pattern)
defer {
globfree(>)
free(cPattern)
}
let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK
if system_glob(cPattern, flags, nil, >) == 0 {
#if os(Linux)
let matchc = gt.gl_pathc
#else
let matchc = gt.gl_matchc
#endif
return (0..<Int(matchc)).flatMap { index in
if let path = String(validatingUTF8: gt.gl_pathv[index]!) {
return Path(path)
}
return nil
}
}
// GLOB_NOMATCH
return []
}
public func glob(_ pattern: String) -> [Path] {
return Path.glob((self + pattern).description)
}
}
// MARK: SequenceType
extension Path : Sequence {
/// Enumerates the contents of a directory, returning the paths of all files and directories
/// contained within that directory. These paths are relative to the directory.
public struct DirectoryEnumerator : IteratorProtocol {
public typealias Element = Path
let path: Path
let directoryEnumerator: FileManager.DirectoryEnumerator
init(path: Path) {
self.path = path
self.directoryEnumerator = Path.fileManager.enumerator(atPath: path.path)!
}
public func next() -> Path? {
if let next = directoryEnumerator.nextObject() as! String? {
return path + next
}
return nil
}
/// Skip recursion into the most recently obtained subdirectory.
public func skipDescendants() {
directoryEnumerator.skipDescendants()
}
}
/// Perform a deep enumeration of a directory.
///
/// - Returns: a directory enumerator that can be used to perform a deep enumeration of the
/// directory.
///
public func makeIterator() -> DirectoryEnumerator {
return DirectoryEnumerator(path: self)
}
}
// MARK: Equatable
extension Path : Equatable {}
/// Determines if two paths are identical
///
/// - Note: The comparison is string-based. Be aware that two different paths (foo.txt and
/// ./foo.txt) can refer to the same file.
///
public func ==(lhs: Path, rhs: Path) -> Bool {
return lhs.path == rhs.path
}
// MARK: Pattern Matching
/// Implements pattern-matching for paths.
///
/// - Returns: `true` iff one of the following conditions is true:
/// - the paths are equal (based on `Path`'s `Equatable` implementation)
/// - the paths can be normalized to equal Paths.
///
public func ~=(lhs: Path, rhs: Path) -> Bool {
return lhs == rhs
|| lhs.normalize() == rhs.normalize()
}
// MARK: Comparable
extension Path : Comparable {}
/// Defines a strict total order over Paths based on their underlying string representation.
public func <(lhs: Path, rhs: Path) -> Bool {
return lhs.path < rhs.path
}
// MARK: Operators
/// Appends a Path fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: Path) -> Path {
return lhs.path + rhs.path
}
/// Appends a String fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: String) -> Path {
return lhs.path + rhs
}
/// Appends a String fragment to another String to produce a new Path
internal func +(lhs: String, rhs: String) -> Path {
if rhs.hasPrefix(Path.separator) {
// Absolute paths replace relative paths
return Path(rhs)
} else {
var lSlice = NSString(string: lhs).pathComponents.fullSlice
var rSlice = NSString(string: rhs).pathComponents.fullSlice
// Get rid of trailing "/" at the left side
if lSlice.count > 1 && lSlice.last == Path.separator {
lSlice.removeLast()
}
// Advance after the first relevant "."
lSlice = lSlice.filter { $0 != "." }.fullSlice
rSlice = rSlice.filter { $0 != "." }.fullSlice
// Eats up trailing components of the left and leading ".." of the right side
while lSlice.last != ".." && rSlice.first == ".." {
if (lSlice.count > 1 || lSlice.first != Path.separator) && !lSlice.isEmpty {
// A leading "/" is never popped
lSlice.removeLast()
}
if !rSlice.isEmpty {
rSlice.removeFirst()
}
switch (lSlice.isEmpty, rSlice.isEmpty) {
case (true, _):
break
case (_, true):
break
default:
continue
}
}
return Path(components: lSlice + rSlice)
}
}
extension Array {
var fullSlice: ArraySlice<Element> {
return self[self.indices.suffix(from: 0)]
}
}
| mit |
CatchChat/Yep | Yep/Views/Cells/SearchedMessage/SearchedMessageCell.swift | 1 | 3057 | //
// SearchedMessageCell.swift
// Yep
//
// Created by NIX on 16/4/5.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class SearchedMessageCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
separatorInset = YepConfig.SearchedItemCell.separatorInset
}
override func prepareForReuse() {
super.prepareForReuse()
avatarImageView.image = nil
nicknameLabel.text = nil
timeLabel.text = nil
messageLabel.text = nil
}
func configureWithMessage(message: Message, keyword: String?) {
guard let user = message.fromFriend else {
return
}
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: miniAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
nicknameLabel.text = user.nickname
if let keyword = keyword {
messageLabel.attributedText = message.textContent.yep_hightlightSearchKeyword(keyword, baseFont: YepConfig.SearchedItemCell.messageFont, baseColor: YepConfig.SearchedItemCell.messageColor)
} else {
messageLabel.text = message.textContent
}
timeLabel.text = NSDate(timeIntervalSince1970: message.createdUnixTime).timeAgo.lowercaseString
}
func configureWithUserMessages(userMessages: SearchConversationsViewController.UserMessages, keyword: String?) {
let user = userMessages.user
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
nicknameLabel.text = user.nickname
let count = userMessages.messages.count
if let message = userMessages.messages.first {
if count > 1 {
messageLabel.textColor = UIColor.yepTintColor()
messageLabel.text = String(format: NSLocalizedString("countMessages%d", comment: ""), count)
timeLabel.hidden = true
timeLabel.text = nil
} else {
messageLabel.textColor = UIColor.blackColor()
if let keyword = keyword {
messageLabel.attributedText = message.textContent.yep_hightlightSearchKeyword(keyword, baseFont: YepConfig.SearchedItemCell.messageFont, baseColor: YepConfig.SearchedItemCell.messageColor)
} else {
messageLabel.text = message.textContent
}
timeLabel.hidden = false
timeLabel.text = NSDate(timeIntervalSince1970: message.createdUnixTime).timeAgo.lowercaseString
}
}
}
}
| mit |
FlaneurApp/FlaneurOpen | Sources/Classes/MapKitUtils/FlaneurMapAnnotation.swift | 1 | 463 | //
// FlaneurMapAnnotation.swift
// Pods
//
// Created by Mickaël Floc'hlay on 21/09/2017.
//
//
import Foundation
import MapKit
public class FlaneurMapAnnotation: MKPointAnnotation {
public let mapItem: FlaneurMapItem
public init(mapItem: FlaneurMapItem) {
self.mapItem = mapItem
super.init()
coordinate = mapItem.mapItemCoordinate2D
title = mapItem.mapItemTitle
subtitle = mapItem.mapItemAddress
}
}
| mit |
mrakowski/RRRUtilities | UIColor+Utilities.swift | 1 | 3347 | //
// UIColor+Utilities.swift
// RRRUtilities
//
// Created by Michael Rakowski on 8/7/16.
// Copyright © 2016 Constant Practice 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 Foundation
import UIKit
extension UIColor {
// MARK:
class func desaturate(color: UIColor) -> UIColor {
var desaturatedColor = color
var hue : CGFloat = 0.0
var sat : CGFloat = 0.0
var bri : CGFloat = 0.0
var alp : CGFloat = 0.0
let gotHSB = color.getHue(&hue,
saturation: &sat,
brightness: &bri,
alpha: &alp)
if (gotHSB) {
desaturatedColor = UIColor.init(hue: hue/2,
saturation: sat/2,
brightness: bri/2,
alpha: alp)
}
return desaturatedColor
}
class func brighten(color: UIColor) -> UIColor {
return self.brighten(color: color, multiplier: 1.2)
}
/**
Brighten a color (modifies the brightness component in HSB color format).
# Parameters:
- color: The color to brighten
- multiplier: The brightening factor (to multiply the brightness component by)
- Returns: A brighter version of the input color (if there was an error computing the HSB representation of the color, the original color will be returned).
*/
class func brighten(color: UIColor, multiplier: CGFloat) -> UIColor {
var brighterColor = color
var hue : CGFloat = 0.0
var sat : CGFloat = 0.0
var bri : CGFloat = 0.0
var alp : CGFloat = 0.0
let gotHSB = color.getHue(&hue,
saturation: &sat,
brightness: &bri,
alpha: &alp)
if (gotHSB) {
brighterColor = UIColor.init(hue: hue,
saturation: sat,
brightness: bri*multiplier,
alpha: alp)
}
return brighterColor
}
}
| mit |
EstefaniaGilVaquero/ciceIOS | App_MVC_INTRO_WEB_SERVICE/ICOModel.swift | 1 | 654 | //
// ICOModel.swift
// App_MVC_INTRO_WEB_SERVICE
//
// Created by cice on 20/7/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
class ICOModel: NSObject {
var estado : String?
var jugador1 : String?
var jugador2 : String?
var resultados : String?
var resultados2 : String?
init(pEstado : String, pJugador1 : String, pJugador2 : String, pResultados : String, pResultados2 : String) {
self.estado = pEstado
self.jugador1 = pJugador1
self.jugador2 = pJugador2
self.resultados = pResultados
self.resultados2 = pResultados2
super.init()
}
}
| apache-2.0 |
itlekt/transitioner | Transitioner/Animator.swift | 1 | 1963 | //
// Created by Alex Balobanov on 4/28/17.
// Copyright © 2017 ITlekt Corporation. All rights reserved.
//
import UIKit
public protocol TransitionerAnimatorProtocol: UIViewControllerAnimatedTransitioning {
var animationInProgress: Bool { get }
init(_ presentation: Bool)
func animate(presentation: Bool, using transitionContext: UIViewControllerContextTransitioning)
func percentComplete(presentation: Bool, using recognizer: UIPanGestureRecognizer) -> CGFloat
}
open class TransitionerAnimator: NSObject, TransitionerAnimatorProtocol {
private let isPresentation: Bool
// MARK: TransitionerAnimatorProtocol
private(set) public var animationInProgress = false
required public init(_ presentation: Bool) {
isPresentation = presentation
}
open func animate(presentation: Bool, using transitionContext: UIViewControllerContextTransitioning) {
}
open func percentComplete(presentation: Bool, using recognizer: UIPanGestureRecognizer) -> CGFloat {
return 0
}
// MARK: UIViewControllerAnimatedTransitioning
// This is used for percent driven interactive transitions, as well as for
// container controllers that have companion animations that might need to
// synchronize with the main animation.
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.35
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
animationInProgress = true
animate(presentation: isPresentation, using: transitionContext)
}
// This is a convenience and if implemented will be invoked by the system when the transition context's completeTransition: method is invoked.
public func animationEnded(_ transitionCompleted: Bool) {
animationInProgress = false
}
// MARK: UIPercentDrivenInteractiveTransition
}
| mit |
cinco-interactive/BluetoothKit | Source/BKSendDataTask.swift | 1 | 2530 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
internal func ==(lhs: BKSendDataTask, rhs: BKSendDataTask) -> Bool {
return lhs.destination == rhs.destination && lhs.data.isEqualToData(rhs.data)
}
internal class BKSendDataTask: Equatable {
// MARK: Properties
internal let data: NSData
internal let destination: BKRemotePeer
internal let completionHandler: BKSendDataCompletionHandler?
internal var offset = 0
internal var maximumPayloadLength: Int {
return destination.maximumUpdateValueLength
}
internal var lengthOfRemainingData: Int {
return data.length - offset
}
internal var sentAllData: Bool {
return lengthOfRemainingData == 0
}
internal var rangeForNextPayload: NSRange {
let lenghtOfNextPayload = maximumPayloadLength <= lengthOfRemainingData ? maximumPayloadLength : lengthOfRemainingData
return NSMakeRange(offset, lenghtOfNextPayload)
}
internal var nextPayload: NSData {
return data.subdataWithRange(rangeForNextPayload)
}
// MARK: Initialization
internal init(data: NSData, destination: BKRemotePeer, completionHandler: BKSendDataCompletionHandler?) {
self.data = data
self.destination = destination
self.completionHandler = completionHandler
}
}
| mit |
apple/swift | test/attr/attr_marker_protocol.swift | 1 | 2133 | // RUN: %target-typecheck-verify-swift
// Marker protocol definition
@_marker protocol P1 {
func f() // expected-error{{marker protocol 'P1' cannot have any requirements}}
}
@_marker protocol P2 {
associatedtype AT // expected-error{{marker protocol 'P2' cannot have any requirements}}
}
@_marker protocol P3 {
typealias A = Int
}
protocol P4 { } // expected-note{{'P4' declared here}}
@_marker protocol P5: P4 { } // expected-error{{marker protocol 'P5' cannot inherit non-marker protocol 'P4'}}
class C { }
@_marker protocol P5a: AnyObject { } // okay
@_marker protocol P5b: C { } // expected-error{{marker protocol 'P5b' cannot inherit class 'C'}}
// Legitimate uses of marker protocols.
extension P3 {
func f() { }
}
extension Int: P3 { }
extension Array: P3 where Element: P3 { } // expected-note{{requirement from conditional conformance of '[Double]' to 'P3'}}
protocol P6: P3 { } // okay
@_marker protocol P7: P3 { } // okay
func genericOk<T: P3>(_: T) { }
func testGenericOk(i: Int, arr: [Int], nope: [Double], p3: P3, p3array: [P3]) {
genericOk(i)
genericOk(arr)
genericOk(nope) // expected-error{{global function 'genericOk' requires that 'Double' conform to 'P3'}}
genericOk(p3)
genericOk(p3array)
}
// Incorrect uses of marker protocols in types.
func testNotOkay(a: Any) {
var mp1: P3 = 17
_ = mp1
mp1 = 17
if let mp2 = a as? P3 { _ = mp2 } // expected-error{{marker protocol 'P3' cannot be used in a conditional cast}}
if let mp3 = a as? AnyObject & P3 { _ = mp3 } // expected-error{{marker protocol 'P3' cannot be used in a conditional cast}}
if a is AnyObject & P3 { } // expected-error{{marker protocol 'P3' cannot be used in a conditional cast}}
func inner(p3: P3) { }
}
@_marker protocol P8 { }
protocol P9: P8 { }
// Implied conditional conformance to P8 is okay because P8 is a marker
// protocol.
extension Array: P9 where Element: P9 { }
protocol P10 { }
extension Array: P10 where Element: P10, Element: P8 { }
// expected-error@-1{{conditional conformance to non-marker protocol 'P10' cannot depend on conformance of 'Element' to marker protocol 'P8'}}
| apache-2.0 |
apple/swift | test/SILGen/objc_final.swift | 5 | 1246 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-verbose-sil | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
final class Foo {
@objc func foo() {}
// CHECK-LABEL: sil private [thunk] [ossa] @$s10objc_final3FooC3foo{{[_0-9a-zA-Z]*}}FTo
@objc var prop: Int = 0
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s10objc_final3FooC4propSivgTo
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s10objc_final3FooC4propSivsTo
}
// CHECK-LABEL: sil hidden [ossa] @$s10objc_final7callFooyyAA0D0CF
func callFoo(_ x: Foo) {
// Calls to the final @objc method statically reference the native entry
// point.
// CHECK: function_ref @$s10objc_final3FooC3foo{{[_0-9a-zA-Z]*}}F
x.foo()
// Final @objc properties are still accessed directly.
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[PROP]] : $*Int
// CHECK: load [trivial] [[READ]] : $*Int
let prop = x.prop
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[PROP]] : $*Int
// CHECK: assign {{%.*}} to [[WRITE]] : $*Int
x.prop = prop
}
| apache-2.0 |
LiulietLee/BilibiliCD | BCD/Model/CoreData/SettingManager.swift | 1 | 1369 | //
// SettingManager.swift
// BCD
//
// Created by Liuliet.Lee on 27/6/2018.
// Copyright © 2018 Liuliet.Lee. All rights reserved.
//
import Foundation
import CoreData
class SettingManager: CoreDataModel {
private func initSetting() {
let initHistoryNum: Int16 = 120
let entity = NSEntityDescription.entity(forEntityName: "Setting", in: context)!
let newItem = Setting(entity: entity, insertInto: context)
newItem.historyNumber = initHistoryNum
saveContext()
}
private var setting: Setting? {
do {
let searchResults = try context.fetch(Setting.fetchRequest())
if searchResults.count == 0 {
initSetting()
return self.setting
} else {
return searchResults[0] as? Setting
}
} catch {
print(error)
}
return nil
}
var historyItemLimit: Int! {
get {
return Int(setting?.historyNumber ?? 0)
}
set {
setting?.historyNumber = Int16(newValue)
saveContext()
}
}
var isSaveOriginImageData: Bool! {
get {
return Bool(setting?.saveOrigin ?? true)
} set {
setting?.saveOrigin = newValue
saveContext()
}
}
}
| gpl-3.0 |
appcompany/SwiftSky | Sources/SwiftSky/Temperature.swift | 1 | 4457 | //
// Temperature.swift
// SwiftSky
//
// Created by Luca Silverentand on 11/04/2017.
// Copyright © 2017 App Company.io. All rights reserved.
//
import Foundation
/// Contains a value, unit and a label describing temperature
public struct Temperature {
/// `Double` representing temperature
private(set) public var value : Double = 0
/// `TemperatureUnit` of the value
public let unit : TemperatureUnit
/// Human-readable representation of the value and unit together
public var label : String { return label(as: unit) }
/**
Same as `Temperature.label`, but converted to a specific unit
- parameter unit: `TemperatureUnit` to convert label to
- returns: String
*/
public func label(as unit : TemperatureUnit) -> String {
let converted = (self.unit == unit ? value : convert(value, from: self.unit, to: unit))
switch unit {
case .fahrenheit:
return "\(converted.noDecimal)℉"
case .celsius:
return "\(converted.noDecimal)℃"
case .kelvin:
return "\(converted.noDecimal)K"
}
}
/**
Same as `Temperature.value`, but converted to a specific unit
- parameter unit: `TemperatureUnit` to convert value to
- returns: Float
*/
public func value(as unit : TemperatureUnit) -> Double {
return convert(value, from: self.unit, to: unit)
}
private func convert(_ value : Double, from : TemperatureUnit, to : TemperatureUnit) -> Double {
switch from {
case .fahrenheit:
switch to {
case .fahrenheit:
return value
case .celsius:
return (value - 32) * (5/9)
case .kelvin:
return (value + 459.67) * (5/9)
}
case .celsius:
switch to {
case .celsius:
return value
case .fahrenheit:
return value * (9/5) + 32
case .kelvin:
return value + 273.15
}
case .kelvin:
switch to {
case .kelvin:
return value
case .fahrenheit:
return ((value - 273.15) * 1.8) + 32
case .celsius:
return value - 273.15
}
}
}
/// :nodoc:
public init(_ value : Double, withUnit : TemperatureUnit) {
unit = SwiftSky.units.temperature
self.value = convert(value, from: withUnit, to: unit)
}
}
/// Contains real-feel current, maximum and minimum `Temperature` values
public struct ApparentTemperature {
/// Current real-feel `Temperature`
public let current : Temperature?
/// Maximum value of real-feel `Temperature` during a given day
public let max : Temperature?
/// Time when `ApparentTemperature.max` occurs during a given day
public let maxTime : Date?
/// Minimum value of real-feel `Temperature` during a given day
public let min : Temperature?
/// Time when `ApparentTemperature.min` occurs during a given day
public let minTime : Date?
var hasData : Bool {
if current != nil { return true }
if max != nil { return true }
if maxTime != nil { return true }
if min != nil { return true }
if minTime != nil { return true }
return false
}
}
/// Contains current, maximum, minimum and apparent `Temperature` values
public struct Temperatures {
/// Current `Temperature`
public let current : Temperature?
/// Maximum value of `Temperature` during a given day
public let max : Temperature?
/// Time when `Temperatures.max` occurs during a given day
public let maxTime : Date?
/// Minimum value of `Temperature` during a given day
public let min : Temperature?
/// Time when `Temperatures.min` occurs during a given day
public let minTime : Date?
/// `ApparentTemperature` value with real-feel `Temperature`s
public let apparent : ApparentTemperature?
var hasData : Bool {
if current != nil { return true }
if max != nil { return true }
if maxTime != nil { return true }
if min != nil { return true }
if minTime != nil { return true }
if apparent?.hasData == true { return true }
return false
}
}
| mit |
cnoon/swift-compiler-crashes | fixed/23792-no-stacktrace.swift | 10 | 2200 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol c : b { func b{
}
let start = [Void{let end = [Void{
let ) -> c : Any) -> Void{
let f = compose([Void{
func b
class d
var b{
class
let a {
{
b { func b<U : a<T>()?
}
let a{
struct A<Int>: A
}{func c
import c
func b{init(object1: a<T where S<T>: Any)
{
protocol c : b { e{{
}}
class A{
class A<Int>()?
= [Void{
class
}
{
{
class d<U : (false)
{
{
func c
case c,
struct c
0.C
}}
let a {
case c}{
i> c {
i> c : d = B<T where S<Int>(false)?
class B<T where g:e) -
class B<T where g:A{
}}
0.C
func a
}class B<T>: a {
0.C("\()
let a {
var e{H:A
class A
{
let a<T where k:a
let f = [c
0.C
{let:a{
func b
let ) -> c { {
B :a
protocol c : d = T>(object1: e) -> Void{
class d<T where T>(){
func a<T where H{
let a
Void{{
var e{
}{
func c
class B<Int>: a {
protocol e : (e : S<e) -> Void{}
0.C
protocol c {
protocol e : e>("\([Void{
protocol e = B<Int>
}
}{
"
let a
class B{
let a {let f = [Void{
enum b
class
struct S<c,
protocol c : a
protocol e : ()
let end = compose(e : b l
struct A{
{let end = []
let start = c : S
class d
class B<U : e) -> Void{
}
i> c {
}
0.C
class c
let f = T>()?
protocol c {
class B<Int>
let end = B<T where S<U : ([Void{
{}{
struct A {
func a
enum b=c,
func a
var e) -> Void{
i> c {{
i> Void{}{
Void{let f = B<T>
class
struct Q<T where S<T where T: (object1: Any)?
func b(().e : (object1: (f: S<e) -> c { func c
i> c : A{
protocol c {
i> c : d = [Void{
}{let:a
{
func a
class B<T where S<T: Any) -
"\(object1: Any)?
}
protocol c {let a {
protocol A {
class A{
protocol b { class c
}
let start = B{for b{}enum S {{}
func b<U : (e : d
{}
func b=b<T : b { {let f = [ {class B<T>
func b
import c:A
let end = compose()?
= [1
{let f = [Void{
{
"
{
struct A {{
}class B<T: b { func a
}
b : c : d = T>(object1: e) -> Void{
0.e : S<T : b : S<c,
((()?
class
i> Void{
protocol e : e) -> c : b : Any)?
func a
{
}}
{
= c : e{H:a
class B<T: e>
import c
struct A {}}
{let f = compose((([]
Void{
let a {init(){{
let end = T>: b { func o<T {
0.C
0.C
let a
func a{
protocol A
class
{
struct Q<e) -> Void{protocol c {
i> 1
| mit |
codefellows/sea-b19-ios | Projects/hashtable/hashtable/AppDelegate.swift | 1 | 2172 | //
// AppDelegate.swift
// hashtable
//
// Created by Bradley Johnson on 9/2/14.
// Copyright (c) 2014 learnswift. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> 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:.
}
}
| gpl-2.0 |
rodrigoruiz/SwiftUtilities | SwiftUtilities/Lite/Foundation/Data+Extension.swift | 1 | 780 | //
// Data+Extension.swift
// SwiftUtilities
//
// Created by Rodrigo Ruiz on 4/25/17.
// Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//
extension Data {
public func split(maximumSizeInBytes: Int) -> [Data] {
let fullChunks = count / maximumSizeInBytes
let result = (0..<fullChunks).map({ i -> Data in
let location = i * maximumSizeInBytes
return subdata(in: location..<location + maximumSizeInBytes)
})
let finalChunkSize = count % maximumSizeInBytes
if finalChunkSize == 0 {
return result
}
let location = fullChunks * maximumSizeInBytes
return result + [subdata(in: location..<location + finalChunkSize)]
}
}
| mit |
KyleLeneau/VersionTracker | VersionTrackerTests/VersionTrackerTests.swift | 1 | 996 | //
// VersionTrackerTests.swift
// VersionTrackerTests
//
// Created by Kyle LeNeau on 4/2/16.
// Copyright © 2016 Kyle LeNeau. All rights reserved.
//
import XCTest
@testable import VersionTracker
class VersionTrackerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
SuPair/firefox-ios | Client/Frontend/Settings/websiteData.swift | 1 | 574 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
let dataStore = WKWebsiteDataStore.default()
let dataTypes = WKWebsiteDataStore.allWebsiteDataTypes()
struct siteData {
let dataOfSite: WKWebsiteDataRecord
let nameOfSite: String
init(dataOfSite: WKWebsiteDataRecord, nameOfSite: String) {
self.dataOfSite = dataOfSite
self.nameOfSite = nameOfSite
}
}
| mpl-2.0 |
czj1127292580/weibo_swift | WeiBo_Swift/WeiBo_Swift/Class/Common/UIBarButtonItem+Category.swift | 1 | 758 | //
// UIBarButtonItem+Category.swift
// WeiBo_Swift
//
// Created by 岑志军 on 16/8/18.
// Copyright © 2016年 cen. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
// 如果在func前面加上class,就相当于OC中的+
class func createBarButtonItem(imageName: String, target: AnyObject?, action: Selector) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
btn.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
btn.sizeToFit()
return UIBarButtonItem(customView: btn)
}
} | mit |
xcode-coffee/JSONFeed | Package.swift | 1 | 960 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "JSONFeed",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "JSONFeed",
targets: ["JSONFeed"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "JSONFeed",
dependencies: []),
.testTarget(
name: "JSONFeedTests",
dependencies: ["JSONFeed"]),
]
)
| mit |
AliSoftware/SwiftGen | SwiftGen.playground/Pages/Fonts-Demo.xcplaygroundpage/Contents.swift | 1 | 3276 | //: #### Other pages
//:
//: * [Demo for `colors` parser](Colors-Demo)
//: * [Demo for `coredata` parser](CoreData-Demo)
//: * Demo for `fonts` parser
//: * [Demo for `files` parser](Files-Demo)
//: * [Demo for `ib` parser](InterfaceBuilder-Demo)
//: * [Demo for `json` parser](JSON-Demo)
//: * [Demo for `plist` parser](Plist-Demo)
//: * [Demo for `strings` parser](Strings-Demo)
//: * [Demo for `xcassets` parser](XCAssets-Demo)
//: * [Demo for `yaml` parser](YAML-Demo)
//: #### Example of code generated by `fonts` parser with "swift5" template
#if os(macOS)
import AppKit.NSFont
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIFont
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Fonts
// swiftlint:disable identifier_name line_length type_body_length
internal enum FontFamily {
internal enum Avenir {
internal static let black = FontConvertible(name: "Avenir-Black", family: "Avenir", path: "Avenir.ttc")
internal static let blackOblique = FontConvertible(name: "Avenir-BlackOblique", family: "Avenir", path: "Avenir.ttc")
internal static let book = FontConvertible(name: "Avenir-Book", family: "Avenir", path: "Avenir.ttc")
internal static let bookOblique = FontConvertible(name: "Avenir-BookOblique", family: "Avenir", path: "Avenir.ttc")
internal static let heavy = FontConvertible(name: "Avenir-Heavy", family: "Avenir", path: "Avenir.ttc")
internal static let heavyOblique = FontConvertible(name: "Avenir-HeavyOblique", family: "Avenir", path: "Avenir.ttc")
internal static let light = FontConvertible(name: "Avenir-Light", family: "Avenir", path: "Avenir.ttc")
internal static let lightOblique = FontConvertible(name: "Avenir-LightOblique", family: "Avenir", path: "Avenir.ttc")
internal static let medium = FontConvertible(name: "Avenir-Medium", family: "Avenir", path: "Avenir.ttc")
internal static let mediumOblique = FontConvertible(name: "Avenir-MediumOblique", family: "Avenir", path: "Avenir.ttc")
internal static let oblique = FontConvertible(name: "Avenir-Oblique", family: "Avenir", path: "Avenir.ttc")
internal static let roman = FontConvertible(name: "Avenir-Roman", family: "Avenir", path: "Avenir.ttc")
internal static let all: [FontConvertible] = [black, blackOblique, book, bookOblique, heavy, heavyOblique, light, lightOblique, medium, mediumOblique, oblique, roman]
}
internal enum ZapfDingbats {
internal static let regular = FontConvertible(name: "ZapfDingbatsITC", family: "Zapf Dingbats", path: "ZapfDingbats.ttf")
internal static let all: [FontConvertible] = [regular]
}
internal static let allCustomFonts: [FontConvertible] = [Avenir.all, ZapfDingbats.all].flatMap { $0 }
internal static func registerAllCustomFonts() {
allCustomFonts.forEach { $0.register() }
}
}
// swiftlint:enable identifier_name line_length type_body_length
//: #### Usage Example
// Using the UIFont constructor…
let body = UIFont(font: FontFamily.Avenir.light, size: 20.0)
// Or using the enum value and its `font` method
let title = FontFamily.ZapfDingbats.regular.font(size: 20.0)
let bodyHuge = FontFamily.Avenir.black.font(size: 100.0)
let titleTiny = UIFont(font: FontFamily.ZapfDingbats.regular, size: 8.0)
| mit |
lorentey/swift | test/AutoDiff/Syntax/round_trip_parse_gen.swift | 1 | 2374 | // RUN: rm -rf %t
// RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t
// RUN: diff -u %s %t
// RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds
// RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds
// RUN: %swift-syntax-test -input-source-filename %s -eof > %t
// RUN: diff -u %s %t
// RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump
// RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t
// RUN: diff -u %s %t
// Note: RUN lines copied from test/Syntax/round_trip_parse_gen.swift.
@differentiable(jvp: foo(_:_:))
func bar(_ x: Float, _: Float) -> Float { return 1 }
@differentiable(jvp: foo(_:_:) where T : FloatingPoint)
func bar<T : Numeric>(_ x: T, _: T) -> T { return 1 }
@differentiable(wrt: x, jvp: foo(_:_:))
func bar(_ x: Float, _: Float) -> Float { return 1 }
@differentiable(wrt: (self, x, y), jvp: foo(_:_:))
func bar(_ x: Float, y: Float) -> Float { return 1 }
@differentiable(wrt: (self, x, y), jvp: bar, vjp: foo(_:_:) where T : FloatingPoint)
func bar<T : Numeric>(_ x: T, y: T) -> T { return 1 }
@derivative(of: -)
func negateDerivative(_ x: Float)
-> (value: Float, pullback: (Float) -> Float) {
return (-x, { v in -v })
}
@derivative(of: baz(label:_:), wrt: (x))
func bazDerivative(_ x: Float, y: Float)
-> (value: Float, pullback: (Float) -> Float) {
return (x, { v in v })
}
@transpose(of: -)
func negateDerivative(_ x: Float)
-> (value: Float, pullback: (Float) -> Float) {
return (-x, { v in -v })
}
@derivative(of: baz(label:_:), wrt: (x))
func bazDerivative(_ x: Float, y: Float)
-> (value: Float, pullback: (Float) -> Float) {
return (x, { v in v })
}
@derivative(of: A.B.C.foo(label:_:), wrt: (x))
func qualifiedDerivative(_ x: Float, y: Float)
-> (value: Float, pullback: (Float) -> Float) {
return (x, { v in v })
}
@transpose(of: +)
func addTranspose(_ v: Float) -> (Float, Float) {
return (v, v)
}
@transpose(of: -, wrt: (0, 1))
func subtractTranspose(_ v: Float) -> (Float, Float) {
return (v, -v)
}
@transpose(of: Float.-, wrt: (0, 1))
func subtractTranspose(_ v: Float) -> (Float, Float) {
return (v, -v)
}
@transpose(of: A.B.C.foo(label:_:), wrt: (0))
func qualifiedTranspose(_ v: Float) -> (Float, Float) {
return (v, -v)
}
| apache-2.0 |
lorentey/swift | test/multifile/synthesized-accessors/materialize-for-set-2/Inputs/library1.swift | 42 | 150 | import Foundation
import CounterFramework
public protocol CounterProtocol {
var value: Int32 { get set }
}
extension Counter : CounterProtocol {}
| apache-2.0 |
marklin2012/iOS_Animation | Section4/Chapter23/O2Logo_starter/O2Logo/RWLogoLayer.swift | 4 | 1332 | //
// RWLogoLayer.swift
// O2Logo
//
// Created by O2.LinYi on 16/3/21.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
import QuartzCore
class RWLogoLayer {
class func logoLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
layer.geometryFlipped = true
// the RW bezier
let bezier = UIBezierPath()
bezier.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.addCurveToPoint(CGPoint(x: 0.0, y: 66.97), controlPoint1:CGPoint(x: 0.0, y: 0.0), controlPoint2:CGPoint(x: 0.0, y: 57.06))
bezier.addCurveToPoint(CGPoint(x: 16.0, y: 39.0), controlPoint1: CGPoint(x: 27.68, y: 66.97), controlPoint2:CGPoint(x: 42.35, y: 52.75))
bezier.addCurveToPoint(CGPoint(x: 26.0, y: 17.0), controlPoint1: CGPoint(x: 17.35, y: 35.41), controlPoint2:CGPoint(x: 26, y: 17))
bezier.addLineToPoint(CGPoint(x: 38.0, y: 34.0))
bezier.addLineToPoint(CGPoint(x: 49.0, y: 17.0))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 51.27))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 0.0))
bezier.addLineToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.closePath()
// create a shape layer
layer.path = bezier.CGPath
layer.bounds = CGPathGetBoundingBox(layer.path)
return layer
}
}
| mit |
apple/swift-nio | Tests/NIOPosixTests/SALChannelTests+XCTest.swift | 1 | 1628 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// SALChannelTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension SALChannelTest {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (SALChannelTest) -> () throws -> Void)] {
return [
("testBasicConnectedChannel", testBasicConnectedChannel),
("testWritesFromWritabilityNotificationsDoNotGetLostIfWePreviouslyWroteEverything", testWritesFromWritabilityNotificationsDoNotGetLostIfWePreviouslyWroteEverything),
("testWeSurviveIfIgnoringSIGPIPEFails", testWeSurviveIfIgnoringSIGPIPEFails),
("testBasicRead", testBasicRead),
("testBasicConnectWithClientBootstrap", testBasicConnectWithClientBootstrap),
("testClientBootstrapBindIsDoneAfterSocketOptions", testClientBootstrapBindIsDoneAfterSocketOptions),
]
}
}
| apache-2.0 |
pendowski/PopcornTimeIOS | Popcorn Time/UI/Collection View Controllers/TVShowsCollectionViewController.swift | 1 | 8240 |
import UIKit
import AlamofireImage
class TVShowsCollectionViewController: ItemOverview, UIPopoverPresentationControllerDelegate, GenresDelegate, ItemOverviewDelegate {
var shows = [PCTShow]()
var currentGenre = TVAPI.genres.All {
didSet {
shows.removeAll()
collectionView?.reloadData()
currentPage = 1
loadNextPage(currentPage)
}
}
var currentFilter = TVAPI.filters.Trending {
didSet {
shows.removeAll()
collectionView?.reloadData()
currentPage = 1
loadNextPage(currentPage)
}
}
@IBAction func searchBtnPressed(sender: UIBarButtonItem) {
presentViewController(searchController, animated: true, completion: nil)
}
@IBAction func filter(sender: AnyObject) {
self.collectionView?.performBatchUpdates({
self.filterHeader!.hidden = !self.filterHeader!.hidden
}, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
loadNextPage(currentPage)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let collectionView = object as? UICollectionView where collectionView == self.collectionView! && keyPath! == "frame" {
collectionView.performBatchUpdates(nil, completion: nil)
}
}
func segmentedControlDidChangeSegment(segmentedControl: UISegmentedControl) {
currentFilter = TVAPI.filters.arrayValue[segmentedControl.selectedSegmentIndex]
}
// MARK: - ItemOverviewDelegate
func loadNextPage(pageNumber: Int, searchTerm: String? = nil, removeCurrentData: Bool = false) {
guard isLoading else {
isLoading = true
hasNextPage = false
TVAPI.sharedInstance.load(currentPage, filterBy: currentFilter, genre: currentGenre, searchTerm: searchTerm) { result in
self.isLoading = false
guard case .success(let items) = result else {
return
}
if removeCurrentData {
self.shows.removeAll()
}
self.shows += items
if items.isEmpty // If the array passed in is empty, there are no more results so the content inset of the collection view is reset.
{
self.collectionView?.contentInset = UIEdgeInsetsMake(69, 0, 0, 0)
} else {
self.hasNextPage = true
}
self.collectionView?.reloadData()
}
return
}
}
func didDismissSearchController(searchController: UISearchController) {
self.shows.removeAll()
collectionView?.reloadData()
self.currentPage = 1
loadNextPage(self.currentPage)
}
func search(text: String) {
self.shows.removeAll()
collectionView?.reloadData()
self.currentPage = 1
self.loadNextPage(self.currentPage, searchTerm: text)
}
func shouldRefreshCollectionView() -> Bool {
return shows.isEmpty
}
// MARK: - Navigation
@IBAction func genresButtonTapped(sender: UIBarButtonItem) {
let controller = cache.objectForKey(TraktTVAPI.type.Shows.rawValue) as? UINavigationController ?? (storyboard?.instantiateViewControllerWithIdentifier("GenresNavigationController"))! as! UINavigationController
cache.setObject(controller, forKey: TraktTVAPI.type.Shows.rawValue)
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.barButtonItem = sender
controller.popoverPresentationController?.backgroundColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0)
(controller.viewControllers[0] as! GenresTableViewController).delegate = self
presentViewController(controller, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
fixIOS9PopOverAnchor(segue)
if segue.identifier == "showDetail" {
let showDetail = segue.destinationViewController as! TVShowDetailViewController
let cell = sender as! CoverCollectionViewCell
showDetail.currentItem = shows[(collectionView?.indexPathForCell(cell)?.row)!]
}
}
// MARK: - Collection view data source
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
collectionView.backgroundView = nil
if shows.count == 0 {
if error != nil {
let background = NSBundle.mainBundle().loadNibNamed("TableViewBackground", owner: self, options: nil).first as! TableViewBackground
background.setUpView(error: error!)
collectionView.backgroundView = background
} else if isLoading {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
indicator.center = collectionView.center
collectionView.backgroundView = indicator
indicator.sizeToFit()
indicator.startAnimating()
} else {
let background = NSBundle.mainBundle().loadNibNamed("TableViewBackground", owner: self, options: nil).first as! TableViewBackground
background.setUpView(image: UIImage(named: "Search")!, title: "No results found.", description: "No search results found for \(searchController.searchBar.text!). Please check the spelling and try again.")
collectionView.backgroundView = background
}
}
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return shows.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CoverCollectionViewCell
cell.titleLabel.text = shows[indexPath.row].title
cell.yearLabel.text = String(shows[indexPath.row].year)
cell.coverImage.af_setImageWithURL(NSURL(string: shows[indexPath.row].coverImageAsString)!, placeholderImage: UIImage(named: "Placeholder"), imageTransition: .CrossDissolve(animationLength))
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
filterHeader = filterHeader ?? {
let reuseableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "filter", forIndexPath: indexPath) as! FilterCollectionReusableView
reuseableView.segmentedControl?.removeAllSegments()
for (index, filterValue) in TVAPI.filters.arrayValue.enumerate() {
reuseableView.segmentedControl?.insertSegmentWithTitle(filterValue.title, atIndex: index, animated: false)
}
reuseableView.hidden = true
reuseableView.segmentedControl?.addTarget(self, action: #selector(segmentedControlDidChangeSegment(_:)), forControlEvents: .ValueChanged)
reuseableView.segmentedControl?.selectedSegmentIndex = 0
return reuseableView
}()
return filterHeader!
}
// MARK: - GenresDelegate
func finished(genreArrayIndex: Int) {
navigationItem.title = TVAPI.genres.arrayValue[genreArrayIndex].rawValue
if TVAPI.genres.arrayValue[genreArrayIndex] == .All {
navigationItem.title = "Shows"
}
currentGenre = TVAPI.genres.arrayValue[genreArrayIndex]
}
func populateDataSourceArray(inout array: [String]) {
for genre in TVAPI.genres.arrayValue {
array.append(genre.rawValue)
}
}
}
| gpl-3.0 |
amcnary/cs147_instagator | instagator-prototype/instagator-prototype/PollActivityResultTableViewCell.swift | 1 | 447 | //
// PollActivityResultTableViewCell.swift
// instagator-prototype
//
// Created by Amanda McNary on 11/29/15.
// Copyright © 2015 ThePenguins. All rights reserved.
//
import Foundation
import UIKit
class PollActivityResultTableViewCell: UITableViewCell {
@IBOutlet weak var activityNameLabel: UILabel!
@IBOutlet weak var activitySatisfactionLabel: UILabel!
static let reuseIdentifier = "PollActivityResultTableViewCell"
} | apache-2.0 |
pubnub/SwiftConsole | PubNubSwiftConsole/Classes/PubNubSwiftConsole.swift | 1 | 574 | //
// PubNubSwiftConsole.swift
// Pods
//
// Created by Jordan Zucker on 7/13/16.
//
//
import Foundation
import PubNub
public func modalClientCreationViewController() -> NavigationController {
return NavigationController(rootViewControllerType: .ClientCreation)
}
public func modalConsoleViewController(client: PubNub) -> NavigationController {
return NavigationController(rootViewControllerType: .Console(client: client))
}
public func modalPublishViewController(client: PubNub) -> PublishViewController {
return PublishViewController(client: client)
}
| mit |
chenhaigang888/CHGGridView_swift | SwiftTest/SwiftTest/CHGGridViewCell.swift | 1 | 716 | //
// CHGGridViewCell.swift
// SwiftTest
//
// Created by Hogan on 2017/2/17.
// Copyright © 2017年 Hogan. All rights reserved.
//
import UIKit
///CHGGridViewCell类 类似UITableViewCell类
class CHGGridViewCell: UIControl {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
///创建cell 通过nib名称
class func initWithNibName(nibName:NSString)->CHGGridViewCell {
let nibs = Bundle.main.loadNibNamed(nibName as String, owner: nil, options: nil)
return nibs!.last as! CHGGridViewCell
}
}
| apache-2.0 |
lacyrhoades/GLSlideshow | GLSlideshow/SlideshowView.swift | 1 | 196 | //
// SlideshowView.swift
// GLSlideshow
//
// Created by Lacy Rhoades on 8/12/16.
// Copyright © 2016 Colordeaf. All rights reserved.
//
import GLKit
class SlideshowView: GLKView {
}
| mit |
eoger/firefox-ios | Shared/RollingFileLogger.swift | 14 | 4158 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
//// A rolling file logger that saves to a different log file based on given timestamp.
open class RollingFileLogger: XCGLogger {
public static let TwoMBsInBytes: Int64 = 2 * 100000
fileprivate let sizeLimit: Int64
fileprivate let logDirectoryPath: String?
let fileLogIdentifierPrefix = "com.mozilla.firefox.filelogger."
fileprivate static let DateFormatter: DateFormatter = {
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
return formatter
}()
let root: String
public init(filenameRoot: String, logDirectoryPath: String?, sizeLimit: Int64 = TwoMBsInBytes) {
root = filenameRoot
self.sizeLimit = sizeLimit
self.logDirectoryPath = logDirectoryPath
super.init()
}
/**
Create a new log file with the given timestamp to log events into
:param: date Date for with to start and mark the new log file
*/
open func newLogWithDate(_ date: Date) {
// Don't start a log if we don't have a valid log directory path
if logDirectoryPath == nil {
return
}
if let filename = filenameWithRoot(root, withDate: date) {
remove(destinationWithIdentifier: fileLogIdentifierWithRoot(root))
add(destination: FileDestination(owner: self, writeToFile: filename, identifier: fileLogIdentifierWithRoot(root)))
info("Created file destination for logger with root: \(self.root) and timestamp: \(date)")
} else {
error("Failed to create a new log with root name: \(self.root) and timestamp: \(date)")
}
}
open func deleteOldLogsDownToSizeLimit() {
// Check to see we haven't hit our size limit and if we did, clear out some logs to make room.
while sizeOfAllLogFilesWithPrefix(self.root, exceedsSizeInBytes: sizeLimit) {
deleteOldestLogWithPrefix(self.root)
}
}
open func logFilenamesAndURLs() throws -> [(String, URL)] {
guard let logPath = logDirectoryPath else {
return []
}
let files = try FileManager.default.contentsOfDirectoryAtPath(logPath, withFilenamePrefix: root)
return files.compactMap { filename in
if let url = URL(string: "\(logPath)/\(filename)") {
return (filename, url)
}
return nil
}
}
fileprivate func deleteOldestLogWithPrefix(_ prefix: String) {
if logDirectoryPath == nil {
return
}
do {
let logFiles = try FileManager.default.contentsOfDirectoryAtPath(logDirectoryPath!, withFilenamePrefix: prefix)
if let oldestLogFilename = logFiles.first {
try FileManager.default.removeItem(atPath: "\(logDirectoryPath!)/\(oldestLogFilename)")
}
} catch _ as NSError {
error("Shouldn't get here")
return
}
}
fileprivate func sizeOfAllLogFilesWithPrefix(_ prefix: String, exceedsSizeInBytes threshold: Int64) -> Bool {
guard let path = logDirectoryPath else {
return false
}
let logDirURL = URL(fileURLWithPath: path)
do {
return try FileManager.default.allocatedSizeOfDirectoryAtURL(logDirURL, forFilesPrefixedWith: prefix, isLargerThanBytes: threshold)
} catch let errorValue as NSError {
error("Error determining log directory size: \(errorValue)")
}
return false
}
fileprivate func filenameWithRoot(_ root: String, withDate date: Date) -> String? {
if let dir = logDirectoryPath {
return "\(dir)/\(root).\(RollingFileLogger.DateFormatter.string(from: date)).log"
}
return nil
}
fileprivate func fileLogIdentifierWithRoot(_ root: String) -> String {
return "\(fileLogIdentifierPrefix).\(root)"
}
}
| mpl-2.0 |
benlangmuir/swift | test/decl/var/lazy_properties.swift | 4 | 6681 | // RUN: %target-typecheck-verify-swift -parse-as-library
lazy func lazy_func() {} // expected-error {{'lazy' may only be used on 'var' declarations}} {{1-6=}}
lazy var b = 42 // expected-error {{'lazy' cannot be used on an already-lazy global}} {{1-6=}}
struct S {
lazy static var lazy_global = 42 // expected-error {{'lazy' cannot be used on an already-lazy global}} {{3-8=}}
}
protocol SomeProtocol {
lazy var x : Int // expected-error {{'lazy' cannot be used on a protocol requirement}} {{3-8=}}
// expected-error@-1 {{property in protocol must have explicit { get } or { get set } specifier}} {{19-19= { get <#set#> \}}}
// expected-error@-2 {{lazy properties must have an initializer}}
lazy var y : Int { get } // expected-error {{'lazy' cannot be used on a protocol requirement}} {{3-8=}}
// expected-error@-1 {{'lazy' cannot be used on a computed property}}
// expected-error@-2 {{lazy properties must have an initializer}}
}
class TestClass {
lazy var a = 42
lazy var a1 : Int = 42
lazy let b = 42 // expected-error {{'lazy' cannot be used on a let}} {{3-8=}}
lazy var c : Int { return 42 } // expected-error {{'lazy' cannot be used on a computed property}} {{3-8=}}
// expected-error@-1 {{lazy properties must have an initializer}}
lazy var d : Int // expected-error {{lazy properties must have an initializer}} {{3-8=}}
lazy var (e, f) = (1,2) // expected-error 2{{'lazy' cannot destructure an initializer}} {{3-8=}}
lazy var g = { 0 }() // single-expr closure
lazy var h : Int = { 0 }() // single-expr closure
lazy var i = { () -> Int in return 0 }()+1 // multi-stmt closure
lazy var j : Int = { return 0 }()+1 // multi-stmt closure
lazy var k : Int = { () -> Int in return 0 }()+1 // multi-stmt closure
lazy var l : Int = 42 { // Okay
didSet {}
willSet {}
}
lazy var m : Int = 42 { // Okay
didSet {}
}
lazy var n : Int = 42 {
willSet {} // Okay
}
init() {
lazy var localvar = 42 // Okay
localvar += 1
_ = localvar
}
}
struct StructTest {
lazy var p1 : Int = 42
mutating func f1() -> Int {
return p1
}
// expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
func f2() -> Int {
return p1 // expected-error {{cannot use mutating getter on immutable value: 'self' is immutable}}
}
static func testStructInits() {
let a = StructTest() // default init
let b = StructTest(p1: 42) // Override the lazily init'd value.
_ = a; _ = b
}
}
// <rdar://problem/16889110> capture lists in lazy member properties cannot use self
class CaptureListInLazyProperty {
lazy var closure1 = { [weak self] in return self!.i }
lazy var closure2: () -> Int = { [weak self] in return self!.i }
var i = 42
}
// Crash when initializer expression is type-checked both to infer the
// property type and also as part of the getter
class WeShouldNotReTypeCheckStatements {
lazy var firstCase = {
_ = nil // expected-error{{'nil' requires a contextual type}}
_ = ()
}
lazy var secondCase = {
_ = ()
_ = ()
}
}
protocol MyProtocol {
func f() -> Int
}
struct MyStruct : MyProtocol {
func f() -> Int { return 0 }
}
struct Outer {
static let p: MyProtocol = MyStruct()
struct Inner {
lazy var x = p.f()
lazy var y = {_ = 3}()
// expected-warning@-1 {{variable 'y' inferred to have type '()', which may be unexpected}}
// expected-note@-2 {{add an explicit type annotation to silence this warning}} {{15-15=: ()}}
}
}
// https://github.com/apple/swift/issues/45221
struct Construction {
init(x: Int, y: Int? = 42) { }
}
class Constructor {
lazy var myQ = Construction(x: 3)
}
// Problems with self references
class BaseClass {
var baseInstanceProp = 42
static var baseStaticProp = 42
}
class ReferenceSelfInLazyProperty : BaseClass {
lazy var refs = (i, f())
lazy var trefs: (Int, Int) = (i, f())
lazy var qrefs = (self.i, self.f())
lazy var qtrefs: (Int, Int) = (self.i, self.f())
lazy var crefs = { (i, f()) }()
lazy var ctrefs: (Int, Int) = { (i, f()) }()
lazy var cqrefs = { (self.i, self.f()) }()
lazy var cqtrefs: (Int, Int) = { (self.i, self.f()) }()
lazy var mrefs = { () -> (Int, Int) in return (i, f()) }()
lazy var mtrefs: (Int, Int) = { return (i, f()) }()
lazy var mqrefs = { () -> (Int, Int) in (self.i, self.f()) }()
lazy var mqtrefs: (Int, Int) = { return (self.i, self.f()) }()
lazy var lcqrefs = { [unowned self] in (self.i, self.f()) }()
lazy var lcqtrefs: (Int, Int) = { [unowned self] in (self.i, self.f()) }()
lazy var lmrefs = { [unowned self] () -> (Int, Int) in return (i, f()) }()
lazy var lmtrefs: (Int, Int) = { [unowned self] in return (i, f()) }()
lazy var lmqrefs = { [unowned self] () -> (Int, Int) in (self.i, self.f()) }()
lazy var lmqtrefs: (Int, Int) = { [unowned self] in return (self.i, self.f()) }()
var i = 42
func f() -> Int { return 0 }
lazy var refBaseClassProp = baseInstanceProp
}
class ReferenceStaticInLazyProperty {
lazy var refs1 = i
// expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
lazy var refs2 = f()
// expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
lazy var trefs1: Int = i
// expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
lazy var trefs2: Int = f()
// expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
static var i = 42
static func f() -> Int { return 0 }
}
// Explicit access to the lazy variable storage
class LazyVarContainer {
lazy var foo: Int = {
return 0
}()
func accessLazyStorage() {
$__lazy_storage_$_foo = nil // expected-error {{access to the underlying storage of a lazy property is not allowed}}
print($__lazy_storage_$_foo!) // expected-error {{access to the underlying storage of a lazy property is not allowed}}
_ = $__lazy_storage_$_foo == nil // expected-error {{access to the underlying storage of a lazy property is not allowed}}
}
}
// Make sure we can still access a synthesized variable with the same name as a lazy storage variable
// i.e. $__lazy_storage_$_{property_name} when using property wrapper where the property name is
// '__lazy_storage_$_{property_name}'.
@propertyWrapper
struct Wrapper {
var wrappedValue: Int { 1 }
var projectedValue: Int { 1 }
}
struct PropertyWrapperContainer {
@Wrapper var __lazy_storage_$_foo
func test() {
_ = $__lazy_storage_$_foo // This is okay.
}
}
| apache-2.0 |
benlangmuir/swift | test/Serialization/Inputs/def_async.swift | 7 | 241 | public func doSomethingBig() async -> Int { return 0 }
@_alwaysEmitIntoClient
public func doSerializedAsyncLet() async {
async let _ = ()
}
@_alwaysEmitIntoClient
public func doSerializedAsyncLetTyped() async {
async let _ : () = ()
}
| apache-2.0 |
mozilla-mobile/firefox-ios | Tests/XCUITests/NavigationTest.swift | 2 | 20275 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import XCTest
let website_1 = ["url": "www.mozilla.org", "label": "Internet for people, not profit — Mozilla", "value": "mozilla.org"]
let website_2 = ["url": "www.example.com", "label": "Example", "value": "example", "link": "More information...", "moreLinkLongPressUrl": "http://www.iana.org/domains/example", "moreLinkLongPressInfo": "iana"]
let urlAddons = "addons.mozilla.org"
let urlGoogle = "www.google.com"
let popUpTestUrl = path(forTestPage: "test-popup-blocker.html")
let requestMobileSiteLabel = "Request Mobile Site"
let requestDesktopSiteLabel = "Request Desktop Site"
class NavigationTest: BaseTestCase {
func testNavigation() {
if !iPad() {
waitForExistence(app.buttons["urlBar-cancel"], timeout: 5)
}
navigator.performAction(Action.CloseURLBarOpen)
let urlPlaceholder = "Search or enter address"
XCTAssert(app.textFields["url"].exists)
let defaultValuePlaceholder = app.textFields["url"].placeholderValue!
// Check the url placeholder text and that the back and forward buttons are disabled
XCTAssert(urlPlaceholder == defaultValuePlaceholder)
if iPad() {
XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
app.textFields["url"].tap()
} else {
XCTAssertFalse(app.buttons["TabToolbar.backButton"].isEnabled)
XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled)
}
// Once an url has been open, the back button is enabled but not the forward button
if iPad() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
}
navigator.openURL(path(forTestPage: "test-example.html"))
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "test-example.html")
if iPad() {
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
} else {
XCTAssertTrue(app.buttons["TabToolbar.backButton"].isEnabled)
XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled)
}
// Once a second url is open, back button is enabled but not the forward one till we go back to url_1
navigator.openURL(path(forTestPage: "test-mozilla-org.html"))
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "test-mozilla-org.html")
if iPad() {
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
// Go back to previous visited web site
app.buttons["URLBarView.backButton"].tap()
} else {
XCTAssertTrue(app.buttons["TabToolbar.backButton"].isEnabled)
XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled)
// Go back to previous visited web site
app.buttons["TabToolbar.backButton"].tap()
}
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "test-example.html")
if iPad() {
app.buttons["Forward"].tap()
} else {
// Go forward to next visited web site
waitForExistence(app.buttons["TabToolbar.forwardButton"])
app.buttons["TabToolbar.forwardButton"].tap()
}
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "test-mozilla-org")
}
func testTapSignInShowsFxAFromTour() {
navigator.performAction(Action.CloseURLBarOpen)
waitForTabsButton()
navigator.nowAt(NewTabScreen)
// Open FxAccount from tour option in settings menu and go throughout all the screens there
navigator.goto(Intro_FxASignin)
navigator.performAction(Action.OpenEmailToSignIn)
checkFirefoxSyncScreenShown()
}
func testTapSigninShowsFxAFromSettings() {
navigator.performAction(Action.CloseURLBarOpen)
waitForTabsButton()
navigator.nowAt(NewTabScreen)
navigator.goto(SettingsScreen)
// Open FxAccount from settings menu and check the Sign in to Firefox screen
let signInToFirefoxStaticText = app.tables[AccessibilityIdentifiers.Settings.tableViewController].staticTexts[AccessibilityIdentifiers.Settings.FirefoxAccount.fxaSettingsButton]
signInToFirefoxStaticText.tap()
checkFirefoxSyncScreenShownViaSettings()
// After that it is possible to go back to Settings
let closeButton = app.navigationBars["Client.FxAWebView"].buttons.element(boundBy: 0)
closeButton.tap()
let closeButtonFxView = app.navigationBars[AccessibilityIdentifiers.Settings.FirefoxAccount.fxaNavigationBar].buttons["Settings"]
closeButtonFxView.tap()
}
// Because the Settings menu does not stretch tot the top we need a different function to check if the Firefox Sync screen is shown
private func checkFirefoxSyncScreenShownViaSettings() {
waitForExistence(app.navigationBars[AccessibilityIdentifiers.Settings.FirefoxAccount.fxaNavigationBar], timeout: 20)
app.buttons["EmailSignIn.button"].tap()
waitForExistence(app.webViews.textFields.element(boundBy: 0), timeout: 20)
let email = app.webViews.textFields.element(boundBy: 0)
// Verify the placeholdervalues here for the textFields
let mailPlaceholder = "Enter your email"
let defaultMailPlaceholder = email.placeholderValue!
XCTAssertEqual(mailPlaceholder, defaultMailPlaceholder, "The mail placeholder does not show the correct value")
}
func testTapSignInShowsFxAFromRemoteTabPanel() {
navigator.performAction(Action.CloseURLBarOpen)
waitForTabsButton()
navigator.nowAt(NewTabScreen)
// Open FxAccount from remote tab panel and check the Sign in to Firefox screen
navigator.goto(TabTray)
navigator.performAction(Action.ToggleSyncMode)
app.tables.buttons[AccessibilityIdentifiers.Settings.FirefoxAccount.fxaSettingsButton].tap()
waitForExistence(app.buttons["EmailSignIn.button"], timeout: 10)
app.buttons["EmailSignIn.button"].tap()
checkFirefoxSyncScreenShown()
}
private func checkFirefoxSyncScreenShown() {
// Disable check, page load issues on iOS13.3 sims, issue #5937
waitForExistence(app.webViews.firstMatch, timeout: 20)
}
func testScrollsToTopWithMultipleTabs() {
navigator.goto(TabTray)
navigator.openURL(website_1["url"]!)
waitForValueContains(app.textFields["url"], value: website_1["value"]!)
// Element at the TOP. TBChanged once the web page is correctly shown
let topElement = app.links.staticTexts["Mozilla"].firstMatch
// Element at the BOTTOM
let bottomElement = app.webViews.links.staticTexts["Legal"]
// Scroll to bottom
bottomElement.tap()
waitUntilPageLoad()
if iPad() {
app.buttons["URLBarView.backButton"].tap()
} else {
app.buttons["TabToolbar.backButton"].tap()
}
waitUntilPageLoad()
// Scroll to top
topElement.tap()
waitForExistence(topElement)
}
// Smoketest
func testLongPressLinkOptions() {
navigator.openURL(path(forTestPage: "test-example.html"))
waitForExistence(app.webViews.links[website_2["link"]!], timeout: 30)
app.webViews.links[website_2["link"]!].press(forDuration: 2)
waitForExistence(app.otherElements.collectionViews.element(boundBy: 0), timeout: 5)
XCTAssertTrue(app.buttons["Open in New Tab"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Open in New Private Tab"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Copy Link"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Download Link"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Share Link"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Bookmark Link"].exists, "The option is not shown")
}
func testLongPressLinkOptionsPrivateMode() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(path(forTestPage: "test-example.html"))
waitForExistence(app.webViews.links[website_2["link"]!], timeout: 5)
app.webViews.links[website_2["link"]!].press(forDuration: 2)
waitForExistence(app.collectionViews.staticTexts[website_2["moreLinkLongPressUrl"]!], timeout: 3)
XCTAssertFalse(app.buttons["Open in New Tab"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Open in New Private Tab"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Copy Link"].exists, "The option is not shown")
XCTAssertTrue(app.buttons["Download Link"].exists, "The option is not shown")
}
// Only testing Share and Copy Link, the other two options are already covered in other tests
func testCopyLink() {
longPressLinkOptions(optionSelected: "Copy Link")
navigator.goto(NewTabScreen)
app.textFields["url"].press(forDuration: 2)
waitForExistence(app.tables["Context Menu"])
app.tables.otherElements[ImageIdentifiers.paste].tap()
app.buttons["Go"].tap()
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: website_2["moreLinkLongPressInfo"]!)
}
func testCopyLinkPrivateMode() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
longPressLinkOptions(optionSelected: "Copy Link")
navigator.goto(NewTabScreen)
waitForExistence(app.textFields["url"])
app.textFields["url"].press(forDuration: 2)
app.tables.otherElements[ImageIdentifiers.paste].tap()
app.buttons["Go"].tap()
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: website_2["moreLinkLongPressInfo"]!)
}
func testLongPressOnAddressBar() {
// This test is for populated clipboard only so we need to make sure there's something in Pasteboard
app.textFields["address"].typeText("www.google.com")
// Tapping two times when the text is not selected will reveal the menu
app.textFields["address"].tap()
waitForExistence(app.textFields["address"])
app.textFields["address"].tap()
waitForExistence(app.menuItems["Select All"])
XCTAssertTrue(app.menuItems["Select All"].exists)
XCTAssertTrue(app.menuItems["Select"].exists)
// Tap on Select All option and make sure Copy, Cut, Paste, and Look Up are shown
app.menuItems["Select All"].tap()
waitForExistence(app.menuItems["Copy"])
if iPad() {
XCTAssertTrue(app.menuItems["Copy"].exists)
XCTAssertTrue(app.menuItems["Cut"].exists)
XCTAssertTrue(app.menuItems["Look Up"].exists)
XCTAssertTrue(app.menuItems["Share…"].exists)
} else {
XCTAssertTrue(app.menuItems["Copy"].exists)
XCTAssertTrue(app.menuItems["Cut"].exists)
XCTAssertTrue(app.menuItems["Look Up"].exists)
}
app.textFields["address"].typeText("\n")
waitUntilPageLoad()
waitForNoExistence(app.staticTexts["XCUITests-Runner pasted from Fennec"])
app.textFields["url"].press(forDuration: 3)
app.tables.otherElements[ImageIdentifiers.copyLink].tap()
sleep(2)
app.textFields["url"].tap()
// Since the textField value appears all selected first time is clicked
// this workaround is necessary
waitForNoExistence(app.staticTexts["XCUITests-Runner pasted from Fennec"])
app.textFields["address"].tap()
waitForExistence(app.menuItems["Copy"])
if iPad() {
XCTAssertTrue(app.menuItems["Copy"].exists)
XCTAssertTrue(app.menuItems["Cut"].exists)
XCTAssertTrue(app.menuItems["Look Up"].exists)
XCTAssertTrue(app.menuItems["Share…"].exists)
XCTAssertTrue(app.menuItems["Paste & Go"].exists)
XCTAssertTrue(app.menuItems["Paste"].exists)
} else {
XCTAssertTrue(app.menuItems["Copy"].exists)
XCTAssertTrue(app.menuItems["Cut"].exists)
XCTAssertTrue(app.menuItems["Look Up"].exists)
}
}
private func longPressLinkOptions(optionSelected: String) {
navigator.openURL(path(forTestPage: "test-example.html"))
waitUntilPageLoad()
app.webViews.links[website_2["link"]!].press(forDuration: 2)
app.buttons[optionSelected].tap()
}
func testDownloadLink() {
longPressLinkOptions(optionSelected: "Download Link")
waitForExistence(app.tables["Context Menu"])
XCTAssertTrue(app.tables["Context Menu"].otherElements["download"].exists)
app.tables["Context Menu"].otherElements["download"].tap()
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
waitForExistence(app.tables["DownloadsTable"])
// There should be one item downloaded. It's name and size should be shown
let downloadedList = app.tables["DownloadsTable"].cells.count
XCTAssertEqual(downloadedList, 1, "The number of items in the downloads table is not correct")
XCTAssertTrue(app.tables.cells.staticTexts["reserved.html"].exists)
// Tap on the just downloaded link to check that the web page is loaded
app.tables.cells.staticTexts["reserved.html"].tap()
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "reserved.html")
}
func testShareLink() {
longPressLinkOptions(optionSelected: "Share Link")
waitForExistence(app.buttons["Copy"], timeout: 3)
XCTAssertTrue(app.buttons["Copy"].exists, "The share menu is not shown")
}
func testShareLinkPrivateMode() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
longPressLinkOptions(optionSelected: "Share Link")
waitForExistence(app.buttons["Copy"], timeout: 3)
XCTAssertTrue(app.buttons["Copy"].exists, "The share menu is not shown")
}
// Smoketest
func testPopUpBlocker() {
waitForExistence(app.buttons["urlBar-cancel"], timeout: 15)
navigator.performAction(Action.CloseURLBarOpen)
// Check that it is enabled by default
navigator.nowAt(BrowserTab)
waitForExistence(app.buttons["TabToolbar.menuButton"], timeout: 10)
navigator.goto(SettingsScreen)
waitForExistence(app.tables["AppSettingsTableViewController.tableView"])
let switchBlockPopUps = app.tables.cells.switches["blockPopups"]
let switchValue = switchBlockPopUps.value!
XCTAssertEqual(switchValue as? String, "1")
// Check that there are no pop ups
navigator.openURL(popUpTestUrl)
waitForValueContains(app.textFields["url"], value: "blocker.html")
waitForExistence(app.webViews.staticTexts["Blocked Element"])
let numTabs = app.buttons["Show Tabs"].value
XCTAssertEqual("1", numTabs as? String, "There should be only on tab")
// Now disable the Block PopUps option
navigator.goto(BrowserTabMenu)
navigator.goto(SettingsScreen)
waitForExistence(switchBlockPopUps, timeout: 5)
switchBlockPopUps.tap()
let switchValueAfter = switchBlockPopUps.value!
XCTAssertEqual(switchValueAfter as? String, "0")
// Check that now pop ups are shown, two sites loaded
navigator.openURL(popUpTestUrl)
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "example.com")
let numTabsAfter = app.buttons["Show Tabs"].value
XCTAssertNotEqual("1", numTabsAfter as? String, "Several tabs are open")
}
// Smoketest
func testSSL() {
waitForExistence(app.buttons["urlBar-cancel"], timeout: 15)
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.openURL("https://expired.badssl.com/")
waitForExistence(app.buttons["Advanced"], timeout: 10)
app.buttons["Advanced"].tap()
waitForExistence(app.links["Visit site anyway"])
app.links["Visit site anyway"].tap()
waitForExistence(app.webViews.otherElements["expired.badssl.com"], timeout: 10)
XCTAssertTrue(app.webViews.otherElements["expired.badssl.com"].exists)
}
// In this test, the parent window opens a child and in the child it creates a fake link 'link-created-by-parent'
func testWriteToChildPopupTab() {
navigator.performAction(Action.CloseURLBarOpen)
waitForTabsButton()
navigator.nowAt(NewTabScreen)
navigator.goto(SettingsScreen)
waitForExistence(app.tables["AppSettingsTableViewController.tableView"])
let switchBlockPopUps = app.tables.cells.switches["blockPopups"]
switchBlockPopUps.tap()
let switchValueAfter = switchBlockPopUps.value!
XCTAssertEqual(switchValueAfter as? String, "0")
navigator.goto(HomePanelsScreen)
navigator.openURL(path(forTestPage: "test-mozilla-org.html"))
waitUntilPageLoad()
navigator.openURL(path(forTestPage: "test-window-opener.html"))
waitForExistence(app.links["link-created-by-parent"], timeout: 10)
}
// Smoketest
func testVerifyBrowserTabMenu() {
waitForExistence(app.buttons["urlBar-cancel"], timeout: 15)
navigator.performAction(Action.CloseURLBarOpen)
waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 5)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
waitForExistence(app.tables["Context Menu"])
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.bookmarks].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.history].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.downloads].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.readingList].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.key].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.sync].exists)
// XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.noImageMode].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.nightMode].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.whatsNew].exists)
XCTAssertTrue(app.tables.otherElements[ImageIdentifiers.settings].exists)
// TODO: Add new options added [Customize home page, new tab, help]
// Customize home page, help and whatsNew are only there when we are on the homepage menu
}
// Smoketest
func testURLBar() {
let urlBar = app.textFields["url"]
waitForExistence(urlBar, timeout: 15)
urlBar.tap()
let addressBar = app.textFields["address"]
XCTAssertTrue(addressBar.value(forKey: "hasKeyboardFocus") as? Bool ?? false)
// These instances are false positives of the swiftlint configuration
// swiftlint:disable empty_count
XCTAssert(app.keyboards.count > 0, "The keyboard is not shown")
app.typeText("example.com\n")
// waitUntilPageLoad()
waitForValueContains(urlBar, value: "example.com/")
XCTAssertFalse(app.keyboards.count > 0, "The keyboard is shown")
// swiftlint:enable empty_count
}
}
| mpl-2.0 |
google/iosched-ios | Source/IOsched/Common/CollectionViewHeaderCell.swift | 1 | 1363 | //
// Copyright (c) 2016 Google 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 UIKit
import MaterialComponents
class CollectionViewHeaderCell: UICollectionViewCell {
var textLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
textLabel = UILabel(frame: CGRect(x: 20, y: 10, width: frame.size.width - 40, height: frame.size.height/3))
textLabel.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .subheadline)
textLabel.alpha = MDCTypography.subheadFontOpacity()
textLabel.textAlignment = .natural
textLabel.enableAdjustFontForContentSizeCategory()
textLabel.lineBreakMode = .byTruncatingTail
contentView.addSubview(textLabel)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
Swinject/SwinjectMVVMExample | Carthage/Checkouts/SwinjectStoryboard/Carthage/Checkouts/Swinject/Carthage/Checkouts/Quick/Package.swift | 5 | 815 | import PackageDescription
let package = Package(
name: "Quick",
// TODO: Once the `test` command has been implemented in the Swift Package Manager, this should be changed to
// be `testDependencies:` instead. For now it has to be done like this for the library to get linked with the test targets.
// See: https://github.com/apple/swift-evolution/blob/master/proposals/0019-package-manager-testing.md
dependencies: [
.Package(url: "https://github.com/norio-nomura/Nimble", "5.0.0-alpha.30p6")
],
exclude: [
"Sources/QuickObjectiveC",
"Tests/QuickTests/QuickFocusedTests/FocusedTests+ObjC.m",
"Tests/QuickTests/QuickTests/FunctionalTests/ObjC",
"Tests/QuickTests/QuickTests/Helpers",
"Tests/QuickTests/QuickTests/QuickConfigurationTests.m",
]
)
| mit |
li1024316925/Swift-TimeMovie | Swift-TimeMovie/Swift-TimeMovie/RatingView.swift | 1 | 2043 | //
// RatingView.swift
// SwiftTimeMovie
//
// Created by DahaiZhang on 16/10/18.
// Copyright © 2016年 LLQ. All rights reserved.
//
import UIKit
class RatingView: UIView {
var yellowView:UIView?
//评分属性,复写set方法,在赋值完成后调用
var rating:CGFloat?{
didSet{
yellowView?.frame = CGRect(x: 0, y: 0, width: frame.size.width * rating! / 10.0, height: frame.size.height)
}
}
override func awakeFromNib() {
loadSubViews()
}
func loadSubViews() -> Void {
//获取图片
let gray = UIImage(named: "gray")!
let yellow = UIImage(named: "yellow")!
//图片大小
let imgHeight = gray.size.height
let imgWidth = gray.size.width * 5.0
//创建视图
let grayView = UIView(frame: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight))
yellowView = UIView(frame: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight))
//设置背景图片,以平铺的方式
grayView.backgroundColor = UIColor.init(patternImage: gray)
yellowView?.backgroundColor = UIColor.init(patternImage: yellow)
self.addSubview(grayView)
self.addSubview(yellowView!)
//获取View的frame之前,要调用此方法,否则获取不到
//立即进行布局
layoutIfNeeded()
//计算放大倍数
let scaleX = frame.size.width/imgWidth
let scaleY = frame.size.height/imgHeight
//调整大小
grayView.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
yellowView?.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
//重定视图位置
grayView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
yellowView?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
}
}
| apache-2.0 |
sydvicious/firefox-ios | Client/Frontend/UIConstants.swift | 6 | 2596 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public struct UIConstants {
static let AboutHomeURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/home/#panel=0")!
static let AppBackgroundColor = UIColor.blackColor()
static let ToolbarHeight: CGFloat = 44
static let DefaultRowHeight: CGFloat = 58
static let DefaultPadding: CGFloat = 10
static let DefaultMediumFontSize: CGFloat = 14
static let DefaultMediumFont = UIFont.systemFontOfSize(DefaultMediumFontSize, weight: UIFontWeightRegular)
static let DefaultMediumBoldFont = UIFont.boldSystemFontOfSize(DefaultMediumFontSize)
static let DefaultSmallFontSize: CGFloat = 11
static let DefaultSmallFont = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightRegular)
static let DefaultSmallFontBold = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightBold)
static let DefaultStandardFontSize: CGFloat = 17
static let DefaultStandardFontBold = UIFont.boldSystemFontOfSize(DefaultStandardFontSize)
// These highlight colors are currently only used on Snackbar buttons when they're pressed
static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9)
static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0)
static let PanelBackgroundColor = DeviceInfo.isBlurSupported() ? UIColor.whiteColor().colorWithAlphaComponent(0.6) : UIColor.whiteColor()
static let SeparatorColor = UIColor(rgb: 0xcccccc)
static let HighlightBlue = UIColor(red:0.3, green:0.62, blue:1, alpha:1)
static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0)
static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.25)
static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1)
// settings
static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0)
static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0)
static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0)
static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4)
// Firefox Orange
static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1)
} | mpl-2.0 |
ntnmrndn/R.swift | Sources/RswiftCore/ResourceTypes/ResourceFile.swift | 4 | 1149 | //
// ResourceFile.swift
// R.swift
//
// Created by Mathijs Kadijk on 09-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
struct ResourceFile {
// These are all extensions of resources that are passed to some special compiler step and not directly available runtime
static let unsupportedExtensions: Set<String> = [
AssetFolder.supportedExtensions,
Storyboard.supportedExtensions,
Nib.supportedExtensions,
LocalizableStrings.supportedExtensions,
]
.reduce([]) { $0.union($1) }
let fullname: String
let filename: String
let pathExtension: String
init(url: URL) throws {
pathExtension = url.pathExtension
if ResourceFile.unsupportedExtensions.contains(pathExtension) {
throw ResourceParsingError.unsupportedExtension(givenExtension: pathExtension, supportedExtensions: ["*"])
}
let fullname = url.lastPathComponent
guard let filename = url.filename else {
throw ResourceParsingError.parsingFailed("Couldn't extract filename from URL: \(url)")
}
self.fullname = fullname
self.filename = filename
}
}
| mit |
VojtaStavik/ProtocolUI | ProtocolUITests/TrackTintColorProtocolTest.swift | 1 | 1037 | //
// TrackTintColorProtocolTest.swift
// ProtocolUI
//
// Created by STRV on 20/08/15.
// Copyright © 2015 Vojta Stavik. All rights reserved.
//
import XCTest
@testable import ProtocolUI
extension TrackTintColor {
var pTrackTintColor : UIColor { return TrackTintColorProtocolTest.testValue }
}
class TrackTintColorProtocolTest: XCTestCase {
typealias CurrentTestProtocol = TrackTintColor
typealias CurrentTestValueType = UIColor
static let testValue : CurrentTestValueType = UIColor(red: 0.01, green: 0.99, blue: 0.02, alpha: 0.98)
func testUIProgressView() {
class TestView : UIProgressView, CurrentTestProtocol { }
let test1 = TestView()
test1.applyProtocolUIAppearance()
XCTAssertEqual(test1.trackTintColor, self.dynamicType.testValue)
let test2 = TestView()
test2.prepareForInterfaceBuilder()
XCTAssertEqual(test2.trackTintColor, self.dynamicType.testValue)
}
} | mit |
ShenghaiWang/FolioReaderKit | Source/FolioReaderPage.swift | 1 | 20128 | //
// FolioReaderPage.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 10/04/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import SafariServices
import MenuItemKit
import JSQWebViewController
/// Protocol which is used from `FolioReaderPage`s.
@objc public protocol FolioReaderPageDelegate: class {
/**
Notify that the page will be loaded. Note: The webview content itself is already loaded at this moment. But some java script operations like the adding of class based on click listeners will happen right after this method. If you want to perform custom java script before this happens this method is the right choice. If you want to modify the html content (and not run java script) you have to use `htmlContentForPage()` from the `FolioReaderCenterDelegate`.
- parameter page: The loaded page
*/
@objc optional func pageWillLoad(_ page: FolioReaderPage)
/**
Notifies that page did load. A page load doesn't mean that this page is displayed right away, use `pageDidAppear` to get informed about the appearance of a page.
- parameter page: The loaded page
*/
@objc optional func pageDidLoad(_ page: FolioReaderPage)
}
open class FolioReaderPage: UICollectionViewCell, UIWebViewDelegate, UIGestureRecognizerDelegate {
weak var delegate: FolioReaderPageDelegate?
/// The index of the current page. Note: The index start at 1!
open var pageNumber: Int!
public var webView: FolioReaderWebView!
fileprivate var colorView: UIView!
fileprivate var shouldShowBar = true
fileprivate var menuIsVisible = false
// MARK: - View life cicle
override public init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
// TODO: Put the notification name in a Constants file
NotificationCenter.default.addObserver(self, selector: #selector(refreshPageMode), name: NSNotification.Name(rawValue: "needRefreshPageMode"), object: nil)
if webView == nil {
webView = FolioReaderWebView(frame: webViewFrame())
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.dataDetectorTypes = .link
webView.scrollView.showsVerticalScrollIndicator = false
webView.scrollView.showsHorizontalScrollIndicator = false
webView.backgroundColor = UIColor.clear
self.contentView.addSubview(webView)
}
webView.delegate = self
if colorView == nil {
colorView = UIView()
colorView.backgroundColor = readerConfig.nightModeBackground
webView.scrollView.addSubview(colorView)
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
tapGestureRecognizer.delegate = self
webView.addGestureRecognizer(tapGestureRecognizer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("storyboards are incompatible with truth and beauty")
}
deinit {
webView.scrollView.delegate = nil
NotificationCenter.default.removeObserver(self)
}
override open func layoutSubviews() {
super.layoutSubviews()
webView.setupScrollDirection()
webView.frame = webViewFrame()
}
func webViewFrame() -> CGRect {
guard readerConfig.hideBars == false else {
return bounds
}
let statusbarHeight = UIApplication.shared.statusBarFrame.size.height
let navBarHeight = FolioReader.shared.readerCenter?.navigationController?.navigationBar.frame.size.height ?? CGFloat(0)
let navTotal = readerConfig.shouldHideNavigationOnTap ? 0 : statusbarHeight + navBarHeight
let paddingTop: CGFloat = 20
let paddingBottom: CGFloat = 30
let paddingleft: CGFloat = 40
let paddingright: CGFloat = 40
return CGRect(
x: bounds.origin.x + paddingleft,
y: isDirection(bounds.origin.y + navTotal, bounds.origin.y + navTotal + paddingTop),
width: bounds.width - paddingleft - paddingright,
height: isDirection(bounds.height - navTotal, bounds.height - navTotal - paddingTop - paddingBottom)
)
}
func loadHTMLString(_ htmlContent: String!, baseURL: URL!) {
// Insert the stored highlights to the HTML
let tempHtmlContent = htmlContentWithInsertHighlights(htmlContent)
// Load the html into the webview
webView.alpha = 0
webView.loadHTMLString(tempHtmlContent, baseURL: baseURL)
}
func load(data: Data, mimeType: String, textEncodingName: String, baseURL: URL) {
//need right mime type to make some epub file to be rendered right
webView.alpha = 0
webView.load(data, mimeType: mimeType, textEncodingName: textEncodingName, baseURL: baseURL)
}
// MARK: - Highlights
fileprivate func htmlContentWithInsertHighlights(_ htmlContent: String) -> String {
var tempHtmlContent = htmlContent as NSString
// Restore highlights
let highlights = Highlight.allByBookId((kBookId as NSString).deletingPathExtension, andPage: pageNumber as NSNumber?)
if highlights.count > 0 {
for item in highlights {
let style = HighlightStyle.classForStyle(item.type)
let tag = "<highlight id=\"\(item.highlightId!)\" onclick=\"callHighlightURL(this);\" class=\"\(style)\">\(item.content!)</highlight>"
var locator = item.contentPre + item.content
locator += item.contentPost
locator = Highlight.removeSentenceSpam(locator) /// Fix for Highlights
let range: NSRange = tempHtmlContent.range(of: locator, options: .literal)
if range.location != NSNotFound {
let newRange = NSRange(location: range.location + item.contentPre.characters.count, length: item.content.characters.count)
tempHtmlContent = tempHtmlContent.replacingCharacters(in: newRange, with: tag) as NSString
}
else {
print("highlight range not found")
}
}
}
return tempHtmlContent as String
}
// MARK: - UIWebView Delegate
open func webViewDidFinishLoad(_ webView: UIWebView) {
guard let webView = webView as? FolioReaderWebView else {
return
}
delegate?.pageWillLoad?(self)
// Add the custom class based onClick listener
self.setupClassBasedOnClickListeners()
refreshPageMode()
if readerConfig.enableTTS && !book.hasAudio() {
webView.js("wrappingSentencesWithinPTags()")
if let audioPlayer = FolioReader.shared.readerAudioPlayer , audioPlayer.isPlaying() {
audioPlayer.readCurrentSentence()
}
}
let direction: ScrollDirection = FolioReader.needsRTLChange ? .positive() : .negative()
if pageScrollDirection == direction && readerConfig.scrollDirection != .horizontalWithVerticalContent {
scrollPageToBottom()
}
UIView.animate(withDuration: 0.2, animations: {webView.alpha = 1}, completion: { finished in
webView.isColors = false
self.webView.createMenu(options: false)
})
delegate?.pageDidLoad?(self)
}
open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
guard
let webView = webView as? FolioReaderWebView,
let scheme = request.url?.scheme else {
return true
}
guard let url = request.url else { return false }
if scheme == "highlight" {
shouldShowBar = false
guard let decoded = url.absoluteString.removingPercentEncoding else { return false }
let rect = CGRectFromString(decoded.substring(from: decoded.index(decoded.startIndex, offsetBy: 12)))
webView.createMenu(options: true)
webView.setMenuVisible(true, andRect: rect)
menuIsVisible = true
return false
} else if scheme == "play-audio" {
guard let decoded = url.absoluteString.removingPercentEncoding else { return false }
let playID = decoded.substring(from: decoded.index(decoded.startIndex, offsetBy: 13))
let chapter = FolioReader.shared.readerCenter?.getCurrentChapter()
let href = chapter?.href ?? ""
FolioReader.shared.readerAudioPlayer?.playAudio(href, fragmentID: playID)
return false
} else if scheme == "file" {
let anchorFromURL = url.fragment
// Handle internal url
if (url.path as NSString).pathExtension != "" {
let base = (book.opfResource.href as NSString).deletingLastPathComponent
let path = url.path
let splitedPath = path.components(separatedBy: base.isEmpty ? kBookId : base)
// Return to avoid crash
if splitedPath.count <= 1 || splitedPath[1].isEmpty {
return true
}
let href = splitedPath[1].trimmingCharacters(in: CharacterSet(charactersIn: "/"))
let hrefPage = (FolioReader.shared.readerCenter?.findPageByHref(href) ?? 0) + 1
if hrefPage == pageNumber {
// Handle internal #anchor
if anchorFromURL != nil {
handleAnchor(anchorFromURL!, avoidBeginningAnchors: false, animated: true)
return false
}
} else {
FolioReader.shared.readerCenter?.changePageWith(href: href, animated: true)
}
return false
}
// Handle internal #anchor
if anchorFromURL != nil {
handleAnchor(anchorFromURL!, avoidBeginningAnchors: false, animated: true)
return false
}
return true
} else if scheme == "mailto" {
print("Email")
return true
} else if url.absoluteString != "about:blank" && scheme.contains("http") && navigationType == .linkClicked {
if #available(iOS 9.0, *) {
let safariVC = SFSafariViewController(url: request.url!)
safariVC.view.tintColor = readerConfig.tintColor
FolioReader.shared.readerCenter?.present(safariVC, animated: true, completion: nil)
} else {
let webViewController = WebViewController(url: request.url!)
let nav = UINavigationController(rootViewController: webViewController)
nav.view.tintColor = readerConfig.tintColor
FolioReader.shared.readerCenter?.present(nav, animated: true, completion: nil)
}
return false
} else {
// Check if the url is a custom class based onClick listerner
var isClassBasedOnClickListenerScheme = false
for listener in readerConfig.classBasedOnClickListeners {
if
(scheme == listener.schemeName),
let absoluteURLString = request.url?.absoluteString,
let range = absoluteURLString.range(of: "/clientX=") {
let baseURL = absoluteURLString.substring(to: range.lowerBound)
let positionString = absoluteURLString.substring(from: range.lowerBound)
if let point = getEventTouchPoint(fromPositionParameterString: positionString) {
let attributeContentString = (baseURL.replacingOccurrences(of: "\(scheme)://", with: "").removingPercentEncoding)
// Call the on click action block
listener.onClickAction(attributeContentString, point)
// Mark the scheme as class based click listener scheme
isClassBasedOnClickListenerScheme = true
}
}
}
if isClassBasedOnClickListenerScheme == false {
// Try to open the url with the system if it wasn't a custom class based click listener
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
return false
}
} else {
return false
}
}
return true
}
fileprivate func getEventTouchPoint(fromPositionParameterString positionParameterString: String) -> CGPoint? {
// Remove the parameter names: "/clientX=188&clientY=292" -> "188&292"
var positionParameterString = positionParameterString.replacingOccurrences(of: "/clientX=", with: "")
positionParameterString = positionParameterString.replacingOccurrences(of: "clientY=", with: "")
// Separate both position values into an array: "188&292" -> [188],[292]
let positionStringValues = positionParameterString.components(separatedBy: "&")
// Multiply the raw positions with the screen scale and return them as CGPoint
if
positionStringValues.count == 2,
let xPos = Int(positionStringValues[0]),
let yPos = Int(positionStringValues[1]) {
return CGPoint(x: xPos, y: yPos)
}
return nil
}
// MARK: Gesture recognizer
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.view is FolioReaderWebView {
if otherGestureRecognizer is UILongPressGestureRecognizer {
if UIMenuController.shared.isMenuVisible {
webView.setMenuVisible(false)
}
return false
}
return true
}
return false
}
open func handleTapGesture(_ recognizer: UITapGestureRecognizer) {
// webView.setMenuVisible(false)
if let _navigationController = FolioReader.shared.readerCenter?.navigationController , _navigationController.isNavigationBarHidden {
let menuIsVisibleRef = menuIsVisible
let selected = webView.js("getSelectedText()")
if selected == nil || selected!.characters.count == 0 {
let seconds = 0.4
let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds
let dispatchTime = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
if self.shouldShowBar && !menuIsVisibleRef {
FolioReader.shared.readerCenter?.toggleBars()
}
self.shouldShowBar = true
})
}
} else if readerConfig.shouldHideNavigationOnTap == true {
FolioReader.shared.readerCenter?.hideBars()
}
// Reset menu
menuIsVisible = false
}
// MARK: - Public scroll postion setter
/**
Scrolls the page to a given offset
- parameter offset: The offset to scroll
- parameter animated: Enable or not scrolling animation
*/
open func scrollPageToOffset(_ offset: CGFloat, animated: Bool) {
let pageOffsetPoint = isDirection(CGPoint(x: 0, y: offset), CGPoint(x: offset, y: 0))
webView.scrollView.setContentOffset(pageOffsetPoint, animated: animated)
}
/**
Scrolls the page to bottom
*/
open func scrollPageToBottom() {
let bottomOffset = isDirection(
CGPoint(x: 0, y: webView.scrollView.contentSize.height - webView.scrollView.bounds.height),
CGPoint(x: webView.scrollView.contentSize.width - webView.scrollView.bounds.width, y: 0),
CGPoint(x: webView.scrollView.contentSize.width - webView.scrollView.bounds.width, y: 0)
)
if bottomOffset.forDirection() >= 0 {
DispatchQueue.main.async(execute: {
self.webView.scrollView.setContentOffset(bottomOffset, animated: false)
})
}
}
/**
Handdle #anchors in html, get the offset and scroll to it
- parameter anchor: The #anchor
- parameter avoidBeginningAnchors: Sometimes the anchor is on the beggining of the text, there is not need to scroll
- parameter animated: Enable or not scrolling animation
*/
open func handleAnchor(_ anchor: String, avoidBeginningAnchors: Bool, animated: Bool) {
if !anchor.isEmpty {
let offset = getAnchorOffset(anchor)
switch readerConfig.scrollDirection {
case .vertical, .defaultVertical:
let isBeginning = offset < frame.forDirection()/2
if !avoidBeginningAnchors {
scrollPageToOffset(offset, animated: animated)
} else if avoidBeginningAnchors && !isBeginning {
scrollPageToOffset(offset, animated: animated)
}
case .horizontal, .horizontalWithVerticalContent:
scrollPageToOffset(offset, animated: animated)
}
}
}
// MARK: Helper
/**
Get the #anchor offset in the page
- parameter anchor: The #anchor id
- returns: The element offset ready to scroll
*/
func getAnchorOffset(_ anchor: String) -> CGFloat {
let horizontal = readerConfig.scrollDirection == .horizontal
if let strOffset = webView.js("getAnchorOffset('\(anchor)', \(horizontal.description))") {
return CGFloat((strOffset as NSString).floatValue)
}
return CGFloat(0)
}
// MARK: Mark ID
/**
Audio Mark ID - marks an element with an ID with the given class and scrolls to it
- parameter ID: The ID
*/
func audioMarkID(_ ID: String) {
guard let currentPage = FolioReader.shared.readerCenter?.currentPage else { return }
currentPage.webView.js("audioMarkID('\(book.playbackActiveClass())','\(ID)')")
}
// MARK: UIMenu visibility
override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if UIMenuController.shared.menuItems?.count == 0 {
webView.isColors = false
webView.createMenu(options: false)
}
if !webView.isShare && !webView.isColors {
if let result = webView.js("getSelectedText()") , result.components(separatedBy: " ").count == 1 {
webView.isOneWord = true
webView.createMenu(options: false)
} else {
webView.isOneWord = false
}
}
return super.canPerformAction(action, withSender: sender)
}
// MARK: ColorView fix for horizontal layout
func refreshPageMode() {
if FolioReader.nightMode {
// omit create webView and colorView
let script = "document.documentElement.offsetHeight"
let contentHeight = webView.stringByEvaluatingJavaScript(from: script)
let frameHeight = webView.frame.height
let lastPageHeight = frameHeight * CGFloat(webView.pageCount) - CGFloat(Double(contentHeight!)!)
colorView.frame = CGRect(x: webView.frame.width * CGFloat(webView.pageCount-1), y: webView.frame.height - lastPageHeight, width: webView.frame.width, height: lastPageHeight)
} else {
colorView.frame = CGRect.zero
}
}
// MARK: - Class based click listener
fileprivate func setupClassBasedOnClickListeners() {
for listener in readerConfig.classBasedOnClickListeners {
self.webView.js("addClassBasedOnClickListener(\"\(listener.schemeName)\", \"\(listener.querySelector)\", \"\(listener.attributeName)\", \"\(listener.selectAll)\")");
}
}
// MARK: - Public Java Script injection
/**
Runs a JavaScript script and returns it result. The result of running the JavaScript script passed in the script parameter, or nil if the script fails.
- returns: The result of running the JavaScript script passed in the script parameter, or nil if the script fails.
*/
open func performJavaScript(_ javaScriptCode: String) -> String? {
return webView.js(javaScriptCode)
}
}
| bsd-3-clause |
touchopia/HackingWithSwift | project1/Project1/DetailViewController.swift | 1 | 1006 | //
// DetailViewController.swift
// Project1
//
// Created by TwoStraws on 12/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var selectedImage: String?
override func viewDidLoad() {
super.viewDidLoad()
title = selectedImage
if let imageToLoad = selectedImage {
imageView.image = UIImage(named: imageToLoad)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| unlicense |
harlanhaskins/swift | test/Driver/PrivateDependencies/chained-private-after-multiple-nominal-members-fine.swift | 1 | 1629 | /// other --> main ==> yet-another
/// other ==>+ main ==> yet-another
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/chained-private-after-multiple-nominal-members-fine/* %t
// RUN: touch -t 201401240005 %t/*.swift
// Generate the build record...
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v
// ...then reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/chained-private-after-multiple-nominal-members-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST-NOT: Handled
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./yet-another.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND-DAG: Handled other.swift
// CHECK-SECOND-DAG: Handled main.swift
// CHECK-SECOND-DAG: Handled yet-another.swift
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.