repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kemalenver/SwiftHackerRank
Algorithms/Sorting.playground/Pages/Sorting - Quicksort 1 - Partition.xcplaygroundpage/Contents.swift
1
1263
import Foundation var inputs = ["5", "4 5 3 7 2"] func readLine() -> String? { let next = inputs.first inputs.removeFirst() return next } let arraySize = Int(readLine()!)! let array = readLine()!.split(separator: " ").map { Int(String($0))! } var left = [Int]() var equal = [Int]() var right = [Int]() func partition<T: Comparable>(values: [T], left: inout [T], equal: inout [T], right: inout [T]) { guard !values.isEmpty else { return } let pivot = values[0] for i in 0..<values.count { if values[i] < pivot { left.append(values[i]) } else if values[i] == pivot { equal.append(values[i]) } else { right.append(values[i]) } } } func printArrays(left: [Int], equal: [Int], right: [Int]) { for number in left { print(number, separator: " ", terminator: " ") } for number in equal { print(number, separator: " ", terminator: " ") } for number in right { print(number, separator: " ", terminator: " ") } } partition(values: array, left: &left, equal: &equal, right: &right) printArrays(left: left, equal: equal, right: right)
mit
fefcfac5b83ba8fbe255ba0536eb52e6
20.40678
97
0.528108
3.682216
false
false
false
false
mightydeveloper/swift
test/SILGen/decls.swift
10
5550
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | FileCheck %s // CHECK-LABEL: sil hidden @_TF5decls11void_returnFT_T_ // CHECK: = tuple // CHECK: return func void_return() { } // CHECK-LABEL: sil hidden @_TF5decls14typealias_declFT_T_ func typealias_decl() { typealias a = Int } // CHECK-LABEL: sil hidden @_TF5decls15simple_patternsFT_T_ func simple_patterns() { _ = 4 var _ : Int } // CHECK-LABEL: sil hidden @_TF5decls13named_patternFT_Si func named_pattern() -> Int { var local_var : Int = 4 var defaulted_var : Int // Defaults to zero initialization return local_var + defaulted_var } func MRV() -> (Int, Float, (), Double) {} // CHECK-LABEL: sil hidden @_TF5decls14tuple_patternsFT_T_ func tuple_patterns() { var (a, b) : (Int, Float) // CHECK: [[AADDR1:%[0-9]+]] = alloc_box $Int // CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[AADDR1]]#1 // CHECK: [[BADDR1:%[0-9]+]] = alloc_box $Float // CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[BADDR1]]#1 var (c, d) = (a, b) // CHECK: [[CADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[DADDR:%[0-9]+]] = alloc_box $Float // CHECK: copy_addr [[AADDR]] to [initialization] [[CADDR]]#1 // CHECK: copy_addr [[BADDR]] to [initialization] [[DADDR]]#1 // CHECK: [[EADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[FADDR:%[0-9]+]] = alloc_box $Float // CHECK: [[GADDR:%[0-9]+]] = alloc_box $() // CHECK: [[HADDR:%[0-9]+]] = alloc_box $Double // CHECK: [[EFGH:%[0-9]+]] = apply // CHECK: [[E:%[0-9]+]] = tuple_extract {{.*}}, 0 // CHECK: [[F:%[0-9]+]] = tuple_extract {{.*}}, 1 // CHECK: [[G:%[0-9]+]] = tuple_extract {{.*}}, 2 // CHECK: [[H:%[0-9]+]] = tuple_extract {{.*}}, 3 // CHECK: store [[E]] to [[EADDR]] // CHECK: store [[F]] to [[FADDR]] // CHECK: store [[H]] to [[HADDR]] var (e,f,g,h) : (Int, Float, (), Double) = MRV() // CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int // CHECK-NOT: alloc_box $Float // CHECK: copy_addr [[AADDR]] to [initialization] [[IADDR]]#1 // CHECK: [[B:%[0-9]+]] = load [[BADDR]] // CHECK-NOT: store [[B]] var (i,_) = (a, b) // CHECK: [[JADDR:%[0-9]+]] = alloc_box $Int // CHECK-NOT: alloc_box $Float // CHECK: [[KADDR:%[0-9]+]] = alloc_box $() // CHECK-NOT: alloc_box $Double // CHECK: [[J_K_:%[0-9]+]] = apply // CHECK: [[J:%[0-9]+]] = tuple_extract {{.*}}, 0 // CHECK: [[K:%[0-9]+]] = tuple_extract {{.*}}, 2 // CHECK: store [[J]] to [[JADDR]] var (j,_,k,_) : (Int, Float, (), Double) = MRV() } // CHECK-LABEL: sil hidden @_TF5decls16simple_arguments // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %0 to [[X]] // CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %1 to [[Y]] func simple_arguments(x: Int, y: Int) -> Int { var x = x var y = y return x+y } // CHECK-LABEL: sil hidden @_TF5decls17curried_arguments // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %1 to [[X]] // CHECK: [[Y:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %0 to [[Y]] func curried_arguments(x: Int)(y: Int) -> Int { var x = x var y = y return x+y } // CHECK-LABEL: sil hidden @_TF5decls14tuple_argument // CHECK: bb0(%0 : $Int, %1 : $Float): // CHECK: [[UNIT:%[0-9]+]] = tuple () // CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $()) // CHECK: [[XADDR:%[0-9]+]] = alloc_box $(Int, Float, ()) func tuple_argument(x: (Int, Float, ())) { var x = x } // CHECK-LABEL: sil hidden @_TF5decls14inout_argument // CHECK: bb0(%0 : $*Int, %1 : $Int): // CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box $Int // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int // CHECK: copy_addr [[YADDR]]#1 to [[X_LOCAL]]#1 func inout_argument(inout x: Int, y: Int) { var y = y x = y } var global = 42 // CHECK-LABEL: sil hidden @_TF5decls16load_from_global func load_from_global() -> Int { return global // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: [[VALUE:%[0-9]+]] = load [[ADDR]] // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden @_TF5decls15store_to_global func store_to_global(x: Int) { var x = x global = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: copy_addr [[XADDR]]#1 to [[ADDR]] // CHECK: return } struct S { var x:Int // CHECK-LABEL: sil hidden @_TFV5decls1SCf init() { x = 219 } init(a:Int, b:Int) { x = a + b } } // CHECK-LABEL: StructWithStaticVar.init // rdar://15821990 - Don't emit default value for static var in instance init() struct StructWithStaticVar { static var a : String = "" var b : String = "" init() { } } // <rdar://problem/17405715> lazy property crashes silgen of implicit memberwise initializer // CHECK-LABEL: // decls.StructWithLazyField.init // CHECK-NEXT: sil hidden @_TFV5decls19StructWithLazyFieldC{{.*}} : $@convention(thin) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField { struct StructWithLazyField { lazy var once : Int = 42 let someProp = "Some value" } // <rdar://problem/21057425> Crash while compiling attached test-app. // CHECK-LABEL: // decls.test21057425 func test21057425() { var x = 0, y: Int = 0 } func useImplicitDecls() { _ = StructWithLazyField(once: 55) }
apache-2.0
3a14c01d494fcd560f5de9e791003197
29.163043
166
0.574595
2.913386
false
false
false
false
WhatsTaste/WTImagePickerController
Vendor/Views/WTAlbumDetailsCell.swift
1
4439
// // WTAlbumDetailsCell.swift // WTImagePickerController // // Created by Jayce on 2017/2/8. // Copyright © 2017年 WhatsTaste. All rights reserved. // import UIKit class WTAlbumDetailsCell: UICollectionViewCell, UIGestureRecognizerDelegate { override init(frame: CGRect) { super.init(frame: frame) // Initialization code contentView.clipsToBounds = true contentView.addSubview(contentImageView) contentView.addSubview(indicatorView) contentView.addConstraint(NSLayoutConstraint.init(item: contentImageView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: contentView, attribute: .right, relatedBy: .equal, toItem: contentImageView, attribute: .right, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: contentImageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: contentImageView, attribute: .bottom, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: contentImageView, attribute: .right, relatedBy: .equal, toItem: indicatorView, attribute: .right, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: contentImageView, attribute: .bottom, relatedBy: .equal, toItem: indicatorView, attribute: .bottom, multiplier: 1, constant: 0)) indicatorView.addConstraint(NSLayoutConstraint.init(item: indicatorView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)) indicatorView.addConstraint(NSLayoutConstraint.init(item: indicatorView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() contentImageView.image = nil indicatorView.isSelected = false } override var tintColor: UIColor! { didSet { indicatorView.tintColor = tintColor } } // MARK: - UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { let location = touch.location(in: gestureRecognizer.view!) return indicatorView.frame.contains(location) } // MARK: - Private @objc private func selectAction(_ sender: UITapGestureRecognizer) { selectHandler?() } // MARK: - Properties public var representedAssetIdentifier: String! public var thumbnailImage: UIImage! { didSet { contentImageView.image = thumbnailImage contentImageView.highlightedImage = contentImageView.image?.applyingColor(UIColor.black.withAlphaComponent(0.5)) } } var selectHandler: (() -> Void)? var checked = false { didSet { self.indicatorView.isSelected = checked } } lazy public private(set) var contentImageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = UIColor(white: 0, alpha: 0.05) imageView.contentMode = .scaleAspectFill imageView.isUserInteractionEnabled = true let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(selectAction(_:))) gestureRecognizer.delegate = self imageView.addGestureRecognizer(gestureRecognizer) return imageView }() lazy private var indicatorView: WTSelectionIndicatorView = { let view = WTSelectionIndicatorView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.clear view.tintColor = self.tintColor view.isUserInteractionEnabled = false view.style = .checkmark view.insets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) return view }() }
mit
0af4b115777998f778b3d12e3baa9ecf
41.653846
192
0.688909
5.293556
false
false
false
false
faraxnak/PayWandBasicElements
Pods/EasyPeasy/EasyPeasy/Context.swift
6
2602
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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 os(iOS) import UIKit /** Struct that from an `UITraitCollection` object populates some helper properties easing access to device and size class information */ public struct Context { /// `true` if the current device is an iPad public let isPad: Bool /// `true` if the current device is an iPhone public let isPhone: Bool /// `true` if both horizontal and vertical size classes are `.Compact` public let isHorizontalVerticalCompact: Bool /// `true` if horizontal size class is `.Compact` public let isHorizontalCompact: Bool /// `true` if vertical size class is `.Compact` public let isVerticalCompact: Bool /// `true` if both horizontal and vertical size classes are `.Regular` public let isHorizontalVerticalRegular: Bool /// `true` if horizontal size class is `.Regular` public let isHorizontalRegular: Bool /// `true` if vertical size class is `.Regular` public let isVerticalRegular: Bool /** Given an `UITraitCollection` object populates device and size class helper properties */ init(with traitCollection: UITraitCollection) { // Device info self.isPad = traitCollection.userInterfaceIdiom == .pad self.isPhone = UIDevice.current.userInterfaceIdiom == .phone // Compact size classes self.isHorizontalCompact = traitCollection.horizontalSizeClass == .compact self.isVerticalCompact = traitCollection.verticalSizeClass == .compact self.isHorizontalVerticalCompact = traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .compact // Regular size classes self.isVerticalRegular = traitCollection.verticalSizeClass == .regular self.isHorizontalRegular = traitCollection.horizontalSizeClass == .regular self.isHorizontalVerticalRegular = traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular } } #endif
mit
9d7c526c466fea6a2a3e2c52360725bf
37.835821
139
0.702921
5.299389
false
false
false
false
Alamofire/Alamofire
Tests/RequestInterceptorTests.swift
2
23118
// // RequestInterceptorTests.swift // // Copyright (c) 2019 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. // @testable import Alamofire import Foundation import XCTest private struct MockError: Error {} private struct RetryError: Error {} // MARK: - final class RetryResultTestCase: BaseTestCase { func testRetryRequiredProperty() { // Given, When let retry = RetryResult.retry let retryWithDelay = RetryResult.retryWithDelay(1.0) let doNotRetry = RetryResult.doNotRetry let doNotRetryWithError = RetryResult.doNotRetryWithError(MockError()) // Then XCTAssertTrue(retry.retryRequired) XCTAssertTrue(retryWithDelay.retryRequired) XCTAssertFalse(doNotRetry.retryRequired) XCTAssertFalse(doNotRetryWithError.retryRequired) } func testDelayProperty() { // Given, When let retry = RetryResult.retry let retryWithDelay = RetryResult.retryWithDelay(1.0) let doNotRetry = RetryResult.doNotRetry let doNotRetryWithError = RetryResult.doNotRetryWithError(MockError()) // Then XCTAssertEqual(retry.delay, nil) XCTAssertEqual(retryWithDelay.delay, 1.0) XCTAssertEqual(doNotRetry.delay, nil) XCTAssertEqual(doNotRetryWithError.delay, nil) } func testErrorProperty() { // Given, When let retry = RetryResult.retry let retryWithDelay = RetryResult.retryWithDelay(1.0) let doNotRetry = RetryResult.doNotRetry let doNotRetryWithError = RetryResult.doNotRetryWithError(MockError()) // Then XCTAssertNil(retry.error) XCTAssertNil(retryWithDelay.error) XCTAssertNil(doNotRetry.error) XCTAssertTrue(doNotRetryWithError.error is MockError) } } // MARK: - final class AdapterTestCase: BaseTestCase { func testThatAdapterCallsAdaptHandler() { // Given let urlRequest = Endpoint().urlRequest let session = Session() var adapted = false let adapter = Adapter { request, _, completion in adapted = true completion(.success(request)) } var result: Result<URLRequest, Error>! // When adapter.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(adapted) XCTAssertTrue(result.isSuccess) } func testThatAdapterCallsAdaptHandlerWithStateAPI() { // Given class StateCaptureAdapter: Adapter { private(set) var urlRequest: URLRequest? private(set) var state: RequestAdapterState? override func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) { self.urlRequest = urlRequest self.state = state super.adapt(urlRequest, using: state, completion: completion) } } let urlRequest = Endpoint().urlRequest let session = Session() let requestID = UUID() var adapted = false let adapter = StateCaptureAdapter { urlRequest, _, completion in adapted = true completion(.success(urlRequest)) } let state = RequestAdapterState(requestID: requestID, session: session) var result: Result<URLRequest, Error>! // When adapter.adapt(urlRequest, using: state) { result = $0 } // Then XCTAssertTrue(adapted) XCTAssertTrue(result.isSuccess) XCTAssertEqual(adapter.urlRequest, urlRequest) XCTAssertEqual(adapter.state?.requestID, requestID) XCTAssertEqual(adapter.state?.session.session, session.session) } func testThatAdapterCallsRequestRetrierDefaultImplementationInProtocolExtension() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) let adapter = Adapter { request, _, completion in completion(.success(request)) } var result: RetryResult! // When adapter.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, .doNotRetry) } func testThatAdapterCanBeImplementedAsynchronously() { // Given let urlRequest = Endpoint().urlRequest let session = Session() var adapted = false let adapter = Adapter { request, _, completion in adapted = true DispatchQueue.main.async { completion(.success(request)) } } var result: Result<URLRequest, Error>! let completesExpectation = expectation(description: "adapter completes") // When adapter.adapt(urlRequest, for: session) { result = $0 completesExpectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertTrue(adapted) XCTAssertTrue(result.isSuccess) } } // MARK: - final class RetrierTestCase: BaseTestCase { func testThatRetrierCallsRetryHandler() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) var retried = false let retrier = Retrier { _, _, _, completion in retried = true completion(.retry) } var result: RetryResult! // When retrier.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertTrue(retried) XCTAssertEqual(result, .retry) } func testThatRetrierCallsRequestAdapterDefaultImplementationInProtocolExtension() { // Given let urlRequest = Endpoint().urlRequest let session = Session() let retrier = Retrier { _, _, _, completion in completion(.retry) } var result: Result<URLRequest, Error>! // When retrier.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(result.isSuccess) } func testThatRetrierCanBeImplementedAsynchronously() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) var retried = false let retrier = Retrier { _, _, _, completion in retried = true DispatchQueue.main.async { completion(.retry) } } var result: RetryResult! let completesExpectation = expectation(description: "retrier completes") // When retrier.retry(request, for: session, dueTo: MockError()) { result = $0 completesExpectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertTrue(retried) XCTAssertEqual(result, .retry) } } // MARK: - final class InterceptorTests: BaseTestCase { func testAdaptHandlerAndRetryHandlerDefaultInitializer() { // Given let adaptHandler: AdaptHandler = { urlRequest, _, completion in completion(.success(urlRequest)) } let retryHandler: RetryHandler = { _, _, _, completion in completion(.doNotRetry) } // When let interceptor = Interceptor(adaptHandler: adaptHandler, retryHandler: retryHandler) // Then XCTAssertEqual(interceptor.adapters.count, 1) XCTAssertEqual(interceptor.retriers.count, 1) } func testAdapterAndRetrierDefaultInitializer() { // Given let adapter = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } let retrier = Retrier { _, _, _, completion in completion(.doNotRetry) } // When let interceptor = Interceptor(adapter: adapter, retrier: retrier) // Then XCTAssertEqual(interceptor.adapters.count, 1) XCTAssertEqual(interceptor.retriers.count, 1) } func testAdaptersAndRetriersDefaultInitializer() { // Given let adapter = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } let retrier = Retrier { _, _, _, completion in completion(.doNotRetry) } // When let interceptor = Interceptor(adapters: [adapter, adapter], retriers: [retrier, retrier]) // Then XCTAssertEqual(interceptor.adapters.count, 2) XCTAssertEqual(interceptor.retriers.count, 2) } func testThatInterceptorCanBeComposedOfMultipleRequestInterceptors() { // Given let adapter = Adapter { request, _, completion in completion(.success(request)) } let retrier = Retrier { _, _, _, completion in completion(.doNotRetry) } let inner = Interceptor(adapter: adapter, retrier: retrier) // When let interceptor = Interceptor(interceptors: [inner]) // Then XCTAssertEqual(interceptor.adapters.count, 1) XCTAssertEqual(interceptor.retriers.count, 1) } func testThatInterceptorCanAdaptRequestWithNoAdapters() { // Given let urlRequest = Endpoint().urlRequest let session = Session() let interceptor = Interceptor() var result: Result<URLRequest, Error>! // When interceptor.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(result.isSuccess) XCTAssertEqual(result.success, urlRequest) } func testThatInterceptorCanAdaptRequestWithOneAdapter() { // Given let urlRequest = Endpoint().urlRequest let session = Session() let adapter = Adapter { _, _, completion in completion(.failure(MockError())) } let interceptor = Interceptor(adapters: [adapter]) var result: Result<URLRequest, Error>! // When interceptor.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failure is MockError) } func testThatInterceptorCanAdaptRequestWithMultipleAdapters() { // Given let urlRequest = Endpoint().urlRequest let session = Session() let adapter1 = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } let adapter2 = Adapter { _, _, completion in completion(.failure(MockError())) } let interceptor = Interceptor(adapters: [adapter1, adapter2]) var result: Result<URLRequest, Error>! // When interceptor.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failure is MockError) } func testThatInterceptorCanAdaptRequestWithMultipleAdaptersUsingStateAPI() { // Given let urlRequest = Endpoint().urlRequest let session = Session() let adapter1 = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } let adapter2 = Adapter { _, _, completion in completion(.failure(MockError())) } let interceptor = Interceptor(adapters: [adapter1, adapter2]) let state = RequestAdapterState(requestID: UUID(), session: session) var result: Result<URLRequest, Error>! // When interceptor.adapt(urlRequest, using: state) { result = $0 } // Then XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failure is MockError) } func testThatInterceptorCanAdaptRequestAsynchronously() { // Given let urlRequest = Endpoint().urlRequest let session = Session() let adapter = Adapter { _, _, completion in DispatchQueue.main.async { completion(.failure(MockError())) } } let interceptor = Interceptor(adapters: [adapter]) var result: Result<URLRequest, Error>! let completesExpectation = expectation(description: "interceptor completes") // When interceptor.adapt(urlRequest, for: session) { result = $0 completesExpectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failure is MockError) } func testThatInterceptorCanRetryRequestWithNoRetriers() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) let interceptor = Interceptor() var result: RetryResult! // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, .doNotRetry) } func testThatInterceptorCanRetryRequestWithOneRetrier() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) let retrier = Retrier { _, _, _, completion in completion(.retry) } let interceptor = Interceptor(retriers: [retrier]) var result: RetryResult! // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, .retry) } func testThatInterceptorCanRetryRequestWithMultipleRetriers() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) let retrier1 = Retrier { _, _, _, completion in completion(.doNotRetry) } let retrier2 = Retrier { _, _, _, completion in completion(.retry) } let interceptor = Interceptor(retriers: [retrier1, retrier2]) var result: RetryResult! // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, .retry) } func testThatInterceptorCanRetryRequestAsynchronously() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) let retrier = Retrier { _, _, _, completion in DispatchQueue.main.async { completion(.retry) } } let interceptor = Interceptor(retriers: [retrier]) var result: RetryResult! let completesExpectation = expectation(description: "interceptor completes") // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 completesExpectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertEqual(result, .retry) } func testThatInterceptorStopsIteratingThroughPendingRetriersWithRetryResult() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) var retrier2Called = false let retrier1 = Retrier { _, _, _, completion in completion(.retry) } let retrier2 = Retrier { _, _, _, completion in retrier2Called = true; completion(.doNotRetry) } let interceptor = Interceptor(retriers: [retrier1, retrier2]) var result: RetryResult! // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, .retry) XCTAssertFalse(retrier2Called) } func testThatInterceptorStopsIteratingThroughPendingRetriersWithRetryWithDelayResult() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) var retrier2Called = false let retrier1 = Retrier { _, _, _, completion in completion(.retryWithDelay(1.0)) } let retrier2 = Retrier { _, _, _, completion in retrier2Called = true; completion(.doNotRetry) } let interceptor = Interceptor(retriers: [retrier1, retrier2]) var result: RetryResult! // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, .retryWithDelay(1.0)) XCTAssertEqual(result.delay, 1.0) XCTAssertFalse(retrier2Called) } func testThatInterceptorStopsIteratingThroughPendingRetriersWithDoNotRetryResult() { // Given let session = Session(startRequestsImmediately: false) let request = session.request(.default) var retrier2Called = false let retrier1 = Retrier { _, _, _, completion in completion(.doNotRetryWithError(RetryError())) } let retrier2 = Retrier { _, _, _, completion in retrier2Called = true; completion(.doNotRetry) } let interceptor = Interceptor(retriers: [retrier1, retrier2]) var result: RetryResult! // When interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } // Then XCTAssertEqual(result, RetryResult.doNotRetryWithError(RetryError())) XCTAssertTrue(result.error is RetryError) XCTAssertFalse(retrier2Called) } } // MARK: - Functional Tests final class InterceptorRequestTests: BaseTestCase { func testThatRetryPolicyRetriesRequestTimeout() { // Given let interceptor = InspectorInterceptor(RetryPolicy(retryLimit: 1, exponentialBackoffScale: 0.1)) let urlRequest = Endpoint.delay(1).modifying(\.timeout, to: 0.01) let expect = expectation(description: "request completed") // When let request = AF.request(urlRequest, interceptor: interceptor).response { _ in expect.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertEqual(request.tasks.count, 2, "There should be two tasks, one original, one retry.") XCTAssertEqual(interceptor.retryCalledCount, 2, "retry() should be called twice.") XCTAssertEqual(interceptor.retries, [.retryWithDelay(0.1), .doNotRetry], "RetryResults should retryWithDelay, doNotRetry") } } // MARK: - Static Accessors #if swift(>=5.5) final class StaticAccessorTests: BaseTestCase { func consumeRequestAdapter(_ requestAdapter: RequestAdapter) { _ = requestAdapter } func consumeRequestRetrier(_ requestRetrier: RequestRetrier) { _ = requestRetrier } func consumeRequestInterceptor(_ requestInterceptor: RequestInterceptor) { _ = requestInterceptor } func testThatAdapterCanBeCreatedStaticallyFromProtocol() { // Given, When, Then consumeRequestAdapter(.adapter { request, _, completion in completion(.success(request)) }) } func testThatRetrierCanBeCreatedStaticallyFromProtocol() { // Given, When, Then consumeRequestRetrier(.retrier { _, _, _, completion in completion(.doNotRetry) }) } func testThatInterceptorCanBeCreatedStaticallyFromProtocol() { // Given, When, Then consumeRequestInterceptor(.interceptor()) } func testThatRetryPolicyCanBeCreatedStaticallyFromProtocol() { // Given, When, Then consumeRequestInterceptor(.retryPolicy()) } func testThatConnectionLostRetryPolicyCanBeCreatedStaticallyFromProtocol() { // Given, When, Then consumeRequestInterceptor(.connectionLostRetryPolicy()) } } #endif // MARK: - Helpers /// Class which captures the output of any underlying `RequestInterceptor`. final class InspectorInterceptor<Interceptor: RequestInterceptor>: RequestInterceptor { var onAdaptation: ((Result<URLRequest, Error>) -> Void)? var onRetry: ((RetryResult) -> Void)? private(set) var adaptations: [Result<URLRequest, Error>] = [] private(set) var retries: [RetryResult] = [] /// Number of times `retry` was called. var retryCalledCount: Int { retries.count } let interceptor: Interceptor init(_ interceptor: Interceptor) { self.interceptor = interceptor } func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) { interceptor.adapt(urlRequest, for: session) { result in self.adaptations.append(result) completion(result) self.onAdaptation?(result) } } func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { interceptor.retry(request, for: session, dueTo: error) { result in self.retries.append(result) completion(result) self.onRetry?(result) } } } /// Retry a request once, allowing the second to succeed using the method path. final class SingleRetrier: RequestInterceptor { private var hasRetried = false func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) { if hasRetried { let method = urlRequest.method ?? .get let endpoint = Endpoint(path: .method(method), method: method, headers: urlRequest.headers) completion(.success(endpoint.urlRequest)) } else { completion(.success(urlRequest)) } } func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { completion(hasRetried ? .doNotRetry : .retry) hasRetried = true } } extension RetryResult: Equatable { public static func ==(lhs: RetryResult, rhs: RetryResult) -> Bool { switch (lhs, rhs) { case (.retry, .retry), (.doNotRetry, .doNotRetry), (.doNotRetryWithError, .doNotRetryWithError): return true case let (.retryWithDelay(leftDelay), .retryWithDelay(rightDelay)): return leftDelay == rightDelay default: return false } } }
mit
256f0b29962e482db60e12ad8bc20d40
31.745042
130
0.638291
5.20207
false
true
false
false
avito-tech/Marshroute
Marshroute/Sources/SettingUpStack/MarshrouteStack.swift
1
2224
import Foundation public struct MarshrouteStack { public let transitionIdGenerator: TransitionIdGenerator public let routerControllersProvider: RouterControllersProvider public let transitionsCoordinator: TransitionsCoordinator public let transitionsCoordinatorDelegateHolder: TransitionsCoordinatorDelegateHolder public let topViewControllerFinder: TopViewControllerFinder public let transitionsMarker: TransitionsMarker public let transitionsTracker: TransitionsTracker public let transitionsHandlersProvider: TransitionsHandlersProvider public let peekAndPopUtility: PeekAndPopUtility public let peekAndPopStateObservable: PeekAndPopStateObservable public let peekAndPopStateViewControllerObservable: PeekAndPopStateViewControllerObservable public init( transitionIdGenerator: TransitionIdGenerator, routerControllersProvider: RouterControllersProvider, transitionsCoordinator: TransitionsCoordinator, transitionsCoordinatorDelegateHolder: TransitionsCoordinatorDelegateHolder, topViewControllerFinder: TopViewControllerFinder, transitionsMarker: TransitionsMarker, transitionsTracker: TransitionsTracker, transitionsHandlersProvider: TransitionsHandlersProvider, peekAndPopUtility: PeekAndPopUtility, peekAndPopStateObservable: PeekAndPopStateObservable, peekAndPopStateViewControllerObservable: PeekAndPopStateViewControllerObservable) { self.transitionIdGenerator = transitionIdGenerator self.routerControllersProvider = routerControllersProvider self.transitionsCoordinator = transitionsCoordinator self.transitionsCoordinatorDelegateHolder = transitionsCoordinatorDelegateHolder self.topViewControllerFinder = topViewControllerFinder self.transitionsMarker = transitionsMarker self.transitionsTracker = transitionsTracker self.transitionsHandlersProvider = transitionsHandlersProvider self.peekAndPopUtility = peekAndPopUtility self.peekAndPopStateObservable = peekAndPopStateObservable self.peekAndPopStateViewControllerObservable = peekAndPopStateViewControllerObservable } }
mit
fcf5e5f50ae5451b5e46440c8b82338e
53.243902
95
0.816547
8.329588
false
false
false
false
1457792186/JWSwift
熊猫TV2/Pods/Alamofire/Source/SessionDelegate.swift
151
35406
// // SessionDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for handling all delegate callbacks for the underlying session. open class SessionDelegate: NSObject { // MARK: URLSessionDelegate Overrides /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? // MARK: URLSessionTaskDelegate Overrides /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and /// requires the caller to call the `completionHandler`. open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? // MARK: URLSessionDataDelegate Overrides /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)? // MARK: URLSessionDownloadDelegate Overrides /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: URLSessionStreamDelegate Overrides #if !os(watchOS) /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskReadClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskWriteClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskBetterRouteDiscovered = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { get { return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void } set { _streamTaskDidBecomeInputStream = newValue } } var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? #endif // MARK: Properties var retrier: RequestRetrier? weak var sessionManager: SessionManager? private var requests: [Int: Request] = [:] private let lock = NSLock() /// Access the task delegate for the specified task in a thread-safe manner. open subscript(task: URLSessionTask) -> Request? { get { lock.lock() ; defer { lock.unlock() } return requests[task.taskIdentifier] } set { lock.lock() ; defer { lock.unlock() } requests[task.taskIdentifier] = newValue } } // MARK: Lifecycle /// Initializes the `SessionDelegate` instance. /// /// - returns: The new `SessionDelegate` instance. public override init() { super.init() } // MARK: NSObject Overrides /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond /// to a specified message. /// /// - parameter selector: A selector that identifies a message. /// /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. open override func responds(to selector: Selector) -> Bool { #if !os(macOS) if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif #if !os(watchOS) if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { switch selector { case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): return streamTaskReadClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): return streamTaskWriteClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): return streamTaskBetterRouteDiscovered != nil case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): return streamTaskDidBecomeInputAndOutputStreams != nil default: break } } #endif switch selector { case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return type(of: self).instancesRespond(to: selector) } } } // MARK: - URLSessionDelegate extension SessionDelegate: URLSessionDelegate { /// Tells the delegate that the session has been invalidated. /// /// - parameter session: The session object that was invalidated. /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { sessionDidBecomeInvalidWithError?(session, error) } /// Requests credentials from the delegate in response to a session-level authentication request from the /// remote server. /// /// - parameter session: The session containing the task that requested authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } completionHandler(disposition, credential) } #if !os(macOS) /// Tells the delegate that all messages enqueued for a session have been delivered. /// /// - parameter session: The session that no longer has any outstanding requests. open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } #endif } // MARK: - URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Tells the delegate that the remote server requested an HTTP redirect. /// /// - parameter session: The session containing the task whose request resulted in a redirect. /// - parameter task: The task whose request resulted in a redirect. /// - parameter response: An object containing the server’s response to the original request. /// - parameter request: A URL request object filled out with the new location. /// - parameter completionHandler: A closure that your handler should call with either the value of the request /// parameter, a modified URL request object, or NULL to refuse the redirect and /// return the body of the redirect response. open func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /// Requests credentials from the delegate in response to an authentication request from the remote server. /// /// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task]?.delegate { delegate.urlSession( session, task: task, didReceive: challenge, completionHandler: completionHandler ) } else { urlSession(session, didReceive: challenge, completionHandler: completionHandler) } } /// Tells the delegate when a task requires a new request body stream to send to the remote server. /// /// - parameter session: The session containing the task that needs a new body stream. /// - parameter task: The task that needs a new body stream. /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. open func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task]?.delegate { delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) } } /// Periodically informs the delegate of the progress of sending body content to the server. /// /// - parameter session: The session containing the data task. /// - parameter task: The data task. /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. /// - parameter totalBytesSent: The total number of bytes sent so far. /// - parameter totalBytesExpectedToSend: The expected length of the body data. open func urlSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } #if !os(watchOS) /// Tells the delegate that the session finished collecting metrics for the task. /// /// - parameter session: The session collecting the metrics. /// - parameter task: The task whose metrics have been collected. /// - parameter metrics: The collected metrics. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) @objc(URLSession:task:didFinishCollectingMetrics:) open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { self[task]?.delegate.metrics = metrics } #endif /// Tells the delegate that the task finished transferring data. /// /// - parameter session: The session containing the task whose request finished transferring data. /// - parameter task: The task whose request finished transferring data. /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { /// Executed after it is determined that the request is not going to be retried let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in guard let strongSelf = self else { return } if let taskDidComplete = strongSelf.taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = strongSelf[task]?.delegate { delegate.urlSession(session, task: task, didCompleteWithError: error) } NotificationCenter.default.post( name: Notification.Name.Task.DidComplete, object: strongSelf, userInfo: [Notification.Key.Task: task] ) strongSelf[task] = nil } guard let request = self[task], let sessionManager = sessionManager else { completeTask(session, task, error) return } // Run all validations on the request before checking if an error occurred request.validations.forEach { $0() } // Determine whether an error has occurred var error: Error? = error if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil { error = taskDelegate.error } /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request /// should be retried. Otherwise, complete the task by notifying the task delegate. if let retrier = retrier, let error = error { retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, delay in guard shouldRetry else { completeTask(session, task, error) ; return } DispatchQueue.utility.after(delay) { [weak self] in guard let strongSelf = self else { return } let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false if retrySucceeded, let task = request.task { strongSelf[task] = request return } else { completeTask(session, task, error) } } } } else { completeTask(session, task, error) } } } // MARK: - URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { /// Tells the delegate that the data task received the initial reply (headers) from the server. /// /// - parameter session: The session containing the data task that received an initial reply. /// - parameter dataTask: The data task that received an initial reply. /// - parameter response: A URL response object populated with headers. /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a /// constant to indicate whether the transfer should continue as a data task or /// should become a download task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: URLSession.ResponseDisposition = .allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /// Tells the delegate that the data task was changed to a download task. /// /// - parameter session: The session containing the task that was replaced by a download task. /// - parameter dataTask: The data task that was replaced by a download task. /// - parameter downloadTask: The new download task that replaced the data task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) } } /// Tells the delegate that the data task has received some of the expected data. /// /// - parameter session: The session containing the data task that provided data. /// - parameter dataTask: The data task that provided data. /// - parameter data: A data object containing the transferred data. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession(session, dataTask: dataTask, didReceive: data) } } /// Asks the delegate whether the data (or upload) task should store the response in the cache. /// /// - parameter session: The session containing the data (or upload) task. /// - parameter dataTask: The data (or upload) task. /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current /// caching policy and the values of certain received headers, such as the Pragma /// and Cache-Control headers. /// - parameter completionHandler: A block that your handler must call, providing either the original proposed /// response, a modified version of that response, or NULL to prevent caching the /// response. If your delegate implements this method, it must call this completion /// handler; otherwise, your app leaks memory. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } } // MARK: - URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { /// Tells the delegate that a download task has finished downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that finished. /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either /// open the file for reading or move it to a permanent location in your app’s sandbox /// container directory before returning from this delegate method. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } } /// Periodically informs the delegate about the download’s progress. /// /// - parameter session: The session containing the download task. /// - parameter downloadTask: The download task. /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate /// method was called. /// - parameter totalBytesWritten: The total number of bytes transferred so far. /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length /// header. If this header was not provided, the value is /// `NSURLSessionTransferSizeUnknown`. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /// Tells the delegate that the download task has resumed downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the /// existing content, then this value is zero. Otherwise, this value is an /// integer representing the number of bytes on disk that do not need to be /// retrieved again. /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } } // MARK: - URLSessionStreamDelegate #if !os(watchOS) @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) extension SessionDelegate: URLSessionStreamDelegate { /// Tells the delegate that the read side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { streamTaskReadClosed?(session, streamTask) } /// Tells the delegate that the write side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { streamTaskWriteClosed?(session, streamTask) } /// Tells the delegate that the system has determined that a better route to the host is available. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { streamTaskBetterRouteDiscovered?(session, streamTask) } /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. /// - parameter inputStream: The new input stream. /// - parameter outputStream: The new output stream. open func urlSession( _ session: URLSession, streamTask: URLSessionStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) { streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) } } #endif
apache-2.0
612d82038f46c44407e36f8b9a5466fe
48.098474
182
0.674181
6.164026
false
false
false
false
HexagonalLoop/DelayTapButton
DelayTapButton/DelayTapButton.swift
1
1338
// // SafeTapButton.swift // // Created by Gaurav Keshre on 3/23/16. // Copyright © 2016 Gaurav Keshre. All rights reserved. // import Foundation import UIKit typealias TouchTouple = (Set<UITouch>, UIEvent?) @IBDesignable class DelayTapButton: UIButton { private var timer: NSTimer? @IBInspectable var waitTimeInterval: Float = 0.5 private var _waitTimeInterval: NSTimeInterval{ return NSTimeInterval(waitTimeInterval) } // MARK: - LifeCycle Methods /* ------------------------------------------------------------ */ deinit{ cleanUp() } // MARK: - Private Helper Methods /* ------------------------------------------------------------ */ func action(sender: NSTimer){ self.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } private func cleanUp(){ timer?.invalidate() timer = nil } // MARK: - Overriden Methods /* ------------------------------------------------------------ */ override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { timer?.invalidate() timer = nil timer = NSTimer.scheduledTimerWithTimeInterval(_waitTimeInterval, target: self, selector: "action:", userInfo: nil, repeats: false) self.highlighted = false } override func didMoveToSuperview() { cleanUp() } override func removeFromSuperview() { cleanUp() } }
mit
0e96e9cb2770661e037599c217a16ba5
21.283333
133
0.608078
4.369281
false
false
false
false
swiftix/swift.old
test/SILGen/closures.swift
2
21306
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | FileCheck %s import Swift var zero = 0 // <rdar://problem/15921334> // CHECK-LABEL: sil hidden @_TF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <A, R> () -> @owned @callee_owned (@out R, @in A) -> () { func return_local_generic_function_without_captures<A, R>() -> A -> R { func f(_: A) -> R { Builtin.int_trap() } // CHECK: [[FN:%.*]] = function_ref @_TFF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <τ_0_0, τ_0_1> (@out τ_0_1, @in τ_0_0) -> () // CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@out τ_0_1, @in τ_0_0) -> () // CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_owned (@out R, @in A) -> () return f } // CHECK-LABEL: sil hidden @_TF8closures17read_only_capture func read_only_capture(x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int func cap() -> Int { return x } return cap() // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures17read_only_capture.*]] : $@convention(thin) (@owned @box Int, @inout Int) -> Int // CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX]]#0, [[XBOX]]#1) // CHECK: release [[XBOX]]#0 // CHECK: return [[RET]] } // CHECK: sil shared @[[CAP_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int, [[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [[XADDR]] // CHECK: release [[XBOX]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures16write_to_capture func write_to_capture(x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int // CHECK: [[X2BOX:%[0-9]+]] = alloc_box $Int var x2 = x func scribble() { x2 = zero } scribble() // CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:_TFF8closures16write_to_capture.*]] : $@convention(thin) (@owned @box Int, @inout Int) -> () // CHECK: apply [[SCRIB]]([[X2BOX]]#0, [[X2BOX]]#1) // CHECK: [[RET:%[0-9]+]] = load [[X2BOX]]#1 // CHECK: release [[X2BOX]]#0 // CHECK: release [[XBOX]]#0 // CHECK: return [[RET]] return x2 } // CHECK: sil shared @[[SCRIB_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int, [[XADDR:%[0-9]+]] : $*Int): // CHECK: copy_addr {{%[0-9]+}} to [[XADDR]] // CHECK: release [[XBOX]] // CHECK: return // CHECK-LABEL: sil hidden @_TF8closures21multiple_closure_refs func multiple_closure_refs(x: Int) -> (() -> Int, () -> Int) { var x = x func cap() -> Int { return x } return (cap, cap) // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned @box Int, @inout Int) -> Int // CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned @box Int, @inout Int) -> Int // CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}}) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF8closures18capture_local_func func capture_local_func(x: Int) -> () -> () -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int func aleph() -> Int { return x } func beth() -> () -> Int { return aleph } // CHECK: [[BETH_REF:%[0-9]+]] = function_ref @[[BETH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_4bethfT_FT_Si]] : $@convention(thin) (@owned @box Int, @inout Int) -> @owned @callee_owned () -> Int // CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [[BETH_REF]]([[XBOX]]#0, [[XBOX]]#1) return beth // CHECK: release [[XBOX]]#0 // CHECK: return [[BETH_CLOSURE]] } // CHECK: sil shared @[[ALEPH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_5alephfT_Si]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int, [[XADDR:%[0-9]+]] : $*Int): // CHECK: sil shared @[[BETH_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int, [[XADDR:%[0-9]+]] : $*Int): // CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@owned @box Int, @inout Int) -> Int // CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [[ALEPH_REF]]([[XBOX]], [[XADDR]]) // CHECK: return [[ALEPH_CLOSURE]] // CHECK-LABEL: sil hidden @_TF8closures22anon_read_only_capture func anon_read_only_capture(x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int return ({ x })() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures22anon_read_only_capture.*]] : $@convention(thin) (@inout Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[XBOX]]#1) // -- cleanup // CHECK: release [[XBOX]]#0 // CHECK: return [[RET]] } // CHECK: sil shared @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [[XADDR]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures21small_closure_capture func small_closure_capture(x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int return { x }() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures21small_closure_capture.*]] : $@convention(thin) (@inout Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[XBOX]]#1) // -- cleanup // CHECK: release [[XBOX]]#0 // CHECK: return [[RET]] } // CHECK: sil shared @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [[XADDR]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures35small_closure_capture_with_argument func small_closure_capture_with_argument(x: Int) -> (y: Int) -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int return { x + $0 } // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @owned @box Int, @inout Int) -> Int // CHECK: retain [[XBOX]]#0 // CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [[ANON]]([[XBOX]]#0, [[XBOX]]#1) // -- return // CHECK: release [[XBOX]]#0 // CHECK: return [[ANON_CLOSURE_APP]] } // CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int, @owned @box Int, @inout Int) -> Int // CHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : $@box Int, [[XADDR:%[0-9]+]] : $*Int): // CHECK: [[PLUS:%[0-9]+]] = function_ref @_TZFsoi1pFTSiSi_Si{{.*}} // CHECK: [[LHS:%[0-9]+]] = load [[XADDR]] // CHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]]) // CHECK: release [[XBOX]] // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8closures24small_closure_no_capture func small_closure_no_capture() -> (y: Int) -> Int { // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures24small_closure_no_captureFT_FT1ySi_SiU_FSiSi]] : $@convention(thin) (Int) -> Int // CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_owned (Int) -> Int // CHECK: return [[ANON_THICK]] return { $0 } } // CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int // CHECK: bb0([[YARG:%[0-9]+]] : $Int): // CHECK-LABEL: sil hidden @_TF8closures17uncaptured_locals{{.*}} : func uncaptured_locals(x: Int) -> (Int, Int) { var x = x // -- locals without captures are stack-allocated // CHECK: bb0([[XARG:%[0-9]+]] : $Int): // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: store [[XARG]] to [[XADDR]] var y = zero // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int return (x, y) } class SomeClass { var x : Int = zero init() { x = { self.x }() // Closing over self. } } // Closures within destructors <rdar://problem/15883734> class SomeGenericClass<T> { deinit { var i: Int = zero // CHECK: [[C1REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout Int) -> Int // CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]#1) : $@convention(thin) (@inout Int) -> Int var x = { i + zero } () // CHECK: [[C2REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int // CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int var y = { zero } () // CHECK: [[C3REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <τ_0_0> () -> () // CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> () var z = { _ = T.self } () } // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout Int) -> Int // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <T> () -> () } // This is basically testing that the constraint system ranking // function conversions as worse than others, and therefore performs // the conversion within closures when possible. class SomeSpecificClass : SomeClass {} func takesSomeClassGenerator(fn : () -> SomeClass) {} func generateWithConstant(x : SomeSpecificClass) { takesSomeClassGenerator({ x }) } // CHECK-LABEL: sil shared @_TFF8closures20generateWithConstant // CHECK: bb0([[T0:%.*]] : $SomeSpecificClass): // CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $SomeSpecificClass to $SomeClass // CHECK-NEXT: return [[T1]] // Check the annoying case of capturing 'self' in a derived class 'init' // method. We allocate a mutable box to deal with 'self' potentially being // rebound by super.init, but 'self' is formally immutable and so is captured // by value. <rdar://problem/15599464> class Base {} class SelfCapturedInInit : Base { var foo : () -> SelfCapturedInInit // CHECK-LABEL: sil hidden @_TFC8closures18SelfCapturedInInitc{{.*}} : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit { // CHECK: [[VAL:%.*]] = load {{%.*}} : $*SelfCapturedInInit // CHECK: [[VAL:%.*]] = load {{%.*}} : $*SelfCapturedInInit // CHECK: [[VAL:%.*]] = load {{%.*}} : $*SelfCapturedInInit // CHECK: strong_retain [[VAL]] : $SelfCapturedInInit // CHECK: partial_apply {{%.*}}([[VAL]]) : $@convention(thin) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit override init() { super.init() foo = { self } } } func takeClosure(fn: () -> Int) -> Int { return fn() } class TestCaptureList { var x = zero func testUnowned() { let aLet = self takeClosure { aLet.x } takeClosure { [unowned aLet] in aLet.x } takeClosure { [weak aLet] in aLet!.x } var aVar = self takeClosure { aVar.x } takeClosure { [unowned aVar] in aVar.x } takeClosure { [weak aVar] in aVar!.x } takeClosure { self.x } takeClosure { [unowned self] in self.x } takeClosure { [weak self] in self!.x } takeClosure { [unowned newVal = TestCaptureList()] in newVal.x } takeClosure { [weak newVal = TestCaptureList()] in newVal!.x } } } class ClassWithIntProperty { final var x = 42 } func closeOverLetLValue() { let a : ClassWithIntProperty a = ClassWithIntProperty() takeClosure { a.x } } // The let property needs to be captured into a temporary stack slot so that it // is loadable even though we capture the value. // CHECK-LABEL: sil shared @_TFF8closures18closeOverLetLValueFT_T_U_FT_Si // CHECK: bb0(%0 : $ClassWithIntProperty): // CHECK-NEXT: [[TMP:%.*]] = alloc_stack $ClassWithIntProperty // let a // CHECK-NEXT: store %0 to [[TMP]]#1 : $*ClassWithIntProperty // CHECK-NEXT: {{.*}} = load [[TMP]]#1 : $*ClassWithIntProperty // CHECK-NEXT: {{.*}} = ref_element_addr {{.*}} : $ClassWithIntProperty, #ClassWithIntProperty.x // CHECK-NEXT: {{.*}} = load {{.*}} : $*Int // CHECK-NEXT: destroy_addr [[TMP]]#1 : $*ClassWithIntProperty // CHECK-NEXT: dealloc_stack %1#0 : $*@local_storage ClassWithIntProperty // CHECK-NEXT: return // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(@noescape fn : () -> Int) struct StructWithMutatingMethod { var x = 42 mutating func mutatingMethod() { // This should not capture the refcount of the self shadow. takesNoEscapeClosure { x = 42; return x } } } // Check that the address of self is passed in, but not the refcount pointer. // CHECK-LABEL: sil hidden @_TFV8closures24StructWithMutatingMethod14mutatingMethod // CHECK: bb0(%0 : $*StructWithMutatingMethod): // CHECK-NEXT: %1 = alloc_box $StructWithMutatingMethod // var self // users: %2, %5, %7, %8 // CHECK-NEXT: copy_addr %0 to [initialization] %1#1 : $*StructWithMutatingMethod // id: %2 // CHECK: [[CLOSURE:%[0-9]+]] = function_ref @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout StructWithMutatingMethod) -> Int // CHECK: partial_apply [[CLOSURE]](%1#1) : $@convention(thin) (@inout StructWithMutatingMethod) -> Int // Check that the closure body only takes the pointer. // CHECK-LABEL: sil shared @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout StructWithMutatingMethod) -> Int { // CHECK: bb0(%0 : $*StructWithMutatingMethod): class SuperBase { func boom() {} } class SuperSub : SuperBase { override func boom() {} // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1a // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1a // CHECK: = apply [[INNER]](%0) // CHECK: return func a() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1a // CHECK: [[CLASS_METHOD:%.*]] = class_method %0 : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]](%0) // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return func a1() { self.boom() super.boom() } a1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1b // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1b // CHECK: = apply [[INNER]](%0) // CHECK: return func b() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1b // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1b // CHECK: = apply [[INNER]](%0) // CHECK: return func b1() { // CHECK-LABEL: sil shared @_TFFFC8closures8SuperSub1b // CHECK: [[CLASS_METHOD:%.*]] = class_method %0 : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]](%0) // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[METHOD]]([[SUPER]]) // CHECK: return func b2() { self.boom() super.boom() } b2() } b1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1c // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1c // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func c() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1c // CHECK: [[CLASS_METHOD:%.*]] = class_method %0 : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]](%0) // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[METHOD]]([[SUPER]]) // CHECK: return let c1 = { () -> Void in self.boom() super.boom() } c1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1d // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1d // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func d() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1d // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1d // CHECK: = apply [[INNER]](%0) // CHECK: return let d1 = { () -> Void in // CHECK-LABEL: sil shared @_TFFFC8closures8SuperSub1d // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[METHOD]]([[SUPER]]) // CHECK: return func d2() { super.boom() } d2() } d1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1e // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1e // CHECK: = apply [[INNER]](%0) // CHECK: return func e() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1e // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1e // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func e1() { // CHECK-LABEL: sil shared @_TFFFC8closures8SuperSub1e // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[METHOD]]([[SUPER]]) // CHECK: return let e2 = { super.boom() } e2() } e1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1f // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1f // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func f() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1f // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1f // CHECK: = partial_apply [[INNER]](%0) // CHECK: return let f1 = { // CHECK-LABEL: sil shared [transparent] @_TFFFC8closures8SuperSub1f // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[METHOD]]([[SUPER]]) // CHECK: return nil ?? super.boom() } } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1g // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1g // CHECK: = apply [[INNER]](%0) // CHECK: return func g() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1g // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1g // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func g1() { // CHECK-LABEL: sil shared [transparent] @_TFFFC8closures8SuperSub1g // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boom // CHECK: = apply [[METHOD]]([[SUPER]]) // CHECK: return nil ?? super.boom() } g1() } } // CHECK-LABEL: sil hidden @_TFC8closures24UnownedSelfNestedCapture13nestedCapture{{.*}} : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> () // CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box $@sil_unowned UnownedSelfNestedCapture // CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_PARAM:%.*]] : // -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here. // -- strong +1, unowned +1 // CHECK: unowned_retain [[UNOWNED_SELF]] // CHECK: store [[UNOWNED_SELF]] to [[OUTER_SELF_CAPTURE]] // CHECK: [[UNOWNED_SELF:%.*]] = load [[OUTER_SELF_CAPTURE]] // -- strong +2, unowned +1 // CHECK: strong_retain_unowned [[UNOWNED_SELF]] // CHECK: [[SELF:%.*]] = unowned_to_ref [[UNOWNED_SELF]] // CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]] // -- strong +2, unowned +2 // CHECK: unowned_retain [[UNOWNED_SELF2]] // -- strong +1, unowned +2 // CHECK: strong_release [[SELF]] // -- closure takes unowned ownership // CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply {{%.*}}([[UNOWNED_SELF2]]) // -- call consumes closure // -- strong +1, unowned +1 // CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CLOSURE]] // CHECK: [[CONSUMED_RESULT:%.*]] = apply [[INNER_CLOSURE]]() // CHECK: strong_release [[CONSUMED_RESULT]] // -- releases unowned self in box // -- strong +1, unowned +0 // CHECK: strong_release [[OUTER_SELF_CAPTURE]] // -- strong +0, unowned +0 // CHECK: return // -- outer closure // -- strong +0, unowned +1 // CHECK-LABEL: sil shared @_TFFC8closures24UnownedSelfNestedCapture13nestedCapture // -- strong +0, unowned +2 // CHECK: unowned_retain [[CAPTURED_SELF:%.*]] : // -- closure takes ownership of unowned ref // CHECK: [[INNER_CLOSURE:%.*]] = partial_apply {{%.*}}([[CAPTURED_SELF]]) // -- strong +0, unowned +1 (claimed by closure) // CHECK: unowned_release [[CAPTURED_SELF]] // CHECK: return [[INNER_CLOSURE]] // -- inner closure // -- strong +0, unowned +1 // CHECK-LABEL: sil shared @_TFFFC8closures24UnownedSelfNestedCapture13nestedCapture // -- strong +1, unowned +1 // CHECK: strong_retain_unowned [[CAPTURED_SELF:%.*]] : // CHECK: [[SELF:%.*]] = unowned_to_ref [[CAPTURED_SELF]] // -- strong +1, unowned +0 (claimed by return) // CHECK: unowned_release [[CAPTURED_SELF]] // CHECK: return [[SELF]] class UnownedSelfNestedCapture { func nestedCapture() { {[unowned self] in { self } }()() } }
apache-2.0
e1a78ba1652bbeb953de85291d35b611
37.861314
207
0.597436
3.41775
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Observability/Sources/ObservabilityKit/Performance/PerformanceTracingService.swift
1
4060
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import Combine import Foundation import ToolKit final class PerformanceTracingService: PerformanceTracingServiceAPI { typealias CreateTrace = (TraceID, [String: String]) -> Trace? private let traces: Atomic<[TraceID: Trace]> private let createTrace: CreateTrace init( createTrace: @escaping CreateTrace, initialTraces: [TraceID: Trace] = [:], listenForClearTraces: @escaping PerformanceTracing.ListenForClearTraces ) { traces = Atomic(initialTraces) self.createTrace = createTrace listenForClearTraces { [traces] in traces.mutate { currentTraces in currentTraces = [:] } } } func begin(trace traceId: TraceID, properties: [String: String]?) { removeTrace(with: traceId) if let trace = createTrace(traceId, properties ?? [:]) { traces.mutate { traces in traces[traceId] = trace } } } func end(trace traceId: TraceID) { guard let trace = traces.value[traceId] else { return } trace.stop() removeTrace(with: traceId) } private func removeTrace(with traceId: TraceID) { traces.mutate { traces in traces.removeValue(forKey: traceId) } } } struct NamepaceTrace: Codable { let start: Tag.Reference let stop: Tag.Reference let id: String let context: [String: Tag.Reference] } public final class PerformanceTracingObserver: Session.Observer { unowned let app: AppProtocol private let service: PerformanceTracingServiceAPI private var bag: Set<AnyCancellable> = [] public init(app: AppProtocol, service: PerformanceTracingServiceAPI) { self.app = app self.service = service } public func start() { app.publisher(for: blockchain.app.configuration.performance.tracing, as: [NamepaceTrace?].self) .compactMap { result in result.value?.compacted() } .flatMap { [app, service] traces -> AnyPublisher<Session.Event, Never> in let starts = traces.map { (trace: NamepaceTrace) -> AnyPublisher<Session.Event, Never> in app.on(trace.start) .handleEvents( receiveOutput: { event in let properties = trace.context.reduce(into: [String: String]()) { properties, next in if let refContext: String? = try? event.reference.context[next.value].decode() { properties[next.key] = refContext } else if let context: String? = try? event.context[next.value].decode() { properties[next.key] = context } else if let state: String? = try? app.state.get(next.value) { properties[next.key] = state } else if let remoteConfig: String? = try? app.remoteConfiguration.get(next.value) { properties[next.key] = remoteConfig } } service.begin(trace: TraceID(trace.id), properties: properties) } ) .eraseToAnyPublisher() } let ends = traces.map { (trace: NamepaceTrace) -> AnyPublisher<Session.Event, Never> in app.on(trace.stop) .handleEvents(receiveOutput: { _ in service.end(trace: TraceID(trace.id)) }) .eraseToAnyPublisher() } return (starts + ends).merge().eraseToAnyPublisher() } .subscribe() .store(in: &bag) } public func stop() { bag.removeAll() } }
lgpl-3.0
9c92867512be6106fff7711f7d9e158c
36.238532
120
0.54373
5.086466
false
false
false
false
zhugejunwei/LeetCode
128. Longest Consecutive Sequence.swift
1
656
import Darwin // 68 ms func longestConsecutive(nums: [Int]) -> Int { var record = [Int:Int]() var result = 0 for num in nums { if record[num] == nil { let left = record[num - 1] let right = record[num + 1] let sum = (left ?? 0) + (right ?? 0) + 1 record[num] = sum result = max(result,sum) if left != nil { record[num - left!] = sum } if right != nil { record[num + right!] = sum } }else { continue } } return result }
mit
7ba3290db58c659596cbbacc8323f2f7
21.62069
52
0.393293
4.287582
false
false
false
false
stowy/LayoutKit
ExampleLayouts/HelloWorldAutoLayoutView.swift
5
2381
// Copyright 2016 LinkedIn Corp. // 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 /** A simple hello world layout that uses Auto Layout. Compare to HelloWorldLayout.swift */ open class HelloWorldAutoLayoutView: UIView { private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical) imageView.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) imageView.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical) imageView.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) imageView.image = UIImage(named: "earth.png") return imageView }() private lazy var label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Hello World!" return label }() public override init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) addSubview(label) let views: [String: UIView] = ["imageView": imageView, "label": label] var constraints = [NSLayoutConstraint]() constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-4-[imageView(==50)]-4-|", options: [], metrics: nil, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-4-[imageView(==50)]-4-[label]-8-|", options: [], metrics: nil, views: views)) constraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) NSLayoutConstraint.activate(constraints) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
92fd9985593afabfe652bc3747b27965
45.686275
170
0.713146
5.033827
false
false
false
false
abunur/quran-ios
UIKitExtension/UIView+Extension.swift
1
2986
// // UIView+Extension.swift // Quran // // Created by Mohamed Afifi on 10/30/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import UIKit extension UIView { public func findFirstResponder() -> UIView? { if isFirstResponder { return self } for subView in subviews { if let responder = subView.findFirstResponder() { return responder } } return nil } @discardableResult public func loadViewFrom(nibClass: UIView.Type) -> UIView { return loadViewFrom(nibName: String(describing: nibClass)) } @discardableResult public func loadViewFrom(nibName: String) -> UIView { let nib = UINib(nibName: nibName, bundle: nil) guard let contentView = nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Couldn't load '\(nibName).xib' as the first item should be a UIView subclass.") } contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": contentView])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": contentView])) return contentView } public func findSubview<T: UIView>(ofType type: T.Type) -> T? { // breadth-first search var queue = subviews while !queue.isEmpty { let subview = queue.removeFirst() if let subview = subview as? T { return subview } queue.append(contentsOf: subview.subviews) } return nil } public func findSubviews<T: UIView>(ofType type: T.Type) -> [T] { // breadth-first search var queue = subviews var result: [T] = [] while !queue.isEmpty { let subview = queue.removeFirst() if let subview = subview as? T { result.append(subview) } queue.append(contentsOf: subview.subviews) } return result } } extension UIView { public var circularRadius: CGFloat { return min(bounds.width, bounds.height) / 2 } }
gpl-3.0
719c904854f7283d96607c7997496252
33.72093
111
0.607837
4.747218
false
false
false
false
Cein-Markey/ios-guessinggame-app
Fingers/AppDelegate.swift
1
6088
// // AppDelegate.swift // Fingers // // Created by Cein Markey on 9/13/15. // Copyright © 2015 Cein Markey. 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.example.Fingers" 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("Fingers", 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
13d6f88467070becdd9deb90a3428a4b
53.837838
291
0.719238
5.886847
false
false
false
false
collegboi/DIT-Timetable-iOS
DIT-Timetable-V2/Applications/Help/HelpPageViewController.swift
1
3507
// // HelpPageViewController.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 18/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import UIKit class HelpPageViewController: UIPageViewController { // Some hard-coded data for our walkthrough screens var pageHeaders = [String]() // make the status bar white (light content) override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide the navigation bar on the this view controller self.navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Show the navigation bar on other view controllers self.navigationController?.setNavigationBarHidden(false, animated: animated) } override func viewDidLoad() { super.viewDidLoad() //print(values) pageHeaders.append("https://timothybarnard.org/images/help/dit_timetable_help.png") pageHeaders.append("https://timothybarnard.org/images/help/login_help.png") pageHeaders.append("https://timothybarnard.org/images/help/notifications_help.png") pageHeaders.append("https://timothybarnard.org/images/help/edit_class_help.png") pageHeaders.append("https://timothybarnard.org/images/help/refresh_classes.png") // this class is the page view controller's data source itself self.dataSource = self // create the first walkthrough vc if let startWalkthroughVC = self.viewControllerAtIndex(0) { setViewControllers([startWalkthroughVC], direction: .forward, animated: true, completion: nil) } } // MARK: - Navigate func nextPageWithIndex(_ index: Int) { if let nextWalkthroughVC = self.viewControllerAtIndex( index+1 ) { setViewControllers([nextWalkthroughVC], direction: .forward, animated: true, completion: nil) } } func viewControllerAtIndex(_ index: Int) -> HelpViewController? { if index == NSNotFound || index < 0 || index >= self.pageHeaders.count { return nil } // create a new walkthrough view controller and assing appropriate date if let helpViewController = storyboard?.instantiateViewController(withIdentifier: "HelpViewController") as? HelpViewController { helpViewController.imageURL = pageHeaders[index] helpViewController.index = index return helpViewController } return nil } } extension HelpPageViewController : UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var index = (viewController as! HelpViewController).index index += 1 return self.viewControllerAtIndex(index) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var index = (viewController as! HelpViewController).index index -= 1 return self.viewControllerAtIndex(index) } } extension HelpPageViewController { }
mit
f9c1612018bb317a088088ef9bd202a6
34.414141
149
0.673702
5.478125
false
false
false
false
pvbaleeiro/movie-aholic
movieaholic/movieaholic/api-http/manager/APIManager.swift
1
2412
// // APIManager.swift // movieaholic // // Created by Victor Baleeiro on 22/09/17. // Copyright © 2017 Victor Baleeiro. All rights reserved. // import UIKit import Foundation import Alamofire import AlamofireObjectMapper import ObjectMapper //------------------------------------------------------------------------------------------------------------- // MARK: Constantes / Enums //------------------------------------------------------------------------------------------------------------- public enum Response<T> { case onSuccess(T) case onError(T) case onNoConnection() } class APIManager { static let sharedInstance = APIManager() //------------------------------------------------------------------------------------------------------------- // MARK: Main //------------------------------------------------------------------------------------------------------------- func customRequest(httpMethod: HTTPMethod, url: URLConvertible, parameters: [String: Any]?, headers: HTTPHeaders, completion: @escaping (_ apiResponse: APIResponse)->()) { //Loga a url chamada LogUtil.log(title: "Url chamada", forClass: String(describing: APIManager.self), method: #function, line: #line, description: String(describing: url)) //Obtem status da conexão let httpResponse = APIResponse() httpResponse.connected = ConnectionUtil.isConnected() //Verifica se está conectado if (httpResponse.connected) { //Tenta realizar o request Alamofire.request(url, method: httpMethod, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in switch response.result { case .success: httpResponse.objectFromServer = response.result.value httpResponse.httpCode = (response.response?.statusCode)! break case .failure(let error): httpResponse.objectFromServer = error httpResponse.httpCode = (response.response?.statusCode)! break } completion(httpResponse) } } else { completion(httpResponse) } } }
mit
02f43da1bd056b42c6dacdd957b62ed0
36.061538
175
0.478207
6.224806
false
false
false
false
dvxiaofan/Pro-Swift-Learning
Part-03/02-Closures.playground/Contents.swift
1
460
//: Playground - noun: a place where people can play import UIKit let printGreeting = { print("hello xiaofan") } printGreeting() let copyGreeting = printGreeting copyGreeting() func createIncrementer() -> () -> Void { var counter = 0 return { counter += 1 print(counter) } } let incrementer = createIncrementer() incrementer() incrementer() let incrementerCopy = incrementer incrementerCopy() incrementer()
mit
de4d5fc913eca3e1d832639323a19fb3
10.5
52
0.663043
4.259259
false
false
false
false
herveperoteau/TracktionProto1
TracktionProto1/TrackRealTimeViewController.swift
1
3492
// // TrackRealTimeViewController.swift // TracktionProto1 // // Created by Hervé PEROTEAU on 29/12/2015. // Copyright © 2015 Hervé PEROTEAU. All rights reserved. // import UIKit import WatchConnectivity class TrackRealTimeViewController: UIViewController { @IBOutlet weak var lbTrackId: UILabel! @IBOutlet weak var lbTimeStamp: UILabel! @IBOutlet weak var lbAccelerationX: UILabel! @IBOutlet weak var sliderAccelerationX: UISlider! @IBOutlet weak var lbAccelerationY: UILabel! @IBOutlet weak var sliderAccelerationY: UISlider! @IBOutlet weak var lbAccelerationZ: UILabel! @IBOutlet weak var sliderAccelerationZ: UISlider! @IBOutlet weak var lbStatus: UILabel! override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.registerForWKNotifications(); } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.unregisterForWKNotifications() } func setupUI() { self.lbTrackId.text = "xxxx" self.lbTimeStamp.text = "xxxxxxxxxxxxxxxx" self.setAccelerationXValue(0) self.setAccelerationYValue(0) self.setAccelerationZValue(0) self.updateStatusUI() } func updateStatusUI() { if let session = WatchConnectivityManager.sharedInstance.session { if !session.paired { self.lbStatus.text = "Need paired with your watch !" } else if !session.watchAppInstalled { self.lbStatus.text = "Install app on your watch !" } else { self.lbStatus.text = "Waiting tracking on Watch ..." } } else { self.lbStatus.text = "WatchApp not supported" } } func refreshWithTrackDataItem(item: TrackDataItem) { if (item.info == infoEndSession) { lbStatus.text = "Tracking \(item.trackStartSession) ended." return; } lbStatus.text = "Tracking \(item.trackStartSession) ..." lbTrackId.text = String(item.trackId) lbTimeStamp.text = String(item.timeStamp) setAccelerationXValue(item.accelerationX) setAccelerationYValue(item.accelerationY) setAccelerationZValue(item.accelerationZ) } func setAccelerationXValue(value: Double) { lbAccelerationX.text = NSString(format: "%.2f", value) as String sliderAccelerationX.value = Float(value) } func setAccelerationYValue(value: Double) { lbAccelerationY.text = NSString(format: "%.2f", value) as String sliderAccelerationY.value = Float(value) } func setAccelerationZValue(value: Double) { lbAccelerationZ.text = NSString(format: "%.2f", value) as String sliderAccelerationZ.value = Float(value) } func registerForWKNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "handlerWCdidReceiveUserInfo:", name:NotificationWCdidReceiveUserInfo, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "handlerWCsessionWatchStateDidChange:", name:NotificationWCsessionWatchStateDidChange, object: nil) } func unregisterForWKNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationWCdidReceiveMessage, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationWCsessionWatchStateDidChange, object: nil) } func handlerWCdidReceiveUserInfo(notification: NSNotification){ if let trackItem = notification.object as? TrackDataItem { refreshWithTrackDataItem(trackItem) } } func handlerWCsessionWatchStateDidChange(notification: NSNotification){ updateStatusUI() } }
mit
31a597f37b5bf51321657c5b45e34865
27.834711
120
0.762683
3.911435
false
false
false
false
felipedemetrius/AppSwift3
AppSwift3/TaskDetailViewController.swift
1
11336
// // TaskDetailViewController.swift // AppSwift3 // // Created by Felipe Silva on 2/14/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import UIKit import Kingfisher /// The sections of the Table View enum Sections : Int { case TaskDetail = 0 case Comments = 1 } /// Responsible for controlling the task detail screen class TaskDetailViewController: UIViewController { @IBOutlet weak var imageCover: UIImageView! @IBOutlet weak var constraintHeader: NSLayoutConstraint! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicatorCover: UIActivityIndicatorView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var labelMessageResults: UILabel! @IBOutlet weak var btnFavoriteTask: UIButton! @IBOutlet weak var contraintBtnFavoriteTask: NSLayoutConstraint! @IBOutlet weak var contraintBtnFavoriteWidth: NSLayoutConstraint! /// Maximum value for the cover image size (One-third the screen size) fileprivate var maxHeaderSize : CGFloat! /// Minimum value for the cover image size fileprivate var minHeaderSize : CGFloat = 50 /// Maximum value for the button star size fileprivate var maxBtnSize : CGFloat = 90 /// Minimum value for the button star size fileprivate var minBtnSize : CGFloat = 50 /// ViewModel for this ViewController var viewModel: TaskDetailViewModel? { didSet { observerViewModel() } } /// Controls UI components for user feedback private var isLoadingDataSource = false { didSet{ if isLoadingDataSource { activityIndicator.startAnimating() labelMessageResults.isHidden = true tableView.separatorStyle = UITableViewCellSeparatorStyle.none btnFavoriteTask.isHidden = true } else { activityIndicator.stopAnimating() if viewModel?.task == nil { labelMessageResults.isHidden = false btnFavoriteTask.isHidden = true tableView.separatorStyle = UITableViewCellSeparatorStyle.none activityIndicatorCover.stopAnimating() } else { tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine btnFavoriteTask.isHidden = false self.setHeader() } } tableView.reloadData() } } /// The cell types for section TaskDetail enum CellTypesTaskDetail : Int { case Actions = 0 case Description = 1 case Address = 2 } override func viewDidLoad() { super.viewDidLoad() observerViewModel() setViewController() setTableView() } private func setHeader(){ imageCover.kf.setImage(with: URL(string: (viewModel?.task.value?.urlPhoto ?? "")), placeholder: nil, options: nil, progressBlock: nil) { [weak self] image in self?.activityIndicatorCover.stopAnimating() } } private func setViewController(){ maxHeaderSize = view.bounds.height / 3 constraintHeader.constant = view.bounds.height / 3 if let topItem = navigationController?.navigationBar.topItem { topItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil) } btnFavoriteTask.layer.borderWidth = 1 btnFavoriteTask.layer.borderColor = UIColor.black.cgColor btnFavoriteTask.contentMode = .scaleAspectFill } fileprivate func observerViewModel(){ if !isViewLoaded { return } guard let viewModel = viewModel else { return } viewModel.isLoadingDatasource.bindAndFire { [unowned self] in self.isLoadingDataSource = $0 } viewModel.title.bindAndFire { [unowned self] in self.title = $0 } } private func setTableView(){ tableView.register(UINib(nibName: "ActionsTaskDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "ActionsTaskDetailTableViewCell") tableView.register(UINib(nibName: "DescriptionTaskDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "DescriptionTaskDetailTableViewCell") tableView.register(UINib(nibName: "AddressTaskDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "AddressTaskDetailTableViewCell") tableView.register(UINib(nibName: "CommentsTaskDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "CommentsTaskDetailTableViewCell") tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 600 tableView.sectionHeaderHeight = 0 tableView.sectionFooterHeight = 0 tableView.contentInset = UIEdgeInsetsMake(-1.0, 0.0, 0.0, 0.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// Favorites button: does nothing @IBAction func favoriteTask(_ sender: UIButton) { viewModel?.favoriteTask() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension TaskDetailViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let task = viewModel?.task.value else {return UITableViewCell()} if indexPath.section == Sections.TaskDetail.rawValue { switch indexPath.row { case CellTypesTaskDetail.Actions.rawValue: return getActionsTaskCell() case CellTypesTaskDetail.Description.rawValue: return getDescriptionTaskCell() case CellTypesTaskDetail.Address.rawValue: return getAddressTaskCell(task: task) default: return UITableViewCell() } } else if indexPath.section == Sections.Comments.rawValue { guard let comment = task.comments?[indexPath.row] else {return UITableViewCell()} return getCommentCell(comment: comment) } return UITableViewCell() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Sections.TaskDetail.rawValue: return 3 default: return viewModel?.task.value?.comments?.count ?? 0 } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let yPos = -scrollView.contentOffset.y let newSizeForHeader = constraintHeader.constant + yPos if newSizeForHeader > maxHeaderSize { constraintHeader.constant = maxHeaderSize } else if newSizeForHeader < minHeaderSize { constraintHeader.constant = minHeaderSize } else { constraintHeader.constant = newSizeForHeader } let newSizeForBtn = contraintBtnFavoriteTask.constant + yPos if newSizeForBtn > maxBtnSize { contraintBtnFavoriteTask.constant = maxBtnSize contraintBtnFavoriteWidth.constant = maxBtnSize } else if newSizeForBtn < minBtnSize { contraintBtnFavoriteTask.constant = minBtnSize contraintBtnFavoriteWidth.constant = minBtnSize } else { contraintBtnFavoriteTask.constant = newSizeForBtn contraintBtnFavoriteWidth.constant = newSizeForBtn } btnFavoriteTask.layer.cornerRadius = contraintBtnFavoriteWidth.constant / 2 btnFavoriteTask.layer.masksToBounds = true view.layoutIfNeeded() } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == Sections.Comments.rawValue { if let commentsCount = viewModel?.task.value?.comments, commentsCount.count > 0 { return "Comentários" } } else { return viewModel?.task.value?.title } return nil } } extension TaskDetailViewController { /// Get the cell with action buttons /// - returns: ActionsTaskDetailTableViewCell internal func getActionsTaskCell()-> ActionsTaskDetailTableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "ActionsTaskDetailTableViewCell") as! ActionsTaskDetailTableViewCell let viewModel = ActionsTaskDetailModel() cell.viewModel = viewModel return cell } /// Get the cell with a description of task /// - returns: DescriptionTaskDetailTableViewCell internal func getDescriptionTaskCell()-> DescriptionTaskDetailTableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "DescriptionTaskDetailTableViewCell") as! DescriptionTaskDetailTableViewCell cell.label.text = viewModel?.task.value?.text return cell } /// Get the cell with a map and a pin with the task coordinates. /// - parameter task: An TaskModel to set cell. /// - returns: AddressTaskDetailTableViewCell internal func getAddressTaskCell(task: TaskModel)-> AddressTaskDetailTableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "AddressTaskDetailTableViewCell") as! AddressTaskDetailTableViewCell let viewModel = AddressTaskDetailModel(task: task) cell.viewModel = viewModel cell.configure() return cell } /// Get the cell with the data of a comment /// - parameter comment: An CommentModel to set cell. /// - returns: CommentsTaskDetailTableViewCell internal func getCommentCell(comment : CommentModel) ->CommentsTaskDetailTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CommentsTaskDetailTableViewCell") as! CommentsTaskDetailTableViewCell let viewModel = CommentsTaskDetailModel(comment: comment) cell.viewModel = viewModel cell.configure() return cell } }
mit
0d8d3d8ed28d758cdd54a9e0892d4957
32.140351
165
0.628639
6.193443
false
false
false
false
vector-im/vector-ios
Riot/Modules/SetPinCode/EnterPinCode/EnterPinCodeCoordinator.swift
1
2872
// File created from ScreenTemplate // $ createScreen.sh SetPinCode/EnterPinCode EnterPinCode /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class EnterPinCodeCoordinator: EnterPinCodeCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession? private var enterPinCodeViewModel: EnterPinCodeViewModelType private let enterPinCodeViewController: EnterPinCodeViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: EnterPinCodeCoordinatorDelegate? // MARK: - Setup init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences = .shared) { self.session = session let enterPinCodeViewModel = EnterPinCodeViewModel(session: self.session, viewMode: viewMode, pinCodePreferences: pinCodePreferences) let enterPinCodeViewController = EnterPinCodeViewController.instantiate(with: enterPinCodeViewModel) self.enterPinCodeViewModel = enterPinCodeViewModel self.enterPinCodeViewController = enterPinCodeViewController } // MARK: - Public methods func start() { self.enterPinCodeViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.enterPinCodeViewController } } // MARK: - EnterPinCodeViewModelCoordinatorDelegate extension EnterPinCodeCoordinator: EnterPinCodeViewModelCoordinatorDelegate { func enterPinCodeViewModelDidComplete(_ viewModel: EnterPinCodeViewModelType) { self.delegate?.enterPinCodeCoordinatorDidComplete(self) } func enterPinCodeViewModelDidCompleteWithReset(_ viewModel: EnterPinCodeViewModelType, dueToTooManyErrors: Bool) { self.delegate?.enterPinCodeCoordinatorDidCompleteWithReset(self, dueToTooManyErrors: dueToTooManyErrors) } func enterPinCodeViewModel(_ viewModel: EnterPinCodeViewModelType, didCompleteWithPin pin: String) { self.delegate?.enterPinCodeCoordinator(self, didCompleteWithPin: pin) } func enterPinCodeViewModelDidCancel(_ viewModel: EnterPinCodeViewModelType) { self.delegate?.enterPinCodeCoordinatorDidCancel(self) } }
apache-2.0
4a001955c0c9e8a1f12040821f5fd0db
35.35443
140
0.749304
6.071882
false
false
false
false
joalbright/Relax
APIs/FoursquareAPI.swift
1
19028
// // FoursquareAPI.swift // Relax // // Created by Jo Albright on 1/12/16. // Copyright (c) 2016 Jo Albright. All rights reserved. // import Foundation // Documentation : https://developer.foursquare.com private let _fs = FoursquareAPI() open class FoursquareAPI: API { open override class func session() -> FoursquareAPI { return _fs } open override func start() { baseURL = "https://api.foursquare.com/v2/" authURL = "https://foursquare.com/oauth2/" authTokenKey = "Foursquare" authBasic = [ "client_id" : FOURSQUARE_CLIENT_ID, "client_secret" : FOURSQUARE_CLIENT_SECRET, "access_token" : "ACCESS_TOKEN", "v" : "20160112" ] } open override func loginDetails() -> (auth: Endpoint, authCode: Endpoint) { var auth = Endpoints.auth.endpoint auth.parameters = [ "client_id" : FOURSQUARE_CLIENT_ID, "response_type" : "code", "redirect_uri" : "https://code.jo2.co" ] var authCode = Endpoints.authCode.endpoint authCode.parameters = [ "client_id" : FOURSQUARE_CLIENT_ID, "client_secret" : FOURSQUARE_CLIENT_SECRET, "redirect_uri" : "https://code.jo2.co", "grant_type" : "authorization_code" ] return (auth, authCode) } public enum Endpoints: String { // Auth case auth case authCode // Users case users case usersRequests case usersSearch case usersCheckins case usersFriends case usersLists case usersMayorships case usersPhotos case usersTastes case usersVenueHistory case usersVenueLikes case usersApprove case usersDeny case usersSetPings case usersUnfriend case usersUpdate // Venues /// Get venue by :venue_id case venues /// Add new venue case venuesAdd /// case venuesCategories /// Explore suggested venues using "near" or "ll" case venuesExplore case venuesManaged /// Search all venues using "near" or "ll" case venuesSearch case venuesSuggestedCompletion case venuesTimeSeries case venuesTrending case venuesEvents case venuesHereNow case venuesHours case venuesLikes case venuesLinks case venuesListed case venuesMenu case venuesNextVenues case venuesPhotos case venuesSimilar case venuesStats case venuesTips case venuesClaim case venuesDislike case venuesFlag case venuesLike case venuesProposeEdit case venuesSetRole case venuesSetSingleLocation // Venue Groups case venueGroups case venueGroupsAdd case venueGroupsDelete case venueGroupsList case venueGroupsTimeSeries case venueGroupsAddVenue case venueGroupsEdit case venueGroupsRemoveVenue case venueGroupsUpdate // Checkins case checkins case checkinsAdd case checkinsRecent case checkinsResolve case checkinsLikes case checkinsAddComment case checkinsAddPost case checkinsDeleteComment case checkinsLike // Tips case tips case tipsAdd case tipsLikes case tipsListed case tipsSaves case tipsFlag case tipsLike case tipsUnmark // Lists case lists case listsAdd case listsFollowers case listsItems case listsSaves case listsSuggestPhoto case listsSuggestTip case listsSuggestVenues case listsAddItem case listsDeleteItem case listsFollow case listsMoveItem case listsShare case listsUnfollow case listsUpdate case listsUpdateItem // Updates case updates case updatesNotifications case updatesMarkNotificationsRead // Photos case photos case photosAdd // Settings case settings case settingsAll case settingsSet // Specials case specials case specialsAdd case specialsList case specialsSearch case specialsFlag // Events case events case eventsCategories case eventsSearch case eventsAdd // Pages case pagesAdd case pagesManaging case pagesAccess case pagesSimilar case pagesTimeSeries case pagesVenues case pagesFollow // Page Updates case pageUpdates case pageUpdatesAdd case pageUpdatesList case pageUpdatesDelete case pageUpdatesLike // Multi case multiGET case multiPOST public var endpoint: Endpoint { return _endpoints[self]! } var _endpoints: [Endpoints:Endpoint] { return [ // Auth .auth : Endpoint(path: "authenticate", requiredParameters: ["client_id","response_type","redirect_uri"]), .authCode : Endpoint(path: "access_token", requiredParameters: ["client_id","client_secret","grant_type","redirect_uri","code"]), // Users .users : Endpoint(path: "users/:user_id", requiresUser: true), .usersRequests : Endpoint(path: "users/requests", requiresUser: true), .usersSearch : Endpoint(path: "users/search", requiresUser: true), .usersCheckins : Endpoint(path: "users/:user_id/checkins", requiresUser: true), .usersFriends : Endpoint(path: "users/:user_id/friends", requiresUser: true), .usersLists : Endpoint(path: "users/:user_id/lists", requiresUser: true), .usersMayorships : Endpoint(path: "users/:user_id/mayorships", requiresUser: true), .usersPhotos : Endpoint(path: "users/:user_id/photos", requiresUser: true), .usersTastes : Endpoint(path: "users/:user_id/tastes", requiresUser: true), .usersVenueHistory : Endpoint(path: "users/:user_id/venuehistory", requiresUser: true), .usersVenueLikes : Endpoint(path: "users/:user_id/venuelikes", requiresUser: true), .usersApprove : Endpoint(path: "users/:user_id/approve", method: .POST, requiresUser: true), .usersDeny : Endpoint(path: "users/:user_id/deny", method: .POST, requiresUser: true), .usersSetPings : Endpoint(path: "users/:user_id/setpings", method: .POST, requiredParameters: ["value"], requiresUser: true), .usersUnfriend : Endpoint(path: "users/:user_id/unfriend", method: .POST, requiresUser: true), .usersUpdate : Endpoint(path: "users/self/update", method: .POST, requiresUser: true), // Venues .venues : Endpoint(path: "venues/:venue_id"), .venuesAdd : Endpoint(path: "venues/add", method: .POST, requiredParameters: ["name"], requiresUser: true), .venuesCategories : Endpoint(path: "venues/categories"), .venuesExplore : Endpoint(path: "venues/explore", requiredParameters: ["ll,near"]), .venuesManaged : Endpoint(path: "venues/managed", requiresUser: true), .venuesSearch : Endpoint(path: "venues/search", requiredParameters: ["ll,near"]), .venuesSuggestedCompletion : Endpoint(path: "venues/suggestcompletion", requiredParameters: ["ll,near","query"]), .venuesTimeSeries : Endpoint(path: "venues/timeseries", requiresUser: true), .venuesTrending : Endpoint(path: "venues/trending", requiredParameters: ["ll"]), .venuesEvents : Endpoint(path: "venues/:venue_id/events"), .venuesHereNow : Endpoint(path: "venues/:venue_id/herenow", requiresUser: true), .venuesHours : Endpoint(path: "venues/:venue_id/hours"), .venuesLikes : Endpoint(path: "venues/:venue_id/likes"), .venuesLinks : Endpoint(path: "venues/:venue_id/links"), .venuesListed : Endpoint(path: "venues/:venue_id/listed"), .venuesMenu : Endpoint(path: "venues/:venue_id/menu"), .venuesNextVenues : Endpoint(path: "venues/:venue_id/nextvenues"), .venuesPhotos : Endpoint(path: "venues/:venue_id/photos"), .venuesSimilar : Endpoint(path: "venues/:venue_id/similar", requiresUser: true), .venuesStats : Endpoint(path: "venues/:venue_id/stats", requiresUser: true), .venuesTips : Endpoint(path: "venues/:venue_id/tips"), .venuesClaim : Endpoint(path: "venues/:venue_id/claim", method: .POST, requiresUser: true), .venuesDislike : Endpoint(path: "venues/:venue_id/dislike", method: .POST, requiresUser: true), .venuesFlag : Endpoint(path: "venues/:venue_id/flag", method: .POST, requiredParameters: ["problem"], requiresUser: true), .venuesLike : Endpoint(path: "venues/:venue_id/like", method: .POST, requiresUser: true), .venuesProposeEdit : Endpoint(path: "venues/:venue_id/proposeedit", method: .POST, requiresUser: true), .venuesSetRole : Endpoint(path: "venues/:venue_id/setrole", method: .POST, requiresUser: true), .venuesSetSingleLocation : Endpoint(path: "venues/:venue_id/setsinglelocation", requiresUser: true), // Venue Groups .venueGroups : Endpoint(path: "venuegroups/:group_id", requiresUser: true), .venueGroupsAdd : Endpoint(path: "venuegroups/add", method: .POST, requiredParameters: ["name"], requiresUser: true), .venueGroupsDelete : Endpoint(path: "venuegroups/:group_id/delete", method: .POST, requiresUser: true), .venueGroupsList : Endpoint(path: "venuegroups/list", requiresUser: true), .venueGroupsTimeSeries : Endpoint(path: "venuegroups/:group_id/timeseries", requiredParameters: ["startAt"], requiresUser: true), .venueGroupsAddVenue : Endpoint(path: "venuegroups/:group_id/addvenue", method: .POST, requiredParameters: ["venueId"], requiresUser: true), .venueGroupsEdit : Endpoint(path: "venuegroups/:group_id/edit", method: .POST, requiresUser: true), .venueGroupsRemoveVenue : Endpoint(path: "venuegroups/:group_id/removevenue", method: .POST, requiredParameters: ["venueId"], requiresUser: true), .venueGroupsUpdate : Endpoint(path: "venuegroups/:group_id/update", method: .POST, requiresUser: true), // Checkins .checkins : Endpoint(path: "checkins/:checkin_id", requiresUser: true), .checkinsAdd : Endpoint(path: "checkins/add", method: .POST, requiredParameters: ["venueId"], requiresUser: true), .checkinsRecent : Endpoint(path: "checkins/recent", requiresUser: true), .checkinsResolve : Endpoint(path: "checkins/resolve", requiredParameters: ["shortId"], requiresUser: true), .checkinsLikes : Endpoint(path: "checkins/:checkin_id/likes"), .checkinsAddComment : Endpoint(path: "checkins/:checkin_id/addcomment", method: .POST, requiresUser: true), .checkinsAddPost : Endpoint(path: "checkins/:checkin_id/addpost", method: .POST, requiresUser: true), .checkinsDeleteComment : Endpoint(path: "checkins/:checkin_id/deletecomment", method: .POST, requiresUser: true), .checkinsLike : Endpoint(path: "checkins/:checkin_id/like", method: .POST, requiresUser: true), // Tips .tips : Endpoint(path: "tips/:tip_id"), .tipsAdd : Endpoint(path: "tips/add", method: .POST, requiredParameters: ["venueId","text"], requiresUser: true), .tipsLikes : Endpoint(path: "tips/:tip_id/likes"), .tipsListed : Endpoint(path: "tips/:tip_id/listed"), .tipsSaves : Endpoint(path: "tips/:tip_id/saves"), .tipsFlag : Endpoint(path: "tips/:tip_id/flag", method: .POST, requiredParameters: ["problem"], requiresUser: true), .tipsLike : Endpoint(path: "tips/:tip_id/like", method: .POST, requiresUser: true), .tipsUnmark : Endpoint(path: "tips/:tip_id/unmark", method: .POST, requiresUser: true), // Lists .lists : Endpoint(path: "lists/:list_id"), .listsAdd : Endpoint(path: "lists/add", method: .POST, requiredParameters: ["name"], requiresUser: true), .listsFollowers : Endpoint(path: "lists/:list_id/followers"), .listsItems : Endpoint(path: "lists/:list_id/:item_id", requiresUser: true), .listsSaves : Endpoint(path: "lists/:list_id/saves"), .listsSuggestPhoto : Endpoint(path: "lists/:list_id/suggestphoto", requiredParameters: ["itemId"], requiresUser: true), .listsSuggestTip : Endpoint(path: "lists/:list_id/suggesttip", requiredParameters: ["itemId"], requiresUser: true), .listsSuggestVenues : Endpoint(path: "lists/:list_id/suggestvenues", requiresUser: true), .listsAddItem : Endpoint(path: "lists/:list_id/additem", method: .POST, requiredParameters: ["venueId,tipId,itemId"], requiresUser: true), .listsDeleteItem : Endpoint(path: "lists/:list_id/deleteitem", method: .POST, requiredParameters: ["venueId,tipId,itemId"], requiresUser: true), .listsFollow : Endpoint(path: "lists/:list_id/follow", method: .POST, requiresUser: true), .listsMoveItem : Endpoint(path: "lists/:list_id/moveitem", method: .POST, requiredParameters: ["itemId","beforeId,afterId"], requiresUser: true), .listsShare : Endpoint(path: "lists/:list_id/share", method: .POST, requiresUser: true), .listsUnfollow : Endpoint(path: "lists/:list_id/unfollow", method: .POST, requiresUser: true), .listsUpdate : Endpoint(path: "lists/:list_id/update", method: .POST, requiresUser: true), .listsUpdateItem : Endpoint(path: "lists/:list_id/updateitem", method: .POST, requiredParameters: ["itemId"], requiresUser: true), // Updates .updates : Endpoint(path: "updates/:update_id", requiresUser: true), .updatesNotifications : Endpoint(path: "updates/notifications", requiresUser: true), .updatesMarkNotificationsRead : Endpoint(path: "updates/marknotificationsread", method: .POST, requiredParameters: ["highWatermark"], requiresUser: true), // Photos .photos : Endpoint(path: "photos/:photo_id", requiresUser: true), .photosAdd : Endpoint(path: "photos/add", method: .POST, requiresUser: true), // Settings .settings : Endpoint(path: "settings/:setting_id", requiresUser: true), .settingsAll : Endpoint(path: "settings/all", requiresUser: true), .settingsSet : Endpoint(path: "settings/:setting_id/set", method: .POST, requiredParameters: ["value"], requiresUser: true), // Specials .specials : Endpoint(path: "specials/:special_id", requiredParameters: ["venueId"]), .specialsAdd : Endpoint(path: "specials/add", method: .POST, requiredParameters: ["text","type"], requiresUser: true), .specialsList : Endpoint(path: "specials/list", requiresUser: true), .specialsSearch : Endpoint(path: "specials/search", requiredParameters: ["ll"]), .specialsFlag : Endpoint(path: "specials/:special_id/flag", method: .POST, requiredParameters: ["venueId","problem"], requiresUser: true), // Events .events : Endpoint(path: "events/:event_id", requiresUser: true), .eventsCategories : Endpoint(path: "events/categories"), .eventsSearch : Endpoint(path: "events/search", requiredParameters: ["domain","eventId,participantId"]), .eventsAdd : Endpoint(path: "events/add", method: .POST, requiresUser: true), // Pages .pagesAdd : Endpoint(path: "pages/add", method: .POST, requiredParameters: ["name"], requiresUser: true), .pagesManaging : Endpoint(path: "pages/managing", requiresUser: true), .pagesAccess : Endpoint(path: "pages/:user_id/access", requiresUser: true), .pagesSimilar : Endpoint(path: "pages/:user_id/similar", requiresUser: true), .pagesTimeSeries : Endpoint(path: "pages/:page_id/timeseries", requiredParameters: ["startAt"], requiresUser: true), .pagesVenues : Endpoint(path: "pages/:page_id/venues"), .pagesFollow : Endpoint(path: "pages/:user_id/follow", method: .POST, requiresUser: true), // Page Updates .pageUpdates : Endpoint(path: "pageupdates/:update_id", requiresUser: true), .pageUpdatesAdd : Endpoint(path: "pageupdates/add", method: .POST, requiredParameters: ["pageId"], requiresUser: true), .pageUpdatesList : Endpoint(path: "pageupdates/list", requiresUser: true), .pageUpdatesDelete : Endpoint(path: "pageupdates/:update_id/delete", method: .POST, requiresUser: true), .pageUpdatesLike : Endpoint(path: "pageupdates/:update_id/like", method: .POST, requiresUser: true), // Multi .multiGET : Endpoint(path: "multi", requiredParameters: ["requests"]), .multiPOST : Endpoint(path: "multi", method: .POST, requiredParameters: ["requests"]) ] } } }
mit
68316b81d01b4f03c2e72f7c8e9c6bac
45.184466
170
0.576361
4.891517
false
false
false
false
between40and2/XALG
frameworks/Framework-XALG/Graph/Algo/SSSP/XALG_Algo_Graph_Dijkstra.swift
1
1553
// // XALG_Algo_Graph_Dijkstra.swift // XALG // // Created by Juguang Xiao on 17/04/2017. // import Swift // https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm class XALG_Algo_Graph_Dijkstra<G : XALG_ADT_Graph_Weighted> : XALG_Algo_Graph_SSSP<G>{ // typealias Vertex = UIView typealias Distance = Float typealias VertexIdentifierType = String // re-defined, overriding the superclass's private var pq : XALG_Rep_PriorityQueue__Heap<VertexType>! override init() { super.init() let sort = { (v0 :VertexType, v1:VertexType) -> Bool in return self.distance_[v0]! < self.distance_[v1]! } pq = XALG_Rep_PriorityQueue__Heap<VertexType>(sort : sort) } var processedVertex_ = Set<VertexType>() override func run() throws { guard let g = graph else { throw XALG_Error_Graph_Algo.graphAbsent } initializeSingleSource() g.vertex_.forEach{ pq.enqueue($0) } while let u = pq.dequeue() { processedVertex_.insert(u) for (v, e) in g.adjecentVertexEdgeTuple_(forVertex: u) { if processedVertex_.contains(v) { continue} let e_w = e as! G.EdgeType_Weighted let w = g.weight(onEdge: e_w) relax(from: u, to: v, w: w) // processedVertex_.insert(v) } } } }
mit
3f875ee77b259c45d7215e60406d2395
24.883333
86
0.526722
4.130319
false
false
false
false
blinksh/blink
Blink/Commands/ssh/Helpers.swift
1
3142
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Foundation public typealias Argv = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>? extension Argv { static func build(_ args: [String]) -> (argc: Int32, argv: Self, buff: UnsafeMutablePointer<Int8>?) { let argc = args.count let cArgsSize = args.reduce(argc) { $0 + $1.utf8.count } // Store arguments in contiguous memory. guard let argsBuffer = calloc(cArgsSize, MemoryLayout<Int8>.size)?.assumingMemoryBound(to: Int8.self) else { return (argc: 0, argv: nil, buff: nil) } let argv = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: argc) var currentArgsPosition = argsBuffer args.enumerated().forEach { i, arg in let len = strlen(arg) strncpy(currentArgsPosition, arg, len) argv[i] = currentArgsPosition currentArgsPosition = currentArgsPosition.advanced(by: len + 1) } return (argc: Int32(argc), argv: argv, buff: argsBuffer) } static func build(_ args: String ...) -> (argc: Int32, argv: Self, buff: UnsafeMutablePointer<Int8>?) { build(args) } func args(count: Int32) -> [String] { guard let argv = self else { return [] } var res: [String] = [] for i in 0..<count { guard let cStr = argv[Int(i)] else { res.append("") continue } res.append(String(cString: cStr)) } return res } } struct CommandError: Error { let message: String } func tty() -> TermDevice { let session = Unmanaged<MCPSession>.fromOpaque(thread_context).takeUnretainedValue() return session.device } func awaitRunLoop(_ runLoop: RunLoop) { let timer = Timer(timeInterval: TimeInterval(INT_MAX), repeats: true) { _ in print("timer") } runLoop.add(timer, forMode: .default) CFRunLoopRun() } func awake(runLoop: RunLoop) { let cfRunLoop = runLoop.getCFRunLoop() CFRunLoopStop(cfRunLoop) }
gpl-3.0
5852f82f7faf4ba344b81f8a523265bf
28.364486
105
0.649586
4.12336
false
false
false
false
LuckyResistor/FontToBytes
FontToBytes/Converter8x8Fixed.swift
1
5902
// // Lucky Resistor's Font to Byte // --------------------------------------------------------------------------- // (c)2015 by Lucky Resistor. See LICENSE for details. // // 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 2 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, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // import Cocoa /// A simple converter which converts 8x8 pixel fonts /// /// Starting from the top-left 8x8 block, it converts each block from /// left to right, from top to down. /// /// Each 8x8 block is converted into 8 bytes, where the left bit is the /// highest bit. /// /// Example: /// ..XXXX.. -> 0x3c /// .XX..XX. -> 0x66 /// .XX..XX. -> 0x66 /// ..XXXXX. -> 0x3e /// .....XX. -> 0x06 /// .....XX. -> 0x06 /// .XX..XX. -> 0x66 /// ..XXXX.. -> 0x3c /// ........ -> 0x00 /// /// This char will result in the byte sequence: 0x3c, 0x66, 0x66, ... /// class Converter8x8Fixed: ModeConverter { /// The direction of the conversion /// enum Direction { case TopDown ///< Each character from top to bottom. case LeftRight ///< Each character from left to right. } /// The direction for the conversion /// private var direction: Direction /// Create a new fixed 8x8 converter /// init(direction: Direction) { self.direction = direction } private func checkImage(inputImage: InputImage) throws { guard inputImage.height >= 8 else { throw ConverterError(summary: "Image Too Small", details: "The height of the image has to be minimum 8 pixel.") } guard inputImage.width >= 8 else { throw ConverterError(summary: "Image Too Small", details: "The width of the image has to be minimum 8 pixel.") } guard (inputImage.height % 8) == 0 else { throw ConverterError(summary: "Odd Image Height", details: "The height of the image has to be a multiple of 8 pixel.") } guard (inputImage.width % 8) == 0 else { throw ConverterError(summary: "Odd Image Width", details: "The width of the image has to be a multiple of 8 pixel.") } guard inputImage.width <= 2048 && inputImage.height <= 2048 else { throw ConverterError(summary: "Image Too Large", details: "The no image dimension must be greater than 2048.") } } func convertImage(inputImage: InputImage, byteWriter: ByteWriter) throws { try checkImage(inputImage); byteWriter.begin() byteWriter.beginArray("font") var characterCount = 0 for y in 0..<(inputImage.height/8) { for x in 0..<(inputImage.width/8) { for row in 0...7 { var byte: UInt8 = 0 for bit in 0...7 { byte <<= 1 switch self.direction { case .TopDown: if inputImage.isPixelSet(x: x*8+bit, y: y*8+row) { byte |= 1 } case .LeftRight: if inputImage.isPixelSet(x: x*8+row, y: y*8+bit) { byte |= 1 } } } byteWriter.writeByte(byte) } byteWriter.addComment(String(format: "Character 0x%02x (%d)", arguments: [characterCount, characterCount])) characterCount++ } } byteWriter.endArray() byteWriter.end() } func createCharacterImages(inputImage: InputImage) throws -> [UnicodeScalar: NSImage] { try checkImage(inputImage); var result = [UnicodeScalar: NSImage]() var characterIndex = 0 for cy in 0..<(inputImage.height/8) { for cx in 0..<(inputImage.width/8) { let pixelSize = 64 let characterImage = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 8*pixelSize, pixelsHigh: 8*pixelSize, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)! let gc = NSGraphicsContext(bitmapImageRep: characterImage)! let context = gc.CGContext CGContextSetFillColorWithColor(context, NSColor.whiteColor().CGColor) CGContextFillRect(context, NSRect(x: 0.0, y: 0.0, width: 8.0*CGFloat(pixelSize), height: 8.0*CGFloat(pixelSize))) CGContextSetFillColorWithColor(context, NSColor.blackColor().CGColor) for y in 0...7 { for x in 0...7 { if inputImage.isPixelSet(x: cx*8+x, y: cy*8+y) { CGContextFillRect(context, NSRect(x: x*pixelSize, y: (7-y)*pixelSize, width: pixelSize, height: pixelSize)) } } } let image = NSImage(size: NSSize(width: 8.0*CGFloat(pixelSize), height: 8.0*CGFloat(pixelSize))) image.addRepresentation(characterImage) result[UnicodeScalar(characterIndex+0x20)] = image characterIndex++ } } return result; } }
gpl-2.0
62f4b36ebaa12adb4b110a45104cf91a
38.610738
274
0.564216
4.647244
false
false
false
false
tannernelson/uribeacon
Source/UriBeacon.swift
1
5391
import GoogleUriBeacon import UIKit public protocol DiscoveryDelegate { func scanner(scanner: Scanner, discoveredUri: Uri) func scanner(scanner: Scanner, lostUri: Uri) } func log(message: String) { println("[UriBeacon] \(message)") } public class Uri: NSObject { //public methods public init(uriBeacon: UBUriBeacon) { self.uri = "\(uriBeacon.URI)" } public var uri: String public var title = "" public var detail = "" //webview to receive metadata var metadataReceived: (()->())? var metadataWebview: UIWebView? public func getMetadata(done: ()->()) { self.title = self.uri self.detail = "Tap to open" Uri.getMetadata(self.uri, done: { (title, detail) -> () in if let title = title { self.title = title } if let detail = detail { self.detail = detail } done() }) } public class func getMetadata(uri: String, done: (title: String?, detail: String?) -> ()) { if let url = NSURL(string: "http://narwhal.mtag.io/v1/metadata?url=\(uri)") { let request = NSMutableURLRequest(URL: url) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, error in var title: String? var detail: String? if data != nil { var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary if let titleString = json.objectForKey("title") as? String { if titleString != "" { title = titleString } } if let detailString = json.objectForKey("description") as? String { if detailString != "" { detail = detailString } } } done(title: title, detail: detail) }) } else { done(title: nil, detail: nil) } } //private methods var importance: Int = 0 func matchesBeacon(uriBeacon: UBUriBeacon) -> Bool { return self.uri == "\(uriBeacon.URI)" } } public class Scanner { var delegate: DiscoveryDelegate public init(delegate: DiscoveryDelegate) { self.delegate = delegate } var uriBeaconScanner = UBUriBeaconScanner() public var uris = [Uri]() public func startScanning() { self.uriBeaconScanner.startScanningWithUpdateBlock({ //Remove any missing beacons for (index, knownUri) in enumerate(self.uris) { var foundKnownInDiscovered = false for discoveredBeacon in self.uriBeaconScanner.beacons() { if let discoveredBeacon = discoveredBeacon as? UBUriBeacon { if knownUri.matchesBeacon(discoveredBeacon) { foundKnownInDiscovered = true } } } if !foundKnownInDiscovered { log("Lost Uri: \(knownUri.uri)") self.uris.removeAtIndex( index ) self.delegate.scanner(self, lostUri: knownUri) } } //Add any new beacons for discoveredBeacon in self.uriBeaconScanner.beacons() { if let discoveredBeacon = discoveredBeacon as? UBUriBeacon { let uri = Uri(uriBeacon: discoveredBeacon) var foundDiscoveredInKnown = false for knownUri in self.uris { if knownUri.matchesBeacon(discoveredBeacon) { foundDiscoveredInKnown = true } } if !foundDiscoveredInKnown { log("Discovered Uri: \(uri.uri)") self.uris.append( uri ) uri.getMetadata({ log("Metadata received") self.delegate.scanner(self, discoveredUri: uri) }) } } } //Update RSSIs on known URIs for discoveredBeacon in self.uriBeaconScanner.beacons() { if let discoveredBeacon = discoveredBeacon as? UBUriBeacon { for knownUri in self.uris { if knownUri.matchesBeacon(discoveredBeacon) { knownUri.importance = discoveredBeacon.RSSI } } } } //Sort beacons by URIs self.uris.sort({ $0.importance > $1.importance }) }) } }
mit
e80d19b7e3f17c64442e043140a585c8
32.283951
143
0.462994
6.010033
false
false
false
false
livetat/TKSwarmAlert
TKSwarmAlert/Classes/TKSWBackgroundView.swift
9
2444
// // SWBackgroundView.swift // blurTest // // Created by Takuya Okamoto on 2015/08/17. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit public enum TKSWBackgroundType { case Blur case BrightBlur case TransparentBlack(alpha: CGFloat) } class TKSWBackgroundView: DynamicBlurView { let transparentBlackView = UIView() var brightView: BrightView? var blackAlphaForBlur:CGFloat = 0.125 var blurDuration: NSTimeInterval = 0.2 override init(frame:CGRect) { super.init(frame:frame) self.hidden = true self.blurRadius = 0 transparentBlackView.frame = frame transparentBlackView.backgroundColor = UIColor.blackColor() transparentBlackView.alpha = 0 self.addSubview(transparentBlackView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show(#type:TKSWBackgroundType, duration:NSTimeInterval = 0.2, didEnd:Closure? = nil) { if duration != 0.2 { self.blurDuration = duration } switch type { case .Blur: showBlur(didEnd: didEnd) case .BrightBlur: showBrightBlur(didEnd: didEnd) case let .TransparentBlack(alpha): self.blackAlphaForBlur = alpha showTransparentBlack(didEnd: didEnd) } } func showTransparentBlack(didEnd:Closure? = nil) { self.hidden = false UIView.animateWithDuration(blurDuration) { self.transparentBlackView.alpha = self.blackAlphaForBlur } NSTimer.schedule(delay: blurDuration + 0.1) { timer in didEnd?() } } func showBlur(didEnd:Closure? = nil) { self.hidden = false UIView.animateWithDuration(blurDuration) { self.blurRadius = 6 self.transparentBlackView.alpha = self.blackAlphaForBlur } NSTimer.schedule(delay: blurDuration + 0.1) { timer in didEnd?() } } func showBrightBlur(didEnd:Closure? = nil) { self.brightView = BrightView(frame: self.frame, center: CGPoint(x: self.center.x, y: self.center.y * 0.6)) self.insertSubview(brightView!, aboveSubview: transparentBlackView) showBlur() { self.brightView?.rotateAnimation() didEnd?() } } }
mit
fd6f3d026ce83ad7cabd1cf806672a31
24.4375
114
0.611794
4.464351
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteCMS/model.CMSMarkdown200Update.swift
1
2010
import OpenbuildExtensionPerfect public class ModelCMSMarkdown200Update: ResponseModel200EntityUpdated, DocumentationProtocol { public var descriptions = [ "error": "An error has occurred, will always be false", "message": "Will always be 'Successfully updated the entity.'", "old": "Object describing the Markdown entity in it's original state.", "updated": "Object describing the Markdown entity in it's updated state." ] public init(old: ModelCMSMarkdown, updated: ModelCMSMarkdown) { super.init(old: old, updated: updated) } public static func describeRAML() -> [String] { if let docs = ResponseDocumentation.getRAML(key: "RouteCMS.ModelCMSMarkdown200Update") { return docs } else { let entityOld = ModelCMSMarkdown( cms_markdown_id: 1, handle: "test", markdown: "#Markdown", html: "<h1>Markdown</h1>" ) let entityUpdated = ModelCMSMarkdown( cms_markdown_id: 1, handle: "test", markdown: "#Markdown updated", html: "<h1>Markdown updated</h1>" ) let model = ModelCMSMarkdown200Update(old: entityOld, updated: entityUpdated) let aMirror = Mirror(reflecting: model) let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions) ResponseDocumentation.setRAML(key: "RouteCMS.ModelCMSMarkdown200Update", lines: docs) return docs } } } extension ModelCMSMarkdown200Update: CustomReflectable { open var customMirror: Mirror { return Mirror( self, children: [ "error": self.error, "message": self.message, "old": self.old, "updated": self.updated ], displayStyle: Mirror.DisplayStyle.class ) } }
gpl-2.0
4a0d085685390638896f37f0c5cb3298
29.014925
103
0.584577
5.037594
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/EditHistoryCompareFunnel.swift
1
3039
import Foundation final class EditHistoryCompareFunnel: EventLoggingFunnel, EventLoggingStandardEventProviding { private enum Action: String, Codable { case showHistory = "show_history" case revisionView = "revision_view" case compare1 case compare2 case thankTry = "thank_try" case thankSuccess = "thank_success" case thankFail = "thank_fail" } private struct Event: EventInterface { static let schema: EventPlatformClient.Schema = .editHistoryCompare let action: Action let primary_language: String let is_anon: Bool } public static let shared = EditHistoryCompareFunnel() private override init() { super.init(schema: "MobileWikiAppiOSEditHistoryCompare", version: 19795952) } private func event(action: Action) -> [String: Any] { let event: [String: Any] = ["action": action.rawValue, "primary_language": primaryLanguage(), "is_anon": isAnon] return event } override func preprocessData(_ eventData: [AnyHashable: Any]) -> [AnyHashable: Any] { return wholeEvent(with: eventData) } private func newLog(action: Action, domain: String?) { let event = Event(action: action, primary_language: primaryLanguage(), is_anon: isAnon.boolValue) EventPlatformClient.shared.submit(stream: .editHistoryCompare, event: event, domain: domain) } public func logShowHistory(articleURL: URL) { log(event(action: .showHistory), language: articleURL.wmf_languageCode) newLog(action: .showHistory, domain: articleURL.wmf_site?.host) } /** * Log a revision view event. * - Parameter url: either a `siteURL` (when logging from `PageHistoryViewController`) * or a `pageURL` (when logging from `DiffContainerViewController`) */ public func logRevisionView(url: URL) { log(event(action: .revisionView), language: url.wmf_languageCode) newLog(action: .revisionView, domain: url.wmf_site?.host) } public func logCompare1(articleURL: URL) { log(event(action: .compare1), language: articleURL.wmf_languageCode) newLog(action: .compare1, domain: articleURL.wmf_site?.host) } public func logCompare2(articleURL: URL) { log(event(action: .compare2), language: articleURL.wmf_languageCode) newLog(action: .compare2, domain: articleURL.wmf_site?.host) } public func logThankTry(siteURL: URL) { log(event(action: .thankTry), language: siteURL.wmf_languageCode) newLog(action: .thankTry, domain: siteURL.host) } public func logThankSuccess(siteURL: URL) { log(event(action: .thankSuccess), language: siteURL.wmf_languageCode) newLog(action: .thankSuccess, domain: siteURL.host) } public func logThankFail(siteURL: URL) { log(event(action: .thankFail), language: siteURL.wmf_languageCode) newLog(action: .thankFail, domain: siteURL.host) } }
mit
ea68006963ae4308aaab4b9c3b16398b
36.518519
120
0.665021
4.214979
false
false
false
false
vincentSuwenliang/Mechandising
MerchandisingSystem/AppDelegate.swift
1
3004
// // AppDelegate.swift // MerchandisingSystem // // Created by Vincent on 12/6/2017. // Copyright © 2017 beyondz. All rights reserved. // import UIKit import Fabric import Crashlytics import RealmSwift // TODO remote notification; show font name @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Fabric.with([Crashlytics.self]) logUser() print("get server url :: \(SERVER_URL)") // let decodedString = BZNetwork.decodeString(string: "630950155a1141004703505d165a531840585043665254575b5315325a47595314345747") // print("get decoded string", decodedString) // let random = srandom(UInt32(2)) not sure how it works // window = UIWindow(frame: UIScreen.main.bounds) AppManager.createDirInDocument(dirname: DirAtDocument.db) configRealmPath() let version = UIDevice.current.systemVersion print("get current system version", version) print("is user loggined?", AppManager.isLoggedIn()) let isLogined = AppManager.isLoggedIn() window = UIWindow(frame: UIScreen.main.bounds) let mainInitialVC = AppManager.getInitialVC(name: .Main) let loginInitialVC = AppManager.getInitialVC(name: .Login) if isLogined { window?.rootViewController = mainInitialVC } else { window?.rootViewController = loginInitialVC } window?.makeKeyAndVisible() return true } func configRealmPath() { // TODO: compare if the same no need to reset var config = Realm.Configuration() let desUrl = config.fileURL! .deletingLastPathComponent() .appendingPathComponent("\(DirAtDocument.db)/hello.realm") print("realm last path:\(desUrl)") config.fileURL = desUrl Realm.Configuration.defaultConfiguration = config } func logUser() { print("get Crashlytics apiKey", Crashlytics.sharedInstance().apiKey) Crashlytics.sharedInstance().setUserName("Vincent Su") } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { print("exec here open url in app delegate") // stop open url? need to be verified return false } }
mit
66f4f12b1df10ed56fa39105bb2ba2e3
26.3
144
0.645355
5.159794
false
true
false
false
justindhill/Facets
Facets/View Controllers/Sort and Filter/OZLFieldSelectorViewController.swift
1
3203
// // OZLFieldSelectorTableViewController.swift // Facets // // Created by Justin Hill on 1/1/16. // Copyright © 2016 Justin Hill. All rights reserved. // import UIKit class OZLFieldSelectorViewController: UITableViewController { fileprivate let defaultFields = [ ("Project", "project"), ("Tracker", "tracker"), ("Status", "status"), ("Priority", "priority"), ("Author", "author"), ("Category", "category"), ("Start Date", "start_date"), ("Due Date", "due_date"), ("Percent Done", "done_ratio"), ("Estimated Hours", "estimated_hours"), ("Creation Date", "created_on"), ("Last Updated", "last_updated") ] let DefaultFieldSection = 0 let CustomFieldSection = 1 var selectionChangeHandler: ((_ field: OZLSortAndFilterField) -> Void)? let TextReuseIdentifier = "TextReuseIdentifier" let customFields = OZLModelCustomField.allObjects() override func viewDidLoad() { super.viewDidLoad() self.title = "Select a Field" self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:self.TextReuseIdentifier) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == DefaultFieldSection { return self.defaultFields.count } else if section == CustomFieldSection { return Int(self.customFields.count) } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.TextReuseIdentifier, for: indexPath) if indexPath.section == DefaultFieldSection { let (displayName, _) = self.defaultFields[indexPath.row] cell.textLabel?.text = displayName } else if indexPath.section == CustomFieldSection { let field = self.customFields[UInt(indexPath.row)] as? OZLModelCustomField cell.textLabel?.text = field?.name } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == DefaultFieldSection { let (displayName, serverName) = self.defaultFields[indexPath.row] self.selectionChangeHandler?(OZLSortAndFilterField(displayName: displayName, serverName: serverName)) } else if indexPath.section == CustomFieldSection { guard let field = self.customFields[UInt(indexPath.row)] as? OZLModelCustomField else { return } if let fieldName = field.name { let serverName = "cf_" + String(field.fieldId) self.selectionChangeHandler?(OZLSortAndFilterField(displayName: fieldName, serverName: serverName)) } } let _ = self.navigationController?.popViewController(animated: true) } }
mit
5a55625fdb219030c2695924d4b2ccd2
34.186813
115
0.626483
5.206504
false
false
false
false
BanyaKrylov/Learn-Swift
Skill/Homework 14/Homework 14/AlamofireThreeWeather.swift
1
2293
// // AlamofireThreeWeather.swift // Homework 14 // // Created by Ivan Krylov on 27.02.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import Foundation class AlamofireThreeWeather { var weatherCondition: String = "" var temp: Int = 0 var date: String = "" init?(weatherJson: NSDictionary) { if let listJson = weatherJson["list"] as? NSArray { for item in listJson { if let main = item as? NSDictionary { if let date = main["dt_txt"] as? String { self.date = date print(date) } if let temp = main["main"] as? NSDictionary { if let temperature = temp["temp"] as? Double { self.temp = Int(round(temperature - 273.15)) print(temp) } } if let nestedJson = main["weather"] as? NSArray { if let desc = nestedJson[0] as? NSDictionary { if let weathCond = desc["description"] as? String { self.weatherCondition = weathCond print(weatherCondition) } } } } } } // guard let listJson = weatherJson["list"] as? NSArray else { return nil } // guard let zeroMain = listJson[0] as? NSDictionary else { return nil } // guard let date = zeroMain["dt_txt"] as? String else { return nil } // self.date = date // guard let temp = zeroMain["main"] as? NSDictionary else { return nil } // guard let temperature = temp["temp"] as? Double else { return nil } // self.temp = Int(round(temperature - 273.15)) // guard let weather = zeroMain["weather"] as? NSArray else { return nil } // guard let desc = weather[0] as? NSDictionary else { return nil } // guard let weatherCondition = desc["description"] as? String else { return nil } // self.weatherCondition = weatherCondition.capitalized } }
apache-2.0
ab656b4155e0d630a3d9cbc05c1868e4
42.245283
97
0.484729
4.929032
false
false
false
false
MrAlek/JSQDataSourcesKit
Example/Example/CollectionViewController.swift
1
2798
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://jessesquires.com/JSQDataSourcesKit // // // GitHub // https://github.com/jessesquires/JSQDataSourcesKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import UIKit import JSQDataSourcesKit class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { typealias CollectionCellFactory = CellFactory<CellViewModel, CollectionViewCell> typealias HeaderViewFactory = TitledCollectionReusableViewFactory<CellViewModel> var dataSourceProvider: CollectionViewDataSourceProvider<Section<CellViewModel>, CollectionCellFactory, HeaderViewFactory>? override func viewDidLoad() { super.viewDidLoad() configureCollectionView(collectionView!) // 1. create view models let section0 = Section(items: CellViewModel(), CellViewModel(), CellViewModel()) let section1 = Section(items: CellViewModel(), CellViewModel(), CellViewModel(), CellViewModel(), CellViewModel(), CellViewModel()) let section2 = Section(items: CellViewModel()) let allSections = [section0, section1, section2] // 2. create cell factory let cellFactory = CellFactory(reuseIdentifier: CellId) { (cell, model: CellViewModel, collectionView, indexPath) -> CollectionViewCell in cell.label.text = model.text + "\n\(indexPath.section), \(indexPath.item)" return cell } // 3. create supplementary view factory let headerFactory = TitledCollectionReusableViewFactory( dataConfigurator: { (header, item: CellViewModel?, kind, collectionView, indexPath) -> TitledCollectionReusableView in header.label.text = "Section \(indexPath.section)" return header }, styleConfigurator: { (headerView) -> Void in headerView.backgroundColor = .darkGrayColor() headerView.label.textColor = .whiteColor() }) // 4. create data source provider self.dataSourceProvider = CollectionViewDataSourceProvider(sections: allSections, cellFactory: cellFactory, supplementaryViewFactory: headerFactory, collectionView: collectionView) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: collectionView.frame.size.width, height: 50) } }
mit
6c560a227cbc1e1a96c1853b1bfbbb66
39.536232
168
0.658205
5.976496
false
false
false
false
maxbritto/cours-ios11-swift4
Niveau_avance/Objectif 5 Synchronisation/Safety First/Safety First/Model/Credentials.swift
3
1222
// // Credentials.swift // Safety First // // Created by Maxime Britto on 05/09/2017. // Copyright © 2017 Maxime Britto. All rights reserved. // import Foundation import RealmSwift class Credentials: Object { @objc private dynamic var _title = "" @objc private dynamic var _login = "" @objc private dynamic var _password = "" @objc private dynamic var _url = "" var title:String { get { return _title } set { realm?.beginWrite() _title = newValue try? realm?.commitWrite() } } var login:String { get { return _login } set { realm?.beginWrite() _login = newValue try? realm?.commitWrite() } } var password:String { get { return _password } set { realm?.beginWrite() _password = newValue try? realm?.commitWrite() } } var url:String { get { return _url } set { realm?.beginWrite() _url = newValue try? realm?.commitWrite() } } }
apache-2.0
9568b4e4bf10afe95a30697b41596492
19.016393
56
0.470106
4.769531
false
false
false
false
werediver/ParserCore
Sources/CLI/main.swift
2
1588
import Foundation import ParserCore import JSON //do { // let source = "1+2" // print(source) // let core = Core(source: source) // let result = core.parse(LSumParser.start()) // dump(result) // exit(0) //} enum ExitCode { static let inputAccepted: Int32 = 0 static let inputRejected: Int32 = 1 static let failure: Int32 = 2 } let file: FileHandle switch CommandLine.argc { case 1: file = FileHandle.standardInput case 2: guard let handle = FileHandle(forReadingAtPath: CommandLine.arguments[1]) else { exit(ExitCode.failure) } file = handle default: exit(ExitCode.failure) } guard let input = String(data: file.readDataToEndOfFile(), encoding: .utf8) else { exit(ExitCode.failure) } var core: Core<String>? var result: Either<Mismatch, JSON>? let stats = benchmark { core = Core(source: input) result = core?.parse(JSONParser.start()) } print("Stats:\n avg. user time: \(stats.avgUserTime) s\n avg. sys time: \(stats.avgSysTime) s") //let core = GenericParserCore(source: input) //let result = core.parse(JSONParser.start()) // //dump(result) //if let ff = core.farthestFailure { // let offset = input.distance(from: input.startIndex, to: ff.position) // print("\nMismatches at offset \(offset):\n") // ff.failures.forEach { f in // print("\(f.trace)\n\(f.mismatch)\n") // } //} if case .right? = result { print("ACCEPTED") exit(ExitCode.inputAccepted) } else { if let report = core?.tracer.report() { print(report) } print("REJECTED") exit(ExitCode.inputRejected) }
mit
de928906ad777338b9fb23d1dd093bfd
23.430769
98
0.657431
3.32914
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Effects/Reverb/Comb Filter Reverb/AKCombFilterReverb.swift
1
4761
// // AKCombFilterReverb.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This filter reiterates input with an echo density determined by /// loopDuration. The attenuation rate is independent and is determined by /// reverbDuration, the reverberation duration (defined as the time in seconds /// for a signal to decay to 1/1000, or 60dB down from its original amplitude). /// Output from a comb filter will appear only after loopDuration seconds. /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). /// - loopDuration: The loop time of the filter, in seconds. This can also be thought of as the delay time. Determines frequency response curve, loopDuration * sr/2 peaks spaced evenly between 0 and sr/2. /// public class AKCombFilterReverb: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKCombFilterReverbAudioUnit? internal var token: AUParameterObserverToken? private var reverbDurationParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). public var reverbDuration: Double = 1.0 { willSet { if reverbDuration != newValue { if internalAU!.isSetUp() { reverbDurationParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.reverbDuration = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). /// - loopDuration: The loop time of the filter, in seconds. This can also be thought of as the delay time. Determines frequency response curve, loopDuration * sr/2 peaks spaced evenly between 0 and sr/2. /// public init( _ input: AKNode, reverbDuration: Double = 1.0, loopDuration: Double = 0.1) { self.reverbDuration = reverbDuration var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x636f6d62 /*'comb'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKCombFilterReverbAudioUnit.self, asComponentDescription: description, name: "Local AKCombFilterReverb", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKCombFilterReverbAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU!.setLoopDuration(Float(loopDuration)) } guard let tree = internalAU?.parameterTree else { return } reverbDurationParameter = tree.valueForKey("reverbDuration") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.reverbDurationParameter!.address { self.reverbDuration = Double(value) } } } internalAU?.reverbDuration = Float(reverbDuration) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
74b01488a8532c3c4e509350d81d92e2
35.623077
210
0.645243
5.214677
false
false
false
false
spacedrabbit/100-days
One00Days/One00Days/Day32ViewController.swift
1
2693
// // Day32ViewController.swift // One00Days // // Created by Louis Tur on 3/23/16. // Copyright © 2016 SRLabs. All rights reserved. // import UIKit func ==(lhs: CubicGrid, rhs: CubicGrid) -> Bool { return false } typealias CubicGridSize = (rows: Int, columns: Int) class CubicGrid: Equatable { var cubicSideLength: CGFloat = 0.0 var cubicBackgroundColor: UIColor? var grid: [[CubicUnit]] = [[CubicUnit]]() init(withCubicSideLength length: CGFloat, initialColor color: UIColor? = ColorSwatch().randomColor()) { self.cubicSideLength = length self.cubicBackgroundColor = color } fileprivate func gridSizeForView(_ view: UIView) -> CubicGridSize { let cubesByWidth: CGFloat = ceil(view.bounds.width / self.cubicSideLength) let cubesByHeight: CGFloat = ceil(view.bounds.height / self.cubicSideLength) return (rows: Int(cubesByWidth), columns: Int(cubesByHeight)) } func createGridForView(_ view: UIView) -> CubicGrid{ let (rows, columns) = self.gridSizeForView(view) var tempGrid = [[CubicUnit]]() for vCubics in 1...columns { var cubicRow = [CubicUnit]() for hCubics in 1...rows { let newCubic: CubicUnit = CubicUnit(withCubicSideLength: self.cubicSideLength) newCubic.backgroundColor = self.cubicBackgroundColor ?? ColorSwatch().randomColor() newCubic.setMatrixPosition(hCubics - 1, column: vCubics - 1) cubicRow.append(newCubic) } tempGrid.append(cubicRow) } self.grid = tempGrid return self // returns self because I wanted a 1 liner } func drawGridInView(_ view: UIView) -> CubicGrid { var currentOrigin: CGPoint = 0.0*&0.0 for cubicRow: [CubicUnit] in self.grid { for cubic: CubicUnit in cubicRow { view.addSubview(cubic) cubic.frame = CGRect(x: currentOrigin.x, y: currentOrigin.y, width: Day30ViewController.blockSize, height: Day30ViewController.blockSize) currentOrigin = CGPoint(x: currentOrigin.x + Day30ViewController.blockSize, y: currentOrigin.y) } currentOrigin = CGPoint(x: 0.0, y: currentOrigin.y + Day30ViewController.blockSize) } return self } } class Day32ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() CubicUnitManager.generateGridToFit(self.view, usingLength: 20.0) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } internal func configureConstraints() { } internal func setupViewHierarchy() { } }
mit
c33b8ca7dd147db5b14b1e1b04363f75
27.041667
145
0.680906
4.072617
false
false
false
false
sunny-fish/teamlobo
ARPlay/ARPlay/CupShuffle.swift
1
3174
// // CupShuffle.swift // ARPlay // // Created by Daniel Giralte on 7/22/17. // Copyright © 2017 Sunny Fish. All rights reserved. // import Foundation struct Cup { var hasBall: Bool var position: Int var emptyPos: Bool var id: Int } struct CupGame { var cups: [Cup] } class CupShuffle { var gameCups = CupGame(cups:[]) init(cups: Int) { let postions = cups for i in 1...postions { // if i == 1 { // gameCups.cups.append(Cup(hasBall: false, position: i, emptyPos: true)) // continue // } // // if i == postions { // gameCups.cups.append(Cup(hasBall: false, position: i, emptyPos: true)) // continue // } gameCups.cups.append(Cup(hasBall: false, position: i, emptyPos: false, id: i)) } } func AddBall() { for i in 1...3 { gameCups.cups.append(Cup(hasBall: false, position: i, emptyPos: false, id: i)) } gameCups.cups[0].hasBall = true } func RandomValidCupIndex(not: Int?) -> Int { arc4random_stir() let theCup = Int(arc4random_uniform(UInt32(gameCups.cups.count))) if !gameCups.cups[theCup].emptyPos && theCup != not { return theCup } else { return RandomValidCupIndex(not: not) } } func ShuffleCups(times: Int) { for _ in 1...times { let moveFrom = RandomValidCupIndex(not: -1) let moveTo = RandomValidCupIndex(not: moveFrom) print ("MoveFrom: \(moveFrom) - MoveTo: \(moveTo)") ShuffleCupStep(fromPos: moveFrom, toPos: moveTo) } } func ShuffleCupsOnce() -> (from: Int, to: Int) { let moveFrom = RandomValidCupIndex(not: -1) let moveTo = RandomValidCupIndex(not: moveFrom) ShuffleCupStep(fromPos: moveFrom, toPos: moveTo) return (from: moveFrom, to: moveTo) } func ShuffleCupStep(fromPos: Int, toPos: Int) { var arr = gameCups.cups arr.swapAt(fromPos, toPos) gameCups.cups = arr let cupElements = gameCups.cups.count - 1 // update positons for i in 0...cupElements { gameCups.cups[i].position = i + 1 } for i in 0...cupElements { printCupAt(i) } print ("\n\n") } func printCupAt(_ index: Int) { print ("Id: \(gameCups.cups[index].id) - " + "Position: \(gameCups.cups[index].position) - " + "Has Ball \(gameCups.cups[index].hasBall) - " + "Empty \(gameCups.cups[index].emptyPos)") } } // Sample Playground Code //var cupGame = CupShuffle(cups: 3) // //cupGame.AddBall() // //cupGame.printCupAt(0) //cupGame.printCupAt(1) //cupGame.printCupAt(2) //print ("****************************\n") // //cupGame.ShuffleCups(times: 4)
unlicense
606b9e9beffed7fb5c4f03d2c1ee893c
25.008197
100
0.502364
4.02665
false
false
false
false
quintonwall/SObjectKit
SObjectKit/Classes/JSON.swift
2
1015
// // JSON.swift // Pods // // Created by QUINTON WALL on 11/29/16. // // import SwiftyJSON extension JSON { public var date: Date? { get { if let str = self.string { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone! let date = dateFormatter.date(from: str) return date } return nil } } public var systemdate: Date? { get { if let str = self.string { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.AAZZZZZ" dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone! let date = dateFormatter.date(from: str) return date } return nil } } }
mit
15489e693f3234adf70dd41c56a180d0
23.166667
77
0.474877
4.787736
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Collections/TextSearch/TextSearchViewController.swift
1
5807
// // Wire // Copyright (C) 2017 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 Foundation import WireSyncEngine final class TextSearchViewController: NSObject { let resultsView: TextSearchResultsView = TextSearchResultsView() let searchBar: TextSearchInputView = TextSearchInputView() weak var delegate: MessageActionResponder? = .none let conversation: ConversationLike var searchQuery: String? { return searchBar.query } fileprivate var textSearchQuery: TextSearchQuery? fileprivate var results: [ZMConversationMessage] = [] { didSet { reloadResults() } } fileprivate var searchStartedDate: Date? init(conversation: ConversationLike) { self.conversation = conversation super.init() loadViews() } private func loadViews() { resultsView.isHidden = results.isEmpty resultsView.tableView.isHidden = results.isEmpty resultsView.noResultsView.isHidden = !results.isEmpty resultsView.tableView.delegate = self resultsView.tableView.dataSource = self searchBar.delegate = self searchBar.placeholderString = "collections.search.field.placeholder".localized(uppercased: true) } func teardown() { textSearchQuery?.cancel() } fileprivate func scheduleSearch() { let searchSelector = #selector(TextSearchViewController.search) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: searchSelector, object: .none) perform(searchSelector, with: .none, afterDelay: 0.2) } @objc fileprivate func search() { let searchSelector = #selector(TextSearchViewController.search) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: searchSelector, object: .none) textSearchQuery?.cancel() textSearchQuery = nil guard let query = searchQuery, !query.isEmpty else { results = [] return } textSearchQuery = TextSearchQuery(conversation: conversation, query: query, delegate: self) if let query = textSearchQuery { searchStartedDate = Date() perform(#selector(showLoadingSpinner), with: nil, afterDelay: 2) query.execute() } } fileprivate func reloadResults() { let query = searchQuery ?? "" let noResults = results.isEmpty let validQuery = TextSearchQuery.isValid(query: query) // We hide the results when we either have none or the query is too short resultsView.tableView.isHidden = noResults || !validQuery // We only show the no results view if there are no results and a valid query resultsView.noResultsView.isHidden = !noResults || !validQuery // If the user did not enter any search query we show the collection again resultsView.isHidden = query.isEmpty resultsView.tableView.reloadData() } @objc fileprivate func showLoadingSpinner() { searchBar.isLoading = true } fileprivate func hideLoadingSpinner() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(showLoadingSpinner), object: nil) searchBar.isLoading = false } } extension TextSearchViewController: TextSearchQueryDelegate { func textSearchQueryDidReceive(result: TextQueryResult) { guard result.query == textSearchQuery else { return } if !result.matches.isEmpty || !result.hasMore { hideLoadingSpinner() results = result.matches } } } extension TextSearchViewController: TextSearchInputViewDelegate { func searchView(_ searchView: TextSearchInputView, didChangeQueryTo query: String) { textSearchQuery?.cancel() searchStartedDate = nil hideLoadingSpinner() if TextSearchQuery.isValid(query: query) { scheduleSearch() } else { // We reset the results to avoid showing the previous // results for a short period for subsequential searches results = [] } } func searchViewShouldReturn(_ searchView: TextSearchInputView) -> Bool { return TextSearchQuery.isValid(query: searchView.query) } } extension TextSearchViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TextSearchResultCell.reuseIdentifier) as! TextSearchResultCell cell.configure(with: results[indexPath.row], queries: searchQuery?.components(separatedBy: .whitespacesAndNewlines) ?? []) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.perform(action: .showInConversation, for: results[indexPath.row], view: tableView) } func scrollViewDidScroll(_ scrollView: UIScrollView) { searchBar.searchInput.endEditing(true) } }
gpl-3.0
2d26d40828e34625e3fdcab9925bd24f
34.193939
130
0.690718
5.303196
false
false
false
false
sanghapark/Vigorous
Vigorous/Vigorously.swift
1
4688
// // Vigorous.swift // Vigorous // // Created by ParkSangHa on 2017. 4. 4.. // Copyright © 2017년 sanghapark1021. All rights reserved. // import Foundation public class Vigorously { typealias Completion = (Bool) -> () fileprivate var delaying = false private let queue = OperationQueue() private let view: UIView lazy var completions = [String: Completion]() public init(_ view: UIView) { self.view = view queue.maxConcurrentOperationCount = 1 queue.qualityOfService = .userInteractive } @discardableResult public func animate(_ animator: Animator, completion: (() -> Void)? = nil) -> Self { for item in animator.items { if let animation = item as? Animation { if animation.operationType == .serial { for animatable in animation.animatables { let op = AnimatableOperation(animatable: animatable) op.name = animation.name op.delegate = self as Vigorously if animation.completion != nil { completions[animation.name] = animation.completion } queue.addOperation(op) } } else if animation.operationType == .parallel { let op = AnimatableOperation(animatables: animation.animatables) op.name = animation.name op.delegate = self as Vigorously if animation.completion != nil { completions[animation.name] = animation.completion } queue.addOperation(op) } } else if let delay = item as? Delay { let op = DelayOperation(delayTime: delay.delayTime ?? 0) op.name = delay.name op.delegate = self as Vigorously if delay.completion != nil { completions[delay.name] = delay.completion } queue.addOperation(op) } } queue.operations.last?.completionBlock = completion return self } @discardableResult public func animate(name: String? = nil, _ animatable: Animatable, completion: ((Bool)->())? = nil) -> Self { let op = AnimatableOperation(animatable: animatable) op.name = name ?? UUID().uuidString op.delegate = self as Vigorously if completion != nil { completions[op.name!] = completion } queue.addOperation(op) return self } @discardableResult public func `repeat`(for count: Int, _ animator: Animator) -> Self { guard count > 0 else { return self } for _ in 1...count { animate(animator) } return self } @discardableResult public func `repeat`(for count: Int, _ animatable: Animatable) -> Self { guard count > 0 else { return self } for _ in 1...count { animate(animatable) } return self } public func repeatForever(_ animator: Animator) { animate(animator) { [weak self, animator] in guard let strongSelf = self else { return } strongSelf.repeatForever(animator) } } public func repeatForever(_ animatable: Animatable) { animate(animatable) { [weak self, animatable] _ in guard let strongSelf = self else { return } strongSelf.repeatForever(animatable) } } @discardableResult public func cancelAll() -> Self { self.view.layer.removeAllAnimations() queue.cancelAllOperations() return self } @discardableResult public func cancel(name: String) -> Self { queue.operations.filter { $0.name == name }.forEach { $0.cancel() } return self } @discardableResult public func pause() -> Bool { // guard !delaying else { return false } let pausedTime: CFTimeInterval = view.layer.convertTime(CACurrentMediaTime(), from: nil) view.layer.speed = 0.0 view.layer.timeOffset = pausedTime return true } @discardableResult public func resume() -> Bool { // guard !delaying else { return false } let pausedTime: CFTimeInterval = view.layer.timeOffset view.layer.speed = 1.0 view.layer.timeOffset = 0.0 view.layer.beginTime = 0.0 let timeSincePause: CFTimeInterval = view.layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime view.layer.beginTime = timeSincePause return true } } extension Vigorously: AnimatableOperationDelegate { func didFinishAnimator(name: String, success: Bool) { self.completions[name]?(success) self.completions.removeValue(forKey: name) } } extension Vigorously: DelayOperationDelegate { func didStartDelay(name: String) { self.delaying = true } func didFinishDelay(name: String, success: Bool) { self.delaying = false self.completions[name]?(success) self.completions.removeValue(forKey: name) } }
mit
0985e4f73b45a212466a6c1aa04f505d
24.601093
111
0.64461
4.509143
false
false
false
false
haiwei-Lee/CustomSlider
CustomSlider/CustomSlider/ViewController.swift
1
1324
// // ViewController.swift // CustomSlider // // Created by Lee on 15/6/17. // Copyright (c) 2015年 Havi. All rights reserved. // import UIKit class ViewController: UIViewController { let rangeSlider = RangeSlider(frame: CGRectZero) override func viewDidLoad() { super.viewDidLoad() view.addSubview(rangeSlider) rangeSlider.addTarget(self, action: "rangeSliderValueChanged:", forControlEvents: .ValueChanged) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { () -> Void in self.rangeSlider.trackHeighlightTintColor = UIColor.redColor() self.rangeSlider.curvaceousness = 0.0 } // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { let margin: CGFloat = 2.0 let width = view.bounds.width - 2 * margin rangeSlider.frame = CGRectMake(margin, margin + topLayoutGuide.length, width, 31.0) } func rangeSliderValueChanged(rangeSlider: RangeSlider){ println("Range slider value changed: (\(rangeSlider.lowerValue) \(rangeSlider.upperValue))") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ea069f233628199a8d239b49825e5a24
24.921569
100
0.695915
4.392027
false
false
false
false
Rendel27/RDExtensionsSwift
RDExtensionsSwift/RDExtensionsSwift/Source/UIAlertController/UIAlertController+Init.swift
1
2083
// // UIAlertController+Init.swift // // Created by Giorgi Iashvili on 19.09.16. // Copyright (c) 2016 Giorgi Iashvili // // 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 extension UIAlertController { /// RDExtensionsSwift: Return a newly initialized view controller for displaying an alert to the user convenience init(title: String? = nil, message: String? = nil, style : UIAlertController.Style = .alert, inputFieldPlaceholders: [String] = [], actions: [UIAlertAction], cancelButtonTitle: String?, completion: (() -> Void)? = nil) { self.init(title: title, message: message, preferredStyle: style) for tfph in inputFieldPlaceholders { self.addTextField { (tf) -> Void in tf.placeholder = tfph } } for action in actions { self.addAction(action) } if let c = cancelButtonTitle { self.addAction(UIAlertAction(title: c, style: .cancel, handler: { _ in })) } } }
mit
f1a378f5375dcbf7f654aac23c6bde98
42.395833
234
0.68459
4.518438
false
false
false
false
chicio/Exploring-SceneKit
ExploringSceneKit/Model/Scenes/Light.swift
1
636
// // Light.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 26.08.17. // import SceneKit class Light { let node: SCNNode init(lightNode: SCNNode) { node = lightNode } init(lightFeatures: LightFeatures) { node = SCNNode() createLight() set(lightFeatures: lightFeatures) } func createLight() { node.light = SCNLight() } private func set(lightFeatures: LightFeatures) { node.light?.color = lightFeatures.color node.position = lightFeatures.position node.eulerAngles = lightFeatures.orientation; } }
mit
2f9126e8b9ddcf89df27021d49cc0475
18.875
53
0.606918
4.211921
false
false
false
false
xmartlabs/Swift-Project-Template
Project-iOS/XLProjectName/XLProjectName/Helpers/Opera/Pagination/PaginationRequestType.swift
1
6129
// PaginationRequestType.swift // Opera ( https://github.com/xmartlabs/Opera ) // // Copyright (c) 2019 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import RxSwift struct Default { static let firstPageParameterValue = "1" static let queryParameterName = "q" static let pageParamName = "page" static let prevRelationName = "prev" static let nextRelationName = "next" static let relationPageParamName = "page" } public protocol BasePaginationRequestType: URLRequestConvertible { /// Route var route: RouteType { get } /// Page, represent request page parameter var page: String { get } /// Query string var query: String? { get } /// Filters var filter: FilterType? { get } } /** * A type that adopts PaginationRequestType encapsulates information required to fetch and filter a collection of items from a server endpoint. It can be used to create a pagination request. The request will take into account page, query, route, filter properties. */ public protocol PaginationRequestType: BasePaginationRequestType { associatedtype Response: PaginationResponseType, Decodable /** Creates a new PaginationRequestType equals to self but updating the page value. - parameter page: new page value - returns: PaginationRequestType instance identically to self and having its page value updated to `page` */ func routeWithPage(_ page: String) -> Self /** Creates a new PaginationRequestType equals to self but updating query strng and setting its page to first page value. - parameter query: query string - returns: PaginationRequestType instance identically to self and having its query value updated to `query` and its page to firs page value. */ func routeWithQuery(_ query: String) -> Self /** Creates a new PaginationRequestType equals to self but updating its filter. Page value is set to first page. - parameter filter: filters - returns: PaginationRequestType instance identically to self and having its filter value updated to `filter` and its page to firs page value. */ func routeWithFilter(_ filter: FilterType) -> Self /** Instantiate a new `PaginationRequestType` - parameter route: route info - parameter page: page - parameter query: query string - parameter filter: filters to get array of items to parse using the JSON parsing library. - returns: The new PaginationRequestType instance. */ init( route: RouteType, page: String?, query: String?, filter: FilterType? ) } extension BasePaginationRequestType { // MARK: URLRequestConvertible conformance public func asURLRequest() throws -> URLRequest { let url = try route.baseURL.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(route.path)) urlRequest.httpMethod = route.method.rawValue var params = (self.route as? URLRequestParametersSetup)? .urlRequestParametersSetup(urlRequest, parameters: parameters) ?? parameters params = (self as? URLRequestParametersSetup)? .urlRequestParametersSetup(urlRequest, parameters: params) ?? params urlRequest = try route.encoding.encode(urlRequest, with: params) return urlRequest } /// Pagination request parameters var parameters: [String: Any]? { var result = route.parameters ?? [:] result[(self as? PaginationRequestTypeSettings)? .pageParameterName ?? Default.pageParamName] = page as AnyObject? if let q = query, q != "" { result[(self as? PaginationRequestTypeSettings)? .queryParameterName ?? Default.queryParameterName] = query as AnyObject? } for (k, v) in filter?.parameters ?? [:] { result.updateValue(v, forKey: k) } return result } } extension PaginationRequestType { public var rx: Reactive<Self> { return Reactive(self) } public func routeWithPage(_ page: String) -> Self { return Self.init( route: route, page: page, query: query, filter: filter ) } public func routeWithQuery(_ query: String) -> Self { return Self.init( route: route, page: (self as? PaginationRequestTypeSettings)? .firstPageParameterValue ?? Default.firstPageParameterValue, query: query, filter: filter ) } public func routeWithFilter(_ filter: FilterType) -> Self { return Self.init( route: route, page: (self as? PaginationRequestTypeSettings)? .firstPageParameterValue ?? Default.firstPageParameterValue, query: query, filter: filter ) } }
mit
ca761b4ebc728a9e84e974480a3c9d59
33.05
88
0.663077
5.061107
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotateMultiple.swift
8
3123
// // NVActivityIndicatorAnimationBallClipRotateMultiple.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/23/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallClipRotateMultiple: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) circleOf(shape: .ringTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layer: layer, size: bigCircleSize, color: color, reverse: false) circleOf(shape: .ringTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layer: layer, size: smallCircleSize, color: color, reverse: true) } func createAnimationIn(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if (!reverse) { rotateAnimation.values = [0, M_PI, 2 * M_PI] } else { rotateAnimation.values = [0, -M_PI, -2 * M_PI] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } func circleOf(shape: NVActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: UIColor, reverse: Bool) { let circle = shape.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layer.bounds.size.width - size) / 2, y: (layer.bounds.size.height - size) / 2, width: size, height: size) let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
apache-2.0
fddbd1cc687834db6a39cc3a3ea90155
39.558442
179
0.628882
5.403114
false
false
false
false
hfutrell/BezierKit
BezierKit/Library/Types.swift
1
3742
// // Types.swift // BezierKit // // Created by Holmes Futrell on 11/3/16. // Copyright © 2016 Holmes Futrell. All rights reserved. // #if canImport(CoreGraphics) import CoreGraphics #endif import Foundation public struct Intersection: Equatable, Comparable { public var t1: CGFloat public var t2: CGFloat public static func < (lhs: Intersection, rhs: Intersection ) -> Bool { if lhs.t1 < rhs.t1 { return true } else if lhs.t1 == rhs.t1 { return lhs.t2 < rhs.t2 } else { return false } } } public struct Interval: Equatable { public var start: CGFloat public var end: CGFloat public init(start: CGFloat, end: CGFloat) { self.start = start self.end = end } } public struct BoundingBox: Equatable { public var min: CGPoint public var max: CGPoint public var cgRect: CGRect { let s = self.size return CGRect(origin: self.min, size: CGSize(width: s.x, height: s.y)) } public static let empty: BoundingBox = BoundingBox(min: .infinity, max: -.infinity) internal init(min: CGPoint, max: CGPoint) { self.min = min self.max = max } @discardableResult public mutating func union(_ other: BoundingBox) -> BoundingBox { self.min = CGPoint.min(self.min, other.min) self.max = CGPoint.max(self.max, other.max) return self } @discardableResult public mutating func union(_ point: CGPoint) -> BoundingBox { self.min = CGPoint.min(self.min, point) self.max = CGPoint.max(self.max, point) return self } public func intersection(_ other: BoundingBox) -> BoundingBox { let box = BoundingBox(min: CGPoint.max(self.min, other.min), max: CGPoint.min(self.max, other.max)) guard box.max.x - box.min.x >= 0, box.max.y - box.min.y >= 0 else { return BoundingBox.empty } return box } public var isEmpty: Bool { return self.min.x > self.max.x || self.min.y > self.max.y } public init(p1: CGPoint, p2: CGPoint) { self.min = CGPoint.min(p1, p2) self.max = CGPoint.max(p1, p2) } public init(first: BoundingBox, second: BoundingBox) { self.min = CGPoint.min(first.min, second.min) self.max = CGPoint.max(first.max, second.max) } public var size: CGPoint { return CGPoint.max(max - min, .zero) } internal var area: CGFloat { let size = self.size return size.x * size.y } public func contains(_ point: CGPoint) -> Bool { guard point.x >= min.x && point.x <= max.x else { return false } guard point.y >= min.y && point.y <= max.y else { return false } return true } public func overlaps(_ other: BoundingBox) -> Bool { let p1 = CGPoint.max(self.min, other.min) let p2 = CGPoint.min(self.max, other.max) return p2.x >= p1.x && p2.y >= p1.y } internal func lowerBoundOfDistance(to point: CGPoint) -> CGFloat { let distanceSquared = (0..<CGPoint.dimensions).reduce(CGFloat(0.0)) { let temp = point[$1] - Utils.clamp(point[$1], self.min[$1], self.max[$1]) return $0 + temp * temp } return sqrt(distanceSquared) } internal func upperBoundOfDistance(to point: CGPoint) -> CGFloat { let distanceSquared = (0..<CGPoint.dimensions).reduce(CGFloat(0.0)) { let diff1 = point[$1] - self.min[$1] let diff2 = point[$1] - self.max[$1] return $0 + CGFloat.maximum(diff1 * diff1, diff2 * diff2) } return sqrt(distanceSquared) } }
mit
bf1a48eb7ccaf825b5d154b97bbb81fc
31.815789
88
0.585405
3.737263
false
false
false
false
PeeJWeeJ/SwiftyHUD
SVProgressHUD/SVProgressHud.swift
1
5810
// // SVProgressHud.swift // SVProgressHUD // // Created by Paul Fechner on 12/27/15. // Copyright © 2015 EmbeddedSources. All rights reserved. // import Foundation class SVProgressHUD { private static var realSharedView: ProgressHUD? private static var sharedView: ProgressHUD? { get{ if (realSharedView == nil){ realSharedView = ProgressHUD(frame: UIScreen.mainScreen().bounds) } return realSharedView } } class func setStatus(status: String){ sharedView!.setStatus(status) } class func setDefaultStyle(style: ProgressHUDStyle){ sharedView!.defaultStyle = style } class func setDefaultMaskType(maskType: ProgressHUDMaskType) { sharedView!.defaultMaskType = maskType } class func setDefaultAnimationType(type: ProgressHUDAnimationType) { sharedView!.defaultAnimationType = type } class func setMinimumSize(minimumSize: CGSize) { sharedView!.minimumSize = minimumSize } class func setRingThickness(ringThickness: CGFloat) { sharedView!.ringThickeness = ringThickness } class func setRingRadius(radius: CGFloat) { sharedView!.ringRadius = radius } class func setRingNoTextRadius(radius: CGFloat) { sharedView!.ringNoTextRadius = radius } class func setCornerRadius(cornerRadius: CGFloat) { sharedView!.cornerRadius = cornerRadius } class func setDefaultMaskType(type: SVProgressHUDAnimationType) { sharedView } class func setFont(font: UIFont) { sharedView!.font = font } class func setForegroundColor(color: UIColor) { sharedView!.foregroundColor = color } class func setBackgroundColor(color: UIColor) { sharedView!.backgroundColor = color } class func setInfoImage(image: UIImage) { sharedView!.infoImage = image } class func setSuccessImage(image: UIImage) { sharedView!.successImage = image } class func setErrorImage(image: UIImage) { sharedView!.errorImage = image } class func setViewForExtension(view: UIView) { sharedView!.viewForExtension = view } class func setMinimumDismissTimeInterval(interval: NSTimeInterval) { sharedView!.minimumDismissTimeInterval = interval } class func setOffsetFromCenter(offset: UIOffset){ sharedView!.offsetFromCenter = offset } class func resetOffsetFromCenter(){ setOffsetFromCenter(UIOffsetZero) } class func show(){ show(nil) } class func show(status: String?){ show(status, maskType: nil) } class func show(maskType: ProgressHUDMaskType){ show(nil, maskType: maskType) } class func show(status: String?, maskType: ProgressHUDMaskType?){ var existingMaskType: ProgressHUDMaskType? = nil if let maskType = maskType { existingMaskType = sharedView!.defaultMaskType setDefaultMaskType(maskType) } showProgress(Float(ProgressHUDUndefinedProgress), status: status) if let existingMaskType = existingMaskType { setDefaultMaskType(existingMaskType) } } class func showProgress(progress: Float){ showProgress(progress, status: nil) } class func showProgress(progress: Float, maskType: ProgressHUDMaskType){ showProgress(progress, status: nil, maskType: maskType) } class func showProgress(progress: Float, status: String?){ showProgress(progress, status: status, maskType: nil) } class func showProgress(progress: Float, status: String?, maskType: ProgressHUDMaskType?){ var existingMaskType: ProgressHUDMaskType? = nil if let maskType = maskType { existingMaskType = sharedView!.defaultMaskType setDefaultMaskType(maskType) } sharedView!.showProgress(progress, status: status) if let existingMaskType = existingMaskType { setDefaultMaskType(existingMaskType) } } class func showInfo(status: String){ showImage(sharedView!.infoImage, status: status) } class func showInfo(status: String, maskType: ProgressHUDMaskType){ let defaultMaskType = sharedView!.defaultMaskType setDefaultMaskType(maskType) showInfo(status) setDefaultMaskType(defaultMaskType) } class func showSuccess(status: String){ showImage(sharedView!.successImage, status: status) } class func showSuccess(status: String, maskType: ProgressHUDMaskType){ let existingMaskType = sharedView!.defaultMaskType setDefaultMaskType(maskType) showSuccess(status) setDefaultMaskType(existingMaskType) } class func showError(status: String){ showImage(sharedView!.errorImage, status: status) } class func showError(status: String, maskType: ProgressHUDMaskType){ let existingMaskType = sharedView!.defaultMaskType setDefaultMaskType(maskType) showError(status) setDefaultMaskType(existingMaskType) } class func showImage(image: UIImage, status: String){ showImage(image, status: status, maskType: nil) } class func showImage(image: UIImage, status: String, maskType: ProgressHUDMaskType?){ var existingMaskType: ProgressHUDMaskType? = nil if let maskType = maskType { existingMaskType = sharedView!.defaultMaskType setDefaultMaskType(maskType) } let displayInterval = displayDuration(status) sharedView!.showImage(image, status: status, duration: displayInterval) if let existingMaskType = existingMaskType{ setDefaultMaskType(existingMaskType) } } class func popActivity(){ if(sharedView!.activityCount > 0){ sharedView!.activityCount -= 1 } if(sharedView!.activityCount == 0){ sharedView!.dismiss() } } class func dismiss(delay: NSTimeInterval){ if(isVisible()){ sharedView!.dismissWithDelay(delay) } } class func dismiss(){ dismiss(0) } class func isVisible() -> Bool{ return Float(sharedView!.alpha) > Float(0.99) } class func displayDuration(text: String) -> NSTimeInterval{ let durations: [Double] = [Double(text.characters.count) * 0.06 + 0.5, sharedView!.minimumDismissTimeInterval] if let duration = durations.minElement() { return duration } else{ return 0 } } }
mit
b0b23518c8b5c73b4ec99fb7f1cfcc49
23.107884
112
0.75383
4.073633
false
false
false
false
DaftMobile/ios4beginners_2017
Class 4/Networking.playground/Pages/ErrorHandling.xcplaygroundpage/Contents.swift
1
1381
//: [Previous](@previous) import Foundation enum VendingMachineError: Error { case invalidSelection case insufficientFunds(coinsNeeded: Int) case outOfStock } struct Item { var price: Int var count: Int } extension Item: CustomDebugStringConvertible { var debugDescription: String { return "ITEM[\(count)]: \(price)" } } class VendingMachine { private var inventory = [ "Candy Bar": Item(price: 12, count: 7), "Chips": Item(price: 10, count: 4), "Pretzels": Item(price: 7, count: 11) ] private(set)var coinsDeposited = 0 func deposit(coins: Int = 1) { coinsDeposited += coins } func vend(itemNamed name: String) throws -> Item { guard let item = inventory[name] else { throw VendingMachineError.invalidSelection } guard item.count > 0 else { throw VendingMachineError.outOfStock } guard item.price <= coinsDeposited else { throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited) } coinsDeposited -= item.price var newItem = item newItem.count -= 1 inventory[name] = newItem return Item(price: item.price, count: 1) } } let vendingMachine = VendingMachine() //TODO: Deposit some coins //vendingMachine.deposit(coins: ) do { // TODO: Try vending here } catch { // TODO: Handle errors here } //TODO: Try using the `try?` and `try!` operators and see what comes back //: [Next](@next)
apache-2.0
6e7f980b3ae8b7bcf7be06001a157665
19.61194
88
0.703838
3.531969
false
false
false
false
hilen/TimedSilver
Sources/UIKit/UIScrollView+TSPage.swift
3
2224
// // UIScrollView+TSPage.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 8/10/16. // Copyright © 2016 Hilen. All rights reserved. // import UIKit extension UIScrollView { /// All pages public var ts_pages: Int { get { let pages = Int(self.contentSize.width / self.frame.size.width); return pages } } /// The current page public var ts_currentPage:Int { get { let pages = Float(self.contentSize.width / self.frame.size.width); let scrollPercent = Float(self.ts_scrollPercent) let currentPage = roundf((pages-1)*scrollPercent) return Int(currentPage) } } /// UIScrollView scroll percent public var ts_scrollPercent: CGFloat { get { let width = self.contentSize.width - self.frame.size.width let scrollPercent = self.contentOffset.x / width return scrollPercent } } /** Set the horizontal UIScrollView to specified page - parameter page: Page number - parameter animated: Animated */ public func ts_setPageX(_ page: Int, animated: Bool? = nil) { let pageWidth = self.frame.size.width; let offsetY = self.contentOffset.y; let offsetX = CGFloat(page) * pageWidth; let offset = CGPoint(x: offsetX, y: offsetY); if animated == nil { self.setContentOffset(offset, animated: false) } else { self.setContentOffset(offset, animated: animated!) } } /** Set the vertical UIScrollView to specified page - parameter page: Page number - parameter animated: Animated */ public func ts_setPageY(_ page: Int, animated: Bool? = nil) { let pageHeight = self.frame.size.height; let offsetX = self.contentOffset.x; let offsetY = CGFloat(page) * pageHeight; let offset = CGPoint(x: offsetX, y: offsetY); if animated == nil { self.setContentOffset(offset, animated: false) } else { self.setContentOffset(offset, animated: animated!) } } }
mit
b2aab949d218046a537612dd493eea22
27.87013
78
0.587494
4.419483
false
false
false
false
haskellswift/swift-package-manager
Sources/PackageModel/Package.swift
2
4245
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ import Basic import Utility // Re-export Version from PackageModel, since it is a key part of the model. @_exported import struct Utility.Version /// The basic package representation. /// /// The package manager conceptually works with five different kinds of /// packages, of which this is only one: /// /// 1. Informally, the repository containing a package can be thought of in some /// sense as the "package". However, this isn't accurate, because the actual /// Package is derived from its manifest, a Package only actually exists at a /// particular repository revision (typically a tag). We also may eventually /// want to support multiple packages within a single repository. /// /// 2. The `PackageDescription.Package` as defined inside a manifest is a /// declarative specification for (part of) the package but not the object that /// the package manager itself is typically working with internally. Rather, /// that specification is primarily used to load the package (see the /// `PackageLoading` module). /// /// 3. A loaded `PackageModel.Manifest` is an abstract representation of a /// package, and is used during package dependency resolution. It contains the /// loaded PackageDescription and information necessary for dependency /// resolution, but nothing else. /// /// 4. A loaded `PackageModel.Package` which has had dependencies loaded and /// resolved. This is the result after `Get.get()`. /// /// 5. A loaded package, as in #4, for which the modules have also been /// loaded. There is not currently a data structure for this, but it is the /// result after `PackageLoading.transmute()`. public final class Package { /// The manifest describing the package. public let manifest: Manifest /// The local path of the package. public let path: AbsolutePath /// The name of the package. public var name: String { return manifest.package.name } /// The URL the package was loaded from. // // FIXME: This probably doesn't belong here... // // FIXME: Eliminate this method forward. public var url: String { return manifest.url } /// The version this package was loaded from, if known. // // FIXME: Eliminate this method forward. public var version: Version? { return manifest.version } /// The modules contained in the package. public let modules: [Module] /// The test modules contained in the package. // // FIXME: Should these just be merged with the regular modules? public let testModules: [Module] /// The products produced by the package. public let products: [Product] /// The resolved dependencies of the package. /// /// This value is only available once package loading is complete. public var dependencies: [Package] = [] public init(manifest: Manifest, path: AbsolutePath, modules: [Module], testModules: [Module], products: [Product]) { self.manifest = manifest self.path = path self.modules = modules self.testModules = testModules self.products = products } public enum Error: Swift.Error, Equatable { case noManifest(String) case noOrigin(String) } } extension Package: CustomStringConvertible { public var description: String { return name } } extension Package: Hashable, Equatable { public var hashValue: Int { return ObjectIdentifier(self).hashValue } } public func ==(lhs: Package, rhs: Package) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } public func ==(lhs: Package.Error, rhs: Package.Error) -> Bool { switch (lhs, rhs) { case let (.noManifest(lhs), .noManifest(rhs)): return lhs == rhs case (.noManifest, _): return false case let (.noOrigin(lhs), .noOrigin(rhs)): return lhs == rhs case (.noOrigin, _): return false } }
apache-2.0
b4dc4d9df34c99ea5d6f0efb78176dc8
32.164063
120
0.687633
4.515957
false
false
false
false
CassiusPacheco/sweettrex
Sources/App/Helpers/URLSession.swift
1
1140
// // URLSession.swift // App // // Created by Cassius Pacheco on 16/10/17. // import Foundation extension URLSession { func data(with request: URLRequest) throws -> (data: Data, response: HTTPURLResponse) { var error: Error? var result: (Data, HTTPURLResponse)? let semaphore = DispatchSemaphore(value: 0) let task = self.dataTask(with: request, completionHandler: { data, response, _error in if let data = data, let response = response as? HTTPURLResponse { result = (data: data, response: response) } else { error = _error } semaphore.signal() }) task.resume() semaphore.wait() if let error = error { throw error } else if let result = result { return result } else { fatalError("There's been a major issue in the URLSession extension") } } }
mit
aa44fd28cd838b2e5f16926903d5adbc
22.265306
94
0.473684
5.327103
false
false
false
false
tensorflow/swift-models
Examples/Custom-CIFAR10/main.swift
1
2411
// Copyright 2019 The TensorFlow 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 Datasets import TensorFlow let batchSize = 100 let dataset = CIFAR10(batchSize: batchSize) var model = KerasModel() let optimizer = RMSProp(for: model, learningRate: 0.0001, decay: 1e-6) print("Starting training...") for (epoch, epochBatches) in dataset.training.prefix(100).enumerated() { Context.local.learningPhase = .training var trainingLossSum: Float = 0 var trainingBatchCount = 0 for batch in epochBatches { let (images, labels) = (batch.data, batch.label) let (loss, gradients) = valueWithGradient(at: model) { model -> Tensor<Float> in let logits = model(images) return softmaxCrossEntropy(logits: logits, labels: labels) } trainingLossSum += loss.scalarized() trainingBatchCount += 1 optimizer.update(&model, along: gradients) } Context.local.learningPhase = .inference var testLossSum: Float = 0 var testBatchCount = 0 var correctGuessCount = 0 var totalGuessCount = 0 for batch in dataset.validation { let (images, labels) = (batch.data, batch.label) let logits = model(images) testLossSum += softmaxCrossEntropy(logits: logits, labels: labels).scalarized() testBatchCount += 1 let correctPredictions = logits.argmax(squeezingAxis: 1) .== labels correctGuessCount = correctGuessCount + Int( Tensor<Int32>(correctPredictions).sum().scalarized()) totalGuessCount = totalGuessCount + batchSize } let accuracy = Float(correctGuessCount) / Float(totalGuessCount) print( """ [Epoch \(epoch)] \ Accuracy: \(correctGuessCount)/\(totalGuessCount) (\(accuracy)) \ Loss: \(testLossSum / Float(testBatchCount)) """ ) }
apache-2.0
8548666ffe84854b3d6e9a2eba13ee3d
35
88
0.676068
4.336331
false
true
false
false
khizkhiz/swift
test/1_stdlib/Reflection_objc.swift
2
7910
// RUN: rm -rf %t && mkdir %t // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/a.out // RUN: %S/timeout.sh 360 %target-run %t/a.out %S/Inputs/shuffle.jpg | FileCheck %s // REQUIRES: executable_test // FIXME: timeout wrapper is necessary because the ASan test runs for hours // // DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift. // // XFAIL: linux import Swift import Foundation #if os(OSX) import AppKit typealias OSImage = NSImage typealias OSColor = NSColor typealias OSBezierPath = NSBezierPath #endif #if os(iOS) || os(tvOS) || os(watchOS) import UIKit typealias OSImage = UIImage typealias OSColor = UIColor typealias OSBezierPath = UIBezierPath #endif // Check ObjC mirror implementation. // CHECK-LABEL: ObjC: print("ObjC:") // CHECK-NEXT: <NSObject: {{0x[0-9a-f]+}}> dump(NSObject()) // CHECK-LABEL: ObjC subclass: print("ObjC subclass:") // CHECK-NEXT: woozle wuzzle dump("woozle wuzzle" as NSString) // Test a mixed Swift-ObjC hierarchy. class NSGood : NSObject { let x: Int = 22 } class NSBetter : NSGood { let y: String = "333" } // CHECK-LABEL: Swift ObjC subclass: // CHECK-NEXT: <Reflection.NSBetter: {{0x[0-9a-f]+}}> #0 // CHECK-NEXT: super: Reflection.NSGood // CHECK-NEXT: super: NSObject print("Swift ObjC subclass:") dump(NSBetter()) // CHECK-LABEL: ObjC quick look objects: print("ObjC quick look objects:") // CHECK-LABEL: ObjC enums: print("ObjC enums:") // CHECK-NEXT: We cannot reflect NSComparisonResult yet print("We cannot reflect \(NSComparisonResult.orderedAscending) yet") // Don't crash when introspecting framework types such as NSURL. // <rdar://problem/16592777> // CHECK-LABEL: NSURL: // CHECK-NEXT: file:///Volumes/ // CHECK-NEXT: - super: NSObject print("NSURL:") dump(NSURL(fileURLWithPath: "/Volumes", isDirectory: true)) // -- Check that quick look Cocoa objects get binned correctly to their // associated enum tag. // CHECK-NEXT: got the expected quick look text switch PlaygroundQuickLook(reflecting: "woozle wuzzle" as NSString) { case .text("woozle wuzzle"): print("got the expected quick look text") case _: print("got something else") } // CHECK-NEXT: foobar let somesubclassofnsstring = ("foo" + "bar") as NSString switch PlaygroundQuickLook(reflecting: somesubclassofnsstring) { case .text(let text): print(text) default: print("not the expected quicklook") } // CHECK-NEXT: got the expected quick look attributed string let astr = NSAttributedString(string: "yizzle pizzle") switch PlaygroundQuickLook(reflecting: astr as NSAttributedString) { case .attributedString(let astr2 as NSAttributedString) where astr === astr2: print("got the expected quick look attributed string") case _: print("got something else") } // CHECK-NEXT: got the expected quick look int switch PlaygroundQuickLook(reflecting: Int.max as NSNumber) { case .int(+Int64(Int.max)): print("got the expected quick look int") case _: print("got something else") } // CHECK-NEXT: got the expected quick look uint switch PlaygroundQuickLook(reflecting: NSNumber(unsignedLongLong: UInt64.max)) { case .uInt(UInt64.max): print("got the expected quick look uint") case _: print("got something else") } // CHECK-NEXT: got the expected quick look double switch PlaygroundQuickLook(reflecting: 22.5 as NSNumber) { case .double(22.5): print("got the expected quick look double") case _: print("got something else") } // CHECK-NEXT: got the expected quick look float switch PlaygroundQuickLook(reflecting: Float32(1.25)) { case .float(1.25): print("got the expected quick look float") case _: print("got something else") } // CHECK-NEXT: got the expected quick look image // CHECK-NEXT: got the expected quick look color // CHECK-NEXT: got the expected quick look bezier path let image = OSImage(contentsOfFile:Process.arguments[1])! switch PlaygroundQuickLook(reflecting: image) { case .image(let image2 as OSImage) where image === image2: print("got the expected quick look image") case _: print("got something else") } let color = OSColor.black() switch PlaygroundQuickLook(reflecting: color) { case .color(let color2 as OSColor) where color === color2: print("got the expected quick look color") case _: print("got something else") } let path = OSBezierPath() switch PlaygroundQuickLook(reflecting: path) { case .bezierPath(let path2 as OSBezierPath) where path === path2: print("got the expected quick look bezier path") case _: print("got something else") } // CHECK-LABEL: Reflecting NSArray: // CHECK-NEXT: [ 1 2 3 4 5 ] print("Reflecting NSArray:") let intNSArray : NSArray = [1 as NSNumber,2 as NSNumber,3 as NSNumber,4 as NSNumber,5 as NSNumber] let arrayMirror = Mirror(reflecting: intNSArray) var buffer = "[ " for i in arrayMirror.children { buffer += "\(i.1) " } buffer += "]" print(buffer) // CHECK-LABEL: Reflecting NSSet: // CHECK-NEXT: NSSet reflection working fine print("Reflecting NSSet:") let numset = NSSet(objects: 1,2,3,4) let numsetMirror = Mirror(reflecting: numset) var numsetNumbers = Set<Int>() for i in numsetMirror.children { if let number = i.1 as? Int { numsetNumbers.insert(number) } } if numsetNumbers == Set([1, 2, 3, 4]) { print("NSSet reflection working fine") } else { print("NSSet reflection broken: here are the numbers we got: \(numsetNumbers)") } // CHECK-NEXT: (3.0, 6.0) // CHECK-NEXT: x: 3.0 // CHECK-NEXT: y: 6.0 dump(CGPoint(x: 3,y: 6)) // CHECK-NEXT: (30.0, 60.0) // CHECK-NEXT: width: 30.0 // CHECK-NEXT: height: 60.0 dump(CGSize(width: 30, height: 60)) // CHECK-NEXT: (50.0, 60.0, 100.0, 150.0) // CHECK-NEXT: origin: (50.0, 60.0) // CHECK-NEXT: x: 50.0 // CHECK-NEXT: y: 60.0 // CHECK-NEXT: size: (100.0, 150.0) // CHECK-NEXT: width: 100.0 // CHECK-NEXT: height: 150.0 dump(CGRect(x: 50, y: 60, width: 100, height: 150)) // rdar://problem/18513769 -- Make sure that QuickLookObject lookup correctly // manages memory. @objc class CanaryBase { deinit { print("\(self.dynamicType) overboard") } required init() { } } var CanaryHandle = false class IsDebugQLO : CanaryBase, CustomStringConvertible { @objc var description: String { return "I'm a QLO" } } class HasDebugQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { return IsDebugQLO() } } class HasNumberQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let number = NSNumber(integer: 97210) return number } } class HasAttributedQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSAttributedString(string: "attributed string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } class HasStringQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSString(string: "plain string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } func testQLO<T : CanaryBase>(type: T.Type) { autoreleasepool { _ = PlaygroundQuickLook(reflecting: type.init()) } } testQLO(IsDebugQLO.self) // CHECK-NEXT: IsDebugQLO overboard testQLO(HasDebugQLO.self) // CHECK-NEXT: HasDebugQLO overboard // CHECK-NEXT: IsDebugQLO overboard testQLO(HasNumberQLO.self) // CHECK-NEXT: HasNumberQLO overboard // TODO: tagged numbers are immortal, so we can't reliably check for // cleanup here testQLO(HasAttributedQLO.self) // CHECK-NEXT: HasAttributedQLO overboard // CHECK-NEXT: CanaryBase overboard testQLO(HasStringQLO.self) // CHECK-NEXT: HasStringQLO overboard // CHECK-NEXT: CanaryBase overboard // CHECK-LABEL: and now our song is done print("and now our song is done")
apache-2.0
bb5c683fdacb8eaa98b5c59a758ba7cf
26.370242
125
0.707585
3.5281
false
false
false
false
hikelee/cinema
Sources/App/Models/Hall.swift
1
3051
import Vapor import Fluent import HTTP import Foundation final class Hall: ChannelBasedModel { static var states:[Int:String]=[1:"空闲",2:"待客中",3:"放映中",4:"待清扫",5:"清扫中"] static var entity: String { return "c_hall" } var id: Node? var projectorId: Node? var channelId: Node?//冗余字段 var name: String? var state: Int = 0 var capacity : Int = 0 var price : Int = 0 var exists: Bool = false //used in fluent init(node: Node, in context: Context) throws { id = node["id"] projectorId = node["projector_id"] channelId = node["channel_id"] name = node["name"]?.string state = node["state"]?.int ?? 0 capacity = node["capacity"]?.int ?? 0 price = node["price"]?.int ?? 0 } func makeNode() throws->Node { return try Node( node:[ "id": id, "projector_id": projectorId, "channel_id": channelId, "name": name, "state": state, "capacity": capacity, "price": price, ]) } func makeLeafNode() throws -> Node { var node = try makeNode() node["projector"]=try Projector.node(projectorId) node["channel"]=try Channel.node(channelId) node["state_name"] = try Hall.states.node(state) return node } func validate(isCreate: Bool) throws -> [String:String] { var result:[String:String]=[:] if (projectorId?.int ?? 0) == 0 { result["projector_id"] = "必选项"; }else if try Projector.load(projectorId) == nil { result["projector_id"] = "找不到所选的投影仪" }else if isCreate { if try Hall.query().filter("projector_id",projectorId?.int ?? 0).first() != nil{ result["projector_id"] = "此投影仪已经关联其它影厅" } } if name?.isEmpty ?? true{result["name"]="必填项"} if state == 0 {result["state"]="必填项"} if capacity == 0 {result["capacity"]="必填项"} if price == 0 {result["price"]="必填项"} return result } } extension Hall { static func orders(channelId:Int = 0,hallId:Int = 0) throws -> [Order]{ let time = Date().string() var sql = "select * from c_order " + " where start_time < '\(time)' and end_time > '\(time)' " + " and state in ('ongoing','inline','stopping')" if channelId>0 { sql += " and channel_id = \(channelId)" } if hallId>0 { sql += " and hall_id = \(hallId)" } sql += " order by id desc" log(sql) if let rows = try Hall.database?.driver.raw(sql,[]),let array = rows.nodeArray { return try array.map{try Order(node:$0)} } return [] } func order() throws -> Order?{ if let id = id?.int,id>0 { return try Hall.orders(hallId:id).first } return nil } }
mit
afd17ad41683047bf237feb44a4e2873
29.340206
92
0.521577
3.827048
false
false
false
false
yanyuqingshi/ios-charts
Charts/Classes/Components/ChartAxisBase.swift
1
3005
// // ChartAxisBase.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartAxisBase: ChartComponentBase { public var labelFont = UIFont.systemFontOfSize(10.0) public var labelTextColor = UIColor.blackColor() public var axisLineColor = UIColor.grayColor() public var axisLineWidth = CGFloat(0.5) public var axisLineDashPhase = CGFloat(0.0) public var axisLineDashLengths: [CGFloat]! public var gridColor = UIColor.grayColor().colorWithAlphaComponent(0.9) public var gridLineWidth = CGFloat(0.5) public var gridLineDashPhase = CGFloat(0.0) public var gridLineDashLengths: [CGFloat]! public var drawGridLinesEnabled = true public var drawAxisLineEnabled = true /// flag that indicates of the labels of this axis should be drawn or not public var drawLabelsEnabled = true /// Sets the used x-axis offset for the labels on this axis. public var xOffset = CGFloat(5.0) /// Sets the used y-axis offset for the labels on this axis. public var yOffset = CGFloat(5.0) /// array of limitlines that can be set for the axis private var _limitLines = [ChartLimitLine]() /// Are the LimitLines drawn behind the data or in front of the data? /// :default: false public var drawLimitLinesBehindDataEnabled = false public override init() { super.init(); } public func getLongestLabel() -> String { fatalError("getLongestLabel() cannot be called on ChartAxisBase"); } public var isDrawGridLinesEnabled: Bool { return drawGridLinesEnabled; } public var isDrawAxisLineEnabled: Bool { return drawAxisLineEnabled; } public var isDrawLabelsEnabled: Bool { return drawLabelsEnabled; } /// Are the LimitLines drawn behind the data or in front of the data? /// :default: false public var isDrawLimitLinesBehindDataEnabled: Bool { return drawLimitLinesBehindDataEnabled; } /// Adds a new ChartLimitLine to this axis. public func addLimitLine(line: ChartLimitLine) { _limitLines.append(line); } /// Removes the specified ChartLimitLine from the axis. public func removeLimitLine(line: ChartLimitLine) { for (var i = 0; i < _limitLines.count; i++) { if (_limitLines[i] === line) { _limitLines.removeAtIndex(i); return; } } } /// Removes all LimitLines from the axis. public func removeAllLimitLines() { _limitLines.removeAll(keepCapacity: false); } /// Returns the LimitLines of this axis. public var limitLines : [ChartLimitLine] { return _limitLines; } }
apache-2.0
d0f1205d9e4d91d39ad2e090a9550105
28.470588
98
0.655241
4.815705
false
false
false
false
rokuz/omim
iphone/Maps/Bookmarks/Categories/Sharing/Tags/TagsCollectionViewLayout.swift
1
4400
final class TagsCollectionViewLayout: UICollectionViewLayout { private var headersCache: [IndexPath : UICollectionViewLayoutAttributes] = [:] private var cellsCache: [IndexPath : UICollectionViewLayoutAttributes] = [:] fileprivate var contentHeight: CGFloat = 0 fileprivate var contentWidth: CGFloat { guard let collectionView = collectionView else { return 0 } let insets = collectionView.contentInset return collectionView.bounds.width - (insets.left + insets.right) } override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } @IBInspectable var itemHeight: CGFloat = 50 @IBInspectable var itemWidth: CGFloat = 50 @IBInspectable var lineSpacing: CGFloat = 10 @IBInspectable var elementsSpacing: CGFloat = 10 @IBInspectable var showHeaders: Bool = true override func prepare() { super.prepare() guard let collectionView = collectionView else { return } var xOffset: CGFloat = 0 var yOffset: CGFloat = 0 contentHeight = 0 var lastItemHeight: CGFloat = 0 for section in 0 ..< collectionView.numberOfSections { xOffset = 0 yOffset += (section == 0) ? 0 : lastItemHeight + 2 * lineSpacing let indexPath = IndexPath(item: 0, section: section) if showHeaders { let headerSize = headersCache[indexPath]?.size ?? CGSize(width: contentWidth, height: itemHeight) let frame = CGRect(x: 0, y: yOffset, width: headerSize.width, height: headerSize.height) let attr = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: indexPath) attr.frame = frame headersCache[indexPath] = attr yOffset += headerSize.height + lineSpacing } for item in 0 ..< collectionView.numberOfItems(inSection: section) { let indexPath = IndexPath(item: item, section: section) let itemSize = cellsCache[indexPath]?.size ?? CGSize(width: itemWidth, height: itemHeight) if xOffset + itemSize.width > contentWidth { xOffset = 0 yOffset = yOffset + lineSpacing + lastItemHeight } let frame = CGRect(x: xOffset, y: yOffset, width: itemSize.width, height: itemSize.height) let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath) attr.frame = frame cellsCache[indexPath] = attr xOffset += itemSize.width + elementsSpacing lastItemHeight = itemSize.height contentHeight = max(contentHeight, frame.maxY) } } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]() for (_, attributes) in headersCache { if attributes.frame.intersects(rect) { visibleLayoutAttributes.append(attributes) } } for (_, attributes) in cellsCache { if attributes.frame.intersects(rect) { visibleLayoutAttributes.append(attributes) } } return visibleLayoutAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cellsCache[indexPath] } override public func shouldInvalidateLayout(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool { //dont validate layout if original width already equals to contentWidth - it's the best deal we can offer to cell if preferredAttributes.size.height != originalAttributes.size.height || (preferredAttributes.size.width != originalAttributes.size.width && originalAttributes.size.width < contentWidth) { if preferredAttributes.representedElementKind == UICollectionView.elementKindSectionHeader { headersCache[originalAttributes.indexPath]?.size = preferredAttributes.size } else { cellsCache[originalAttributes.indexPath]?.size = CGSize(width: min(preferredAttributes.size.width, contentWidth), height: preferredAttributes.size.height) } return true } return false } }
apache-2.0
30e001a4187392baf99d72bb85f25ad2
38.285714
139
0.684545
5.736636
false
false
false
false
towlebooth/watchos-sabbatical-countdown-part2
SabbaticalCountdown2/EditViewController.swift
1
1441
// // EditViewController.swift // SabbaticalCountdown2 // // Created by Chad Towle on 12/5/15. // Copyright © 2015 Intertech. All rights reserved. // import UIKit class EditViewController: UIViewController { @IBOutlet weak var startDatePicker: UIDatePicker! override func viewDidLoad() { // get value from user defaults and set datepicker let defaults = NSUserDefaults.standardUserDefaults() if let dateString = defaults.stringForKey("dateKey") { let userCalendar = NSCalendar.currentCalendar() let dateFormat = NSDateFormatter() dateFormat.calendar = userCalendar dateFormat.dateFormat = "yyyy-MM-dd" startDatePicker.date = dateFormat.dateFromString(dateString)! } super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { print("prepForSegue") // send values to display view controller if let destination = segue.destinationViewController as? DisplayViewController { destination.savedDate = startDatePicker.date print("segue!") } } }
mit
f218e61462e6871da5e6c0c0ce9addce
29
88
0.646528
5.603113
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/ProductVariantConnection.swift
1
5272
// // ProductVariantConnection.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. 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 extension Storefront { /// An auto-generated type for paginating through multiple ProductVariants. open class ProductVariantConnectionQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = ProductVariantConnection /// A list of edges. @discardableResult open func edges(alias: String? = nil, _ subfields: (ProductVariantEdgeQuery) -> Void) -> ProductVariantConnectionQuery { let subquery = ProductVariantEdgeQuery() subfields(subquery) addField(field: "edges", aliasSuffix: alias, subfields: subquery) return self } /// A list of the nodes contained in ProductVariantEdge. @discardableResult open func nodes(alias: String? = nil, _ subfields: (ProductVariantQuery) -> Void) -> ProductVariantConnectionQuery { let subquery = ProductVariantQuery() subfields(subquery) addField(field: "nodes", aliasSuffix: alias, subfields: subquery) return self } /// Information to aid in pagination. @discardableResult open func pageInfo(alias: String? = nil, _ subfields: (PageInfoQuery) -> Void) -> ProductVariantConnectionQuery { let subquery = PageInfoQuery() subfields(subquery) addField(field: "pageInfo", aliasSuffix: alias, subfields: subquery) return self } } /// An auto-generated type for paginating through multiple ProductVariants. open class ProductVariantConnection: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = ProductVariantConnectionQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "edges": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: ProductVariantConnection.self, field: fieldName, value: fieldValue) } return try value.map { return try ProductVariantEdge(fields: $0) } case "nodes": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: ProductVariantConnection.self, field: fieldName, value: fieldValue) } return try value.map { return try ProductVariant(fields: $0) } case "pageInfo": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: ProductVariantConnection.self, field: fieldName, value: fieldValue) } return try PageInfo(fields: value) default: throw SchemaViolationError(type: ProductVariantConnection.self, field: fieldName, value: fieldValue) } } /// A list of edges. open var edges: [Storefront.ProductVariantEdge] { return internalGetEdges() } func internalGetEdges(alias: String? = nil) -> [Storefront.ProductVariantEdge] { return field(field: "edges", aliasSuffix: alias) as! [Storefront.ProductVariantEdge] } /// A list of the nodes contained in ProductVariantEdge. open var nodes: [Storefront.ProductVariant] { return internalGetNodes() } func internalGetNodes(alias: String? = nil) -> [Storefront.ProductVariant] { return field(field: "nodes", aliasSuffix: alias) as! [Storefront.ProductVariant] } /// Information to aid in pagination. open var pageInfo: Storefront.PageInfo { return internalGetPageInfo() } func internalGetPageInfo(alias: String? = nil) -> Storefront.PageInfo { return field(field: "pageInfo", aliasSuffix: alias) as! Storefront.PageInfo } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "edges": internalGetEdges().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "nodes": internalGetNodes().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "pageInfo": response.append(internalGetPageInfo()) response.append(contentsOf: internalGetPageInfo().childResponseObjectMap()) default: break } } return response } } }
mit
48b53177a11290f34be338c6ce6ff089
34.38255
122
0.724203
4.268826
false
false
false
false
ChrisMash/Fieldbook-SwiftSDK
Pod/Classes/FieldbookSDK.swift
1
21921
// // FieldbookSDK.swift // Fieldbook-SwiftSDK // // Created by Chris Mash on 22/02/2016. // Copyright © 2016 Chris Mash. All rights reserved. // import UIKit public class FieldbookSDK : NSObject { private static let SDK_ERROR_DOMAIN = "FieldbookSDK" private static let API_BASE_URL = "https://api.fieldbook.com/v1/" private static let CODELET_BASE_URL = "https://fieldbookcode.com/" private static var username : String? private static var password : String? private enum RequestType { case Post case Get case Delete case Patch } /// Types of error specific to the SDK public enum FieldbookSDKError : Int { case UnexpectedAPIResponse case BadQueryURL case APIError } /// Set the authentication details (key & secret / username & password) /// Necessary if you wish to add/update/delete items or access a private book /// /// - parameters: /// - key: key / username from API-access on Fieldbook website /// - secret: secret / password from API-access on Fieldbook website public static func setAuthDetails( key: String, secret: String ) { username = key password = secret } /// Get all the items at the specified path /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - completion: block called upon completion of the query, with either an array of items or an error public static func getItems( query: String, completion: (items: NSArray?, error: NSError?) -> Void ) { getItems( query, limit: 0, offset: 0, filters: nil, include: nil, exclude: nil) { (items, more, error) -> Void in completion( items: items, error: error ) } } /// Get a subset of the items at the specified path (book_id/sheet_name) /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - limit: the max number of items to be returned /// - offset: the number of items to skip, for paging /// - filters: key/value pairs to filter the results by, of the form "name=amy". Case-sensitive. /// - include: comma-separated string of fields that should be included in the returned items. Set to nil to get everything /// - exclude: comma-separated string of fields that should be excluded in the returned items. Set to nil to get everything /// - completion: block called upon completion of the query, with either an array of items or an error and a flag specifying whethere there are more items that can be requested public static func getItems( query: String, limit: UInt, offset: UInt, filters: NSArray?, include: String?, exclude: String?, completion: (items: NSArray?, more: Bool, error: NSError?) -> Void ) { var parameters = "" if limit > 0 { parameters = "?limit=\(limit)&offset=\(offset)" } if let unwrappedFilters = filters { for filter in unwrappedFilters { // The filter could have spaces in it so let's percent encode it so it forms a URL correctly if let encodedFilter = filter.stringByAddingPercentEscapesUsingEncoding( NSUTF8StringEncoding ) { if parameters.characters.count == 0 { parameters = "?" } else { parameters += "&" } parameters += "\(encodedFilter)" } } } if let unwrappedInclude = include { if parameters.characters.count == 0 { parameters = "?" } else { parameters += "&" } parameters += "include=\(unwrappedInclude)" } if let unwrappedExclude = exclude { if parameters.characters.count == 0 { parameters = "?" } else { parameters += "&" } parameters += "exclude=\(unwrappedExclude)" } // We're going to get a GET request here of the form // https://api.fieldbook.com/v1/56cb45f67753cf030003e42b/sheet_1/?limit=5&offset=0 let request = requestFor( API_BASE_URL, additionalPath: query + parameters, type: .Get, data: nil ) makeRequest( request, completion: { (json: AnyObject?, error: NSError?) -> Void in if error != nil { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( items: nil, more: false, error: error ) }) } else if let unwrappedJson = json { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ // Depending on whether we applied any page limits or requested the full set of items // we'll get a different response structure if let unwrappedItems = unwrappedJson[ "items" ] { // Requested paged results let items = unwrappedItems as! NSArray let count = unwrappedJson[ "count" ]! as! NSNumber let received = Int( offset ) + items.count completion( items: items, more: received < count.integerValue, error: nil ) } else { // Requested full results completion( items: unwrappedJson as? NSArray, more: false, error: nil ) } }) } else { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( items: nil, more: false, error: unexpectedResponseError() ) }) } }) } /// Get a single item with the specified path (book_id/sheet_name) and id /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - id: the id number of the item to return /// - completion: block called upon completion of the query, with either the item or an error public static func getItem( query: String, id: NSNumber, completion: (item: NSDictionary?, error: NSError?) -> Void ) { getItem( query, id: id, include: nil, exclude: nil, completion: completion ) } /// Get a single item with the specified path (book_id/sheet_name) and id /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - id: the id number of the item to return /// - include: comma-separated string of fields of the item that should be included. Set to nil to get everything /// - exclude: comma-separated string of fields of the item that should be excluded. Set to nil to get everything /// - completion: block called upon completion of the query, with either the item or an error public static func getItem( query: String, id: NSNumber, include: NSString?, exclude: NSString?, completion: (item: NSDictionary?, error: NSError?) -> Void ) { var parameters = "" if let unwrappedInclude = include { if parameters.characters.count == 0 { parameters = "?" } else { parameters += "&" } parameters += "include=\(unwrappedInclude)" } if let unwrappedExclude = exclude { if parameters.characters.count == 0 { parameters = "?" } else { parameters += "&" } parameters += "exclude=\(unwrappedExclude)" } // We're going to get a GET request here of the form // https://api.fieldbook.com/v1/56cb45f67753cf030003e42b/sheet_1/1 let request = requestFor( API_BASE_URL, additionalPath: query + "/\(id)" + parameters, type: .Get, data: nil ) makeRequest( request, completion: { (json: AnyObject?, error: NSError?) -> Void in if error != nil { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: nil, error: error ) }) } else if let unwrappedDict = json as? NSDictionary { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: unwrappedDict, error: nil ) }) } else { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: nil, error: unexpectedResponseError() ) }) } }) } /// Add a single item to the specified path (book_id/sheet_name) /// Do not include an 'id' field in the item as Fieldbook will generate that itself (your sheet should NOT have an 'id' column as it will cause a clash) /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - item: the fields of the item to be added /// - completion: block called upon completion of the query, with either the newly added item or an error public static func addToList( query: String, item: NSDictionary, completion: (item: NSDictionary?, error: NSError?) -> Void ) { // We're going to get a POST request here of the form // https://api.fieldbook.com/v1/56cb45f67753cf030003e42b/sheet_1/ let request = requestFor( API_BASE_URL, additionalPath: query, type: .Post, data: item ) makeRequest( request, completion: { (json: AnyObject?, error: NSError?) -> Void in if error != nil { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: nil, error: error ) }) } else if let unwrappedDict = json as? NSDictionary { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: unwrappedDict, error: nil ) }) } else { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: nil, error: unexpectedResponseError() ) }) } }) } /// Update an item at the specified path (book_id/sheet_name) /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - id: the id number of the item to be updated /// - item: the fields of the item to be updated (don't need to include fileds that don't need to change) /// - completion: block called upon completion of the query, with either the newly updated item or an error public static func updateItem( query: String, id: NSNumber, item: NSDictionary, completion: (item: NSDictionary?, error: NSError?) -> Void ) { // We're going to get a PATCH request here of the form // https://api.fieldbook.com/v1/56cb45f67753cf030003e42b/sheet_1/1 let request = requestFor( API_BASE_URL, additionalPath: query + "/\(id)", type: .Patch, data: item ) makeRequest( request, completion: { (json: AnyObject?, error: NSError?) -> Void in if error != nil { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: nil, error: error ) }) } else if let unwrappedDict = json as? NSDictionary { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: unwrappedDict, error: nil ) }) } else { // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( item: nil, error: unexpectedResponseError() ) }) } }) } /// Delete an item from the specified path (book_id/sheet_name) /// /// - parameters: /// - query: query path of the form "<book_id>/<sheet_name>" /// - id: the id number of the item to be deleted /// - completion: block called upon completion of the query, with either nil or an error public static func deleteItem( query: String, id: NSNumber, completion: (error: NSError?) -> Void ) { // We're going to get a DELETE request here of the form // https://api.fieldbook.com/v1/56cb45f67753cf030003e42b/sheet_1/1 let request = requestFor( API_BASE_URL, additionalPath: query + "/\(id)", type: .Delete, data: nil ) makeRequest( request, completion: { (json: AnyObject?, error: NSError?) -> Void in // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( error: error ) }) }) } /// Send a query to a Fieldbook Codelet (book_id/codelet_name) /// /// - parameters: /// - query: query path of the form "<book_id>/<codelet_name>" /// - completion: block called upon completion of the query, with either the response or an error public static func queryCodelet( query: String, completion: (response: AnyObject?, error: NSError?) -> Void ) { // We're going to get a GET request here of the form // https://fieldbookcode.com//56cb45f67753cf030003e42b/xyz let request = requestFor( CODELET_BASE_URL, additionalPath: query, type: .Get, data: nil ) makeRequest( request ) { (json : AnyObject?, error: NSError?) -> Void in // Need to make sure we call the completion method on the main thread dispatch_async(dispatch_get_main_queue(),{ completion( response: json, error: error ) }) } } // MARK: - Private methods private static func requestFor( base: String, additionalPath: String, type: RequestType, data: NSDictionary? ) -> NSMutableURLRequest? { // Create a request with the specified path applied to the base URL let url = NSURL( string: base + additionalPath ) if let unwrappedURL = url { let request = NSMutableURLRequest( URL: unwrappedURL ) if type == .Post { request.HTTPMethod = "POST" } else if type == .Delete { request.HTTPMethod = "DELETE" } else if type == .Patch { request.HTTPMethod = "PATCH" } // If there's some data passed in convert it from json to NSData if let unwrappedData = data { request.setValue( "application/json", forHTTPHeaderField: "Content-Type" ) do { request.HTTPBody = try NSJSONSerialization.dataWithJSONObject( unwrappedData, options: [] ) } catch let error as NSError { NSLog( "Error forming json body: %@ from: %@", error, unwrappedData ) } } request.setValue( "application/json", forHTTPHeaderField: "Accept" ) // If we've got authentication details then put them in the request if let unwrappedUsername = username, let unwrappedPassword = password { // Basic authentication with base64 encoding let auth = "Basic \(base64( unwrappedUsername + ":" + unwrappedPassword ))" request.setValue( auth, forHTTPHeaderField: "Authorization" ) } return request } return nil } private static func makeRequest( request: NSURLRequest?, completion: (json: AnyObject?, error: NSError?) -> Void ) { if let unwrappedRequest = request { let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration() ) let task = session.dataTaskWithRequest( unwrappedRequest ) { (data, response, error) -> Void in /*var dataString : String? if let unwrappedData = data { dataString = String( data: unwrappedData, encoding: NSUTF8StringEncoding ) } print("Response: \(response)") print("Error: \(error)") print("Data: \(dataString)")*/ var webServiceError = error if let httpResponse = response as? NSHTTPURLResponse { if let unwrappedData = data { var json : AnyObject? if unwrappedData.length > 0 { json = convertDataToDictionary( unwrappedData, verbose: true ) } if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 { completion( json: json, error: nil ) return } else { webServiceError = self.formatFieldbookAPIError( httpResponse, json: json ) } } } completion( json: nil, error: webServiceError ) } task.resume() } else { completion( json: nil, error: NSError( domain: SDK_ERROR_DOMAIN, code: FieldbookSDKError.BadQueryURL.rawValue, userInfo: [NSLocalizedDescriptionKey : "Failed to generate query URL. You may have spaces in your query string?"] ) ) } } private static func formatFieldbookAPIError( response: NSHTTPURLResponse, json: AnyObject? ) -> NSError { var message = "No details" if let unwrappedJson = json, let unwrappedMessage = unwrappedJson[ "message" ] as? String { message = unwrappedMessage } return NSError( domain: "FieldbookAPI", code: FieldbookSDKError.APIError.rawValue, userInfo: [ NSLocalizedDescriptionKey : "Unexpected FieldbookAPI error \(response.statusCode): \(message)" ] ) } private static func convertDataToDictionary( data: NSData, verbose: Bool ) -> AnyObject? { do { return try NSJSONSerialization.JSONObjectWithData( data, options: [ .AllowFragments ] ) } catch let error as NSError { if verbose { print( "JSON conversion error: \(error)" ) } } return nil } private static func base64( string: String ) -> String { let utf8str = string.dataUsingEncoding( NSUTF8StringEncoding ) if let base64Encoded = utf8str?.base64EncodedStringWithOptions( NSDataBase64EncodingOptions( rawValue: 0 ) ) { return base64Encoded } return "" } private static func unexpectedResponseError() -> NSError { return NSError( domain: SDK_ERROR_DOMAIN, code: FieldbookSDKError.UnexpectedAPIResponse.rawValue, userInfo: [NSLocalizedDescriptionKey : "Unexpected response from API"] ) } }
mit
96402279af483b565624fdb19a310633
37.79646
240
0.517838
5.315228
false
false
false
false
lemberg/connfa-ios
Pods/SwiftDate/Sources/SwiftDate/DateInRegion/DateInRegion+Components.swift
1
6541
// // DateInRegion+Components.swift // SwiftDate // // Created by Daniele Margutti on 06/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public extension DateInRegion { /// Indicates whether the month is a leap month. public var isLeapMonth: Bool { let calendar = self.region.calendar // Library function for leap contains a bug for Gregorian calendars, implemented workaround if calendar.identifier == Calendar.Identifier.gregorian && self.year > 1582 { guard let range: Range<Int> = calendar.range(of: .day, in: .month, for: self.date) else { return false } return ((range.upperBound - range.lowerBound) == 29) } // For other calendars: return calendar.dateComponents([.day, .month, .year], from: self.date).isLeapMonth! } /// Indicates whether the year is a leap year. public var isLeapYear: Bool { let calendar = self.region.calendar // Library function for leap contains a bug for Gregorian calendars, implemented workaround if calendar.identifier == Calendar.Identifier.gregorian { var newComponents = self.dateComponents newComponents.month = 2 newComponents.day = 10 let testDate = DateInRegion(components: newComponents, region: self.region) return testDate!.isLeapMonth } else if calendar.identifier == Calendar.Identifier.chinese { /// There are 12 or 13 months in each year and 29 or 30 days in each month. /// A 13-month year is a leap year, which meaning more than 376 days is a leap year. return ( self.dateAtStartOf(.year).toUnit(.day, to: self.dateAtEndOf(.year)) > 375 ) } // For other calendars: return calendar.dateComponents([.day, .month, .year], from: self.date).isLeapMonth! } /// Julian day is the continuous count of days since the beginning of /// the Julian Period used primarily by astronomers. public var julianDay: Double { let destRegion = Region(calendar: Calendars.gregorian, zone: Zones.gmt, locale: Locales.english) let utc = self.convertTo(region: destRegion) let year = Double(utc.year) let month = Double(utc.month) let day = Double(utc.day) let hour = Double(utc.hour) + Double(utc.minute) / 60.0 + (Double(utc.second) + Double(utc.nanosecond) / 1e9) / 3600.0 var jd = 367.0 * year - floor( 7.0 * ( year + floor((month + 9.0) / 12.0)) / 4.0 ) jd -= floor( 3.0 * (floor( (year + (month - 9.0) / 7.0) / 100.0 ) + 1.0) / 4.0 ) jd += floor(275.0 * month / 9.0) + day + 1_721_028.5 + hour / 24.0 return jd } /// The Modified Julian Date (MJD) was introduced by the Smithsonian Astrophysical Observatory /// in 1957 to record the orbit of Sputnik via an IBM 704 (36-bit machine) /// and using only 18 bits until August 7, 2576. public var modifiedJulianDay: Double { return self.julianDay - 2_400_000.5 } /// Return elapsed time expressed in given components since the current receiver and a reference date. /// Time is evaluated with the fixed measumerent of each unity. /// /// - Parameters: /// - refDate: reference date (`nil` to use current date in the same region of the receiver) /// - component: time unit to extract. /// - Returns: value public func getInterval(toDate: DateInRegion?, component: Calendar.Component) -> Int64 { let refDate = (toDate ?? self.region.nowInThisRegion()) switch component { case .year: let end = self.calendar.ordinality(of: .year, in: .era, for: refDate.date) let start = self.calendar.ordinality(of: .year, in: .era, for: self.date) return Int64(end! - start!) case .month: let end = self.calendar.ordinality(of: .month, in: .era, for: refDate.date) let start = self.calendar.ordinality(of: .month, in: .era, for: self.date) return Int64(end! - start!) case .day: let end = self.calendar.ordinality(of: .day, in: .era, for: refDate.date) let start = self.calendar.ordinality(of: .day, in: .era, for: self.date) return Int64(end! - start!) case .hour: let interval = refDate.date.timeIntervalSince(self.date) return Int64(interval / 1.hours.timeInterval) case .minute: let interval = refDate.date.timeIntervalSince(self.date) return Int64(interval / 1.minutes.timeInterval) case .second: return Int64(refDate.date.timeIntervalSince(self.date)) case .weekday: let end = self.calendar.ordinality(of: .weekday, in: .era, for: refDate.date) let start = self.calendar.ordinality(of: .weekday, in: .era, for: self.date) return Int64(end! - start!) case .weekdayOrdinal: let end = self.calendar.ordinality(of: .weekdayOrdinal, in: .era, for: refDate.date) let start = self.calendar.ordinality(of: .weekdayOrdinal, in: .era, for: self.date) return Int64(end! - start!) case .weekOfYear: let end = self.calendar.ordinality(of: .weekOfYear, in: .era, for: refDate.date) let start = self.calendar.ordinality(of: .weekOfYear, in: .era, for: self.date) return Int64(end! - start!) default: debugPrint("Passed component cannot be used to extract values using interval() function between two dates. Returning 0.") return 0 } } /// The interval between the receiver and the another parameter. /// If the receiver is earlier than anotherDate, the return value is negative. /// If anotherDate is nil, the results are undefined. /// /// - Parameter date: The date with which to compare the receiver. /// - Returns: time interval between two dates public func timeIntervalSince(_ date: DateInRegion) -> TimeInterval { return self.date.timeIntervalSince(date.date) } /// Extract DateComponents from the difference between two dates. /// /// - Parameter rhs: date to compare /// - Returns: components public func componentsTo(_ rhs: DateInRegion) -> DateComponents { return self.calendar.dateComponents(DateComponents.allComponentsSet, from: rhs.date, to: self.date) } /// Returns the difference between two dates (`date - self`) expressed as date components. /// /// - Parameters: /// - date: reference date as initial date (left operand) /// - components: components to extract, `nil` to use default `DateComponents.allComponentsSet` /// - Returns: extracted date components public func componentsSince(_ date: DateInRegion, components: [Calendar.Component]? = nil) -> DateComponents { if date.calendar != self.calendar { debugPrint("Date has different calendar, results maybe wrong") } let cmps = (components != nil ? Calendar.Component.toSet(components!) : DateComponents.allComponentsSet) return date.calendar.dateComponents(cmps, from: date.date, to: self.date) } }
apache-2.0
852f53ad9abfe2c3d17b2de4a0f4111d
39.875
124
0.705505
3.531317
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/External Apps/HATApplicationsDataRequired.swift
1
1348
// /** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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/ */ // MARK: Struct public struct HATApplicationsDataRequired: HATObject { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `isRolling` in JSON is `rolling` * `bundle` in JSON is `bundle` * `startDate` in JSON is `startDate` * `endDate` in JSON is `endDate` */ private enum CodingKeys: String, CodingKey { case isRolling = "rolling" case bundle = "bundle" case startDate = "startDate" case endDate = "endDate" } // MARK: - Variables /// A flag indicating if the data will be collected in a rolling scenario public var isRolling: Bool = false /// The bundle info definition for this app public var bundle: HATDataDefinition = HATDataDefinition() /// The start date in an ISO format. Optional public var startDate: String? /// The end date in an ISO format. Optional public var endDate: String? }
mpl-2.0
02c07964bb7c85f60ac9c99a5dc89a79
27.680851
77
0.63724
4.160494
false
false
false
false
gkaimakas/ReactiveBluetooth
ReactiveBluetooth/Classes/CBPeripheral/CBPeripheral+DelegateEvent.swift
1
9243
// // CBPeripheral+DelegateEvent.swift // ReactiveCoreBluetooth // // Created by George Kaimakas on 03/03/2018. // import CoreBluetooth extension CBPeripheral { internal enum DelegateEvent { case didUpdateName(peripheral: CBPeripheral) case didReadRSSI(peripheral: CBPeripheral, RSSI: NSNumber, error: Error?) case didDiscoverServices(peripheral: CBPeripheral, error: Error?) case didDiscoverIncludedServices(peripheral: CBPeripheral, service: CBService, error: Error?) case didDiscoverCharacteristics(peripheral: CBPeripheral, service: CBService, error: Error?) case didDiscoverDescriptors(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: Error?) case didUpdateNotificationState(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: Error?) case didWriteValueForCharacteristic(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: Error?) case didWriteValueForDescriptor(peripheral: CBPeripheral, descriptor: CBDescriptor, error: Error?) case didUpdateValueForCharacteristic(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: Error?) case didUpdateValueForDescriptor(peripheral: CBPeripheral, descriptor: CBDescriptor, error: Error?) func filter(peripheral: CBPeripheral) -> Bool { switch self { case .didUpdateName(peripheral: let _peripheral): return peripheral.identifier == _peripheral.identifier case .didReadRSSI(peripheral: let _peripheral, RSSI: _, error: _): return peripheral.identifier == _peripheral.identifier case .didDiscoverServices(peripheral: let _peripheral, error: _): return peripheral.identifier == _peripheral.identifier case .didDiscoverIncludedServices(peripheral: let _peripheral, service: _, error: _): return peripheral.identifier == _peripheral.identifier case .didDiscoverCharacteristics(peripheral: let _peripheral, service: _, error: _): return peripheral.identifier == _peripheral.identifier case .didDiscoverDescriptors(peripheral: let _peripheral, characteristic: _, error: _): return peripheral.identifier == _peripheral.identifier case .didUpdateNotificationState(peripheral: let _peripheral, characteristic: _, error: _): return peripheral.identifier == _peripheral.identifier case .didWriteValueForCharacteristic(peripheral: let _peripheral, characteristic: _, error: _): return peripheral.identifier == _peripheral.identifier case .didWriteValueForDescriptor(peripheral: let _peripheral, descriptor: _, error: _): return peripheral.identifier == _peripheral.identifier case .didUpdateValueForCharacteristic(peripheral: let _peripheral, characteristic: _, error: _): return peripheral.identifier == _peripheral.identifier case .didUpdateValueForDescriptor(peripheral: let _peripheral, descriptor: _, error: _): return peripheral.identifier == _peripheral.identifier } } func filter(service: CBService) -> Bool { return filter(service: service.uuid) } func filter(service: CBUUID) -> Bool { return filter(service: service.uuidString) } func filter(service: String) -> Bool { switch self { case .didDiscoverIncludedServices(peripheral: _, service: let _service, error: _): return service == _service.uuid.uuidString case .didDiscoverCharacteristics(peripheral: _, service: let _service, error: _): return service == _service.uuid.uuidString default: return false } } func filter(characteristic: CBCharacteristic) -> Bool { return filter(characteristic: characteristic.uuid) } func filter(characteristic: CBUUID) -> Bool { return filter(characteristic: characteristic.uuidString) } func filter(characteristic: String) -> Bool { switch self { case .didDiscoverDescriptors(peripheral: _, characteristic: let _characteristic, error: _): return characteristic == _characteristic.uuid.uuidString case .didUpdateNotificationState(peripheral: _, characteristic: let _characteristic, error: _): return characteristic == _characteristic.uuid.uuidString case .didWriteValueForCharacteristic(peripheral: _, characteristic: let _characteristic, error: _): return characteristic == _characteristic.uuid.uuidString case .didUpdateValueForCharacteristic(peripheral: _, characteristic: let _characteristic, error: _): return characteristic == _characteristic.uuid.uuidString default: return false } } func filter(descriptor: CBDescriptor) -> Bool { return filter(descriptor: descriptor.uuid) } func filter(descriptor: CBUUID) -> Bool { return filter(descriptor: descriptor.uuidString) } func filter(descriptor: String) -> Bool { switch self { case .didWriteValueForDescriptor(peripheral: _, descriptor: let _descriptor, error: _): return descriptor == _descriptor.uuid.uuidString case .didUpdateValueForDescriptor(peripheral: _, descriptor: let _descriptor, error: _): return descriptor == _descriptor.uuid.uuidString default: return false } } var didUpdateName: CBPeripheral? { switch self { case .didUpdateName(let peripheral): return peripheral default: return nil } } var didReadRSSI: (RSSI: NSNumber, error: Error?)? { switch self { case .didReadRSSI( _, let RSSI, let error): return (RSSI: RSSI, error: error) default: return nil } } var didDiscoverServices: (peripheral: CBPeripheral, error: Error?)? { switch self { case .didDiscoverServices(let peripheral, let error): return (peripheral: peripheral, error: error) default: return nil } } var didDiscoverIncludedServices: (service: CBService, error: Error?)? { switch self { case .didDiscoverIncludedServices(peripheral: _, let service, let error): return (service: service, error: error) default: return nil } } var didDiscoverCharacteristics: (service: CBService, error: Error?)? { switch self { case .didDiscoverCharacteristics(peripheral: _, let service, let error): return (service: service, error: error) default: return nil } } var didDiscoverDescriptors: (characteristic: CBCharacteristic, error: Error?)? { switch self { case .didDiscoverDescriptors(_, let characteristic, let error): return (characteristic: characteristic, error: error) default: return nil } } var didUpdateNotificationState: (characteristic: CBCharacteristic, error: Error?)? { switch self { case .didUpdateNotificationState(_, let characteristic, let error): return (characteristic: characteristic, error: error) default: return nil } } var didWriteValueForCharacteristic: (characteristic: CBCharacteristic, error: Error?)? { switch self { case .didWriteValueForCharacteristic(_, let characteristic, let error): return (characteristic: characteristic, error: error) default: return nil } } var didWriteValueForDescriptor: (descriptor: CBDescriptor, error: Error?)? { switch self { case .didWriteValueForDescriptor(_, let descriptor, let error): return (descriptor: descriptor, error: error) default: return nil } } var didUpdateValueForCharacteristic: (characteristic: CBCharacteristic, error: Error?)? { switch self { case .didUpdateValueForCharacteristic(_, let characteristic, let error): return (characteristic: characteristic, error: error) default: return nil } } var didUpdateValueForDescriptor: (descriptor: CBDescriptor, error: Error?)? { switch self { case .didUpdateValueForDescriptor(_, let descriptor, let error): return (descriptor: descriptor, error: error) default: return nil } } } }
mit
1e022fa90ae9b90f7ed14f17de03d4b1
42.805687
119
0.609001
6.076923
false
false
false
false
clowwindy/firefox-ios
Client/Frontend/Settings/SearchEnginePicker.swift
4
1700
/* 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 protocol SearchEnginePickerDelegate { func searchEnginePicker(searchEnginePicker: SearchEnginePicker, didSelectSearchEngine engine: OpenSearchEngine?) -> Void } class SearchEnginePicker: UITableViewController { var delegate: SearchEnginePickerDelegate? var engines: [OpenSearchEngine]! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Default Search Engine", comment: "Title for default search engine picker.") navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "SELcancel") } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return engines.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let engine = engines[indexPath.item] let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.textLabel?.text = engine.shortName cell.imageView?.image = engine.image return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let engine = engines[indexPath.item] delegate?.searchEnginePicker(self, didSelectSearchEngine: engine) } func SELcancel() { delegate?.searchEnginePicker(self, didSelectSearchEngine: nil) } }
mpl-2.0
1b3b06cef889470c8d7f6193d5c7cdf4
39.47619
144
0.736471
5.414013
false
false
false
false
iq3addLi/WebStruct
Tests/WebStructTests/WebStructTests.swift
1
3362
// // WebStructTests.swift // WebStructTests // // Created by iq3 on 2016/08/24. // Copyright © 2016年 addli.co.jp. All rights reserved. // import XCTest @testable import WebStruct /** This UnitTest is need WebStrcutTestServer(https://github.com/iq3addLi/WebStructTestServer.git) running. */ class WebStructTests: XCTestCase { static let allTests = [ ("testBasicInitalize", testBasicInitalize), ("testInitializationFailedServersideError",testInitializationFailedServersideError), ("testInitializationFailedDueToTimeout", testInitializationFailedDueToTimeout), ("testCustomHttpHeaders", testCustomHttpHeaders) ] override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testBasicInitalize() { let basic = try? BasicStruct( path: "http://localhost:8080/basic", body: RequestStruct(value: "hello") ) XCTAssert(basic != nil,"test is nil.") } func testInitializationFailedServersideError(){ do{ let _ = try ErrorStruct( path: "http://localhost:8080/error", body: RequestStruct(value: "hello") ) } catch let error as WebStruct.Error{ switch (error) { case .network( _): // Network error XCTAssert( false,"Network error is unexpected.") case .http( _): // HTTP error XCTAssert( false,"HTTP error is unexpected.") case .ignoreData: // Unexpected response data XCTAssert( false,"IgnoreData error is unexpected.") case .parse( _): // Failed parse response data XCTAssert( false,"Parse error is unexpected.") case .application(let e): // Server side defined error XCTAssert( e is ApplicationError, "Serialize for ApplicationError is fail.") } } catch { // Unexpected throws XCTAssert( false,"Unexpected error.") } } func testInitializationFailedDueToTimeout(){ do{ let _ = try CustomRequestStruct( path: "http://localhost:8080/timeout", body: RequestStruct(value: "hello") ) } catch let error as WebStruct.Error{ if case .network(let e) = error{ if case let nserror as NSError = e, nserror.userInfo["NSLocalizedDescription"] as! String == "The request timed out."{ return // OK } } } catch { } XCTAssert(false,"invalid error.") } func testCustomHttpHeaders(){ let st:CustomHeadersStruct do{ st = try CustomHeadersStruct( path: "http://localhost:8080/headers", body: RequestStruct(value: "hello") ) } catch let error as WebStruct.Error{ XCTAssert(false,"Test failed. detail=\(error)");return } catch { XCTAssert(false,"Test failed.");return } XCTAssertEqual( st.headers["HeaderForTest"] , "ValueForTest" ) } }
mit
2f48850029699d9237324d36015328ef
29.816514
104
0.543316
5.066365
false
true
false
false
SusanDoggie/Doggie
Sources/DoggieMath/Accelerate/CircularConvolve2D.swift
1
4671
// // CircularConvolve2D.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // @inlinable @inline(__always) public func Radix2CircularConvolve2D<T: BinaryFloatingPoint>(_ log2n: (Int, Int), _ signal: UnsafePointer<T>, _ signal_stride: Int, _ signal_count: (Int, Int), _ kernel: UnsafePointer<T>, _ kernel_stride: Int, _ kernel_count: (Int, Int), _ output: UnsafeMutablePointer<T>, _ out_stride: Int, _ temp: UnsafeMutablePointer<T>, _ temp_stride: Int) where T: ElementaryFunctions { let width = 1 << log2n.0 let height = 1 << log2n.1 let half_width = width >> 1 let half_height = height >> 1 if _slowPath(signal_count.0 == 0 || signal_count.1 == 0 || kernel_count.0 == 0 || kernel_count.1 == 0) { var output = output for _ in 0..<width * height { output.pointee = 0 output += out_stride } return } let _sreal = temp let _simag = temp + temp_stride let _kreal = output let _kimag = output + out_stride let s_stride = temp_stride << 1 let k_stride = out_stride << 1 HalfRadix2CooleyTukey2D(log2n, signal, signal_stride, signal_count, _sreal, _simag, s_stride) HalfRadix2CooleyTukey2D(log2n, kernel, kernel_stride, kernel_count, _kreal, _kimag, k_stride) let m = 1 / T(width * height) let s_row_stride = s_stride * half_width let k_row_stride = k_stride * half_width func _multiply_complex(_ length: Int, _ sreal: UnsafeMutablePointer<T>, _ simag: UnsafeMutablePointer<T>, _ s_stride: Int, _ kreal: UnsafePointer<T>, _ kimag: UnsafePointer<T>, _ k_stride: Int) { var sreal = sreal var simag = simag var kreal = kreal var kimag = kimag for _ in 1..<length { sreal += s_stride simag += s_stride kreal += k_stride kimag += k_stride let _sr = sreal.pointee let _si = simag.pointee let _kr = m * kreal.pointee let _ki = m * kimag.pointee sreal.pointee = _sr * _kr - _si * _ki simag.pointee = _sr * _ki + _si * _kr } } do { var _sreal = _sreal var _simag = _simag var _kreal = _kreal var _kimag = _kimag _sreal.pointee *= m * _kreal.pointee _simag.pointee *= m * _kimag.pointee _sreal += s_row_stride _simag += s_row_stride _kreal += k_row_stride _kimag += k_row_stride _sreal.pointee *= m * _kreal.pointee _simag.pointee *= m * _kimag.pointee } _multiply_complex(half_height, _sreal, _sreal + s_row_stride, s_row_stride << 1, _kreal, _kreal + k_row_stride, k_row_stride << 1) _multiply_complex(half_height, _simag, _simag + s_row_stride, s_row_stride << 1, _kimag, _kimag + k_row_stride, k_row_stride << 1) do { var _sreal = _sreal var _simag = _simag var _kreal = _kreal var _kimag = _kimag let s_row_stride = s_stride * half_width let k_row_stride = k_stride * half_width for _ in 0..<height { _multiply_complex(half_width, _sreal, _simag, s_stride, _kreal, _kimag, k_stride) _sreal += s_row_stride _simag += s_row_stride _kreal += k_row_stride _kimag += k_row_stride } } HalfInverseRadix2CooleyTukey2D(log2n, _sreal, _simag, s_stride, output, out_stride) }
mit
8088c023865e734ee1fdf17a106271fa
37.286885
375
0.597088
3.766935
false
false
false
false
HwwDaDa/WeiBo_swift
WeiBo/WeiBo/Classes/View/Main/VisitorView/WBVisitorView.swift
1
6319
// // WBVisitorView.swift // WeiBo // // Created by Admin on 2017/7/6. // Copyright © 2017年 Admin. All rights reserved. // import UIKit //访客视图 class WBVisitorView: UIView { //访客视图的信息字典 var visitorInfo: [String : String]? { didSet{ guard let imageName = visitorInfo?["imageName"], let message = visitorInfo?["message"] else { return } //设置消息 tipLable.text = message //设置头像 if imageName == ""{ startAnimation() return } iconView.image = UIImage(named: imageName) //其他控制器不需要显示小房子,遮罩视图隐藏 houseIconView.isHidden = true maskIconView.isHidden = true } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //旋转图标动画首页的(首页需要) func startAnimation() { let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = 2 * (Double.pi) anim.repeatCount = MAXFLOAT anim.duration = 15 //动画完成不删除,如果iconView被释放,动画会一起销毁 //在设置连续播放动画的时候非常有用 anim.isRemovedOnCompletion = false //将动画添加到图层 iconView.layer.add(anim, forKey: nil) } // MARK:私有控件 lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) //遮挡头像 lazy var maskIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) //小房子 lazy var houseIconView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) // 懒加载属性只有调用UIKit的控件指定的构造函数 lazy var tipLable: UILabel = UILabel.cz_label(withText: "关注一些人,回这里看看什么惊喜关注一些人,回这里看看什么惊喜", fontSize: 14, color: UIColor.darkGray) lazy var registerButton: UIButton = UIButton.cz_textButton("注册", fontSize: 16, normalColor: UIColor.orange, highlightedColor: UIColor.darkGray, backgroundImageName: "common_button_white_disable") lazy var loginButton: UIButton = UIButton.cz_textButton("登录", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.darkGray, backgroundImageName: "common_button_white_disable") } extension WBVisitorView { func setupUI() { backgroundColor = UIColor.cz_color(withHex: 0xEDEDED) // 添加控件 addSubview(iconView) addSubview(maskIconView) addSubview(houseIconView) addSubview(tipLable) addSubview(registerButton) addSubview(loginButton) //文本居中 tipLable.textAlignment = .center // 取消autoresizing for v in subviews { v.translatesAutoresizingMaskIntoConstraints = false } // 自动布局 let margin :CGFloat = 20; // 图像视图 addConstraint(NSLayoutConstraint(item: iconView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: iconView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: -60)) // 小房子 addConstraint(NSLayoutConstraint(item: houseIconView, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: houseIconView, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1.0, constant: 0)) //提示标签 addConstraint(NSLayoutConstraint(item: tipLable, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: tipLable, attribute: .top, relatedBy: .equal, toItem: iconView, attribute: .bottom, multiplier: 1.0, constant: margin)) addConstraint(NSLayoutConstraint(item: tipLable, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 236)) //注册按钮 addConstraint(NSLayoutConstraint(item: registerButton, attribute: .left, relatedBy: .equal, toItem: tipLable, attribute: .left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: registerButton, attribute: .top, relatedBy: .equal, toItem: tipLable, attribute: .bottom, multiplier: 1, constant: margin)) addConstraint(NSLayoutConstraint(item: registerButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: margin * 5)) //登录按钮 addConstraint(NSLayoutConstraint(item: loginButton, attribute: .right, relatedBy: .equal, toItem: tipLable, attribute: .right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: .top, relatedBy: .equal, toItem: tipLable, attribute: .bottom, multiplier: 1.0, constant: margin)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: .width, relatedBy: .equal, toItem: registerButton, attribute: .width, multiplier: 1.0, constant: 0)) //遮罩头像 //views定义VFL控件中的名称和实际的映射关系 let viewDict = ["maskIconView":maskIconView, "registerButton":registerButton] as [String : Any] addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[maskIconView]-0-|", options: [], metrics: nil, views: viewDict)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[maskIconView]-(-35)-[registerButton]", options: [], metrics: nil, views: viewDict)) } }
mit
7fad5b42bb313c0ce7865f10f400e034
41.042857
199
0.644071
4.675139
false
false
false
false
dirk/Roost
vendor/MessagePack/Source/MessagePack.swift
2
21188
import Foundation /** The MessagePackValue enum encapsulates the following types: - Nil - Bool - Int - UInt - Float - Double - String - Binary - Array - Map - Extended */ public enum MessagePackValue: Equatable { case Nil case Bool(Swift.Bool) case Int(Int64) case UInt(UInt64) case Float(Float32) case Double(Float64) case String(Swift.String) case Binary(NSData) case Array([MessagePackValue]) case Map([MessagePackValue : MessagePackValue]) case Extended(type: Int8, data: NSData) } extension MessagePackValue: Hashable { public var hashValue: Swift.Int { switch self { case .Nil: return 0 case .Bool(let value): return value.hashValue case .Int(let value): return value.hashValue case .UInt(let value): return value.hashValue case .Float(let value): return value.hashValue case .Double(let value): return value.hashValue case .String(let string): return string.hashValue case .Binary(let data): return data.hash case .Array(let array): return array.count case .Map(let dict): return dict.count case .Extended(let type, let data): return type.hashValue ^ data.hash } } } /** Unpacks a generator of bytes into a MessagePackValue. :param: generator The generator that yields bytes. :returns: A MessagePackValue, or `nil` if the generator runs out of bytes. */ public func unpack<G: GeneratorType where G.Element == UInt8>(inout generator: G) -> MessagePackValue? { if let value = generator.next() { switch value { // positive fixint case 0x00...0x7f: return .UInt(UInt64(value)) // fixmap case 0x80...0x8f: let length = Int(value - 0x80) if let dict = joinMap(&generator, length) { return .Map(dict) } // fixarray case 0x90...0x9f: let length = Int(value - 0x90) if let array = joinArray(&generator, length) { return .Array(array) } // fixstr case 0xa0...0xbf: let length = Int(value - 0xa0) if let string = joinString(&generator, length) { return .String(string) } // nil case 0xc0: return .Nil // (never used) case 0xc1: break // false case 0xc2: return .Bool(false) // true case 0xc3: return .Bool(true) // bin 8, 16, 32 case 0xc4...0xc6: let size = 1 << Int(value - 0xc4) if let length = joinUInt64(&generator, size), data = joinData(&generator, Int(length)) { return .Binary(data) } // ext 8, 16, 32 case 0xc7...0xc9: let size = 1 << Int(value - 0xc7) if let length = joinUInt64(&generator, size), typeByte = generator.next() { let type = Int8(bitPattern: typeByte) if let data = joinData(&generator, Int(length)) { return .Extended(type: type, data: data) } } // float 32 case 0xca: if let bytes = joinUInt64(&generator, 4) { let float = unsafeBitCast(UInt32(truncatingBitPattern: bytes), Float32.self) return .Float(float) } // float 64 case 0xcb: if let bytes = joinUInt64(&generator, 8) { let double = unsafeBitCast(bytes, Float64.self) return .Double(double) } // uint 8, 16, 32, 64 case 0xcc...0xcf: let length = 1 << (Int(value) - 0xcc) if let integer = joinUInt64(&generator, length) { return .UInt(integer) } // int 8 case 0xd0: if let byte = generator.next() { let integer = Int8(bitPattern: byte) return .Int(Int64(integer)) } // int 16 case 0xd1: if let bytes = joinUInt64(&generator, 2) { let integer = Int16(bitPattern: UInt16(truncatingBitPattern: bytes)) return .Int(Int64(integer)) } // int 32 case 0xd2: if let bytes = joinUInt64(&generator, 4) { let integer = Int32(bitPattern: UInt32(truncatingBitPattern: bytes)) return .Int(Int64(integer)) } // int 64 case 0xd3: if let bytes = joinUInt64(&generator, 2) { let integer = Int64(bitPattern: bytes) return .Int(integer) } // fixent 1, 2, 4, 8, 16 case 0xd4...0xd8: let length = 1 << Int(value - 0xd4) if let typeByte = generator.next() { let type = Int8(bitPattern: typeByte) if let bytes = joinData(&generator, length) { return .Extended(type: type, data: bytes) } } // str 8, 16, 32 case 0xd9...0xdb: let lengthSize = 1 << Int(value - 0xd9) if let length = joinUInt64(&generator, lengthSize), string = joinString(&generator, Int(length)) { return .String(string) } // array 16, 32 case 0xdc...0xdd: let lengthSize = 1 << Int(value - 0xdc) if let length = joinUInt64(&generator, lengthSize), array = joinArray(&generator, Int(length)) { return .Array(array) } // map 16, 32 case 0xde...0xdf: let lengthSize = 1 << Int(value - 0xdc) if let length = joinUInt64(&generator, lengthSize), dict = joinMap(&generator, Int(length)) { return .Map(dict) } // negative fixint case 0xe0...0xff: return .Int(Int64(value) - 0x100) default: break } } return nil } /** Unpacks a data object into a MessagePackValue. :param: data A data object to unpack. :returns: A MessagePackValue, or `nil` if the data is malformed. */ public func unpack(data: NSData) -> MessagePackValue? { let immutableData = data.copy() as! NSData let ptr = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(immutableData.bytes), count: immutableData.length) var generator = ptr.generate() return unpack(&generator) } /** Packs a MessagePackValue into an array of bytes. :param: value The value to encode :returns: An array of bytes. */ public func pack(value: MessagePackValue) -> NSData { switch value { case .Nil: return makeData([0xc0]) case .Bool(let value): return makeData([value ? 0xc3 : 0xc2]) case .Int(let value): return value >= 0 ? packIntPos(UInt64(value)) : packIntNeg(value) case .UInt(let value): return packIntPos(value) case .Float(let value): let integerValue = unsafeBitCast(value, UInt32.self) return makeData([0xca] + splitInt(UInt64(integerValue), parts: 4)) case .Double(let value): let integerValue = unsafeBitCast(value, UInt64.self) return makeData([0xcb] + splitInt(integerValue, parts: 8)) case .String(let string): let utf8 = string.utf8 let prefix: [UInt8] switch UInt32(utf8.count) { case let count where count <= 0x19: prefix = [0xa0 | UInt8(count)] case let count where count <= 0xff: prefix = [0xd9, UInt8(count)] case let count where count <= 0xffff: let truncated = UInt16(bitPattern: Int16(count)) prefix = [0xda] + splitInt(UInt64(truncated), parts: 2) case let count where count <= 0xffff_ffff: prefix = [0xdb] + splitInt(UInt64(count), parts: 4) default: preconditionFailure() } return makeData(prefix + utf8) case .Binary(let data): let prefix: [UInt8] switch UInt32(data.length) { case let count where count <= 0xff: prefix = [0xc4, UInt8(count)] case let count where count <= 0xffff: let truncated = UInt16(bitPattern: Int16(count)) prefix = [0xc5] + splitInt(UInt64(truncated), parts: 2) case let count where count <= 0xffff_ffff: prefix = [0xc6] + splitInt(UInt64(count), parts: 4) default: preconditionFailure() } let mutableData = NSMutableData() mutableData.appendData(makeData(prefix)) mutableData.appendData(data) return mutableData case .Array(let array): let prefix: [UInt8] switch UInt32(array.count) { case let count where count <= 0xe: prefix = [0x90 | UInt8(count)] case let count where count <= 0xffff: let truncated = UInt16(bitPattern: Int16(count)) prefix = [0xdc] + splitInt(UInt64(truncated), parts: 2) case let count where count <= 0xffff_ffff: prefix = [0xdd] + splitInt(UInt64(count), parts: 4) default: preconditionFailure() } let mutableData = NSMutableData() mutableData.appendData(makeData(prefix)) return array.map(pack).reduce(mutableData) { (mutableData: NSMutableData, data) in mutableData.appendData(data) return mutableData } case .Map(let dict): var prefix: [UInt8] switch UInt32(dict.count) { case let count where count <= 0xe: prefix = [0x80 | UInt8(count)] case let count where count <= 0xffff: let truncated = UInt16(bitPattern: Int16(count)) prefix = [0xde] + splitInt(UInt64(truncated), parts: 2) case let count where count <= 0xffff_ffff: prefix = [0xdf] + splitInt(UInt64(count), parts: 4) default: preconditionFailure() } let mutableData = NSMutableData() mutableData.appendData(makeData(prefix)) return flatten(dict).map(pack).reduce(mutableData) { (mutableData: NSMutableData, data) in mutableData.appendData(data) return mutableData } case .Extended(let type, let data): let unsignedType = UInt8(bitPattern: type) var prefix: [UInt8] switch UInt32(data.length) { case 1: prefix = [0xd4, unsignedType] case 2: prefix = [0xd5, unsignedType] case 4: prefix = [0xd6, unsignedType] case 8: prefix = [0xd7, unsignedType] case 16: prefix = [0xd8, unsignedType] case let count where count <= 0xff: prefix = [0xc7, UInt8(count), unsignedType] case let count where count <= 0xffff: let truncated = UInt16(bitPattern: Int16(count)) prefix = [0xc8] + splitInt(UInt64(truncated), parts: 2) + [unsignedType] case let count where count <= 0xffff_ffff: prefix = [0xc9] + splitInt(UInt64(count), parts: 4) + [unsignedType] default: preconditionFailure() } let mutableData = NSMutableData() mutableData.appendData(makeData(prefix)) mutableData.appendData(data) return mutableData } } public func ==(lhs: MessagePackValue, rhs: MessagePackValue) -> Bool { switch (lhs, rhs) { case (.Nil, .Nil): return true case let (.Bool(lhv), .Bool(rhv)) where lhv == rhv: return true case let (.Int(lhv), .Int(rhv)) where lhv == rhv: return true case let (.UInt(lhv), .UInt(rhv)) where lhv == rhv: return true case let (.Int(lhv), .UInt(rhv)) where lhv >= 0 && UInt64(lhv) == rhv: return true case let (.UInt(lhv), .Int(rhv)) where rhv >= 0 && lhv == UInt64(rhv): return true case let (.Float(lhv), .Float(rhv)) where lhv == rhv: return true case let (.Double(lhv), .Double(rhv)) where lhv == rhv: return true case let (.String(lhv), .String(rhv)) where lhv == rhv: return true case let (.Binary(lhv), .Binary(rhv)) where lhv == rhv: return true case let (.Array(lhv), .Array(rhv)) where lhv == rhv: return true case let (.Map(lhv), .Map(rhv)) where lhv == rhv: return true case let (.Extended(lht, lhb), .Extended(rht, rhb)) where lht == rht && lhb == rhb: return true default: return false } } extension MessagePackValue: ArrayLiteralConvertible { public init(arrayLiteral elements: MessagePackValue...) { self = .Array(elements) } } extension MessagePackValue: BooleanLiteralConvertible { public init(booleanLiteral value: Swift.Bool) { self = .Bool(value) } } extension MessagePackValue: DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (MessagePackValue, MessagePackValue)...) { let dict = elements.reduce([MessagePackValue : MessagePackValue]()) { (var dict, tuple) in let (key, value) = tuple dict[key] = value return dict } self = .Map(dict) } } extension MessagePackValue: ExtendedGraphemeClusterLiteralConvertible { public init(extendedGraphemeClusterLiteral value: Swift.String) { self = .String(value) } } extension MessagePackValue: FloatLiteralConvertible { public init(floatLiteral value: Swift.Double) { self = .Double(value) } } extension MessagePackValue: IntegerLiteralConvertible { public init(integerLiteral value: Int64) { self = .Int(value) } } extension MessagePackValue: NilLiteralConvertible { public init(nilLiteral: ()) { self = .Nil } } extension MessagePackValue: StringLiteralConvertible { public init(stringLiteral value: Swift.String) { self = .String(value) } } extension MessagePackValue: UnicodeScalarLiteralConvertible { public init(unicodeScalarLiteral value: Swift.String) { self = .String(value) } } extension MessagePackValue { public init() { self = .Nil } public init<B: BooleanType>(_ value: B) { self = .Bool(value.boolValue) } public init<S: SignedIntegerType>(_ value: S) { self = .Int(Int64(value.toIntMax())) } public init<U: UnsignedIntegerType>(_ value: U) { self = .UInt(UInt64(value.toUIntMax())) } public init(_ value: Swift.Float) { self = .Float(value) } public init(_ value: Swift.Double) { self = .Double(value) } public init(_ value: Swift.String) { self = .String(value) } public init(_ value: [MessagePackValue]) { self = .Array(value) } public init(_ value: [MessagePackValue : MessagePackValue]) { self = .Map(value) } public init(_ value: NSData) { self = .Binary(value) } } extension MessagePackValue { /// The number of elements in the `.Array` or `.Map`, `nil` otherwise. public var count: Swift.Int? { switch self { case .Array(let array): return array.count case .Map(let dict): return dict.count default: return nil } } /// The element at subscript `i` in the `.Array`, `nil` otherwise. public subscript (i: Swift.Int) -> MessagePackValue? { switch self { case .Array(let array) where i < array.count: return array[i] default: return nil } } /// The element at keyed subscript `key`, `nil` otherwise. public subscript (key: MessagePackValue) -> MessagePackValue? { switch self { case .Map(let dict): return dict[key] default: return nil } } /// True if `.Nil`, false otherwise. public var isNil: Swift.Bool { return self == .Nil } /// The integer value if `.Int` or an appropriately valued `.UInt`, `nil` otherwise. public var integerValue: Int64? { switch self { case .Int(let value): return value case .UInt(let value) where value < UInt64(Swift.Int64.max): return Int64(value) default: return nil } } /// The unsigned integer value if `.UInt` or positive `.Int`, `nil` otherwise. public var unsignedIntegerValue: UInt64? { switch self { case .Int(let value) where value > 0: return UInt64(value) case .UInt(let value): return value default: return nil } } /// The contained array if `.Array`, `nil` otherwise. public var arrayValue: [MessagePackValue]? { switch self { case .Array(let array): return array default: return nil } } /// The contained boolean value if `.Bool`, `nil` otherwise. public var boolValue: Swift.Bool? { switch self { case .Bool(let value): return value default: return nil } } /// The contained floating point value if `.Float` or `.Double`, `nil` otherwise. public var floatValue: Swift.Float? { switch self { case .Float(let value): return value case .Double(let value): return Swift.Float(value) default: return nil } } /// The contained double-precision floating point value if `.Float` or `.Double`, `nil` otherwise. public var doubleValue: Swift.Double? { switch self { case .Float(let value): return Swift.Double(value) case .Double(let value): return value default: return nil } } /// The contained string if `.String`, `nil` otherwise. public var stringValue: Swift.String? { switch self { case .String(let string): return string default: return nil } } /// The contained data if `.Binary` or `.Extended`, `nil` otherwise. public var dataValue: NSData? { switch self { case .Binary(let bytes): return bytes case .Extended(type: _, data: let data): return data default: return nil } } /// The contained type and data if Extended, `nil` otherwise. public var extendedValue: (type: Int8, data: NSData)? { switch self { case .Extended(type: let type, data: let data): return (type, data) default: return nil } } /// The contained type if `.Extended`, `nil` otherwise. public var extendedType: Int8? { switch self { case .Extended(type: let type, data: _): return type default: return nil } } /// The contained dictionary if `.Map`, `nil` otherwise. public var dictionaryValue: [MessagePackValue : MessagePackValue]? { switch self { case .Map(let dict): return dict default: return nil } } } extension MessagePackValue: CustomStringConvertible { public var description: Swift.String { switch self { case .Nil: return "<Nil>" case .Bool(let value): return value ? "true" : "false" case .Int(let value): return "\(value)" case .UInt(let value): return "\(value)" case .Float(let value): return "\(value)" case .Double(let value): return "\(value)" case .String(let string): return string case .Binary(let data): return "<Data: \(data.length) byte(s)>" case .Array(let array): return "<Array: \(array.count) element(s)>" case .Map(let dict): return "<Map: \(dict.count) pair(s)>" case .Extended(let type, let data): return "<ExtendedType: type \(type); \(data.length) byte(s)>" } } } extension MessagePackValue: CustomDebugStringConvertible { public var debugDescription: Swift.String { switch self { case .Nil: return ".Nil" case .Bool(let value): return ".Bool(\(value))" case .Int(let value): return ".Int(\(value))" case .UInt(let value): return ".UInt(\(value))" case .Float(let value): return ".Float(\(value))" case .Double(let value): return ".Double(\(value))" case .String(let string): return ".String(\"\(string)\")" case .Binary(let bytes): return ".Binary(\(bytes))" case .Array(let array): return ".Array(\(array))" case .Map(let dict): return ".Map(\(dict))" case .Extended(let type, let bytes): return ".Extended(type: \(type), bytes: \(bytes))" } } }
bsd-3-clause
38d8163a470147da0eae0b21fa2c3804
28.592179
119
0.555126
4.338247
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Online/CategoryCache.swift
1
1760
// // CategoryCache.swift // MusicApp // // Created by Hưng Đỗ on 6/20/17. // Copyright © 2017 HungDo. All rights reserved. // import Foundation class CategoryCache<Item> { private let cache = NSCache<NSString, ItemValue<Item>>() private var pages: [String:[Int]] = [:] func setItem(_ item: Item, category: String, page: Int) { let key = ItemKey(category: category, page: page) cache.setObject(ItemValue(item), forKey: key.description as NSString) if self.pages[category] == nil { self.pages[category] = [] } var pages = self.pages[category]! if !pages.contains(page) { pages.append(page) self.pages[category] = pages } } func getItem(category: String, page: Int) -> Item? { let key = ItemKey(category: category, page: page) let value = cache.object(forKey: key.description as NSString) return value?.item } func removeItems(category: String) { guard let pages = self.pages[category] else { return } for page in pages { let key = ItemKey(category: category, page: page) cache.removeObject(forKey: key.description as NSString) } self.pages[category] = nil } } fileprivate class ItemKey: CustomStringConvertible { let category: String let page: Int init(category: String, page: Int) { self.category = category self.page = page } var description: String { return category + "/\(page)" } } fileprivate class ItemValue<Item> { let item: Item init(_ item: Item) { self.item = item } }
mit
45e930e6a0b945f3ae5e72fba4105cfe
22.716216
77
0.569231
4.178571
false
false
false
false
4taras4/totp-auth
TOTP/ViperModules/AddItem/Module/Router/AddItemRouter.swift
1
1551
// // AddItemAddItemRouter.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import UIKit final class AddItemRouter: AddItemRouterInput { weak var transitionHandler: UIViewController! func popToRoot() { transitionHandler.navigationController?.popToRootViewController(animated: true) } func pushManualyViewController() { let newItemManualyViewController = AddItemManualyViewController.instantiate(useSwinject: true) transitionHandler.navigationController?.pushViewController(newItemManualyViewController, animated: true) } func showSettingsAlert() { let alertController = UIAlertController (title: Constants.text.cameraAlertTitle, message: Constants.text.cameraAlertDescription, preferredStyle: .alert) let settingsAction = UIAlertAction(title: Constants.text.settingsAlertButton, style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl) } } alertController.addAction(settingsAction) let cancelAction = UIAlertAction(title: Constants.text.cancelAlertButton, style: .default, handler: nil) alertController.addAction(cancelAction) transitionHandler.present(alertController, animated: true, completion: nil) } }
mit
0856ac43e6395e4aa8bb856f0bb86dbd
39.789474
160
0.703226
5.438596
false
false
false
false
davidbutz/ChristmasFamDuels
iOS/Boat Aware/LoadingAppViewController.swift
1
7171
// // LoadingAppViewController.swift // Boat Aware // // Created by Dave Butz on 6/23/16. // Copyright © 2016 Thrive Engineering. All rights reserved. // import UIKit class LoadingAppViewController: UIViewController { var window: UIWindow? typealias JSONArray = Array<AnyObject> typealias JSONDictionary = Dictionary<String, AnyObject> override func viewDidLoad() { super.viewDidLoad() let defaults = NSUserDefaults.standardUserDefaults(); let appvar = ApplicationVariables.applicationvariables; LoadingOverlay.shared.showOverlay(self.view); LoadingOverlay.shared.setCaption("Authenticating..."); if let savedAuthenticationToken = defaults.stringForKey("authenticationtoken") { if(savedAuthenticationToken != ""){ //i have a saved AuthToken. Check if it is still valid... let JSONObject: [String : AnyObject] = [ "login_token" : savedAuthenticationToken ] let api = APICalls() api.apicallout("/api/accounts/loginTokenValid/" + savedAuthenticationToken , iptype: "localIPAddress", method: "GET", JSONObject: JSONObject, callback: { (response) -> () in let success = (response as! NSDictionary)["success"] as! Bool; if(success){ //yes it is valid and good. //need to populate the appvar information with data from the call..... let appvar = ApplicationVariables.applicationvariables; appvar.username = (response as! NSDictionary)["username"] as! String; appvar.logintoken = (response as! NSDictionary)["authenticationtoken"] as! String; appvar.userid = (response as! NSDictionary)["userid"] as! String; appvar.account_id = (response as! NSDictionary)["account_id"] as! String; appvar.fname = (response as! NSDictionary)["firstname"] as! String; appvar.lname = (response as! NSDictionary)["lastname"] as! String; //appvar.account_name = (response as! NSDictionary)["account_name"] as! String; appvar.password = (response as! NSDictionary)["password"] as! String; appvar.cellphone = (response as! NSDictionary)["cellphone"] as! String; let JSONObject: [String : AnyObject] = [ "login_token" : appvar.logintoken ] api.apicallout("/api/setup/getleagues/" + appvar.userid + "/" + appvar.logintoken , iptype: "localIPAddress", method: "GET", JSONObject: JSONObject, callback: { (leagueresponse) -> () in dispatch_async(dispatch_get_main_queue()) { LoadingOverlay.shared.hideOverlayView(); }; let leaguesuccess = (leagueresponse as! NSDictionary)["success"] as! Bool; let leaguecount = (leagueresponse as! NSDictionary)["leagueCount"] as! NSNumber; if(leaguesuccess){ if(leaguecount == 1){ let leagueArray = (leagueresponse as! NSDictionary)["leagues"] as! JSONArray; let leagueInformation = leagueArray[0] as! JSONDictionary; let userxleagueID = leagueInformation["userxleagueID"] as! String; let leagueName = leagueInformation["leagueName"] as! String; let leagueID = leagueInformation["leagueID"] as! String; let leagueOwnerID = leagueInformation["leagueOwnerID"] as! NSNumber; let roleID = leagueInformation["roleID"] as! String; let leaguevar = LeagueVariables.leaguevariables; leaguevar.leagueID = leagueID; leaguevar.leagueName = leagueName; leaguevar.leagueOwnerID = String(leagueOwnerID); leaguevar.roleID = NSNumber(integer: Int(roleID)!); leaguevar.userxleagueID = userxleagueID; dispatch_async(dispatch_get_main_queue()) { self.handleViewAppearance("viewLaunch"); } } else { print("They have more than one league and I dont handle that right now...") } } else{ //They signed in, but dont have any league(s) properly set up. print("They signed in, but dont have any league(s) properly set up.") } }); } else{ dispatch_async(dispatch_get_main_queue()) { LoadingOverlay.shared.hideOverlayView(); }; //the token is not valid, or has expired. They need to login again. dispatch_async(dispatch_get_main_queue()) { self.handleViewAppearance("viewLogin"); } } }); } else{ //check for login here.. dispatch_async(dispatch_get_main_queue()) { LoadingOverlay.shared.hideOverlayView(); }; if(appvar.logintoken == "fake"){ handleViewAppearance("viewLogin"); } } } else{ //check for login here.. dispatch_async(dispatch_get_main_queue()) { LoadingOverlay.shared.hideOverlayView(); }; if(appvar.logintoken == "fake"){ handleViewAppearance("viewLogin"); } } } func handleViewAppearance(viewToAppear: String){ let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier(viewToAppear) as UIViewController self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = initialViewControlleripad self.window?.makeKeyAndVisible() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
8429554e144509e2ceb940a5ce2aafbd
53.318182
211
0.502092
6.086587
false
false
false
false
kota/ObjectMapper
ObjectMapper/Core/Mapper.swift
1
12026
// // Mapper.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // Copyright (c) 2014 hearst. All rights reserved. // import Foundation public protocol Mappable { init?(_ map: Map) mutating func mapping(map: Map) } public enum MappingType { case FromJSON case ToJSON } /// A class used for holding mapping data public final class Map { public let mappingType: MappingType var JSONDictionary: [String : AnyObject] = [:] var currentValue: AnyObject? var currentKey: String? var keyIsNested = false /// Counter for failing cases of deserializing values to `let` properties. private var failedCount: Int = 0 public init(mappingType: MappingType, JSONDictionary: [String : AnyObject]) { self.mappingType = mappingType self.JSONDictionary = JSONDictionary } /// Sets the current mapper value and key. /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects. public subscript(key: String) -> Map { // save key and value associated to it return self[key, nested: true] } public subscript(key: String, nested nested: Bool) -> Map { // save key and value associated to it currentKey = key keyIsNested = nested // check if a value exists for the current key if nested == false { currentValue = JSONDictionary[key] } else { // break down the components of the key that are separated by . currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), dictionary: JSONDictionary) } return self } // MARK: Immutable Mapping public func value<T>() -> T? { return currentValue as? T } public func valueOr<T>(@autoclosure defaultValue: () -> T) -> T { return value() ?? defaultValue() } /// Returns current JSON value of type `T` if it is existing, or returns a /// unusable proxy value for `T` and collects failed count. public func valueOrFail<T>() -> T { if let value: T = value() { return value } else { // Collects failed count failedCount++ // Returns dummy memory as a proxy for type `T` let pointer = UnsafeMutablePointer<T>.alloc(0) pointer.dealloc(0) return pointer.memory } } /// Returns whether the receiver is success or failure. public var isValid: Bool { return failedCount == 0 } } /// Fetch value from JSON dictionary, loop through them until we reach the desired object. private func valueFor(keyPathComponents: ArraySlice<String>, dictionary: [String : AnyObject]) -> AnyObject? { // Implement it as a tail recursive function. if keyPathComponents.isEmpty { return nil } if let object: AnyObject = dictionary[keyPathComponents.first!] { switch object { case is NSNull: return nil case let dict as [String : AnyObject] where keyPathComponents.count > 1: let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: dict) default: return object } } return nil } /// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects public final class Mapper<N: Mappable> { public init(){ } // MARK: Mapping functions that map to an existing object toObject /// Map a JSON string onto an existing object public func map(JSONString: String, toObject object: N) -> N { if let JSON = parseJSONDictionary(JSONString) { return map(JSON, toObject: object) } return object } /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is public func map(JSON: AnyObject?, toObject object: N) -> N { if let JSON = JSON as? [String : AnyObject] { return map(JSON, toObject: object) } return object } /// Maps a JSON dictionary to an existing object that conforms to Mappable. /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject public func map(JSONDictionary: [String : AnyObject], var toObject object: N) -> N { let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary) object.mapping(map) return object } //MARK: Mapping functions that create an object /// Map a JSON string to an object that conforms to Mappable public func map(JSONString: String) -> N? { if let JSON = parseJSONDictionary(JSONString) { return map(JSON) } return nil } /// Map a JSON NSString to an object that conforms to Mappable public func map(JSONString: NSString) -> N? { return map(JSONString as String) } /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. public func map(JSON: AnyObject?) -> N? { if let JSON = JSON as? [String : AnyObject] { return map(JSON) } return nil } /// Maps a JSON dictionary to an object that conforms to Mappable public func map(JSONDictionary: [String : AnyObject]) -> N? { let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary) if var object = N(map) { object.mapping(map) return object } return nil } //MARK: Mapping functions for Arrays and Dictionaries /// Maps a JSON array to an object that conforms to Mappable public func mapArray(JSONString: String) -> [N] { let parsedJSON: AnyObject? = parseJSONString(JSONString) if let objectArray = mapArray(parsedJSON) { return objectArray } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(parsedJSON) { return [object] } return [] } /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapArray(JSON: AnyObject?) -> [N]? { if let JSONArray = JSON as? [[String : AnyObject]] { return mapArray(JSONArray) } return nil } /// Maps an array of JSON dictionary to an array of Mappable objects public func mapArray(JSONArray: [[String : AnyObject]]) -> [N] { // map every element in JSON array to type N return JSONArray.flatMap(map) } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSON: AnyObject?) -> [String : N]? { if let JSONDictionary = JSON as? [String : [String : AnyObject]] { return mapDictionary(JSONDictionary) } return nil } /// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N] { // map every value in dictionary to type N return JSONDictionary.filterMap(map) } /// Maps a JSON object to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? { if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] { return mapDictionaryOfArrays(JSONDictionary) } return nil } ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]] { // map every value in dictionary to type N return JSONDictionary.filterMap({ mapArray($0) }) } // MARK: Functions that create JSON from objects ///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject> public func toJSON(var object: N) -> [String : AnyObject] { let map = Map(mappingType: .ToJSON, JSONDictionary: [:]) object.mapping(map) return map.JSONDictionary } ///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]] public func toJSONArray(array: [N]) -> [[String : AnyObject]] { return array.map { // convert every element in array to JSON dictionary equivalent self.toJSON($0) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] { return dictionary.map { k, v in // convert every value in dictionary to its JSON dictionary equivalent return (k, self.toJSON(v)) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] { return dictionary.map { k, v in // convert every value (array) in dictionary to its JSON dictionary equivalent return (k, self.toJSONArray(v)) } } /// Maps an Object to a JSON string public func toJSONString(object: N, prettyPrint: Bool) -> String? { let JSONDict = toJSON(object) if NSJSONSerialization.isValidJSONObject(JSONDict) { let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : [] let JSONData: NSData? do { JSONData = try NSJSONSerialization.dataWithJSONObject(JSONDict, options: options) } catch let error { print(error) JSONData = nil } if let JSON = JSONData { return NSString(data: JSON, encoding: NSUTF8StringEncoding) as? String } } return nil } // MARK: Private utility functions for converting strings to JSON objects /// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization private func parseJSONDictionary(JSON: String) -> [String : AnyObject]? { let parsedJSON: AnyObject? = parseJSONString(JSON) return parseJSONDictionary(parsedJSON) } /// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization private func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? { if let JSONDict = JSON as? [String : AnyObject] { return JSONDict } return nil } /// Convert a JSON String into an Object using NSJSONSerialization private func parseJSONString(JSON: String) -> AnyObject? { let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) if let data = data { let parsedJSON: AnyObject? do { parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) } catch let error { print(error) parsedJSON = nil } return parsedJSON } return nil } } extension Mapper where N: Hashable{ /// Maps a JSON array to an object that conforms to Mappable public func mapSet(JSONString: String) -> Set<N> { let parsedJSON: AnyObject? = parseJSONString(JSONString) if let objectArray = mapArray(parsedJSON){ return Set(objectArray) } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(parsedJSON) { return Set([object]) } return Set() } /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapSet(JSON: AnyObject?) -> Set<N>? { if let JSONArray = JSON as? [[String : AnyObject]] { return mapSet(JSONArray) } return nil } /// Maps an Set of JSON dictionary to an array of Mappable objects public func mapSet(JSONArray: [[String : AnyObject]]) -> Set<N> { // map every element in JSON array to type N return Set(JSONArray.flatMap(map)) } ///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]] public func toJSONSet(set: Set<N>) -> [[String : AnyObject]] { return set.map { // convert every element in set to JSON dictionary equivalent self.toJSON($0) } } } extension Dictionary { internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] { var mapped = [K : V]() for element in self { let newElement = f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] { var mapped = [K : [V]]() for element in self { let newElement = f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] { var mapped = [Key : U]() for (key, value) in self { if let newValue = f(value){ mapped[key] = newValue } } return mapped } }
mit
676f70476d5b90c332abb6acc66f2cc5
27.701671
123
0.697988
3.825064
false
false
false
false
juliangrosshauser/Habits
Habits/Source/HabitsViewModel.swift
1
1281
// // HabitsViewModel.swift // Habits // // Created by Julian Grosshauser on 26/09/15. // Copyright © 2015 Julian Grosshauser. All rights reserved. // import ReactiveCocoa class HabitsViewModel { //MARK: Properties private let store: Store var habits: Habits { return store.habits } let addHabitEnabled = MutableProperty(true) let deleteHabitEnabled = MutableProperty(true) private(set) var addHabit: Action<String, NSIndexPath, NoError>! private(set) var deleteHabit: Action<PrimaryKey, NSIndexPath, StoreError>! //MARK: Initialization init(store: Store) { self.store = store addHabit = Action(enabledIf: addHabitEnabled) { [unowned self] name in self.addHabit(name) } deleteHabit = Action(enabledIf: deleteHabitEnabled) { [unowned self] primaryKey in self.deleteHabit(primaryKey) } } //MARK: Manage Habits private func addHabit(name: String) -> SignalProducer<NSIndexPath, NoError> { return SignalProducer(value: store.addHabit(name)) } private func deleteHabit(primaryKey: PrimaryKey) -> SignalProducer<NSIndexPath, StoreError> { return SignalProducer(result: store.deleteHabit(primaryKey)) } }
mit
86b359d10d70e178a062586861443b38
24.6
97
0.670313
4.654545
false
false
false
false
Jnosh/swift
test/Interpreter/generic_objc_subclass.swift
2
5910
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import ObjCClasses @objc protocol P { func calculatePrice() -> Int } protocol PP { func calculateTaxes() -> Int } // // Generic subclass of an @objc class // class A<T> : HasHiddenIvars, P { var first: Int = 16 var second: T? var third: Int = 61 override var description: String { return "Grilled artichokes" } func calculatePrice() -> Int { return 400 } } let a = A<Int>() // CHECK: Grilled artichokes // CHECK: Grilled artichokes print(a.description) print((a as NSObject).description) let f = { (a.x, a.y, a.z, a.t, a.first, a.second, a.third) } // CHECK: (0, 0, 0, 0, 16, nil, 61) print(f()) // CHECK: (25, 225, 255, 2255, 16, nil, 61) a.x = 25 a.y = 225 a.z = 255 a.t = 2255 print(f()) // CHECK: (36, 225, 255, 2255, 16, nil, 61) a.x = 36 print(f()) // CHECK: (36, 225, 255, 2255, 16, Optional(121), 61) a.second = 121 print(f()) // // Instantiate the class with a different set of generic parameters // let aa = A<(Int, Int)>() let ff = { (aa.x, aa.y, aa.z, aa.t, aa.first, aa.second, aa.third) } // CHECK: (0, 0, 0, 0, 16, nil, 61) print(ff()) aa.x = 101 aa.second = (19, 84) aa.third = 17 // CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17) print(ff()) // // Concrete subclass of generic subclass of @objc class // class B : A<(Int, Int)> { override var description: String { return "Salmon" } @nonobjc override func calculatePrice() -> Int { return 1675 } } class BB : B {} class C : A<(Int, Int)>, PP { @nonobjc override var description: String { return "Invisible Chicken" } override func calculatePrice() -> Int { return 650 } func calculateTaxes() -> Int { return 110 } } // CHECK: 400 // CHECK: 400 // CHECK: 650 // CHECK: 110 print((BB() as P).calculatePrice()) print((B() as P).calculatePrice()) print((C() as P).calculatePrice()) print((C() as PP).calculateTaxes()) // CHECK: Salmon // CHECK: Grilled artichokes print((B() as NSObject).description) print((C() as NSObject).description) let b = B() let g = { (b.x, b.y, b.z, b.t, b.first, b.second, b.third) } // CHECK: (0, 0, 0, 0, 16, nil, 61) print(g()) b.x = 101 b.second = (19, 84) b.third = 17 // CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17) print(g()) // // Generic subclass of @objc class without any generically-sized members // class FixedA<T> : HasHiddenIvars, P { var first: Int = 16 var second: [T] = [] var third: Int = 61 override var description: String { return "Grilled artichokes" } func calculatePrice() -> Int { return 400 } } let fixedA = FixedA<Int>() // CHECK: Grilled artichokes // CHECK: Grilled artichokes print(fixedA.description) print((fixedA as NSObject).description) let fixedF = { (fixedA.x, fixedA.y, fixedA.z, fixedA.t, fixedA.first, fixedA.second, fixedA.third) } // CHECK: (0, 0, 0, 0, 16, [], 61) print(fixedF()) // CHECK: (25, 225, 255, 2255, 16, [], 61) fixedA.x = 25 fixedA.y = 225 fixedA.z = 255 fixedA.t = 2255 print(fixedF()) // CHECK: (36, 225, 255, 2255, 16, [], 61) fixedA.x = 36 print(fixedF()) // CHECK: (36, 225, 255, 2255, 16, [121], 61) fixedA.second = [121] print(fixedF()) // // Instantiate the class with a different set of generic parameters // let fixedAA = FixedA<(Int, Int)>() let fixedFF = { (fixedAA.x, fixedAA.y, fixedAA.z, fixedAA.t, fixedAA.first, fixedAA.second, fixedAA.third) } // CHECK: (0, 0, 0, 0, 16, [], 61) print(fixedFF()) fixedAA.x = 101 fixedAA.second = [(19, 84)] fixedAA.third = 17 // CHECK: (101, 0, 0, 0, 16, [(19, 84)], 17) print(fixedFF()) // // Concrete subclass of generic subclass of @objc class // without any generically-sized members // class FixedB : FixedA<Int> { override var description: String { return "Salmon" } override func calculatePrice() -> Int { return 1675 } } // CHECK: 675 print((FixedB() as P).calculatePrice()) // CHECK: Salmon print((FixedB() as NSObject).description) let fixedB = FixedB() let fixedG = { (fixedB.x, fixedB.y, fixedB.z, fixedB.t, fixedB.first, fixedB.second, fixedB.third) } // CHECK: (0, 0, 0, 0, 16, [], 61) print(fixedG()) fixedB.x = 101 fixedB.second = [19, 84] fixedB.third = 17 // CHECK: (101, 0, 0, 0, 16, [19, 84], 17) print(fixedG()) // Problem with field alignment in direct generic subclass of NSObject - // <https://bugs.swift.org/browse/SR-2586> public class PandorasBox<T>: NSObject { final public var value: T public init(_ value: T) { // Uses ConstantIndirect access pattern self.value = value } } let c = PandorasBox(30) // CHECK: 30 // Uses ConstantDirect access pattern print(c.value) // Super method calls from a generic subclass of an @objc class class HasDynamicMethod : NSObject { @objc dynamic class func funkyTown() { print("Here we are with \(self)") } } class GenericOverrideOfDynamicMethod<T> : HasDynamicMethod { override class func funkyTown() { print("Hello from \(self) with T = \(T.self)") super.funkyTown() print("Goodbye from \(self) with T = \(T.self)") } } class ConcreteOverrideOfDynamicMethod : GenericOverrideOfDynamicMethod<Int> { override class func funkyTown() { print("Hello from \(self)") super.funkyTown() print("Goodbye from \(self)") } } // CHECK: Hello from ConcreteOverrideOfDynamicMethod // CHECK: Hello from ConcreteOverrideOfDynamicMethod with T = Int // CHECK: Here we are with ConcreteOverrideOfDynamicMethod // CHECK: Goodbye from ConcreteOverrideOfDynamicMethod with T = Int // CHECK: Goodbye from ConcreteOverrideOfDynamicMethod ConcreteOverrideOfDynamicMethod.funkyTown()
apache-2.0
4355b29bc204485f34f103d0313e864b
20.032028
108
0.646362
3.105623
false
false
false
false
psharanda/adocgen
Carthage/Checkouts/GRMustache.swift/Tests/Public/SuitesTests/twitter/hogan.js/HoganSuite.swift
1
2926
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Mustache class HoganSuite: SuiteTestCase { func testSuite() { // This suite contains template inheritance tests taken from // https://github.com/twitter/hogan.js/blob/master/test/index.js runTestsFromResource("template_inheritance.json", directory: "HoganSuite") } func testLambdaExpressionInInheritedTemplateSubsections() { // Test "Lambda expression in inherited template subsections" from hogan.js tests let lambda = Lambda { return "altered \($0)" } let templates = [ "partial": "{{$section1}}{{#lambda}}parent1{{/lambda}}{{/section1}} - {{$section2}}{{#lambda}}parent2{{/lambda}}{{/section2}}", "template": "{{< partial}}{{$section1}}{{#lambda}}child1{{/lambda}}{{/section1}}{{/ partial}}", ] let repo = TemplateRepository(templates: templates) let template = try! repo.template(named: "template") let rendering = try! template.render(["lambda": lambda]) XCTAssertEqual(rendering, "altered child1 - altered parent2") } func testBlah() { // Test "Lambda expression in included partial templates" from hogan.js tests let lambda = Lambda { return "changed \($0)" } let templates = [ "parent": "{{$section}}{{/section}}", "partial": "{{$label}}test1{{/label}}", "template": "{{< parent}}{{$section}}{{<partial}}{{$label}}{{#lambda}}test2{{/lambda}}{{/label}}{{/partial}}{{/section}}{{/parent}}", ] let repo = TemplateRepository(templates: templates) let template = try! repo.template(named: "template") let rendering = try! template.render(["lambda": lambda]) XCTAssertEqual(rendering, "changed test2") } }
mit
e851086802287ebf31ff1059bf1b6633
45.428571
145
0.666325
4.577465
false
true
false
false
cactis/SwiftEasyKit
Source/Classes/TextField.swift
1
5935
// // TextField.swift // // Created by ctslin on 3/31/16. import UIKit open class Password: TextField { override open func textRect(forBounds bounds: CGRect) -> CGRect { isSecureTextEntry = true return super.textRect(forBounds: bounds) } } open class TextField: UITextField { public var dx: CGFloat = 10 public var bordered = false { didSet { if bordered { borderStyle = .roundedRect } else { borderStyle = .none } } } public init(placeholder: String = "", bordered: Bool = false) { super.init(frame: .zero) self.placeholder = placeholder ({ self.bordered = bordered })() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func inset(bounds: CGRect) -> CGRect { let b = CGRect(origin: bounds.origin, size: CGSize(width: bounds.width - 20, height: bounds.height)) // return CGRectInset(b, bounds.width * 0.05, bounds.height * -0.03) return b.insetBy(dx: dx, dy: bounds.height * -0.03) } // placeholder position // override open func textRect(forBounds bounds: CGRect) -> CGRect { // if bounds.width > 100 { // rightViewMode = .always // clearButtonMode = .whileEditing // } // return inset(bounds: bounds) // // var rect: CGRect = super.textRectForBounds(bounds) // // var insets: UIEdgeInsets = UIEdgeInsetsMake(inset, inset, inset, inset) // // return UIEdgeInsetsInsetRect(rect, insets) // } // text position // override open func editingRect(forBounds _ bounds: CGRect) -> CGRect { // return inset(bounds) // // var rect: CGRect = super.editingRectForBounds(bounds) // // var insets: UIEdgeInsets = UIEdgeInsetsMake(inset, inset, inset, inset) // // return UIEdgeInsetsInsetRect(rect, insets) // } override open func clearButtonRect(forBounds bounds: CGRect) -> CGRect { let rect: CGRect = super.clearButtonRect(forBounds: bounds) return rect.offsetBy(dx: -5, dy: 0) } } //open class TextView: UITextView { // @discardableResult public func texted(value: String) -> TextView { // text = value // return self // } //} open class TextView: DefaultView, UITextViewDelegate { public var field = UITextView() public var clearButton = UIButton() var text: String! { get { return field.text } } override open func layoutUI() { super.layoutUI() layout([field, clearButton]) } override open func styleUI() { super.styleUI() clearButton.imaged(getIcon(.remove)).isHidden = true } @discardableResult public func texted(_ value: String) -> TextView { field.text = value return self } override open func bindUI() { super.bindUI() field.delegate = self clearButton.whenTapped { self.field.text = "" } } override open func layoutSubviews() { super.layoutSubviews() clearButton.anchorToEdge(.right, padding: 0, width: 14, height: 14) if field.isEditable { field.anchorAndFillEdge(.left, xPad: 0, yPad: 0, otherSize: clearButton.leftEdge()) } else { field.fillSuperview() } } public func textViewDidBeginEditing(_ textView: UITextView) { clearButton.isHidden = false } public func textViewDidEndEditing(_ textView: UITextView) { clearButton.isHidden = true } } private var kAssociationKeyNextField: UInt8 = 0 extension UITextField { public var nextField: UIView? { get { return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UIView } set(newField) { objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN) } } @discardableResult public func styled(_ options: NSDictionary = NSDictionary()) -> UITextField { text = text ?? Lorem.name() let color = options["color"] as? UIColor ?? K.Color.text let size: CGFloat = options["fontSize"] as? CGFloat ?? options["size"] as? CGFloat ?? K.Size.Text.normal let backgroundColor = options["backgroundColor"] as? UIColor ?? UIColor.clear textColor = color font = UIFont.systemFont(ofSize: size) self.backgroundColor = backgroundColor return self } } extension UITextView { public var nextField: UIView? { get { return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UIView } set(newField) { objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN) } } // // @discardableResult public func texted(text: String) -> UITextView { // return self // } // public func styled(options: NSDictionary = NSDictionary()) -> UITextView { // let lineHeight = options["lineHeight"] as? CGFloat ?? K.Size.Text.normal * 1.5 // let size: CGFloat = options["size"] as? CGFloat ?? K.Size.Text.normal // // let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle() // paragraphStyle.lineHeightMultiple = lineHeight // paragraphStyle.maximumLineHeight = lineHeight // paragraphStyle.minimumLineHeight = lineHeight // let ats = [NSFontAttributeName: UIFont.systemFont(ofSize: size), NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: K.Color.text] // attributedText = NSAttributedString(string: text, attributes: ats) // return self // } public func getHeightByWidth(_ width: CGFloat) -> CGFloat { return sizeThatFits(CGSize(width: width, height: 100000)).height } @discardableResult public func styled(options: NSDictionary = NSDictionary()) -> UITextView { text = text ?? Lorem.name() let color = options["color"] as? UIColor ?? K.Color.text let size: CGFloat = options["fontSize"] as? CGFloat ?? options["size"] as? CGFloat ?? K.Size.Text.normal let backgroundColor = options["backgroundColor"] as? UIColor ?? UIColor.clear textColor = color font = UIFont.systemFont(ofSize: size) self.backgroundColor = backgroundColor return self } }
mit
eb8839108eaac1a13d25a52ee4e4b4f8
29.911458
163
0.683235
4.245351
false
false
false
false
alberttra/A-Framework
Pod/Classes/CoreDataStack.swift
1
6257
// // CoreDataStack.swift // Pods // // Created by Albert Tra on 31/01/16. // // import Foundation import CoreData public class CoreDataStack { /// 758E8C5B-CF61-4D8A-A2EC-79DEBA46EE6A Pg. 65 // let modelName = "CoreData" /** Should be the same as your *.xcdatamodeld For example, if you create a data model named Customer.xcdatamodeld, the your model name in this case is Customer */ private var modelName: String! /** This is the name of core data which is stored in your device */ private var storeName: String! /** NSMigratePersistentStoresAutomaticallyOption: true Ref: itx | D01A6F5E-F9FD-4E01-808A-73B1A26D8FE5 NSInferMappingModelAutomaticallyOption: true Ref: itx | AA727045-16DD-44DE-B8C9-1AF813B798DB NSPersistentStoreUbiquitousContentNameKey: "Journey" Ref: itx | 3E18EDA3-78DE-4379-A10E-F2720A33AEF9 */ private var options: [NSObject: AnyObject]? /** updateContextWithUbiquitousContentUpdates is a flag that tells the stack to start or stop listening for the notification. It has a property observer, which sets an internal property to either the default notification center or nil. Using a property observer on that property actually starts or stops observing the notification Ref: /// itx | DA5339A0-2599-4723-BABE-A5C596833469 :Author: Albert Tra */ public var updateContextWithUbiquitousContentUpdates: Bool = false { willSet { ubiquitousChangesObserver = newValue ? NSNotificationCenter.defaultCenter() : nil } } /** :Author: Albert Tra */ private var ubiquitousChangesObserver: NSNotificationCenter? { didSet { oldValue?.removeObserver(self, name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: coordinator) /// itx | A78D64F1-FFAE-40CB-986E-FD981F548814 ubiquitousChangesObserver?.addObserver(self, selector: #selector(persistentStoreDidImportUbiquitousContentChanges(_:)), name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: coordinator) } } public init(modelName: String, storeName: String, options: [NSObject: AnyObject]? = nil) { self.modelName = modelName self.storeName = storeName self.options = options } lazy var model: NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")!)! var store: NSPersistentStore? var storeURL : NSURL { var storePaths = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true) as [String] let storePath = String(storePaths[0]) as NSString let fileManager = NSFileManager.defaultManager() do { try fileManager.createDirectoryAtPath(storePath as String, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print("Error creating storePath \(storePath): \(error)") } let sqliteFilePath = storePath.stringByAppendingPathComponent(storeName + ".sqlite") return NSURL(fileURLWithPath: sqliteFilePath) } lazy var coordinator : NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.model) do { self.store = try coordinator.addPersistentStoreWithType( NSSQLiteStoreType, configuration: nil, URL: self.storeURL, options: self.options) } catch let error as NSError { print("Store Error: \(error)") self.store = nil } catch { fatalError() } return coordinator }() /** Every time iCloud sync (merge) with others, this method will be called :Author: Albert Tra */ @objc func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) { print("\n6A6030A4-287E-4D43-B28C-2B0C1DDD6E1F \t persistentStoreDidImportUbiquitousContentChanges()") print("MERGING CHANGES FROM CONTEXT") managedObjectContext.performBlock { () -> Void in self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification) } } private lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")! // momd: 758E8C5B-CF61-4D8A-A2EC-79DEBA46EE6A Pg. 666 return NSManagedObjectModel(contentsOfURL: modelURL)! }() public lazy var managedObjectContext: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.coordinator return managedObjectContext }() public func save(completion completion: (done: Bool, error: NSError?) -> Void) { do { try managedObjectContext.save() completion(done: true, error: nil) } catch let error as NSError { completion(done: false, error: error) print(error.localizedDescription) } } public func delete(entityName: String, predicate: NSPredicate, completion: (done: Bool, error: NSError?) -> Void) { let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.predicate = predicate do { let results = try managedObjectContext.executeFetchRequest(fetchRequest) for object in results { managedObjectContext.deleteObject(object as! NSManagedObject) } // completion(done: true, error: error) completion(done: true, error: nil) } catch let error as NSError { completion(done: false, error: error) } } // public func create(entityName: String, completion: (done: Bool, error: NSError?) -> Void) { // // } } //extension CoreDataStack: NSManagedObjectContext { // //}
mit
70d79b2e1913f3f75c1ac7386a0bae5c
36.921212
331
0.662298
5.025703
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/结构体/Closures and Mutability.playgroundpage/Contents.swift
1
2826
/*: ## Closures and Mutability In this section, we'll look at how closures store data. For example, consider a function that generates a unique integer every time it gets called (until it reaches `Int.max`). It works by moving the state outside of the function. In other words, it *closes* over the variable `i`: */ //#-editable-code var i = 0 func uniqueInteger() -> Int { i += 1 return i } //#-end-editable-code /*: Every time we call this function, the shared variable `i` will change, and a different integer will be returned. Functions are reference types as well — if we assign `uniqueInteger` to another variable, the compiler won't copy the function (or `i`). Instead, it'll create a reference to the same function: */ //#-editable-code let otherFunction: () -> Int = uniqueInteger //#-end-editable-code /*: Calling `otherFunction` will have exactly the same effect as calling `uniqueInteger`. This is true for all closures and functions: if we pass them around, they always get passed by reference, and they always share the same state. Recall the function-based `fibsIterator` example from the collection protocols chapter, where we saw this behavior before. When we used the iterator, the iterator itself (being a function) was mutating its state. In order to create a fresh iterator for each iteration, we had to wrap it in an `AnySequence`. If we want to have multiple different unique integer providers, we can use the same technique: instead of returning the integer, we return a closure that captures the mutable variable. The returned closure is a reference type, and passing it around will share the state. However, calling `uniqueIntegerProvider` repeatedly returns a fresh function that starts at zero every time: */ //#-editable-code func uniqueIntegerProvider() -> () -> Int { var i = 0 return { i += 1 return i } } //#-end-editable-code /*: Instead of returning a closure, we can also wrap the behavior in an `AnyIterator`. That way, we can even use our integer provider in a for loop: */ //#-editable-code func uniqueIntegerProvider() -> AnyIterator<Int> { var i = 0 return AnyIterator { i += 1 return i } } //#-end-editable-code /*: Swift structs are commonly stored on the stack rather than on the heap. However, this is an optimization: by default, a struct is stored on the heap, and in almost all cases, the optimization will store the struct on the stack. When a struct variable is closed over by a function, the optimization doesn't apply, and the struct is stored on the heap. Because the `i` variable is closed over by the function, the struct exists on the heap. That way, it persists even when the scope of `uniqueIntegerProvider` exits. Likewise, if a struct is too large, it's also stored on the heap. */
mit
eb958191be4c8b22a63fc1e091dbba53
31.45977
80
0.735127
4.122628
false
false
false
false
sonnygauran/trailer
PocketTrailer/CommentBlacklistViewController.swift
1
2926
import UIKit final class CommentBlacklistViewController: UITableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Settings.commentAuthorBlacklist.count == 0 ? 0 : 1 } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Settings.commentAuthorBlacklist.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UsernameCell", forIndexPath: indexPath) cell.textLabel?.text = Settings.commentAuthorBlacklist[indexPath.row] return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { var blackList = Settings.commentAuthorBlacklist blackList.removeAtIndex(indexPath.row) Settings.commentAuthorBlacklist = blackList if blackList.count==0 { // last delete tableView.deleteSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Automatic) } else { tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } } @IBAction func addSelected() { let a = UIAlertController(title: "Block commenter", message: "Enter the username of the poster whose comments you don't want to be notified about", preferredStyle: UIAlertControllerStyle.Alert) a.addTextFieldWithConfigurationHandler({ textField in textField.placeholder = "Username" }) a.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) a.addAction(UIAlertAction(title: "Block", style: UIAlertActionStyle.Default, handler: { action in if let tf = a.textFields?.first, n = tf.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) { var name: String = n if name.characters.startsWith("@".characters) { name = name.substringFromIndex(name.startIndex.advancedBy(1)) } atNextEvent { [weak self] in if !name.isEmpty && !Settings.commentAuthorBlacklist.contains(name) { var blackList = Settings.commentAuthorBlacklist blackList.append(name) Settings.commentAuthorBlacklist = blackList let ip = NSIndexPath(forRow: blackList.count-1, inSection: 0) if blackList.count == 1 { // first insert self!.tableView.insertSections(NSIndexSet(index: 0), withRowAnimation:UITableViewRowAnimation.Automatic) } else { self!.tableView.insertRowsAtIndexPaths([ip], withRowAnimation:UITableViewRowAnimation.Automatic) } } } } })) presentViewController(a, animated: true, completion: nil) } }
mit
36632dd64758b6863582b1c0badb8bcb
38.540541
154
0.763158
4.773246
false
false
false
false
azimin/Rainbow
Rainbow/ColorGradientTemplate.swift
1
2111
// // UCColorGradientTemplate.swift // GetColorBetween // // Created by Alex Zimin on 18/03/16. // Copyright © 2016 Alex Zimin. All rights reserved. // import UIKit /* Alexander Zimin (azimin) Example of generating 5 colors between red and blue: let gradientTemplate = UCColorGradientTemplate(startColor: UIColor.redColor(), endColor: UIColor.blueColor()) let colors = gradientTemplate.getColorsWithNumberOfSteps(5) */ struct ColorGradientTemplate { private typealias colorRGBComponents = (red: Float, green: Float, blue: Float) private var startColorComponents: colorRGBComponents private var endColorComponents: colorRGBComponents init(startColor: Color, endColor: Color) { startColorComponents = (red: startColor.red(), green: startColor.green(), blue: startColor.blue()) endColorComponents = (red: endColor.red(), green: endColor.green(), blue: endColor.blue()) } /* return color that locate between `startColor` and `endColor` 0 <= percent <= 1 */ func getColorBetweenWithPercentMove(percent: Float) -> Color { assert(percent >= 0, "Percent must be more or equal than 0") assert(percent <= 1, "Percent must be lest or equal than 1") let red = startColorComponents.red + percent * (endColorComponents.red - startColorComponents.red) let green = startColorComponents.green + percent * (endColorComponents.green - startColorComponents.green) let blue = startColorComponents.blue + percent * (endColorComponents.blue - startColorComponents.blue) return Color(red: red, green: green, blue: blue) } /* return array of colors that located between `startColor` and `endColor` (included bounds) numberOfSteps >= 2 */ func getColorsWithNumberOfSteps(numberOfSteps: Int) -> [Color] { assert(numberOfSteps >= 2, "Number of steps must be more or equal than 2") let step = 1 / Float(numberOfSteps - 1) var colors = [Color]() for i in 0..<numberOfSteps { let color = getColorBetweenWithPercentMove(step * Float(i)) colors.append(color) } return colors } }
mit
08c7c135b4abf3caf969c6be19336e0c
32.492063
111
0.706635
4.36853
false
false
false
false
Donny8028/Swift-TinyFeatures
PhotoPicker/PhotoPicker/ImagePickerSheetController/Sheet/SheetActionCollectionViewCell.swift
1
1790
// // SheetActionCollectionViewCell.swift // ImagePickerSheetController // // Created by Laurin Brandner on 26/08/15. // Copyright © 2015 Laurin Brandner. All rights reserved. // import UIKit private var KVOContext = 0 class SheetActionCollectionViewCell: SheetCollectionViewCell { lazy private(set) var textLabel: UILabel = { let label = UILabel() label.textColor = self.tintColor label.textAlignment = .Center self.addSubview(label) return label }() // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { textLabel.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions(rawValue: 0), context: &KVOContext) } deinit { textLabel.removeObserver(self, forKeyPath: "text") } // MARK: - Accessibility override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard context == &KVOContext else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) return } accessibilityLabel = textLabel.text } // MARK: - override func tintColorDidChange() { super.tintColorDidChange() textLabel.textColor = tintColor } override func layoutSubviews() { super.layoutSubviews() textLabel.frame = UIEdgeInsetsInsetRect(bounds, backgroundInsets) } }
mit
35169f26cc8f2f42c9fb3ec4d943fdbd
24.557143
157
0.622694
5.292899
false
false
false
false
koogawa/iSensorSwift
iSensorSwift/Controller/AltitudeViewController.swift
1
1814
// // AltitudeViewController.swift // iSensorSwift // // Created by koogawa on 2016/03/27. // Copyright © 2016 koogawa. All rights reserved. // import UIKit import CoreLocation class AltitudeViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var textField: UITextField! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() if CLLocationManager.locationServicesEnabled() { locationManager = CLLocationManager() locationManager.delegate = self locationManager.startUpdatingLocation() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if CLLocationManager.locationServicesEnabled() { locationManager.stopUpdatingLocation() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CLLocationManager delegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .notDetermined: locationManager.requestWhenInUseAuthorization() case .restricted, .denied: break case .authorizedAlways, .authorizedWhenInUse: break } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let newLocation = locations.last, CLLocationCoordinate2DIsValid(newLocation.coordinate) else { self.textField.text = "Error" return } self.textField.text = "".appendingFormat("%.2f m", newLocation.altitude) } }
mit
d4765e8bcf8a2de918ffbf78307a5e98
28.241935
110
0.664093
5.905537
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/User/UserDetail/UserDetailTableView.swift
1
1810
// // UserDetailTableView.swift // Rocket.Chat // // Created by Matheus Cardoso on 6/26/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit class UserDetailTableView: UITableView { var additionalTopInset: CGFloat = 0 { didSet { contentInset = UIEdgeInsets(top: headerViewHeight - topInset, left: 0, bottom: 16, right: 0) } } private var topInset: CGFloat { return UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 0 } private var headerViewHeight: CGFloat { return 220 + topInset + additionalTopInset } var preferredContentSize: CGSize { let height = headerViewHeight + contentSize.height let width = CGFloat(300) return CGSize(width: width, height: height) } lazy var headerView: UIView = { let headerView = tableHeaderView ?? UIView() tableHeaderView = nil contentInset = UIEdgeInsets(top: headerViewHeight - topInset, left: 0, bottom: 16, right: 0) return headerView }() override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) addSubview(headerView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(headerView) } override func layoutSubviews() { super.layoutSubviews() updateHeaderView() } private func updateHeaderView() { var headerRect = CGRect( x: 0, y: -headerViewHeight, width: bounds.width, height: headerViewHeight ) if contentOffset.y < -headerViewHeight { headerRect.origin.y = contentOffset.y headerRect.size.height = -contentOffset.y } headerView.frame = headerRect } }
mit
44a0f3cbf26fb2f47655f292c55d2ace
26
104
0.628524
4.773087
false
false
false
false
CSSE497/pathfinder-ios
examples/ClusterObserver/ClusterObserver/AppDelegate.swift
1
4329
// // AppDelegate.swift // ClusterObserver // // Created by Adam Michael on 10/25/15. // Copyright © 2015 Pathfinder. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { let GMSAPIKey = "AIzaSyCxkw1-mYOy6nsSTdyQ6CIjOjIRP33iIxY" var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { GMSServices.provideAPIKey(GMSAPIKey) return true } func applicationWillTerminate(application: UIApplication) { 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 "io.pathfinder.ClusterObserver" 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("ClusterObserver", 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
23edd108b51def87e12eec9235604beb
46.043478
289
0.726201
5.613489
false
false
false
false
DylanModesitt/Verb
Verb/Verb/SettingsTableTableViewController.swift
1
3271
// // SettingsTableTableViewController.swift // Verb // // Created by Dylan Modesitt on 12/2/15. // Copyright © 2015 Verb. All rights reserved. // import UIKit class SettingsTableTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } */ /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
6ea1617a6c2f3e0c8c3b092341c00da3
32.030303
157
0.684404
5.599315
false
false
false
false
bradhilton/August
Sources/Callbacks/Callbacks.swift
1
2583
// // Callbacks.swift // Request // // Created by Bradley Hilton on 2/6/16. // Copyright © 2016 Brad Hilton. All rights reserved. // public typealias ChallengeCallback = (_ challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) public typealias StartCallback = (_ task: Task) -> Void public typealias ProgressCallback = (_ task: Task) -> Void public typealias FailureCallback = (_ error: Error, _ request: Request) -> Void public typealias CompletionCallback = (_ response: Response<Data>?, _ errors: [Error], _ request: Request) -> Void internal struct ErrorCallback { let callback: (_ error: Error, _ request: Request) -> Void init(callback: @escaping (_ error: Error, _ request: Request) -> Void) { self.callback = callback } init<T : Error>(callback: @escaping (_ error: T, _ request: Request) -> Void) { self.callback = { (error, request) in if let error = error as? T { callback(error, request) } } } } protocol ReponseCallbackProtocol { var callback: (_ response: Response<Data>, _ queue: OperationQueue) throws -> Void { get } init(callback: (_ response: Response<Data>, _ queue: OperationQueue) throws -> Void) } internal struct ResponseCallback { let callback: (_ response: Response<Data>, _ queue: OperationQueue) throws -> Void init<T>(responseCodes: Set<Int>, callback: @escaping (_ response: Response<T>) -> Void) { self.callback = responseCallback(successCallback: false, responseCodes: responseCodes, callback: callback) } } internal struct SuccessCallback { let callback: (_ response: Response<Data>, _ queue: OperationQueue) throws -> Void init<T>(responseCodes: Set<Int>, callback: @escaping (_ response: Response<T>) -> Void) { self.callback = responseCallback(successCallback: true, responseCodes: responseCodes, callback: callback) } } private func responseCallback<T>( successCallback: Bool, responseCodes: Set<Int>, callback: @escaping (_ response: Response<T>) -> Void) -> (_ response: Response<Data>, _ queue: OperationQueue) throws -> Void { return { (response, queue) in guard responseCodes.contains(response.statusCode) else { if successCallback { throw ResponseError(response: response) } return } let newResponse = try Response<T>(response) queue.addOperation { callback(newResponse) } } }
mit
86d291e8f4913573f97865ca28b3acfc
32.973684
135
0.641751
4.521891
false
false
false
false
ivanmoskalev/Chop
lib/TaskGroup.swift
1
3722
// // TaskGroup.swift // Chop // // Copyright (C) 2016 Ivan Moskalev // // This software may be modified and distributed under the terms of the MIT license. // See the LICENSE file for details. // import Foundation /** `TaskGroup` is a class representing an execution context for instances of `Task`. `TaskGroup`s manage execution of tasks, disposing of those that are finished, and, optionally, enforcing uniqueness. */ public final class TaskGroup: TaskType { /** An enumeration defining the behavior of the `TaskGroup` when a new task is added with an identifier that is already used in this `TaskGroup`. */ public enum Policy { /// The new task replaces the old one, terminating it. case replace /// The new task is ignored and terminated, if there are no other references to it. case ignore } /// A dictionary of tasks retrievable by task identifiers. fileprivate(set) var tasks = [String: TaskType]() /// Whether the tasks should start immediately upon being added. public let startsImmediately: Bool /// The policy defining how to treat a new task with a conflicting identifier. For list of possible values see `Policy`. public let policy: Policy /// The lock that protects `tasks` dictionary. fileprivate let tasksLock = NSRecursiveLock() ////////////////////////////////////////////////// // Init /** Creates a `TaskGroup` with supplied options. - parameter policy: The policy defining how to treat a new task with a conflicting identifier. Default is `Policy.Ignore`. - parameter startsImmediately: Whether the tasks should be started immediately upon addition. Default is `true`. - returns: An instance of `TaskGroup`. */ public init(policy: Policy = .ignore, startsImmediately: Bool = true) { self.policy = policy self.startsImmediately = startsImmediately } ////////////////////////////////////////////////// // Public /** Registers a task in the group under given identifier. If a task with a given identifier is already in the queue, the behavior is defined by `policy` property of a `TaskGroup`. By default the task is registered with an unique identifier. - parameter task: An object of `TaskType` to register. - parameter taskId: Optional. The identifier of this task. Default value is an UUID string. */ public func register(_ task: TaskType, taskId: String = UUID().uuidString) { tasksLock.lock() removeFinished() if policy == .replace || tasks[taskId] == nil { tasks[taskId] = task subscribeToCompletion(task) if startsImmediately { task.start() } } tasksLock.unlock() } /** Starts all the managed tasks, if they are not started already. If `startsImmediately` is true, this method is a de-facto no-op. */ public func start() { for (_, task) in tasks { task.start() } } /** Silently cancels all managed tasks. */ public func cancel() { for (_, task) in tasks { task.cancel() } } /** Always returns `false`. */ public func isFinished() -> Bool { return false } ////////////////////////////////////////////////// // Private /** Removes all tasks that are finished, freeing up the resources. */ fileprivate func removeFinished() { tasksLock.lock() for (key, task) in tasks where task.isFinished() { tasks[key] = nil } tasksLock.unlock() } /** Adds call to `removeFinished` on task completion. */ fileprivate func subscribeToCompletion(_ task: TaskType) { guard let task = task as? CompletionSubscribable else { return } task.onCompletion { [weak self] in self?.removeFinished() } } }
mit
625370433606e6cdd391027dfc9c1f65
27.630769
144
0.649919
4.572482
false
false
false
false
BillyBons/Attendees
Sources/App/Controllers/AdminController.swift
1
1223
// // AdminController.swift // Attendees // // Created by Sergiy Bilyk on 11.12.16. // // import Vapor import HTTP final class AdminController { func addRoutes(drop: Droplet) { drop.get("admin", handler: indexView) drop.post("admin", handler: addAttendee) drop.post("admin", Attendee.self, "delete", handler: deleteAttendee) } func indexView(request: Request) throws -> ResponseRepresentable { let attendees = try Attendee.all().makeNode() let parameters = try Node(node: [ "attendees" : attendees ]) return try drop.view.make("index", parameters) } func addAttendee(request: Request) throws -> ResponseRepresentable { guard let name = request.data["name"]?.string, let email = request.data["email"]?.string else { throw Abort.badRequest } var attendee = Attendee(name: name, email: email) try attendee.save() return Response(redirect: "/admin") } func deleteAttendee(request: Request, attendee: Attendee) throws -> ResponseRepresentable { try attendee.delete() return Response(redirect: "/admin") } }
mit
ca4139b61f7b168c7543d0233150f225
28.119048
96
0.609158
4.431159
false
false
false
false
bhajian/raspi-remote
Carthage/Checkouts/ios-sdk/Source/DocumentConversionV1/Models/ConversionResponse.swift
1
1656
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Freddy /** **ConversionResponse** Response object for Document Conversion calls */ public struct ConversationResponse: JSONDecodable { /** Id of the source document */ public let sourceDocId: String? /** Time of document conversion */ public let timestamp: String? /** The type of media autodetected by the service */ public let detectedMediaType: String? /** see **ConversionMetadata** */ public let metadata: [ConversionMetadata]? /** see **AnswerUnits**/ public let answerUnits: [AnswerUnits]? /** used inernally to initialize ConversationResponse objects */ public init(json: JSON) throws { sourceDocId = try? json.string("source_document_id") timestamp = try? json.string("timestamp") detectedMediaType = try? json.string("media_type_detected") metadata = try? json.arrayOf("metadata", type: ConversionMetadata.self) answerUnits = try? json.arrayOf("answer_units", type: AnswerUnits.self) } }
mit
745a3219cc05115b0f28f296ccc597fa
30.264151
79
0.691425
4.512262
false
false
false
false
BluechipSystems/viper-module-generator
VIPERGenDemo/VIPERGenDemo/Shared/Controllers/TwitterList/DataManager/Local/TwitterListLocalDataManager.swift
4
4334
// // TwitterListLocalDataManager.swift // TwitterListGenDemo // // Created by AUTHOR on 24/10/14. // Copyright (c) 2014 AUTHOR. All rights reserved. // import Foundation import CoreData class TwitterListLocalDataManager: TwitterListLocalDataManagerInputProtocol, NSFetchedResultsControllerDelegate { init() {} var fetchedResultsController: NSFetchedResultsController? var interactor: TwitterListLocalDataManagerOutputProtocol? func logoutUser() { logoutFunction() } func loadLocalTweets() { self.fetchedResultsController = Tweet.all().sorted(by: "date", ascending: false).fetchedResultsController(nil) self.fetchedResultsController!.delegate = self var error: NSError? self.fetchedResultsController!.performFetch(&error) if error != nil { println("Error initializing fetched results controller")} } func mostRecentTweetIdentifier() -> Double? { let foundTweets: [AnyObject]? = Tweet.all().sorted(by: "identifier", ascending: true).find() as [AnyObject]? let tweet: Tweet? = (foundTweets as [Tweet]).last? return tweet?.identifier.doubleValue } func oldestTweetDate() -> NSDate? { let foundTweets: [AnyObject]? = Tweet.all().sorted(by: "identifier", ascending: true).find() as [AnyObject]? let tweet: Tweet? = (foundTweets as [Tweet]).first? return tweet?.date } func persist(#tweets: [TwitterListItem]) { SugarRecord.operation(inBackground: true, stackType: SugarRecordStackType.SugarRecordStackTypeCoreData) { (context) -> () in context.beginWriting() var allTweets: [Tweet]? = Tweet.all().find(inContext: context) as [Tweet]? if (allTweets == nil) { allTweets = [Tweet]() } for twitterListItem: TwitterListItem in tweets { let tweetAlreadyExists: Bool = allTweets!.filter({ (tweet: Tweet) -> Bool in return tweet.identifier.isEqual(twitterListItem.identifier!) }).count != 0 if (tweetAlreadyExists) { continue } var tweet: Tweet = Tweet.create(inContext: context) as Tweet tweet.username = twitterListItem.username! tweet.avatar = twitterListItem.avatar! tweet.date = twitterListItem.date! tweet.identifier = twitterListItem.identifier! tweet.body = twitterListItem.body! } context.endWriting() } } func numberOfTweets(inSection section: Int) -> Int { if (self.fetchedResultsController != nil) { let s = (self.fetchedResultsController!.sections as? [NSFetchedResultsSectionInfo])! return s[section].numberOfObjects } return 0 } func numberOfSections() -> Int { if (self.fetchedResultsController != nil) { return self.fetchedResultsController!.sections!.count} return 0 } func twitterListItemAtIndexPath(indexPath: NSIndexPath) -> TwitterListItem { let object: AnyObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) return TwitterListItem(tweet: object as Tweet) } //MARK: NSFetchedResultsControllerProtocol func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { self.interactor?.tweetDidChange(TwitterListChangeType.from(type), tweet: TwitterListItem(tweet: anObject as Tweet), atIndexPath: indexPath?, newIndexPath: newIndexPath?) } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { self.interactor?.tweetSectionsDidChange(TwitterListChangeType.from(type), atIndex: sectionIndex) } func controllerWillChangeContent(controller: NSFetchedResultsController) { self.interactor?.tweetsListWillChange() } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.interactor?.tweetsListDidChange() } }
mit
5c26027705913acef818bb110af8c656
37.705357
209
0.66982
5.390547
false
false
false
false
KnuffApp/Knuff-iOS
Knuff/Controllers/ServiceAdvertiser.swift
1
1719
// // ServiceAdvertiser.swift // Knuff // // Created by Simon Blommegard on 03/04/15. // Copyright (c) 2015 Bowtie. All rights reserved. // import Foundation import MultipeerConnectivity class ServiceAdvertiser: NSObject { var serviceAdvertiser: MCNearbyServiceAdvertiser? var deviceTokenString: String? func setDeviceToken(_ deviceToken: Data?) { if let token = deviceToken { let tokenChars = (token as NSData).bytes.bindMemory(to: CChar.self, capacity: token.count) var tokenString = "" for i in 0 ..< token.count { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } deviceTokenString = tokenString } else { deviceTokenString = nil } advertise() } func advertise() { if let advertiser = serviceAdvertiser { advertiser.stopAdvertisingPeer() } if let tokenString = deviceTokenString { let peerID = MCPeerID(displayName: UIDevice.current.name) serviceAdvertiser = MCNearbyServiceAdvertiser( peer: peerID, discoveryInfo: ["token": tokenString], serviceType: "knuff" ) serviceAdvertiser?.delegate = self serviceAdvertiser?.startAdvertisingPeer(); } } } extension ServiceAdvertiser: MCNearbyServiceAdvertiserDelegate { func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) { } func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) { invitationHandler(false, MCSession()) } }
mit
b3058123f7b550611fb1a46e2ee5a035
24.656716
192
0.670157
5.177711
false
false
false
false
edx/edx-app-ios
Source/JSONFormBuilderChooser.swift
1
6502
// // JSONFormBuilderChooser.swift // edX // // Created by Michael Katz on 10/1/15. // Copyright © 2015 edX. All rights reserved. // import Foundation private class JSONFormTableSelectionCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) tintColor = OEXStyles.shared().primaryBaseColor() contentView.accessibilityIdentifier = "JSONFormTableSelectionCell:content-view" textLabel?.accessibilityIdentifier = "JSONFormTableSelectionCell:title-label" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private let cellIdentifier = "Cell" class JSONFormViewController<T>: UIViewController { /** Options Selector Table */ private lazy var tableView = UITableView() var dataSource: ChooserDataSource<T>? var instructions: String? var subInstructions: String? var doneChoosing: ((_ value:T?)->())? init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func makeAndInstallHeader() { if let instructions = instructions { let headerView = UIView() headerView.accessibilityIdentifier = "JSONFormViewController:header-view" headerView.backgroundColor = OEXStyles.shared().neutralXLight() let instructionStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralBlackT()) let headerStr = instructionStyle.attributedString(withText: instructions).mutableCopy() as! NSMutableAttributedString if let subInstructions = subInstructions { let style = OEXTextStyle(weight: .normal, size: .xSmall, color: OEXStyles.shared().neutralXXDark()) let subStr = style.attributedString(withText: "\n" + subInstructions) headerStr.append(subStr) } let label = UILabel() label.accessibilityIdentifier = "JSONFormViewController:heaer-title-label" label.attributedText = headerStr label.numberOfLines = 0 headerView.addSubview(label) label.snp.makeConstraints { make in make.top.equalTo(headerView.snp.topMargin) make.bottom.equalTo(headerView.snp.bottomMargin) make.leading.equalTo(headerView.snp.leading).offset(20) make.trailing.equalTo(headerView.snp.trailing).inset(20) } let size = label.sizeThatFits(CGSize(width: 240, height: CGFloat.greatestFiniteMagnitude)) headerView.frame = CGRect(origin: .zero, size: size) tableView.tableHeaderView = headerView } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = OEXStyles.shared().standardBackgroundColor() tableView.register(JSONFormTableSelectionCell.self, forCellReuseIdentifier: cellIdentifier) tableView.dataSource = dataSource tableView.delegate = dataSource tableView.cellLayoutMarginsFollowReadableWidth = false makeAndInstallHeader() addSubViews() setAccessibilityIdentifiers() } private func setAccessibilityIdentifiers() { view.accessibilityIdentifier = "JSONFormViewController:view" tableView.accessibilityIdentifier = "JSONFormViewController:table-view" } private func addSubViews() { view.addSubview(tableView) setConstraints() } private func setConstraints() { tableView.snp.makeConstraints { make in make.edges.equalTo(safeEdges) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) OEXAnalytics.shared().trackScreen(withName: OEXAnalyticsScreenChooseFormValue + " " + (title ?? "")) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard let index = dataSource?.selectedIndex else { return } tableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .middle, animated: false) } override func willMove(toParent parent: UIViewController?) { if parent == nil { //removing from the hierarchy doneChoosing?(dataSource?.selectedItem) } } } struct ChooserDatum<T> { let value: T let title: String? let attributedTitle: NSAttributedString? } class ChooserDataSource<T> : NSObject, UITableViewDataSource, UITableViewDelegate { let data: [ChooserDatum<T>] var selectedIndex: Int = -1 var selectedItem: T? { return selectedIndex < data.count && selectedIndex >= 0 ? data[selectedIndex].value : nil } init(data: [ChooserDatum<T>]) { self.data = data super.init() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.applyStandardSeparatorInsets() let datum = data[indexPath.row] if let title = datum.attributedTitle { cell.textLabel?.attributedText = title } else { cell.textLabel?.text = datum.title } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let oldIndexPath = selectedIndex selectedIndex = indexPath.row var rowsToRefresh = [indexPath] if oldIndexPath != -1 { rowsToRefresh.append(IndexPath(row: oldIndexPath, section: indexPath.section)) } tableView.reloadRows(at: rowsToRefresh, with: .automatic) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.accessoryType = indexPath.row == selectedIndex ? .checkmark : .none } }
apache-2.0
f0e0fdeb294ea398b9e6e5064fd83581
35.116667
129
0.650515
5.285366
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCCountTableViewCell.swift
2
1637
// // NCCountTableViewCell.swift // Neocom // // Created by Artem Shimanski on 07.02.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit class NCCountTableViewCell: NCTableViewCell { @IBOutlet weak var pickerView: UIPickerView? } extension Prototype { enum NCCountTableViewCell { static let `default` = Prototype(nib: nil, reuseIdentifier: "NCCountTableViewCell") } } class NCCountRow: TreeRow, UIPickerViewDataSource, UIPickerViewDelegate { var value: Int var range: Range<Int> init(value: Int, range: Range<Int>) { self.value = value self.range = range super.init(prototype: Prototype.NCCountTableViewCell.default) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCCountTableViewCell else {return} cell.pickerView?.dataSource = self cell.pickerView?.delegate = self cell.pickerView?.reloadAllComponents() cell.pickerView?.selectRow(value - range.lowerBound, inComponent: 0, animated: false) } //MARK: - UIPickerViewDataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return range.count } //MARK: - UIPickerViewDelegate func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { return String(range.lowerBound + row) * [NSAttributedStringKey.foregroundColor: pickerView.tintColor] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { value = range.lowerBound + row } }
lgpl-2.1
7bfe680983324a60d9d2d5444ccdc6d3
27.206897
130
0.751222
4.100251
false
false
false
false
AlvinL33/TownHunt
TownHunt-1.1 (LoginScreen)/TownHunt/RegistrationPageViewController.swift
1
4112
// // RegistrationPageViewController.swift // TownHunt // // Created by Alvin Lee on 18/02/2017. // Copyright © 2017 LeeTech. All rights reserved. // import UIKit class RegistrationPageViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var userEmailTextField: UITextField! @IBOutlet weak var userPasswordTextField: UITextField! @IBOutlet weak var userRepeatPassWordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "registrationBackgroundImage")?.draw(in: self.view.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func registerButtonTapped(_ sender: Any) { let username = usernameTextField.text let userEmail = userEmailTextField.text let userPassword = userPasswordTextField.text let userRepeatPassword = userRepeatPassWordTextField.text //Check for empty fields if((username?.isEmpty)! || (userEmail?.isEmpty)! || (userPassword?.isEmpty)! || (userRepeatPassword?.isEmpty)!) { //Display error message displayAlertMessage(alertTitle: "Data Entry Error", alertMessage: "All fields must be complete") return } //Check if passwords are the same if(userPassword != userRepeatPassword){ //Displays error message displayAlertMessage(alertTitle: "ERROR", alertMessage: "Passwords do not match") return } //Sends data to be posted and receives a response let responseJSON = DatabaseInteraction().postToDatabase(apiName: "registerUser.php", postData: "username=\(username!)&userEmail=\(userEmail!)&userPassword=\(userPassword!)"){ (dbResponse: NSDictionary) in //If there is an error, the error is presented to the user var alertTitle = "ERROR" var alertMessage = "JSON File Invalid" var isUserRegistered = false if dbResponse["error"]! as! Bool{ print("error: \(dbResponse["error"]!)") alertTitle = "ERROR" alertMessage = dbResponse["message"]! as! String } else if !(dbResponse["error"]! as! Bool){ alertTitle = "Thank You" alertMessage = dbResponse["message"]! as! String isUserRegistered = true } else{ alertTitle = "ERROR" alertMessage = "JSON File Invalid" } DispatchQueue.main.async(execute: { let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in if isUserRegistered{ self.dismiss(animated: true, completion: nil) }})) self.present(alertCon, animated: true, completion: nil) }) } } @IBAction func alreadyHaveAccountButtonTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil) } func displayAlertMessage(alertTitle: String, alertMessage: String){ let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertCon, animated: true, completion: nil) } }
apache-2.0
dec2e204a780fed86f11c8d0f66a0c5e
34.747826
212
0.60253
5.733612
false
false
false
false
TruckMuncher/TruckMuncher-iOS
TruckMuncher/ServingModePulse.swift
1
3002
// // ServingModePulse.swift // TruckMuncher // // Adapted by Andrew Moore on 10/18/14 From: // YQViewController.swift // yiqin on 7/12/14 // https://github.com/yiqin/Pulse-Animation // // Copyright (c) 2014 TruckMuncher. All rights reserved. // import UIKit class ServingModePulse: CALayer { var radius: CGFloat var fromValueForRadius: CGFloat var fromValueForAlpha: CGFloat var keyTimeForHalfOpacity: CGFloat var animationDuration: NSTimeInterval var pulseInterval: NSTimeInterval var animationGroup: CAAnimationGroup override init() { self.radius = 60 self.fromValueForRadius = 0.0 self.fromValueForAlpha = 0.45 self.keyTimeForHalfOpacity = 0.2 self.animationDuration = 2 self.pulseInterval = 0 self.animationGroup = CAAnimationGroup(); super.init() self.repeatCount = Float.infinity; self.backgroundColor = pinkColor.CGColor; var tempPos = self.position; var diameter = self.radius * 2; self.bounds = CGRectMake(0, 0, diameter, diameter); self.cornerRadius = self.radius; self.position = tempPos; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { self.setupAnimationGroup() dispatch_async(dispatch_get_main_queue(), { self.addAnimation(self.animationGroup, forKey: "pulse") }) }) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupAnimationGroup() { self.animationGroup = CAAnimationGroup() self.animationGroup.duration = self.animationDuration + self.pulseInterval self.animationGroup.repeatCount = self.repeatCount self.animationGroup.removedOnCompletion = false self.animationGroup.fillMode = kCAFillModeForwards; self.animationGroup.delegate = self var defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) self.animationGroup.timingFunction = defaultCurve var scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = self.fromValueForRadius scaleAnimation.toValue = 1.0; scaleAnimation.duration = self.animationDuration; var opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.values = [self.fromValueForAlpha, 0.45, 0] opacityAnimation.keyTimes = [0, self.keyTimeForHalfOpacity, 1] opacityAnimation.duration = self.animationDuration opacityAnimation.removedOnCompletion = false var animations = [scaleAnimation, opacityAnimation] self.animationGroup.animations = animations } override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { self.removeFromSuperlayer() } }
gpl-2.0
29aa3aebec3fd5e2528709864e6a8fac
32.730337
87
0.660227
5.028476
false
false
false
false
acelan/superfour2
Stone.swift
1
2712
// // Stone.swift // SuperFour2 // // Created by AceLan Kao on 2014/6/10. // Copyright (c) 2014年 AceLan Kao. All rights reserved. // import UIKit class Stone : UIView { var color: UIColor var radius: UInt let CHEESE_RADIUS: CGFloat = 25 init(frame f: CGRect, color c: UIColor) { color = c // TODO: should use display resolution to calc the radius radius = 25 super.init(frame: f) opaque = false userInteractionEnabled = true } func drawCheese(context: CGContextRef) { CGContextSetLineWidth(context, 5.0) color.setStroke() // draw a circle CGContextBeginPath(context); CGContextAddArc(context, CGFloat(3+radius), CGFloat(3+radius), CGFloat(radius), CGFloat(0), CGFloat(2*M_PI), 1); CGContextStrokePath(context); var points: CGPoint[] = [ CGPointMake(0, CGFloat(arc4random() % 60)), CGPointMake(60, CGFloat(arc4random() % 60)), CGPointMake(0, CGFloat(arc4random() % 60)), CGPointMake(60, CGFloat(arc4random() % 60)), CGPointMake(0, CGFloat(arc4random() % 60)), CGPointMake(60, CGFloat(arc4random() % 60)) ] CGContextBeginPath(context); CGContextAddLines(context, points, UInt(points.count)); CGContextStrokePath(context); } func moveTo(pt: CGPoint) { UIView.beginAnimations("moveStone", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut) UIView.setAnimationDuration(1.0) var rect: CGRect = self.frame rect.origin.x = pt.x - CHEESE_RADIUS; rect.origin.y = pt.y - CHEESE_RADIUS; // move to new location self.frame = rect; UIView.commitAnimations() } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() UIGraphicsPushContext(context) drawCheese(context) UIGraphicsPopContext() } override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) { UIView.beginAnimations("moveStone", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut) UIView.setAnimationDuration(1.0) let touch: UITouch = touches.anyObject() as UITouch let pt = touch.locationInView(superview) var rect = frame rect.origin.x = pt.x - CHEESE_RADIUS rect.origin.y = pt.y - CHEESE_RADIUS frame = rect NSLog("[%@,%d] position= (%f,%f) -> (%f,%f)", __FUNCTION__, __LINE__,pt.x,pt.y,rect.origin.x,rect.origin.y) UIView.commitAnimations() } }
mit
46a61721af3a6575edc3bfc3a2a81d51
30.894118
120
0.601476
4.34992
false
false
false
false
Spriter/SwiftyHue
Sources/BridgeServices/BridgeFinder/Validator/BridgeResultParser.swift
1
4209
// // BridgeResultParser.swift // HueSDK // // Created by Nils Lattek on 24.04.16. // Copyright © 2016 Nils Lattek. All rights reserved. // import Foundation class BridgeResultParser: NSObject, XMLParserDelegate { private let parser: XMLParser private var element: String = "" private var bridge: HueBridge? private var successBlock: ((_ bridge: HueBridge) -> Void)? private var failureBlock: ((_ error: NSError) -> Void)? private var urlBase: String = "" private var ip: String = "" private var deviceType: String = "" private var friendlyName: String = "" private var modelDescription: String = "" private var modelName: String = "" private var serialNumber: String = "" private var UDN: String = "" private var icons = [HueBridgeIcon]() private var mimetype: String = "" private var height: String = "" private var width: String = "" private var iconName: String = "" init(xmlData: Data) { parser = XMLParser(data: xmlData) super.init() parser.delegate = self } func parse(_ success: @escaping (_ bridge: HueBridge) -> Void, failure: @escaping (_ error: NSError) -> Void) { self.successBlock = success self.failureBlock = failure parser.parse() } private func cancelWithError(_ errorMessage: String) { parser.abortParsing() if let failureBlock = failureBlock { failureBlock(NSError(domain: "HueBridgeParser", code: 500, userInfo: [NSLocalizedDescriptionKey: errorMessage])) } } // MARK: - NSXMLParserDelegate public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { element = elementName if elementName == "root" { if attributeDict["xmlns"] == nil || attributeDict["xmlns"] != "urn:schemas-upnp-org:device-1-0" { cancelWithError("XML is not a known HueBridge XML.") } } else if elementName == "icon" { mimetype = "" height = "" width = "" iconName = "" } } public func parser(_ parser: XMLParser, foundCharacters string: String) { switch element { case "deviceType": deviceType += string case "friendlyName": friendlyName += string case "modelDescription": modelDescription += string case "modelName": modelName += string case "serialNumber": serialNumber += string case "UDN": UDN += string case "URLBase": urlBase += string case "mimetype": mimetype += string case "height": height += string case "width": width += string case "url": iconName += string default: break } } public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { element = "" if elementName == "device" { if isBridgeDataValid() { bridge = HueBridge(ip: ip, deviceType: deviceType, friendlyName: friendlyName, modelDescription: modelDescription, modelName: modelName, serialNumber: serialNumber, UDN: UDN, icons: icons) } else { cancelWithError("HueBridge data not valid.") } } else if elementName == "URLBase" { let url = URL(string: urlBase) if let host = url?.host { ip = host } } else if elementName == "icon" { if let height = Int(height), let width = Int(width) { icons.append(HueBridgeIcon(mimetype: mimetype, height: height, width: width, name: iconName)) } } } public func parserDidEndDocument(_ parser: XMLParser) { if let successBlock = successBlock, let bridge = bridge { successBlock(bridge) } } private func isBridgeDataValid() -> Bool { return ip.count != 0 && deviceType.count != 0 } }
mit
4632413319a1a201b0669123ea7571ff
32.133858
204
0.583175
4.921637
false
false
false
false
SAP/IssieBoard
ConfigurableKeyboard/StandardKeyboardLayout.swift
1
46919
import Foundation import UIKit class LayoutConstants: NSObject { class var landscapeRatio: CGFloat { get { return 2 }} // side edges increase on 6 in portrait class var sideEdgesPortraitArray: [CGFloat] { get { return [3, 4] }} class var sideEdgesPortraitWidthThreshholds: [CGFloat] { get { return [400] }} class var sideEdgesLandscape: CGFloat { get { return 3 }} // top edges decrease on various devices in portrait class var topEdgePortraitArray: [CGFloat] { get { return [12, 10, 8] }} class var topEdgePortraitWidthThreshholds: [CGFloat] { get { return [350, 400] }} class var topEdgeLandscape: CGFloat { get { return 6 }} // keyboard area shrinks in size in landscape on 6 and 6+ class var keyboardShrunkSizeArray: [CGFloat] { get { return [522, 524] }} class var keyboardShrunkSizeWidthThreshholds: [CGFloat] { get { return [700] }} class var keyboardShrunkSizeBaseWidthThreshhold: CGFloat { get { return 600 }} // row gaps are weird on 6 in portrait class var rowGapPortraitArray: [CGFloat] { get { return [15, 11, 10] }} class var rowGapPortraitThreshholds: [CGFloat] { get { return [350, 400] }} class var rowGapPortraitLastRow: CGFloat { get { return 9 }} class var rowGapPortraitLastRowIndex: Int { get { return 1 }} class var rowGapLandscape: CGFloat { get { return 7 }} // key gaps have weird and inconsistent rules class var keyGapPortraitNormal: CGFloat { get { return 7 }} class var keyGapPortraitSmall: CGFloat { get { return 6 }} class var keyGapPortraitNormalThreshhold: CGFloat { get { return 350 }} class var keyGapPortraitUncompressThreshhold: CGFloat { get { return 350 }} class var keyGapLandscapeNormal: CGFloat { get { return 12 }} class var keyGapLandscapeSmall: CGFloat { get { return 11 }} class var keyCompressedThreshhold: Int { get { return 11 }} class var flexibleEndRowTotalWidthToKeyWidthMPortrait: CGFloat { get { return 1 }} class var flexibleEndRowTotalWidthToKeyWidthCPortrait: CGFloat { get { return -14 }} class var flexibleEndRowTotalWidthToKeyWidthMLandscape: CGFloat { get { return 0.9231 }} class var flexibleEndRowTotalWidthToKeyWidthCLandscape: CGFloat { get { return -9.4615 }} class var flexibleEndRowMinimumStandardCharacterWidth: CGFloat { get { return 7 }} class var lastRowKeyGapPortrait: CGFloat { get { return 6 }} class var lastRowKeyGapLandscapeArray: [CGFloat] { get { return [8, 7, 5] }} class var lastRowKeyGapLandscapeWidthThreshholds: [CGFloat] { get { return [500, 700] }} class var lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }} class var lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }} class var lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }} class var lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }} class var micButtonPortraitWidthRatioToOtherSpecialButtons: CGFloat { get { return 0.765 }} class var popupGap: CGFloat { get { return 8 }} class var popupWidthIncrement: CGFloat { get { return 26 }} class var popupTotalHeightArray: [CGFloat] { get { return [102, 108] }} class var popupTotalHeightDeviceWidthThreshholds: [CGFloat] { get { return [350] }} class func sideEdgesPortrait(width: CGFloat) -> CGFloat { return self.findThreshhold(self.sideEdgesPortraitArray, threshholds: self.sideEdgesPortraitWidthThreshholds, measurement: width) } class func topEdgePortrait(width: CGFloat) -> CGFloat { return self.findThreshhold(self.topEdgePortraitArray, threshholds: self.topEdgePortraitWidthThreshholds, measurement: width) } class func rowGapPortrait(width: CGFloat) -> CGFloat { return self.findThreshhold(self.rowGapPortraitArray, threshholds: self.rowGapPortraitThreshholds, measurement: width) } class func rowGapPortraitLastRow(width: CGFloat) -> CGFloat { let index = self.findThreshholdIndex(self.rowGapPortraitThreshholds, measurement: width) if index == self.rowGapPortraitLastRowIndex { return self.rowGapPortraitLastRow } else { return self.rowGapPortraitArray[index] } } class func keyGapPortrait(width: CGFloat, rowCharacterCount: Int) -> CGFloat { let compressed = (rowCharacterCount >= self.keyCompressedThreshhold) if compressed { if width >= self.keyGapPortraitUncompressThreshhold { return self.keyGapPortraitNormal } else { return self.keyGapPortraitSmall } } else { return self.keyGapPortraitNormal } } class func keyGapLandscape(width: CGFloat, rowCharacterCount: Int) -> CGFloat { let compressed = (rowCharacterCount >= self.keyCompressedThreshhold) let shrunk = self.keyboardIsShrunk(width) if compressed || shrunk { return self.keyGapLandscapeSmall } else { return self.keyGapLandscapeNormal } } class func lastRowKeyGapLandscape(width: CGFloat) -> CGFloat { return self.findThreshhold(self.lastRowKeyGapLandscapeArray, threshholds: self.lastRowKeyGapLandscapeWidthThreshholds, measurement: width) } class func keyboardIsShrunk(width: CGFloat) -> Bool { let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad return (isPad ? false : width >= self.keyboardShrunkSizeBaseWidthThreshhold) } class func keyboardShrunkSize(width: CGFloat) -> CGFloat { let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad if isPad { return width } if width >= self.keyboardShrunkSizeBaseWidthThreshhold { return self.findThreshhold(self.keyboardShrunkSizeArray, threshholds: self.keyboardShrunkSizeWidthThreshholds, measurement: width) } else { return width } } class func popupTotalHeight(deviceWidth: CGFloat) -> CGFloat { return self.findThreshhold(self.popupTotalHeightArray, threshholds: self.popupTotalHeightDeviceWidthThreshholds, measurement: deviceWidth) } class func findThreshhold(elements: [CGFloat], threshholds: [CGFloat], measurement: CGFloat) -> CGFloat { assert(elements.count == threshholds.count + 1, "elements and threshholds do not match") return elements[self.findThreshholdIndex(threshholds, measurement: measurement)] } class func findThreshholdIndex(threshholds: [CGFloat], measurement: CGFloat) -> Int { for (i, threshhold) in Array(threshholds.reverse()).enumerate() { if measurement >= threshhold { let actualIndex = threshholds.count - i return actualIndex } } return 0 } } class GlobalColors: NSObject { //Default Settings class var defaultBackgroundColor : UIColor { get {return UIColor.whiteColor()} set {GlobalColors.defaultBackgroundColor = newValue} } class var defaultTextColor : UIColor { get {return UIColor.blackColor()} set {GlobalColors.defaultTextColor = newValue} } class var defaultKeyColor : UIColor { get {return UIColor(hue: 0, saturation: 0, brightness: 0.8, alpha: 1.0)} set {GlobalColors.defaultTextColor = newValue} } class var defaultBorderColor : UIColor { get { return UIColor.whiteColor()} set { GlobalColors.defaultKeyColor = newValue} } class var backspaceKeyColor : UIColor { get { return UIColor.redColor() } set { GlobalColors.backspaceKeyColor = newValue} } class var spaceKeyColor : UIColor { get { return GlobalColors.defaultKeyColor} set { GlobalColors.spaceKeyColor = newValue} } class var returnKeyColor : UIColor { get { return UIColor.greenColor()} set { GlobalColors.returnKeyColor = newValue} } class var changeModeKeyColor : UIColor { get { return GlobalColors.defaultKeyColor} set { GlobalColors.changeModeKeyColor = newValue} } //Settings for area One class var cutomCharSetOneKeyColor : UIColor { get { return UIColor.blueColor()} set { GlobalColors.cutomCharSetOneKeyColor = newValue} } class var cutomCharSetOneTextColor : UIColor { get { return UIColor.whiteColor()} set { GlobalColors.cutomCharSetOneTextColor = newValue} } class var cutomCharSetOneBorderColor : UIColor { get { return UIColor.yellowColor()} set { GlobalColors.cutomCharSetOneBorderColor = newValue} } //Settings for ares two class var cutomCharSetTwoKeyColor : UIColor { get { return UIColor.yellowColor()} set { GlobalColors.cutomCharSetTwoKeyColor = newValue} } class var cutomCharSetTwoTextColor : UIColor { get { return UIColor.blackColor()} set { GlobalColors.cutomCharSetTwoTextColor = newValue} } class var cutomCharSetTwoBorderColor : UIColor { get { return GlobalColors.defaultBorderColor} set { GlobalColors.cutomCharSetTwoBorderColor = newValue} } //Settings for area three class var cutomCharSetThreeKeyColor : UIColor { get { return UIColor.orangeColor()} set { GlobalColors.cutomCharSetThreeKeyColor = newValue} } class var cutomCharSetThreeTextColor : UIColor { get { return UIColor.whiteColor()} set { GlobalColors.cutomCharSetThreeTextColor = newValue} } class var cutomCharSetThreeBorderColor : UIColor { get { return GlobalColors.defaultBorderColor} set { GlobalColors.cutomCharSetThreeBorderColor = newValue} } //Settings for hidden keys class var hiddenKeyColor : UIColor { get { return GlobalColors.defaultBackgroundColor} } class var keyFont : UIFont { get { return UIFont(name: Settings.sharedInstance.Font, size: 55)! } } } extension CGRect: Hashable { public var hashValue: Int { get { return (origin.x.hashValue ^ origin.y.hashValue ^ size.width.hashValue ^ size.height.hashValue) } } } extension CGSize: Hashable { public var hashValue: Int { get { return (width.hashValue ^ height.hashValue) } } } // handles the layout for the keyboard, including key spacing and arrangement class KeyboardLayout: NSObject, KeyboardKeyProtocol { class var shouldPoolKeys: Bool { get { return true }} var layoutConstants: LayoutConstants.Type var globalColors: GlobalColors.Type unowned var model: Keyboard unowned var superview: UIView var modelToView: [Key:KeyboardKey] = [:] var viewToModel: [KeyboardKey:Key] = [:] var keyPool: [KeyboardKey] = [] var nonPooledMap: [String:KeyboardKey] = [:] var sizeToKeyMap: [CGSize:[KeyboardKey]] = [:] var shapePool: [String:Shape] = [:] var initialized: Bool required init(model: Keyboard, superview: UIView, layoutConstants: LayoutConstants.Type, globalColors: GlobalColors.Type) { self.layoutConstants = layoutConstants self.globalColors = globalColors self.initialized = false self.model = model self.superview = superview } func initialize() { assert(!self.initialized, "already initialized") self.initialized = true } func viewForKey(model: Key) -> KeyboardKey? { return self.modelToView[model] } func keyForView(key: KeyboardKey) -> Key? { return self.viewToModel[key] } func layoutKeys(pageNum: Int) { CATransaction.begin() CATransaction.setDisableActions(true) if !self.dynamicType.shouldPoolKeys { if self.keyPool.isEmpty { for p in 0..<self.model.pages.count { self.positionKeys(p) } self.updateKeyAppearance() self.updateKeyCaps(true) } } self.positionKeys(pageNum) self.superview.backgroundColor = Settings.sharedInstance.GetBackgroundColorByTemplate() for (p, page) in self.model.pages.enumerate() { for (_, row) in page.rows.enumerate() { for (_, key) in row.enumerate() { if let keyView = self.modelToView[key] { keyView.hidePopup() keyView.highlighted = false keyView.hidden = (p != pageNum) } } } } if self.dynamicType.shouldPoolKeys { self.updateKeyAppearance() self.updateKeyCaps(true) } CATransaction.commit() } func positionKeys(pageNum: Int) { CATransaction.begin() CATransaction.setDisableActions(true) let setupKey = { (view: KeyboardKey, model: Key, frame: CGRect) -> Void in view.frame = frame self.modelToView[model] = view self.viewToModel[view] = model } if var keyMap = self.generateKeyFrames(self.model, bounds: self.superview.bounds, page: pageNum) { if self.dynamicType.shouldPoolKeys { self.modelToView.removeAll(keepCapacity: true) self.viewToModel.removeAll(keepCapacity: true) self.resetKeyPool() var foundCachedKeys = [Key]() for (key, frame) in keyMap { if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) { foundCachedKeys.append(key) setupKey(keyView, key, frame) } } foundCachedKeys.map { keyMap.removeValueForKey($0) } for (key, frame) in keyMap { let keyView = self.generateKey() setupKey(keyView, key, frame) } } else { for (key, frame) in keyMap { if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) { setupKey(keyView, key, frame) } } } } CATransaction.commit() } func updateKeyAppearance() { CATransaction.begin() CATransaction.setDisableActions(true) for (key, view) in self.modelToView { view.shape = nil if let imageKey = view as? ImageKey { imageKey.image = nil } self.setAppearanceForKey(view, model: key) } CATransaction.commit() } func updateKeyCaps(fullReset: Bool){ CATransaction.begin() CATransaction.setDisableActions(true) CATransaction.commit() } func setAppearanceForKey(key: KeyboardKey, model: Key) { key.text = model.getKeyTitle() key.label.font = self.globalColors.keyFont key.label.adjustsFontSizeToFitWidth = true // Settings - By Sections Strings // let customCharSetOne : String = "פםןףךלץתצ" let customCharSetTwo : String = "וטאחיעמנה" let customCharSetThree : String = "רקכגדשבסז,." let customTwoCharSetOne : String = "@&₪098'\"" let customTwoCharSetTwo : String = "765;()?!" let customTwoCharSetThree : String = ".,4123-/:" let customThreeCharSetOne : String = "*+=$€£'•" let customThreeCharSetTwo : String = "?!~<>#%^" let customThreeCharSetThree : String = ",.[]{}_\\|" // Settings - By Row Strings // let customKeyboardOneRowOne : String = ",.קראטוןםפ" let customKeyboardOneRowTwo : String = "שדגכעיחלךף" let customKeyboardOneRowThree : String = "זסבהנמצתץ" let customKeyboardThreeRowOne : String = "[]{}#%^*+=" let customKeyboardThreeRowTwo : String = "_\\|~<>$€£" let customKeyboardThreeRowThree : String = "?!'•,." let customKeyboardTwoRowOne : String = "1234567890" let customKeyboardTwoRowTwo : String = "-/:;()₪&@" let customKeyboardTwoRowThree : String = "?!'\",." let rowOrCol : String = Settings.sharedInstance.RowOrCol if(Settings.sharedInstance.SpecialKeys.rangeOfString(key.text) != nil) { model.type = Key.KeyType.SpecialKeys } else if (model.type != Key.KeyType.HiddenKey) { if(rowOrCol == "By Rows") { if(model.pageNum == 0) { if customKeyboardOneRowOne.rangeOfString(key.text) != nil { model.type = Key.KeyType.CustomCharSetOne } else if customKeyboardOneRowTwo.rangeOfString(key.text) != nil { model.type = Key.KeyType.CustomCharSetTwo } else if customKeyboardOneRowThree.rangeOfString(key.text) != nil { model.type = Key.KeyType.CustomCharSetThree } } else if(model.pageNum == 1) { if customKeyboardTwoRowOne.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetOne } else if customKeyboardTwoRowTwo.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetTwo } else if customKeyboardTwoRowThree.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetThree } } else if(model.pageNum == 2) { if customKeyboardThreeRowOne.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetOne } else if customKeyboardThreeRowTwo.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetTwo } else if customKeyboardThreeRowThree.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetThree } } } else { if(model.pageNum == 0) { if customCharSetOne.rangeOfString(key.text) != nil { model.type = Key.KeyType.CustomCharSetOne } else if customCharSetTwo.rangeOfString(key.text) != nil { model.type = Key.KeyType.CustomCharSetTwo } else if customCharSetThree.rangeOfString(key.text) != nil { model.type = Key.KeyType.CustomCharSetThree } } else if(model.pageNum == 1) { if customTwoCharSetOne.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetOne } else if customTwoCharSetTwo.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetTwo } else if customTwoCharSetThree.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetThree } } else if(model.pageNum == 2) { if customThreeCharSetOne.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetOne } else if customThreeCharSetTwo.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetTwo } else if customThreeCharSetThree.rangeOfString(key.text) != nil{ model.type = Key.KeyType.CustomCharSetThree } } } } switch model.type { case Key.KeyType.Character, Key.KeyType.Undo, Key.KeyType.Restore : key.color = Settings.sharedInstance.OtherKeysColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.changeModeKeyColor key.downTextColor = nil key.textColor = self.globalColors.defaultTextColor case Key.KeyType.CustomCharSetOne : key.color = Settings.sharedInstance.GetKeyColorByTemplate(model) key.borderColor = self.globalColors.cutomCharSetOneBorderColor key.downColor = self.globalColors.changeModeKeyColor key.downTextColor = nil key.textColor = Settings.sharedInstance.GetKeyTextColorByTemplate(model) case Key.KeyType.CustomCharSetTwo : key.color = Settings.sharedInstance.GetKeyColorByTemplate(model) key.borderColor = self.globalColors.cutomCharSetTwoBorderColor key.downColor = self.globalColors.changeModeKeyColor key.downTextColor = nil key.textColor = Settings.sharedInstance.GetKeyTextColorByTemplate(model) case Key.KeyType.CustomCharSetThree : key.color = Settings.sharedInstance.GetKeyColorByTemplate(model) key.borderColor = self.globalColors.cutomCharSetThreeBorderColor key.downColor = self.globalColors.changeModeKeyColor key.downTextColor = nil key.textColor = Settings.sharedInstance.GetKeyTextColorByTemplate(model) case Key.KeyType.Space : key.color = Settings.sharedInstance.SpaceColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.changeModeKeyColor key.downTextColor = nil key.textColor = self.globalColors.defaultTextColor case Key.KeyType.Backspace : key.color = Settings.sharedInstance.BackspaceColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.defaultKeyColor if key.shape == nil { let backspaceShape = self.getShape(BackspaceShape) key.shape = backspaceShape } key.labelInset = 3 case Key.KeyType.ModeChange : key.color = Settings.sharedInstance.OtherKeysColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.defaultKeyColor key.textColor = self.globalColors.defaultTextColor case Key.KeyType.KeyboardChange : key.color = Settings.sharedInstance.OtherKeysColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.defaultKeyColor if let imageKey = key as? ImageKey { if imageKey.image == nil { let keyboardImage = UIImage(named: "globe-512") let keyboardImageView = UIImageView(image: keyboardImage) imageKey.setImageSizeToScaleGC(30) imageKey.image = keyboardImageView } } case Key.KeyType.DismissKeyboard: key.color = Settings.sharedInstance.OtherKeysColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.defaultKeyColor if let imageKey = key as? ImageKey { if imageKey.image == nil { let keyboardImage = UIImage(named: "ic_keyboard_hide_48px-512") let keyboardImageView = UIImageView(image: keyboardImage) imageKey.setImageSizeToScaleGC(40) imageKey.image = keyboardImageView } } case Key.KeyType.Return : key.color = Settings.sharedInstance.EnterColor key.borderColor = self.globalColors.defaultBorderColor key.downColor = self.globalColors.defaultKeyColor key.textColor = self.globalColors.defaultTextColor if let imageKey = key as? ImageKey { if imageKey.image == nil { let keyboardImage = UIImage(named: "ic_keyboard_return_48px-512") let keyboardImageView = UIImageView(image: keyboardImage) imageKey.setImageSizeToScaleGC(60) imageKey.image = keyboardImageView } } case Key.KeyType.HiddenKey : key.color = Settings.sharedInstance.GetBackgroundColorByTemplate() key.textColor = Settings.sharedInstance.GetBackgroundColorByTemplate() key.borderColor = Settings.sharedInstance.GetBackgroundColorByTemplate() key.hidden = true; key.downColor = nil case Key.KeyType.SpecialKeys : if(Settings.sharedInstance.currentTemplate == "My Configuration"){ key.color = Settings.sharedInstance.SpecialKeyColor key.textColor = Settings.sharedInstance.SpecialKeyTextColor key.borderColor = Settings.sharedInstance.defaultBackgroundColor } else{ key.color = Settings.sharedInstance.GetKeyColorByTemplate(model) key.textColor = Settings.sharedInstance.GetKeyTextColorByTemplate(model) key.borderColor = Settings.sharedInstance.GetBackgroundColorByTemplate() } key.downColor = nil default: break } } // if pool is disabled, always returns a unique key view for the corresponding key model func pooledKey(key aKey: Key, model: Keyboard, frame: CGRect) -> KeyboardKey? { if !self.dynamicType.shouldPoolKeys { var p: Int! var r: Int! var k: Int! var foundKey: Bool = false for (pp, page) in model.pages.enumerate() { for (rr, row) in page.rows.enumerate() { for (kk, key) in row.enumerate() { if key == aKey { p = pp r = rr k = kk foundKey = true } if foundKey { break } } if foundKey { break } } if foundKey { break } } let id = "p\(p)r\(r)k\(k)" if let key = self.nonPooledMap[id] { return key } else { let key = generateKey() self.nonPooledMap[id] = key return key } } else { if var keyArray = self.sizeToKeyMap[frame.size] { if let key = keyArray.last { if keyArray.count == 1 { self.sizeToKeyMap.removeValueForKey(frame.size) } else { keyArray.removeLast() self.sizeToKeyMap[frame.size] = keyArray } return key } else { return nil } } else { return nil } } } func createNewKey() -> KeyboardKey { return ImageKey(vibrancy: nil) } func generateKey() -> KeyboardKey { let createAndSetupNewKey = { () -> KeyboardKey in let keyView = self.createNewKey() keyView.enabled = true keyView.delegate = self self.superview.addSubview(keyView) self.keyPool.append(keyView) return keyView } if self.dynamicType.shouldPoolKeys { if !self.sizeToKeyMap.isEmpty { var (size, keyArray) = self.sizeToKeyMap[self.sizeToKeyMap.startIndex] if let key = keyArray.last { if keyArray.count == 1 { self.sizeToKeyMap.removeValueForKey(size) } else { keyArray.removeLast() self.sizeToKeyMap[size] = keyArray } return key } else { return createAndSetupNewKey() } } else { return createAndSetupNewKey() } } else { return createAndSetupNewKey() } } func resetKeyPool() { if self.dynamicType.shouldPoolKeys { self.sizeToKeyMap.removeAll(keepCapacity: true) for key in self.keyPool { if var keyArray = self.sizeToKeyMap[key.frame.size] { keyArray.append(key) self.sizeToKeyMap[key.frame.size] = keyArray } else { var keyArray = [KeyboardKey]() keyArray.append(key) self.sizeToKeyMap[key.frame.size] = keyArray } key.hidden = true } } } func getShape(shapeClass: Shape.Type) -> Shape { let className = NSStringFromClass(shapeClass) if self.dynamicType.shouldPoolKeys { if let shape = self.shapePool[className] { return shape } else { let shape = shapeClass.init(frame: CGRectZero) self.shapePool[className] = shape return shape } } else { return shapeClass.init(frame: CGRectZero) } } func rounded(measurement: CGFloat) -> CGFloat { return round(measurement * UIScreen.mainScreen().scale) / UIScreen.mainScreen().scale } func generateKeyFrames(model: Keyboard, bounds: CGRect, page pageToLayout: Int) -> [Key:CGRect]? { if bounds.height == 0 || bounds.width == 0 { return nil } var keyMap = [Key:CGRect]() let isLandscape: Bool = { let boundsRatio = bounds.width / bounds.height return (boundsRatio >= self.layoutConstants.landscapeRatio) }() var sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(bounds.width)) let bottomEdge = sideEdges let normalKeyboardSize = bounds.width - CGFloat(2) * sideEdges let shrunkKeyboardSize = self.layoutConstants.keyboardShrunkSize(normalKeyboardSize) sideEdges += ((normalKeyboardSize - shrunkKeyboardSize) / CGFloat(2)) let topEdge: CGFloat = (isLandscape ? self.layoutConstants.topEdgeLandscape : self.layoutConstants.topEdgePortrait(bounds.width)) let rowGap: CGFloat = (isLandscape ? self.layoutConstants.rowGapLandscape : self.layoutConstants.rowGapPortrait(bounds.width)) let lastRowGap: CGFloat = (isLandscape ? rowGap : self.layoutConstants.rowGapPortraitLastRow(bounds.width)) let flexibleEndRowM = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait) let flexibleEndRowC = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait) let lastRowLeftSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth) let lastRowRightSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth) let lastRowKeyGap = (isLandscape ? self.layoutConstants.lastRowKeyGapLandscape(bounds.width) : self.layoutConstants.lastRowKeyGapPortrait) for (p, page) in model.pages.enumerate() { if p != pageToLayout { continue } let numRows = page.rows.count let mostKeysInRow: Int = { var currentMax: Int = 0 for (i, row) in page.rows.enumerate() { currentMax = max(currentMax, row.count) } return currentMax }() let rowGapTotal = CGFloat(numRows - 1 - 1) * rowGap + lastRowGap let keyGap: CGFloat = (isLandscape ? self.layoutConstants.keyGapLandscape(bounds.width, rowCharacterCount: mostKeysInRow) : self.layoutConstants.keyGapPortrait(bounds.width, rowCharacterCount: mostKeysInRow)) let keyHeight: CGFloat = { let totalGaps = bottomEdge + topEdge + rowGapTotal let returnHeight = (bounds.height - totalGaps) / CGFloat(numRows) return self.rounded(returnHeight) }() let letterKeyWidth: CGFloat = { let totalGaps = (sideEdges * CGFloat(2)) + (keyGap * CGFloat(mostKeysInRow - 1)) let returnWidth = (bounds.width - totalGaps) / CGFloat(mostKeysInRow) return self.rounded(returnWidth) }() let processRow = { (row: [Key], frames: [CGRect], inout map: [Key:CGRect]) -> Void in assert(row.count == frames.count, "row and frames don't match") for (k, key) in row.enumerate() { map[key] = frames[k] } } for (r, row) in page.rows.enumerate() { let rowGapCurrentTotal = (r == page.rows.count - 1 ? rowGapTotal : CGFloat(r) * rowGap) let frame = CGRectMake(rounded(sideEdges), rounded(topEdge + (CGFloat(r) * keyHeight) + rowGapCurrentTotal), rounded(bounds.width - CGFloat(2) * sideEdges), rounded(keyHeight)) var frames: [CGRect]! if self.characterRowHeuristic(row) { frames = self.layoutCharacterRow(row, keyWidth: letterKeyWidth, gapWidth: keyGap, frame: frame) } else if self.oneLeftSidedRowHeuristic(row) { frames = self.layoutCharacterWithOneSideRow(row, frame: frame, isLandscape: isLandscape, keyWidth: letterKeyWidth, keyGap: keyGap) } else if self.doubleLeftSidedOneRightSidedRowHeuristic(row) { frames = self.layoutCharacterWithAsymetricSidesRow(row, frame: frame, isLandscape: isLandscape, keyWidth: letterKeyWidth, keyGap: keyGap) } else { frames = layoutCharacterWithSymetricSidesRow(row, frame: frame, isLandscape: isLandscape, keyWidth: letterKeyWidth, keyGap: keyGap) } processRow(row, frames, &keyMap) } } return keyMap } func characterRowHeuristic(row: [Key]) -> Bool { return (row.count >= 1 && row[0].isCharacter && row[row.count-1].isCharacter) } func doubleLeftSidedOneRightSidedRowHeuristic(row: [Key]) -> Bool { return (row.count >= 3 && !row[0].isCharacter && !row[1].isCharacter && !row[row.count-1].isCharacter && row[row.count-2].isCharacter) } func oneLeftSidedRowHeuristic(row: [Key]) -> Bool { return (row.count >= 3 && row[0].isCharacter && !row[row.count-1].isCharacter) } func layoutCharacterRow(row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, frame: CGRect) -> [CGRect] { var frames = [CGRect]() let keySpace = CGFloat(row.count) * keyWidth + CGFloat(row.count - 1) * gapWidth var actualGapWidth = gapWidth var sideSpace = (frame.width - keySpace) / CGFloat(2) if sideSpace < 0 { sideSpace = 0 actualGapWidth = (frame.width - (CGFloat(row.count) * keyWidth)) / CGFloat(row.count - 1) } if sideSpace > keyWidth/CGFloat(2) { sideSpace = keyWidth/CGFloat(3) } var currentOrigin = frame.origin.x + sideSpace for (k, key) in row.enumerate() { let roundedOrigin = rounded(currentOrigin) if roundedOrigin + keyWidth > frame.origin.x + frame.width { frames.append(CGRectMake(rounded(frame.origin.x + frame.width - keyWidth), frame.origin.y, keyWidth, frame.height)) } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, keyWidth, frame.height)) } currentOrigin += (keyWidth + actualGapWidth) } return frames } func layoutCharacterWithAsymetricSidesRow(row: [Key], frame: CGRect, isLandscape: Bool, keyWidth: CGFloat, keyGap: CGFloat) -> [CGRect] { var frames = [CGRect]() let keySpace = CGFloat(row.count) * keyWidth + CGFloat(row.count - 1) * keyGap var actualGapWidth = keyGap var sideSpace = (frame.width - keySpace) / CGFloat(2) if sideSpace > keyWidth/CGFloat(2) { sideSpace = keyWidth/CGFloat(3) } var currentOrigin = frame.origin.x for (k, key) in row.enumerate() { if k == 1 { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, CGFloat(1.8)*keyWidth, frame.height)) currentOrigin += (CGFloat(1.8)*keyWidth + keyGap) } else if k == row.count - 1 { currentOrigin += (frame.width - currentOrigin - CGFloat(1.3)*keyWidth) frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y,(CGFloat(1.3)*keyWidth), frame.height)) } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, keyWidth, frame.height)) currentOrigin += (keyWidth + keyGap) } } return frames } func layoutCharacterWithSymetricSidesRow(row: [Key], frame: CGRect, isLandscape: Bool, keyWidth: CGFloat, keyGap: CGFloat) -> [CGRect] { var frames = [CGRect]() let sizeSpaceKey = CGFloat(6)*keyWidth + CGFloat(5)*keyGap let sizeForAllSpecialKeys = (frame.width - sizeSpaceKey - keyWidth - (CGFloat(4)*keyGap)) let sizeOfSpecialKeyExceptOne = sizeForAllSpecialKeys/CGFloat(3) var currentOrigin = frame.origin.x frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, sizeOfSpecialKeyExceptOne, frame.height)) currentOrigin += (sizeOfSpecialKeyExceptOne + keyGap) frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, sizeOfSpecialKeyExceptOne, frame.height)) currentOrigin += (sizeOfSpecialKeyExceptOne + keyGap) frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, sizeSpaceKey, frame.height)) currentOrigin += (sizeSpaceKey + keyGap) frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, sizeOfSpecialKeyExceptOne, frame.height)) currentOrigin += (sizeOfSpecialKeyExceptOne + keyGap) frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, keyWidth, frame.height)) return frames } func layoutCharacterWithOneSideRow(row: [Key], frame: CGRect, isLandscape: Bool, keyWidth: CGFloat, keyGap: CGFloat) -> [CGRect] { var frames = [CGRect]() let keySpace = CGFloat(row.count) * keyWidth + CGFloat(row.count - 1) * keyGap var actualGapWidth = keyGap var sideSpace = (frame.width - keySpace) / CGFloat(2) if sideSpace > keyWidth/CGFloat(2) { sideSpace = keyWidth/CGFloat(2) } var currentOrigin = frame.origin.x + 1.5*sideSpace for (k, key) in row.enumerate() { if k == 0 { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, keyWidth, frame.height)) currentOrigin += (keyWidth + keyGap) } else if k == row.count - 1 { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, (frame.width-currentOrigin), frame.height)) } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, keyWidth, frame.height)) currentOrigin += (keyWidth + keyGap) } } return frames } func layoutSpecialKeysRow(row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, leftSideRatio: CGFloat, rightSideRatio: CGFloat, micButtonRatio: CGFloat, isLandscape: Bool, frame: CGRect) -> [CGRect] { var frames = [CGRect]() var keysBeforeSpace = 0 var keysAfterSpace = 0 var reachedSpace = false for (k, key) in row.enumerate() { if key.type == Key.KeyType.Space { reachedSpace = true } else { if !reachedSpace { keysBeforeSpace += 1 } else { keysAfterSpace += 1 } } } let hasButtonInMicButtonPosition = (keysBeforeSpace == 3) var leftSideAreaWidth = frame.width * leftSideRatio let rightSideAreaWidth = frame.width * rightSideRatio var leftButtonWidth = (leftSideAreaWidth - (gapWidth * CGFloat(2 - 1))) / CGFloat(2) leftButtonWidth = rounded(leftButtonWidth) var rightButtonWidth = (rightSideAreaWidth - (gapWidth * CGFloat(keysAfterSpace - 1))) / CGFloat(keysAfterSpace) rightButtonWidth = rounded(rightButtonWidth) let micButtonWidth = (isLandscape ? leftButtonWidth : leftButtonWidth * micButtonRatio) if hasButtonInMicButtonPosition { leftSideAreaWidth = leftSideAreaWidth + gapWidth + micButtonWidth } var spaceWidth = frame.width - leftSideAreaWidth - rightSideAreaWidth - gapWidth * CGFloat(2) spaceWidth = rounded(spaceWidth) var currentOrigin = frame.origin.x var beforeSpace: Bool = true for (k, key) in row.enumerate() { if key.type == Key.KeyType.Space { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, spaceWidth, frame.height)) currentOrigin += (spaceWidth + gapWidth) beforeSpace = false } else if beforeSpace { if hasButtonInMicButtonPosition && k == 2 { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, micButtonWidth, frame.height)) currentOrigin += (micButtonWidth + gapWidth) } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, leftButtonWidth, frame.height)) currentOrigin += (leftButtonWidth + gapWidth) } } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, rightButtonWidth, frame.height)) currentOrigin += (rightButtonWidth + gapWidth) } } return frames } func frameForPopup(key: KeyboardKey, direction: Direction) -> CGRect { let actualScreenWidth = (UIScreen.mainScreen().nativeBounds.size.width / UIScreen.mainScreen().nativeScale) let totalHeight = self.layoutConstants.popupTotalHeight(actualScreenWidth) let popupWidth = key.bounds.width + self.layoutConstants.popupWidthIncrement let popupHeight = totalHeight - self.layoutConstants.popupGap - key.bounds.height let popupCenterY = 0 return CGRectMake((key.bounds.width - popupWidth) / CGFloat(2), -popupHeight - self.layoutConstants.popupGap, popupWidth, popupHeight) } func willShowPopup(key: KeyboardKey, direction: Direction) { if let popup = key.popup { let actualSuperview = (self.superview.superview != nil ? self.superview.superview! : self.superview) var localFrame = actualSuperview.convertRect(popup.frame, fromView: popup.superview) if localFrame.origin.y < 3 { localFrame.origin.y = 3 key.background.attached = Direction.Down key.connector?.startDir = Direction.Down key.background.hideDirectionIsOpposite = true } else { key.background.hideDirectionIsOpposite = false } if localFrame.origin.x < 3 { localFrame.origin.x = key.frame.origin.x } if localFrame.origin.x + localFrame.width > superview.bounds.width - 3 { localFrame.origin.x = key.frame.origin.x + key.frame.width - localFrame.width } popup.frame = actualSuperview.convertRect(localFrame, toView: popup.superview) } } func willHidePopup(key: KeyboardKey) {} }
apache-2.0
0b58f1c8e85772bb1297edd23b8d97b6
40.13345
220
0.58035
5.437043
false
false
false
false
LYM-mg/DemoTest
indexView/indexView/One/加密相关/控制器/AESViewController.swift
1
12800
// // AESViewController.swift // indexView // // Created by i-Techsys.com on 17/3/20. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit class AESViewController: UIViewController { fileprivate lazy var imageView: UIImageView = { let img = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 350)) img.center = CGPoint(x: MGScreenW/2, y: MGScreenH/2) img.isUserInteractionEnabled = true img.image = #imageLiteral(resourceName: "ming1") img.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AESViewController.tapClick(_:)))) return img }() fileprivate lazy var pageControl: UIPageControl = { let pageControl = UIPageControl() pageControl.center = CGPoint(x: MGScreenW/2, y: MGScreenH/2) pageControl.isUserInteractionEnabled = true pageControl.numberOfPages = 4 pageControl.tintColor = UIColor.blue pageControl.pageIndicatorTintColor = UIColor.brown pageControl.currentPageIndicatorTintColor = UIColor.orange pageControl.setValue(UIImage(named: "current"), forKey: "_currentPageImage") pageControl.setValue(UIImage(named: "other"), forKey: "_pageImage") pageControl.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AESViewController.tapClick(_:)))) return pageControl }() // 自定义属性 fileprivate lazy var i: Int = 0 var direction: UIPanGestureRecognizerDirection = .undefined fileprivate lazy var prePoint: CGPoint = .zero lazy var timer = DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.main) // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white view.addSubview(imageView) let testAESBtn = UIButton(frame: CGRect(x: 0, y: 100, width: 70, height: 30)) testAESBtn.backgroundColor = UIColor.magenta testAESBtn.center = CGPoint(x: MGScreenW/2, y: 85) testAESBtn.setTitle("测试", for: .normal) testAESBtn.addTarget(self, action: #selector(AESViewController.btnClick(_:)), for: .touchUpInside) view.addSubview(testAESBtn) imageView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(AESViewController.handlePanGesture(pan:)))) imageView.addSubview(pageControl) pageControl.center = CGPoint(x: imageView.frame.size.width/2, y: imageView.frame.size.height-10) addTimer() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer.cancel() } deinit { print("AESViewController--deinit") } // 添加定时器 fileprivate func addTimer() { timer = DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.main) timer.scheduleRepeating(deadline: .now(), interval: 5.0) timer.setEventHandler { [unowned self] in self.i += 1 if self.i <= 0 { self.i = 4 } if self.i > 4 { self.i = 1 } self.pageControl.currentPage = self.i - 1 let transition = CATransition() transition.duration = 1.5 transition.type = CATransitionType(rawValue: "cameraIrisHollowClose") // suckEffect rippleEffect cameraIrisHollowOpen reveal transition.subtype = CATransitionSubtype.fromLeft self.imageView.layer.add(transition, forKey: nil) self.imageView.image = UIImage(named: "ming\(self.i)") } timer.resume() //定时器开始激活 } @objc fileprivate func moveLeft(_ tap: UISwipeGestureRecognizer) { i -= 1 if i <= 0 { i = 4 } transition(i: i) } @objc fileprivate func moveRight(_ tap: UISwipeGestureRecognizer) { i += 1 if i > 4 { i = 1 } transition(i: i) } func transition(i: Int) { self.pageControl.currentPage = i - 1 let transition = CATransition() transition.type = CATransitionType(rawValue: "rippleEffect") // rippleEffect transition.duration = 1.0 imageView.layer.add(transition, forKey: nil) imageView.image = UIImage(named: "ming\(i)") } @objc fileprivate func tapClick(_ tap: UISwipeGestureRecognizer) { imageView.layer.removeAllAnimations() let transition = CATransition() if tap.location(in: tap.view).y > imageView.frame.size.height/2 { i -= 1 transition.type = CATransitionType(rawValue: "pageCurl") } else { i += 1 transition.type = CATransitionType(rawValue: "pageUnCurl") } if i <= 0 { i = 4 } if i > 4 { i = 1 } self.pageControl.currentPage = i - 1 transition.duration = 1.5 imageView.layer.add(transition, forKey: nil) imageView.image = UIImage(named: "ming\(i)") } } // MARK: - pan手势代替轻扫手势 enum UIPanGestureRecognizerDirection{ case undefined,up,down,left,right } extension AESViewController { //加载手势 @objc func handlePanGesture(pan: UIPanGestureRecognizer){ switch(pan.state){ case .began: timer.suspend() // 暂停定时器 prePoint = pan.location(in: pan.view!) case .changed: let curP = pan.location(in: pan.view!) let isVerticalGesture = fabs(curP.y) > fabs(prePoint.y) // 上下之分 let isHorizontalGesture = fabs(curP.x) > fabs(prePoint.x) // 左右之分 let isHelpDirection = fabs((curP.y - prePoint.y)/(curP.x - prePoint.x)) <= 1 if isHorizontalGesture && isHelpDirection{ direction = .right } else if !isHorizontalGesture && isHelpDirection { direction = .left } else if isVerticalGesture && !isHelpDirection { direction = .down } else if !isVerticalGesture && !isHelpDirection{ direction = .up }else { direction = .undefined } break case .ended: switch direction { case .up: i += 1 handleUpwardsGesture() case .down: i -= 1 handleDownwardsGesture() case .right: i += 1 handleRightwardsGesture() case .left: i -= 1 handleLeftwardsGesture() default: break } DispatchQueue.main.asyncAfter(deadline: .now()+3) { self.timer.resume() //定时器继续执行; } default: break } if i <= 0 { i = 4 } if i > 4 { i = 1 } pageControl.currentPage = i - 1 let transition = CATransition() transition.type = CATransitionType(rawValue: "rippleEffect") // rippleEffect transition.duration = 1.0 imageView.layer.add(transition, forKey: nil) imageView.image = UIImage(named: "ming\(i)") } fileprivate func handleUpwardsGesture() { print("Up") } fileprivate func handleDownwardsGesture() { print("Down") } fileprivate func handleRightwardsGesture() { print("Right") } fileprivate func handleLeftwardsGesture() { print("left") } // 轻扫手势 func handleSwipeGesture(){ let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(AESViewController.moveLeft(_:))) leftSwipe.numberOfTouchesRequired = 1 leftSwipe.direction = UISwipeGestureRecognizer.Direction.left imageView.addGestureRecognizer(leftSwipe) let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(AESViewController.moveRight(_:))) rightSwipe.numberOfTouchesRequired = 1 rightSwipe.direction = UISwipeGestureRecognizer.Direction.right imageView.addGestureRecognizer(rightSwipe) } } // MARK: - 测试 extension AESViewController { @objc fileprivate func btnClick(_ btn: UIButton) { self.view.endEditing(true) NSData.test() Data.test1() } } // MARK: - NSData测试 extension NSData{ // AES128Crypt加密 func AES128Crypt(operation:CCOperation,keyData:NSData) -> NSData? { let keyBytes = keyData.bytes let keyLength = Int(kCCKeySizeAES256) let dataLength = self.length let dataBytes = self.bytes let cryptLength = Int(dataLength+kCCBlockSizeAES128) let cryptPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: cryptLength) let algoritm: CCAlgorithm = CCAlgorithm(kCCAlgorithmAES128) let option: CCOptions = CCOptions(kCCOptionECBMode + kCCOptionPKCS7Padding) let numBytesEncrypted = UnsafeMutablePointer<Int>.allocate(capacity: 1) numBytesEncrypted.initialize(to: 0) let cryptStatus = CCCrypt(CCOperation(operation), algoritm, option, keyBytes, keyLength, nil, dataBytes, dataLength, cryptPointer, cryptLength, numBytesEncrypted) if CCStatus(cryptStatus) == CCStatus(kCCSuccess) { let len = Int(numBytesEncrypted.pointee) let data:NSData = NSData(bytesNoCopy: cryptPointer, length: len) numBytesEncrypted.deallocate() return data } else { numBytesEncrypted.deallocate() cryptPointer.deallocate() return nil } } static func test(){ let keyString = "12345678901234567890123456789012" let keyData: NSData! = (keyString as NSString).data(using: String.Encoding.utf8.rawValue) as NSData? let message = "你是大傻瓜吗?你才是" let data: NSData! = (message as NSString).data(using: String.Encoding.utf8.rawValue) as NSData? print("要加密的字符串:" + message) let result:NSData? = data.AES128Crypt(operation: CCOperation(kCCEncrypt), keyData: keyData) print("encrypt = \(result!)") let oldData = result!.AES128Crypt(operation: CCOperation(kCCDecrypt), keyData: keyData) print("decrypt = \(oldData!)") print(String(data: oldData as! Data, encoding: String.Encoding.utf8)!) let enData = data.enCrypt(algorithm: .AES, keyData: keyData) let deData = enData?.deCrypt(algorithm: .AES, keyData: keyData) print("通过解密后的字符串:" + String(data: deData as! Data, encoding: String.Encoding.utf8)!) let enData1 = data.enCrypt(algorithm: .DES, keyData: keyData) let deData1 = enData1?.deCrypt(algorithm: .DES, keyData: keyData) print("通过解密后的字符串:" + String(data: deData1 as! Data, encoding: String.Encoding.utf8)!) let enData2 = data.enCrypt(algorithm: .RC2, keyData: keyData) let deData2 = enData2?.deCrypt(algorithm: .RC2, keyData: keyData) print("通过解密后的字符串:" + String(data: deData2 as! Data, encoding: String.Encoding.utf8)!) print("enData-AES: + \(enData!)") print("enData-DES: + \(enData1!)") print("enData-RC2: + \(enData2!)") print("deData-AES: + \(deData!)") print("deData-DES: + \(deData1!)") print("deData-RC2: + \(deData2!)") } } // MARK: - Data测试 extension Data { static func test1(){ let keyString = "123" let message = "you are so stuip" let keyData = keyString.data(using: String.Encoding.utf8) var data = message.data(using: String.Encoding.utf8) var result = data?.enCrypt(algorithm: CryptoAlgorithm.AES, keyData: keyData!) print("result = \(result!)") let data1 = NSData(data: result!) print(data1) print(NSString(data: result!, encoding: String.Encoding.utf8.rawValue)) let oldData = result?.deCrypt(algorithm: CryptoAlgorithm.AES, keyData: keyData!) print("oldData = \(oldData! as NSData)") print(String(data: oldData!, encoding: String.Encoding.utf8)!) } }
mit
b2e095c9f9786cdd4f1a3ce2a8456cb2
36.198225
170
0.588801
4.72314
false
false
false
false
guardianproject/poe
POE/Classes/ScanQrViewController.swift
1
6659
// // ScanQrViewController.swift // Pods // // Created by Benjamin Erhart on 09.06.17. // // import UIKit import AVFoundation class ScanQrViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var videoView: UIView! private var captureSession: AVCaptureSession? private var videoPreviewLayer: AVCaptureVideoPreviewLayer? private lazy var picker: UIImagePickerController = { let picker = UIImagePickerController() picker.sourceType = .photoLibrary picker.delegate = self return picker }() private lazy var detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) startReading() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopReading() } // MARK: - AVCaptureMetadataOutputObjectsDelegate /** BUGFIX: Signature of method changed in Swift 4, without notifications. No migration assistance either. See https://stackoverflow.com/questions/46639519/avcapturemetadataoutputobjectsdelegate-not-called-in-swift-4-for-qr-scanner */ func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if metadataObjects.count > 0, let metadata = metadataObjects[0] as? AVMetadataMachineReadableCodeObject, metadata.type == .qr { captureSession?.stopRunning() tryDecode(metadata.stringValue) } } // MARK: Actions @IBAction func pickImage(_ sender: UIBarButtonItem) { captureSession?.stopRunning() picker.popoverPresentationController?.barButtonItem = sender present(picker, animated: true) } // MARK: UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) var raw = "" if let image = (info[.editedImage] ?? info[.originalImage]) as? UIImage, let ciImage = image.ciImage ?? (image.cgImage != nil ? CIImage(cgImage: image.cgImage!) : nil) { let features = detector?.features(in: ciImage) for feature in features as? [CIQRCodeFeature] ?? [] { raw += feature.messageString ?? "" } } tryDecode(raw) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true) captureSession?.startRunning() } // MARK: Private methods private func startReading() { if let captureDevice = AVCaptureDevice.default(for: .video) { do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() if let captureSession = captureSession { captureSession.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) captureMetadataOutput.metadataObjectTypes = [.qr] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) if let videoPreviewLayer = videoPreviewLayer { videoPreviewLayer.videoGravity = .resizeAspectFill videoPreviewLayer.frame = videoView.layer.bounds videoView.layer.addSublayer(videoPreviewLayer) captureSession.startRunning() return } } } catch { // Just fall thru to alert. } } let warning = UILabel(frame: .zero) warning.text = "Camera access was not granted or QR Code scanning is not supported by your device.".localize() warning.translatesAutoresizingMaskIntoConstraints = false warning.numberOfLines = 0 warning.textAlignment = .center warning.textColor = .white // hard white, will always look better on dark purple. videoView.addSubview(warning) warning.leadingAnchor.constraint(equalTo: videoView.leadingAnchor, constant: 16).isActive = true warning.trailingAnchor.constraint(equalTo: videoView.trailingAnchor, constant: -16).isActive = true warning.topAnchor.constraint(equalTo: videoView.topAnchor, constant: 16).isActive = true warning.bottomAnchor.constraint(equalTo: videoView.bottomAnchor, constant: -16).isActive = true } private func stopReading() { if captureSession != nil { captureSession?.stopRunning() captureSession = nil } if videoPreviewLayer != nil { videoPreviewLayer?.removeFromSuperlayer() videoPreviewLayer = nil } } private func tryDecode(_ raw: String?) { // They really had to use JSON for content encoding but with illegal single quotes instead // of double quotes as per JSON standard. Srsly? if let data = raw?.replacingOccurrences(of: "'", with: "\"").data(using: .utf8), let newBridges = try? JSONSerialization.jsonObject(with: data, options: []) as? [String], let vc = self.navigationController?.viewControllers, let customVC = vc[(vc.count) - 2] as? CustomBridgeViewController { customVC.bridges = newBridges navigationController?.popViewController(animated: true) } else { alert("QR Code could not be decoded! Are you sure you scanned a QR code from bridges.torproject.org?".localize()) { _ in self.captureSession?.startRunning() } } } private func alert(_ message: String, handler: ((UIAlertAction) -> Void)? = nil) { let alert = UIAlertController( title: "Error".localize(), message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel".localize(), style: .cancel, handler: handler)) alert.view.tintColor = .poeAccentLight present(alert, animated: true, completion: nil) } }
bsd-3-clause
e1cde07a30b8ad2821372df9c7161bb1
33.324742
144
0.640937
5.676897
false
false
false
false
huonw/swift
stdlib/public/core/ReflectionMirror.swift
2
5767
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("swift_reflectionMirror_normalizedType") internal func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("swift_reflectionMirror_count") internal func _getChildCount<T>(_: T, type: Any.Type) -> Int internal typealias NameFreeFunc = @convention(c) (UnsafePointer<CChar>?) -> Void @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("swift_reflectionMirror_subscript") internal func _getChild<T>( of: T, type: Any.Type, index: Int, outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> ) -> Any // Returns 'c' (class), 'e' (enum), 's' (struct), 't' (tuple), or '\0' (none) @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("swift_reflectionMirror_displayStyle") internal func _getDisplayStyle<T>(_: T) -> CChar @inlinable // FIXME(sil-serialize-all) internal func getChild<T>(of value: T, type: Any.Type, index: Int) -> (label: String?, value: Any) { var nameC: UnsafePointer<CChar>? = nil var freeFunc: NameFreeFunc? = nil let value = _getChild(of: value, type: type, index: index, outName: &nameC, outFreeFunc: &freeFunc) let name = nameC.flatMap({ String(validatingUTF8: $0) }) freeFunc?(nameC) return (name, value) } #if _runtime(_ObjC) @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("swift_reflectionMirror_quickLookObject") internal func _getQuickLookObject<T>(_: T) -> AnyObject? @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("_swift_stdlib_NSObject_isKindOfClass") internal func _isImpl(_ object: AnyObject, kindOf: AnyObject) -> Bool @inlinable // FIXME(sil-serialize-all) internal func _is(_ object: AnyObject, kindOf `class`: String) -> Bool { return _isImpl(object, kindOf: `class` as AnyObject) } @inlinable // FIXME(sil-serialize-all) internal func _getClassPlaygroundQuickLook( _ object: AnyObject ) -> PlaygroundQuickLook? { if _is(object, kindOf: "NSNumber") { let number: _NSNumber = unsafeBitCast(object, to: _NSNumber.self) switch UInt8(number.objCType[0]) { case UInt8(ascii: "d"): return .double(number.doubleValue) case UInt8(ascii: "f"): return .float(number.floatValue) case UInt8(ascii: "Q"): return .uInt(number.unsignedLongLongValue) default: return .int(number.longLongValue) } } if _is(object, kindOf: "NSAttributedString") { return .attributedString(object) } if _is(object, kindOf: "NSImage") || _is(object, kindOf: "UIImage") || _is(object, kindOf: "NSImageView") || _is(object, kindOf: "UIImageView") || _is(object, kindOf: "CIImage") || _is(object, kindOf: "NSBitmapImageRep") { return .image(object) } if _is(object, kindOf: "NSColor") || _is(object, kindOf: "UIColor") { return .color(object) } if _is(object, kindOf: "NSBezierPath") || _is(object, kindOf: "UIBezierPath") { return .bezierPath(object) } if _is(object, kindOf: "NSString") { return .text(_forceBridgeFromObjectiveC(object, String.self)) } return .none } #endif extension Mirror { @inlinable // FIXME(sil-serialize-all) internal init(internalReflecting subject: Any, subjectType: Any.Type? = nil, customAncestor: Mirror? = nil) { let subjectType = subjectType ?? _getNormalizedType(subject, type: type(of: subject)) let childCount = _getChildCount(subject, type: subjectType) let children = (0 ..< childCount).lazy.map({ getChild(of: subject, type: subjectType, index: $0) }) self.children = Children(children) self._makeSuperclassMirror = { guard let subjectClass = subjectType as? AnyClass, let superclass = _getSuperclass(subjectClass) else { return nil } // Handle custom ancestors. If we've hit the custom ancestor's subject type, // or descendants are suppressed, return it. Otherwise continue reflecting. if let customAncestor = customAncestor { if superclass == customAncestor.subjectType { return customAncestor } if customAncestor._defaultDescendantRepresentation == .suppressed { return customAncestor } } return Mirror(internalReflecting: subject, subjectType: superclass, customAncestor: customAncestor) } let rawDisplayStyle = _getDisplayStyle(subject) switch UnicodeScalar(Int(rawDisplayStyle)) { case "c": self.displayStyle = .class case "e": self.displayStyle = .enum case "s": self.displayStyle = .struct case "t": self.displayStyle = .tuple case "\0": self.displayStyle = nil default: preconditionFailure("Unknown raw display style '\(rawDisplayStyle)'") } self.subjectType = subjectType self._defaultDescendantRepresentation = .generated } @inlinable // FIXME(sil-serialize-all) internal static func quickLookObject(_ subject: Any) -> PlaygroundQuickLook? { #if _runtime(_ObjC) let object = _getQuickLookObject(subject) return object.flatMap(_getClassPlaygroundQuickLook) #else return nil #endif } }
apache-2.0
4b9daa7ef31f839d179e9a80e5b44eca
32.725146
101
0.658921
4.145938
false
false
false
false