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 |
---|---|---|---|---|---|
intelygenz/NetClient-iOS | URLSession/NetURLSessionDelegate.swift | 1 | 5296 | //
// NetURLSessionDelegate.swift
// Net
//
// Created by Alex Rupérez on 17/3/17.
//
//
import Foundation
class NetURLSessionDelegate: NSObject {
weak var netURLSession: NetURLSession?
final var tasks = [URLSessionTask: NetTask]()
init(_ urlSession: NetURLSession) {
netURLSession = urlSession
super.init()
}
func add(_ task: URLSessionTask, _ netTask: NetTask?) {
tasks[task] = netTask
}
deinit {
tasks.removeAll()
netURLSession = nil
}
}
extension NetURLSessionDelegate: URLSessionDelegate {}
extension NetURLSessionDelegate: URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
handle(challenge, tasks[task], completion: completionHandler)
}
@available(iOS 10.0, tvOS 10.0, watchOS 3.0, macOS 10.12, *)
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting taskMetrics: URLSessionTaskMetrics) {
if let netTask = tasks[task] {
netTask.metrics = NetTaskMetrics(taskMetrics, request: netTask.request, response: netTask.response)
tasks[task] = nil
}
}
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
func urlSession(_ session: URLSession, task: URLSessionTask, willBeginDelayedRequest request: URLRequest, completionHandler: @escaping (URLSession.DelayedRequestDisposition, URLRequest?) -> Void) {
completionHandler(.continueLoading, nil)
}
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
if let netTask = tasks[task] {
netTask.state = .waitingForConnectivity
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let netTask = tasks[task] {
let netError = netURLSession?.netError(error, netTask.response?.responseObject, task.response)
netURLSession?.process(netTask, netTask.response, netError)
tasks[task] = nil
}
}
}
extension NetURLSessionDelegate: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let netTask = tasks[dataTask] {
guard let response = netTask.response, var oldData = try? response.object() as Data else {
tasks[dataTask]?.response = netURLSession?.netResponse(dataTask.response, netTask, data)
return
}
tasks[dataTask]?.response = netURLSession?.netResponse(dataTask.response, netTask, oldData.append(data))
}
}
}
extension NetURLSessionDelegate: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
}
@available(iOS 9.0, *)
extension NetURLSessionDelegate: URLSessionStreamDelegate {}
extension NetURLSessionDelegate {
func handle(_ challenge: URLAuthenticationChallenge, _ netTask: NetTask? = nil, completion: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
guard let authChallenge = netURLSession?.authChallenge else {
guard challenge.previousFailureCount == 0 else {
challenge.sender?.cancel(challenge)
if let realm = challenge.protectionSpace.realm {
print(realm)
print(challenge.protectionSpace.authenticationMethod)
}
completion(.cancelAuthenticationChallenge, nil)
return
}
var credential: URLCredential? = challenge.proposedCredential
if credential?.hasPassword != true, challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest, let request = netTask?.request {
switch request.authorization {
case .basic(let user, let password):
credential = URLCredential(user: user, password: password, persistence: .forSession)
default:
break
}
}
if credential == nil, challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust {
let host = challenge.protectionSpace.host
if let policy = netURLSession?.serverTrust[host] {
if policy.evaluate(serverTrust, host: host) {
credential = URLCredential(trust: serverTrust)
} else {
credential = nil
}
} else {
credential = URLCredential(trust: serverTrust)
}
}
completion(credential != nil ? .useCredential : .cancelAuthenticationChallenge, credential)
return
}
authChallenge(challenge, completion)
}
}
| mit |
koher/Alamofire | Tests/TLSEvaluationTests.swift | 1 | 17070 | // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
private struct TestCertificates {
static let RootCA = TestCertificates.certificateWithFileName("root-ca-disig")
static let IntermediateCA = TestCertificates.certificateWithFileName("intermediate-ca-disig")
static let Leaf = TestCertificates.certificateWithFileName("testssl-expire.disig.sk")
static func certificateWithFileName(fileName: String) -> SecCertificate {
class Bundle {}
let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
let data = NSData(contentsOfFile: filePath)!
let certificate = SecCertificateCreateWithData(nil, data).takeRetainedValue()
return certificate
}
}
// MARK: -
private struct TestPublicKeys {
static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
static let IntermediateCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA)
static let Leaf = TestPublicKeys.publicKeyForCertificate(TestCertificates.Leaf)
static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey {
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
var unmanagedTrust: Unmanaged<SecTrust>?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &unmanagedTrust)
let trust = unmanagedTrust!.takeRetainedValue()
let publicKey = SecTrustCopyPublicKey(trust).takeRetainedValue()
return publicKey
}
}
// MARK: -
class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase {
let URL = "https://testssl-expire.disig.sk/"
let host = "testssl-expire.disig.sk"
var configuration: NSURLSessionConfiguration!
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
self.configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
}
// MARK: Default Behavior Tests
func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
// Given
let expectation = expectationWithDescription("\(self.URL)")
let manager = Manager(configuration: self.configuration)
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorServerCertificateUntrusted, "error should be NSURLErrorServerCertificateUntrusted")
}
// MARK: Server Trust Policy - Perform Default Tests
func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
// Given
let policies = [self.host: ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
// MARK: Server Trust Policy - Certificate Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf, TestCertificates.IntermediateCA, TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Public Key Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.RootCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Disabling Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
// Given
let policies = [self.host: ServerTrustPolicy.DisableEvaluation]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Custom Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
// Given
let policies = [
self.host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return true
}
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
// Given
let policies = [
self.host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return false
}
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
}
| mit |
findM/PasswordView | SampleDemo/AppDelegate.swift | 1 | 2151 | //
// AppDelegate.swift
// SampleDemo
//
// Created by 陈光临 on 15/11/30.
// Copyright © 2015年 cn.chenguanglin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
hughbe/ui-components | src/LoadableView/StoryboardLoadable.swift | 1 | 910 | //
// StoryboardLoadable.swift
// Slater
//
// Created by Hugh Bellamy on 02/09/2015.
// Copyright (c) 2015 Hugh Bellamy. All rights reserved.
//
import Foundation
public protocol StoryboardLoadable {
static var storyboardIdentifier: String { get }
}
public extension StoryboardLoadable {
public static func standardController() -> Self {
return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier(Self.storyboardIdentifier) as! Self
}
}
public extension UIViewController {
public var modalNavigationController: UINavigationController {
let navigationController = UINavigationController(rootViewController: self)
navigationController.modalPresentationStyle = modalPresentationStyle
navigationController.modalTransitionStyle = modalTransitionStyle
return navigationController
}
} | mit |
caronae/caronae-ios | Caronae/Ride/RideCell.swift | 1 | 2861 | import UIKit
class RideCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var arrivalDateTimeLabel: UILabel!
@IBOutlet weak var driverNameLabel: UILabel!
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var badgeLabel: UILabel!
var ride: Ride!
var color: UIColor! {
didSet {
titleLabel.textColor = color
arrivalDateTimeLabel.textColor = color
driverNameLabel.textColor = color
photo.layer.borderColor = color.cgColor
tintColor = color
}
}
var badgeCount: Int! {
didSet {
if badgeCount > 0 {
badgeLabel.text = String(badgeCount)
badgeLabel.isHidden = false
} else {
badgeLabel.isHidden = true
}
}
}
let dateFormatter = DateFormatter()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
dateFormatter.dateFormat = "HH:mm | E | dd/MM"
}
/// Configures the cell with a Ride object, updating the cell's labels and style accordingly.
///
/// - parameter ride: A Ride object.
func configureCell(with ride: Ride) {
configureBasicCell(with: ride)
accessoryType = .disclosureIndicator
if ride.going {
arrivalDateTimeLabel.text = String(format: "Chegando às %@", dateString())
} else {
arrivalDateTimeLabel.text = String(format: "Saindo às %@", dateString())
}
}
/// Configures the cell with a Ride object which belongs to a user's ride history, updating the cell's labels and style accordingly.
///
/// - parameter ride: A Ride object.
func configureHistoryCell(with ride: Ride) {
configureBasicCell(with: ride)
accessoryType = .none
if ride.going {
arrivalDateTimeLabel.text = String(format: "Chegou às %@", dateString())
} else {
arrivalDateTimeLabel.text = String(format: "Saiu às %@", dateString())
}
}
func configureBasicCell(with ride: Ride) {
self.ride = ride
titleLabel.text = ride.title.uppercased()
driverNameLabel.text = ride.driver.shortName
updatePhoto()
color = PlaceService.instance.color(forZone: ride.region)
badgeLabel.isHidden = true
}
func dateString() -> String {
return dateFormatter.string(from: ride.date).capitalized(after: "|")
}
func updatePhoto() {
if let profilePictureURL = ride.driver.profilePictureURL, !profilePictureURL.isEmpty {
photo.crn_setImage(with: URL(string: profilePictureURL))
} else {
photo.image = UIImage(named: CaronaePlaceholderProfileImage)
}
}
}
| gpl-3.0 |
kildevaeld/Sockets | Pod/Classes/DNS/in_addr.swift | 1 | 2067 | //
// in_addr.swift
// Sock
//
// Created by Rasmus Kildevæld on 27/07/15.
// Copyright © 2015 Rasmus Kildevæld . All rights reserved.
//
import Foundation
public extension in_addr {
public init() {
s_addr = INADDR_ANY.s_addr
}
public init(string: String?) {
if let s = string {
if s.isEmpty {
s_addr = INADDR_ANY.s_addr
}
else {
var buf = INADDR_ANY // Swift wants some initialization
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }
s_addr = buf.s_addr
}
}
else {
s_addr = INADDR_ANY.s_addr
}
}
public var asString: String {
if self == INADDR_ANY {
return "*.*.*.*"
}
let len = Int(INET_ADDRSTRLEN) + 2
var buf = [CChar](count: len, repeatedValue: 0)
var selfCopy = self // &self doesn't work, because it can be const?
let cs = inet_ntop(AF_INET, &selfCopy, &buf, socklen_t(len))
return String.fromCString(cs)!
}
}
public func ==(lhs: in_addr, rhs: in_addr) -> Bool {
return __uint32_t(lhs.s_addr) == __uint32_t(rhs.s_addr)
}
extension in_addr : Equatable, Hashable {
public var hashValue: Int {
// Knuth?
return Int(UInt32(s_addr) * 2654435761 % (2^32))
}
}
extension in_addr: StringLiteralConvertible {
// this allows you to do: let addr : in_addr = "192.168.0.1"
public init(stringLiteral value: StringLiteralType) {
self.init(string: value)
}
public init(extendedGraphemeClusterLiteral v: ExtendedGraphemeClusterType) {
self.init(string: v)
}
public init(unicodeScalarLiteral value: String) {
// FIXME: doesn't work with UnicodeScalarLiteralType?
self.init(string: value)
}
}
extension in_addr: CustomStringConvertible {
public var description: String {
return asString
}
}
| mit |
zjjzmw1/speedxSwift | speedxSwift/Pods/Log/Source/Theme.swift | 1 | 2915 | //
// Theme.swift
//
// Copyright (c) 2015-2016 Damien (http://delba.io)
//
// 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.
//
public class Themes {}
public class Theme: Themes {
/// The theme colors.
internal var colors: [Level: String]
/// The theme textual representation.
internal var description: String {
return colors.keys.sort().map {
$0.description.withColor(colors[$0]!)
}.joinWithSeparator(" ")
}
/**
Creates and returns a theme with the specified colors.
- parameter trace: The color for the trace level.
- parameter debug: The color for the debug level.
- parameter info: The color for the info level.
- parameter warning: The color for the warning level.
- parameter error: The color for the error level.
- returns: A theme with the specified colors.
*/
public init(trace: String, debug: String, info: String, warning: String, error: String) {
self.colors = [
.Trace: Theme.formatHex(trace),
.Debug: Theme.formatHex(debug),
.Info: Theme.formatHex(info),
.Warning: Theme.formatHex(warning),
.Error: Theme.formatHex(error)
]
}
/**
Returns a string representation of the hex color.
- parameter hex: The hex color.
- returns: A string representation of the hex color.
*/
private static func formatHex(hex: String) -> String {
let scanner = NSScanner(string: hex)
var hex: UInt32 = 0
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
scanner.scanHexInt(&hex)
let r = (hex & 0xFF0000) >> 16
let g = (hex & 0xFF00) >> 8
let b = (hex & 0xFF)
return [r, g, b].map({ String($0) }).joinWithSeparator(",")
}
} | mit |
PlutoMa/EmployeeCard | EmployeeCard/EmployeeCard/Model/WeddingModel.swift | 1 | 1006 | //
// WeddingModel.swift
// EmployeeCard
//
// Created by PlutoMa on 2017/4/7.
// Copyright © 2017年 PlutoMa. All rights reserved.
//
import Foundation
class WeddingModel {
let mid: String
let mdepart: String
let mname: String
let wname: String
let shortdate: String
let lxr: String
let email: String
let marrydate: String
let hotel: String
let photo: String
let type: String
init(mid: String?, mdepart: String?, mname: String?, wname: String?, shortdate: String?, lxr: String?, email: String?, marrydate: String?, hotel: String?, photo: String?, type: String?) {
self.mid = mid ?? ""
self.mdepart = mdepart ?? ""
self.mname = mname ?? ""
self.wname = wname ?? ""
self.shortdate = shortdate ?? ""
self.lxr = lxr ?? ""
self.email = email ?? ""
self.marrydate = marrydate ?? ""
self.hotel = hotel ?? ""
self.photo = photo ?? ""
self.type = type ?? ""
}
}
| mit |
ustwo/formvalidator-swift | Sources/Protocols/Form.swift | 1 | 3163 | //
// Form.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 14/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
/**
* A form to assist in validating `ValidatorControl` objects' current states.
*/
public protocol Form {
// MARK: - Properties
/// Entries in the form.
var entries: [FormEntry] { get set }
/// Whether or not the entire form is valid.
var isValid: Bool { get }
// MARK: - Initializers
/**
Creates an empty `Form`.
*/
init()
/**
Creates a `Form` where each `Validatable` uses its own `Validator` for validation.
- parameter validatables: Array of `Validatable`.
*/
init(validatables: [ValidatorControl])
/**
Creates a `Form` where each `Validatable` uses a custom `Validator` for validation. If `validatables` and `validators` have a different number of elements then returns `nil`.
- parameter validatables: Array of `Validatable`.
- parameter validators: Array of `Validator`.
*/
init?(validatables: [ValidatorControl], validators: [Validator])
// MARK: - Manipulate Entry
mutating func addEntry(_ control: ValidatorControl)
mutating func removeControlAtIndex(_ index: Int) -> ValidatorControl?
// MARK: - Check
/**
Checks the text from each entry in `entries`.
- returns: An array of conditions that were violated. If no conditions were violated then `nil` is returned.
*/
func checkConditions() -> [Condition]?
}
// Default implementation for `isValid`, `init(validatables:)`, `init?(validatables:validators:)`, and `checkConditions`.
public extension Form {
// MARK: - Properties
var isValid: Bool {
return checkConditions() == nil
}
// MARK: - Initializers
init(validatables: [ValidatorControl]) {
self.init()
entries = validatables.map { FormEntry(validatable: $0, validator: $0.validator) }
}
init?(validatables: [ValidatorControl], validators: [Validator]) {
guard validatables.count == validators.count else {
return nil
}
self.init()
var entries = [FormEntry]()
for index in 0 ..< validatables.count {
entries.append(FormEntry(validatable: validatables[index], validator: validators[index]))
}
self.entries = entries
}
// MARK: - Manipulate Entry
mutating func addEntry(_ control: ValidatorControl) {
entries.append(FormEntry(validatable: control, validator: control.validator))
}
mutating func removeControlAtIndex(_ index: Int) -> ValidatorControl? {
let entry = entries.remove(at: index)
return entry.validatable
}
// MARK: - Check
func checkConditions() -> [Condition]? {
let violatedConditions = entries.map { $0.checkConditions() }.filter { $0 != nil }.map { $0! }.flatMap { $0 }
return violatedConditions.isEmpty ? nil : violatedConditions
}
}
| mit |
openbuild-sheffield/jolt | Sources/RouteAuth/repository.UserLinkRole.swift | 1 | 2642 | import OpenbuildMysql
import OpenbuildRepository
import OpenbuildSingleton
public class RepositoryUserLinkRole: OpenbuildMysql.OBMySQL {
public init() throws {
guard let connectionDetails = OpenbuildSingleton.Manager.getConnectionDetails(
module: "auth",
name: "role",
type: "mysql"
)else{
throw RepoError.connection(
messagePublic: "Connection details not found for RouteAuth:Auth",
messageDev: "Connection details not found for RouteAuth:Auth auth:role:mysql"
)
}
try super.init(
connectionParams: connectionDetails.connectionParams as! MySQLConnectionParams,
database: connectionDetails.connectionDetails.db
)
}
public func install() throws -> Bool {
let installed = try super.tableExists(table: "userLinkRole")
if installed == false {
print("installed: \(installed)")
let installSQL = String(current: #file, path: "SQL/userLinkRole.sql")
print("DOING CREATE TABLE:")
print(installSQL!)
let created = try super.tableCreate(statement: installSQL!)
print("created: \(created)")
let insertSQL = String(current: #file, path: "SQL/userLinkRoleInsert.sql")
print("INSERT DATA:")
print(insertSQL!)
let results = insert(
statement: insertSQL!
)
print(results)
} else {
print("installed: \(installed)")
}
//TODO - upgrades
return true
}
public func addRole(user: ModelUserPlainMin, role: ModelRole) -> ModelRole{
let results = insert(
statement: "INSERT INTO userLinkRole (user_id, role_id) VALUES (?, ?)",
params: [user.user_id!, role.role_id!]
)
if results.error == true {
role.errors["insert"] = results.errorMessage
} else if results.affectedRows! != 1 {
role.errors["insert"] = "Failed to insert."
}
return role
}
public func deleteRole(user: ModelUserPlainMin, role: ModelRole) -> ModelRole{
let results = insert(
statement: "DELETE FROM userLinkRole WHERE user_id = ? AND role_id = ?",
params: [user.user_id!, role.role_id!]
)
if results.error == true {
role.errors["delete"] = results.errorMessage
} else if results.affectedRows! != 1 {
role.errors["delete"] = "Failed to insert."
}
return role
}
} | gpl-2.0 |
DataBreweryIncubator/StructuredQuery | Tests/RelationTests/RelationTests.swift | 1 | 8210 | import XCTest
@testable import Relation
@testable import Schema
@testable import Types
// TODO: Base Tables!!!
let events = Relation.table(Table("events",
Column("id", INTEGER),
Column("name", TEXT),
Column("value", INTEGER)
))
let contacts = Relation.table(Table("contacts",
Column("id", INTEGER),
Column("address", TEXT),
Column("city", TEXT),
Column("country", TEXT)
))
let a = Relation.table(Table("a", Column("id", INTEGER)))
let b = Relation.table(Table("b", Column("id", INTEGER)))
let c = Relation.table(Table("c", Column("id", INTEGER)))
class ProjectionTestCase: XCTestCase {
func testProjectionFromNothing(){
//
// SELECT 1
//
let list: [Expression] = [1]
var rel: Relation = Relation.projection(list, .none)
// Relation Conformance
XCTAssertEqual(rel.projectedExpressions, list)
XCTAssertEqual(rel.attributeReferences, [
AttributeReference(index:.concrete(0), name: nil, relation: rel)
])
//
// SELECT 1 as scalar
//
let expr = Expression.integer(1).label(as: "scalar")
rel = Relation.projection([expr], .none)
XCTAssertEqual(rel.attributeReferences, [
AttributeReference(index:.concrete(0), name: "scalar", relation: rel)
])
}
// Table
// -----
func testSelectAllFromOneTable() {
//
// SELECT id, name, value FROM events
//
let p1: Relation
let p2: Relation
let exprs = events.projectedExpressions
p1 = .projection(exprs, events.relation)
XCTAssertEqual(p1.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: p1),
AttributeReference(index:.concrete(1), name: "name", relation: p1),
AttributeReference(index:.concrete(2), name: "value", relation: p1)
])
// XCTAssertEqual(select.baseTables, [events])
//
// SELECT id, name, value FROM (SELECT id, name, value FROM events)
//
p2 = events.project()
XCTAssertEqual(p2.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: p2),
AttributeReference(index:.concrete(1), name: "name", relation: p2),
AttributeReference(index:.concrete(2), name: "value", relation: p2)
])
XCTAssertEqual(p1, p2)
}
func testSelectSomethingFromTable() {
//
// SELECT id, name FROM events
//
let p: Relation
let list: [Expression] = [events["name"], events["id"]]
p = .projection(list, events.relation)
XCTAssertEqual(p.attributeReferences, [
AttributeReference(index:.concrete(0), name: "name", relation: p),
AttributeReference(index:.concrete(1), name: "id", relation: p)
])
}
}
class AliasTestCase: XCTestCase {
// Alias
// -----
func testSelectFromAlias() {
let p: Relation
let alias: Relation
p = events.project()
alias = p.alias(as:"renamed")
XCTAssertEqual(alias.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: alias),
AttributeReference(index:.concrete(1), name: "name", relation: alias),
AttributeReference(index:.concrete(2), name: "value", relation: alias)
])
}
}
class JoinTestCase: XCTestCase {
// Join
// ----
func testJoin() {
let joined: Relation
let left = events.alias(as: "left")
let right = events.alias(as: "right")
joined = left.join(right)
XCTAssertEqual(joined.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: left),
AttributeReference(index:.concrete(1), name: "name", relation: left),
AttributeReference(index:.concrete(2), name: "value", relation: left),
AttributeReference(index:.concrete(0), name: "id", relation: right),
AttributeReference(index:.concrete(1), name: "name", relation: right),
AttributeReference(index:.concrete(2), name: "value", relation: right)
])
}
}
class RelationTestCase: XCTestCase {
// Attribute Reference Errors
// --------------------------
func testAmbiguousReference() {
var p: Relation
p = events.project([events["id"], events["id"]])
XCTAssertEqual(p.attributeReferences, [
AttributeReference(index:.ambiguous, name: "id", relation: p),
AttributeReference(index:.ambiguous, name: "id", relation: p)
])
p = events.project([events["name"].label(as: "other"),
events["value"].label(as: "other")])
XCTAssertEqual(p.attributeReferences, [
AttributeReference(index:.ambiguous, name: "other", relation: p),
AttributeReference(index:.ambiguous, name: "other", relation: p)
])
}
// Errors
// ------
// Select column from nothing
// SELECT id
// SELECT events.id FROM contacts
func testInvalidColumn() {
// let p = Relation.projection([events["id"]], Relation.none)
}
func assertEqual(_ lhs: [Relation], _ rhs: [Relation], file: StaticString = #file, line: UInt = #line) {
if lhs.count != rhs.count
|| zip(lhs, rhs).first(where: { l, r in l != r }) != nil {
XCTFail("Relation lists are not equal: left: \(lhs) right: \(rhs)",
file: file, line: line)
}
}
// Children and bases
//
func testChildren() {
var rel: Relation
var x: Relation
// SELECT * FROM a
// C: a
// B: a
rel = a.project()
assertEqual(rel.immediateRelations, [a])
assertEqual(rel.baseRelations, [a])
//
// SELECT * FROM a JOIN b
// C: a, b
// B: a, b
rel = a.join(b)
assertEqual(rel.immediateRelations, [a, b])
assertEqual(rel.baseRelations, [a, b])
rel = a.join(b).project()
assertEqual(rel.immediateRelations, [a, b])
assertEqual(rel.baseRelations, [a, b])
// SELECT * FROM a AS x
//
x = a.alias(as: "x")
rel = x.project()
assertEqual(rel.immediateRelations, [x])
assertEqual(rel.baseRelations, [a])
// SELECT * FROM (SELECT * FROM a) AS x)
x = a.project().alias(as: "x")
rel = a.join(b).project()
assertEqual(rel.immediateRelations, [a, b])
assertEqual(rel.baseRelations, [a, b])
//
// SELECT * FROM (SELECT * FROM a JOIN b) x
// C: x
// B: a, b
x = a.join(b).alias(as: "x")
rel = x.project()
assertEqual(rel.immediateRelations, [x])
assertEqual(rel.baseRelations, [a, b])
//
// SELECT * FROM a JOIN b JOIN c
// C: a, b, c
// B: a, b, c
rel = a.join(b).join(c)
assertEqual(rel.immediateRelations, [a, b, c])
assertEqual(rel.baseRelations, [a, b, c])
//
// SELECT * FROM a JOIN b JOIN c AS x
// C: a, b, x
// B: a, b, c
x = c.alias(as: "x")
rel = a.join(b).join(x)
assertEqual(rel.immediateRelations, [a, b, x])
assertEqual(rel.baseRelations, [a, b, c])
}
/*
func testSelectAliasColumns() {
let list = [
events["name"].label(as:"type"),
(events["value"] * 100).label(as: "greater_value"),
]
let p = events.select(list)
XCTAssertEqual(alias.attributes, [
AttributeReference(index:.concrete(0), name: "type", relation: p),
AttributeReference(index:.concrete(1), name: "greater_value", relation: p),
])
}
*/
func testInvalidRelationReference() {
// SELECT a.id FROM b
var rel: Relation
rel = b.project([a["id"]])
if rel.error == nil {
XCTFail("Invalid reference should cause an error: \(rel)")
}
}
// TODO: SELECT x.? FROM y
}
| mit |
brentsimmons/Evergreen | Account/Tests/AccountTests/Feedly/TestGetPagedStreamIdsService.swift | 1 | 2407 | //
// TestGetPagedStreamIdsService.swift
// AccountTests
//
// Created by Kiel Gillard on 29/10/19.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import XCTest
@testable import Account
final class TestGetPagedStreamIdsService: FeedlyGetStreamIdsService {
var parameterTester: ((FeedlyResourceId, String?, Date?, Bool?) -> ())?
var getStreamIdsExpectation: XCTestExpectation?
var pages = [String: FeedlyStreamIds]()
func addAtLeastOnePage(for resource: FeedlyResourceId, continuations: [String], numberOfEntriesPerPage count: Int) {
pages = [String: FeedlyStreamIds](minimumCapacity: continuations.count + 1)
// A continuation is an identifier for the next page.
// The first page has a nil identifier.
// The last page has no next page, so the next continuation value for that page is nil.
// Therefore, each page needs to know the identifier of the next page.
for index in -1..<continuations.count {
let nextIndex = index + 1
let continuation: String? = nextIndex < continuations.count ? continuations[nextIndex] : nil
let page = makeStreamIds(for: resource, continuation: continuation, between: 0..<count)
let key = TestGetPagedStreamIdsService.getPagingKey(for: resource, continuation: index < 0 ? nil : continuations[index])
pages[key] = page
}
}
private func makeStreamIds(for resource: FeedlyResourceId, continuation: String?, between range: Range<Int>) -> FeedlyStreamIds {
let entryIds = range.map { _ in UUID().uuidString }
let stream = FeedlyStreamIds(continuation: continuation, ids: entryIds)
return stream
}
static func getPagingKey(for stream: FeedlyResourceId, continuation: String?) -> String {
return "\(stream.id)@\(continuation ?? "")"
}
func getStreamIds(for resource: FeedlyResourceId, continuation: String?, newerThan: Date?, unreadOnly: Bool?, completion: @escaping (Result<FeedlyStreamIds, Error>) -> ()) {
let key = TestGetPagedStreamIdsService.getPagingKey(for: resource, continuation: continuation)
guard let page = pages[key] else {
XCTFail("Missing page for \(resource.id) and continuation \(String(describing: continuation)). Test may time out because the completion will not be called.")
return
}
parameterTester?(resource, continuation, newerThan, unreadOnly)
DispatchQueue.main.async {
completion(.success(page))
self.getStreamIdsExpectation?.fulfill()
}
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/00414-swift-archetypebuilder-resolvearchetype.swift | 11 | 419 | // 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
// RUN: not %target-swift-frontend %s -parse
class B<T where T.e = B<T>
| apache-2.0 |
brentsimmons/Evergreen | Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift | 1 | 1508 | //
// AccountsAddCloudKitWindowController.swift
// NetNewsWire
//
// Created by Maurice Parker on 3/18/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
import Account
enum AccountsAddCloudKitWindowControllerError: LocalizedError {
case iCloudDriveMissing
var errorDescription: String? {
return NSLocalizedString("Unable to add iCloud Account. Please make sure you have iCloud and iCloud enabled in System Preferences.", comment: "Unable to add iCloud Account.")
}
}
class AccountsAddCloudKitWindowController: NSWindowController {
private weak var hostWindow: NSWindow?
convenience init() {
self.init(windowNibName: NSNib.Name("AccountsAddCloudKit"))
}
override func windowDidLoad() {
super.windowDidLoad()
}
// MARK: API
func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) {
self.hostWindow = hostWindow
hostWindow.beginSheet(window!, completionHandler: completion)
}
// MARK: Actions
@IBAction func cancel(_ sender: Any) {
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel)
}
@IBAction func create(_ sender: Any) {
guard FileManager.default.ubiquityIdentityToken != nil else {
NSApplication.shared.presentError(AccountsAddCloudKitWindowControllerError.iCloudDriveMissing)
return
}
let _ = AccountManager.shared.createAccount(type: .cloudKit)
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
}
}
| mit |
dbruzzone/wishing-tree | iOS/Pace/Location+CoreDataProperties.swift | 1 | 666 | //
// Location+CoreDataProperties.swift
// Pace
//
// Created by Davide Bruzzone on 11/1/15.
// Copyright © 2015 Davide Bruzzone. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Location {
@NSManaged var altitude: NSNumber?
@NSManaged var horizontalAccuracy: NSNumber?
@NSManaged var latitude: NSNumber?
@NSManaged var longitude: NSNumber?
@NSManaged var summary: String?
@NSManaged var timestamp: NSDate?
@NSManaged var verticalAccuracy: NSNumber?
}
| gpl-3.0 |
seeRead/roundware-ios-framework-v2 | Pod/Classes/RWFrameworkTags.swift | 1 | 5609 | //
// RWFrameworkTags.swift
// RWFramework
//
// Created by Joe Zobkiw on 2/12/15.
// Copyright (c) 2015 Roundware. All rights reserved.
//
import Foundation
extension RWFramework {
// MARK: get/set tags/values
/*
var a: AnyObject? = getListenTags() // if needed to get various codes, etc.
var b: AnyObject? = getListenTagsCurrent("gender")
var ba = (b as? NSArray) as Array?
if (ba != nil) {
ba!.append(5)
setListenTagsCurrent("gender", value: ba!)
}
var c: AnyObject? = getListenTagsCurrent("gender")
println("\(b) \(c)")
*/
// MARK: Listen Tags
// /// Returns an array of dictionaries of listen information
// public func getListenTags() -> AnyObject? {
// return NSUserDefaults.standardUserDefaults().objectForKey("tags_listen")
// }
//
// /// Sets the array of dictionaries as listen information
// public func setListenTags(value: AnyObject) {
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: "tags_listen")
// }
//
// /// Get the current values for the listen tags code
// public func getListenTagsCurrent(code: String) -> AnyObject? {
// let defaultsKeyName = "tags_listen_\(code)_current"
// return NSUserDefaults.standardUserDefaults().objectForKey(defaultsKeyName)
// }
//
// /// Set the current values for the listen tags code
// public func setListenTagsCurrent(code: String, value: AnyObject) {
// let defaultsKeyName = "tags_listen_\(code)_current"
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: defaultsKeyName)
// }
//
// /// Get all the current values for the listen tags
// public func getAllListenTagsCurrent() -> AnyObject? {
// var allListenTagsCurrentArray = [AnyObject]()
// if let listenTagsArray = getListenTags() as! NSArray? {
// for d in listenTagsArray {
// let code = d["code"] as! String
// if let tagsForCode = getListenTagsCurrent(code) as! [AnyObject]? {
// allListenTagsCurrentArray += tagsForCode
// }
// }
// }
// return allListenTagsCurrentArray
// }
//
// /// Get all the current values for the listen tags as a comma-separated string
// public func getAllListenTagsCurrentAsString() -> String {
// var tag_ids = ""
// if let allListenTagsArray = getAllListenTagsCurrent() as! NSArray? {
// for tag in allListenTagsArray {
// if (tag_ids != "") { tag_ids += "," }
// tag_ids += tag.description
// }
// }
// return tag_ids
// }
// MARK: Speak Tags
//
// /// Returns an array of dictionaries of speak information
// public func getSpeakTags() -> AnyObject? {
// return NSUserDefaults.standardUserDefaults().objectForKey("tags_speak")
// }
//
// /// Sets the array of dictionaries of speak information
// public func setSpeakTags(value: AnyObject) {
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: "tags_speak")
// }
//
// /// Get the current values for the speak tags code
// public func getSpeakTagsCurrent(code: String) -> AnyObject? {
// let defaultsKeyName = "tags_speak_\(code)_current"
// return NSUserDefaults.standardUserDefaults().objectForKey(defaultsKeyName)
// }
//
// /// Set the current values for the speak tags code
// public func setSpeakTagsCurrent(code: String, value: AnyObject) {
// let defaultsKeyName = "tags_speak_\(code)_current"
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: defaultsKeyName)
// }
//
// /// Get all the current values for the speak tags
// public func getAllSpeakTagsCurrent() -> AnyObject? {
// var allSpeakTagsCurrentArray = [AnyObject]()
// if let speakTagsArray = getSpeakTags() as! NSArray? {
// for d in speakTagsArray {
// let code = d["code"] as! String
// if let tagsForCode = getSpeakTagsCurrent(code) as! [AnyObject]? {
// allSpeakTagsCurrentArray += tagsForCode
// }
// }
// }
// return allSpeakTagsCurrentArray
// }
//
// /// Get all the current values for the speak tags as a comma-separated string
// public func getAllSpeakTagsCurrentAsString() -> String {
// if let allSpeakTagsArray = getAllSpeakTagsCurrent() as! NSArray? {
// var tags = ""
// for tag in allSpeakTagsArray {
// if (tags != "") { tags += "," }
// tags += tag.description
// }
// return tags
// }
// return ""
// }
// MARK: submit tags
/// Submit all current listen tags to the server
// public func submitListenTags() {
// let tag_ids = getAllListenTagsCurrentAsString()
// apiPatchStreamsIdWithTags(tag_ids)
// }
public func submitTags(tagIdsAsString: String) {
apiPatchStreamsIdWithTags(tag_ids: tagIdsAsString)
}
// MARK: edit tags
//
// /// Edit the Listen tags in a web view
// public func editListenTags() {
// editTags("tags_listen", title:LS("Listen Tags"))
// }
//
// /// Edit the Speak tags in a web view
// public func editSpeakTags() {
// editTags("tags_speak", title:LS("Speak Tags"))
// }
//
// /// Edit the Listen or Speak tags in a web view
// func editTags(type: String, title: String) {
// println("editing tags not yet supported but coming soon via WKWebView")
// }
}
| mit |
BPForEveryone/BloodPressureForEveryone | BPApp/Shared/Patient.swift | 1 | 6606 | //
// Patient.swift
// BPApp
//
// Created by MiningMarsh on 9/26/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
// Implements a patient instance that supports serialization to be encoded and decoded.
import Foundation
import os.log
public class Patient: NSObject, NSCoding {
public enum Sex {
case male
case female
}
var firstName: String
var lastName: String
var birthDate: Date
var height: Height
private var sexInBoolean: Bool
private var bloodPressureMeasurementsSorted: [BloodPressureMeasurement]! = []
public var bloodPressureMeasurements: [BloodPressureMeasurement] {
get {
return self.bloodPressureMeasurementsSorted
}
set(newBloodPressureMeasurements) {
self.bloodPressureMeasurementsSorted = newBloodPressureMeasurements.sorted {
return $0.measurementDate > $1.measurementDate
}
}
}
public var norms: BPNormsEntry {
get {
return BPNormsTable.index(patient: self)
}
}
public var normsArray: [BPNormsEntry] {
get {
return BPNormsTable.indexForArray(patient: self)
}
}
public var percentile: Int {
get {
let norms = self.norms
if self.bloodPressureMeasurements.count == 0 {
return 0
}
let measurement = self.bloodPressureMeasurements[0]
if norms.diastolic95 < measurement.diastolic {
return 95
} else if norms.diastolic90 < measurement.diastolic {
return 90
} else if norms.diastolic50 < measurement.diastolic {
return 50
}
return 0
}
}
public var diastolic: Int {
if self.bloodPressureMeasurements.count == 0 {
return 0
}
return self.bloodPressureMeasurements[0].diastolic
}
public var systolic: Int {
if self.bloodPressureMeasurements.count == 0 {
return 0
}
return self.bloodPressureMeasurements[0].systolic
}
public var sex: Patient.Sex {
get {
if self.sexInBoolean {
return Patient.Sex.male
} else {
return Patient.Sex.female
}
}
set(newSex) {
switch newSex {
case .male: self.sexInBoolean = true
case .female: self.sexInBoolean = false
}
}
}
// The properties to save for a patients, make sure this reflects with the properties patients have.
struct PropertyKey {
static let firstName = "firstName"
static let lastName = "lastName"
static let birthDate = "birthDate"
static let heightInMeters = "heightInMeters"
static let sexInBoolean = "sexInBoolean"
static let bloodPressureMeasurementsSorted = "bloodPressureMeasurementsSorted"
}
// Create a new patient
init?(firstName: String, lastName: String, birthDate: Date, height: Height, sex: Patient.Sex, bloodPressureMeasurements: [BloodPressureMeasurement]) {
// The names must not be empty
guard !firstName.isEmpty else {
return nil
}
guard !lastName.isEmpty else {
return nil
}
// Height must be positive.
guard height.meters >= 0.0 else {
return nil
}
self.firstName = firstName
self.lastName = lastName
self.birthDate = birthDate
self.height = height
switch sex {
case .male: self.sexInBoolean = true
case .female: self.sexInBoolean = false
}
self.bloodPressureMeasurementsSorted = bloodPressureMeasurements.sorted {
return $0.measurementDate < $1.measurementDate
}
}
// Encoder used to store a patient.
public func encode(with encoder: NSCoder) {
encoder.encode(firstName, forKey: PropertyKey.firstName)
encoder.encode(lastName, forKey: PropertyKey.lastName)
encoder.encode(birthDate, forKey: PropertyKey.birthDate)
encoder.encode(height.meters, forKey: PropertyKey.heightInMeters)
encoder.encode(sexInBoolean, forKey: PropertyKey.sexInBoolean)
encoder.encode(bloodPressureMeasurementsSorted, forKey: PropertyKey.bloodPressureMeasurementsSorted)
}
public required convenience init?(coder decoder: NSCoder) {
// First name is required
guard let lastName = decoder.decodeObject(forKey: PropertyKey.lastName) as? String else {
os_log("Unable to decode the first name for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
// Last name is required.
guard let firstName = decoder.decodeObject(forKey: PropertyKey.firstName) as? String else {
os_log("Unable to decode the last name for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
// Age is required.
guard let birthDate = decoder.decodeObject(forKey: PropertyKey.birthDate) as? Date else {
os_log("Unable to decode the birth date for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
let heightInMeters = decoder.decodeDouble(forKey: PropertyKey.heightInMeters)
let sexInBoolean = decoder.decodeBool(forKey: PropertyKey.sexInBoolean)
var sex: Patient.Sex = Patient.Sex.male
if sexInBoolean {
sex = Patient.Sex.male
} else {
sex = Patient.Sex.female
}
// Blood pressure log is required.
guard let bloodPressureMeasurementsSorted = decoder.decodeObject(forKey: PropertyKey.bloodPressureMeasurementsSorted) as? [BloodPressureMeasurement] else {
os_log("Unable to decode the blood pressure log for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
// Initialize with decoded values.
self.init(
firstName: firstName,
lastName: lastName,
birthDate: birthDate,
height: Height(heightInMeters: heightInMeters),
sex: sex,
bloodPressureMeasurements: bloodPressureMeasurementsSorted
)
}
}
| mit |
hryk224/PCLBlurEffectAlert | Sources/PCLBlurEffectAlert+TransitionAnimator.swift | 1 | 5108 | //
// PCLBlurEffectAlertController+Tr.swift
// PCLBlurEffectAlert
//
// Created by hiroyuki yoshida on 2017/02/26.
//
//
import UIKit
public typealias PCLBlurEffectAlertTransitionAnimator = PCLBlurEffectAlert.TransitionAnimator
extension PCLBlurEffectAlert {
// MARK: - TransitionAnimator
open class TransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
fileprivate typealias TransitionAnimator = PCLBlurEffectAlert.TransitionAnimator
fileprivate static let presentBackAnimationDuration: TimeInterval = 0.45
fileprivate static let dismissBackAnimationDuration: TimeInterval = 0.35
fileprivate var goingPresent: Bool!
init(present: Bool) {
super.init()
goingPresent = present
}
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if goingPresent == true {
return TransitionAnimator.presentBackAnimationDuration
} else {
return TransitionAnimator.dismissBackAnimationDuration
}
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if goingPresent == true {
presentAnimation(transitionContext)
} else {
dismissAnimation(transitionContext)
}
}
}
}
// MARK: - Extension
private extension PCLBlurEffectAlert.TransitionAnimator {
func presentAnimation(_ transitionContext: UIViewControllerContextTransitioning) {
guard let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? PCLBlurEffectAlertController else {
transitionContext.completeTransition(false)
return
}
let containerView = transitionContext.containerView
containerView.backgroundColor = .clear
containerView.addSubview(alertController.view)
alertController.overlayView.alpha = 0
let animations: (() -> Void)
switch alertController.style {
case .actionSheet:
alertController.alertView.transform = CGAffineTransform(translationX: 0,
y: alertController.alertView.frame.height)
animations = {
alertController.overlayView.alpha = 1
alertController.alertView.transform = CGAffineTransform(translationX: 0, y: -10)
}
default:
alertController.cornerView.subviews.forEach { $0.alpha = 0 }
alertController.alertView.center = alertController.view.center
alertController.alertView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
animations = {
alertController.overlayView.alpha = 1
alertController.cornerView.subviews.forEach { $0.alpha = 1 }
alertController.alertView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
}
}
UIView.animate(withDuration: transitionDuration(using: transitionContext) * (5 / 9), animations: animations) { finished in
guard finished else { return }
let animations = {
alertController.alertView.transform = CGAffineTransform.identity
}
UIView.animate(withDuration: self.transitionDuration(using: transitionContext) * (4 / 9), animations: animations) { finished in
guard finished else { return }
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
alertController.view.removeFromSuperview()
}
transitionContext.completeTransition(!cancelled)
}
}
}
func dismissAnimation(_ transitionContext: UIViewControllerContextTransitioning) {
guard let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? PCLBlurEffectAlertController else {
transitionContext.completeTransition(false)
return
}
let animations = {
alertController.overlayView.alpha = 0
switch alertController.style {
case .actionSheet:
alertController.containerView.transform = CGAffineTransform(translationX: 0,
y: alertController.alertView.frame.height)
default:
alertController.alertView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
alertController.cornerView.subviews.forEach { $0.alpha = 0 }
}
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations) { finished in
guard finished else { return }
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit |
PlanTeam/BSON | Sources/BSON/Types/JavaScript.swift | 1 | 501 | public struct JavaScriptCode: Primitive, ExpressibleByStringLiteral, Hashable {
public var code: String
public init(_ code: String) {
self.code = code
}
public init(stringLiteral value: String) {
self.code = value
}
}
public struct JavaScriptCodeWithScope: Primitive, Hashable {
public var code: String
public var scope: Document
public init(_ code: String, scope: Document) {
self.code = code
self.scope = scope
}
}
| mit |
niklassaers/PackStream-Swift | Sources/PackStream/Int.swift | 1 | 9012 | import Foundation
#if swift(>=4.0)
#elseif swift(>=3.0)
typealias BinaryInteger = Integer
#endif
extension PackProtocol {
public func intValue() -> Int64? {
if let i = self as? Int8 {
return Int64(i)
} else if let i = self as? Int16 {
return Int64(i)
} else if let i = self as? Int32 {
return Int64(i)
} else if let i = self as? Int64 {
return i
} else if let i = self as? UInt8 {
return Int64(i)
} else if let i = self as? UInt16 {
return Int64(i)
} else if let i = self as? UInt32 {
return Int64(i)
}
return nil
}
public func uintValue() -> UInt64? {
if let i = self as? UInt64 {
return i
} else if let i = self.intValue() {
if i < 0 {
return nil
} else {
return UInt64(i)
}
}
return nil
}
}
extension Int8: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xC8
}
public func pack() throws -> [Byte] {
switch self {
case -0x10 ... 0x7F:
return packInt8(withByteMarker: false)
default:
return packInt8(withByteMarker: true)
}
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int8 {
switch bytes.count {
case 1:
return try unpackInt8(bytes, withMarker: false)
case 2:
return try unpackInt8(bytes, withMarker: true)
default:
throw UnpackError.incorrectNumberOfBytes
}
}
private func packInt8(withByteMarker: Bool) -> [Byte] {
if withByteMarker == true {
return [ Constants.byteMarker, Byte(bitPattern: self) ]
} else {
return [ Byte(bitPattern: self) ]
}
}
private static func unpackInt8(_ bytes: ArraySlice<Byte>, withMarker: Bool) throws -> Int8 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if withMarker == false {
return Int8(bitPattern: firstByte)
} else {
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 2 {
throw UnpackError.incorrectNumberOfBytes
}
let byte: Byte = bytes[bytes.startIndex + 1]
return Int8(bitPattern: byte)
}
}
}
extension Int16: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xC9
}
public func pack() throws -> [Byte] {
let nv: Int16 = Int16(self).bigEndian
let uNv = UInt16(bitPattern: nv)
let second = UInt8(uNv >> 8)
let first = UInt8(uNv & 0x00ff)
return [ Constants.byteMarker, first, second ]
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int16 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 3 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 3)
let i: Int16 = Int.readInteger(data: data, start: 1)
return Int16(bigEndian: i)
}
}
extension UInt8 {
func pack() throws -> [Byte] {
return [ self ]
}
static func unpack(_ bytes: ArraySlice<Byte>) throws -> UInt8 {
if bytes.count != 1 {
throw UnpackError.incorrectNumberOfBytes
}
return bytes[bytes.startIndex]
}
}
extension UInt16 {
public func pack() throws -> [Byte] {
var i: UInt16 = UInt16(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<UInt16>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> UInt16 {
if bytes.count != 2 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 2)
let i: UInt16 = Int.readInteger(data: data, start: 0)
return UInt16(bigEndian: i)
}
}
extension UInt32 {
func pack() throws -> [Byte] {
var i: UInt32 = UInt32(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<UInt32>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> UInt32 {
if bytes.count != 4 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 4)
let i: UInt32 = Int.readInteger(data: data, start: 0)
return UInt32(bigEndian: i)
}
}
extension Int32: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xCA
}
public func pack() throws -> [Byte] {
var i: Int32 = Int32(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<Int32>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return [Constants.byteMarker] + bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int32 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 5 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 5)
let i: Int32 = Int.readInteger(data: data, start: 1)
return Int32(bigEndian: i)
}
}
extension Int64: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xCB
}
public func pack() throws -> [Byte] {
var i: Int64 = Int64(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<Int64>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return [Constants.byteMarker] + bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int64 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 9 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 9)
let i: Int64 = Int.readInteger(data: data, start: 1)
return Int64(bigEndian: i)
}
}
extension Int: PackProtocol {
public func pack() throws -> [Byte] {
#if __LP64__ || os(Linux)
switch self {
case -0x10 ... 0x7F:
return try Int8(self).pack()
case -0x7F ..< -0x7F:
return try Int8(self).pack()
case -0x8000 ..< 0x8000:
return try Int16(self).pack()
case -0x80000000 ... 0x7fffffff:
return try Int32(self).pack()
case -0x8000000000000000 ... (0x800000000000000 - 1):
return try Int64(self).pack()
default:
throw PackError.notPackable
}
#else
switch self {
case -0x10 ... 0x7F:
return try Int8(self).pack()
case -0x7F ..< -0x7F:
return try Int8(self).pack()
case -0x8000 ..< 0x8000:
return try Int16(self).pack()
case -0x80000000 ... 0x7fffffff:
return try Int32(self).pack()
default:
throw PackError.notPackable
}
#endif
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int {
switch bytes.count {
case 1:
return Int(try Int8.unpack(bytes))
case 2:
return Int(try Int8.unpack(bytes))
case 3:
return Int(try Int16.unpack(bytes))
case 5:
return Int(try Int32.unpack(bytes))
case 9:
return Int(try Int64.unpack(bytes))
default:
throw UnpackError.incorrectNumberOfBytes
}
}
static func readInteger<T: BinaryInteger>(data: NSData, start: Int) -> T {
var d: T = 0 as T
data.getBytes(&d, range: NSRange(location: start, length: MemoryLayout<T>.size))
return d
}
}
| bsd-3-clause |
yannickl/FlowingMenu | Example/FlowingMenuUITests/FlowingMenuUITests.swift | 1 | 902 | //
// FlowingMenuUITests.swift
// FlowingMenuUITests
//
// Created by Yannick LORIOT on 04/12/15.
// Copyright © 2015 Yannick LORIOT. All rights reserved.
//
import XCTest
class FlowingMenuUITests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
XCUIApplication().launch()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTransition() {
let app = XCUIApplication()
app.navigationBars["Contacts"].children(matching: .button).element.tap()
let tablesQuery = app.tables
tablesQuery.staticTexts["Inmaculada Cortes"].tap()
app.navigationBars["Chat"].children(matching: .button).element.tap()
tablesQuery.cells.containing(.staticText, identifier:"Silvia Herrero").staticTexts["Work"].tap()
}
}
| mit |
Quick/Nimble | Package.swift | 1 | 1077 | // swift-tools-version:5.7
import PackageDescription
let package = Package(
name: "Nimble",
platforms: [
.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)
],
products: [
.library(name: "Nimble", targets: ["Nimble"]),
],
dependencies: [
.package(url: "https://github.com/mattgallagher/CwlPreconditionTesting.git", .upToNextMajor(from: "2.1.0")),
],
targets: [
.target(
name: "Nimble",
dependencies: [
.product(name: "CwlPreconditionTesting", package: "CwlPreconditionTesting",
condition: .when(platforms: [.macOS, .iOS])),
.product(name: "CwlPosixPreconditionTesting", package: "CwlPreconditionTesting",
condition: .when(platforms: [.tvOS, .watchOS]))
],
exclude: ["Info.plist"]
),
.testTarget(
name: "NimbleTests",
dependencies: ["Nimble"],
exclude: ["objc", "Info.plist"]
),
],
swiftLanguageVersions: [.v5]
)
| apache-2.0 |
jinSasaki/Vulcan | Sources/Vulcan/UIImageView+Vulcan.swift | 1 | 609 | //
// UIImageView+Vulcan.swift
// Vulcan
//
// Created by Jin Sasaki on 2017/04/23
// Copyright © 2017年 Sasakky. All rights reserved.
//
import UIKit
private var kVulcanKey: UInt = 0
public extension UIImageView {
public var vl: Vulcan {
if let vulcan = objc_getAssociatedObject(self, &kVulcanKey) as? Vulcan {
return vulcan
}
let vulcan = Vulcan()
if vulcan.imageView == nil {
vulcan.imageView = self
}
objc_setAssociatedObject(self, &kVulcanKey, vulcan, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return vulcan
}
}
| mit |
phillfarrugia/appstore-clone | AppStoreClone/PresentStoryViewAnimationController.swift | 1 | 2157 | //
// StoryViewAnimationController.swift
// AppStoreClone
//
// Created by Phillip Farrugia on 6/17/17.
// Copyright © 2017 Phill Farrugia. All rights reserved.
//
import UIKit
internal class PresentStoryViewAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
internal var selectedCardFrame: CGRect = .zero
// MARK: - UIViewControllerAnimatedTransitioning
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// 1
let containerView = transitionContext.containerView
guard let fromViewController = transitionContext.viewController(forKey: .from) as? TodayViewController,
let toViewController = transitionContext.viewController(forKey: .to) as? StoryDetailViewController else {
return
}
// 2
containerView.addSubview(toViewController.view)
toViewController.positionContainer(left: 20.0,
right: 20.0,
top: selectedCardFrame.origin.y + 20.0,
bottom: 0.0)
toViewController.setHeaderHeight(self.selectedCardFrame.size.height - 40.0)
toViewController.configureRoundedCorners(shouldRound: true)
// 3
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
toViewController.positionContainer(left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0)
toViewController.setHeaderHeight(500)
toViewController.view.backgroundColor = .white
toViewController.configureRoundedCorners(shouldRound: false)
}) { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.1
}
}
| mit |
qinting513/WeiBo-Swift | WeiBo_V2/WeiBo/Classes/View[视图跟控制器]/Main/WBMainNavigationController.swift | 2 | 2274 | //
// WBMainNavigationController.swift
// WeiBo
//
// Created by Qinting on 16/9/6.
// Copyright © 2016年 Qinting. All rights reserved.
//
import UIKit
class WBMainNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// 关键点:把系统导航栏隐藏
navigationBar.isHidden = true;
}
/** 重写push方法 */
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
/** 如果有子VC 则隐藏底部的 根控制器不需要处理*/
if childViewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
// 取出自定义的 naviItem
if let vc = viewController as? WBBaseViewController {
let backBtn = UIButton(type: .custom)
backBtn.setImage(UIImage(named: "navigationbar_back_withtext"), for: UIControlState())
backBtn.setImage(UIImage(named: "navigationbar_back_withtext_highlighted"), for: .highlighted)
backBtn.contentHorizontalAlignment = .left
var title = "返回"
// 判断控制器的级数,只有一个子控制器的时候,显示栈底控制器的标题
if childViewControllers.count == 1 {
title = childViewControllers.first?.title ?? "返回"
}
backBtn.setTitle(title, for: UIControlState())
backBtn.setTitleColor(UIColor.black(), for: UIControlState(rawValue:0))
backBtn.setTitleColor(UIColor.orange(), for: .highlighted)
backBtn.bounds = CGRect(x: 0, y: 0, width: 70, height: 30)
backBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0)
vc.naviItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
backBtn.addTarget(self, action:#selector(WBMainNavigationController.back), for: .touchUpInside)
}
}
super.pushViewController(viewController, animated: true)
}
func back() {
self.popViewController(animated: true)
}
// override func popViewControllerAnimated(animated: Bool) -> UIViewController? {
//
// }
}
| apache-2.0 |
nubbel/swift-tensorflow | Sources/tfprof_options.pb.swift | 1 | 20162 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: tensorflow/core/profiler/tfprof_options.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// Refers to tfprof_options.h/cc for documentation.
/// Only used to pass tfprof options from Python to C++.
public struct Tensorflow_Tfprof_OptionsProto: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".OptionsProto"
public var maxDepth: Int64 {
get {return _storage._maxDepth}
set {_uniqueStorage()._maxDepth = newValue}
}
public var minBytes: Int64 {
get {return _storage._minBytes}
set {_uniqueStorage()._minBytes = newValue}
}
public var minPeakBytes: Int64 {
get {return _storage._minPeakBytes}
set {_uniqueStorage()._minPeakBytes = newValue}
}
public var minResidualBytes: Int64 {
get {return _storage._minResidualBytes}
set {_uniqueStorage()._minResidualBytes = newValue}
}
public var minOutputBytes: Int64 {
get {return _storage._minOutputBytes}
set {_uniqueStorage()._minOutputBytes = newValue}
}
public var minMicros: Int64 {
get {return _storage._minMicros}
set {_uniqueStorage()._minMicros = newValue}
}
public var minAcceleratorMicros: Int64 {
get {return _storage._minAcceleratorMicros}
set {_uniqueStorage()._minAcceleratorMicros = newValue}
}
public var minCpuMicros: Int64 {
get {return _storage._minCpuMicros}
set {_uniqueStorage()._minCpuMicros = newValue}
}
public var minParams: Int64 {
get {return _storage._minParams}
set {_uniqueStorage()._minParams = newValue}
}
public var minFloatOps: Int64 {
get {return _storage._minFloatOps}
set {_uniqueStorage()._minFloatOps = newValue}
}
public var minOccurrence: Int64 {
get {return _storage._minOccurrence}
set {_uniqueStorage()._minOccurrence = newValue}
}
public var step: Int64 {
get {return _storage._step}
set {_uniqueStorage()._step = newValue}
}
public var orderBy: String {
get {return _storage._orderBy}
set {_uniqueStorage()._orderBy = newValue}
}
public var accountTypeRegexes: [String] {
get {return _storage._accountTypeRegexes}
set {_uniqueStorage()._accountTypeRegexes = newValue}
}
public var startNameRegexes: [String] {
get {return _storage._startNameRegexes}
set {_uniqueStorage()._startNameRegexes = newValue}
}
public var trimNameRegexes: [String] {
get {return _storage._trimNameRegexes}
set {_uniqueStorage()._trimNameRegexes = newValue}
}
public var showNameRegexes: [String] {
get {return _storage._showNameRegexes}
set {_uniqueStorage()._showNameRegexes = newValue}
}
public var hideNameRegexes: [String] {
get {return _storage._hideNameRegexes}
set {_uniqueStorage()._hideNameRegexes = newValue}
}
public var accountDisplayedOpOnly: Bool {
get {return _storage._accountDisplayedOpOnly}
set {_uniqueStorage()._accountDisplayedOpOnly = newValue}
}
public var select: [String] {
get {return _storage._select}
set {_uniqueStorage()._select = newValue}
}
public var output: String {
get {return _storage._output}
set {_uniqueStorage()._output = newValue}
}
public var dumpToFile: String {
get {return _storage._dumpToFile}
set {_uniqueStorage()._dumpToFile = newValue}
}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt64Field(value: &_storage._maxDepth)
case 2: try decoder.decodeSingularInt64Field(value: &_storage._minBytes)
case 3: try decoder.decodeSingularInt64Field(value: &_storage._minMicros)
case 4: try decoder.decodeSingularInt64Field(value: &_storage._minParams)
case 5: try decoder.decodeSingularInt64Field(value: &_storage._minFloatOps)
case 7: try decoder.decodeSingularStringField(value: &_storage._orderBy)
case 8: try decoder.decodeRepeatedStringField(value: &_storage._accountTypeRegexes)
case 9: try decoder.decodeRepeatedStringField(value: &_storage._startNameRegexes)
case 10: try decoder.decodeRepeatedStringField(value: &_storage._trimNameRegexes)
case 11: try decoder.decodeRepeatedStringField(value: &_storage._showNameRegexes)
case 12: try decoder.decodeRepeatedStringField(value: &_storage._hideNameRegexes)
case 13: try decoder.decodeSingularBoolField(value: &_storage._accountDisplayedOpOnly)
case 14: try decoder.decodeRepeatedStringField(value: &_storage._select)
case 15: try decoder.decodeSingularStringField(value: &_storage._output)
case 16: try decoder.decodeSingularStringField(value: &_storage._dumpToFile)
case 17: try decoder.decodeSingularInt64Field(value: &_storage._minOccurrence)
case 18: try decoder.decodeSingularInt64Field(value: &_storage._step)
case 19: try decoder.decodeSingularInt64Field(value: &_storage._minPeakBytes)
case 20: try decoder.decodeSingularInt64Field(value: &_storage._minResidualBytes)
case 21: try decoder.decodeSingularInt64Field(value: &_storage._minOutputBytes)
case 22: try decoder.decodeSingularInt64Field(value: &_storage._minAcceleratorMicros)
case 23: try decoder.decodeSingularInt64Field(value: &_storage._minCpuMicros)
default: break
}
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._maxDepth != 0 {
try visitor.visitSingularInt64Field(value: _storage._maxDepth, fieldNumber: 1)
}
if _storage._minBytes != 0 {
try visitor.visitSingularInt64Field(value: _storage._minBytes, fieldNumber: 2)
}
if _storage._minMicros != 0 {
try visitor.visitSingularInt64Field(value: _storage._minMicros, fieldNumber: 3)
}
if _storage._minParams != 0 {
try visitor.visitSingularInt64Field(value: _storage._minParams, fieldNumber: 4)
}
if _storage._minFloatOps != 0 {
try visitor.visitSingularInt64Field(value: _storage._minFloatOps, fieldNumber: 5)
}
if !_storage._orderBy.isEmpty {
try visitor.visitSingularStringField(value: _storage._orderBy, fieldNumber: 7)
}
if !_storage._accountTypeRegexes.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._accountTypeRegexes, fieldNumber: 8)
}
if !_storage._startNameRegexes.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._startNameRegexes, fieldNumber: 9)
}
if !_storage._trimNameRegexes.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._trimNameRegexes, fieldNumber: 10)
}
if !_storage._showNameRegexes.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._showNameRegexes, fieldNumber: 11)
}
if !_storage._hideNameRegexes.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._hideNameRegexes, fieldNumber: 12)
}
if _storage._accountDisplayedOpOnly != false {
try visitor.visitSingularBoolField(value: _storage._accountDisplayedOpOnly, fieldNumber: 13)
}
if !_storage._select.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._select, fieldNumber: 14)
}
if !_storage._output.isEmpty {
try visitor.visitSingularStringField(value: _storage._output, fieldNumber: 15)
}
if !_storage._dumpToFile.isEmpty {
try visitor.visitSingularStringField(value: _storage._dumpToFile, fieldNumber: 16)
}
if _storage._minOccurrence != 0 {
try visitor.visitSingularInt64Field(value: _storage._minOccurrence, fieldNumber: 17)
}
if _storage._step != 0 {
try visitor.visitSingularInt64Field(value: _storage._step, fieldNumber: 18)
}
if _storage._minPeakBytes != 0 {
try visitor.visitSingularInt64Field(value: _storage._minPeakBytes, fieldNumber: 19)
}
if _storage._minResidualBytes != 0 {
try visitor.visitSingularInt64Field(value: _storage._minResidualBytes, fieldNumber: 20)
}
if _storage._minOutputBytes != 0 {
try visitor.visitSingularInt64Field(value: _storage._minOutputBytes, fieldNumber: 21)
}
if _storage._minAcceleratorMicros != 0 {
try visitor.visitSingularInt64Field(value: _storage._minAcceleratorMicros, fieldNumber: 22)
}
if _storage._minCpuMicros != 0 {
try visitor.visitSingularInt64Field(value: _storage._minCpuMicros, fieldNumber: 23)
}
}
try unknownFields.traverse(visitor: &visitor)
}
fileprivate var _storage = _StorageClass.defaultInstance
}
public struct Tensorflow_Tfprof_AdvisorOptionsProto: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".AdvisorOptionsProto"
/// checker name -> a dict of key-value options.
public var checkers: Dictionary<String,Tensorflow_Tfprof_AdvisorOptionsProto.CheckerOption> = [:]
public var unknownFields = SwiftProtobuf.UnknownStorage()
public struct CheckerOption: SwiftProtobuf.Message {
public static let protoMessageName: String = Tensorflow_Tfprof_AdvisorOptionsProto.protoMessageName + ".CheckerOption"
public var options: Dictionary<String,String> = [:]
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &self.options)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.options.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: self.options, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
}
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,Tensorflow_Tfprof_AdvisorOptionsProto.CheckerOption>.self, value: &self.checkers)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.checkers.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,Tensorflow_Tfprof_AdvisorOptionsProto.CheckerOption>.self, value: self.checkers, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "tensorflow.tfprof"
extension Tensorflow_Tfprof_OptionsProto: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "max_depth"),
2: .standard(proto: "min_bytes"),
19: .standard(proto: "min_peak_bytes"),
20: .standard(proto: "min_residual_bytes"),
21: .standard(proto: "min_output_bytes"),
3: .standard(proto: "min_micros"),
22: .standard(proto: "min_accelerator_micros"),
23: .standard(proto: "min_cpu_micros"),
4: .standard(proto: "min_params"),
5: .standard(proto: "min_float_ops"),
17: .standard(proto: "min_occurrence"),
18: .same(proto: "step"),
7: .standard(proto: "order_by"),
8: .standard(proto: "account_type_regexes"),
9: .standard(proto: "start_name_regexes"),
10: .standard(proto: "trim_name_regexes"),
11: .standard(proto: "show_name_regexes"),
12: .standard(proto: "hide_name_regexes"),
13: .standard(proto: "account_displayed_op_only"),
14: .same(proto: "select"),
15: .same(proto: "output"),
16: .standard(proto: "dump_to_file"),
]
fileprivate class _StorageClass {
var _maxDepth: Int64 = 0
var _minBytes: Int64 = 0
var _minPeakBytes: Int64 = 0
var _minResidualBytes: Int64 = 0
var _minOutputBytes: Int64 = 0
var _minMicros: Int64 = 0
var _minAcceleratorMicros: Int64 = 0
var _minCpuMicros: Int64 = 0
var _minParams: Int64 = 0
var _minFloatOps: Int64 = 0
var _minOccurrence: Int64 = 0
var _step: Int64 = 0
var _orderBy: String = String()
var _accountTypeRegexes: [String] = []
var _startNameRegexes: [String] = []
var _trimNameRegexes: [String] = []
var _showNameRegexes: [String] = []
var _hideNameRegexes: [String] = []
var _accountDisplayedOpOnly: Bool = false
var _select: [String] = []
var _output: String = String()
var _dumpToFile: String = String()
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_maxDepth = source._maxDepth
_minBytes = source._minBytes
_minPeakBytes = source._minPeakBytes
_minResidualBytes = source._minResidualBytes
_minOutputBytes = source._minOutputBytes
_minMicros = source._minMicros
_minAcceleratorMicros = source._minAcceleratorMicros
_minCpuMicros = source._minCpuMicros
_minParams = source._minParams
_minFloatOps = source._minFloatOps
_minOccurrence = source._minOccurrence
_step = source._step
_orderBy = source._orderBy
_accountTypeRegexes = source._accountTypeRegexes
_startNameRegexes = source._startNameRegexes
_trimNameRegexes = source._trimNameRegexes
_showNameRegexes = source._showNameRegexes
_hideNameRegexes = source._hideNameRegexes
_accountDisplayedOpOnly = source._accountDisplayedOpOnly
_select = source._select
_output = source._output
_dumpToFile = source._dumpToFile
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public func _protobuf_generated_isEqualTo(other: Tensorflow_Tfprof_OptionsProto) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_storage, other_storage) in
if _storage._maxDepth != other_storage._maxDepth {return false}
if _storage._minBytes != other_storage._minBytes {return false}
if _storage._minPeakBytes != other_storage._minPeakBytes {return false}
if _storage._minResidualBytes != other_storage._minResidualBytes {return false}
if _storage._minOutputBytes != other_storage._minOutputBytes {return false}
if _storage._minMicros != other_storage._minMicros {return false}
if _storage._minAcceleratorMicros != other_storage._minAcceleratorMicros {return false}
if _storage._minCpuMicros != other_storage._minCpuMicros {return false}
if _storage._minParams != other_storage._minParams {return false}
if _storage._minFloatOps != other_storage._minFloatOps {return false}
if _storage._minOccurrence != other_storage._minOccurrence {return false}
if _storage._step != other_storage._step {return false}
if _storage._orderBy != other_storage._orderBy {return false}
if _storage._accountTypeRegexes != other_storage._accountTypeRegexes {return false}
if _storage._startNameRegexes != other_storage._startNameRegexes {return false}
if _storage._trimNameRegexes != other_storage._trimNameRegexes {return false}
if _storage._showNameRegexes != other_storage._showNameRegexes {return false}
if _storage._hideNameRegexes != other_storage._hideNameRegexes {return false}
if _storage._accountDisplayedOpOnly != other_storage._accountDisplayedOpOnly {return false}
if _storage._select != other_storage._select {return false}
if _storage._output != other_storage._output {return false}
if _storage._dumpToFile != other_storage._dumpToFile {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Tensorflow_Tfprof_AdvisorOptionsProto: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "checkers"),
]
public func _protobuf_generated_isEqualTo(other: Tensorflow_Tfprof_AdvisorOptionsProto) -> Bool {
if self.checkers != other.checkers {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Tensorflow_Tfprof_AdvisorOptionsProto.CheckerOption: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "options"),
]
public func _protobuf_generated_isEqualTo(other: Tensorflow_Tfprof_AdvisorOptionsProto.CheckerOption) -> Bool {
if self.options != other.options {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
| mit |
sarvex/SwiftRecepies | Tables/Providing Header and Footer in a Collection View/Providing Header and Footer in a Collection ViewTests/Providing_Header_and_Footer_in_a_Collection_ViewTests.swift | 1 | 1787 | //
// Providing_Header_and_Footer_in_a_Collection_ViewTests.swift
// Providing Header and Footer in a Collection ViewTests
//
// Created by Vandad Nahavandipoor on 7/2/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at vandad.np@gmail.com
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import XCTest
class Providing_Header_and_Footer_in_a_Collection_ViewTests: 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.
}
}
}
| isc |
cconeil/Standard-Template-Protocols | STP/BlockGestureRecognizer.swift | 1 | 1720 | //
// BlockGestureRecognizer.swift
// STP
//
// Created by Chris O'Neil on 10/11/15.
// Copyright © 2015 Because. All rights reserved.
//
private class MultiDelegate : NSObject, UIGestureRecognizerDelegate {
@objc func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension UIGestureRecognizer {
struct PropertyKeys {
static var blockKey = "BCBlockPropertyKey"
static var multiDelegateKey = "BCMultiDelegateKey"
}
private var block:((recognizer:UIGestureRecognizer) -> Void) {
get {
return Associator.getAssociatedObject(self, associativeKey:&PropertyKeys.blockKey)!
}
set {
Associator.setAssociatedObject(self, value: newValue, associativeKey:&PropertyKeys.blockKey, policy: .OBJC_ASSOCIATION_RETAIN)
}
}
private var multiDelegate:MultiDelegate {
get {
return Associator.getAssociatedObject(self, associativeKey:&PropertyKeys.multiDelegateKey)!
}
set {
Associator.setAssociatedObject(self, value: newValue, associativeKey:&PropertyKeys.multiDelegateKey, policy: .OBJC_ASSOCIATION_RETAIN)
}
}
convenience init(block:(recognizer:UIGestureRecognizer) -> Void) {
self.init()
self.block = block
self.multiDelegate = MultiDelegate()
self.delegate = self.multiDelegate
self.addTarget(self, action: "didInteractWithGestureRecognizer:")
}
@objc func didInteractWithGestureRecognizer(sender:UIGestureRecognizer) {
self.block(recognizer: sender)
}
}
| mit |
benlangmuir/swift | test/multifile/resilient-module.swift | 28 | 949 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift-dylib(%t/%target-library-name(A)) -enable-library-evolution -module-name A -emit-module -emit-module-path %t/A.swiftmodule %S/Inputs/resilient-module-2.swift
// RUN: %target-swift-frontend -enable-library-evolution -module-name A %S/Inputs/resilient-module-2.swift -emit-ir | %FileCheck --check-prefix=METADATA %s
// RUN: %target-build-swift -I%t -L%t -lA -o %t/main %target-rpath(%t) %s
// RUN: %target-build-swift -I%t -L%t -lA -o %t/main %target-rpath(%t) %s
// RUN: %target-codesign %t/main %t/%target-library-name(A)
// RUN: %target-run %t/main %t/%target-library-name(A) | %FileCheck %s
// REQUIRES: executable_test
// METADATA: @"$s1A8SomeEnumOMn" = {{.*}}constant <{ i32, i32, i32, i32, i32, i32, i32 }> <{{{.*}} i32 33554434, i32 0 }>
import A
func runTest() {
let e = SomeEnum.first(ResilientType.a(Int64(10)))
// CHECK: first(A.ResilientType.a(10))
print(e)
}
runTest()
| apache-2.0 |
samodom/UIKitSwagger | UIKitSwaggerTests/Tests/HSBComponentsTests.swift | 1 | 7748 | //
// HSBComponentsTests.swift
// UIKitSwagger
//
// Created by Sam Odom on 3/1/15.
// Copyright (c) 2015 Swagger Soft. All rights reserved.
//
import UIKit
import XCTest
@testable import UIKitSwagger
// See `ColorTestHelpers.swift` for colors and values used herein.
class HSBComponentsTests: XCTestCase {
var components = HSBComponents(
hue: randomHueValue,
saturation: randomSaturationValue,
brightness: randomBrightnessValue,
alpha: randomAlphaValue
)
// MARK: - Component values
func testHueComponentWithRGBColor() {
XCTAssertEqual(sampleRGBColor.hue, sampleRGBColor.hsbComponents.hue, "The hue component of the RGB color should be provided")
}
func testHueComponentWithHSBColor() {
XCTAssertEqualWithAccuracy(sampleHSBColor.hue, randomHueValue, accuracy: ColorComponentValueTestAccuracy, "The hue component of the HSB color should be provided")
}
func testHueComponentWithMonochromeColor() {
XCTAssertEqual(sampleMonochromeColor.hue, sampleMonochromeColor.hsbComponents.hue, "The hue component of the monochrome color should be provided")
}
func testSaturationComponentWithRGBColor() {
XCTAssertEqual(sampleRGBColor.saturation, sampleRGBColor.hsbComponents.saturation, "The saturation component of the RGB color should be provided")
}
func testSaturationComponentWithHSBColor() {
XCTAssertEqualWithAccuracy(sampleHSBColor.saturation, randomSaturationValue, accuracy: ColorComponentValueTestAccuracy, "The saturation component of the HSB color should be provided")
}
func testSaturationComponentWithMonochromeColor() {
XCTAssertEqual(sampleMonochromeColor.saturation, sampleMonochromeColor.hsbComponents.saturation, "The saturation component of the monochrome color should be provided")
}
func testBrightnessComponentWithRGBColor() {
XCTAssertEqual(sampleRGBColor.brightness, sampleRGBColor.hsbComponents.brightness, "The brightness component of the RGB color should be provided")
}
func testBrightnessComponentWithHSBColor() {
XCTAssertEqualWithAccuracy(sampleHSBColor.brightness, randomBrightnessValue, accuracy: ColorComponentValueTestAccuracy, "The brightness component of the HSB color should be provided")
}
func testBrightnessComponentWithMonochromeColor() {
XCTAssertEqual(sampleMonochromeColor.brightness, sampleMonochromeColor.hsbComponents.brightness, "The white component of the monochrome color should be provided")
}
// MARK: Components structure
func testHSBComponentStructureWithDefaultAlpha() {
components = HSBComponents(
hue: randomHueValue,
saturation: randomSaturationValue,
brightness: randomBrightnessValue
)
XCTAssertEqual(components.hue, randomHueValue, "The components should include a hue value")
XCTAssertEqual(components.saturation, randomSaturationValue, "The components should include a saturation value")
XCTAssertEqual(components.brightness, randomBrightnessValue, "The components should include a brightness value")
XCTAssertEqual(components.alpha, 1.0, "The components should use a default alpha value of 1.0")
}
func testHSBComponentStructure() {
XCTAssertEqual(components.hue, randomHueValue, "The components should include a hue value")
XCTAssertEqual(components.saturation, randomSaturationValue, "The components should include a saturation value")
XCTAssertEqual(components.brightness, randomBrightnessValue, "The components should include a brightness value")
XCTAssertEqual(components.alpha, randomAlphaValue, "The components should include an alpha value")
}
// MARK: Equality
func testEqualityOfHSBComponentStructure() {
let moreComponents = HSBComponents(
hue: randomHueValue,
saturation: randomSaturationValue,
brightness: randomBrightnessValue,
alpha: randomAlphaValue
)
XCTAssertEqual(components, moreComponents, "The components should be considered equal")
}
func testInequalityOfHSBComponentsWithMismatchedHueValues() {
let moreComponents = HSBComponents(
hue: nudgeComponentValue(randomHueValue),
saturation: randomSaturationValue,
brightness: randomBrightnessValue,
alpha: randomAlphaValue
)
XCTAssertNotEqual(components, moreComponents, "The components should not be considered equal")
}
func testInequalityOfHSBComponentsWithMismatchedSaturationValues() {
let moreComponents = HSBComponents(
hue: randomHueValue,
saturation: nudgeComponentValue(randomSaturationValue),
brightness: randomBrightnessValue,
alpha: randomAlphaValue
)
XCTAssertNotEqual(components, moreComponents, "The components should not be considered equal")
}
func testInequalityOfHSBComponentsWithMismatchedBrightnessValues() {
let moreComponents = HSBComponents(
hue: randomHueValue,
saturation: randomSaturationValue,
brightness: nudgeComponentValue(randomBrightnessValue),
alpha: randomAlphaValue
)
XCTAssertNotEqual(components, moreComponents, "The components should not be considered equal")
}
func testInequalityOfHSBComponentsWithMismatchedAlphaValues() {
let moreComponents = HSBComponents(
hue: randomHueValue,
saturation: randomSaturationValue,
brightness: randomBrightnessValue,
alpha: nudgeComponentValue(randomAlphaValue)
)
XCTAssertNotEqual(components, moreComponents, "The components should not be considered equal")
}
// MARK: Creating components from colors
func testHSBComponentsWithRGBColor() {
var hueValue = CGFloat(0)
var saturationValue = CGFloat(0)
var brightnessValue = CGFloat(0)
var alphaValue = CGFloat(0)
sampleRGBColor.getHue(&hueValue,
saturation: &saturationValue,
brightness: &brightnessValue,
alpha: &alphaValue
)
components = HSBComponents(
hue: hueValue,
saturation: saturationValue,
brightness: brightnessValue,
alpha: alphaValue
)
XCTAssertEqual(sampleRGBColor.hsbComponents, components, "The hue, saturation, brightness and alpha components of the color should be provided")
}
func testHSBComponentsWithHSBColor() {
XCTAssertEqual(sampleHSBColor.hsbComponents, components, "The hue, saturation, brightness and alpha components of the color should be provided")
}
func testHSBComponentsWithMonochromeColor() {
var hueValue = CGFloat(0)
var saturationValue = CGFloat(0)
var brightnessValue = CGFloat(0)
var alphaValue = CGFloat(0)
sampleMonochromeColor.getHue(&hueValue,
saturation: &saturationValue,
brightness: &brightnessValue,
alpha: &alphaValue
)
components = HSBComponents(
hue: hueValue,
saturation: saturationValue,
brightness: brightnessValue,
alpha: alphaValue
)
XCTAssertEqual(sampleMonochromeColor.hsbComponents, components, "The hue, saturation, brightness and alpha components of the color should be provided")
}
// MARK: Creating colors from components
func testColorCreationWithHSBComponents() {
XCTAssertEqual(components.color(), sampleHSBColor, "The components should create an instance of UIColor using the same values")
}
}
| mit |
raycoast/FlowChartKit | FlowChartKit/FlowChart/FlowChartView+DrawShape.swift | 1 | 10637 | //
// FlowChartView+DrawShape.swift
// FlowChartKit
//
// Created by QiangRen on 11/5/15.
// Copyright (c) 2015 QiangRen. All rights reserved.
//
import UIKit
// MARK: - CoreGraphics Shapes
extension FlowChartView {
func drawShape(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) {
let view: UIView
switch shape.type {
case .Circle:
view = drawCircle(shape, style: style)
case .Oval: // Terminal
view = drawOval(shape, style: style)
case .Ellipse:
view = drawEllipse(shape, style: style)
case .Square: // Process
view = drawSquare(shape, style: style)
case .Diamond: // Decision
view = drawDiamond(shape, style: style)
case .Quadangle: // Input/Output
view = drawQuadangle(shape, style: style)
case .Hexagon: // Preparation
view = drawHexagon(shape, style: style)
}
contentView.addSubview(view)
shape.draw(view, style: style)
}
func drawCircle(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let d = min(shape.rect.size.width, shape.rect.size.height)
let dx = (shape.rect.size.width - d) / 2
let dy = (shape.rect.size.height - d) / 2
let rect = shape.rect.rectByInsetting(dx: dx, dy: dy)
let v = UIButton(frame: rect)
v.layer.cornerRadius = d / 2
v.layer.borderColor = style.borderColor
v.layer.borderWidth = style.borderWidth
v.setTitleColor(style.textColor, forState: .Normal)
v.setTitle(shape.title, forState: UIControlState.Normal)
return v
}
func drawOval(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIButton(frame: shape.rect)
v.layer.cornerRadius = min(shape.rect.width, shape.rect.height) / 2
v.layer.borderColor = style.borderColor
v.layer.borderWidth = style.borderWidth
v.setTitleColor(style.textColor, forState: .Normal)
v.setTitle(shape.title, forState: UIControlState.Normal)
v.addTarget(self, action: "onTaped:", forControlEvents: .TouchUpInside)
for (i, s) in enumerate(shapes ?? []) {
if s.id == shape.id {
v.tag = i
break
}
}
return v
}
func drawEllipse(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
CGPathAddEllipseInRect(path, nil, CGRectMake(0, 0, shape.rect.width, shape.rect.height))
//CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func drawSquare(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIButton(frame: shape.rect)
v.layer.cornerRadius = style.cornerRadius
v.layer.borderColor = style.borderColor
v.layer.borderWidth = style.borderWidth
v.setTitleColor(style.textColor, forState: .Normal)
v.setTitle(shape.title, forState: UIControlState.Normal)
v.addTarget(self, action: "onTaped:", forControlEvents: .TouchUpInside)
for (i, s) in enumerate(shapes ?? []) {
if s.id == shape.id {
v.tag = i
break
}
}
return v
}
func drawDiamond(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
let points = [
CGPointMake(shape.rect.width / 2, 0),
CGPointMake(shape.rect.width, shape.rect.height / 2),
CGPointMake(shape.rect.width / 2, shape.rect.height),
CGPointMake(0, shape.rect.height / 2),
CGPointMake(shape.rect.width / 2, 0),
]
//CGPathMoveToPoint(path, nil, shape.rect.midX, 0)
CGPathAddLines(path, nil, points, points.count)
CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func drawQuadangle(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
let halfHeight = shape.rect.size.height/2
let halfWidth = shape.rect.size.width/2
let oneQuarterHeight = shape.rect.size.height/4
let oneQuarterWidth = shape.rect.size.width/4
let threeQuarterHeight = oneQuarterHeight * 3
let threeQuarterWidth = oneQuarterWidth * 3
let fullHeight = shape.rect.size.height
let fullWidth = shape.rect.size.width
let originX: CGFloat = 0.0 //shape.rect.origin.x
let originY: CGFloat = 0.0 //shape.rect.origin.y
let radius:CGFloat = style.cornerRadius //fullHeight/9.0
//CENTERS
let leftBottom = CGPoint(x: originX, y: originY + fullHeight)
let rightTop = CGPoint(x: originX + fullWidth, y: originY)
//QUARTERS
let leftTopQuarter = CGPoint(x: originX + oneQuarterWidth, y: originY)
let rightBottomQuarter = CGPoint(x: originX + threeQuarterWidth, y: originY + fullHeight)
//Computed Start Point
let computedX = leftBottom.x + (leftTopQuarter.x - leftBottom.x)/2.0
let computedY = leftBottom.y - (leftBottom.y - leftTopQuarter.y)/2.0
//Start here (needs to be between first and last point
//This will be the top center of the view, so half way in (X) and full up (Y)
CGPathMoveToPoint(path, nil, computedX, computedY)
//Take it to that point, and point it at the next direction
CGPathAddArcToPoint(path, nil, leftTopQuarter.x, leftTopQuarter.y, rightTop.x, rightTop.y, radius)
CGPathAddArcToPoint(path, nil, rightTop.x, rightTop.y, rightBottomQuarter.x, rightBottomQuarter.y, radius)
CGPathAddArcToPoint(path, nil, rightBottomQuarter.x, rightBottomQuarter.y, leftBottom.x, leftBottom.y, radius)
CGPathAddArcToPoint(path, nil, leftBottom.x, leftBottom.y, leftTopQuarter.x, leftTopQuarter.y, radius)
CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func drawHexagon(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
let halfHeight = shape.rect.size.height/2
let halfWidth = shape.rect.size.width/2
let oneQuarterHeight = shape.rect.size.height/4
let oneQuarterWidth = shape.rect.size.width/4
let threeQuarterHeight = oneQuarterHeight * 3
let threeQuarterWidth = oneQuarterWidth * 3
let fullHeight = shape.rect.size.height
let fullWidth = shape.rect.size.width
let originX: CGFloat = 0.0 //shape.rect.origin.x
let originY: CGFloat = 0.0 //shape.rect.origin.y
let radius:CGFloat = style.cornerRadius //fullHeight/9.0
//CENTERS
let leftCenter = CGPoint(x: originX, y: originY + halfHeight)
let rightCenter = CGPoint(x: originX + fullWidth, y: originY + halfHeight)
//QUARTERS
let leftTopQuarter = CGPoint(x: originX + oneQuarterWidth, y: originY)
let leftBottomQuarter = CGPoint(x: originX + oneQuarterWidth, y: originY + fullHeight)
let rightTopQuarter = CGPoint(x: originX + threeQuarterWidth, y: originY)
let rightBottomQuarter = CGPoint(x: originX + threeQuarterWidth, y: originY + fullHeight)
//Computed Start Point
let computedX = leftCenter.x + (leftBottomQuarter.x - leftCenter.x)/2.0
let computedY = leftCenter.y - (leftBottomQuarter.y - leftCenter.y)/2.0
//Start here (needs to be between first and last point
//This will be the top center of the view, so half way in (X) and full up (Y)
CGPathMoveToPoint(path, nil, computedX, computedY)
//Take it to that point, and point it at the next direction
CGPathAddArcToPoint(path, nil, leftTopQuarter.x, leftTopQuarter.y, rightTopQuarter.x, rightTopQuarter.y, radius)
CGPathAddArcToPoint(path, nil, rightTopQuarter.x, rightTopQuarter.y, rightCenter.x, rightCenter.y, radius)
CGPathAddArcToPoint(path, nil, rightCenter.x, rightCenter.y, rightBottomQuarter.x, rightBottomQuarter.y, radius)
CGPathAddArcToPoint(path, nil, rightBottomQuarter.x, rightBottomQuarter.y, leftBottomQuarter.x, leftBottomQuarter.y, radius)
CGPathAddArcToPoint(path, nil, leftBottomQuarter.x, leftBottomQuarter.y, leftCenter.x, leftCenter.y, radius)
//
CGPathAddArcToPoint(path, nil, leftCenter.x, leftCenter.y, leftTopQuarter.x, leftTopQuarter.y, radius)
CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func onTaped(sender: UIButton) {
delegate?.flowChartView(self, didTaponShape: self.shapes?[sender.tag])
}
}
| bsd-2-clause |
Pocketbrain/nativeadslib-ios | PocketMediaNativeAds/DataSource/TableView/NativeAdTableViewDataSource.swift | 1 | 8396 | //
// UITableViewDataSourceAdapater.swift
// PocketMediaNativeAds
//
// Created by Kees Bank on 02/03/16.
// Copyright © 2016 PocketMedia. All rights reserved.
//
import UIKit
/**
Wraps around a datasource so it contains both a mix of ads and none ads.
*/
open class NativeAdTableViewDataSource: DataSource, UITableViewDataSource, UITableViewDataSourceWrapper {
/// Original datasource.
open var datasource: UITableViewDataSource
/// Original tableView.
open var tableView: UITableView
/// Original deglegate.
open var delegate: NativeAdTableViewDelegate?
// Ad position logic.
fileprivate var adPosition: AdPosition
/**
Hijacks the sent delegate and datasource and make it use our wrapper. Also registers the ad unit we'll be using.
- parameter controller: The controller to create NativeAdTableViewDelegate
- parameter tableView: The tableView this datasource is attached to.
- parameter adPosition: The instance that will define where ads are positioned.
*/
@objc
public required init(controller: UIViewController, tableView: UITableView, adPosition: AdPosition, customXib: UINib? = nil) {
if tableView.dataSource == nil {
preconditionFailure("Your tableview must have a dataSource set before use.")
}
self.datasource = tableView.dataSource!
self.adPosition = adPosition
self.tableView = tableView
super.init(type: AdUnit.UIType.TableView, customXib: customXib, adPosition: adPosition)
UITableView.swizzleNativeAds(tableView)
// Hijack the delegate and datasource and make it use our wrapper.
if tableView.delegate != nil {
self.delegate = NativeAdTableViewDelegate(datasource: self, controller: controller, delegate: tableView.delegate!)
tableView.delegate = self.delegate
}
tableView.dataSource = self
}
/**
Reset the datasource. if this wrapper is deinitialized.
*/
deinit {
self.tableView.dataSource = datasource
}
/**
This function checks if we have a cell registered with that name. If not we'll register it.
*/
public override func registerNib(nib: UINib?, identifier: String) {
let bundle = PocketMediaNativeAdsBundle.loadBundle()!
let registerNib = nib == nil ? UINib(nibName: identifier, bundle: bundle) : nib
tableView.register(registerNib, forCellReuseIdentifier: identifier)
}
/**
Return the cell of a identifier.
*/
public override func dequeueReusableCell(identifier: String, indexPath: IndexPath) -> UIView {
return tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
/**
Required. Asks the data source for a cell to insert in a particular location of the table view.
*/
@objc
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let listing = getNativeAdListing(indexPath) {
if let cell = getAdCell(listing.ad, indexPath: indexPath) as? UITableViewCell {
return cell
}
return UITableViewCell()
}
return datasource.tableView(tableView, cellForRowAt: getOriginalPositionForElement(indexPath))
}
/**
Returns the number of rows (table cells) in a specified section.
*/
@objc
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let ads = adListingsPerSection[section]?.count {
return datasource.tableView(tableView, numberOfRowsInSection: section) + ads
}
return datasource.tableView(tableView, numberOfRowsInSection: section)
}
/**
Asks the data source for the title of the header of the specified section of the table view.
*/
@objc
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let string = datasource.tableView?(tableView, titleForHeaderInSection: section) {
return string
}
return nil
}
/**
Asks the data source for the title of the footer of the specified section of the table view.
*/
@objc
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if let string = datasource.tableView?(tableView, titleForFooterInSection: section) {
return string
}
return nil
}
/**
Asks the data source to verify that the given row is editable.
*/
@objc
open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:canEditRowAt:))) {
return datasource.tableView!(tableView, canEditRowAt: indexPath)
}
return true
}
/**
Asks the data source whether a given row can be moved to another location in the table view.
*/
@objc
open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:canMoveRowAt:))) {
return datasource.tableView!(tableView, canMoveRowAt: indexPath)
}
return true
}
/**
Asks the data source to return the index of the section having the given title and section title index.
*/
@objc
open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:sectionForSectionIndexTitle:at:))) {
return datasource.tableView!(tableView, sectionForSectionIndexTitle: title, at: index)
}
return 0
}
/**
Tells the data source to move a row at a specific location in the table view to another location.
*/
@objc
open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:moveRowAt:to:))) {
datasource.tableView?(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath)
}
}
/**
Asks the data source to return the titles for the sections for a table view.
*/
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return datasource.sectionIndexTitles?(for: tableView)
}
/**
default is UITableViewCellEditingStyleNone. This is set by UITableView using the delegate's value for cells who customize their appearance
*/
@objc
open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
datasource.tableView?(tableView, commit: editingStyle, forRowAt: indexPath)
}
/**
Method that dictates what happens when a ad network request resulted successful. It should kick off what to do with this list of ads.
- important:
Abstract classes that a datasource should override. It's specific to the type of data source.
*/
open override func onAdRequestSuccess(_ ads: [NativeAd]) {
super.onAdRequestSuccess(ads)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.tableView.reloadData()
}
}
/**
The actual important to a UITableView functions are down below here.
*/
@objc
open func numberOfSections(in tableView: UITableView) -> Int {
if let result = datasource.numberOfSections?(in: tableView) {
return result
}
return 1
}
public override func numberOfSections() -> Int {
return numberOfSections(in: self.tableView)
}
public override func numberOfRowsInSection(section: Int) -> Int {
return datasource.tableView(tableView, numberOfRowsInSection: section)
}
open override func reloadRowsAtIndexPaths(indexPaths: [IndexPath], animation: Bool) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.tableView.beginUpdates()
self.tableView.reloadRows(at: indexPaths, with: animation ? UITableViewRowAnimation.automatic : UITableViewRowAnimation.none)
self.tableView.endUpdates()
}
}
}
| mit |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/Content/Text/ConversationFileMessageCell.swift | 1 | 4807 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireDataModel
final class ConversationFileMessageCell: RoundedView, ConversationMessageCell {
struct Configuration {
let message: ZMConversationMessage
var isObfuscated: Bool {
return message.isObfuscated
}
}
private var containerView = UIView()
private let fileTransferView = FileTransferView(frame: .zero)
private let obfuscationView = ObfuscationView(icon: .paperclip)
private let restrictionView = FileMessageRestrictionView()
weak var delegate: ConversationMessageCellDelegate?
weak var message: ZMConversationMessage?
var isSelected: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
configureSubview()
configureConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureSubview() {
shape = .rounded(radius: 4)
backgroundColor = .from(scheme: .placeholderBackground)
clipsToBounds = true
addSubview(containerView)
}
private func configureConstraints() {
containerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
heightAnchor.constraint(equalToConstant: 56),
// containerView
containerView.leadingAnchor.constraint(equalTo: leadingAnchor),
containerView.topAnchor.constraint(equalTo: topAnchor),
containerView.trailingAnchor.constraint(equalTo: trailingAnchor),
containerView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
func configure(with object: Configuration, animated: Bool) {
if object.isObfuscated {
setup(obfuscationView)
} else if !object.message.canBeShared {
setup(restrictionView)
restrictionView.configure(for: object.message)
} else {
setup(fileTransferView)
fileTransferView.delegate = self
fileTransferView.configure(for: object.message, isInitial: false)
}
}
private func setup(_ view: UIView) {
containerView.removeSubviews()
containerView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
view.topAnchor.constraint(equalTo: containerView.topAnchor),
view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])
}
override public var tintColor: UIColor! {
didSet {
self.fileTransferView.tintColor = self.tintColor
}
}
var selectionView: UIView! {
return fileTransferView
}
var selectionRect: CGRect {
return fileTransferView.bounds
}
}
extension ConversationFileMessageCell: TransferViewDelegate {
func transferView(_ view: TransferView, didSelect action: MessageAction) {
guard let message = message else { return }
delegate?.perform(action: action, for: message, view: self)
}
}
final class ConversationFileMessageCellDescription: ConversationMessageCellDescription {
typealias View = ConversationFileMessageCell
let configuration: View.Configuration
var topMargin: Float = 8
var showEphemeralTimer: Bool = false
let isFullWidth: Bool = false
let supportsActions: Bool = true
let containsHighlightableContent: Bool = true
weak var message: ZMConversationMessage?
weak var delegate: ConversationMessageCellDelegate?
weak var actionController: ConversationMessageActionController?
var accessibilityIdentifier: String? {
return configuration.isObfuscated ? "ObfuscatedFileCell" : "FileCell"
}
let accessibilityLabel: String? = nil
init(message: ZMConversationMessage) {
self.configuration = View.Configuration(message: message)
}
}
| gpl-3.0 |
mikewxk/DYLiveDemo_swift | DYLiveDemo/DYLiveDemo/Classes/Tools/Extension/UIBarButtonItem-Ext.swift | 1 | 1282 | //
// UIBarButtonItem-Ext.swift
// DYLiveDemo
//
// Created by xiaokui wu on 12/16/16.
// Copyright © 2016 wxk. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
/* 类方法扩展,swift鼓励用构造函数
class func createItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: .Normal)
btn.setImage(UIImage(named: highImageName), forState: .Highlighted)
btn.frame = CGRect(origin: CGPointZero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
// 在extension中只能扩展便捷构造函数, 1必须以convenience开头,2必须明确调用指定构造函数
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSizeZero) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: .Normal)
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), forState: .Highlighted)
}
if size == CGSizeZero {
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPointZero, size: size)
}
self.init(customView: btn)
}
}
| unlicense |
Liujlai/DouYuD | DYTV/DYTV/GameViewController.swift | 1 | 5682 | //
// GameViewController.swift
// DYTV
//
// Created by idea on 2017/8/12.
// Copyright © 2017年 idea. All rights reserved.
//
import UIKit
//边缘间距
private let kEdgeMargin :CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH : CGFloat = kItemW * 6 / 5
private let kHeaderViewH : CGFloat = 50
private let kGameViewH: CGFloat = 90
private let kGameCellID = "kGameCellID"
private let kHeaderViewID = "kHeaderViewID"
class GameViewController: BaseViewController {
//MARK:懒加载属性
fileprivate lazy var gameVM :GameViewModel = GameViewModel()
fileprivate lazy var collectionView: UICollectionView = { [ unowned self ] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
// 最小间距为0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
// 添加头部
layout.headerReferenceSize = CGSize(width: kScreenH, height: kHeaderViewH)
// 2. 创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
//为了让其显示,注册Cell
collectionView.register( UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 注册头部
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.dataSource = self
return collectionView
}()
fileprivate lazy var topHeaderView: CollectionHeaderView = {
let headerView = CollectionHeaderView.collectionHeaderView()
headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH)
headerView.iconImageView.image = UIImage(named: "shortvideo_column_dot")
headerView.titleLable.text = "常用"
// 把button隐藏起来
headerView.moreBtn.isHidden = true
return headerView
}()
fileprivate lazy var gameView: RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
//MARK: 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: 设置UI界面
extension GameViewController{
override func setupUI(){
// 添加加载动画
// 给contenView进行赋值
contenView = collectionView
// 1.添加UICollectionView
view.addSubview(collectionView)
// 2.添加顶部的HeaderView
collectionView.addSubview(topHeaderView)
// 3. 将常用游戏的View,添加到collectionView中
collectionView.addSubview(gameView)
// 为了不用往下拖动就显示,设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0)
super.setupUI()
}
}
//MARK: 请求数据
extension GameViewController{
fileprivate func loadData(){
gameVM.loadAllGameData {
// 1.显示全部游戏
self.collectionView.reloadData()
// 2.展示常用游戏
// var tempArray = [BaseGameModel]()
// for i in 0..<10{
// tempArray.append(self.gameVM.game[i])
// }
//
// self.gameView.groups = tempArray
self.gameView.groups = Array(self.gameVM.game[0..<10])
// 3.数据请求完成
self.loadDataFinished()
}
}
}
//MARK: 遵守UICollectionView 的数据源&代理
extension GameViewController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.game.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
// 设置随机背景颜色
// cell.backgroundColor = UIColor.randomColor()
cell.baseGame = gameVM.game[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HearderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置属性
headerView.titleLable.text = "全部"
headerView.iconImageView.image = UIImage(named: "shortvideo_column_dot")
// 把button隐藏起来
headerView.moreBtn.isHidden = true
return headerView
}
}
| mit |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDKTests/SBAActivityArchiveTests.swift | 1 | 12987 | //
// SBAActivityArchive.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
class SBAActivityArchive: 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()
}
// MARK: V1 Survey support
func testSingleChoiceQuestionResult() {
let result = ORKChoiceQuestionResult(identifier: "test")
result.questionType = .singleChoice
result.choiceAnswers = ["answer"]
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "SingleChoice")
guard let choiceAnswers = json["choiceAnswers"] as? [String] else {
XCTAssert(false, "\(String(describing: json["choiceAnswers"])) not of expected type")
return
}
XCTAssertEqual(choiceAnswers, ["answer"])
guard let answer = json["answer"] as? String else {
XCTAssert(false, "\(String(describing: json["answer"])) not of expected type")
return
}
XCTAssertEqual(answer, "answer")
}
func testMultipleChoiceQuestionResult() {
let result = ORKChoiceQuestionResult(identifier: "test")
result.questionType = .multipleChoice
result.choiceAnswers = ["A", "B"]
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "MultipleChoice")
guard let choiceAnswers = json["choiceAnswers"] as? [String] else {
XCTAssert(false, "\(String(describing: json["choiceAnswers"])) not of expected type")
return
}
XCTAssertEqual(choiceAnswers, ["A", "B"])
}
func testScaleQuestionResult() {
let result = ORKScaleQuestionResult(identifier: "test")
result.questionType = .scale
result.scaleAnswer = NSNumber(value: 5)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Scale")
XCTAssertEqual(json["scaleAnswer"] as? NSNumber, NSNumber(value: 5))
}
func testBooleanQuestionResult() {
let result = ORKBooleanQuestionResult(identifier: "test")
result.questionType = .boolean
result.booleanAnswer = NSNumber(value: true)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Boolean")
XCTAssertEqual(json["booleanAnswer"] as? NSNumber, NSNumber(value: true))
}
func testTextQuestionResult() {
let result = ORKTextQuestionResult(identifier: "test")
result.questionType = .text
result.textAnswer = "foo bar"
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Text")
XCTAssertEqual(json["textAnswer"] as? String, "foo bar")
}
func testNumericQuestionResult_Integer() {
let result = ORKNumericQuestionResult(identifier: "test")
result.questionType = .integer
result.numericAnswer = NSNumber(value: 5)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Integer")
XCTAssertEqual(json["numericAnswer"] as? NSNumber, NSNumber(value: 5))
}
func testNumericQuestionResult_Decimal() {
let result = ORKNumericQuestionResult(identifier: "test")
result.questionType = .decimal
result.numericAnswer = NSNumber(value: 1.2)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Decimal")
XCTAssertEqual(json["numericAnswer"] as? NSNumber, NSNumber(value: 1.2))
}
func testTimeOfDayQuestionResult() {
let result = ORKTimeOfDayQuestionResult(identifier: "test")
result.questionType = .timeOfDay
result.dateComponentsAnswer = DateComponents()
result.dateComponentsAnswer?.hour = 5
result.dateComponentsAnswer?.minute = 32
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "TimeOfDay")
XCTAssertEqual(json["dateComponentsAnswer"] as? String, "05:32:00")
}
func testDateQuestionResult_Date() {
let result = ORKDateQuestionResult(identifier: "test")
result.questionType = .date
result.dateAnswer = date(year: 1969, month: 8, day: 3)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Date")
XCTAssertEqual(json["dateAnswer"] as? String, "1969-08-03")
}
func testDateQuestionResult_DateAndTime() {
let result = ORKDateQuestionResult(identifier: "test")
result.questionType = .dateAndTime
result.dateAnswer = date(year: 1969, month: 8, day: 3, hour: 4, minute: 10, second: 00)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Date")
let expectedAnswer = "1969-08-03T04:10:00.000" + timezoneString(for: result.dateAnswer!)
XCTAssertEqual(json["dateAnswer"] as? String, expectedAnswer)
}
func testTimeIntervalQuestionResult() {
// TODO: syoung 08/11/2016 Not currently used by any studies. The implementation that is available in RK
// is limited and does not match the format expected by the server. Revisit this when there is a need to
// support it.
}
// MARK: Helper methods
func checkSharedArchiveKeys(_ result: ORKResult, stepIdentifier: String, expectedFilename: String) -> [AnyHashable: Any]? {
result.startDate = date(year: 2016, month: 7, day: 4, hour: 8, minute: 29, second: 54)
result.endDate = date(year: 2016, month: 7, day: 4, hour: 8, minute: 30, second: 23)
// Create the archive
let archiveObject = result.bridgeData(stepIdentifier)
XCTAssertNotNil(archiveObject)
guard let archiveResult = archiveObject else { return nil }
XCTAssertEqual(archiveResult.filename, expectedFilename)
guard let json = archiveResult.result as? [AnyHashable: Any] else {
XCTAssert(false, "\(archiveResult.result) not of expected type")
return nil
}
// NSDate does not carry the timezone and thus, will always be
// represented in the current timezone
let expectedStart = "2016-07-04T08:29:54.000" + timezoneString(for: result.startDate)
let expectedEnd = "2016-07-04T08:30:23.000" + timezoneString(for: result.endDate)
let actualStart = json["startDate"] as? String
let actualEnd = json["endDate"] as? String
XCTAssertEqual(actualStart, expectedStart)
XCTAssertEqual(actualEnd, expectedEnd)
return json
}
func date(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
var components = DateComponents()
components.day = day
components.month = month
components.year = year
components.hour = hour
components.minute = minute
components.second = second
return calendar.date(from: components)!
}
func timezoneString(for date: Date) -> String {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
guard calendar.timeZone.secondsFromGMT() != 0 else {
return "Z" // At GMT, use a 'Z' rather than time zone offset
}
// Figure out what the timezone would be for different locations
// so that the unit test can use baked in times (that do not rely upon the formatter)
let minuteUnit = 60
let hoursUnit = 60 * minuteUnit
let isDST = calendar.timeZone.isDaylightSavingTime(for: date)
let isNowDST = calendar.timeZone.isDaylightSavingTime()
let timezoneNowHours: Int = calendar.timeZone.secondsFromGMT() / hoursUnit
let timezoneNowMinutes: Int = abs(calendar.timeZone.secondsFromGMT() / minuteUnit - timezoneNowHours * 60)
let timezoneHours: Int = timezoneNowHours + (isDST && !isNowDST ? 1 : 0) + (!isDST && isNowDST ? -1 : 0)
let timezone = String(format: "%+.2d:%.2d", timezoneHours, timezoneNowMinutes)
return timezone
}
}
| bsd-3-clause |
archpoint/sparkmap | app/Spark/WelcomePageViewController.swift | 1 | 3407 | //
// WelcomePageViewController.swift
// SparkMap
//
// Created by Edvard Holst on 13/07/16.
// Copyright © 2016 Zygote Labs. All rights reserved.
//
import UIKit
class WelcomePageViewController: UIPageViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 49/255, green: 42/225, blue: 48/225, alpha: 1.0)
dataSource = self
setViewControllers([getStepZero()], direction: .forward, animated: false, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getStepZero() -> WelcomeZeroViewController {
return storyboard!.instantiateViewController(withIdentifier: "WelcomeZero") as! WelcomeZeroViewController
}
func getStepOne() -> WelcomeOneViewController {
return storyboard!.instantiateViewController(withIdentifier: "WelcomeOne") as! WelcomeOneViewController
}
func getStepTwo() -> WelcomeTwoViewController {
return storyboard!.instantiateViewController(withIdentifier: "WelcomeTwo") as! WelcomeTwoViewController
}
func getStepThree() -> WelcomeThreeViewController {
return storyboard!.instantiateViewController(withIdentifier: "WelcomeThree") as! WelcomeThreeViewController
}
func getStepFour() -> WelcomeFourViewController {
return storyboard!.instantiateViewController(withIdentifier: "WelcomeFour") as! WelcomeFourViewController
}
//Changing Status Bar
override var preferredStatusBarStyle : UIStatusBarStyle {
//LightContent
return UIStatusBarStyle.lightContent
//Default
//return UIStatusBarStyle.Default
}
}
extension WelcomePageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if viewController.isKind(of: WelcomeFourViewController.self) {
return getStepThree()
} else if viewController.isKind(of: WelcomeThreeViewController.self) {
return getStepTwo()
} else if viewController.isKind(of: WelcomeTwoViewController.self) {
return getStepOne()
} else if viewController.isKind(of: WelcomeOneViewController.self) {
return getStepZero()
} else {
return nil
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if viewController.isKind(of: WelcomeZeroViewController.self) {
return getStepOne()
} else if viewController.isKind(of: WelcomeOneViewController.self) {
return getStepTwo()
} else if viewController.isKind(of: WelcomeTwoViewController.self) {
return getStepThree()
} else if viewController.isKind(of: WelcomeThreeViewController.self) {
return getStepFour()
} else {
return nil
}
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return 5
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
| mit |
magicien/GLTFSceneKit | Sources/GLTFSceneKit/GLTFErrors.swift | 1 | 1053 | //
// GLTFErrors.swift
// GLTFSceneKit
//
// Created by magicien on 2017/08/18.
// Copyright © 2017 DarkHorse. All rights reserved.
//
import Foundation
public enum GLTFUnarchiveError: Error {
case DataInconsistent(String)
case NotSupported(String)
case Unknown(String)
}
extension GLTFUnarchiveError: LocalizedError {
public var errorDescription: String? {
switch self {
case .DataInconsistent(let message):
return NSLocalizedString("DataInconsistent: " + message, comment: "")
case .NotSupported(let message):
return NSLocalizedString("NotSupported: " + message, comment: "")
case .Unknown(let message):
return NSLocalizedString(message, comment: "")
}
}
}
public enum GLTFArchiveError: Error {
case Unknown(String)
}
extension GLTFArchiveError: LocalizedError {
public var errorDescription: String? {
switch self {
case .Unknown(let message):
return NSLocalizedString(message, comment: "")
}
}
}
| mit |
alfiehanssen/ThreeSixtyPlayer | ThreeSixtyPlayer/Navigation/DeviceMotionController.swift | 2 | 3057 | //
// DeviceMotionController.swift
// ThreeSixtyPlayer
//
// Created by Alfred Hanssen on 9/25/16.
// Copyright © 2016 Alfie Hanssen. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreMotion
/// A controller that manages device motion updates.
class DeviceMotionController
{
/// The interval at which device motion updates will be reported.
fileprivate static let DeviceMotionUpdateInterval: TimeInterval = 1 / 60
/// The motion manager used to adjust camera position based on device motion.
fileprivate let motionManager = CMMotionManager()
/// Accessor for the current device motion.
var currentDeviceMotion: CMDeviceMotion?
{
return self.motionManager.deviceMotion
}
/// A boolean that starts and stops device motion updates, if device motion is available.
var enabled = false
{
didSet
{
guard self.motionManager.isDeviceMotionAvailable else
{
return
}
// Start and stop device motion reporting as appropriate.
if self.enabled
{
guard !self.motionManager.isDeviceMotionActive else
{
return
}
self.motionManager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryZVertical)
}
else
{
guard self.motionManager.isDeviceMotionActive else
{
return
}
self.motionManager.stopDeviceMotionUpdates()
}
}
}
deinit
{
self.enabled = false
}
init()
{
guard self.motionManager.isDeviceMotionAvailable else
{
return
}
self.motionManager.deviceMotionUpdateInterval = type(of: self).DeviceMotionUpdateInterval
}
}
| mit |
jjochen/JJFloatingActionButton | Example/Tests/Mocks/JJFloationgActionButtonDelegateMock.swift | 1 | 1851 | //
// JJFloationgActionButtonDelegateMock.swift
//
// Copyright (c) 2017-Present Jochen Pfeiffer
//
// 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.
//
@testable import JJFloatingActionButton
class JJFloatingActionButtonDelegateMock: JJFloatingActionButtonDelegate {
var willOpenCalled = false
var didOpenCalled = false
var willCloseCalled = false
var didCloseCalled = false
func floatingActionButtonWillOpen(_: JJFloatingActionButton) {
willOpenCalled = true
}
func floatingActionButtonDidOpen(_: JJFloatingActionButton) {
didOpenCalled = true
}
func floatingActionButtonWillClose(_: JJFloatingActionButton) {
willCloseCalled = true
}
func floatingActionButtonDidClose(_: JJFloatingActionButton) {
didCloseCalled = true
}
}
| mit |
LongPF/FaceTube | FaceTube/Tool/Capture/FTImageTarget.swift | 1 | 298 | //
// FTImageTarget.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/12.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import Foundation
@objc protocol FTImageTarget: NSObjectProtocol {
@objc optional func setImage(image: CIImage)
}
| mit |
LoopKit/LoopKit | LoopKitHostedTests/GlucoseStoreTests.swift | 1 | 41600 | //
// GlucoseStoreTests.swift
// LoopKitHostedTests
//
// Created by Darin Krauss on 10/12/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import XCTest
import HealthKit
@testable import LoopKit
class GlucoseStoreTestsBase: PersistenceControllerTestCase, GlucoseStoreDelegate {
private static let device = HKDevice(name: "NAME", manufacturer: "MANUFACTURER", model: "MODEL", hardwareVersion: "HARDWAREVERSION", firmwareVersion: "FIRMWAREVERSION", softwareVersion: "SOFTWAREVERSION", localIdentifier: "LOCALIDENTIFIER", udiDeviceIdentifier: "UDIDEVICEIDENTIFIER")
internal let sample1 = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.minutes(6)),
quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 123.4),
condition: nil,
trend: nil,
trendRate: nil,
isDisplayOnly: true,
wasUserEntered: false,
syncIdentifier: "1925558F-E98F-442F-BBA6-F6F75FB4FD91",
syncVersion: 2,
device: device)
internal let sample2 = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.minutes(2)),
quantity: HKQuantity(unit: .millimolesPerLiter, doubleValue: 7.4),
condition: nil,
trend: .flat,
trendRate: HKQuantity(unit: .millimolesPerLiterPerMinute, doubleValue: 0.0),
isDisplayOnly: false,
wasUserEntered: true,
syncIdentifier: "535F103C-3DFE-48F2-B15A-47313191E7B7",
syncVersion: 3,
device: device)
internal let sample3 = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.minutes(4)),
quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 400.0),
condition: .aboveRange,
trend: .upUpUp,
trendRate: HKQuantity(unit: .milligramsPerDeciliterPerMinute, doubleValue: 4.2),
isDisplayOnly: false,
wasUserEntered: false,
syncIdentifier: "E1624D2B-A971-41B8-B8A0-3A8212AC3D71",
syncVersion: 4,
device: device)
var healthStore: HKHealthStoreMock!
var glucoseStore: GlucoseStore!
var delegateCompletion: XCTestExpectation?
var authorizationStatus: HKAuthorizationStatus = .notDetermined
override func setUp() {
super.setUp()
let semaphore = DispatchSemaphore(value: 0)
cacheStore.onReady { error in
XCTAssertNil(error)
semaphore.signal()
}
semaphore.wait()
healthStore = HKHealthStoreMock()
healthStore.authorizationStatus = authorizationStatus
glucoseStore = GlucoseStore(healthStore: healthStore,
cacheStore: cacheStore,
cacheLength: .hours(1),
observationInterval: .minutes(30),
provenanceIdentifier: HKSource.default().bundleIdentifier)
glucoseStore.delegate = self
}
override func tearDown() {
let semaphore = DispatchSemaphore(value: 0)
glucoseStore.purgeAllGlucoseSamples(healthKitPredicate: HKQuery.predicateForObjects(from: HKSource.default())) { error in
XCTAssertNil(error)
semaphore.signal()
}
semaphore.wait()
delegateCompletion = nil
glucoseStore = nil
healthStore = nil
super.tearDown()
}
// MARK: - GlucoseStoreDelegate
func glucoseStoreHasUpdatedGlucoseData(_ glucoseStore: GlucoseStore) {
delegateCompletion?.fulfill()
}
}
class GlucoseStoreTestsAuthorizationRequired: GlucoseStoreTestsBase {
func testObserverQueryStartup() {
XCTAssert(glucoseStore.authorizationRequired);
XCTAssertNil(glucoseStore.observerQuery);
let authorizationCompletion = expectation(description: "authorization completion")
glucoseStore.authorize { (result) in
authorizationCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNotNil(glucoseStore.observerQuery);
}
}
class GlucoseStoreTests: GlucoseStoreTestsBase {
override func setUp() {
authorizationStatus = .sharingAuthorized
super.setUp()
}
// MARK: - HealthKitSampleStore
func testHealthKitQueryAnchorPersistence() {
var observerQuery: HKObserverQueryMock? = nil
var anchoredObjectQuery: HKAnchoredObjectQueryMock? = nil
// Check that an observer query was registered even without authorize() being called.
XCTAssertFalse(glucoseStore.authorizationRequired);
XCTAssertNotNil(glucoseStore.observerQuery);
glucoseStore.createObserverQuery = { (sampleType, predicate, updateHandler) -> HKObserverQuery in
observerQuery = HKObserverQueryMock(sampleType: sampleType, predicate: predicate, updateHandler: updateHandler)
return observerQuery!
}
let authorizationCompletion = expectation(description: "authorization completion")
glucoseStore.authorize { (result) in
authorizationCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNotNil(observerQuery)
let anchoredObjectQueryCreationExpectation = expectation(description: "anchored object query creation")
glucoseStore.createAnchoredObjectQuery = { (sampleType, predicate, anchor, limit, resultsHandler) -> HKAnchoredObjectQuery in
anchoredObjectQuery = HKAnchoredObjectQueryMock(type: sampleType, predicate: predicate, anchor: anchor, limit: limit, resultsHandler: resultsHandler)
anchoredObjectQueryCreationExpectation.fulfill()
return anchoredObjectQuery!
}
let observerQueryCompletionExpectation = expectation(description: "observer query completion")
let observerQueryCompletionHandler = {
observerQueryCompletionExpectation.fulfill()
}
// This simulates a signal marking the arrival of new HK Data.
observerQuery!.updateHandler(observerQuery!, observerQueryCompletionHandler, nil)
wait(for: [anchoredObjectQueryCreationExpectation], timeout: 10)
// Trigger results handler for anchored object query
let returnedAnchor = HKQueryAnchor(fromValue: 5)
anchoredObjectQuery!.resultsHandler(anchoredObjectQuery!, [], [], returnedAnchor, nil)
// Wait for observerQueryCompletionExpectation
waitForExpectations(timeout: 10)
XCTAssertNotNil(glucoseStore.queryAnchor)
cacheStore.managedObjectContext.performAndWait {}
// Create a new glucose store, and ensure it uses the last query anchor
let newGlucoseStore = GlucoseStore(healthStore: healthStore,
cacheStore: cacheStore,
provenanceIdentifier: HKSource.default().bundleIdentifier)
let newAuthorizationCompletion = expectation(description: "authorization completion")
observerQuery = nil
newGlucoseStore.createObserverQuery = { (sampleType, predicate, updateHandler) -> HKObserverQuery in
observerQuery = HKObserverQueryMock(sampleType: sampleType, predicate: predicate, updateHandler: updateHandler)
return observerQuery!
}
newGlucoseStore.authorize { (result) in
newAuthorizationCompletion.fulfill()
}
waitForExpectations(timeout: 10)
anchoredObjectQuery = nil
let newAnchoredObjectQueryCreationExpectation = expectation(description: "new anchored object query creation")
newGlucoseStore.createAnchoredObjectQuery = { (sampleType, predicate, anchor, limit, resultsHandler) -> HKAnchoredObjectQuery in
anchoredObjectQuery = HKAnchoredObjectQueryMock(type: sampleType, predicate: predicate, anchor: anchor, limit: limit, resultsHandler: resultsHandler)
newAnchoredObjectQueryCreationExpectation.fulfill()
return anchoredObjectQuery!
}
// This simulates a signal marking the arrival of new HK Data.
observerQuery!.updateHandler(observerQuery!, {}, nil)
waitForExpectations(timeout: 10)
// Assert new glucose store is querying with the last anchor that our HealthKit mock returned
XCTAssertEqual(returnedAnchor, anchoredObjectQuery?.anchor)
anchoredObjectQuery!.resultsHandler(anchoredObjectQuery!, [], [], returnedAnchor, nil)
}
// MARK: - Fetching
func testGetGlucoseSamples() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNotNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2")
glucoseStore.getGlucoseSamples(start: Date(timeIntervalSinceNow: -.minutes(5)), end: Date(timeIntervalSinceNow: -.minutes(3))) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample3)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples3Completion = expectation(description: "getGlucoseSamples3")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
enum Error: Swift.Error { case arbitrary }
func testGetGlucoseSamplesDelayedHealthKitStorage() {
glucoseStore.healthKitStorageDelay = .minutes(5)
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// HealthKit storage is deferred, so the second 2 UUIDs are nil
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNotNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNotNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual([sample1.quantitySample.description], hkobjects.map { $0.description })
}
func testGetGlucoseSamplesErrorHealthKitStorage() {
healthStore.saveError = Error.arbitrary
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// HealthKit storage is deferred, so the second 2 UUIDs are nil
XCTAssertNil(samples[0].uuid)
XCTAssertNotNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNotNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNotNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(3, hkobjects.count)
}
func testGetGlucoseSamplesDeniedHealthKitStorage() {
healthStore.authorizationStatus = .sharingDenied
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// HealthKit storage is denied, so all UUIDs are nil
XCTAssertNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertTrue(hkobjects.isEmpty)
}
func testGetGlucoseSamplesSomeDeniedHealthKitStorage() {
glucoseStore.healthKitStorageDelay = 0
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamples1Completion = expectation(description: "addGlucoseSamples1")
// Authorized
glucoseStore.addGlucoseSamples([sample1]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
}
addGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(1, hkobjects.count)
hkobjects = []
healthStore.authorizationStatus = .sharingDenied
let addGlucoseSamples2Completion = expectation(description: "addGlucoseSamples2")
// Denied
glucoseStore.addGlucoseSamples([sample2]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
}
addGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(0, hkobjects.count)
hkobjects = []
healthStore.authorizationStatus = .sharingAuthorized
let addGlucoseSamples3Completion = expectation(description: "addGlucoseSamples3")
// Authorized
glucoseStore.addGlucoseSamples([sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
}
addGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(1, hkobjects.count)
hkobjects = []
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testLatestGlucose() {
XCTAssertNil(glucoseStore.latestGlucose)
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
assertEqualSamples(samples[0], self.sample1)
assertEqualSamples(samples[1], self.sample2)
assertEqualSamples(samples[2], self.sample3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNotNil(glucoseStore.latestGlucose)
XCTAssertEqual(glucoseStore.latestGlucose?.startDate, sample2.date)
XCTAssertEqual(glucoseStore.latestGlucose?.endDate, sample2.date)
XCTAssertEqual(glucoseStore.latestGlucose?.quantity, sample2.quantity)
XCTAssertEqual(glucoseStore.latestGlucose?.provenanceIdentifier, HKSource.default().bundleIdentifier)
XCTAssertEqual(glucoseStore.latestGlucose?.isDisplayOnly, sample2.isDisplayOnly)
XCTAssertEqual(glucoseStore.latestGlucose?.wasUserEntered, sample2.wasUserEntered)
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNil(glucoseStore.latestGlucose)
}
// MARK: - Modification
func testAddGlucoseSamples() {
let addGlucoseSamples1Completion = expectation(description: "addGlucoseSamples1")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3, sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// Note: the HealthKit UUID is no longer updated before being returned as a result of addGlucoseSamples.
XCTAssertNil(samples[0].uuid)
XCTAssertNotNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNotNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample2)
XCTAssertNil(samples[2].uuid)
XCTAssertNotNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample3)
}
addGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNotNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let addGlucoseSamples2Completion = expectation(description: "addGlucoseSamples2")
glucoseStore.addGlucoseSamples([sample3, sample1, sample2]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
addGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2Completion")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNotNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testAddGlucoseSamplesEmpty() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testAddGlucoseSamplesNotification() {
delegateCompletion = expectation(description: "delegate")
let glucoseSamplesDidChangeCompletion = expectation(description: "glucoseSamplesDidChange")
let observer = NotificationCenter.default.addObserver(forName: GlucoseStore.glucoseSamplesDidChange, object: glucoseStore, queue: nil) { notification in
glucoseSamplesDidChangeCompletion.fulfill()
}
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
wait(for: [glucoseSamplesDidChangeCompletion, delegateCompletion!, addGlucoseSamplesCompletion], timeout: 10, enforceOrder: true)
NotificationCenter.default.removeObserver(observer)
delegateCompletion = nil
}
// MARK: - Watch Synchronization
func testSyncGlucoseSamples() {
var syncGlucoseSamples: [StoredGlucoseSample] = []
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples1Completion = expectation(description: "getSyncGlucoseSamples1")
glucoseStore.getSyncGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 3)
XCTAssertNotNil(objects[0].uuid)
assertEqualSamples(objects[0], self.sample1)
XCTAssertNotNil(objects[1].uuid)
assertEqualSamples(objects[1], self.sample3)
XCTAssertNotNil(objects[2].uuid)
assertEqualSamples(objects[2], self.sample2)
syncGlucoseSamples = objects
}
getSyncGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples2Completion = expectation(description: "getSyncGlucoseSamples2")
glucoseStore.getSyncGlucoseSamples(start: Date(timeIntervalSinceNow: -.minutes(5)), end: Date(timeIntervalSinceNow: -.minutes(3))) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 1)
XCTAssertNotNil(objects[0].uuid)
assertEqualSamples(objects[0], self.sample3)
}
getSyncGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples3Completion = expectation(description: "getSyncGlucoseSamples3")
glucoseStore.getSyncGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getSyncGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
let setSyncGlucoseSamplesCompletion = expectation(description: "setSyncGlucoseSamples")
glucoseStore.setSyncGlucoseSamples(syncGlucoseSamples) { error in
XCTAssertNil(error)
setSyncGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples4Completion = expectation(description: "getSyncGlucoseSamples4")
glucoseStore.getSyncGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 3)
XCTAssertNotNil(objects[0].uuid)
assertEqualSamples(objects[0], self.sample1)
XCTAssertNotNil(objects[1].uuid)
assertEqualSamples(objects[1], self.sample3)
XCTAssertNotNil(objects[2].uuid)
assertEqualSamples(objects[2], self.sample2)
syncGlucoseSamples = objects
}
getSyncGlucoseSamples4Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
// MARK: - Cache Management
func testEarliestCacheDate() {
XCTAssertEqual(glucoseStore.earliestCacheDate.timeIntervalSinceNow, -.hours(1), accuracy: 1)
}
func testPurgeAllGlucoseSamples() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeAllGlucoseSamplesCompletion = expectation(description: "purgeAllGlucoseSamples")
glucoseStore.purgeAllGlucoseSamples(healthKitPredicate: HKQuery.predicateForObjects(from: HKSource.default())) { error in
XCTAssertNil(error)
purgeAllGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testPurgeExpiredGlucoseObjects() {
let expiredSample = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.hours(2)),
quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 198.7),
condition: nil,
trend: nil,
trendRate: nil,
isDisplayOnly: false,
wasUserEntered: false,
syncIdentifier: "6AB8C7F3-A2CE-442F-98C4-3D0514626B5F",
syncVersion: 3)
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3, expiredSample]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 4)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamplesCompletion = expectation(description: "getGlucoseSamples")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
getGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testPurgeCachedGlucoseObjects() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjects1Completion = expectation(description: "purgeCachedGlucoseObjects1")
glucoseStore.purgeCachedGlucoseObjects(before: Date(timeIntervalSinceNow: -.minutes(5))) { error in
XCTAssertNil(error)
purgeCachedGlucoseObjects1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 2)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjects2Completion = expectation(description: "purgeCachedGlucoseObjects2")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjects2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples3Completion = expectation(description: "getGlucoseSamples3")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testPurgeCachedGlucoseObjectsNotification() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
delegateCompletion = expectation(description: "delegate")
let glucoseSamplesDidChangeCompletion = expectation(description: "glucoseSamplesDidChange")
let observer = NotificationCenter.default.addObserver(forName: GlucoseStore.glucoseSamplesDidChange, object: glucoseStore, queue: nil) { notification in
glucoseSamplesDidChangeCompletion.fulfill()
}
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
wait(for: [glucoseSamplesDidChangeCompletion, delegateCompletion!, purgeCachedGlucoseObjectsCompletion], timeout: 10, enforceOrder: true)
NotificationCenter.default.removeObserver(observer)
delegateCompletion = nil
}
}
fileprivate func assertEqualSamples(_ storedGlucoseSample: StoredGlucoseSample,
_ newGlucoseSample: NewGlucoseSample,
provenanceIdentifier: String = HKSource.default().bundleIdentifier,
file: StaticString = #file,
line: UInt = #line) {
XCTAssertEqual(storedGlucoseSample.provenanceIdentifier, provenanceIdentifier, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.syncIdentifier, newGlucoseSample.syncIdentifier, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.syncVersion, newGlucoseSample.syncVersion, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.startDate, newGlucoseSample.date, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.quantity, newGlucoseSample.quantity, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.isDisplayOnly, newGlucoseSample.isDisplayOnly, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.wasUserEntered, newGlucoseSample.wasUserEntered, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.device, newGlucoseSample.device, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.condition, newGlucoseSample.condition, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.trend, newGlucoseSample.trend, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.trendRate, newGlucoseSample.trendRate, file: file, line: line)
}
| mit |
daher-alfawares/iBeacon | Beacon/BeaconTests/BeaconTests.swift | 1 | 905 | //
// BeaconTests.swift
// BeaconTests
//
// Created by Daher Alfawares on 1/19/15.
// Copyright (c) 2015 Daher Alfawares. All rights reserved.
//
import UIKit
import XCTest
class BeaconTests: 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.
}
}
}
| apache-2.0 |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/02175-swift-scopeinfo-addtoscope.swift | 12 | 291 | // 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 NSObject {
func a {
{
}
{
}
{
{
{
}
{
}
}
}
protocol A : a {
{
{
}
{
{
}
}
}
func a
}
{
}
var String {
{
{
}
func a
}
| mit |
neugierige/webservices-example-ios | consuming-webservices/Models/LED.swift | 1 | 254 | //
// LED.swift
// consuming-webservices
//
// Created by Stephen Wong on 9/13/16.
// Copyright © 2016 Intrepid Pursuits. All rights reserved.
//
import Foundation
enum LEDState {
case on, off
}
struct LED {
var status: LEDState = .off
}
| mit |
AndreMuis/Algorithms | RotateArray.playground/Contents.swift | 1 | 225 |
// Rotate an array to the right
let numbers = [1, 2, 3, 4, 5, 6, 7]
let steps = 3
let first = numbers[0 ..< numbers.count - steps]
let last = numbers[numbers.count - steps ..< numbers.count]
let result = last + first
| mit |
Egibide-DAM/swift | 02_ejemplos/07_ciclo_vida/03_arc/06_referencias_ciclicas_clausuras.playground/Contents.swift | 1 | 878 | class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
let heading = HTMLElement(name: "h1")
let defaultText = "some default text"
heading.asHTML = {
return "<\(heading.name)>\(heading.text ?? defaultText)</\(heading.name)>"
}
print(heading.asHTML())
// Prints "<h1>some default text</h1>"
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
// Prints "<p>hello, world</p>"
paragraph = nil
// no muestra el deinit()
| apache-2.0 |
tokyovigilante/CesiumKit | CesiumKit/Core/Matrix3.swift | 1 | 31282 | //
// Matrix3.swift
// CesiumKit
//
// Created by Ryan Walklin on 8/09/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
import simd
/**
* A 3x3 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix3
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
*
* @see Matrix3.fromColumnMajorArray
* @see Matrix3.fromRowMajorArray
* @see Matrix3.fromQuaternion
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix2
* @see Matrix4
*/
public struct Matrix3 {
fileprivate (set) internal var simdType: double3x3
var floatRepresentation: float3x3 {
return float3x3([
simd_float(simdType[0]),
simd_float(simdType[1]),
simd_float(simdType[2])
])
}
public init(_ column0Row0: Double, _ column1Row0: Double, _ column2Row0: Double,
_ column0Row1: Double, _ column1Row1: Double, _ column2Row1: Double,
_ column0Row2: Double, _ column1Row2: Double, _ column2Row2: Double) {
simdType = double3x3(rows: [
double3(column0Row0, column1Row0, column2Row0),
double3(column0Row1, column1Row1, column2Row1),
double3(column0Row2, column1Row2, column2Row2),
])
}
/**
* Computes a 3x3 rotation matrix from the provided quaternion.
*
* @param {Quaternion} quaternion the quaternion to use.
* @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
*/
public init(quaternion: Quaternion) {
let x2 = quaternion.x * quaternion.x
let xy = quaternion.x * quaternion.y
let xz = quaternion.x * quaternion.z
let xw = quaternion.x * quaternion.w
let y2 = quaternion.y * quaternion.y
let yz = quaternion.y * quaternion.z
let yw = quaternion.y * quaternion.w
let z2 = quaternion.z * quaternion.z
let zw = quaternion.z * quaternion.w
let w2 = quaternion.w * quaternion.w
let m00 = x2 - y2 - z2 + w2
let m01 = 2.0 * (xy - zw)
let m02 = 2.0 * (xz + yw)
let m10 = 2.0 * (xy + zw)
let m11 = -x2 + y2 - z2 + w2
let m12 = 2.0 * (yz - xw)
let m20 = 2.0 * (xz - yw)
let m21 = 2.0 * (yz + xw)
let m22 = -x2 - y2 + z2 + w2
self.init(
m00, m01, m02,
m10, m11, m12,
m20, m21, m22
)
}
init (fromMatrix4 matrix: Matrix4) {
let m4col0 = matrix[0]
let m4col1 = matrix[1]
let m4col2 = matrix[2]
self.init(
m4col0.x, m4col0.y, m4col0.z,
m4col0.w, m4col1.x, m4col1.y,
m4col1.z, m4col1.w, m4col2.x
)
}
public init (simd: double3x3) {
simdType = simd
}
public init (_ scalar: Double = 0.0) {
simdType = double3x3(scalar)
}
public init (diagonal: double3) {
simdType = double3x3(diagonal: diagonal)
}
public subscript (column: Int) -> Cartesian3 {
assert(column >= 0 && column <= 3, "column index out of range")
return Cartesian3(simd: simdType[column])
}
/// Access to individual elements.
public subscript (column: Int, row: Int) -> Double {
assert(column >= 0 && column <= 3, "column index out of range")
assert(row >= 0 && row <= 3, "row index out of range")
return simdType[column][row]
}
/*
/**
* Creates a Matrix3 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
Matrix3.fromColumnMajorArray = function(values, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(values)) {
throw new DeveloperError('values parameter is required');
}
//>>includeEnd('debug');
return Matrix3.clone(values, result);
};
*/
/**
* Creates a Matrix3 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
public init(rows: [Cartesian3]) {
assert(rows.count == 3, "invalid row array")
simdType = double3x3(rows: [rows[0].simdType, rows[1].simdType, rows[2].simdType])
}
/**
* Computes a Matrix3 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0]
* // [0.0, 0.0, 9.0]
* var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
init (scale: Cartesian3) {
self.init(simd: double3x3(diagonal: scale.simdType))
}
/*
/**
* Computes a Matrix3 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0]
* // [0.0, 0.0, 2.0]
* var m = Cesium.Matrix3.fromUniformScale(2.0);
*/
Matrix3.fromUniformScale = function(scale, result) {
//>>includeStart('debug', pragmas.debug);
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
return new Matrix3(
scale, 0.0, 0.0,
0.0, scale, 0.0,
0.0, 0.0, scale);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = scale;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = scale;
return result;
};
/**
* Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
*
* @param {Cartesian3} the vector on the left hand side of the cross product operation.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [0.0, -9.0, 8.0]
* // [9.0, 0.0, -7.0]
* // [-8.0, 7.0, 0.0]
* var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix3.fromCrossProduct = function(vector, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(vector)) {
throw new DeveloperError('vector is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
return new Matrix3(
0.0, -vector.z, vector.y,
vector.z, 0.0, -vector.x,
-vector.y, vector.x, 0.0);
}
result[0] = 0.0;
result[1] = vector.z;
result[2] = -vector.y;
result[3] = -vector.z;
result[4] = 0.0;
result[5] = vector.x;
result[6] = vector.y;
result[7] = -vector.x;
result[8] = 0.0;
return result;
};
*/
/**
* Creates a rotation matrix around the x-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the x-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p);
*/
init (rotationX angle: Double) {
let cosAngle = cos(angle)
let sinAngle = sin(angle)
self.init(
1.0, 0.0, 0.0,
0.0, cosAngle, -sinAngle,
0.0, sinAngle, cosAngle
)
}
/**
* Creates a rotation matrix around the y-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the y-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p);
*/
init (rotationY angle: Double) {
let cosAngle = cos(angle)
let sinAngle = sin(angle)
self.init(
cosAngle, 0.0, sinAngle,
0.0, 1.0, 0.0,
-sinAngle, 0.0, cosAngle
)
}
/**
* Creates a rotation matrix around the z-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the z-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p);
*/
init (rotationZ angle: Double) {
let cosAngle: Double = cos(angle)
let sinAngle: Double = sin(angle)
self.init(
cosAngle, -sinAngle, 0.0,
sinAngle, cosAngle, 0.0,
0.0, 0.0, 1.0
)
}
/*
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, or 2.
* @exception {DeveloperError} column must be 0, 1, or 2.
*
* @example
* var myMatrix = new Cesium.Matrix3();
* var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix3.getElementIndex = function(column, row) {
//>>includeStart('debug', pragmas.debug);
if (typeof row !== 'number' || row < 0 || row > 2) {
throw new DeveloperError('row must be 0, 1, or 2.');
}
if (typeof column !== 'number' || column < 0 || column > 2) {
throw new DeveloperError('column must be 0, 1, or 2.');
}
//>>includeEnd('debug');
return column * 3 + row;
};
*/
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
func column (_ index: Int) -> Cartesian3 {
assert(index >= 0 && index <= 2, "index must be 0, 1, or 2.")
return Cartesian3(simd: simdType[index])
}
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
func setColumn (_ index: Int, cartesian: Cartesian3) -> Matrix3 {
assert(index >= 0 && index <= 2, "index must be 0, 1, or 2.")
var result = simdType
result[index] = cartesian.simdType
return Matrix3(simd: result)
}
/*
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.getRow = function(matrix, index, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
var x = matrix[index];
var y = matrix[index + 3];
var z = matrix[index + 6];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.setRow = function(matrix, index, cartesian, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result = Matrix3.clone(matrix, result);
result[index] = cartesian.x;
result[index + 3] = cartesian.y;
result[index + 6] = cartesian.z;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix3.getScale = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors.
*
* @param {Matrix3} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix3.getMaximumScale = function(matrix) {
Matrix3.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
*/
/*
/**
* Computes the sum of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.add = function(left, right, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
return result;
};
/**
* Computes the difference of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.subtract = function(left, right, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
return result;
};
*/
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} cartesian The column.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
public func multiplyByVector (_ cartesian: Cartesian3) -> Cartesian3 {
return Cartesian3(simd: simdType * cartesian.simdType)
}
/*
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix3} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.multiplyByScalar = function(matrix, scalar, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar must be a number');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
return result;
};
*/
/**
* Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
*
* @param {Matrix3} matrix The matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix3.fromScale
* @see Matrix3.multiplyByUniformScale
*
* @example
* // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
* Cesium.Matrix3.multiplyByScale(m, scale, m);
*/
func multiplyByScale (_ scale: Cartesian3) -> Matrix3 {
var grid = toArray()
grid[0] *= scale.x
grid[1] *= scale.x
grid[2] *= scale.x
grid[3] *= scale.y
grid[4] *= scale.y
grid[5] *= scale.y
grid[6] *= scale.z
grid[7] *= scale.z
grid[8] *= scale.z
return Matrix3(array: grid)
}
/**
* Computes the product of two matrices.
*
* @param {MatrixType} self The first matrix.
* @param {MatrixType} other The second matrix.
* @returns {MatrixType} The modified result parameter.
*/
public func multiply(_ other: Matrix3) -> Matrix3 {
return Matrix3(simd: simdType * other.simdType)
}
public var negate: Matrix3 {
return Matrix3(simd: -simdType)
}
public var transpose: Matrix3 {
return Matrix3(simd: simdType.transpose)
}
public func equals(_ other: Matrix3) -> Bool {
return simd_equal(simdType, other.simdType)
}
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {MatrixType} [left] The first matrix.
* @param {MatrixType} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
func equalsEpsilon(_ other: Matrix3, epsilon: Double) -> Bool {
return simd_almost_equal_elements(simdType, other.simdType, epsilon)
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {MatrixType} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
/*
function computeFrobeniusNorm(matrix) {
var norm = 0.0;
for (var i = 0; i < 9; ++i) {
var temp = matrix[i];
norm += temp * temp;
}
return Math.sqrt(norm);
}
var rowVal = [1, 0, 0];
var colVal = [2, 2, 1];
function offDiagonalFrobeniusNorm(matrix) {
// Computes the "off-diagonal" Frobenius norm.
// Assumes matrix is symmetric.
var norm = 0.0;
for (var i = 0; i < 3; ++i) {
var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
norm += 2.0 * temp * temp;
}
return Math.sqrt(norm);
}
function shurDecomposition(matrix, result) {
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.2 The 2by2 Symmetric Schur Decomposition.
//
// The routine takes a matrix, which is assumed to be symmetric, and
// finds the largest off-diagonal term, and then creates
// a matrix (result) which can be used to help reduce it
var tolerance = CesiumMath.EPSILON15;
var maxDiagonal = 0.0;
var rotAxis = 1;
// find pivot (rotAxis) based on max diagonal of matrix
for (var i = 0; i < 3; ++i) {
var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
if (temp > maxDiagonal) {
rotAxis = i;
maxDiagonal = temp;
}
}
var c = 1.0;
var s = 0.0;
var p = rowVal[rotAxis];
var q = colVal[rotAxis];
if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
var qq = matrix[Matrix3.getElementIndex(q, q)];
var pp = matrix[Matrix3.getElementIndex(p, p)];
var qp = matrix[Matrix3.getElementIndex(q, p)];
var tau = (qq - pp) / 2.0 / qp;
var t;
if (tau < 0.0) {
t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
} else {
t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
}
c = 1.0 / Math.sqrt(1.0 + t * t);
s = t * c;
}
result = Matrix3.clone(Matrix3.IDENTITY, result);
result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
result[Matrix3.getElementIndex(q, p)] = s;
result[Matrix3.getElementIndex(p, q)] = -s;
return result;
}
var jMatrix = new Matrix3();
var jMatrixTranspose = new Matrix3();
/**
* Computes the eigenvectors and eigenvalues of a symmetric matrix.
* <p>
* Returns a diagonal matrix and unitary matrix such that:
* <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
* </p>
* <p>
* The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
* of the unitary matrix are the corresponding eigenvectors.
* </p>
*
* @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
* @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
* @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
*
* @example
* var a = //... symetric matrix
* var result = {
* unitary : new Cesium.Matrix3(),
* diagonal : new Cesium.Matrix3()
* };
* Cesium.Matrix3.computeEigenDecomposition(a, result);
*
* var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary);
* var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal);
* Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
*
* var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0).x; // first eigenvalue
* var v = Cesium.Matrix3.getColumn(result.unitary, 0); // first eigenvector
* var c = Cesium.Cartesian3.multiplyBy(scalar: v, lambda, new Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
*/
Matrix3.computeEigenDecomposition = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
//>>includeEnd('debug');
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.3 The Classical Jacobi Algorithm
var tolerance = CesiumMath.EPSILON20;
var maxSweeps = 10;
var count = 0;
var sweep = 0;
if (!defined(result)) {
result = {};
}
var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
shurDecomposition(diagMatrix, jMatrix);
Matrix3.transpose(jMatrix, jMatrixTranspose);
Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
if (++count > 2) {
++sweep;
count = 0;
}
}
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix3} matrix The matrix with signed elements.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.abs = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
return result;
};
*/
/**
* An immutable Matrix3 instance initialized to the identity matrix.
*
* @type {Matrix3}
* @constant
*/
public static let identity = Matrix3(1.0)
/**
* An immutable Matrix3 instance initialized to the zero matrix.
*
* @type {Matrix3}
* @constant
*/
public static let zero = Matrix3()
}
extension Matrix3: Packable {
var length: Int {
return Matrix3.packedLength()
}
public static func packedLength() -> Int {
return 9
}
public init(array: [Double], startingIndex: Int = 0) {
self.init(
array[startingIndex], array[startingIndex+3], array[startingIndex+6],
array[startingIndex+1], array[startingIndex+4], array[startingIndex+7],
array[startingIndex+2], array[startingIndex+5], array[startingIndex+8]
)
}
func toArray() -> [Double] {
let col0 = simdType[0]
let col1 = simdType[1]
let col2 = simdType[2]
return [
col0.x, col0.y, col0.z,
col1.x, col1.y, col1.z,
col2.x, col2.y, col2.z
]
}
}
extension Matrix3: Equatable {}
public func == (left: Matrix3, right: Matrix3) -> Bool {
return left.equals(right)
}
| apache-2.0 |
Legoless/Alpha | Demo/UIKitCatalog/ViewControllersMenuViewController.swift | 1 | 634 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `MenuTableViewController` subclass for the "View Controllers" section of the app.
*/
import UIKit
class ViewControllersMenuViewController: MenuTableViewController {
// MARK: Properties
override var segueIdentifierMap: [[String]] {
return [
[
"ShowAlertControllers",
"ShowCollectionViewController",
"ShowPageViewController",
"ShowVideoPlayerViewController"
]
]
}
}
| mit |
ahoppen/swift | test/attr/spi_available.swift | 5 | 490 | // RUN: %target-typecheck-verify-swift
@_spi_available(*, deprecated, renamed: "another") // expected-error {{SPI available only supports introducing version on specific platform}}
public class SPIClass1 {}
@_spi_available(*, unavailable) // expected-error {{SPI available only supports introducing version on specific platform}}
public class SPIClass2 {}
@_spi_available(AlienPlatform 5.2, *) // expected-warning {{unrecognized platform name 'AlienPlatform'}}
public class SPIClass3 {}
| apache-2.0 |
Swift3Home/Swift3_Object-oriented | 002-函数/002-函数/ViewController.swift | 1 | 2691 | //
// ViewController.swift
// 002-函数
//
// Created by lichuanjun on 2017/5/29.
// Copyright © 2017年 lichuanjun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Swift 1.0: sum(10, 50),所有的形参都会省略,其他的程序员非常喜欢!
// Swift 2.0: sum(10, y:50),第一个形参的名称省略
// Swift 3.0: 调用的方式 -> OC的程序员非常喜欢
// print(sum(x: 10, y: 50))
// 测试外部参数
// print(sum1(num1: 30, num2: 60))
// print(40, 60)
// 测试默认值
print(sum3())
print(sum3(x: 10, y: 20))
print(sum3(x: 10))
print(sum3(y: 80))
demo1()
demo2()
demo3()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - 无返回值
/**
知道就行,主要用在闭包,在阅读第三方框架代码时,保证能够看懂
- 直接省略
- ()
- Void
*/
func demo1() {
print("哈哈")
}
func demo2() -> () {
print("呵呵")
}
func demo3() -> Void {
print("嘻嘻")
}
// MARK: - 默认值
// 通过给参数设置默认值,在调用的时候,可以任意组合参数,如果不指定,就使用默认值
// OC 中需要定义很多的方法,以及方法实现,最终调用包含所有参数的那个函数
func sum3(x: Int = 1, y: Int = 2) -> Int {
return x + y
}
// MARK: - 外部参数
// - 外部参数就是在形参前加一个名称
// - 外部参数不会影响函数内部的细节
// - 外部参数会让外部调用方看起来更加的直观
// - 外部参数如果使用_, 在外部调用函数里,会忽略形参的名字
func sum2(_ x: Int, _ y: Int) -> Int {
// 在swift中,_就是可以忽略任意不感兴趣的内容
// Immutable value 'i' was never used; consider replacing with '_' or removing it
// i 从来没有被使用,建议使用 _ 替代
for _ in 0..<10 {
print("Hello world")
}
return x+y
}
func sum1(num1 x: Int, num2 y: Int) -> Int {
return x + y
}
// MARK: - 函数定义
/// 函数定义,格式 函数名(形参列表) -> 返回值类型
func sum(x: Int, y: Int) -> Int {
return x + y
}
}
| mit |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Challenge1.playgroundpage/Sources/Assessments.swift | 1 | 1381 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let hints = [
"Just like in the previous exercise, you need to update the value of the `gemCounter` variable each time Byte collects a gem.",
"Collect a gem, and then use the assignment operator to set a new `gemCounter` value. \nExample: `gemCounter = 3`",
"After Byte collects all the gems, the value of the `gemCounter` variable should be 5.",
"This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it."
]
let solution: String? = nil
public func assessmentPoint() -> AssessmentResults {
let success: String
if finalGemCount == 5 {
success = "### Excellent work! \nBy continuously updating the `gemCounter` value, you can track that value as it changes over time. Next, you'll learn a more efficient way to do this.\n\n[**Next Page**](@next)"
}
else {
success = "You collected all the gems, but didn't track them correctly. Your `gemCounter` variable has a value of `\(finalGemCount)`, but it should have a value of `5`. Try adjusting the code to accurately track how many gems Byte has collected."
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit |
Connorrr/ParticleAlarm | IOS/Alarm/LabelEditViewController.swift | 1 | 1166 | //
// labelEditViewController.swift
// Alarm-ios8-swift
//
// Created by longyutao on 15/10/21.
// Copyright (c) 2015年 LongGames. All rights reserved.
//
import UIKit
class LabelEditViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var labelTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
labelTextField.becomeFirstResponder()
// Do any additional setup after loading the view.
self.labelTextField.delegate = self
labelTextField.text = Global.label
//defined in UITextInputTraits protocol
labelTextField.returnKeyType = UIReturnKeyType.done
labelTextField.enablesReturnKeyAutomatically = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
Global.label = textField.text!
//Becuase segue push is used
//navigationController?.popViewController(animated: true)
return false
}
}
| mit |
emilstahl/swift | validation-test/compiler_crashers/0530-swift-metatypetype-get.swift | 9 | 416 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
static
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
| apache-2.0 |
aamays/Rotten-Tomatoes | Rotten Tomatoes/RTUtilities.swift | 1 | 1330 | //
// RTUtilities.swift
// Rotten Tomatoes
//
// Created by Amay Singhal on 9/19/15.
// Copyright © 2015 ple. All rights reserved.
//
import Foundation
import UIKit
class RTUitilities {
static func updateTextAndTintColorForNavBar(navController: UINavigationController?, tintColor: UIColor?, textColor: UIColor?) {
navController?.navigationBar.barTintColor = tintColor ?? RTConstants.ApplicationBarTintColor
navController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: textColor ?? UIColor.darkGrayColor()]
}
static func getAttributedStringForAlertMessage(message: String, withIconSize size: CGFloat = 17, andBaseLine baseline: CGFloat = -3) -> NSAttributedString {
let attributedString = NSMutableAttributedString()
if let font = UIFont(name: "fontastic", size: size) {
let attrs = [NSFontAttributeName : font,
NSBaselineOffsetAttributeName: baseline]
let cautionSign = NSMutableAttributedString(string: "a", attributes: attrs)
attributedString.appendAttributedString(cautionSign)
attributedString.appendAttributedString(NSAttributedString(string: " "))
}
attributedString.appendAttributedString(NSAttributedString(string: message))
return attributedString
}
} | mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/27020-llvm-foldingset-swift-tupletype-getnodeprofile.swift | 1 | 473 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class B<T where g:a{class n{func a{class C<w{func b{{class c{func e<Tt{b=a
| apache-2.0 |
philipbannon/iOS | FriendBookPlus/FriendBookPlusTests/FriendBookPlusTests.swift | 1 | 1009 | //
// FriendBookPlusTests.swift
// FriendBookPlusTests
//
// Created by Philip Bannon on 06/01/2016.
// Copyright © 2016 Philip Bannon. All rights reserved.
//
import XCTest
@testable import FriendBookPlus
class FriendBookPlusTests: 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.
}
}
}
| gpl-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/01510-swift-typebase-getcanonicaltype.swift | 1 | 495 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol a {
protocol a : d {
typealias d
}
protocol A where T](_ = B<T where l) {
}
func g: a {
| apache-2.0 |
ben-ng/swift | test/IDE/print_types.swift | 6 | 5974 | // This file should not have any syntax or type checker errors.
// RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-types -source-filename %s -fully-qualified-types=false | %FileCheck %s -strict-whitespace
// RUN: %target-swift-ide-test -print-types -source-filename %s -fully-qualified-types=true | %FileCheck %s -check-prefix=FULL -strict-whitespace
typealias MyInt = Int
// CHECK: TypeAliasDecl '''MyInt''' MyInt.Type{{$}}
// FULL: TypeAliasDecl '''MyInt''' swift_ide_test.MyInt.Type{{$}}
func testVariableTypes(_ param: Int, param2: inout Double) {
// CHECK: FuncDecl '''testVariableTypes''' (Int, inout Double) -> (){{$}}
// FULL: FuncDecl '''testVariableTypes''' (Swift.Int, inout Swift.Double) -> (){{$}}
var a1 = 42
// CHECK: VarDecl '''a1''' Int{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a1''' Swift.Int{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a1 = 17; _ = a1
var a2 : Int = 42
// CHECK: VarDecl '''a2''' Int{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a2''' Swift.Int{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a2 = 17; _ = a2
var a3 = Int16(42)
// CHECK: VarDecl '''a3''' Int16{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a3''' Swift.Int16{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a3 = 17; _ = a3
var a4 = Int32(42)
// CHECK: VarDecl '''a4''' Int32{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a4''' Swift.Int32{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a4 = 17; _ = a4
var a5 : Int64 = 42
// CHECK: VarDecl '''a5''' Int64{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a5''' Swift.Int64{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a5 = 17; _ = a5
var typealias1 : MyInt = 42
// CHECK: VarDecl '''typealias1''' MyInt{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''typealias1''' swift_ide_test.MyInt{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
_ = typealias1 ; typealias1 = 1
var optional1 = Optional<Int>.none
// CHECK: VarDecl '''optional1''' Optional<Int>{{$}}
// FULL: VarDecl '''optional1''' Swift.Optional<Swift.Int>{{$}}
_ = optional1 ; optional1 = nil
var optional2 = Optional<[Int]>.none
_ = optional2 ; optional2 = nil
// CHECK: VarDecl '''optional2''' Optional<[Int]>{{$}}
// FULL: VarDecl '''optional2''' Swift.Optional<[Swift.Int]>{{$}}
}
func testFuncType1() {}
// CHECK: FuncDecl '''testFuncType1''' () -> (){{$}}
// FULL: FuncDecl '''testFuncType1''' () -> (){{$}}
func testFuncType2() -> () {}
// CHECK: FuncDecl '''testFuncType2''' () -> (){{$}}
// FULL: FuncDecl '''testFuncType2''' () -> (){{$}}
func testFuncType3() -> Void {}
// CHECK: FuncDecl '''testFuncType3''' () -> Void{{$}}
// FULL: FuncDecl '''testFuncType3''' () -> Swift.Void{{$}}
func testFuncType4() -> MyInt {}
// CHECK: FuncDecl '''testFuncType4''' () -> MyInt{{$}}
// FULL: FuncDecl '''testFuncType4''' () -> swift_ide_test.MyInt{{$}}
func testFuncType5() -> (Int) {}
// CHECK: FuncDecl '''testFuncType5''' () -> (Int){{$}}
// FULL: FuncDecl '''testFuncType5''' () -> (Swift.Int){{$}}
func testFuncType6() -> (Int, Int) {}
// CHECK: FuncDecl '''testFuncType6''' () -> (Int, Int){{$}}
// FULL: FuncDecl '''testFuncType6''' () -> (Swift.Int, Swift.Int){{$}}
func testFuncType7(_ a: Int, withFloat b: Float) {}
// CHECK: FuncDecl '''testFuncType7''' (Int, Float) -> (){{$}}
// FULL: FuncDecl '''testFuncType7''' (Swift.Int, Swift.Float) -> (){{$}}
func testVariadicFuncType(_ a: Int, b: Float...) {}
// CHECK: FuncDecl '''testVariadicFuncType''' (Int, Float...) -> (){{$}}
// FULL: FuncDecl '''testVariadicFuncType''' (Swift.Int, Swift.Float...) -> (){{$}}
func testCurriedFuncType1(_ a: Int) -> (_ b: Float) -> () {}
// CHECK: FuncDecl '''testCurriedFuncType1''' (Int) -> (Float) -> (){{$}}
// FULL: FuncDecl '''testCurriedFuncType1''' (Swift.Int) -> (Swift.Float) -> (){{$}}
protocol FooProtocol {}
protocol BarProtocol {}
protocol QuxProtocol { associatedtype Qux }
struct GenericStruct<A, B : FooProtocol> {}
func testInGenericFunc1<A, B : FooProtocol, C : FooProtocol & BarProtocol>(_ a: A, b: B, c: C) {
// CHECK: FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}}
// FULL: FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}}
var a1 = a
_ = a1; a1 = a
// CHECK: VarDecl '''a1''' A{{$}}
// FULL: VarDecl '''a1''' A{{$}}
var b1 = b
_ = b1; b1 = b
// CHECK: VarDecl '''b1''' B{{$}}
// FULL: VarDecl '''b1''' B{{$}}
var gs1 = GenericStruct<A, B>()
_ = gs1; gs1 = GenericStruct<A, B>()
// CHECK: VarDecl '''gs1''' GenericStruct<A, B>{{$}}
// CHECK: CallExpr:[[@LINE-2]] '''GenericStruct<A, B>()''' GenericStruct<A, B>{{$}}
// CHECK: ConstructorRefCallExpr:[[@LINE-3]] '''GenericStruct<A, B>''' () -> GenericStruct<A, B>
// FULL: VarDecl '''gs1''' swift_ide_test.GenericStruct<A, B>{{$}}
// FULL: CallExpr:[[@LINE-6]] '''GenericStruct<A, B>()''' swift_ide_test.GenericStruct<A, B>{{$}}
// FULL: ConstructorRefCallExpr:[[@LINE-7]] '''GenericStruct<A, B>''' () -> swift_ide_test.GenericStruct<A, B>
}
func testInGenericFunc2<T : QuxProtocol, U : QuxProtocol>() where T.Qux == U.Qux {}
// CHECK: FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> () -> (){{$}}
// FULL: FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> () -> (){{$}}
| apache-2.0 |
billyburton/SwiftMySql | Sources/SwiftMySql/MySqlFactory.swift | 1 | 3814 | //
// MySqlFactory.swift
// SwiftMySql
//
// Created by William Burton on 08/02/2017.
//
//
import Foundation
public class MySqlFactory {
//MARK: connection factory
static var connectionClosure: (String, String, String, String) throws -> (MySqlConnectionProtocol) = {
server, database, user, password in
return try MySqlConnection(server: server, database: database, user: user, password: password)
}
/**
Factory method for creating a MySqlConnectionProtocol instance.
- throws:
An error of type MySqlError.InvalidConnection.
- parameters:
- server: Name of the MySql server.
- database: Name of the MySql database.
- user: Name of user that will be used to access the database.
- password: Password of the MySql user.
- returns:
An instance of MySqlConnectionProtocol.
*/
public class func createConnection(server: String, database: String, user: String, password: String) throws -> MySqlConnectionProtocol {
return try connectionClosure(server, database, user, password)
}
//MARK: Transaction factory
static var transactionClosure: (MySqlConnectionProtocol) -> (MySqlTransactionProtocol) = {
connection in
return MySqlTransaction(connection: connection)
}
/**
Factory method for creating a MySqlTransactionProtocol instance
- parameters:
- connection: An instance of MySqlConnectionProtocol created using the createConnection method.
- returns:
An instance of MySqlTransactionProtocol
*/
public class func createTransaction(connection: MySqlConnectionProtocol) -> (MySqlTransactionProtocol) {
return transactionClosure(connection)
}
//MARK: reader factory
static var readerClosure: (MySqlConnectionProtocol) throws -> (MySqlReaderProtocol) = {
connection in
return try MySqlReader(connection: connection)
}
/**
Factory method for creating a MySqlReaderProtocol
- throws:
An error of type MySqlError.ReaderError
- parameters:
- connection: An instance of MySqlConnectionProtocol created using the createConnection method.
- returns:
An instance of MySqlReaderProtocol
*/
class func createReader(connection: MySqlConnectionProtocol) throws -> MySqlReaderProtocol {
return try readerClosure(connection)
}
//MARK: command factory
static var commandClosure: (String, MySqlConnectionProtocol) -> (MySqlCommandProtocol) = {
command, connection in
return MySqlCommand(command: command, connection: connection)
}
/**
Factory method for creating a MySqlCommandProtocol
- parameters:
- command: Sql query command.
- connection: An instance of MySqlConnectionProtocol created using the createConnection method
- returns:
An instance of MySqlCommandProtocol
*/
public class func createCommand(command: String, connection: MySqlConnectionProtocol) -> MySqlCommandProtocol {
return commandClosure(command, connection)
}
//MARK: schema factory
static var schemaClosure: (MySqlResultsProtocol) -> (MySqlSchemaProtocol) = {
results in
return MySqlSchema(results)
}
/**
Factory method for creating a MySqlSchemaProtocol
- parameters:
- results: An instance of MySqlResultsProtocol, that contains a resultset returned from the MySql database.
- returns:
An instance of MySqlSchemaProtocol
*/
class func createSchema(results: MySqlResultsProtocol) -> MySqlSchemaProtocol {
return schemaClosure(results)
}
}
| apache-2.0 |
sigito/material-components-ios | catalog/MDCCatalog/AppDelegate.swift | 1 | 3027 | /*
Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import CatalogByConvention
import MaterialComponents.MaterialBottomAppBar
import MaterialComponents.MDCActivityIndicatorColorThemer
import MaterialComponents.MDCBottomNavigationBarColorThemer
import MaterialComponents.MDCBottomAppBarColorThemer
import MaterialComponents.MDCButtonBarColorThemer
import MaterialComponents.MDCButtonColorThemer
import MaterialComponents.MDCAlertColorThemer
import MaterialComponents.MDCFeatureHighlightColorThemer
import MaterialComponents.MDCFlexibleHeaderColorThemer
import MaterialComponents.MDCHeaderStackViewColorThemer
import MaterialComponents.MDCNavigationBarColorThemer
import MaterialComponents.MDCPageControlColorThemer
import MaterialComponents.MDCProgressViewColorThemer
import MaterialComponents.MDCSliderColorThemer
import MaterialComponents.MDCTabBarColorThemer
import MaterialComponents.MaterialTextFields
import MaterialComponents.MDCTextFieldColorThemer
import MaterialComponents.MaterialThemes
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = MDCCatalogWindow(frame: UIScreen.main.bounds)
UIApplication.shared.statusBarStyle = .lightContent
// The navigation tree will only take examples that implement
// and return YES to catalogIsPresentable.
let tree = CBCCreatePresentableNavigationTree()
let rootNodeViewController = MDCCatalogComponentsController(node: tree)
let navigationController = UINavigationController(rootViewController: rootNodeViewController)
// In the event that an example view controller hides the navigation bar we generally want to
// ensure that the edge-swipe pop gesture can still take effect. This may be overly-assumptive
// but we'll explore other alternatives when we have a concrete example of this approach causing
// problems.
navigationController.interactivePopGestureRecognizer?.delegate = navigationController
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
}
extension UINavigationController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
| apache-2.0 |
MegaManX32/CD | CD/CD/View Controllers/SignupYourInterestsViewController.swift | 1 | 5753 | //
// SignupYourInterestsViewController.swift
// CustomDeal
//
// Created by Vladislav Simovic on 9/28/16.
// Copyright © 2016 Vladislav Simovic. All rights reserved.
//
import UIKit
import MBProgressHUD
fileprivate let sectionInsets = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 30.0, right: 20.0)
fileprivate let itemsPerRow: CGFloat = 3
fileprivate let heightOfRow: CGFloat = 100
class SignupYourInterestsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// MARK: - Properties
@IBOutlet weak var collectionView : UICollectionView!
var userID : String!
var interestsArray : [(interest : Interest, checked : Bool)] = [(Interest, Bool)]()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// fetch interests
MBProgressHUD.showAdded(to: self.view, animated: true)
NetworkManager.sharedInstance.getAllInterests(
success: { [unowned self] in
let context = CoreDataManager.sharedInstance.mainContext
let interests = Interest.findAllInterests(context: context)
for interest in interests {
self.interestsArray.append((interest, false))
}
self.collectionView.reloadData()
MBProgressHUD.hide(for: self.view, animated: true)
},
failure: { [unowned self] (errorMessage) in
print(errorMessage)
MBProgressHUD.hide(for: self.view, animated: true)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - User Actions
@IBAction func nextAction(sender: UIButton) {
// try to update interests on user
var selectedInterestsIDArray = [String]()
for interestOption in self.interestsArray {
if interestOption.checked {
selectedInterestsIDArray.append(interestOption.interest.uid!)
}
}
// at least 3 interests must be selected
if selectedInterestsIDArray.count < 4 {
CustomAlert.presentAlert(message: "At least 4 interests must be selected", controller: self)
return
}
MBProgressHUD.showAdded(to: self.view, animated: true)
let context = CoreDataManager.sharedInstance.createScratchpadContext(onMainThread: false)
context.perform {
[unowned self] in
// find user
let user = User.findUserWith(uid: self.userID, context: context)!
// update user with interests
for interestID in selectedInterestsIDArray {
user.addToInterests(Interest.findInterestWith(id: interestID, context: context)!)
}
// create of or update user
NetworkManager.sharedInstance.createOrUpdate(user: user, context: context, success: { [unowned self] (userID) in
let controller = self.storyboard?.instantiateViewController(withIdentifier: "SignupCongratulationsViewController") as! SignupCongratulationsViewController
controller.userID = userID
self.show(controller, sender: self)
MBProgressHUD.hide(for: self.view, animated: true)
}, failure: { [unowned self] (errorMessage) in
print(errorMessage)
MBProgressHUD.hide(for: self.view, animated: true)
})
}
}
// MARK: - UICollectionViewDelegate methods
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.interestsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SignupInterestsCollectionViewCell.cellIdentifier(), for: indexPath) as! SignupInterestsCollectionViewCell
cell.populateCellWithInterest(name: self.interestsArray[indexPath.item].interest.name!,
imageName: (self.interestsArray[indexPath.item].interest.name!).lowercased(),
checked: self.interestsArray[indexPath.item].checked
)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: heightOfRow)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.interestsArray[indexPath.item].checked = !self.interestsArray[indexPath.item].checked
self.collectionView.reloadItems(at: [indexPath])
}
}
| mit |
gobetti/Swift | PagedBasedApp/PagedBasedApp/RootViewController.swift | 1 | 5227 | //
// RootViewController.swift
// PagedBasedApp
//
// Created by Carlos Butron on 07/12/14.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
lazy var modelController = ModelController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0)
}
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) {
// In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers![0]
let viewControllers = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
// In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
let currentViewController = self.pageViewController!.viewControllers![0] as! DataViewController
var viewControllers: [UIViewController]
let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController)
if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController)
viewControllers = [currentViewController, nextViewController!]
} else {
let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController)
viewControllers = [previousViewController!, currentViewController]
}
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
return .Mid
}
}
| mit |
devpunk/punknote | punknote/Model/Create/MCreateContentBackground.swift | 1 | 363 | import UIKit
class MCreateContentBackground:MCreateContentProtocol
{
private let kCellHeight:CGFloat = 70
var cellHeight:CGFloat
{
get
{
return kCellHeight
}
}
var reusableIdentifier:String
{
get
{
return VCreateCellBackground.reusableIdentifier
}
}
}
| mit |
iamrajhans/RatingAppiOS | RatingApp/RatingApp/AppDelegate.swift | 1 | 6099 | //
// AppDelegate.swift
// RatingApp
//
// Created by Rajhans Jadhao on 11/09/16.
// Copyright © 2016 Rajhans Jadhao. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.drone.RatingApp" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("RatingApp", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/CreateEntity.swift | 2 | 2873 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** CreateEntity. */
public struct CreateEntity: Encodable {
/// The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 64 characters.
public var entity: String
/// The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.
public var description: String?
/// Any metadata related to the value.
public var metadata: [String: JSON]?
/// An array of objects describing the entity values.
public var values: [CreateValue]?
/// Whether to use fuzzy matching for the entity.
public var fuzzyMatch: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case entity = "entity"
case description = "description"
case metadata = "metadata"
case values = "values"
case fuzzyMatch = "fuzzy_match"
}
/**
Initialize a `CreateEntity` with member variables.
- parameter entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 64 characters.
- parameter description: The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.
- parameter metadata: Any metadata related to the value.
- parameter values: An array of objects describing the entity values.
- parameter fuzzyMatch: Whether to use fuzzy matching for the entity.
- returns: An initialized `CreateEntity`.
*/
public init(entity: String, description: String? = nil, metadata: [String: JSON]? = nil, values: [CreateValue]? = nil, fuzzyMatch: Bool? = nil) {
self.entity = entity
self.description = description
self.metadata = metadata
self.values = values
self.fuzzyMatch = fuzzyMatch
}
}
| mit |
jeffreybergier/udacity-animation | animation-playground.playground/Pages/Gesture Recognizers.xcplaygroundpage/Contents.swift | 1 | 3261 | //: [Previous](@previous)
import UIKit
import XCPlayground
// MARK: Custom View Controller Subclass
class SpringViewController: UIViewController {
// MARK: Custom Properties
let redView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.redColor()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var xConstraint: NSLayoutConstraint = { self.redView.centerXAnchor.constraintEqualToAnchor(vc.view.centerXAnchor, constant: 0) }()
lazy var yConstraint: NSLayoutConstraint = { self.redView.centerYAnchor.constraintEqualToAnchor(vc.view.centerYAnchor, constant: 0) }()
// MARK: Configure the View Controller
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.configureRedView()
}
// MARK: Add View to Animate
// and configure constraints
func configureRedView() {
vc.view.addSubview(self.redView)
NSLayoutConstraint.activateConstraints(
[
self.xConstraint,
self.yConstraint,
self.redView.heightAnchor.constraintEqualToConstant(60),
self.redView.widthAnchor.constraintEqualToConstant(60)
]
)
}
// MARK: Handle Animations from Gesture Recognizer
func animateBackToCenter() {
UIView.animateWithDuration(
0.6,
delay: 0.0,
usingSpringWithDamping: 0.35,
initialSpringVelocity: 1.5,
options: [],
animations: {
self.xConstraint.constant = 0
self.yConstraint.constant = 0
vc.view.setNeedsLayout()
},
completion: { finished in
print("Snapped Back")
}
)
}
func gestureFired(sender: UIPanGestureRecognizer) {
switch sender.state {
case .Began, .Possible:
// don't need to do anything to start
break
case .Changed:
// get the amount of change cause by the finger moving
let translation = sender.translationInView(vc.view)
// add that change to our autolayout constraints
xConstraint.constant += translation.x
yConstraint.constant += translation.y
// tell the view to update
vc.view.setNeedsLayout()
// reset the translation in the gesture recognizer to 0
// try removing this line of code and see what happens when dragging
sender.setTranslation(CGPoint.zero, inView: vc.view)
case .Cancelled, .Ended, .Failed:
// animate back to the center when done
animateBackToCenter()
}
}
}
// MARK: Instantiate Spring View Controller
let vc = SpringViewController()
vc.view.frame = CGRect(x: 0, y: 0, width: 400, height: 600)
XCPlaygroundPage.currentPage.liveView = vc.view
// MARK: Configure Gesture Recognizer
let panGestureRecognizer = UIPanGestureRecognizer(target: vc, action: #selector(vc.gestureFired(_:)))
vc.redView.addGestureRecognizer(panGestureRecognizer)
| mit |
swift-gtk/SwiftGTK | Sources/UIKit/Orientation.swift | 1 | 709 |
public enum Orientation: RawRepresentable {
/// The element is in horizontal orientation.
case horizontal
/// The element is in vertical orientation.
case vertical
public typealias RawValue = GtkOrientation
public var rawValue: RawValue {
switch self {
case .horizontal:
return GTK_ORIENTATION_HORIZONTAL
case .vertical:
return GTK_ORIENTATION_VERTICAL
}
}
public init?(rawValue: RawValue) {
switch rawValue {
case GTK_ORIENTATION_HORIZONTAL:
self = .horizontal
case GTK_ORIENTATION_VERTICAL:
self = .vertical
default: return nil
}
}
}
| gpl-2.0 |
ruslanskorb/CoreStore | Sources/XcodeDataModelSchema.swift | 2 | 9223 | //
// XcodeDataModelSchema.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
import Foundation
// MARK: - XcodeDataModelSchema
/**
The `XcodeDataModelSchema` describes a model version declared in a single *.xcdatamodeld file.
```
CoreStoreDefaults.dataStack = DataStack(
XcodeDataModelSchema(modelName: "MyAppV1", bundle: .main)
)
```
*/
public final class XcodeDataModelSchema: DynamicSchema {
/**
Creates a `XcodeDataModelSchema` for each of the models declared in the specified (.xcdatamodeld) model file.
- parameter modelName: the name of the (.xcdatamodeld) model file. If not specified, the application name (CFBundleName) will be used if it exists, or "CoreData" if it the bundle name was not set.
- parameter bundle: an optional bundle to load .xcdatamodeld models from. If not specified, the main bundle will be used.
- parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
- returns: a tuple containing all `XcodeDataModelSchema` for the models declared in the specified .xcdatamodeld file, and the current model version string declared or inferred from the file.
*/
public static func from(modelName: XcodeDataModelFileName, bundle: Bundle = Bundle.main, migrationChain: MigrationChain = nil) -> (allSchema: [XcodeDataModelSchema], currentModelVersion: ModelVersion) {
guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else {
// For users migrating from very old Xcode versions: Old xcdatamodel files are not contained inside xcdatamodeld (with a "d"), and will thus fail this check. If that was the case, create a new xcdatamodeld file and copy all contents into the new model.
let foundModels = bundle
.paths(forResourcesOfType: "momd", inDirectory: nil)
.map({ ($0 as NSString).lastPathComponent })
Internals.abort("Could not find \"\(modelName).momd\" from the bundle \"\(bundle.bundleIdentifier ?? "<nil>")\". Other model files in bundle: \(foundModels.coreStoreDumpString)")
}
let modelFileURL = URL(fileURLWithPath: modelFilePath)
let versionInfoPlistURL = modelFileURL.appendingPathComponent("VersionInfo.plist", isDirectory: false)
guard let versionInfo = NSDictionary(contentsOf: versionInfoPlistURL),
let versionHashes = versionInfo["NSManagedObjectModel_VersionHashes"] as? [String: AnyObject] else {
Internals.abort("Could not load \(Internals.typeName(NSManagedObjectModel.self)) metadata from path \"\(versionInfoPlistURL)\".")
}
let modelVersions = Set(versionHashes.keys)
let modelVersionHints = migrationChain.leafVersions
let currentModelVersion: String
if let plistModelVersion = versionInfo["NSManagedObjectModel_CurrentVersionName"] as? String,
modelVersionHints.isEmpty || modelVersionHints.contains(plistModelVersion) {
currentModelVersion = plistModelVersion
}
else if let resolvedVersion = modelVersions.intersection(modelVersionHints).first {
Internals.log(
.warning,
message: "The \(Internals.typeName(MigrationChain.self)) leaf versions do not include the model file's current version. Resolving to version \"\(resolvedVersion)\"."
)
currentModelVersion = resolvedVersion
}
else if let resolvedVersion = modelVersions.first ?? modelVersionHints.first {
if !modelVersionHints.isEmpty {
Internals.log(
.warning,
message: "The \(Internals.typeName(MigrationChain.self)) leaf versions do not include any of the model file's embedded versions. Resolving to version \"\(resolvedVersion)\"."
)
}
currentModelVersion = resolvedVersion
}
else {
Internals.abort("No model files were found in URL \"\(modelFileURL)\".")
}
var allSchema: [XcodeDataModelSchema] = []
for modelVersion in modelVersions {
let fileURL = modelFileURL.appendingPathComponent("\(modelVersion).mom", isDirectory: false)
allSchema.append(XcodeDataModelSchema(modelName: modelVersion, modelVersionFileURL: fileURL))
}
return (allSchema, currentModelVersion)
}
/**
Initializes an `XcodeDataModelSchema` from an *.xcdatamodeld version name and its containing `Bundle`.
```
CoreStoreDefaults.dataStack = DataStack(
XcodeDataModelSchema(modelName: "MyAppV1", bundle: .main)
)
```
- parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension)
- parameter bundle: the `Bundle` that contains the .xcdatamodeld's "momd" file. If not specified, the `Bundle.main` will be searched.
*/
public convenience init(modelName: ModelVersion, bundle: Bundle = Bundle.main) {
guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else {
// For users migrating from very old Xcode versions: Old xcdatamodel files are not contained inside xcdatamodeld (with a "d"), and will thus fail this check. If that was the case, create a new xcdatamodeld file and copy all contents into the new model.
let foundModels = bundle
.paths(forResourcesOfType: "momd", inDirectory: nil)
.map({ ($0 as NSString).lastPathComponent })
Internals.abort("Could not find \"\(modelName).momd\" from the bundle \"\(bundle.bundleIdentifier ?? "<nil>")\". Other model files in bundle: \(foundModels.coreStoreDumpString)")
}
let modelFileURL = URL(fileURLWithPath: modelFilePath)
let fileURL = modelFileURL.appendingPathComponent("\(modelName).mom", isDirectory: false)
self.init(modelName: modelName, modelVersionFileURL: fileURL)
}
/**
Initializes an `XcodeDataModelSchema` from an *.xcdatamodeld file URL.
```
CoreStoreDefaults.dataStack = DataStack(
XcodeDataModelSchema(modelName: "MyAppV1", modelVersionFileURL: fileURL)
)
```
- parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension)
- parameter modelVersionFileURL: the file URL that points to the .xcdatamodeld's "momd" file.
*/
public required init(modelName: ModelVersion, modelVersionFileURL: URL) {
Internals.assert(
NSManagedObjectModel(contentsOf: modelVersionFileURL) != nil,
"Could not find the \"\(modelName).mom\" version file for the model at URL \"\(modelVersionFileURL)\"."
)
self.modelVersion = modelName
self.modelVersionFileURL = modelVersionFileURL
}
// MARK: DynamicSchema
public let modelVersion: ModelVersion
public func rawModel() -> NSManagedObjectModel {
if let cachedRawModel = self.cachedRawModel {
return cachedRawModel
}
if let rawModel = NSManagedObjectModel(contentsOf: self.modelVersionFileURL) {
self.cachedRawModel = rawModel
return rawModel
}
Internals.abort("Could not create an \(Internals.typeName(NSManagedObjectModel.self)) from the model at URL \"\(self.modelVersionFileURL)\".")
}
// MARK: Internal
internal let modelVersionFileURL: URL
private lazy var rootModelFileURL: URL = Internals.with { [unowned self] in
return self.modelVersionFileURL.deletingLastPathComponent()
}
// MARK: Private
private weak var cachedRawModel: NSManagedObjectModel?
}
| mit |
csnu17/Firebase-iOS-Authentication-Demo | firebase authentication/Extensions/MyViewControllerExtension.swift | 1 | 574 | //
// MyViewControllerExtension.swift
// firebase authentication
//
// Created by Kittisak Phetrungnapha on 2/13/2560 BE.
// Copyright © 2560 Kittisak Phetrungnapha. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
static func getViewControllerWith(storyboardName: String = "Main", viewControllerIdentifier: String) -> UIViewController {
let storyboard = UIStoryboard.init(name: storyboardName, bundle: nil)
return storyboard.instantiateViewController(withIdentifier: viewControllerIdentifier)
}
}
| mit |
tkremenek/swift | validation-test/compiler_crashers_2_fixed/rdar76249579.swift | 13 | 245 | // RUN: %target-swift-frontend -emit-ir %s
public class Base {}
public class Derived : Base {}
public protocol P {}
public class C : P {}
public class G<X : P, Y : Base> {}
extension G where X == C, Y == Derived {
public func foo() {}
}
| apache-2.0 |
nsnull0/YWTopInputField | YWTopInputField/Classes/YWTopInputFieldLogic.swift | 1 | 3248 | //
// YWTopInputFieldLogic.swift
// YWTopInputField
//
// Created by Yoseph Wijaya on 2017/06/25.
// Copyright © 2017 Yoseph Wijaya. All rights reserved.
//
import UIKit
struct propertyVal {
var correctionType:UITextAutocorrectionType = .no
var spellCheckType:UITextSpellCheckingType = .no
var keyboardType:UIKeyboardType = .default
var keyboardAppearance:UIKeyboardAppearance = .default
var containerEffectType:UIBlurEffectStyle = .dark
var titleColorText:UIColor = .white
var messageColorText:UIColor = .white
var titleFontText:UIFont = .boldSystemFont(ofSize: 15.0)
var messageFontText:UIFont = .systemFont(ofSize: 12.0)
var heightContainerConstraint:CGFloat = 200
}
public class YWTopInputFieldLogic {
var propertyYW:propertyVal = propertyVal()
public func setCorrectionType(_type:UITextAutocorrectionType) -> YWTopInputFieldLogic {
self.propertyYW.correctionType = _type
return self
}
public func setSpellCheckType(_type:UITextSpellCheckingType) -> YWTopInputFieldLogic {
self.propertyYW.spellCheckType = _type
return self
}
public func setKeyboardType(_type:UIKeyboardType) -> YWTopInputFieldLogic {
self.propertyYW.keyboardType = _type
return self
}
public func setKeyboardAppearance(_type:UIKeyboardAppearance) -> YWTopInputFieldLogic {
self.propertyYW.keyboardAppearance = _type
return self
}
public func setBlurStyleEffectContainer(_type:UIBlurEffectStyle) -> YWTopInputFieldLogic {
self.propertyYW.containerEffectType = _type
return self
}
public func setTitleColor(_color:UIColor) -> YWTopInputFieldLogic {
self.propertyYW.titleColorText = _color
return self
}
public func setMessageColor(_color:UIColor) -> YWTopInputFieldLogic {
self.propertyYW.messageColorText = _color
return self
}
public func setFontTitle(_font:UIFont) -> YWTopInputFieldLogic {
self.propertyYW.titleFontText = _font
return self
}
public func setMessageFont(_font:UIFont) -> YWTopInputFieldLogic {
self.propertyYW.messageFontText = _font
return self
}
public func setHeightTextContainer(_height:CGFloat) -> YWTopInputFieldLogic {
guard _height >= 200 else {
return self
}
self.propertyYW.heightContainerConstraint = _height
return self
}
public func validate() {
if self.propertyYW.heightContainerConstraint < 200 {
self.propertyYW.heightContainerConstraint = 200
}
}
//MARK: Static Function
static func checkValidate(_onContent targetStr:String, _defaultContent content:String) -> String {
let strProcess = targetStr.replacingOccurrences(of: " ", with: "")
guard strProcess.characters.count > 0 else {
return content
}
return targetStr
}
}
| mit |
tkremenek/swift | validation-test/stdlib/Collection/DefaultedMutableRangeReplaceableBidirectionalCollection.swift | 32 | 2268 | // -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// FIXME: the test is too slow when the standard library is not optimized.
// rdar://problem/46878013
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
var CollectionTests = TestSuite("Collection")
// Test collections using value types as elements.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addRangeReplaceableBidirectionalCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return DefaultedMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return DefaultedMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
CollectionTests.addMutableBidirectionalCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return DefaultedMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return DefaultedMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
return DefaultedMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks
, withUnsafeMutableBufferPointerIsSupported: false,
isFixedLengthCollection: true
)
}
runAllTests()
| apache-2.0 |
cuappdev/podcast-ios | old/Podcast/TopicsGridCollectionViewCell.swift | 1 | 2352 |
//
// TopicsGridCollectionViewCell.swift
// Podcast
//
// Created by Mindy Lou on 12/22/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
class TopicsGridCollectionViewCell: UICollectionViewCell {
var backgroundLabel: UILabel!
var backgroundTileImageView: ImageView!
var topicLabel: UILabel!
let topicLabelHeight: CGFloat = 18
let topicTileAlpha: CGFloat = 0.25
let backgroundColors: [UIColor] = [.rosyPink, .sea, .duskyBlue, .dullYellow]
override init(frame: CGRect) {
super.init(frame: frame)
backgroundLabel = UILabel(frame: frame)
addSubview(backgroundLabel)
backgroundLabel.snp.makeConstraints { make in
make.top.equalToSuperview()
make.width.height.equalTo(frame.width)
make.leading.trailing.equalToSuperview()
}
backgroundTileImageView = ImageView(frame: .zero)
addSubview(backgroundTileImageView)
backgroundTileImageView.snp.makeConstraints { make in
make.top.equalToSuperview()
make.width.height.equalTo(frame.width)
make.leading.trailing.equalToSuperview()
}
topicLabel = UILabel(frame: .zero)
topicLabel.textAlignment = .center
topicLabel.lineBreakMode = .byWordWrapping
topicLabel.numberOfLines = 0
topicLabel.textColor = .offWhite
topicLabel.font = ._12SemiboldFont()
addSubview(topicLabel)
topicLabel.snp.makeConstraints { make in
make.center.equalTo(backgroundLabel.snp.center)
make.leading.trailing.equalToSuperview()
make.width.equalTo(backgroundLabel.snp.width)
}
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundTileImageView.addCornerRadius(height: frame.width)
backgroundLabel.addCornerRadius(height: frame.width)
}
func configure(for topic: Topic, at index: Int) {
topicLabel.text = topic.name
backgroundLabel.backgroundColor = backgroundColors[index % 4]
if let topicType = topic.topicType {
backgroundTileImageView.image = topicType.tileImage.withAlpha(topicTileAlpha)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
playgroundscon/Playgrounds | Playgrounds/Protocol/Request/Requestable.swift | 1 | 2891 | //
// ScheduleDay.swift
// Playgrounds
//
// Created by Andyy Hope on 18/11/16.
// Copyright © 2016 Andyy Hope. All rights reserved.
//
import Foundation
import SwiftyJSON
public typealias Parameters = [String: AnyObject]
public protocol Requestable {
static func request(url: URL, parameters: Parameters?, log: Bool, function: String, file: String, completion: @escaping RequestResponse<JSON>.Completion)
}
public extension Requestable {
// MARK: - Requester
public static func request(url: URL, parameters: Parameters? = nil, log: Bool = false, function: String = #function, file: String = #file, completion: @escaping RequestResponse<JSON>.Completion) {
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpBody = httpBody(for: parameters)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTask(with: request) { data, response, error in
if log {
print(file)
print(function)
print(url)
if let parameters = parameters { print(parameters) }
}
if let error = error {
print(error)
print(file)
print(url)
completion(.fail(.session(error as NSError)))
}
else if let data = data {
self.parseRequest(data: data, response: response, log: log, completion: completion)
} else {
fatalError("An unknown network error occurred.")
}
}
.resume()
}
// MARK: - Parser
internal static func parseRequest(data: Data, response: URLResponse?, log: Bool, completion: @escaping RequestResponse<JSON>.Completion) {
var error: NSError?
let json = JSON(data: data, options: .mutableLeaves, error: &error)
DispatchQueue.main.async {
if let error = error {
completion(.fail(.invalidData(error)))
} else {
if log { print(json) }
completion(.success(json))
}
}
}
// MARK: - Parameter Utilities
private static func httpBody(for parameters: Parameters?) -> Data? {
guard let parameters = parameters else { return nil }
do {
let httpBody = try JSONSerialization.data(withJSONObject: parameters)
return httpBody
} catch let error as NSError {
print(error)
assertionFailure()
return nil
} catch let data as Data {
return data
}
}
}
| gpl-3.0 |
nlambson/CanvasKit | CanvasKitTests/Networking Tests/CKIPollNetworkingTests.swift | 3 | 2368 | //
// CKIPollNetworkingTests.swift
// CanvasKit
//
// Created by Nathan Lambson on 7/29/14.
// Copyright (c) 2014 Instructure. All rights reserved.
//
import XCTest
class CKIPollNetworkingTests: 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 testFetchPollsForCurrentUser() {
let client = MockCKIClient()
client.fetchPollsForCurrentUser()
XCTAssertEqual(client.capturedPath!, "/api/v1/polls", "CKIPoll returned API path for testFetchPollsForCurrentUser was incorrect")
XCTAssertEqual(client.capturedMethod!, MockCKIClient.Method.Fetch, "CKIPoll API Interaction Method was incorrect")
}
func testFetchPollWithID() {
let client = MockCKIClient()
client.fetchPollWithID("1023")
XCTAssertEqual(client.capturedPath!, "/api/v1/polls/1023", "CKIPoll returned API path for testFetchPollsForCurrentUser was incorrect")
XCTAssertEqual(client.capturedMethod!, MockCKIClient.Method.Fetch, "CKIPoll API Interaction Method was incorrect")
}
func testCreatePoll() {
let client = MockCKIClient()
let pollDictionary = Helpers.loadJSONFixture("poll") as NSDictionary
let poll = CKIPoll(fromJSONDictionary: pollDictionary)
client.createPoll(poll)
XCTAssertEqual(client.capturedPath!, "/api/v1/polls", "CKIPoll returned API path for testFetchPollsForCurrentUser was incorrect")
XCTAssertEqual(client.capturedMethod!, MockCKIClient.Method.Create, "CKIPoll API Interaction Method was incorrect")
}
func testDeletePoll() {
let client = MockCKIClient()
let pollDictionary = Helpers.loadJSONFixture("poll") as NSDictionary
let poll = CKIPoll(fromJSONDictionary: pollDictionary)
client.deletePoll(poll)
XCTAssertEqual(client.capturedPath!, "/api/v1/polls/1023", "CKIPoll returned API path for testDeletePoll was incorrect")
XCTAssertEqual(client.capturedMethod!, MockCKIClient.Method.Delete, "CKIPoll API Interaction Method was incorrect")
}
}
| mit |
thebnich/firefox-ios | SyncTests/MockSyncServerTests.swift | 8 | 9197 | /* 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 UIKit
import XCTest
import Shared
import Storage
import Sync
private class MockBackoffStorage: BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp?
func clearServerBackoff() {
serverBackoffUntilLocalTimestamp = nil
}
func isInBackoff(now: Timestamp) -> Timestamp? {
return nil
}
}
class MockSyncServerTests: XCTestCase {
var server: MockSyncServer!
var client: Sync15StorageClient!
override func setUp() {
server = MockSyncServer(username: "1234567")
server.start()
client = getClient(server)
}
private func getClient(server: MockSyncServer) -> Sync15StorageClient? {
guard let url = server.baseURL.asURL else {
XCTFail("Couldn't get URL.")
return nil
}
let authorizer: Authorizer = identity
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
print("URL: \(url)")
return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage())
}
func testDeleteSpec() {
// Deletion of a collection path itself, versus trailing slash, sets the right flags.
let all = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks", withQuery: [:])!
XCTAssertTrue(all.wholeCollection)
XCTAssertNil(all.ids)
let some = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks", withQuery: ["ids": "123456,abcdef"])!
XCTAssertFalse(some.wholeCollection)
XCTAssertEqual(["123456", "abcdef"], some.ids!)
let one = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks/123456", withQuery: [:])!
XCTAssertFalse(one.wholeCollection)
XCTAssertNil(one.ids)
}
func testInfoCollections() {
server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326251111000)
server.storeRecords([], inCollection: "tabs", now: 1326252222500)
server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326252222000)
server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "clients", now: 1326253333000)
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
client.getInfoCollections().upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// JSON contents.
XCTAssertEqual(response.value.collectionNames().sort(), ["bookmarks", "clients", "tabs"])
XCTAssertEqual(response.value.modified("bookmarks"), 1326252222000)
XCTAssertEqual(response.value.modified("clients"), 1326253333000)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertEqual(response.metadata.records, 3) // bookmarks, clients, tabs.
// X-Last-Modified, max of all collection modified timestamps.
XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326253333000)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testGet() {
server.storeRecords([MockSyncServer.makeValidEnvelope("guid", modified: 0)], inCollection: "bookmarks", now: 1326251111000)
let collectionClient = client.clientForCollection("bookmarks", encrypter: getEncrypter())
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
collectionClient.get("guid").upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// JSON contents.
XCTAssertEqual(response.value.id, "guid")
XCTAssertEqual(response.value.modified, 1326251111000)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326251111000)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
// And now a missing record, which should produce a 404.
collectionClient.get("missing").upon { result in
XCTAssertNotNil(result.failureValue)
guard let response = result.failureValue else {
expectation.fulfill()
return
}
XCTAssertNotNil(response as? NotFound<NSHTTPURLResponse>)
}
}
func testWipeStorage() {
server.storeRecords([MockSyncServer.makeValidEnvelope("a", modified: 0)], inCollection: "bookmarks", now: 1326251111000)
server.storeRecords([MockSyncServer.makeValidEnvelope("b", modified: 0)], inCollection: "bookmarks", now: 1326252222000)
server.storeRecords([MockSyncServer.makeValidEnvelope("c", modified: 0)], inCollection: "clients", now: 1326253333000)
server.storeRecords([], inCollection: "tabs")
// For now, only testing wiping the storage root, which is the only thing we use in practice.
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
client.wipeStorage().upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// JSON contents: should be the empty object.
XCTAssertEqual(response.value.toString(), "{}")
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertNil(response.metadata.lastModifiedMilliseconds)
// And we really wiped the data.
XCTAssertTrue(self.server.collections.isEmpty)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testPut() {
// For now, only test uploading crypto/keys. There's nothing special about this PUT, however.
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: KeyBundle.random(), ifUnmodifiedSince: nil).upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// Contents: should be just the record timestamp.
XCTAssertLessThanOrEqual(before, response.value)
XCTAssertLessThanOrEqual(response.value, after)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertNil(response.metadata.lastModifiedMilliseconds)
// And we really uploaded the record.
XCTAssertNotNil(self.server.collections["crypto"])
XCTAssertNotNil(self.server.collections["crypto"]?.records["keys"])
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
}
| mpl-2.0 |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Event/NotUse/BFEventView.swift | 1 | 9865 | //
// BFEventView.swift
// BeeFun
//
// Created by WengHengcong on 23/09/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
/*
event类型1:pull request类型
5 days ago
ashfurrow opened pull request AFNetworking/AFNetworking#4051
╭┈┈┈╮ Exposes C function prototype
| | ------------------------------------------------
╰┈┈┈╯ | -0- 1 commit with 1 addition and 0 deletions |
------------------------------------------------
*/
/*
event类型2:push commit、release类型
--->>>>>>>> push类型
4 days ago
davemachado pushed to master at toddmotto/public-apis
╭┈┈┈╮ ╭-╮ 2f9b6f0 Merge pull request #486 from DustyReagan/countio
| | ╰—╯
╰┈┈┈╯ ╭-╮ 4e79d6d Remove '... API' from Description
╰—╯
View comparison for these 2 commits » or
15 more commits »
注意:后面有两种类型,一种是查看这两个commit的对比,一个是查看更多的commit
--->>>>>>>> release类型
4 days ago
davemachado pushed to master at toddmotto/public-apis
╭┈┈┈╮ ╭-╮ Source code (zip)
| | ╰—╯
╰┈┈┈╯
注意:点击source code中直接下载zip文件
*/
/*
event类型3:opened issue、commented on issue 等类型
5 days ago
ashfurrow opened pull request AFNetworking/AFNetworking#4051
╭┈┈┈╮
| | Format string warnings
╰┈┈┈╯
*/
/*
event类型4:starred、forked等类型
5 days ago
Bogdan-Lyashenko starred byoungd/english-level-up-tips-for-Chinese
*/
class BFEventView: UIView {
var contentView: UIView = UIView() ///整个视图的容器
/// event 左上角的Action 图标,固定
var actionImageView = UIImageView()
var timeView: BFEventTimeView? /// 时间
var titleView: BFEventTitleView? /// title
/// 内容区域
var actionContentView = UIView() /// 内容区域的容器
var actorImageView = UIImageView() /// event 执行者头像
var textView: BFEventTextView? /// 内容,见类型1、3、4部分的文字内容区域
var prDetailView: BFEventPRDetailView? /// pull request的部分内容区域,见类型1
var commitView: BFEventCommitView? /// push commit的内容区域,见类型2
var topLine: UIView = UIView()
var bottomLine: UIView = UIView()
//数据
var cell: BFEventCell?
var layout: BFEventLayout?
override init(frame: CGRect) {
var newFrame = frame
if frame.size.width == 0 && frame.size.height == 0 {
newFrame.size.width = ScreenSize.width
newFrame.size.height = 1
}
super.init(frame: newFrame)
isUserInteractionEnabled = true
backgroundColor = .clear
contentView.backgroundColor = .clear
contentView.isUserInteractionEnabled = true
contentView.width = ScreenSize.width
contentView.height = 1.0
self.addSubview(contentView)
//line
let retinaPixelSize = 1.0 / (UIScreen.main.scale)
topLine.backgroundColor = UIColor.bfLineBackgroundColor
topLine.frame = CGRect(x: 0, y: 0, w: self.width, h: retinaPixelSize)
contentView.addSubview(topLine)
bottomLine.backgroundColor = UIColor.bfLineBackgroundColor
bottomLine.frame = CGRect(x: 0, y: self.height-retinaPixelSize, w: self.width, h: retinaPixelSize)
contentView.addSubview(bottomLine)
//action image name
actionImageView.frame = CGRect(x: BFEventConstants.ACTION_IMG_LEFT, y: BFEventConstants.ACTION_IMG_TOP, w: BFEventConstants.ACTION_IMG_WIDTH, h: BFEventConstants.ACTION_IMG_WIDTH)
// actionImageView.isHidden = true
actionImageView.image = UIImage(named: "git-comment-discussion_50")
actionImageView.isUserInteractionEnabled = true
contentView.addSubview(actionImageView)
//time
timeView = BFEventTimeView()
// timeView?.isHidden = true
contentView.addSubview(timeView!)
//title
titleView = BFEventTitleView()
// titleView?.isHidden = true
contentView.addSubview(titleView!)
//内容区域
actionContentView.backgroundColor = .clear
actionContentView.isUserInteractionEnabled = true
// actionContentView.isHidden = true
contentView.addSubview(actionContentView)
//actor image view
actorImageView.frame = CGRect(x: 0, y: 0, w: BFEventConstants.ACTOR_IMG_WIDTH, h: BFEventConstants.ACTOR_IMG_WIDTH)
actorImageView.isHidden = true
actionContentView.addSubview(actorImageView)
//text view
textView = BFEventTextView()
textView?.isHidden = true
actionContentView.addSubview(textView!)
//pull request detail view
prDetailView = BFEventPRDetailView()
prDetailView?.isHidden = true
actionContentView.addSubview(prDetailView!)
//commit view
commitView = BFEventCommitView()
commitView?.isHidden = true
actionContentView.addSubview(commitView!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setLayout(layout: BFEventLayout) {
self.layout = layout
//contnet view的位置
contentView.top = layout.marginTop
contentView.height = layout.totalHeight - layout.marginTop - layout.marginBottom
contentView.left = layout.marginLeft
contentView.right = ScreenSize.width - layout.marginLeft
//action image
if let actionImageName = layout.eventTypeActionImage {
actionImageView.image = UIImage(named: actionImageName)
}
//time
timeView?.origin = CGPoint(x: BFEventConstants.TIME_X, y: BFEventConstants.TIME_Y)
// timeView?.backgroundColor = UIColor.red
if layout.timeHeight > 0 {
timeView?.isHidden = false
timeView?.height = layout.timeHeight
timeView?.setLayout(layout: layout)
} else {
timeView?.isHidden = true
}
//title
titleView?.origin = CGPoint(x: timeView!.left, y: timeView!.bottom)
// titleView?.backgroundColor = UIColor.green
if layout.titleHeight > 0 {
titleView?.isHidden = false
titleView?.height = layout.titleHeight
titleView?.setLayout(layout: layout)
} else {
titleView?.isHidden = true
}
//-------------->>>>>> actionContentView 内容区域 <<<<<<<-------------
actionContentView.origin = CGPoint(x: titleView!.left, y: titleView!.bottom)
// actionContentView.backgroundColor = UIColor.red
actionContentView.width = BFEventConstants.ACTION_CONTENT_WIDTH
actionContentView.height = layout.actionContentHeight
//actor image
if let avatarUrl = layout.event?.actor?.avatar_url, let url = URL(string: avatarUrl) {
actorImageView.isHidden = false
actorImageView.origin = CGPoint(x: BFEventConstants.ACTOR_IMG_LEFT, y: BFEventConstants.ACTOR_IMG_TOP)
actorImageView.kf.setImage(with: url)
} else {
actorImageView.isHidden = true
}
if let type = layout.event?.type {
if type == .watchEvent {
actorImageView.isHidden = true
}
}
if layout.prDetailHeight > 0 {
//pull request 中,同样有text
textView?.origin = CGPoint(x: BFEventConstants.TEXT_X, y: BFEventConstants.TEXT_Y)
// textView?.backgroundColor = .red
if layout.textHeight > 0 {
textView?.isHidden = false
textView?.height = layout.textHeight
textView?.setLayout(layout: layout)
} else {
textView?.isHidden = true
}
commitView?.isHidden = true
prDetailView?.isHidden = false
prDetailView?.origin = CGPoint(x: textView!.left, y: textView!.bottom)
prDetailView?.height = layout.prDetailHeight
prDetailView?.setLayout(layout: layout)
} else if layout.commitHeight > 0 {
prDetailView?.isHidden = true
textView?.isHidden = true
commitView?.isHidden = false
commitView?.origin = CGPoint(x: BFEventConstants.COMMIT_X, y: BFEventConstants.COMMIT_Y)
commitView?.height = layout.commitHeight
commitView?.setLayout(layout: layout)
} else {
prDetailView?.isHidden = true
commitView?.isHidden = true
//text
textView?.origin = CGPoint(x: BFEventConstants.TEXT_X, y: BFEventConstants.TEXT_Y)
if layout.textHeight > 0 {
textView?.isHidden = false
textView?.height = layout.textHeight
textView?.setLayout(layout: layout)
} else {
textView?.isHidden = true
}
}
switch layout.style {
case .pullRequest:
actionContentView.isHidden = false
case .pushCommit:
actionContentView.isHidden = false
case .textPicture:
actionContentView.isHidden = false
case .text:
actionContentView.isHidden = true
break
}
}
}
| mit |
carabina/Butterfly | Example/Butterfly-Demo/ViewController.swift | 1 | 1754 | //
// ViewController.swift
// Butterfly-Demo
//
// Created by Wongzigii on 6/30/15.
// Copyright (c) 2015 Wongzigii. All rights reserved.
//
import UIKit
import Butterfly
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var objectArray: [String]?
var titleArray: [String]?
var dateArray: [String]?
var root = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
root = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("data", ofType: "plist")!)!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return root.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomSportCell", forIndexPath: indexPath) as! CustomCell
cell.selectionStyle = .None
let imgstr = root[indexPath.row]["bgimage"] as! String
cell.backgroundImageView.image = UIImage(named: imgstr)
let stadium = root[indexPath.row]["match"] as! String
cell.stadiumLabel.text = stadium
let date = root[indexPath.row]["date"] as! String
cell.dateLabel.text = date
let title = root[indexPath.row]["title"] as! String
cell.titleLabel.text = title
return cell
}
}
public class CustomCell : UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var stadiumLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var backgroundImageView: UIImageView!
}
| mit |
mcgraw/dojo-parse-tiiny | final/dojo-parse-tiiny/dojo-parse-tiiny/XMCTiinyViewController.swift | 1 | 4962 | //
// XMCTiinyViewController.swift
// dojo-parse-tiiny
//
// Created by David McGraw on 12/2/14.
// Copyright (c) 2014 David McGraw. All rights reserved.
//
import UIKit
class XMCTiinyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var photoCollectionView: UICollectionView!
@IBOutlet weak var capturePhoto: UIButton!
var cameraCellReference: XMCCameraCollectionViewCell?
var images: NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
self.refreshLayout()
}
func refreshLayout() {
let query = PFQuery(className: "XMCPhoto")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
// jump back to the background process the results
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
for (index, value) in enumerate(objects) {
let photoObj = value as PFObject
let image: PFFile = photoObj["image"] as PFFile
let imageData = image.getData()
// be sure to send the results back to our main thread
dispatch_async(dispatch_get_main_queue()) {
self.images.addObject(UIImage(data: imageData)!)
}
}
// refresh the collection
dispatch_async(dispatch_get_main_queue()) {
self.photoCollectionView.reloadData()
}
}
}
}
// MARK: Collection View
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.images.count + 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.row == 0 {
cameraCellReference = collectionView.dequeueReusableCellWithReuseIdentifier("cameraCellIdentifier", forIndexPath: indexPath) as? XMCCameraCollectionViewCell
return cameraCellReference!
}
var cell: XMCPhotoCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCellIdentifier", forIndexPath: indexPath) as XMCPhotoCollectionViewCell
var position = self.images.count - indexPath.row
cell.setPhotoWithImage(self.images.objectAtIndex(position) as? UIImage)
return cell
}
// MARK: Flow Layout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var value = UIScreen.mainScreen().bounds.width
value = (value/3.0) - 4
return CGSizeMake(value, value)
}
// MARK: Actions
@IBAction func takePhoto(sender: AnyObject) {
cameraCellReference?.captureFrame { (image) -> Void in
if let still = image {
// assume success so that the user will not encounter more lag than needed
self.images.addObject(still)
self.photoCollectionView.insertItemsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)])
// send the image to parse
var file: PFFile = PFFile(data: UIImageJPEGRepresentation(still, 0.7))
file.saveInBackgroundWithBlock({ (success, fileError) -> Void in
if success {
var object: PFObject = PFObject(className: "XMCPhoto")
object["image"] = file
object.saveInBackgroundWithBlock({ (success, objError) -> Void in
if success {
println("Photo object saved")
} else {
println("Unable to create a photo object: \(objError)")
}
})
} else {
println("Unable to save file: \(fileError)")
}
})
/* NOTE: in the event that the code above fails, you want to revert
our photo addition and then alert the user.
OR, create an upload manager that will retry the upload attempt.
*/
}
}
}
// MARK: Gesture Actions
@IBAction func doubleTappedCollection(sender: AnyObject) {
var point = sender.locationInView(self.photoCollectionView)
var indexPath = self.photoCollectionView.indexPathForItemAtPoint(point)
if indexPath?.row > 0 {
println("Double Tapped Photo At Index \(indexPath!.row-1)")
}
}
}
| mit |
marko1503/Algorithms-and-Data-Structures-Swift | Sort/Insertion Sort/InsertionSort.playground/Contents.swift | 1 | 1310 | //: Playground - noun: a place where people can play
import UIKit
// MARK: - Insertion sort
//func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
// var a = array
// for x in 1..<a.count {
// var y = x
// let temp = a[y]
// while y > 0 && isOrderedBefore(temp, a[y - 1]) {
// a[y] = a[y - 1]
// y -= 1
// }
// a[y] = temp
// }
// return a
//}
//: 
func insertionSort<Element>(array: [Element]) -> [Element] {
// check for tirivial case
// we have only 1 element in array
guard array.count > 1 else { return array }
var output: [Element] = array
for primaryIndex in 1..<output.count {
let primaryElement = output[primaryIndex]
var tempIndex = primaryIndex - 1
while tempIndex > -1 {
// primaryElement and element at tempIndex are not ordered. We need to change them
// Then, remove primary element
// tempIndex + 1 - primaryElement always after tempIndex
output.remove(at: tempIndex + 1)
// and insert primary element before tempElement
output.insert(primaryElement, at: tempIndex)
tempIndex -= 1
}
}
return output
}
| apache-2.0 |
ReactiveX/RxSwift | RxSwift/Traits/Infallible/Infallible+Operators.swift | 1 | 34638 | //
// Infallible+Operators.swift
// RxSwift
//
// Created by Shai Mishali on 27/08/2020.
// Copyright © 2020 Krunoslav Zaher. All rights reserved.
//
// MARK: - Static allocation
extension InfallibleType {
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element) -> Infallible<Element> {
Infallible(.just(element))
}
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- parameter scheduler: Scheduler to send the single element on.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Infallible<Element> {
Infallible(.just(element, scheduler: scheduler))
}
/**
Returns a non-terminating infallible sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence whose observers will never get called.
*/
public static func never() -> Infallible<Element> {
Infallible(.never())
}
/**
Returns an empty infallible sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence with no elements.
*/
public static func empty() -> Infallible<Element> {
Infallible(.empty())
}
/**
Returns an infallible sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> Infallible<Element>)
-> Infallible<Element> {
Infallible(.deferred { try observableFactory().asObservable() })
}
}
// MARK: From & Of
extension Infallible {
/**
This method creates a new Infallible instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription.
- returns: The Infallible sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> {
Infallible(Observable.from(elements, scheduler: scheduler))
}
}
extension Infallible {
/**
Converts an array to an Infallible sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The Infallible sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> {
Infallible(Observable.from(array, scheduler: scheduler))
}
/**
Converts a sequence to an Infallible sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The Infallible sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> where Sequence.Element == Element {
Infallible(Observable.from(sequence, scheduler: scheduler))
}
}
// MARK: - Filter
extension InfallibleType {
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (Element) -> Bool)
-> Infallible<Element> {
Infallible(asObservable().filter(predicate))
}
}
// MARK: - Map
extension InfallibleType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) -> Result)
-> Infallible<Result> {
Infallible(asObservable().map(transform))
}
/**
Projects each element of an observable sequence into an optional form and filters all optional results.
- parameter transform: A transform function to apply to each source element and which returns an element or nil.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) -> Result?)
-> Infallible<Result> {
Infallible(asObservable().compactMap(transform))
}
}
// MARK: - Distinct
extension InfallibleType where Element: Equatable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinctUntilChanged()
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged())
}
}
extension InfallibleType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged(keySelector, comparer: { $0 == $1 }))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged({ $0 }, comparer: comparer))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged(keySelector, comparer: comparer))
}
/**
Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path
*/
public func distinctUntilChanged<Property: Equatable>(at keyPath: KeyPath<Element, Property>) ->
Infallible<Element> {
Infallible(asObservable().distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] })
}
}
// MARK: - Throttle
extension InfallibleType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().debounce(dueTime, scheduler: scheduler))
}
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().throttle(dueTime, latest: latest, scheduler: scheduler))
}
}
// MARK: - FlatMap
extension InfallibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMap(selector))
}
/**
Projects each element of an observable sequence into a new sequence of observable sequences and then
transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
It is a combination of `map` + `switchLatest` operator
- seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an
Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func flatMapLatest<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapLatest(selector))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapFirst(selector))
}
}
// MARK: - Concat
extension InfallibleType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Infallible<Element> where Source.Element == Element {
Infallible(Observable.concat([self.asObservable(), second.asObservable()]))
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Infallible<Element>
where Sequence.Element == Infallible<Element> {
Infallible(Observable.concat(sequence.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Infallible<Element>
where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(collection.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Infallible<Element> ...) -> Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().concatMap(selector))
}
}
// MARK: - Merge
extension InfallibleType {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences from array into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: [Infallible<Element>]) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: Infallible<Element>...) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
}
// MARK: - Do
extension Infallible {
/**
Invokes an action for each event in the infallible sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter afterCompleted: Action to invoke after graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Infallible<Element> {
Infallible(asObservable().do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose))
}
}
// MARK: - Scan
extension InfallibleType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(into seed: Seed, accumulator: @escaping (inout Seed, Element) -> Void)
-> Infallible<Seed> {
Infallible(asObservable().scan(into: seed, accumulator: accumulator))
}
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(_ seed: Seed, accumulator: @escaping (Seed, Element) -> Seed)
-> Infallible<Seed> {
Infallible(asObservable().scan(seed, accumulator: accumulator))
}
}
// MARK: - Start with
extension InfallibleType {
/**
Prepends a value to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter element: Element to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
public func startWith(_ element: Element) -> Infallible<Element> {
Infallible(asObservable().startWith(element))
}
}
// MARK: - Take and Skip {
extension InfallibleType {
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: InfallibleType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other.asObservable()))
}
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other))
}
/**
Returns elements from an observable sequence until the specified condition is true.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter predicate: A function to test each element for a condition.
- parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes.
*/
public func take(until predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(until: predicate, behavior: behavior))
}
/**
Returns elements from an observable sequence as long as a specified condition is true.
- seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
public func take(while predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(while: predicate, behavior: behavior))
}
/**
Returns a specified number of contiguous elements from the start of an observable sequence.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter count: The number of elements to return.
- returns: An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
public func take(_ count: Int) -> Infallible<Element> {
Infallible(asObservable().take(count))
}
/**
Takes elements for the specified duration from the start of the infallible source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An infallible sequence with the elements taken during the specified duration from the start of the source sequence.
*/
public func take(for duration: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().take(for: duration, scheduler: scheduler))
}
/**
Bypasses elements in an infallible sequence as long as a specified condition is true and then returns the remaining elements.
- seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An infallible sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
public func skip(while predicate: @escaping (Element) throws -> Bool) -> Infallible<Element> {
Infallible(asObservable().skip(while: predicate))
}
/**
Returns the elements from the source infallible sequence that are emitted after the other infallible sequence produces an element.
- seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html)
- parameter other: Infallible sequence that starts propagation of elements of the source sequence.
- returns: An infallible sequence containing the elements of the source sequence that are emitted after the other sequence emits an item.
*/
public func skip<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().skip(until: other))
}
}
// MARK: - Share
extension InfallibleType {
/**
Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer.
This operator is equivalent to:
* `.whileConnected`
```
// Each connection will have it's own subject instance to store replay events.
// Connections will be isolated from each another.
source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount()
```
* `.forever`
```
// One subject will store replay events for all connections to source.
// Connections won't be isolated from each another.
source.multicast(Replay.create(bufferSize: replay)).refCount()
```
It uses optimized versions of the operators for most common operations.
- parameter replay: Maximum element count of the replay buffer.
- parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
-> Infallible<Element> {
Infallible(asObservable().share(replay: replay, scope: scope))
}
}
// MARK: - withUnretained
extension InfallibleType {
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence.
In the case the provided object cannot be retained successfully, the sequence will complete.
- note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle.
- parameter obj: The object to provide an unretained reference on.
- parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence.
- returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence.
*/
public func withUnretained<Object: AnyObject, Out>(
_ obj: Object,
resultSelector: @escaping (Object, Element) -> Out
) -> Infallible<Out> {
Infallible(self.asObservable().withUnretained(obj, resultSelector: resultSelector))
}
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence.
In the case the provided object cannot be retained successfully, the sequence will complete.
- note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle.
- parameter obj: The object to provide an unretained reference on.
- returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence.
*/
public func withUnretained<Object: AnyObject>(_ obj: Object) -> Infallible<(Object, Element)> {
withUnretained(obj) { ($0, $1) }
}
}
extension InfallibleType {
// MARK: - withLatestFrom
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: InfallibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Infallible<ResultType> {
Infallible(self.asObservable().withLatestFrom(second.asObservable(), resultSelector: resultSelector))
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: InfallibleType>(_ second: Source) -> Infallible<Source.Element> {
withLatestFrom(second) { $1 }
}
}
| mit |
diejmon/SystemWindowController | Package.swift | 1 | 389 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "SystemWindowController",
platforms: [
.iOS(.v10)
],
products: [
.library(
name: "SystemWindowController",
targets: ["SystemWindowController"]
),
],
dependencies: [
],
targets: [
.target(
name: "SystemWindowController",
dependencies: []
)
]
)
| mit |
glock45/swifter | XCode/SwifterTestsCommon/SwifterTestsRC4.swift | 1 | 580 | //
// SwifterTestsRC4.swift
// Swifter
//
// Copyright © 2016 Damian Kołakowski. All rights reserved.
//
import XCTest
class SwifterTestsRC4: XCTestCase {
func testRC4() {
let encrypted = RC4.encrypt([UInt8]("Plaintext".utf8), [UInt8]("Key".utf8))
XCTAssertEqual(encrypted, [0xbb, 0xf3, 0x16, 0xe8, 0xd9, 0x40, 0xaf, 0x0a, 0xd3])
let decrypted = RC4.decrypt([0xbb, 0xf3, 0x16, 0xe8, 0xd9, 0x40, 0xaf, 0x0a, 0xd3], [UInt8]("Key".utf8))
XCTAssertEqual(decrypted, [UInt8]("Plaintext".utf8))
}
}
| bsd-3-clause |
louisdh/panelkit | PanelKit/Model/Constants.swift | 1 | 964 | //
// Constants.swift
// PanelKit
//
// Created by Louis D'hauwe on 07/03/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import Foundation
import CoreGraphics
import UIKit
// Exposé
let exposeOuterPadding: CGFloat = 44.0
let exposeExitDuration: TimeInterval = 0.3
let exposeEnterDuration: TimeInterval = 0.3
let exposePanelHorizontalSpacing: CGFloat = 20.0
let exposePanelVerticalSpacing: CGFloat = 20.0
// Pinned
let pinnedPanelPreviewAlpha: CGFloat = 0.4
let pinnedPanelPreviewGrowDuration: TimeInterval = 0.3
let pinnedPanelPreviewFadeDuration: TimeInterval = 0.3
let panelGrowDuration: TimeInterval = 0.3
// Floating
let panelPopDuration: TimeInterval = 0.2
let panelPopYOffset: CGFloat = 12.0
// PanelViewController
let cornerRadius: CGFloat = 16.0
// Panel shadow
let shadowRadius: CGFloat = 8.0
let shadowOpacity: Float = 0.3
let shadowOffset: CGSize = CGSize(width: 0, height: 10.0)
let shadowColor = UIColor.black.cgColor
| mit |
LKY769215561/KYHandMade | KYHandMade/KYHandMade/Class/NewFeature(新特性)/Controller/KYNewFeatureController.swift | 1 | 1779 | //
// KYNewFeatureController.swift
// KYHandMade
//
// Created by Kerain on 2017/6/8.
// Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved.
//
import UIKit
let featureCellId = "featureCell"
class KYNewFeatureController: UICollectionViewController{
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(UINib.init(nibName: "KYNewFeatureCell", bundle: nil), forCellWithReuseIdentifier: featureCellId)
collectionView?.bounces = false
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.isPagingEnabled = true
}
}
extension KYNewFeatureController{
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let kyCell = (collectionView.dequeueReusableCell(withReuseIdentifier: featureCellId, for: indexPath)) as! KYNewFeatureCell
kyCell.featureImageView.image = UIImage(named : "newfeature_0\(indexPath.item+1)_736")
return kyCell
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
if indexPath.item == 4 {
UIApplication.shared.keyWindow?.rootViewController = KYAdViewController.loadFromNib()
let anim = CATransition()
anim.type = "rippleEffect"
anim.duration = 1
UIApplication.shared.keyWindow?.layer.add(anim, forKey: nil)
}
}
}
| apache-2.0 |
jfosterdavis/FlashcardHero | FlashcardHero/MissionFeedbackViewController.swift | 1 | 7986 | //
// MissionFeedbackViewController.swift
// FlashcardHero
//
// Created by Jacob Foster Davis on 12/9/16.
// Copyright © 2016 Zero Mu, LLC. All rights reserved.
//
import Foundation
import CoreData
import UIKit
protocol MissionFeedbackDelegate {
func setupWith(wasSuccess: Bool, numStars: Int, timeElapsedString time: String, totalPoints points: Int, accuracy: Double, customStats stats: [String:Any]?, senderVC sender: UIViewController, destinationVC:UIViewController?, vCCompletion: (() -> Void)?)
}
class MissionFeedbackViewController: CoreDataQuizletCollectionViewController, MissionFeedbackDelegate {
@IBOutlet weak var summaryLabel: UILabel!
@IBOutlet weak var star1: UIImageView!
@IBOutlet weak var star2: UIImageView!
@IBOutlet weak var star3: UIImageView!
@IBOutlet weak var timeElapsedLabel: UILabel!
@IBOutlet weak var accuracyLabel: UILabel!
@IBOutlet weak var customLabel1: UILabel!
@IBOutlet weak var customLabel2: UILabel!
@IBOutlet weak var customStatLabel1: UILabel!
@IBOutlet weak var customStatLabel2: UILabel!
@IBOutlet weak var totalPointsLabel: UILabel!
@IBOutlet weak var okButton: UIButton!
var destinationVC: UIViewController!
var senderVC: UIViewController!
var destinationVCCompletion: (() -> Void)?
var summaryLabelText = ""
var numStars = 0
var timeElapsedLabelText = ""
var totalPointsLabelText = ""
var accuracyLabelText = ""
var customLabel1Text = ""
var customLabel2Text = ""
var customStatLabel1Text = ""
var customStatLabel2Text = ""
/******************************************************/
/*******************///MARK: Life Cycle
/******************************************************/
override func viewDidLoad() {
super.viewDidLoad()
summaryLabel.text = summaryLabelText
switch numStars {
case 0:
//highlight 0 stars
starHighlighter(0)
case 1:
//highlight 1 star
starHighlighter(1)
case 2:
//highlight 2 stars
starHighlighter(2)
case 3:
//highlight 3 stars
starHighlighter(3)
default:
//highlight 0 stars
starHighlighter(0)
}
timeElapsedLabel.text = timeElapsedLabelText
totalPointsLabel.text = totalPointsLabelText
accuracyLabel.text = accuracyLabelText
customLabel1.text = customLabel1Text
customLabel2.text = customLabel2Text
customStatLabel1.text = customStatLabel1Text
customStatLabel2.text = customStatLabel2Text
//show or hide the custom stats
if customLabel1.text != nil && customStatLabel1.text != nil {
customLabel1.isHidden = false
customStatLabel1.isHidden = false
} else {
customLabel1.isHidden = true
customStatLabel1.isHidden = true
}
if customLabel2.text != nil && customStatLabel2.text != nil {
customLabel2.isHidden = false
customStatLabel2.isHidden = false
} else {
customLabel2.isHidden = true
customStatLabel2.isHidden = true
}
}
/******************************************************/
/*******************///MARK: MissionFeedbackDelegate
/******************************************************/
/**
Delegate method used by anything that calls this view, should do so with this method in closure.
*/
func setupWith(wasSuccess: Bool, numStars: Int, timeElapsedString time: String, totalPoints points: Int, accuracy: Double, customStats stats: [String:Any]? = nil, senderVC sender: UIViewController, destinationVC:UIViewController? = nil, vCCompletion: (() -> Void)? = nil){
if wasSuccess {
summaryLabelText = "Success!"
} else {
summaryLabelText = "Failed!"
}
self.numStars = numStars
timeElapsedLabelText = time
totalPointsLabelText = String(describing: points)
if accuracy.isNaN || accuracy.isInfinite {
print("Incoming accuracy was NaN or infinate. \(accuracy)")
accuracyLabelText = "--"
} else {
let aValue = Int(round(accuracy * 100))
accuracyLabelText = "\(aValue)%"
}
senderVC = sender
//if didn't supply a destination, then assume destination is back to sender
if let destinationVC = destinationVC {
self.destinationVC = destinationVC
} else {
self.destinationVC = sender
}
self.destinationVCCompletion = vCCompletion
//handle the first two custom stats
if let stats = stats {
customLabel1Text = ""
for (statLabel, statValue) in stats {
if customLabel1Text == "" {
customLabel1Text = statLabel
customStatLabel1Text = String(describing: statValue)
} else { //if the first label is nil, do the second label
customLabel2Text = statLabel
customStatLabel2Text = String(describing: statValue)
}
}
}
}
func starHighlighter(_ numStars: Int) {
guard numStars <= 3 && numStars >= 0 else {
print("Invalid number of stars to highlight \(numStars)")
return
}
switch numStars {
case 0:
//don't highlight anything, keep all gray
starHighlight(star: 1, doHighlight: false)
starHighlight(star: 2, doHighlight: false)
starHighlight(star: 3, doHighlight: false)
case 1:
starHighlight(star: 1, doHighlight: true)
starHighlight(star: 2, doHighlight: false)
starHighlight(star: 3, doHighlight: false)
case 2:
starHighlight(star: 1, doHighlight: true)
starHighlight(star: 2, doHighlight: true)
starHighlight(star: 3, doHighlight: false)
case 3:
starHighlight(star: 1, doHighlight: true)
starHighlight(star: 2, doHighlight: true)
starHighlight(star: 3, doHighlight: true)
default:
return
}
}
func starHighlight(star:Int, doHighlight: Bool) {
guard star <= 3 && star >= 1 else {
print("Requested to highlight invalid star number \(star)")
return
}
var starToHighlight: UIImageView
switch star {
case 1:
starToHighlight = star1
case 2:
starToHighlight = star2
case 3:
starToHighlight = star3
default:
return
}
if doHighlight {
starToHighlight.image = #imageLiteral(resourceName: "Star")
} else {
starToHighlight.image = #imageLiteral(resourceName: "StarGray")
}
}
/******************************************************/
/*******************///MARK: Actions
/******************************************************/
@IBAction func okButtonPressed(_ sender: Any) {
if senderVC == destinationVC {
//TODO: Improve visuals of this transition
self.senderVC.dismiss(animated: false, completion: self.destinationVCCompletion)
self.dismiss(animated: true, completion: nil)
} else { //needs to be send elsewhere
//TODO: Improve this for user
self.dismiss(animated: false, completion: { self.present(self.destinationVC, animated: false, completion: self.destinationVCCompletion)})
}
}
}
| apache-2.0 |
rivetlogic/liferay-mobile-directory-ios | MobilePeopleDirectory/PersonViewCell.swift | 1 | 830 | //
// PersonViewCell.swift
// MobilePeopleDirectory
//
// Created by alejandro soto on 1/24/15.
// Copyright (c) 2015 Rivet Logic. All rights reserved.
//
import UIKit
class PersonViewCell: UITableViewCell {
@IBOutlet weak var fullName: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var thumbnailImage: UIImageView!
@IBOutlet weak var emailIcon: UIImageView!
@IBOutlet weak var phoneIcon: UIImageView!
@IBOutlet weak var skypeIcon: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 |
TCA-Team/iOS | TUM Campus App/LecturesTableViewController.swift | 1 | 3545 | //
// LecturesTableViewController.swift
// TUM Campus App
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Sweeft
import UIKit
private func mapped(lectures: [Lecture]) -> [(String, [Lecture])] {
let ordered = lectures.map { $0.semester }
let semesters = Set(ordered).sorted(ascending: { ordered.index(of: $0) ?? ordered.count })
return semesters.map { semester in
return (semester, lectures.filter { $0.semester == semester })
}
}
class LecturesTableViewController: RefreshableTableViewController<Lecture>, DetailViewDelegate, DetailView {
override var values: [Lecture] {
get {
return lectures.flatMap { $1 }
}
set {
lectures = mapped(lectures: newValue)
}
}
var lectures = [(String,[Lecture])]() {
didSet {
tableView.reloadData()
}
}
weak var delegate: DetailViewDelegate?
var currentLecture: DataElement?
func dataManager() -> TumDataManager? {
return delegate?.dataManager()
}
override func fetch(skipCache: Bool) -> Promise<[Lecture], APIError>? {
return delegate?.dataManager()?.lecturesManager.fetch(skipCache: skipCache)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let mvc = segue.destination as? LectureDetailsTableViewController {
mvc.lecture = currentLecture
mvc.delegate = self
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return lectures.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lectures[section].1.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return lectures[section].0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = lectures[indexPath.section].1[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: item.getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell()
cell.setElement(item)
return cell
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.contentView.backgroundColor = Constants.tumBlue
header.textLabel?.textColor = UIColor.white
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
currentLecture = lectures[indexPath.section].1[indexPath.row]
return indexPath
}
}
| gpl-3.0 |
alreadyRight/Swift-algorithm | 计算型属性/计算型属性/Person.swift | 1 | 1127 | //
// Person.swift
// 计算型属性
//
// Created by 周冰烽 on 2017/12/12.
// Copyright © 2017年 周冰烽. All rights reserved.
//
import UIKit
class Person: NSObject {
var _name: String?
// getter & setter 仅用演示,日常开发不用
// Swift 中一般不会重写getter和setter方法
var name: String? {
get{
//返回 _成员变量
return _name
}
set{
_name = newValue
}
}
var title: String?{
//只
get{
return "Mr." + (name ?? "")
}
}
//只读属性的简写 -->直接 return
//又称为计算型属性 -> 本省不保存内容,都是通过计算获取结果
//类似一个函数
// - 没有参数
// - 一定有返回值
var title2: String {
return "Mr XXX." + (name ?? "")
}
//懒加载的 title ,本质是一个闭包
//懒加载会在第一次访问的时候,执行,闭包执行结束后,会把结果保存在 title3 中
lazy var title3: String = {
return "lazy" + (self.name ?? "")
}()
}
| mit |
kennethcc2005/Sharity | LuckymoneyTableViewCell.swift | 1 | 572 | //
// LuckymoneyTableViewCell.swift
// Sharity
//
// Created by Zoesh on 10/24/15.
// Copyright © 2015 Zoesh. All rights reserved.
//
import UIKit
protocol LuckymoneyCellDelegate {
func didTappedBuyButton () -> Void
}
class LuckymoneyTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
mathewsheets/SwiftLearning | SwiftLearning.playground/Pages/Exercise 8.xcplaygroundpage/Contents.swift | 1 | 571 | /*:
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
- - -
* callout(Exercise): Create two classes `Dog` and `Cat`. Each will have properties of `breed`, `color`, `age` and `name`. They also have methods of `barking` (dog's) only, `meowing` (cats only), `eating`, `sleeping`, `playing`, and `chase`.
**Constraints:**
- Initializer & Deinitializer
- Computed Properties
- Property Observers
- Method body is up to you, but your method signatures need parameter(s)
- - -
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
*/ | mit |
lkzhao/Hero | Sources/Preprocessors/SourcePreprocessor.swift | 1 | 3416 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <me@lkzhao.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(UIKit)
import UIKit
class SourcePreprocessor: BasePreprocessor {
override func process(fromViews: [UIView], toViews: [UIView]) {
for fv in fromViews {
guard let id = context[fv]?.source,
let tv = context.destinationView(for: id) else { continue }
prepareFor(view: fv, targetView: tv)
}
for tv in toViews {
guard let id = context[tv]?.source,
let fv = context.sourceView(for: id) else { continue }
prepareFor(view: tv, targetView: fv)
}
}
func prepareFor(view: UIView, targetView: UIView) {
let targetPos = context.container.convert(targetView.layer.position, from: targetView.superview!)
let targetTransform = context.container.layer.flatTransformTo(layer: targetView.layer)
var state = context[view]!
// use global coordinate space since over target position is converted from the global container
state.coordinateSpace = .global
state.position = targetPos
state.transform = targetTransform
// remove incompatible options
state.size = nil
if view.bounds.size != targetView.bounds.size {
state.size = targetView.bounds.size
}
if state.cornerRadius == nil, view.layer.cornerRadius != targetView.layer.cornerRadius {
state.cornerRadius = targetView.layer.cornerRadius
}
if view.layer.shadowColor != targetView.layer.shadowColor {
state.shadowColor = targetView.layer.shadowColor
}
if view.layer.shadowOpacity != targetView.layer.shadowOpacity {
state.shadowOpacity = targetView.layer.shadowOpacity
}
if view.layer.shadowOffset != targetView.layer.shadowOffset {
state.shadowOffset = targetView.layer.shadowOffset
}
if view.layer.shadowRadius != targetView.layer.shadowRadius {
state.shadowRadius = targetView.layer.shadowRadius
}
if view.layer.shadowPath != targetView.layer.shadowPath {
state.shadowPath = targetView.layer.shadowPath
}
if view.layer.contentsRect != targetView.layer.contentsRect {
state.contentsRect = targetView.layer.contentsRect
}
if view.layer.contentsScale != targetView.layer.contentsScale {
state.contentsScale = targetView.layer.contentsScale
}
context[view] = state
}
}
#endif
| mit |
gb-6k-house/YsSwift | Sources/Rabbit/Manager.swift | 1 | 7109 | /******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: 管理类
** Copyright © 2017年 尧尚信息科技(www.yourshares.cn). All rights reserved
******************************************************************************/
import Foundation
#if YSSWIFT_DEBUG
import YsSwift
#endif
import Result
//网络图片加载管理类
//完成如下流程: 数据从网络中下载 ->数据缓存本地(硬盘+内存) -> 数据解析成图片 -> 返回上层应用
public final class Manager {
public var loader: Loading
public let cache: Cache<ImageCache.CachedImage>?
public let defauleLoader : Loader = {
return Loader.shared as! Loader
}()
/// A set of trusted hosts when receiving server trust challenges.
//single instance
public static let shared = Manager(loader: Loader.shared, cache: ImageCache.shared)
//
public init(loader: Loading, cache: Cache<ImageCache.CachedImage>? = nil) {
self.loader = loader
self.cache = cache
}
// MARK: Loading Images into Targets
/// Loads an image into the given target. Cancels previous outstanding request
/// associated with the target.
///
/// If the image is stored in the memory cache, the image is displayed
/// immediately. The image is loaded using the `loader` object otherwise.
///
/// `Manager` keeps a weak reference to the target. If the target deallocates
/// the associated request automatically gets cancelled.
public func loadImage(with request: Request, into target: Target) {
loadImage(with: request, into: target) { [weak target] in
target?.handle(response: $0, isFromMemoryCache: $1)
}
}
public typealias Handler = (Result<Image, YsSwift.RequestError>, _ isFromMemoryCache: Bool) -> Void
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed. The handler gets called immediately
/// if the image was stored in the memory cache.
///
/// See `loadImage(with:into:)` method for more info.
public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Handler) {
assert(Thread.isMainThread)
// Cancel outstanding request if any
cancelRequest(for: target)
// Quick synchronous memory cache lookup
if let image = cachedImage(for: request) {
handler(.success(image), true)
return
}
// Create context and associate it with a target
let cts = CancellationTokenSource(lock: CancellationTokenSource.lock)
let context = Context(cts)
Manager.setContext(context, for: target)
// Start the request
loadImage(with: request, token: cts.token) { [weak context, weak target] in
guard let context = context, let target = target else { return }
guard Manager.getContext(for: target) === context else { return }
handler($0, false)
context.cts = nil // Avoid redundant cancellations on deinit
}
}
// MARK: Loading Images w/o Targets
/// Loads an image with a given request by using manager's cache and loader.
///
/// - parameter completion: Gets called asynchronously on the main thread.
public func loadImage(with request: Request, token: CancellationToken?, completion: @escaping (Result<Image, YsSwift.RequestError>) -> Void) {
if token?.isCancelling == true { return } // Fast preflight check
self._loadImage(with: request, token: token) { result in
DispatchQueue.main.async { completion(result) }
}
}
private func _loadImage(with request: Request, token: CancellationToken? = nil, completion: @escaping (Result<Image, YsSwift.RequestError>) -> Void) {
// Check if image is in memory cache
if let image = cachedImage(for: request) {
completion(.success(image))
} else {
// Use underlying loader to load an image and then store it in cache
loader.loadImage(with: request, token: token) { [weak self] in
if let image = $0.value {
self?.store(image: image, for: request)
}
completion($0)
}
}
}
/// Cancels an outstanding request associated with the target.
public func cancelRequest(for target: AnyObject) {
assert(Thread.isMainThread)
if let context = Manager.getContext(for: target) {
context.cts?.cancel()
Manager.setContext(nil, for: target)
}
}
// MARK: Memory Cache Helpers
private func cachedImage(for request: Request) -> Image? {
return cache?[request]?.value as? Image
}
private func store(image: Image, for request: Request) {
cache?[request] = ImageCache.CachedImage(value: image)
}
// MARK: Managing Context
private static var contextAK = "com.github.YKit.Manager.Context.AssociatedKey"
// Associated objects is a simplest way to bind Context and Target lifetimes
// The implementation might change in the future.
private static func getContext(for target: AnyObject) -> Context? {
return objc_getAssociatedObject(target, &contextAK) as? Context
}
private static func setContext(_ context: Context?, for target: AnyObject) {
objc_setAssociatedObject(target, &contextAK, context, .OBJC_ASSOCIATION_RETAIN)
}
private final class Context {
var cts: CancellationTokenSource?
init(_ cts: CancellationTokenSource) { self.cts = cts }
// Automatically cancel the request when target deallocates.
deinit { cts?.cancel() }
}
}
public extension Manager {
/// Loads an image into the given target. See the corresponding
/// `loadImage(with:into)` method that takes `Request` for more info.
public func loadImage(with url: URL, into target: Target) {
loadImage(with: Request(url: url), into: target)
}
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed. The handler gets called immediately
/// if the image was stored in the memory cache.
///
/// See `loadImage(with:into:)` method for more info.
public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Handler) {
loadImage(with: Request(url: url), into: target, handler: handler)
}
}
| mit |
hyp/SwiftDocDigger | SwiftDocDigger/DocXMLParser.swift | 1 | 10484 | //
// DocXMLParser.swift
// SwiftDocDigger
//
import Foundation
public enum SwiftDocXMLError : Error {
case unknownParseError
/// An xml parse error.
case parseError(Error)
/// A required attribute is missing, e.g. <Link> without href attribute.
case missingRequiredAttribute(element: String, attribute: String)
/// A required child element is missing e.g. <Parameter> without the <Name>.
case missingRequiredChildElement(element: String, childElement: String)
/// More than one element is specified where just one is needed.
case moreThanOneElement(element: String)
/// An element is outside of its supposed parent.
case elementNotInsideExpectedParentElement(element: String, expectedParentElement: String)
}
/// Parses swift's XML documentation.
public func parseSwiftDocAsXML(_ source: String) throws -> Documentation? {
guard !source.isEmpty else {
return nil
}
guard let data = source.data(using: String.Encoding.utf8) else {
assertionFailure()
return nil
}
let delegate = SwiftXMLDocParser()
do {
let parser = XMLParser(data: data)
parser.delegate = delegate
guard parser.parse() else {
guard let error = parser.parserError else {
throw SwiftDocXMLError.unknownParseError
}
throw SwiftDocXMLError.parseError(error)
}
}
if let error = delegate.parseError {
throw error
}
assert(delegate.stack.isEmpty)
return Documentation(declaration: delegate.declaration, abstract: delegate.abstract, discussion: delegate.discussion, parameters: delegate.parameters, resultDiscussion: delegate.resultDiscussion)
}
private class SwiftXMLDocParser: NSObject, XMLParserDelegate {
enum StateKind {
case root
case declaration
case abstract
case discussion
case parameters
case parameter(name: NSMutableString, discussion: [DocumentationNode]?)
case parameterName(NSMutableString)
case parameterDiscussion
case resultDiscussion
case node(DocumentationNode.Element)
// Some other node we don't really care about.
case other
}
struct State {
var kind: StateKind
let elementName: String
var nodes: [DocumentationNode]
}
var stack: [State] = []
var parameterDepth = 0
var hasFoundRoot = false
var parseError: SwiftDocXMLError?
// The results
var declaration: [DocumentationNode]?
var abstract: [DocumentationNode]?
var discussion: [DocumentationNode]?
var resultDiscussion: [DocumentationNode]?
var parameters: [Documentation.Parameter]?
func add(_ element: DocumentationNode.Element, children: [DocumentationNode] = []) {
guard !stack.isEmpty else {
assertionFailure()
return
}
stack[stack.count - 1].nodes.append(DocumentationNode(element: element, children: children))
}
func replaceTop(_ state: StateKind) {
assert(!stack.isEmpty)
stack[stack.count - 1].kind = state
}
func handleError(_ error: SwiftDocXMLError) {
guard parseError == nil else {
return
}
parseError = error
}
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
func push(_ state: StateKind) {
stack.append(State(kind: state, elementName: elementName, nodes: []))
}
if stack.isEmpty {
// Root node.
assert(!hasFoundRoot)
assert(elementName == "Class" || elementName == "Function" || elementName == "Other")
push(.root)
hasFoundRoot = true
return
}
if case .parameter? = stack.last?.kind {
// Parameter information.
switch elementName {
case "Name":
assert(parameterDepth > 0)
push(.parameterName(""))
case "Discussion":
assert(parameterDepth > 0)
push(.parameterDiscussion)
default:
// Don't really care about the other nodes here (like Direction).
push(.other)
}
return
}
switch elementName {
case "Declaration":
push(.declaration)
case "Abstract":
push(.abstract)
case "Discussion":
push(.discussion)
case "Parameters":
push(.parameters)
case "Parameter":
assert(parameterDepth == 0)
parameterDepth += 1
let last = stack.last
push(.parameter(name: "", discussion: nil))
guard case .parameters? = last?.kind else {
handleError(.elementNotInsideExpectedParentElement(element: elementName, expectedParentElement: "Parameters"))
return
}
case "ResultDiscussion":
push(.resultDiscussion)
case "Para":
push(.node(.paragraph))
case "rawHTML":
push(.node(.rawHTML("")))
case "codeVoice":
push(.node(.codeVoice))
case "Link":
guard let href = attributeDict["href"] else {
handleError(.missingRequiredAttribute(element: elementName, attribute: "href"))
push(.other)
return
}
push(.node(.link(href: href)))
case "emphasis":
push(.node(.emphasis))
case "strong":
push(.node(.strong))
case "bold":
push(.node(.bold))
case "List-Bullet":
push(.node(.bulletedList))
case "List-Number":
push(.node(.numberedList))
case "Item":
push(.node(.listItem))
case "CodeListing":
push(.node(.codeBlock(language: attributeDict["language"])))
case "zCodeLineNumbered":
push(.node(.numberedCodeLine))
case "Complexity", "Note", "Requires", "Warning", "Postcondition", "Precondition":
push(.node(.label(elementName)))
case "See":
push(.node(.label("See also")))
case "Name", "USR":
guard case .root? = stack.last?.kind else {
assertionFailure("This node is expected to be immediately inside the root node.")
return
}
// Don't really need these ones.
push(.other)
default:
push(.node(.other(elementName)))
}
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
guard let top = stack.popLast() else {
assertionFailure("Invalid XML")
return
}
assert(top.elementName == elementName)
switch top.kind {
case .node(let element):
add(element, children: top.nodes)
case .abstract:
guard abstract == nil else {
handleError(.moreThanOneElement(element: elementName))
return
}
abstract = top.nodes
case .declaration:
guard declaration == nil else {
handleError(.moreThanOneElement(element: elementName))
return
}
declaration = top.nodes
case .discussion:
// Docs can have multiple discussions.
discussion = discussion.flatMap { $0 + top.nodes } ?? top.nodes
case .parameter(let nameString, let discussion):
assert(parameterDepth > 0)
parameterDepth -= 1
let name = nameString as String
guard !name.isEmpty else {
handleError(.missingRequiredChildElement(element: "Parameter", childElement: "Name"))
return
}
let p = Documentation.Parameter(name: name, discussion: discussion)
parameters = parameters.flatMap { $0 + [ p ] } ?? [ p ]
case .parameterName(let nameString):
assert(parameterDepth > 0)
let name = nameString as String
guard !name.isEmpty else {
handleError(.missingRequiredChildElement(element: "Parameter", childElement: "Name"))
return
}
assert(top.nodes.isEmpty, "Other nodes present in parameter name")
switch stack.last?.kind {
case .parameter(let currentName, _)?:
guard (currentName as String).isEmpty else {
handleError(.moreThanOneElement(element: "Parameter.Name"))
return
}
currentName.setString(name)
default:
assertionFailure()
}
case .parameterDiscussion:
assert(parameterDepth > 0)
switch stack.last?.kind {
case .parameter(let name, let discussion)?:
// Parameters can have multiple discussions.
replaceTop(.parameter(name: name, discussion: discussion.flatMap { $0 + top.nodes } ?? top.nodes))
default:
assertionFailure()
}
case .resultDiscussion:
guard resultDiscussion == nil else {
handleError(.moreThanOneElement(element: elementName))
return
}
resultDiscussion = top.nodes
default:
break
}
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
guard stack.count > 1 else {
return
}
if case .parameterName(let name)? = stack.last?.kind {
name.append(string)
return
}
add(.text(string))
}
@objc func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
guard let str = String(data: CDATABlock, encoding: String.Encoding.utf8) else {
assertionFailure()
return
}
switch stack.last?.kind {
case .node(.rawHTML(let html))?:
replaceTop(.node(.rawHTML(html + str)))
break
case .node(.numberedCodeLine)?:
add(.text(str))
break
default:
assertionFailure("Unsupported data block")
}
}
}
| mit |
rizainuddin/ios-nd-alien-adventure-swift-3 | Alien Adventure/InscriptionEternalStar.swift | 1 | 814 | //
// InscriptionEternalStar.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 9/30/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func inscriptionEternalStar(inventory: [UDItem]) -> UDItem? {
var theEternalStar: UDItem?
let inscriptionText = "The Eternal Star"
for item in inventory {
if item.inscription?.contains(inscriptionText.uppercased()) == true {
theEternalStar = item
}
}
// print(theEternalStar)
return theEternalStar
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 3"
| mit |
kristoferdoman/stormy-treehouse-weather-app | Stormy/BackgroundView.swift | 2 | 1400 | //
// BackgroundView.swift
// Stormy
//
// Created by Kristofer Doman on 2015-07-02.
// Copyright (c) 2015 Kristofer Doman. All rights reserved.
//
import UIKit
class BackgroundView: UIView {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
// Background View
//// Color Declarations
let lightPurple: UIColor = UIColor(red: 0.377, green: 0.075, blue: 0.778, alpha: 1.000)
let darkPurple: UIColor = UIColor(red: 0.060, green: 0.036, blue: 0.202, alpha: 1.000)
let context = UIGraphicsGetCurrentContext()
//// Gradient Declarations
let purpleGradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [lightPurple.CGColor, darkPurple.CGColor], [0, 1])
//// Background Drawing
let backgroundPath = UIBezierPath(rect: CGRectMake(0, 0, self.frame.width, self.frame.height))
CGContextSaveGState(context)
backgroundPath.addClip()
CGContextDrawLinearGradient(context, purpleGradient,
CGPointMake(160, 0),
CGPointMake(160, 568),
UInt32(kCGGradientDrawsBeforeStartLocation) | UInt32(kCGGradientDrawsAfterEndLocation))
CGContextRestoreGState(context)
}
}
| mit |
ykyouhei/QiitaKit | QiitaKit/Sources/Requests/User/GetFolloweesRequest.swift | 1 | 1394 | //
// GetFolloweesRequest.swift
// QiitaKit
//
// Created by kyo__hei on 2016/07/16.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import Foundation
public extension QiitaAPI.User {
/// ユーザがフォローしているユーザ一覧を取得します
///
/// https://qiita.com/api/v2/docs#get-apiv2usersuser_idfollowees
public struct GetFolloweesRequest: QiitaPageableRequestType {
public typealias Response = PageableResponse<User>
// MARK: Properties
/// 取得するユーザID
public let userID: String
/// ページ番号 (1から100まで)
public var page: Int
/// 1ページあたりに含まれる要素数 (1から100まで)
public var perPage: Int
// MARK: Initialize
public init(userID: String, page: Int, perPage: Int) {
self.userID = userID
self.page = page
self.perPage = perPage
}
// MARK: QiitaRequest
public var method: HTTPMethod {
return .get
}
public var path: String {
return "users/\(userID)/followees"
}
public var queries: [String: String]? {
return pageParamaters
}
}
}
| mit |
knutigro/AppReviews | AppReviews/NSImageView+Networking.swift | 1 | 5938 | //
// NSImageView+Networking.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-13.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
protocol AFImageCacheProtocol:class{
func cachedImageForRequest(request:NSURLRequest) -> NSImage?
func cacheImage(image:NSImage, forRequest request:NSURLRequest);
}
extension NSImageView {
private struct AssociatedKeys {
static var SharedImageCache = "SharedImageCache"
static var RequestImageOperation = "RequestImageOperation"
static var URLRequestImage = "UrlRequestImage"
}
class func setSharedImageCache(cache:AFImageCacheProtocol?) {
objc_setAssociatedObject(self, &AssociatedKeys.SharedImageCache, cache, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
class func sharedImageCache() -> AFImageCacheProtocol {
struct Static {
static var token: dispatch_once_t = 0
static var defaultImageCache:AFImageCache?
}
dispatch_once(&Static.token, { () -> Void in
Static.defaultImageCache = AFImageCache()
})
return objc_getAssociatedObject(self, &AssociatedKeys.SharedImageCache) as? AFImageCache ?? Static.defaultImageCache!
}
class func af_sharedImageRequestOperationQueue() -> NSOperationQueue {
struct Static {
static var token:dispatch_once_t = 0
static var queue:NSOperationQueue?
}
dispatch_once(&Static.token, { () -> Void in
Static.queue = NSOperationQueue()
Static.queue!.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
})
return Static.queue!
}
private var af_requestImageOperation:(operation:NSOperation?, request: NSURLRequest?) {
get {
let operation:NSOperation? = objc_getAssociatedObject(self, &AssociatedKeys.RequestImageOperation) as? NSOperation
let request:NSURLRequest? = objc_getAssociatedObject(self, &AssociatedKeys.URLRequestImage) as? NSURLRequest
return (operation, request)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.RequestImageOperation, newValue.operation, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &AssociatedKeys.URLRequestImage, newValue.request, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func setImageWithUrl(url:NSURL, placeHolderImage:NSImage? = nil) {
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.addValue("image/*", forHTTPHeaderField: "Accept")
setImageWithUrlRequest(request, placeHolderImage: placeHolderImage, success: nil, failure: nil)
}
func setImageWithUrlRequest(request:NSURLRequest, placeHolderImage:NSImage? = nil,
success:((request:NSURLRequest?, response:NSURLResponse?, image:NSImage) -> Void)?,
failure:((request:NSURLRequest?, response:NSURLResponse?, error:NSError) -> Void)?)
{
cancelImageRequestOperation()
if let cachedImage = NSImageView.sharedImageCache().cachedImageForRequest(request) {
if success != nil {
success!(request: nil, response:nil, image: cachedImage)
}
else {
image = cachedImage
}
return
}
if placeHolderImage != nil {
image = placeHolderImage
}
af_requestImageOperation = (NSBlockOperation(block: { () -> Void in
var response:NSURLResponse?
var error:NSError?
let data: NSData?
do {
data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
} catch let error1 as NSError {
error = error1
data = nil
} catch {
fatalError()
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if request.URL!.isEqual(self.af_requestImageOperation.request?.URL) {
let image:NSImage? = (data != nil ? NSImage(data: data!): nil)
if image != nil {
if success != nil {
success!(request: request, response: response, image: image!)
}
else {
self.image = image!
}
}
else {
if failure != nil {
failure!(request: request, response:response, error: error!)
}
}
self.af_requestImageOperation = (nil, nil)
}
})
}), request)
NSImageView.af_sharedImageRequestOperationQueue().addOperation(af_requestImageOperation.operation!)
}
private func cancelImageRequestOperation() {
af_requestImageOperation.operation?.cancel()
af_requestImageOperation = (nil, nil)
}
}
func AFImageCacheKeyFromURLRequest(request:NSURLRequest) -> String {
return request.URL!.absoluteString
}
class AFImageCache: NSCache, AFImageCacheProtocol {
func cachedImageForRequest(request: NSURLRequest) -> NSImage? {
switch request.cachePolicy {
case NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData,
NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData:
return nil
default:
break
}
return objectForKey(AFImageCacheKeyFromURLRequest(request)) as? NSImage
}
func cacheImage(image: NSImage, forRequest request: NSURLRequest) {
setObject(image, forKey: AFImageCacheKeyFromURLRequest(request))
}
} | gpl-3.0 |
linkedin/ConsistencyManager-iOS | SampleApp/ConsistencyManagerDemo/ViewControllers/DetailViewController.swift | 2 | 2112 | // © 2016 LinkedIn Corp. 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.
import UIKit
import ConsistencyManager
class DetailViewController: UIViewController, ConsistencyManagerListener {
var update: UpdateModel
@IBOutlet weak var likeButton: UIButton!
init(update: UpdateModel) {
self.update = update
super.init(nibName: "DetailViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge()
title = update.id
ConsistencyManager.sharedInstance.addListener(self)
loadData()
}
func loadData() {
likeButton.isHidden = false
if update.liked {
likeButton.setTitle("Unlike", for: UIControl.State())
} else {
likeButton.setTitle("Like", for: UIControl.State())
}
}
@IBAction func deleteTapped(_ sender: UIButton) {
ConsistencyManager.sharedInstance.deleteModel(update)
_ = navigationController?.popViewController(animated: true)
}
@IBAction func likeButtonTapped(_ sender: UIButton) {
UpdateHelper.likeUpdate(update, like: !update.liked)
}
// MARK - Consistency Manager Delegate
func currentModel() -> ConsistencyManagerModel? {
return update
}
func modelUpdated(_ model: ConsistencyManagerModel?, updates: ModelUpdates, context: Any?) {
if let model = model as? UpdateModel {
if model != update {
update = model
loadData()
}
}
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.