repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Hout/SwiftMoment
refs/heads/master
CalendarViewDemo/Pods/SwiftMoment/SwiftMoment/SwiftMoment/Duration.swift
bsd-2-clause
5
// // Duration.swift // SwiftMoment // // Created by Adrian on 19/01/15. // Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved. // import Foundation public struct Duration: Equatable { let interval: NSTimeInterval public init(value: NSTimeInterval) { self.interval = value } public init(value: Int) { self.interval = NSTimeInterval(value) } public var years: Double { return interval / 31536000 // 365 days } public var quarters: Double { return interval / 7776000 // 3 months } public var months: Double { return interval / 2592000 // 30 days } public var days: Double { return interval / 86400 // 24 hours } public var hours: Double { return interval / 3600 // 60 minutes } public var minutes: Double { return interval / 60 } public var seconds: Double { return interval } public func ago() -> Moment { return moment().substract(self) } public func add(duration: Duration) -> Duration { return Duration(value: self.interval + duration.interval) } public func substract(duration: Duration) -> Duration { return Duration(value: self.interval - duration.interval) } public func isEqualTo(duration: Duration) -> Bool { return self.interval == duration.interval } } extension Duration: Printable { public var description: String { let formatter = NSDateComponentsFormatter() formatter.allowedUnits = .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitWeekOfMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond let referenceDate = NSDate(timeIntervalSinceReferenceDate: 0) let intervalDate = NSDate(timeInterval: self.interval, sinceDate: referenceDate) return formatter.stringFromDate(referenceDate, toDate: intervalDate)! } }
edbce6cd4456d120113a70f740772e92
24.697368
181
0.65489
false
false
false
false
cotkjaer/SilverbackFramework
refs/heads/master
SilverbackFramework/HexagonCollectionViewFlowLayout.swift
mit
1
// // HexagonCollectionViewFlowLayout.swift // SilverbackFramework // // Created by Christian Otkjær on 30/06/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import UIKit public class HexagonCell: UICollectionViewCell { // let hexView = HexView() // // override public var contentView : UIView { return self.hexView } } public class HexagonCollectionViewFlowLayout: UICollectionViewFlowLayout { /// describes whether each line of hexes should have the same number of hexes in it, or if every other line will have itemsPerLine and the rest will have itemsPerLine - 1 public var alternateLineLength = true { didSet { invalidateLayout() } } public var itemsPerLine : Int? { didSet { invalidateLayout() } } public init(flowLayout: UICollectionViewFlowLayout) { super.init() sectionInset = flowLayout.sectionInset itemSize = flowLayout.itemSize minimumLineSpacing = flowLayout.minimumLineSpacing minimumInteritemSpacing = flowLayout.minimumInteritemSpacing scrollDirection = flowLayout.scrollDirection } required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } // Mark: Item Size private func updateCellSize() { if let itemsPLine = itemsPerLine, let boundsSize = self.collectionView?.bounds.size { let lineLength = (scrollDirection == .Horizontal ? boundsSize.height : boundsSize.width) let boundsLength = lineLength / (CGFloat(itemsPLine) + (alternateLineLength ? 0.0 : 0.5)) var size = CGSize(width: boundsLength, height: boundsLength) switch scrollDirection { case .Horizontal: size.width /= sin60 case .Vertical: size.height = size.height / sin60 } itemSize = size } } //Mark: - UICollectionViewLayout overrides public override func invalidateLayout() { updateCellSize() super.invalidateLayout() } override public func prepareLayout() { attributesCache.removeAll(keepCapacity: true) super.prepareLayout() } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if let numberOfItems = self.collectionView?.numberOfItemsInSection(0) { return (0..<numberOfItems).map({ self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: $0, inSection: 0))! } ) } return nil } var attributesCache = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>() func rowAndColForIndexPath(indexPath: NSIndexPath) -> (row: Int, col: Int) { let itemsInUpperLine = (itemsPerLine ?? 1) - (alternateLineLength ? 1 : 0) let itemsInLowerLine = (itemsPerLine ?? 1) let twoLinesItemCount = itemsInLowerLine + itemsInUpperLine var col = (indexPath.item % twoLinesItemCount) var row = (indexPath.item / twoLinesItemCount) row = row * 2 if col >= itemsInUpperLine { row += 1 col -= itemsInUpperLine } debugPrint("item: \(indexPath.item) -> (\(row), \(col))") return (row, col) } override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { if let attributes = attributesCache[indexPath] { return attributes } let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) attributes.size = self.itemSize let (row, col) = rowAndColForIndexPath(indexPath) if scrollDirection == .Vertical { let horiOffset : CGFloat = ((row % 2) != 0) ? 0 : self.itemSize.width * 0.5 let vertOffset : CGFloat = 0 attributes.center = CGPoint( x: ( (col * self.itemSize.width) + (0.5 * self.itemSize.width) + horiOffset), y: ( ( (row * 0.75) * self.itemSize.height) + (0.5 * self.itemSize.height) + vertOffset) ) } else { let horiOffset : CGFloat = 0 let vertOffset : CGFloat = ((row % 2) != 0) ? 0 : self.itemSize.height * 0.5 attributes.center = CGPoint( x: ( ( (row * 0.75) * itemSize.width) + (0.5 * itemSize.width) + horiOffset), y: ( (col * itemSize.height) + (0.5 * itemSize.height) + vertOffset) ) } attributesCache[indexPath] = attributes return attributes } override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return false } // private var lastIndexPath : NSIndexPath? // { // if let collectionView = self.collectionView // { // let section = collectionView.numberOfSections() - 1 // // if section >= 0 // { // let item = collectionView.numberOfItemsInSection(section) - 1 // // if item >= 0 // { // return NSIndexPath(forItem: item, inSection: section) // } // } // } // // return nil // } private var cachedCollectionViewContentSize : CGSize? override public func collectionViewContentSize() -> CGSize { if let size = cachedCollectionViewContentSize { return size } if let collectionView = self.collectionView, let lastIndexPath = collectionView.lastIndexPath, let attributes = layoutAttributesForItemAtIndexPath(lastIndexPath) { return CGSize( width: max(collectionView.bounds.width, attributes.frame.maxX), height: max(collectionView.bounds.height, attributes.frame.maxY)) } return CGSizeZero } }
661a809c4a80993e5028584179c6efcf
29.961538
174
0.562578
false
false
false
false
apple/swift-protobuf
refs/heads/main
Sources/SwiftProtobuf/TimeUtils.swift
apache-2.0
3
// Sources/SwiftProtobuf/TimeUtils.swift - Generally useful time/calendar functions // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Generally useful time/calendar functions and constants /// // ----------------------------------------------------------------------------- let minutesPerDay: Int32 = 1440 let minutesPerHour: Int32 = 60 let secondsPerDay: Int32 = 86400 let secondsPerHour: Int32 = 3600 let secondsPerMinute: Int32 = 60 let nanosPerSecond: Int32 = 1000000000 internal func timeOfDayFromSecondsSince1970(seconds: Int64) -> (hh: Int32, mm: Int32, ss: Int32) { let secondsSinceMidnight = Int32(mod(seconds, Int64(secondsPerDay))) let ss = mod(secondsSinceMidnight, secondsPerMinute) let mm = mod(div(secondsSinceMidnight, secondsPerMinute), minutesPerHour) let hh = Int32(div(secondsSinceMidnight, secondsPerHour)) return (hh: hh, mm: mm, ss: ss) } internal func julianDayNumberFromSecondsSince1970(seconds: Int64) -> Int64 { // January 1, 1970 is Julian Day Number 2440588. // See http://aa.usno.navy.mil/faq/docs/JD_Formula.php return div(seconds + 2440588 * Int64(secondsPerDay), Int64(secondsPerDay)) } internal func gregorianDateFromSecondsSince1970(seconds: Int64) -> (YY: Int32, MM: Int32, DD: Int32) { // The following implements Richards' algorithm (see the Wikipedia article // for "Julian day"). // If you touch this code, please test it exhaustively by playing with // Test_Timestamp.testJSON_range. let JJ = julianDayNumberFromSecondsSince1970(seconds: seconds) let f = JJ + 1401 + div(div(4 * JJ + 274277, 146097) * 3, 4) - 38 let e = 4 * f + 3 let g = Int64(div(mod(e, 1461), 4)) let h = 5 * g + 2 let DD = div(mod(h, 153), 5) + 1 let MM = mod(div(h, 153) + 2, 12) + 1 let YY = div(e, 1461) - 4716 + div(12 + 2 - MM, 12) return (YY: Int32(YY), MM: Int32(MM), DD: Int32(DD)) } internal func nanosToString(nanos: Int32) -> String { if nanos == 0 { return "" } else if nanos % 1000000 == 0 { return ".\(threeDigit(abs(nanos) / 1000000))" } else if nanos % 1000 == 0 { return ".\(sixDigit(abs(nanos) / 1000))" } else { return ".\(nineDigit(abs(nanos)))" } }
88c690393c12a999b0ffcc73e77e9ecf
37.307692
102
0.637605
false
false
false
false
Ataraxiis/MGW-Esport
refs/heads/develop
Carthage/Checkouts/RxSwift/RxCocoa/Common/Observable+Bind.swift
apache-2.0
28
// // Observable+Bind.swift // Rx // // Created by Krunoslav Zaher on 8/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif extension ObservableType { /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better, and enables writing more consistent binding code. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer. */ @warn_unused_result(message="http://git.io/rxs.ud") public func bindTo<O: ObserverType where O.E == E>(observer: O) -> Disposable { return self.subscribe(observer) } /** Creates new subscription and sends elements to variable. In case error occurs in debug mode, `fatalError` will be raised. In case error occurs in release mode, `error` will be logged. - parameter variable: Target variable for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer. */ @warn_unused_result(message="http://git.io/rxs.ud") public func bindTo(variable: Variable<E>) -> Disposable { return subscribe { e in switch e { case let .Next(element): variable.value = element case let .Error(error): let error = "Binding error to variable: \(error)" #if DEBUG rxFatalError(error) #else print(error) #endif case .Completed: break } } } /** Subscribes to observable sequence using custom binder function. - parameter binder: Function used to bind elements from `self`. - returns: Object representing subscription. */ @warn_unused_result(message="http://git.io/rxs.ud") public func bindTo<R>(binder: Self -> R) -> R { return binder(self) } /** Subscribes to observable sequence using custom binder function and final parameter passed to binder function after `self` is passed. public func bindTo<R1, R2>(binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return binder(self)(curriedArgument) } - parameter binder: Function used to bind elements from `self`. - parameter curriedArgument: Final argument passed to `binder` to finish binding process. - returns: Object representing subscription. */ @warn_unused_result(message="http://git.io/rxs.ud") public func bindTo<R1, R2>(binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return binder(self)(curriedArgument) } /** Subscribes an element handler to an observable sequence. In case error occurs in debug mode, `fatalError` will be raised. In case error occurs in release mode, `error` will be logged. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func bindNext(onNext: E -> Void) -> Disposable { return subscribe(onNext: onNext, onError: { error in let error = "Binding error: \(error)" #if DEBUG rxFatalError(error) #else print(error) #endif }) } }
ac9aaf78f9815188d8f0d6dd049d6f1e
32.149533
112
0.625317
false
false
false
false
ivanbruel/Moya-ObjectMapper
refs/heads/master
Sample/Demo-ReactiveSwift/ViewController.swift
mit
1
// // ViewController.swift // Demo-ReactiveSwift // // Created by Robin Picard on 12/04/2019. // Copyright © 2019 Ash Furrow. All rights reserved. // import Moya import ReactiveCocoa import ReactiveSwift import UIKit class ViewController: UIViewController { @IBOutlet weak var zenButton: UIBarButtonItem! @IBOutlet weak var searchButton: UIBarButtonItem! @IBOutlet var tableView: UITableView! { didSet { tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.dataSource = self tableView.reactive.reloadData <~ viewModel.reloadDataSignal } } private let viewModel: ReactiveDemoViewModel = ReactiveDemoViewModel(networking: GitHubProvider) override func viewDidLoad() { super.viewDidLoad() initializeViewModel() } fileprivate func initializeViewModel() { viewModel.downloadZenSignal.observeValues { [weak self] result in switch result { case .success(let value): self?.showMessage(message: value) case .failure(let error): self?.showError(error: error) } } viewModel.downloadRepoSignal.observeValues { [weak self] result in switch result { case .success: break case .failure: self?.presentUsernamePrompt() } } viewModel.downloadRepositories(username: "p-rob") } fileprivate func showError(error: Error) { let alert = UIAlertController(title: "An error has occured!", message: error.localizedDescription, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } fileprivate func showMessage(message: String) { let alert = UIAlertController(title: "Info", message: message, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } fileprivate func presentUsernamePrompt() { var usernameTextField: UITextField? let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in if let username = usernameTextField?.text { self?.viewModel.downloadRepositories(username: username) } }) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) promptController.addAction(ok) promptController.addAction(cancel) promptController.addTextField { (textField) -> Void in usernameTextField = textField } present(promptController, animated: true, completion: nil) } // MARK: - User Interaction @IBAction func searchWasPressed(_ sender: UIBarButtonItem) { presentUsernamePrompt() } @IBAction func zenWasPressed(_ sender: UIBarButtonItem) { viewModel.downloadZen() } } extension ViewController: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.datasource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let repo = viewModel.datasource[indexPath.row] cell.textLabel?.text = repo.name return cell } }
3ab0166b57312364602342b72225e2c5
31.907407
126
0.712155
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
refs/heads/master
Source/Cards/Client/CardClient+Queries.swift
bsd-3-clause
1
// // Copyright (C) 2015-2020 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation // MARK: - Queries extension CardClient: CardClientProtocol { /// HTTP header key for getCard response that marks outdated cards @objc public static let xVirgilIsSuperseededKey = "x-virgil-is-superseeded" /// HTTP header value for xVirgilIsSuperseededKey key for getCard response that marks outdated cards @objc public static let xVirgilIsSuperseededTrue = "true" private func createRetry() -> RetryProtocol { return ExpBackoffRetry(config: self.retryConfig) } /// Returns `GetCardResponse` with `RawSignedModel` of card from the Virgil Cards Service with given ID, if exists /// /// - Parameter cardId: String with unique Virgil Card identifier /// - Returns: `GetCardResponse` if card found /// - Throws: /// - `CardClientError.constructingUrl`, if url initialization failed /// - Rethrows from `ServiceRequest` /// - Rethrows `ServiceError` or `NSError` from `BaseClient` @objc open func getCard(withId cardId: String) throws -> GetCardResponse { guard let url = URL(string: "card/v5/\(cardId)", relativeTo: self.serviceUrl) else { throw CardClientError.constructingUrl } let tokenContext = TokenContext(service: "cards", operation: "get", forceReload: false) let request = try ServiceRequest(url: url, method: .get) let response = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) .startSync() .get() let isOutdated: Bool // Swift dictionaries doesn't support case-insensitive keys, NSDictionary does let allHeaders = (response.response.allHeaderFields as NSDictionary) if let xVirgilIsSuperseeded = allHeaders[CardClient.xVirgilIsSuperseededKey] as? String, xVirgilIsSuperseeded == CardClient.xVirgilIsSuperseededTrue { isOutdated = true } else { isOutdated = false } return GetCardResponse(rawCard: try self.processResponse(response), isOutdated: isOutdated) } /// Creates Virgil Card instance on the Virgil Cards Service /// Also makes the Card accessible for search/get queries from other users /// `RawSignedModel` should contain appropriate signatures /// /// - Parameter model: Signed `RawSignedModel` /// - Returns: `RawSignedModel` of created card /// - Throws: /// - `CardClientError.constructingUrl`, if url initialization failed /// - Rethrows from `ServiceRequest` /// - Rethrows `ServiceError` or `NSError` from `BaseClient` @objc open func publishCard(model: RawSignedModel) throws -> RawSignedModel { guard let url = URL(string: "card/v5", relativeTo: self.serviceUrl) else { throw CardClientError.constructingUrl } let tokenContext = TokenContext(service: "cards", operation: "publish", forceReload: false) let request = try ServiceRequest(url: url, method: .post, params: model) let response = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) .startSync() .get() return try self.processResponse(response) } /// Performs search of Virgil Cards using given identities on the Virgil Cards Service /// /// - Parameter identities: Identities of cards to search /// - Returns: Array with `RawSignedModel`s of matched Virgil Cards /// - Throws: /// - CardClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with CardClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc public func searchCards(identities: [String]) throws -> [RawSignedModel] { guard let url = URL(string: "card/v5/actions/search", relativeTo: self.serviceUrl) else { throw CardClientError.constructingUrl } let tokenContext = TokenContext(service: "cards", operation: "search", forceReload: false) let request = try ServiceRequest(url: url, method: .post, params: ["identities": identities]) let response = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) .startSync() .get() return try self.processResponse(response) } /// Returns list of cards that were replaced with newer ones /// /// - Parameter cardIds: card ids to check /// - Returns: List of old card ids /// - Throws: /// - CardClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with CardClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc public func getOutdated(cardIds: [String]) throws -> [String] { guard let url = URL(string: "card/v5/actions/outdated", relativeTo: self.serviceUrl) else { throw CardClientError.constructingUrl } let tokenContext = TokenContext(service: "cards", operation: "get-outdated", forceReload: false) let request = try ServiceRequest(url: url, method: .post, params: ["card_ids": cardIds]) let response = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) .startSync() .get() return try self.processResponse(response) } /// Revokes card. Revoked card gets isOutdated flag to be set to true. /// Also, such cards could be obtained using get query, but will be absent in search query result. /// /// - Parameter cardId: identifier of card to revoke /// - Throws: /// - CardClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with CardClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc public func revokeCard(withId cardId: String) throws { guard let url = URL(string: "card/v5/actions/revoke/\(cardId)", relativeTo: self.serviceUrl) else { throw CardClientError.constructingUrl } let tokenContext = TokenContext(service: "cards", operation: "revoke", forceReload: false) let request = try ServiceRequest(url: url, method: .post) let response = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) .startSync() .get() try self.validateResponse(response) } }
240df3b28e6e48a3153591db66d09ea3
45.172414
118
0.63875
false
false
false
false
hibu/apptentive-ios
refs/heads/master
Demo/iOSDemo/DataViewController.swift
bsd-3-clause
1
// // DataViewController.swift // iOS Demo // // Created by Frank Schmitt on 4/27/16. // Copyright © 2016 Apptentive, Inc. All rights reserved. // import UIKit class DataViewController: UITableViewController { @IBOutlet var modeControl: UISegmentedControl! let dataSources = [PersonDataSource(), DeviceDataSource()] override func setEditing(editing: Bool, animated: Bool) { dataSources.forEach { $0.editing = editing } let numberOfRows = self.tableView.numberOfRowsInSection(1) var indexPaths = [NSIndexPath]() if editing { for row in numberOfRows..<(numberOfRows + 3) { indexPaths.append(NSIndexPath(forRow: row, inSection: 1)) } self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Top) } else { for row in (numberOfRows - 3)..<numberOfRows { indexPaths.append(NSIndexPath(forRow: row, inSection: 1)) } self.tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Top) } super.setEditing(editing, animated: animated) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.titleView = modeControl self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateMode(modeControl) } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { if indexPath.section == 1 { if indexPath.row >= tableView.numberOfRowsInSection(1) - 3 { return .Insert } else { return .Delete } } return .None } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let dataSource = tableView.dataSource as? DataSource where dataSource == dataSources[0] && indexPath.section == 0 && self.editing { if let navigationController = self.storyboard?.instantiateViewControllerWithIdentifier("NameEmailNavigation") as? UINavigationController, let stringViewController = navigationController.viewControllers.first as? StringViewController { stringViewController.title = indexPath.row == 0 ? "Edit Name" : "Edit Email" stringViewController.string = indexPath.row == 0 ? Apptentive.sharedConnection().personName : Apptentive.sharedConnection().personEmailAddress self.presentViewController(navigationController, animated: true, completion: nil) } } } @IBAction func updateMode(sender: UISegmentedControl) { let dataSource = dataSources[sender.selectedSegmentIndex] dataSource.refresh() self.tableView.dataSource = dataSource; self.tableView.reloadData() } @IBAction func returnToDataList(sender: UIStoryboardSegue) { if let value = (sender.sourceViewController as? StringViewController)?.string { if let selectedIndex = self.tableView.indexPathForSelectedRow?.row { if selectedIndex == 0 { Apptentive.sharedConnection().personName = value } else { Apptentive.sharedConnection().personEmailAddress = value } } tableView.reloadSections(NSIndexSet(index:0), withRowAnimation: .Automatic) } } func addCustomData(index: Int) { print("Adding type with index \(index)") } } class DataSource: NSObject, UITableViewDataSource { var editing = false override init() { super.init() self.refresh() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("Datum", forIndexPath: indexPath) } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Standard Data" } else { return "Custom Data" } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return indexPath.section == 1 } func refresh() { } // TODO: convert to enum? func labelForAdding(index: Int) -> String { switch index { case 0: return "Add String" case 1: return "Add Number" default: return "Add Boolean" } } func reuseIdentifierForAdding(index: Int) -> String { switch index { case 0: return "String" case 1: return "Number" default: return "Boolean" } } } class PersonDataSource: DataSource { var customKeys = [String]() var customData = [String : NSObject]() override func refresh() { if let customData = (Apptentive.sharedConnection().customPersonData as NSDictionary) as? [String : NSObject] { self.customData = customData self.customKeys = customData.keys.sort { $0 < $1 } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 } else { return self.customKeys.count + (self.editing ? 3 : 0) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell if indexPath.section == 0 || indexPath.row < self.customKeys.count { cell = tableView.dequeueReusableCellWithIdentifier("Datum", forIndexPath: indexPath) let key: String let value: String? if indexPath.section == 0 { if indexPath.row == 0 { key = "Name" value = Apptentive.sharedConnection().personName } else { key = "Email" value = Apptentive.sharedConnection().personEmailAddress } } else { key = self.customKeys[indexPath.row] value = self.customData[key]?.description } cell.textLabel?.text = key cell.detailTextLabel?.text = value } else { cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifierForAdding(indexPath.row - self.customKeys.count), forIndexPath: indexPath) } return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { return } else if editingStyle == .Delete { Apptentive.sharedConnection().removeCustomPersonDataWithKey(self.customKeys[indexPath.row]) self.refresh() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } else if editingStyle == .Insert { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomDataCell, let key = cell.keyField.text { switch self.reuseIdentifierForAdding(indexPath.row - self.customKeys.count) { case "String": if let textField = cell.valueControl as? UITextField, string = textField.text { Apptentive.sharedConnection().addCustomPersonDataString(string, withKey: key) textField.text = nil } case "Number": if let textField = cell.valueControl as? UITextField, numberString = textField.text, number = NSNumberFormatter().numberFromString(numberString) { Apptentive.sharedConnection().addCustomPersonDataNumber(number, withKey: key) textField.text = nil } case "Boolean": if let switchControl = cell.valueControl as? UISwitch { Apptentive.sharedConnection().addCustomPersonDataBool(switchControl.on, withKey: key) switchControl.on = true } default: break; } tableView.deselectRowAtIndexPath(indexPath, animated: true) self.refresh() tableView.reloadSections(NSIndexSet(index:1), withRowAnimation: .Automatic) cell.keyField.text = nil } } } } class DeviceDataSource: DataSource { var deviceKeys = [String]() var deviceData = [String : AnyObject]() var customDeviceKeys = [String]() var customDeviceData = [String : NSObject]() override func refresh() { self.deviceData = Apptentive.sharedConnection().deviceInfo self.deviceKeys = self.deviceData.keys.sort { $0 < $1 } if let customDataKeyIndex = self.deviceKeys.indexOf("custom_data") { self.deviceKeys.removeAtIndex(customDataKeyIndex) } if let customDeviceData = (Apptentive.sharedConnection().customDeviceData as NSDictionary) as? [String : NSObject] { self.customDeviceData = customDeviceData self.customDeviceKeys = customDeviceData.keys.sort { $0 < $1 } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.deviceKeys.count } else { return self.customDeviceKeys.count + (self.editing ? 3 : 0) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell if indexPath.section == 0 || indexPath.row < self.customDeviceKeys.count { cell = tableView.dequeueReusableCellWithIdentifier("Datum", forIndexPath: indexPath) let key: String let value: String? if indexPath.section == 0 { key = self.deviceKeys[indexPath.row] value = self.deviceData[key]?.description } else { key = self.customDeviceKeys[indexPath.row] value = self.customDeviceData[key]?.description } cell.textLabel?.text = key cell.detailTextLabel?.text = value cell.selectionStyle = indexPath.section == 0 ? .None : .Default } else { cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifierForAdding(indexPath.row - self.customDeviceKeys.count), forIndexPath: indexPath) } return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { return } else if editingStyle == .Delete { Apptentive.sharedConnection().removeCustomDeviceDataWithKey(self.customDeviceKeys[indexPath.row]) self.refresh() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } else if editingStyle == .Insert { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomDataCell, let key = cell.keyField.text { switch self.reuseIdentifierForAdding(indexPath.row - self.customDeviceKeys.count) { case "String": if let textField = cell.valueControl as? UITextField, string = textField.text { Apptentive.sharedConnection().addCustomDeviceDataString(string, withKey: key) textField.text = nil } case "Number": if let textField = cell.valueControl as? UITextField, numberString = textField.text, number = NSNumberFormatter().numberFromString(numberString) { Apptentive.sharedConnection().addCustomDeviceDataNumber(number, withKey: key) textField.text = nil } case "Boolean": if let switchControl = cell.valueControl as? UISwitch { Apptentive.sharedConnection().addCustomDeviceDataBool(switchControl.on, withKey: key) switchControl.on = true } default: break; } tableView.deselectRowAtIndexPath(indexPath, animated: true) self.refresh() tableView.reloadSections(NSIndexSet(index:1), withRowAnimation: .Automatic) cell.keyField.text = nil } } } }
5013b4ffb89aaebb707e6b457a8f75ee
31.81982
237
0.730442
false
false
false
false
realm/SwiftLint
refs/heads/main
Source/SwiftLintFramework/Models/Example.swift
mit
1
/// Captures code and context information for an example of a triggering or /// non-triggering style public struct Example { /// The contents of the example public private(set) var code: String /// The untyped configuration to apply to the rule, if deviating from the default configuration. /// The structure should match what is expected as a configuration value for the rule being tested. /// /// For example, if the following YAML would be used to configure the rule: /// /// ``` /// severity: warning /// ``` /// /// Then the equivalent configuration value would be `["severity": "warning"]`. public private(set) var configuration: Any? /// Whether the example should be tested by prepending multibyte grapheme clusters /// /// - SeeAlso: addEmoji(_:) public private(set) var testMultiByteOffsets: Bool /// Whether tests shall verify that the example wrapped in a comment doesn't trigger private(set) var testWrappingInComment: Bool /// Whether tests shall verify that the example wrapped into a string doesn't trigger private(set) var testWrappingInString: Bool /// Whether tests shall verify that the disabled rule (comment in the example) doesn't trigger private(set) var testDisableCommand: Bool /// Whether the example should be tested on Linux public private(set) var testOnLinux: Bool /// The path to the file where the example was created public private(set) var file: StaticString /// The line in the file where the example was created public var line: UInt /// Specifies whether the example should be excluded from the rule documentation. /// /// It can be set to `true` if an example has mainly been added as another test case, but is not suitable /// as a user example. User examples should be easy to understand. They should clearly show where and /// why a rule is applied and where not. Complex examples with rarely used language constructs or /// pathological use cases which are indeed important to test but not helpful for understanding can be /// hidden from the documentation with this option. let excludeFromDocumentation: Bool /// Specifies whether the test example should be the only example run during the current test case execution. var isFocused: Bool } public extension Example { /// Create a new Example with the specified code, file, and line. /// - Parameters: /// - code: The contents of the example. /// - configuration: The untyped configuration to apply to the rule, if deviating from the default /// configuration. /// - testMultibyteOffsets: Whether the example should be tested by prepending multibyte grapheme clusters. /// - testWrappingInComment:Whether test shall verify that the example wrapped in a comment doesn't trigger. /// - testWrappingInString: Whether tests shall verify that the example wrapped into a string doesn't trigger. /// - testDisableCommand: Whether tests shall verify that the disabled rule (comment in the example) doesn't /// trigger. /// - testOnLinux: Whether the example should be tested on Linux. /// - file: The path to the file where the example is located. /// Defaults to the file where this initializer is called. /// - line: The line in the file where the example is located. /// Defaults to the line where this initializer is called. init(_ code: String, configuration: Any? = nil, testMultiByteOffsets: Bool = true, testWrappingInComment: Bool = true, testWrappingInString: Bool = true, testDisableCommand: Bool = true, testOnLinux: Bool = true, file: StaticString = #file, line: UInt = #line, excludeFromDocumentation: Bool = false) { self.code = code self.configuration = configuration self.testMultiByteOffsets = testMultiByteOffsets self.testOnLinux = testOnLinux self.file = file self.line = line self.excludeFromDocumentation = excludeFromDocumentation self.testWrappingInComment = testWrappingInComment self.testWrappingInString = testWrappingInString self.testDisableCommand = testDisableCommand self.isFocused = false } /// Returns the same example, but with the `code` that is passed in /// - Parameter code: the new code to use in the modified example func with(code: String) -> Example { var new = self new.code = code return new } /// Returns a copy of the Example with all instances of the "↓" character removed. func removingViolationMarkers() -> Example { return with(code: code.replacingOccurrences(of: "↓", with: "")) } } extension Example { func skipWrappingInCommentTest() -> Self { var new = self new.testWrappingInComment = false return new } func skipWrappingInStringTest() -> Self { var new = self new.testWrappingInString = false return new } func skipMultiByteOffsetTest() -> Self { var new = self new.testMultiByteOffsets = false return new } func skipDisableCommandTest() -> Self { var new = self new.testDisableCommand = false return new } /// Makes the current example focused. This is for debugging purposes only. func focused() -> Example { // swiftlint:disable:this unused_declaration var new = self new.isFocused = true return new } } extension Example: Hashable { public static func == (lhs: Example, rhs: Example) -> Bool { // Ignoring file/line metadata because two Examples could represent // the same idea, but captured at two different points in the code return lhs.code == rhs.code } public func hash(into hasher: inout Hasher) { // Ignoring file/line metadata because two Examples could represent // the same idea, but captured at two different points in the code hasher.combine(code) } } extension Example: Comparable { public static func < (lhs: Example, rhs: Example) -> Bool { return lhs.code < rhs.code } } extension Array where Element == Example { /// Make these examples skip wrapping in comment tests. func skipWrappingInCommentTests() -> Self { map { $0.skipWrappingInCommentTest() } } /// Make these examples skip wrapping in string tests. func skipWrappingInStringTests() -> Self { map { $0.skipWrappingInStringTest() } } /// Make these examples skip multi-byte offset tests. func skipMultiByteOffsetTests() -> Self { map { $0.skipMultiByteOffsetTest() } } /// Make these examples skip disable command tests. func skipDisableCommandTests() -> Self { map { $0.skipDisableCommandTest() } } }
8240c53882eb06b3d96af1348a629cba
41.487952
116
0.661562
false
true
false
false
SamirTalwar/advent-of-code
refs/heads/main
2018/AOC_13_2.swift
mit
1
enum Turning { case left case straight case right } enum Direction: CustomStringConvertible { case north case east case south case west var description: String { switch self { case .north: return "^" case .east: return ">" case .south: return "v" case .west: return "<" } } var isHorizontal: Bool { return self == .east || self == .west } var isVertical: Bool { return self == .north || self == .south } func turn(_ turning: Turning) -> Direction { switch (self, turning) { case (.north, .left): return .west case (.east, .left): return .north case (.south, .left): return .east case (.west, .left): return .south case (.north, .right): return .east case (.east, .right): return .south case (.south, .right): return .west case (.west, .right): return .north case (_, .straight): return self } } } struct Position: Equatable, Comparable, Hashable, CustomStringConvertible { let x: Int let y: Int var description: String { return "(\(x), \(y))" } static func < (lhs: Position, rhs: Position) -> Bool { if lhs.y != rhs.y { return lhs.y < rhs.y } else { return lhs.x < rhs.x } } func move(_ direction: Direction) -> Position { switch direction { case .north: return Position(x: x, y: y - 1) case .east: return Position(x: x + 1, y: y) case .south: return Position(x: x, y: y + 1) case .west: return Position(x: x - 1, y: y) } } } enum TrackPiece { case empty case horizontal case vertical case turningLeftFromNorthOrSouth case turningRightFromNorthOrSouth case intersection } extension TrackPiece: CustomStringConvertible { var description: String { switch self { case .empty: return " " case .horizontal: return "-" case .vertical: return "|" case .turningLeftFromNorthOrSouth: return "\\" case .turningRightFromNorthOrSouth: return "/" case .intersection: return "+" } } } struct Tracks: CustomStringConvertible { private let tracks: [[TrackPiece]] init(_ tracks: [[TrackPiece]]) { self.tracks = tracks } var description: String { return tracks.map { row in row.map { cell in cell.description }.joined() }.joined(separator: "\n") } subscript(position: Position) -> TrackPiece { return tracks[position.y][position.x] } } struct Cart: CustomStringConvertible { let position: Position let direction: Direction let intersectionTurning: Turning var description: String { return "\(position) \(direction)" } func move(tracks: Tracks) -> Cart { let newPosition = position.move(direction) var newDirection = direction var newIntersectionTurning = intersectionTurning switch tracks[newPosition] { case .empty: fatalError("A cart ended up on a piece of empty track.") case .horizontal: if direction.isVertical { fatalError("A cart ended up going vertically on a horizontal track.") } case .vertical: if direction.isHorizontal { fatalError("A cart ended up going horizontally on a vertical track.") } case .turningLeftFromNorthOrSouth: newDirection = direction.isVertical ? direction.turn(.left) : direction.turn(.right) case .turningRightFromNorthOrSouth: newDirection = direction.isVertical ? direction.turn(.right) : direction.turn(.left) case .intersection: newDirection = direction.turn(intersectionTurning) switch intersectionTurning { case .left: newIntersectionTurning = .straight case .straight: newIntersectionTurning = .right case .right: newIntersectionTurning = .left } } return Cart( position: newPosition, direction: newDirection, intersectionTurning: newIntersectionTurning ) } } func main() { let tracksAndCarts = StdIn().enumerated().map { line in line.element.enumerated().map { character in parseTrack(position: Position(x: character.offset, y: line.offset), character: character.element) } } let columns = tracksAndCarts.map { row in row.count }.max()! let tracks = Tracks(tracksAndCarts.map { row in pad(row.map { track, _ in track }, to: columns, with: .empty) }) let initialCarts = tracksAndCarts.flatMap { row in row.compactMap { _, cart in cart } } var carts = initialCarts while carts.count > 1 { carts.sort(by: comparing { cart in cart.position }) var i = 0 while carts.count > 1, i < carts.count { carts[i] = carts[i].move(tracks: tracks) var crash = false for crashIndex in carts.startIndex ..< carts.endIndex { if crashIndex >= carts.endIndex { break } if crashIndex != i, carts[crashIndex].position == carts[i].position { crash = true carts.remove(at: crashIndex) if crashIndex < i { i -= 1 } } } if crash { carts.remove(at: i) } else { i += 1 } } } carts[0] = carts[0].move(tracks: tracks) print(carts[0].position) } func parseTrack(position: Position, character: Character) -> (TrackPiece, Cart?) { switch character { case " ": return (.empty, nil) case "-": return (.horizontal, nil) case "|": return (.vertical, nil) case "\\": return (.turningLeftFromNorthOrSouth, nil) case "/": return (.turningRightFromNorthOrSouth, nil) case "+": return (.intersection, nil) case "^": return (.vertical, Cart(position: position, direction: .north, intersectionTurning: .left)) case "v": return (.vertical, Cart(position: position, direction: .south, intersectionTurning: .left)) case "<": return (.horizontal, Cart(position: position, direction: .west, intersectionTurning: .left)) case ">": return (.horizontal, Cart(position: position, direction: .east, intersectionTurning: .left)) default: preconditionFailure("\"\(character)\" is an invalid track piece.") } } func pad<T>(_ array: [T], to size: Int, with value: T) -> [T] { if array.count < size { return array + Array(repeating: value, count: size - array.count) } return array }
0bd194d572616017283392076aec436f
27.356863
109
0.545153
false
false
false
false
nathantannar4/InputBarAccessoryView
refs/heads/master
Example/Sources/InputBar Examples/InputBarStyle.swift
mit
1
// // InputBarStyle.swift // Example // // Created by Nathan Tannar on 8/18/17. // Copyright © 2017-2020 Nathan Tannar. All rights reserved. // import Foundation import InputBarAccessoryView enum InputBarStyle: String, CaseIterable { case imessage = "iMessage" case slack = "Slack" case githawk = "GitHawk" case facebook = "Facebook" case noTextView = "No InputTextView" case `default` = "Default" func generate() -> InputBarAccessoryView { switch self { case .imessage: return iMessageInputBar() case .slack: return SlackInputBar() case .githawk: return GitHawkInputBar() case .facebook: return FacebookInputBar() case .noTextView: return NoTextViewInputBar() case .default: return InputBarAccessoryView() } } }
8184c6705d88a812a1ea7d976918077d
25.612903
61
0.658182
false
false
false
false
DuCalixte/iTunesSearchPattern
refs/heads/develop
iTunesSearchPattern/SearchItunesController.swift
mit
1
// // SearchItunesController.swift // iTunesSearchPattern // // Created by STANLEY CALIXTE on 10/25/14. // Copyright (c) 2014 STANLEY CALIXTE. All rights reserved. // import Foundation import UIKit class SearchItunesController: UIViewController, UITableViewDataSource, UITableViewDelegate, ITunesAPIControllerProtocol { @IBOutlet weak var tableView: UITableView! // @IBOutlet var tableView : UITableView? @IBOutlet weak var searchField: UITextField! let kCellIdentifier: String = "SearchResultCell" var api : ITunesAPIController? var imageCache = [String : UIImage]() var albums = [Album]() var entities = [Entity]() var mediaOption: String = "music" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. api = ITunesAPIController(delegate: self) self.tableView?.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin // UIViewAutoresizingFlexibleTopMargin; // UIViewAutoresizingFlexibleHeight; self.tableView.delegate = self; self.tableView.dataSource = self; // self.tableView.delegate = self self.tableView.showsVerticalScrollIndicator=true UIApplication.sharedApplication().networkActivityIndicatorVisible = true api!.searchItunesFor("Beatles", mediaType: self.mediaOption) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count:Int = 0 switch self.mediaOption{ case "music": count = self.albums.count break; default: count = self.entities.count } return count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell: UITableViewCell = (tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell?)! switch self.mediaOption{ case "music": self.setCellFromAlbum(tableView, displayCell: cell, forRowAtIndexPath: indexPath) break; default: break; } return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1,1,1) }) } func setCellFromAlbum(tableView: UITableView, displayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){ let album = self.albums[indexPath.row] cell.textLabel.text = album.title cell.imageView.image = UIImage(named: "Blank52") // Get the formatted price string for display in the subtitle let formattedPrice = album.price // Grab the artworkUrl60 key to get an image URL for the app's thumbnail let urlString = album.thumbnailImageURL // Check our image cache for the existing key. This is just a dictionary of UIImages //var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage var image = self.imageCache[urlString] if( image == nil ) { // If the image does not exist, we need to download it var imgURL: NSURL = NSURL(string: urlString)! // Download an NSData representation of the image at the URL let request: NSURLRequest = NSURLRequest(URL: imgURL) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in if error == nil { image = UIImage(data: data) // Store the image in to our cache self.imageCache[urlString] = image dispatch_async(dispatch_get_main_queue(), { if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) { cellToUpdate.imageView.image = image } }) } else { println("Error: \(error.localizedDescription)") } }) } else { dispatch_async(dispatch_get_main_queue(), { if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) { cellToUpdate.imageView.image = image } }) } cell.detailTextLabel?.text = formattedPrice } func didReceiveAPIResults(results: NSDictionary){ switch self.mediaOption{ case "music": self.updateAlbumsContent(results) break; default: break; } } func updateAlbumsContent(results: NSDictionary){ var resultsArr: NSArray = results["results"] as NSArray dispatch_async(dispatch_get_main_queue(), { self.albums = Album.albumsWithJSON(resultsArr) self.tableView!.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) } @IBAction func onOptionChange(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: mediaOption = "music" break; case 1: mediaOption = "movie" default: mediaOption = "all" } } @IBAction func onSearch(sender: UIButton) { if self.searchField.text != ""{ api!.searchItunesFor(self.searchField.text, mediaType: self.mediaOption) } } }
009d283e74e0c6f194cd611b2b6ab38b
34.827586
202
0.611004
false
false
false
false
cybertunnel/SplashBuddy
refs/heads/master
SplashBuddy/View/MainViewController_Actions.swift
apache-2.0
1
// // MainViewController_Actions.swift // SplashBuddy // // Created by Francois Levaux on 02.03.17. // Copyright © 2017 François Levaux-Tiffreau. All rights reserved. // import Foundation extension MainViewController { func setupInstalling() { indeterminateProgressIndicator.startAnimation(self) indeterminateProgressIndicator.isHidden = false installingLabel.stringValue = NSLocalizedString("Installing…", comment: "") statusLabel.stringValue = "" continueButton.isEnabled = false } func errorWhileInstalling() { indeterminateProgressIndicator.isHidden = true installingLabel.stringValue = "" continueButton.isEnabled = true statusLabel.textColor = .red let _failedSoftwareArray = SoftwareArray.sharedInstance.failedSoftwareArray() if _failedSoftwareArray.count == 1 { if let failedDisplayName = _failedSoftwareArray[0].displayName { statusLabel.stringValue = String.localizedStringWithFormat(NSLocalizedString( "%@ failed to install. Support has been notified.", comment: "A specific application failed to install"), failedDisplayName) } else { statusLabel.stringValue = NSLocalizedString( "An application failed to install. Support has been notified.", comment: "One (unnamed) application failed to install") } } else { statusLabel.stringValue = NSLocalizedString( "Some applications failed to install. Support has been notified.", comment: "More than one application failed to install") } } func canContinue() { continueButton.isEnabled = true } func doneInstalling() { indeterminateProgressIndicator.isHidden = true installingLabel.stringValue = "" statusLabel.textColor = .labelColor statusLabel.stringValue = NSLocalizedString( "All applications were installed. Please click continue.", comment: "All applications were installed. Please click continue.") } }
294a56073718ae62cd69230721ab3ca1
29.402597
93
0.605297
false
false
false
false
zmeyc/SQLite.swift
refs/heads/master
Sources/SQLite/Extensions/FTS4.swift
mit
1
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // extension Module { @warn_unused_result public static func FTS4(_ column: Expressible, _ more: Expressible...) -> Module { return FTS4([column] + more) } @warn_unused_result public static func FTS4(_ columns: [Expressible] = [], tokenize tokenizer: Tokenizer? = nil) -> Module { var columns = columns if let tokenizer = tokenizer { columns.append("=".join([Expression<Void>(literal: "tokenize"), Expression<Void>(literal: tokenizer.description)])) } return Module(name: "fts4", arguments: columns) } } extension VirtualTable { /// Builds an expression appended with a `MATCH` query against the given /// pattern. /// /// let emails = VirtualTable("emails") /// /// emails.filter(emails.match("Hello")) /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: An expression appended with a `MATCH` query against the given /// pattern. @warn_unused_result public func match(_ pattern: String) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } @warn_unused_result public func match(_ pattern: Expression<String>) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } @warn_unused_result public func match(_ pattern: Expression<String?>) -> Expression<Bool?> { return "MATCH".infix(tableName(), pattern) } /// Builds a copy of the query with a `WHERE … MATCH` clause. /// /// let emails = VirtualTable("emails") /// /// emails.match("Hello") /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A query with the given `WHERE … MATCH` clause applied. @warn_unused_result public func match(_ pattern: String) -> QueryType { return filter(match(pattern)) } @warn_unused_result public func match(_ pattern: Expression<String>) -> QueryType { return filter(match(pattern)) } @warn_unused_result public func match(_ pattern: Expression<String?>) -> QueryType { return filter(match(pattern)) } } public struct Tokenizer { public static let Simple = Tokenizer("simple") public static let Porter = Tokenizer("porter") @warn_unused_result public static func Unicode61(removeDiacritics: Bool? = nil, tokenchars: Set<Character> = [], separators: Set<Character> = []) -> Tokenizer { var arguments = [String]() if let removeDiacritics = removeDiacritics { arguments.append("removeDiacritics=\(removeDiacritics ? 1 : 0)".quote()) } if !tokenchars.isEmpty { let joined = tokenchars.map { String($0) }.joined(separator: "") arguments.append("tokenchars=\(joined)".quote()) } if !separators.isEmpty { let joined = separators.map { String($0) }.joined(separator: "") arguments.append("separators=\(joined)".quote()) } return Tokenizer("unicode61", arguments) } @warn_unused_result public static func Custom(_ name: String) -> Tokenizer { return Tokenizer(Tokenizer.moduleName.quote(), [name.quote()]) } public let name: String public let arguments: [String] private init(_ name: String, _ arguments: [String] = []) { self.name = name self.arguments = arguments } private static let moduleName = "SQLite.swift" } extension Tokenizer : CustomStringConvertible { public var description: String { return ([name] + arguments).joined(separator: " ") } } extension Connection { public func registerTokenizer(_ submoduleName: String, next: (String) -> (String, Range<String.Index>)?) throws { fatalError("Not implemented") // FIXME // try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { input, offset, length in // let string = String.fromCString(input)! // // guard let (token, range) = next(string) else { return nil } // // let view = string.utf8 // offset.memory += string.substringToIndex(range.startIndex).utf8.count // length.memory = Int32(range.startIndex.samePositionIn(view).distanceTo(range.endIndex.samePositionIn(view))) // return token // }) } }
4dfed63719a84493571404c0157b5b46
34.289308
164
0.650864
false
false
false
false
nyin005/Forecast-App
refs/heads/master
Forecast/Forecast/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // Forecast // // Created by appledev110 on 11/11/16. // Copyright © 2016 appledev110. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var tabVC : TabViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = UIColor.white // let vc = UIViewController() // vc.view.backgroundColor = UIColor.white // self.window?.rootViewController = vc self.window?.makeKeyAndVisible() // vc.removeFromParentViewController() tabVC = TabViewController() self.window?.rootViewController = tabVC return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
f4bf4b3e077692a1413ea2a753b68d8d
46.8
285
0.736782
false
false
false
false
SwiftOnEdge/Reactive
refs/heads/master
Sources/StreamKit/Signal.swift
mit
1
// // Signal.swift // Edge // // Created by Tyler Fleming Cloutier on 5/29/16. // // import Foundation public final class Signal<Value>: SignalType, InternalSignalType, SpecialSignalGenerator { internal var observers = Bag<Observer<Value>>() private var handlerDisposable: Disposable? public var cancelDisposable: Disposable? public var signal: Signal<Value> { return self } /// Initializes a Signal that will immediately invoke the given generator, /// then forward events sent to the given observer. /// /// The disposable returned from the closure will be automatically disposed /// if a terminating event is sent to the observer. The Signal itself will /// remain alive until the observer is released. This is because the observer /// captures a self reference. public init(_ startHandler: @escaping (Observer<Value>) -> Disposable?) { let observer = Observer(with: CircuitBreaker(holding: self)) let handlerDisposable = startHandler(observer) // The cancel disposable should send interrupted and then dispose of the // disposable produced by the startHandler. cancelDisposable = ActionDisposable { observer.sendInterrupted() handlerDisposable?.dispose() } } deinit { cancelDisposable?.dispose() } /// Creates a Signal that will be controlled by sending events to the returned /// observer. /// /// The Signal will remain alive until a terminating event is sent to the /// observer. public static func pipe() -> (Signal, Observer<Value>) { var observer: Observer<Value>! let signal = self.init { innerObserver in observer = innerObserver return nil } return (signal, observer) } } extension Signal: CustomDebugStringConvertible { public var debugDescription: String { let obs = Array(self.observers.map { String(describing: $0) }) return "Signal[\(obs.joined(separator: ", "))]" } } public protocol SpecialSignalGenerator { /// The type of values being sent on the signal. associatedtype Value init(_ generator: @escaping (Observer<Value>) -> Disposable?) } public extension SpecialSignalGenerator { /// Creates a Signal that will immediately send one value /// then complete. public init(value: Value) { self.init { observer in observer.sendNext(value) observer.sendCompleted() return nil } } /// Creates a Signal that will immediately fail with the /// given error. public init(error: Error) { self.init { observer in observer.sendFailed(error) return nil } } /// Creates a Signal that will immediately send the values /// from the given sequence, then complete. public init<S: Sequence>(values: S) where S.Iterator.Element == Value { self.init { observer in var disposed = false for value in values { observer.sendNext(value) if disposed { break } } observer.sendCompleted() return ActionDisposable { disposed = true } } } /// Creates a Signal that will immediately send the values /// from the given sequence, then complete. public init(values: Value...) { self.init(values: values) } /// A Signal that will immediately complete without sending /// any values. public static var empty: Self { return self.init { observer in observer.sendCompleted() return nil } } /// A Signal that never sends any events to its observers. public static var never: Self { return self.init { _ in return nil } } } /// An internal protocol for adding methods that require access to the observers /// of the signal. internal protocol InternalSignalType: SignalType { var observers: Bag<Observer<Value>> { get } } /// Note that this type is not parameterized by an Error type which is in line /// with the Swift error handling model. /// A good reference for a discussion of the pros and cons is here: /// https://github.com/ReactiveX/RxSwift/issues/650 public protocol SignalType { /// The type of values being sent on the signal. associatedtype Value /// The exposed raw signal that underlies the `SignalType`. var signal: Signal<Value> { get } var cancelDisposable: Disposable? { get } } public extension SignalType { /// Adds an observer to the `Signal` which observes any future events from the `Signal`. /// If the `Signal` has already terminated, the observer will immediately receive an /// `Interrupted` event. /// /// Returns a Disposable which can be used to disconnect the observer. Disposing /// of the Disposable will have no effect on the `Signal` itself. @discardableResult public func add(observer: Observer<Value>) -> Disposable? { let token = signal.observers.insert(observer) return ActionDisposable { self.signal.observers.remove(using: token) } } /// Convenience override for add(observer:) to allow trailing-closure style /// invocations. @discardableResult public func on(action: @escaping Observer<Value>.Action) -> Disposable? { return self.add(observer: Observer(action)) } /// Observes the Signal by invoking the given callback when `next` events are /// received. /// /// Returns a Disposable which can be used to stop the invocation of the /// callbacks. Disposing of the Disposable will have no effect on the Signal /// itself. @discardableResult public func onNext(next: @escaping (Value) -> Void) -> Disposable? { return self.add(observer: Observer(next: next)) } /// Observes the Signal by invoking the given callback when a `completed` event is /// received. /// /// Returns a Disposable which can be used to stop the invocation of the /// callback. Disposing of the Disposable will have no effect on the Signal /// itself. @discardableResult public func onCompleted(completed: @escaping () -> Void) -> Disposable? { return self.add(observer: Observer(completed: completed)) } /// Observes the Signal by invoking the given callback when a `failed` event is /// received. /// /// Returns a Disposable which can be used to stop the invocation of the /// callback. Disposing of the Disposable will have no effect on the Signal /// itself. @discardableResult public func onFailed(error: @escaping (Error) -> Void) -> Disposable? { return self.add(observer: Observer(failed: error)) } /// Observes the Signal by invoking the given callback when an `interrupted` event is /// received. If the Signal has already terminated, the callback will be invoked /// immediately. /// /// Returns a Disposable which can be used to stop the invocation of the /// callback. Disposing of the Disposable will have no effect on the Signal /// itself. @discardableResult public func onInterrupted(interrupted: @escaping () -> Void) -> Disposable? { return self.add(observer: Observer(interrupted: interrupted)) } } public extension SignalType { public var identity: Signal<Value> { return self.map { $0 } } /// Maps each value in the signal to a new value. public func map<U>(_ transform: @escaping (Value) -> U) -> Signal<U> { return Signal { observer in return self.on { event -> Void in observer.send(event.map(transform)) } } } /// Maps errors in the signal to a new error. public func mapError<F: Error>(_ transform: @escaping (Error) -> F) -> Signal<Value> { return Signal { observer in return self.on { event -> Void in observer.send(event.mapError(transform)) } } } /// Preserves only the values of the signal that pass the given predicate. public func filter(_ predicate: @escaping (Value) -> Bool) -> Signal<Value> { return Signal { observer in return self.on { (event: Event<Value>) -> Void in guard let value = event.value else { observer.send(event) return } if predicate(value) { observer.sendNext(value) } } } } /// Splits the signal into two signals. The first signal in the tuple matches the /// predicate, the second signal does not match the predicate public func partition(_ predicate: @escaping (Value) -> Bool) -> (Signal<Value>, Signal<Value>) { let (left, leftObserver) = Signal<Value>.pipe() let (right, rightObserver) = Signal<Value>.pipe() self.on { (event: Event<Value>) -> Void in guard let value = event.value else { leftObserver.send(event) rightObserver.send(event) return } if predicate(value) { leftObserver.sendNext(value) } else { rightObserver.sendNext(value) } } return (left, right) } /// Aggregate values into a single combined value. Mirrors the Swift Collection public func reduce<T>(initial: T, _ combine: @escaping (T, Value) -> T) -> Signal<T> { return Signal { observer in var accumulator = initial return self.on { event in observer.send(event.map { value in accumulator = combine(accumulator, value) return accumulator }) } } } public func flatMap<U>(_ transform: @escaping (Value) -> U?) -> Signal<U> { return Signal { observer in return self.on { event -> Void in if let e = event.flatMap(transform) { observer.send(e) } } } } public func flatMap<U>(_ transform: @escaping (Value) -> Signal<U>) -> Signal<U> { return map(transform).joined() } } extension SignalType where Value: SignalType { /// Listens to every `Source` produced from the current `Signal` /// Starts each `Source` and forwards on all values and errors onto /// the `Signal` which is returned. In this way it joins each of the /// `Source`s into a single `Signal`. /// /// The joined `Signal` completes when the current `Signal` and all of /// its produced `Source`s complete. /// /// Note: This means that each `Source` will be started as it is received. public func joined() -> Signal<Value.Value> { // Start the number in flight at 1 for `self` return Signal { observer in var numberInFlight = 1 var disposables = [Disposable]() func decrementInFlight() { numberInFlight -= 1 if numberInFlight == 0 { observer.sendCompleted() } } func incrementInFlight() { numberInFlight += 1 } self.on { event in switch event { case .next(let source): incrementInFlight() source.on { event in switch event { case .completed, .interrupted: decrementInFlight() case .next, .failed: observer.send(event) } } source.cancelDisposable.map { disposables.append($0) } (source as? Source<Value.Value>)?.start() case .failed(let error): observer.sendFailed(error) case .completed: decrementInFlight() case .interrupted: observer.sendInterrupted() } } return ActionDisposable { for disposable in disposables { disposable.dispose() } } } } }
2e326fe4223acee26bc220cc5912d5e1
31.194937
101
0.578674
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Pods/RxSwiftExt/Source/RxSwift/ObservableType+Weak.swift
mit
1
// // ObservableType+Weak.swift // RxSwiftExt // // Created by Ian Keen on 17/04/2016. // Copyright © 2016 RxSwift Community. All rights reserved. // import Foundation import RxSwift extension ObservableType { /** Leverages instance method currying to provide a weak wrapper around an instance function - parameter obj: The object that owns the function - parameter method: The instance function represented as `InstanceType.instanceFunc` */ fileprivate func weakify<A: AnyObject, B>(_ obj: A, method: ((A) -> (B) -> Void)?) -> ((B) -> Void) { return { [weak obj] value in guard let obj = obj else { return } method?(obj)(value) } } fileprivate func weakify<A: AnyObject>(_ obj: A, method: ((A) -> () -> Void)?) -> (() -> Void) { return { [weak obj] in guard let obj = obj else { return } method?(obj)() } } /** Subscribes an event handler to an observable sequence. - parameter weak: Weakly referenced object containing the target function. - parameter on: Function to invoke on `weak` for each event in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe<A: AnyObject>(weak obj: A, _ on: @escaping (A) -> (Event<Element>) -> Void) -> Disposable { return self.subscribe(weakify(obj, method: on)) } /** Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. - parameter weak: Weakly referenced object containing the target function. - parameter onNext: Function to invoke on `weak` for each element in the observable sequence. - parameter onError: Function to invoke on `weak` upon errored termination of the observable sequence. - parameter onCompleted: Function to invoke on `weak` upon graceful termination of the observable sequence. - parameter onDisposed: Function to invoke on `weak` upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is cancelled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe<A: AnyObject>( weak obj: A, onNext: ((A) -> (Element) -> Void)? = nil, onError: ((A) -> (Error) -> Void)? = nil, onCompleted: ((A) -> () -> Void)? = nil, onDisposed: ((A) -> () -> Void)? = nil) -> Disposable { let disposable: Disposable if let disposed = onDisposed { disposable = Disposables.create(with: weakify(obj, method: disposed)) } else { disposable = Disposables.create() } let observer = AnyObserver { [weak obj] (e: Event<Element>) in guard let obj = obj else { return } switch e { case .next(let value): onNext?(obj)(value) case .error(let e): onError?(obj)(e) disposable.dispose() case .completed: onCompleted?(obj)() disposable.dispose() } } return Disposables.create(self.asObservable().subscribe(observer), disposable) } /** Subscribes an element handler to an observable sequence. - parameter weak: Weakly referenced object containing the target function. - parameter onNext: Function to invoke on `weak` for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribeNext<A: AnyObject>(weak obj: A, _ onNext: @escaping (A) -> (Element) -> Void) -> Disposable { return self.subscribe(onNext: weakify(obj, method: onNext)) } /** Subscribes an error handler to an observable sequence. - parameter weak: Weakly referenced object containing the target function. - parameter onError: Function to invoke on `weak` upon errored termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribeError<A: AnyObject>(weak obj: A, _ onError: @escaping (A) -> (Error) -> Void) -> Disposable { return self.subscribe(onError: weakify(obj, method: onError)) } /** Subscribes a completion handler to an observable sequence. - parameter weak: Weakly referenced object containing the target function. - parameter onCompleted: Function to invoke on `weak` graceful termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribeCompleted<A: AnyObject>(weak obj: A, _ onCompleted: @escaping (A) -> () -> Void) -> Disposable { return self.subscribe(onCompleted: weakify(obj, method: onCompleted)) } }
c9e9f0cb0f8c24c4559bfce69faef042
38.235294
118
0.689869
false
false
false
false
material-components/material-components-ios
refs/heads/develop
components/Ripple/examples/CardCellsWithRippleExample.swift
apache-2.0
2
// Copyright 2019-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialCards_Theming import MaterialComponents.MaterialColorScheme import MaterialComponents.MaterialContainerScheme import MaterialComponents.MaterialTypographyScheme class CardCellsWithRippleExample: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { enum ToggleMode: Int { case edit = 1 case reorder } let collectionView = UICollectionView( frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) var toggle = ToggleMode.edit @objc var containerScheme: MDCContainerScheming @objc var colorScheme: MDCColorScheming { return containerScheme.colorScheme } @objc var typographyScheme: MDCTypographyScheming { return containerScheme.typographyScheme } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { containerScheme = MDCContainerScheme() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() collectionView.frame = view.bounds collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = colorScheme.backgroundColor collectionView.alwaysBounceVertical = true collectionView.register(MDCCardCollectionCell.self, forCellWithReuseIdentifier: "Cell") collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.allowsMultipleSelection = true view.addSubview(collectionView) navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Reorder", style: .plain, target: self, action: #selector(toggleModes)) let longPressGesture = UILongPressGestureRecognizer( target: self, action: #selector(reorderCards(gesture:))) longPressGesture.cancelsTouchesInView = false collectionView.addGestureRecognizer(longPressGesture) let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ collectionView.leftAnchor.constraint(equalTo: guide.leftAnchor), collectionView.rightAnchor.constraint(equalTo: guide.rightAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor), ]) collectionView.contentInsetAdjustmentBehavior = .always self.updateTitle() } func preiOS11Constraints() { self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) } func updateTitle() { switch toggle { case .edit: navigationItem.rightBarButtonItem?.title = "Reorder" self.title = "Cards (Edit)" case .reorder: navigationItem.rightBarButtonItem?.title = "Edit" self.title = "Cards (Reorder)" } } @objc func toggleModes() { switch toggle { case .edit: toggle = .reorder case .reorder: toggle = .edit } self.updateTitle() collectionView.reloadData() } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) guard let cardCell = cell as? MDCCardCollectionCell else { return cell } cardCell.enableRippleBehavior = true cardCell.applyTheme(withScheme: containerScheme) cardCell.isSelectable = (toggle == .edit) cardCell.isAccessibilityElement = true cardCell.accessibilityLabel = title return cardCell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard toggle == .edit else { return } } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { guard toggle == .edit else { return } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return 30 } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let cardSize = (collectionView.bounds.size.width / 3) - 12 return CGSize(width: cardSize, height: cardSize) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int ) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath ) -> Bool { return toggle == .reorder } func collectionView( _ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath ) { } @objc func reorderCards(gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: guard let selectedIndexPath = collectionView.indexPathForItem( at: gesture.location(in: collectionView)) else { break } let cell = collectionView.cellForItem(at: selectedIndexPath) guard let cardCell = cell as? MDCCardCollectionCell else { break } collectionView.beginInteractiveMovementForItem(at: selectedIndexPath) if toggle == .reorder { cardCell.isDragged = true } case .changed: guard let gestureView = gesture.view else { break } collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gestureView)) case .ended: collectionView.endInteractiveMovement() default: collectionView.cancelInteractiveMovement() } } } extension CardCellsWithRippleExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Ripple", "Card Cell with Ripple"], "primaryDemo": false, "presentable": true, ] } }
2f4da3b692f4437709f41a2d5314e750
29.08871
99
0.722058
false
false
false
false
CodePath2017Group4/travel-app
refs/heads/master
RoadTripPlanner/DetailView.swift
mit
1
// // DetailView.swift // RoadTripPlanner // // Created by Deepthy on 10/26/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit @IBDesignable class DetailView: UIView { override init(frame: CGRect) { super.init(frame: frame) setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func awakeFromNib() { super.awakeFromNib() setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() } var transitionProgress: CGFloat = 0 { didSet { updateViews() } } let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() let overlayView: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 0.655, green: 0.737, blue: 0.835, alpha: 0.8) return view }() let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 20) label.textColor = UIColor.white label.textAlignment = .center return label }() let subtitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 17) label.textColor = UIColor.white label.textAlignment = .center label.numberOfLines = 0 return label }() func updateViews() { let progress = min(max(transitionProgress, 0), 1) let antiProgress = 1.0 - progress let titleLabelOffsetTop: CGFloat = 20.0 let titleLabelOffsetMiddle: CGFloat = bounds.height/2 - 44 let titleLabelOffset = transitionProgress * titleLabelOffsetMiddle + antiProgress * titleLabelOffsetTop let subtitleLabelOffsetTop: CGFloat = 64 let subtitleLabelOffsetMiddle: CGFloat = bounds.height/2 let subtitleLabelOffset = transitionProgress * subtitleLabelOffsetMiddle + antiProgress * subtitleLabelOffsetTop titleLabel.frame = CGRect(x: 0, y: titleLabelOffset, width: bounds.width, height: 44) subtitleLabel.preferredMaxLayoutWidth = bounds.width subtitleLabel.frame = CGRect(x: 0, y: subtitleLabelOffset, width: bounds.width, height: subtitleLabel.font.lineHeight) imageView.alpha = progress } func setup() { addSubview(imageView) addSubview(overlayView) addSubview(titleLabel) addSubview(subtitleLabel) clipsToBounds = true titleLabel.text = "Title of Business" //subtitleLabel.text = "Description of Business" imageView.image = UIImage(named: "sf") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = bounds overlayView.frame = bounds updateViews() } }
4b0acb2a424282c0e80e06d1ef31d09d
27.065421
126
0.612388
false
false
false
false
ibm-bluemix-mobile-services/bms-clientsdk-swift-security
refs/heads/master
Sample/BMSSecuritySample/BMSSecuritySample/ViewController.swift
apache-2.0
1
// // ViewController.swift // GoogleMCA // // Created by Ilan Klein on 15/02/2016. // Copyright © 2016 ibm. All rights reserved. // import UIKit import BMSCore import BMSSecurity class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var answerTextView: UILabel! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func logout(sender: AnyObject) { MCAAuthorizationManager.sharedInstance.logout(nil) } @IBAction func login(sender: AnyObject) { let callBack:BmsCompletionHandler = {(response: Response?, error: NSError?) in var ans:String = ""; if error == nil { ans="response:\(response?.responseText), no error" } else { ans="ERROR , error=\(error)" } dispatch_async(dispatch_get_main_queue(), { self.answerTextView.text = ans }) } let request = Request(url: AppDelegate.customResourceURL, method: HttpMethod.GET) request.sendWithCompletionHandler(callBack) } }
a881c59fb900d1da139f8494c9ddefda
27.869565
89
0.615211
false
false
false
false
sora0077/iTunesMusic
refs/heads/master
Demo/Views/HistoryViewController.swift
mit
1
// // HistoryViewController.swift // iTunesMusic // // Created by 林達也 on 2016/10/18. // Copyright © 2016年 jp.sora0077. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa import iTunesMusic private class TableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } final class HistoryViewController: UIViewController { fileprivate let tableView = UITableView() fileprivate let history = Model.History.shared override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") tableView.delegate = self tableView.dataSource = self tableView.snp.makeConstraints { make in make.edges.equalTo(0) } history.changes .subscribe(tableView.rx.itemUpdates()) .addDisposableTo(disposeBag) } } extension HistoryViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return history.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let (track, played) = history[indexPath.row] cell.textLabel?.text = track.name cell.detailTextLabel?.text = "\(played)" return cell } } extension HistoryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let (track, _) = history[indexPath.row] guard track.canPreview else { return } UIApplication.shared.open(appURL(path: "/track/\(track.id)")) } }
f41a7750a80cb9915f502b97c390f70a
27.857143
100
0.687129
false
false
false
false
roecrew/AudioKit
refs/heads/master
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Drum Synthesizers.xcplaygroundpage/Contents.swift
mit
1
//: ## Drum Synthesizers //: These can also be hooked up to MIDI or a sequencer. import XCPlayground import AudioKit //: Set up instruments: var kick = AKSynthKick() var snare = AKSynthSnare(duration: 0.07) var mix = AKMixer(kick, snare) var reverb = AKReverb(mix) AudioKit.output = reverb AudioKit.start() reverb.loadFactoryPreset(.MediumRoom) //: Generate a cheap electro beat var counter = 0 AKPlaygroundLoop(frequency: 4.44) { let onFirstBeat = counter == 0 let everyOtherBeat = counter % 4 == 2 let randomHit = (0...3).randomElement() == 0 if onFirstBeat || randomHit { kick.play(noteNumber:60, velocity: 100) kick.stop(noteNumber:60) } if everyOtherBeat { let velocity = (1...100).randomElement() snare.play(noteNumber:60, velocity: velocity) snare.stop(noteNumber:60) } counter += 1 } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
b550e93183f6d09169cb66305bb5a76b
23.552632
60
0.684887
false
false
false
false
PJayRushton/TeacherTools
refs/heads/master
Pods/Marshal/Sources/ValueType.swift
mit
2
// // M A R S H A L // // () // /\ // ()--' '--() // `. .' // / .. \ // ()' '() // // import Foundation // MARK: - ValueType public protocol ValueType { associatedtype Value = Self static func value(from object: Any) throws -> Value } extension ValueType { public static func value(from object: Any) throws -> Value { guard let objectValue = object as? Value else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return objectValue } } // MARK: - ValueType Implementations extension String: ValueType {} extension Int: ValueType {} extension UInt: ValueType {} extension Bool: ValueType {} extension Float: ValueType { public static func value(from object: Any) throws -> Float { guard let value = object as? NSNumber else { throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object)) } return value.floatValue } } extension Double: ValueType { public static func value(from object: Any) throws -> Double { guard let value = object as? NSNumber else { throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object)) } return value.doubleValue } } extension Int64: ValueType { public static func value(from object: Any) throws -> Int64 { guard let value = object as? NSNumber else { throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object)) } return value.int64Value } } extension Array where Element: ValueType { public static func value(from object: Any, discardingErrors: Bool = false) throws -> [Element] { guard let anyArray = object as? [Any] else { throw MarshalError.typeMismatch(expected: self, actual: type(of: object)) } if discardingErrors { return anyArray.compactMap { let value = try? Element.value(from: $0) guard let element = value as? Element else { return nil } return element } } else { return try anyArray.map { let value = try Element.value(from: $0) guard let element = value as? Element else { throw MarshalError.typeMismatch(expected: Element.self, actual: type(of: value)) } return element } } } public static func value(from object: Any) throws -> [Element?] { guard let anyArray = object as? [Any] else { throw MarshalError.typeMismatch(expected: self, actual: type(of: object)) } return anyArray.map { let value = try? Element.value(from: $0) guard let element = value as? Element else { return nil } return element } } } extension Dictionary where Value: ValueType { public static func value(from object: Any) throws -> Dictionary<Key, Value> { guard let objectValue = object as? [Key: Any] else { throw MarshalError.typeMismatch(expected: self, actual: type(of: object)) } var result: [Key: Value] = [:] for (k, v) in objectValue { guard let value = try Value.value(from: v) as? Value else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: any)) } result[k] = value } return result } } extension Set where Element: ValueType { public static func value(from object: Any) throws -> Set<Element> { let elementArray: [Element] = try [Element].value(from: object) return Set<Element>(elementArray) } } extension URL: ValueType { public static func value(from object: Any) throws -> URL { guard let urlString = object as? String else { throw MarshalError.typeMismatch(expected: String.self, actual: type(of: object)) } guard let objectValue = URL(string: urlString) else { throw MarshalError.typeMismatch(expected: "valid URL", actual: urlString) } return objectValue } } extension Int8: ValueType { public static func value(from object: Any) throws -> Int8 { guard let value = object as? Int else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return Int8(value) } } extension Int16: ValueType { public static func value(from object: Any) throws -> Int16 { guard let value = object as? Int else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return Int16(value) } } extension Int32: ValueType { public static func value(from object: Any) throws -> Int32 { guard let value = object as? Int else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return Int32(value) } } extension UInt8: ValueType { public static func value(from object: Any) throws -> UInt8 { guard let value = object as? UInt else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return UInt8(value) } } extension UInt16: ValueType { public static func value(from object: Any) throws -> UInt16 { guard let value = object as? UInt else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return UInt16(value) } } extension UInt32: ValueType { public static func value(from object: Any) throws -> UInt32 { guard let value = object as? UInt else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return UInt32(value) } } extension UInt64: ValueType { public static func value(from object: Any) throws -> UInt64 { guard let value = object as? NSNumber else { throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object)) } return value.uint64Value } } extension Character: ValueType { public static func value(from object: Any) throws -> Character { guard let value = object as? String else { throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object)) } return Character(value) } } #if swift(>=4.1) #else extension Collection { func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try flatMap(transform) } } #endif
c4a1a3a33b2b033934ff761b3b8a6441
30.136986
100
0.601261
false
false
false
false
mkihmouda/LoadMore
refs/heads/master
BulkRequest/ViewController.swift
mit
1
// // ViewController.swift // BulkRequestAPI // // Created by Mac on 3/2/17. // Copyright © 2017 Mac. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate { @IBOutlet var tableView: UITableView! var lastId = 0 var reachEnd = false var intArray = [Int]() override func viewDidLoad() { super.viewDidLoad() callMessageAPI() defineCollectionAndTableViewCells() self.tableView.dataSource = self self.tableView.delegate = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return intArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! MessageCell cell.textLabel?.text = "\(intArray[indexPath.row])" if indexPath.row == lastId - 3 { callMessageAPI() } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } func callMessageAPI(){ if !reachEnd { let messageAPI = callAPI() messageAPI.callMessageAPI(completed: { print(self.intArray.count) self.lastId = self.intArray.count self.tableView.reloadData() }, delegate : self) } } // MARK: register nib cell func defineCollectionAndTableViewCells(){ let userDetailsNIB = UINib(nibName: "MessageCell", bundle: nil) tableView.register(userDetailsNIB, forCellReuseIdentifier: "messageCell") } }
74816cca25028832a7834a99572304b6
22.1
111
0.551227
false
false
false
false
naveenrana1309/NRControls
refs/heads/master
NRControls/Classes/NRControls.swift
mit
1
// // NRControls.swift // // // Created by Naveen Rana on 21/08/16. // Developed by Naveen Rana. All rights reserved. // import Foundation import MessageUI fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } /// This completionhandler use for call back image picker controller delegates. public typealias ImagePickerControllerCompletionHandler = (_ controller: UIImagePickerController, _ info: [UIImagePickerController.InfoKey: Any]) -> Void /// This completionhandler use for call back mail controller delegates. public typealias MailComposerCompletionHandler = (_ result:MFMailComposeResult ,_ error: NSError?) -> Void /// This completionhandler use for call back alert(Alert) controller delegates. public typealias AlertControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int) -> Void /// This completionhandler use for call back alert(ActionSheet) controller delegates. public typealias AlertTextFieldControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int, _ text: String) -> Void /// This completionhandler use for call back of selected image using image picker controller delegates. public typealias CompletionImagePickerController = (_ selectedImage: UIImage?) -> Void /// This completionhandler use for call back of selected url using DocumentPicker controller delegates. public typealias DocumentPickerCompletionHandler = (_ selectedDocuments: [URL]?) -> Void /// This class is used for using a common controls like alert, action sheet and imagepicker controller with proper completion Handlers. open class NRControls: NSObject,UIImagePickerControllerDelegate,MFMailComposeViewControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate{ /// This completionhandler use for call back image picker controller delegates. var imagePickerControllerHandler: ImagePickerControllerCompletionHandler? /// This completionhandler use for call back mail controller delegates. var mailComposerCompletionHandler: MailComposerCompletionHandler? /// This completionhandler use for call back mail controller delegates. var documentPickerCompletionHandler: DocumentPickerCompletionHandler? ///Shared instance public static let sharedInstance = NRControls() /** This function is used for taking a picture from iphone camera or camera roll. - Parameters: - viewController: Source viewcontroller from which you want to present this popup. - completionHandler: This completion handler will give you image or nil. */ //MARK: UIImagePickerController open func takeOrChoosePhoto(_ viewController: UIViewController, completionHandler: @escaping CompletionImagePickerController) { let actionSheetController: UIAlertController = UIAlertController(title: "", message: "Choose photo", preferredStyle: .actionSheet) //Create and add the Cancel action let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in //Just dismiss the action sheet completionHandler(nil) } actionSheetController.addAction(cancelAction) //Create and add first option action //Create and add a second option action let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .default) { action -> Void in self.openImagePickerController(.camera, isVideo: false, inViewController: viewController) { (controller, info) -> Void in let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage completionHandler(image) } } actionSheetController.addAction(takePictureAction) //Create and add a second option action let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose from library", style: .default) { action -> Void in self.openImagePickerController(.photoLibrary, isVideo: false, inViewController: viewController) { (controller, info) -> Void in let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage completionHandler(image) } } actionSheetController.addAction(choosePictureAction) if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) { // In this case the device is an iPad. if let popoverController = actionSheetController.popoverPresentationController { popoverController.sourceView = viewController.view popoverController.sourceRect = viewController.view.bounds } } viewController.present(actionSheetController, animated: true, completion: nil) } /** This function is used open image picker controller. - Parameters: - sourceType: PhotoLibrary, Camera, SavedPhotosAlbum - inViewController: Source viewcontroller from which you want to present this imagecontroller. - isVideo: if you want to capture video then set it to yes, by default value is false. - completionHandler: Gives you the call back with Imagepickercontroller and information about image. */ open func openImagePickerController(_ sourceType: UIImagePickerController.SourceType, isVideo: Bool = false, inViewController:UIViewController, completionHandler: @escaping ImagePickerControllerCompletionHandler)-> Void { self.imagePickerControllerHandler = completionHandler let controller = UIImagePickerController() controller.allowsEditing = false controller.delegate = self; if UIImagePickerController.isSourceTypeAvailable(sourceType){ controller.sourceType = sourceType } else { print("this source type not supported in this device") } if (UI_USER_INTERFACE_IDIOM() == .pad) { //iPad support // In this case the device is an iPad. if let popoverController = controller.popoverPresentationController { popoverController.sourceView = inViewController.view popoverController.sourceRect = inViewController.view.bounds } } inViewController.present(controller, animated: true, completion: nil) } //MARK: UIImagePickerController Delegates public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { print("didFinishPickingMediaWithInfo") self.imagePickerControllerHandler!(picker, info) picker.dismiss(animated: true, completion: nil) } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } /** This function is used for open Mail Composer. - Parameters: - recipientsEmailIds: email ids of recipents for you want to send emails. - viewcontroller: Source viewcontroller from which you want to present this mail composer. - subject: Subject of mail. - message: body of mail. - attachment: optional this is nsdata of video/photo or any other document. - completionHandler: Gives you the call back with result and error if any. */ //MARK: MFMailComposeViewController open func openMailComposerInViewController(_ recipientsEmailIds:[String], viewcontroller: UIViewController, subject: String = "", message: String = "" ,attachment: Data? = nil,completionHandler: @escaping MailComposerCompletionHandler){ if !MFMailComposeViewController.canSendMail() { print("No mail configured. please configure your mail first") return() } self.mailComposerCompletionHandler = completionHandler let mailComposerViewController = MFMailComposeViewController() mailComposerViewController.mailComposeDelegate = self mailComposerViewController.setSubject(subject) mailComposerViewController.setMessageBody(message, isHTML: true) mailComposerViewController.setToRecipients(recipientsEmailIds) if let _ = attachment { if (attachment!.count>0) { mailComposerViewController.addAttachmentData(attachment!, mimeType: "image/jpeg", fileName: "attachment.jpeg") } } viewcontroller.present(mailComposerViewController, animated: true, completion:nil) } //MARK: MFMailComposeViewController Delegates open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion:nil) if self.mailComposerCompletionHandler != nil { self.mailComposerCompletionHandler!(result, error as NSError?) } } //MARK: AlertController /** This function is used for open Alert View. - Parameters: - viewcontroller: Source viewcontroller from which you want to present this mail composer. - title: title of the alert. - message: message of the alert . - buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"]. - completionHandler: Gives you the call back with alertController and index of selected button . */ open func openAlertViewFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for element in buttonsTitlesArray { let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in if let _ = completionHandler { completionHandler!(alertController, buttonsTitlesArray.index(of: element)!) } }) alertController.addAction(action) } viewController.present(alertController, animated: true, completion: nil) } /** This function is used for open Action Sheet. - Parameters: - viewcontroller: Source viewcontroller from which you want to present this mail composer. - title: title of the alert. - message: message of the alert . - buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"]. - completionHandler: Gives you the call back with alertController and index of selected button . */ open func openActionSheetFromViewController(_ viewController: UIViewController, title: String, message: String, buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) for element in buttonsTitlesArray { let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in if let _ = completionHandler { completionHandler!(alertController, buttonsTitlesArray.index(of: element)!) } }) alertController.addAction(action) } viewController.present(alertController, animated: true, completion: nil) } /** This function is used for openAlertView with textfield. - Parameters: - viewcontroller: source viewcontroller from which you want to present this mail composer. - title: title of the alert. - message: message of the alert. - placeHolder: placeholder of the textfield. - isSecure: true if you want texfield secure, by default is false. - isNumberKeyboard: true if keyboard is of type numberpad, . - buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"]. - completionHandler: Gives you the call back with alertController,index and text of textfield. */ open func openAlertViewWithTextFieldFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", placeHolder: String = "", isSecure: Bool = false, buttonsTitlesArray: [String], isNumberKeyboard: Bool = false, completionHandler: AlertTextFieldControllerCompletionHandler?){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for element in buttonsTitlesArray { let action: UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in if let _ = completionHandler { if let _ = alertController.textFields , alertController.textFields?.count > 0 , let text = alertController.textFields?.first?.text { completionHandler!(alertController, buttonsTitlesArray.index(of: element)!, text) } } }) alertController.addAction(action) } alertController.addTextField { (textField : UITextField!) -> Void in textField.isSecureTextEntry = isSecure textField.placeholder = placeHolder if isNumberKeyboard { textField.keyboardType = .numberPad } else { textField.keyboardType = .emailAddress } } viewController.present(alertController, animated: false, completion: nil) } }
c5721df66c1916cf91a4694c96434642
42.326284
312
0.66669
false
false
false
false
YifengBai/YuDou
refs/heads/master
YuDou/YuDou/Classes/Main/Controller/BaseAnchorViewController.swift
mit
1
// // BaseAnchorViewController.swift // YuDou // // Created by Bemagine on 2017/1/16. // Copyright © 2017年 bemagine. All rights reserved. // import UIKit let kItemMargin : CGFloat = 10 private let kHeaderViewH : CGFloat = 50 let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 let kNormalItemH = kNormalItemW * 3 / 4 let kPrettyItemH = kNormalItemW * 4 / 3 private let HeaderViewId = "collectionSectionHeaderId" let GameCellId = "GameCellId" let BeautyCellId = "BeautyCellId" class BaseAnchorViewController: BaseViewController { var baseVM : BaseViewModel! lazy var collectionView : UICollectionView = {[unowned self] in let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.backgroundColor = UIColor.white collectionView.delegate = self collectionView.dataSource = self collectionView.register(UINib(nibName: "GameCell", bundle: nil), forCellWithReuseIdentifier: GameCellId) collectionView.register(UINib(nibName: "BeautyCell", bundle: nil), forCellWithReuseIdentifier: BeautyCellId) collectionView.register(UINib(nibName: "SectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderViewId) return collectionView }() fileprivate var startOffY : CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() view.autoresizingMask = [.flexibleHeight, .flexibleWidth] setupUI() loadData() } } extension BaseAnchorViewController { override func setupUI() { contentView = collectionView view.addSubview(collectionView) super.setupUI() } func loadData() { } } extension BaseAnchorViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return baseVM.groupData.count; } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseVM.groupData[section].anchors.count; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 取出数据 let groupD = self.baseVM.groupData[indexPath.section] let item = groupD.anchors[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GameCellId, for: indexPath) as! GameCell cell.roomModel = item return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderViewId, for: indexPath) as! SectionHeaderView header.group = baseVM.groupData[indexPath.section] return header } } extension BaseAnchorViewController : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let nextOffY = scrollView.contentOffset.y var scrollDrection : ScrollDirection! if nextOffY > startOffY { scrollDrection = .ScrollDown } else { scrollDrection = .ScrollUp } // guard let parentVC = self.parent as? BaseViewController else { return } // parentVC.navigationBarTransform(direction: scrollDrection) NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationNavigationBarTransform), object: scrollDrection) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { startOffY = scrollView.contentOffset.y } }
9a6d96314f2d27a845096d8856b1f517
31.757353
187
0.683726
false
false
false
false
phatblat/3DTouchDemo
refs/heads/master
3DTouchDemo/TouchCanvas/TouchCanvas/ReticleView.swift
mit
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `ReticleView` allows visualization of the azimuth and altitude related properties of a `UITouch` via an indicator similar to the sighting devices such as a telescope. */ import UIKit class ReticleView: UIView { // MARK: Properties var actualAzimuthAngle: CGFloat = 0.0 { didSet { setNeedsLayout() } } var actualAzimuthUnitVector = CGVector(dx: 0, dy: 0) { didSet { setNeedsLayout() } } var actualAltitudeAngle: CGFloat = 0.0 { didSet { setNeedsLayout() } } var predictedAzimuthAngle: CGFloat = 0.0 { didSet { setNeedsLayout() } } var predictedAzimuthUnitVector = CGVector(dx: 0, dy: 0) { didSet { setNeedsLayout() } } var predictedAltitudeAngle: CGFloat = 0.0 { didSet { setNeedsLayout() } } let reticleLayer = CALayer() let radius: CGFloat = 80 var reticleImage: UIImage! let reticleColor = UIColor(hue: 0.516, saturation: 0.38, brightness: 0.85, alpha: 0.4) let dotRadius: CGFloat = 8 let lineWidth: CGFloat = 2 var predictedDotLayer = CALayer() var predictedLineLayer = CALayer() let predictedIndicatorColor = UIColor(hue: 0.53, saturation: 0.86, brightness: 0.91, alpha: 1.0) var dotLayer = CALayer() var lineLayer = CALayer() let indicatorColor = UIColor(hue: 0.0, saturation: 0.86, brightness: 0.91, alpha: 1.0) // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) reticleLayer.contentsGravity = kCAGravityCenter reticleLayer.position = layer.position layer.addSublayer(reticleLayer) configureDotLayer(layer: predictedDotLayer, withColor: predictedIndicatorColor) predictedDotLayer.hidden = true configureLineLayer(layer: predictedLineLayer, withColor: predictedIndicatorColor) predictedLineLayer.hidden = true configureDotLayer(layer: dotLayer, withColor: indicatorColor) configureLineLayer(layer: lineLayer, withColor: indicatorColor) reticleLayer.addSublayer(predictedDotLayer) reticleLayer.addSublayer(predictedLineLayer) reticleLayer.addSublayer(dotLayer) reticleLayer.addSublayer(lineLayer) renderReticleImage() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UIView Overrides override func intrinsicContentSize() -> CGSize { return reticleImage.size } override func layoutSubviews() { super.layoutSubviews() CATransaction.setDisableActions(true) reticleLayer.position = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) layoutIndicator() CATransaction.setDisableActions(false) } // MARK: Convenience func renderReticleImage() { let imageRadius = ceil(radius * 1.2) let imageSize = CGSize(width: imageRadius * 2, height: imageRadius * 2) UIGraphicsBeginImageContextWithOptions(imageSize, false, contentScaleFactor) let ctx = UIGraphicsGetCurrentContext() CGContextTranslateCTM(ctx, imageRadius, imageRadius) CGContextSetLineWidth(ctx, 2) CGContextSetStrokeColorWithColor(ctx, reticleColor.CGColor) CGContextStrokeEllipseInRect(ctx, CGRect(x: -radius, y: -radius, width: radius * 2, height: radius * 2)) // Draw targeting lines. let path = CGPathCreateMutable() var transform = CGAffineTransformIdentity for _ in 0..<4 { CGPathMoveToPoint(path, &transform, radius * 0.5, 0) CGPathAddLineToPoint(path, &transform, radius * 1.15, 0) transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2)) } CGContextAddPath(ctx, path) CGContextStrokePath(ctx) reticleImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() reticleLayer.contents = reticleImage.CGImage reticleLayer.bounds = CGRect(x: 0, y: 0, width: imageRadius * 2, height: imageRadius * 2) reticleLayer.contentsScale = contentScaleFactor } func layoutIndicator() { // Predicted. layoutIndicatorForAzimuthAngle(predictedAzimuthAngle, azimuthUnitVector: predictedAzimuthUnitVector, altitudeAngle: predictedAltitudeAngle, lineLayer: predictedLineLayer, dotLayer: predictedDotLayer) // Actual. layoutIndicatorForAzimuthAngle(actualAzimuthAngle, azimuthUnitVector: actualAzimuthUnitVector, altitudeAngle: actualAltitudeAngle, lineLayer: lineLayer, dotLayer: dotLayer) } func layoutIndicatorForAzimuthAngle(azimuthAngle: CGFloat, azimuthUnitVector: CGVector, altitudeAngle: CGFloat, lineLayer targetLineLayer: CALayer, dotLayer targetDotLayer: CALayer) { let reticleBounds = reticleLayer.bounds let centeringTransform = CGAffineTransformMakeTranslation(reticleBounds.width / 2, reticleBounds.height / 2) var rotationTransform = CGAffineTransformMakeRotation(azimuthAngle) // Draw the indicator opposite the azimuth by rotating pi radians, for easy visualization. rotationTransform = CGAffineTransformRotate(rotationTransform, CGFloat(M_PI)) /* Make the length of the indicator's line representative of the `altitudeAngle`. When the angle is zero radians (parallel to the screen surface) the line will be at its longest. At `M_PI`/2 radians, only the dot on top of the indicator will be visible directly beneath the touch location. */ let altitudeRadius = (1.0 - altitudeAngle / CGFloat(M_PI_2)) * radius var lineTransform = CGAffineTransformMakeScale(altitudeRadius, 1) lineTransform = CGAffineTransformConcat(lineTransform, rotationTransform) lineTransform = CGAffineTransformConcat(lineTransform, centeringTransform) targetLineLayer.setAffineTransform(lineTransform) var dotTransform = CGAffineTransformMakeTranslation(-azimuthUnitVector.dx * altitudeRadius, -azimuthUnitVector.dy * altitudeRadius) dotTransform = CGAffineTransformConcat(dotTransform, centeringTransform) targetDotLayer.setAffineTransform(dotTransform) } func configureDotLayer(layer targetLayer: CALayer, withColor color: UIColor) { targetLayer.backgroundColor = color.CGColor targetLayer.bounds = CGRect(x: 0, y: 0, width: dotRadius * 2, height: dotRadius * 2) targetLayer.cornerRadius = dotRadius targetLayer.position = CGPoint.zero } func configureLineLayer(layer targetLayer: CALayer, withColor color: UIColor) { targetLayer.backgroundColor = color.CGColor targetLayer.bounds = CGRect(x: 0, y: 0, width: 1, height: lineWidth) targetLayer.anchorPoint = CGPoint(x: 0, y: 0.5) targetLayer.position = CGPoint.zero } }
dc9fc93f25d6f9c930ce11ba40023873
38.12766
207
0.66789
false
false
false
false
Ivacker/swift
refs/heads/master
stdlib/public/core/CTypes.swift
apache-2.0
10
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // C Primitive Types //===----------------------------------------------------------------------===// /// The C 'char' type. /// /// This will be the same as either `CSignedChar` (in the common /// case) or `CUnsignedChar`, depending on the platform. public typealias CChar = Int8 /// The C 'unsigned char' type. public typealias CUnsignedChar = UInt8 /// The C 'unsigned short' type. public typealias CUnsignedShort = UInt16 /// The C 'unsigned int' type. public typealias CUnsignedInt = UInt32 /// The C 'unsigned long' type. public typealias CUnsignedLong = UInt /// The C 'unsigned long long' type. public typealias CUnsignedLongLong = UInt64 /// The C 'signed char' type. public typealias CSignedChar = Int8 /// The C 'short' type. public typealias CShort = Int16 /// The C 'int' type. public typealias CInt = Int32 /// The C 'long' type. public typealias CLong = Int /// The C 'long long' type. public typealias CLongLong = Int64 /// The C 'float' type. public typealias CFloat = Float /// The C 'double' type. public typealias CDouble = Double // FIXME: long double // FIXME: Is it actually UTF-32 on Darwin? // /// The C++ 'wchar_t' type. public typealias CWideChar = UnicodeScalar // FIXME: Swift should probably have a UTF-16 type other than UInt16. // /// The C++11 'char16_t' type, which has UTF-16 encoding. public typealias CChar16 = UInt16 /// The C++11 'char32_t' type, which has UTF-32 encoding. public typealias CChar32 = UnicodeScalar /// The C '_Bool' and C++ 'bool' type. public typealias CBool = Bool /// A wrapper around an opaque C pointer. /// /// Opaque pointers are used to represent C pointers to types that /// cannot be represented in Swift, such as incomplete struct types. public struct COpaquePointer : Equatable, Hashable, NilLiteralConvertible { var _rawValue: Builtin.RawPointer /// Construct a `nil` instance. @_transparent public init() { _rawValue = _nilRawPointer } @_transparent init(_ v: Builtin.RawPointer) { _rawValue = v } /// Construct a `COpaquePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. @_transparent public init(bitPattern: Int) { _rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Construct a `COpaquePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. @_transparent public init(bitPattern: UInt) { _rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Convert a typed `UnsafePointer` to an opaque C pointer. @_transparent public init<T>(_ source: UnsafePointer<T>) { self._rawValue = source._rawValue } /// Convert a typed `UnsafeMutablePointer` to an opaque C pointer. @_transparent public init<T>(_ source: UnsafeMutablePointer<T>) { self._rawValue = source._rawValue } /// Determine whether the given pointer is null. @_transparent var _isNull : Bool { return self == nil } /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: The hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { return Int(Builtin.ptrtoint_Word(_rawValue)) } /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { _rawValue = _nilRawPointer } } extension COpaquePointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return _rawPointerToString(_rawValue) } } @warn_unused_result public func ==(lhs: COpaquePointer, rhs: COpaquePointer) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } /// The family of C function pointer types. /// /// This type has been removed. Instead of `CFunctionType<(T) -> U>`, a native /// function type with the C convention can be used, `@convention(c) (T) -> U`. @available(*, unavailable, message="use a function type '@convention(c) (T) -> U'") public struct CFunctionPointer<T> {} /// The corresponding Swift type to `va_list` in imported C APIs. public struct CVaListPointer { var value: UnsafeMutablePointer<Void> public // @testable init(_fromUnsafeMutablePointer from: UnsafeMutablePointer<Void>) { value = from } } extension CVaListPointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return value.debugDescription } } func _memcpy( dest destination: UnsafeMutablePointer<Void>, src: UnsafeMutablePointer<Void>, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memcpy_RawPointer_RawPointer_Int64( dest, src, size, /*alignment:*/ Int32()._value, /*volatile:*/ false._value) }
36455c449caddd65c8a17eb230d204b8
27.455959
83
0.669519
false
false
false
false
KaushalElsewhere/AllHandsOn
refs/heads/master
CleanSwiftTry/CleanSwiftTry/Scenes/CreateOrder/CreateOrderViewController.swift
mit
1
// // CreateOrderViewController.swift // CleanSwiftTry // // Created by Kaushal Elsewhere on 10/05/2017. // Copyright (c) 2017 Elsewhere. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol CreateOrderViewControllerInput { func displayPrice(_ viewModel: CreateOrder_Price_ViewModel) func displaySomething(_ viewModel: CreateOrder.Something.ViewModel) } protocol CreateOrderViewControllerOutput { var shippingMethods: [String] { get } func calculatePrice(_ request: CreateOrder_Price_Request) func doSomething(_ request: CreateOrder.Something.Request) func getPaymentOptions() } class CreateOrderViewController: UITableViewController, CreateOrderViewControllerInput { var output: CreateOrderViewControllerOutput! var router: CreateOrderRouter! @IBOutlet weak var shippingTextField: UITextField! @IBOutlet var pickerView: UIPickerView! override func awakeFromNib() { CreateOrderConfigurator.sharedInstance.configure(self) } override func viewDidLoad() { super.viewDidLoad() doSomethingOnLoad() } func configurePicker() { shippingTextField.inputView = self.pickerView shippingTextField.becomeFirstResponder() } func doSomethingOnLoad() { configurePicker() setDefaultValue() // NOTE: Ask the Interactor to do some work //let request = CreateOrder.Something.Request() //output.doSomething(request) } func setDefaultValue() { pickerView.selectRow(0, inComponent: 0, animated: false) let request = CreateOrder_Price_Request(selectedIndex: 0) output.calculatePrice(request) } // MARK: - Display logic func displaySomething(_ viewModel: CreateOrder.Something.ViewModel) { // NOTE: Display the result from the Presenter // nameTextField.text = viewModel.name } func displayPrice(_ viewModel: CreateOrder_Price_ViewModel) { shippingTextField.text = viewModel.price } } extension CreateOrderViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return output.shippingMethods.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return output.shippingMethods[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let request = CreateOrder_Price_Request(selectedIndex: row) output.calculatePrice(request) } }
16cd68c12b368f03e5a535b87083b612
29.53125
111
0.696349
false
false
false
false
WickedColdfront/Slide-iOS
refs/heads/master
Pods/reddift/reddift/Model/MediaEmbed.swift
apache-2.0
1
// // MediaEmbed.swift // reddift // // Created by sonson on 2015/04/21. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Media represents the content which is embeded a link. */ public struct MediaEmbed { /// Height of content. let height: Int /// Width of content. let width: Int /// Information of content. let content: String /// Is content scrolled? let scrolling: Bool /** Update each property with JSON object. - parameter json: JSON object which is included "t2" JSON. */ public init (json: JSONDictionary) { height = json["height"] as? Int ?? 0 width = json["width"] as? Int ?? 0 let tempContent = json["content"] as? String ?? "" content = tempContent.gtm_stringByUnescapingFromHTML() scrolling = json["scrolling"] as? Bool ?? false } var string: String { get { return "{content=\(content)\nsize=\(width)x\(height)}\n" } } }
14183525d841f47bb0a16ba2e9e9bbe8
22.333333
68
0.615306
false
false
false
false
cdtschange/SwiftMKit
refs/heads/master
SwiftMKitDemo/SwiftMKitDemo/UI/Data/NetworkRequest/MKNetworkRequestTableViewCell.swift
mit
1
// // MKDataNetworkRequestTableViewCell.swift // SwiftMKitDemo // // Created by Mao on 4/18/16. // Copyright © 2016 cdts. All rights reserved. // import UIKit import Kingfisher class MKNetworkRequestTableViewCell: UITableViewCell { @IBOutlet weak var imgPic: UIImageView! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblContent: UILabel! @IBOutlet weak var lblTime: UILabel! @IBOutlet weak var lblComments: UILabel! @IBOutlet weak var constraintImageHeight: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() imgPic.image = nil } var newsModel: NewsModel? { didSet { guard let newsModel = newsModel else { return } self.lblTitle?.text = newsModel.title self.lblContent?.text = newsModel.digest + "..." if let imageUrl = newsModel.imgsrc { self.imgPic.kf.setImage(with: URL(string: imageUrl)!, placeholder: UIImage(named: "default_image")) } else { self.imgPic.image = nil self.constraintImageHeight.constant = 0 self.setNeedsLayout() } self.lblTime.text = newsModel.displayTime self.lblComments.text = "\(newsModel.displayCommentCount)跟帖" } } }
08fa75f7a9e1f1c99ae4571e3afc0a3e
29.528302
115
0.630408
false
false
false
false
rafaell-lycan/GithubPulse
refs/heads/master
widget/GithubPulse/Controllers/ContentViewController.swift
mit
2
// // ContentViewController.swift // GithubPulse // // Created by Tadeu Zagallo on 12/28/14. // Copyright (c) 2014 Tadeu Zagallo. All rights reserved. // import Cocoa import WebKit class ContentViewController: NSViewController, NSXMLParserDelegate, WebPolicyDelegate { @IBOutlet weak var webView:WebView? @IBOutlet weak var lastUpdate:NSTextField? var regex = try? NSRegularExpression(pattern: "^osx:(\\w+)\\((.*)\\)$", options: NSRegularExpressionOptions.CaseInsensitive) var calls: [String: [String] -> Void] func loadCalls() { self.calls = [:] self.calls["contributions"] = { (args) in Contributions.fetch(args[0]) { (success, commits, streak, today) in if success { if args.count < 2 || args[1] == "true" { NSNotificationCenter.defaultCenter().postNotificationName("check_icon", object: nil, userInfo: ["today": today]) } } let _ = self.webView?.stringByEvaluatingJavaScriptFromString("contributions(\"\(args[0])\", \(success), \(today),\(streak),\(commits))") } } self.calls["set"] = { (args) in let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(args[1], forKey: args[0]) userDefaults.synchronize() if args[0] == "username" { NSNotificationCenter.defaultCenter().postNotificationName("check_username", object: self, userInfo: nil) } } self.calls["get"] = { (args) in var value = NSUserDefaults.standardUserDefaults().valueForKey(args[0]) as? String if value == nil { value = "" } let key = args[0].stringByReplacingOccurrencesOfString("'", withString: "\\'", options: [], range: nil) let v = value!.stringByReplacingOccurrencesOfString("'", withString: "\\'", options: [], range: nil) self.webView?.stringByEvaluatingJavaScriptFromString("get('\(key)', '\(v)', \(args[1]))"); } self.calls["remove"] = { (args) in let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.removeObjectForKey(args[0]) userDefaults.synchronize() if args[0] == "username" { NSNotificationCenter.defaultCenter().postNotificationName("check_username", object: self, userInfo: nil) } } self.calls["check_login"] = { (args) in let active = NSBundle.mainBundle().isLoginItem() self.webView?.stringByEvaluatingJavaScriptFromString("raw('check_login', \(active))") } self.calls["toggle_login"] = { (args) in if NSBundle.mainBundle().isLoginItem() { NSBundle.mainBundle().removeFromLoginItems() } else { NSBundle.mainBundle().addToLoginItems() } } self.calls["quit"] = { (args) in NSApplication.sharedApplication().terminate(self) } self.calls["update"] = { (args) in GithubUpdate.check(true) } self.calls["open_url"] = { (args) in if let checkURL = NSURL(string: args[0]) { NSWorkspace.sharedWorkspace().openURL(checkURL) } } } required init?(coder: NSCoder) { self.calls = [:] super.init(coder: coder) self.loadCalls() } override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.calls = [:] super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.loadCalls() } override func viewDidLoad() { #if DEBUG let url = NSURL(string: "http://0.0.0.0:8080")! #else let indexPath = NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "front") let url = NSURL(fileURLWithPath: indexPath!) #endif let request = NSURLRequest(URL: url) self.webView?.policyDelegate = self self.webView?.drawsBackground = false self.webView?.wantsLayer = true self.webView?.layer?.cornerRadius = 5 self.webView?.layer?.masksToBounds = true self.webView?.mainFrame.loadRequest(request) super.viewDidLoad() } @IBAction func refresh(sender: AnyObject?) { self.webView?.reload(sender) } func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { let url:String = request.URL!.absoluteString.stringByRemovingPercentEncoding! if url.hasPrefix("osx:") { let matches = self.regex?.matchesInString(url, options: [], range: NSMakeRange(0, url.characters.count)) if let match = matches?[0] { let fn = (url as NSString).substringWithRange(match.rangeAtIndex(1)) let args = (url as NSString).substringWithRange(match.rangeAtIndex(2)).componentsSeparatedByString("%%") #if DEBUG print(fn, args) #endif let closure = self.calls[fn] closure?(args) } } else if (url.hasPrefix("log:")) { #if DEBUG print(url) #endif } else { listener.use() } } }
30fe2d676d5adb7cccbff6d55fe064c0
31.551948
208
0.635674
false
false
false
false
doronkatz/firefox-ios
refs/heads/master
Client/Frontend/Home/HomePanelViewController.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SnapKit import UIKit import Storage // For VisitType. private struct HomePanelViewControllerUX { // Height of the top panel switcher button toolbar. static let ButtonContainerHeight: CGFloat = 40 static let ButtonContainerBorderColor = UIColor.black.withAlphaComponent(0.1) static let BackgroundColorNormalMode = UIConstants.PanelBackgroundColor static let BackgroundColorPrivateMode = UIConstants.PrivateModeAssistantToolbarBackgroundColor static let ToolbarButtonDeselectedColorNormalMode = UIColor(white: 0.2, alpha: 0.5) static let ToolbarButtonDeselectedColorPrivateMode = UIColor(white: 0.9, alpha: 1) } protocol HomePanelViewControllerDelegate: class { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) func homePanelViewController(_ HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int) func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) } protocol HomePanel: class { weak var homePanelDelegate: HomePanelDelegate? { get set } } struct HomePanelUX { static let EmptyTabContentOffset = -180 } protocol HomePanelDelegate: class { func homePanelDidRequestToSignIn(_ homePanel: HomePanel) func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) } struct HomePanelState { var isPrivate: Bool = false var selectedIndex: Int = 0 } enum HomePanelType: Int { case topSites = 0 case bookmarks = 1 case history = 2 case readingList = 3 var localhostURL: URL { return URL(string:"#panel=\(self.rawValue)", relativeTo: UIConstants.AboutHomePage as URL)! } } class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate { var profile: Profile! var notificationToken: NSObjectProtocol! var panels: [HomePanelDescriptor]! var url: URL? weak var delegate: HomePanelViewControllerDelegate? weak var appStateDelegate: AppStateDelegate? fileprivate var buttonContainerView: UIView! fileprivate var buttonContainerBottomBorderView: UIView! fileprivate var controllerContainerView: UIView! fileprivate var buttons: [UIButton] = [] var isPrivateMode: Bool = false { didSet { if oldValue != isPrivateMode { self.buttonContainerView.backgroundColor = isPrivateMode ? HomePanelViewControllerUX.BackgroundColorPrivateMode : HomePanelViewControllerUX.BackgroundColorNormalMode self.updateButtonTints() self.updateAppState() } } } var homePanelState: HomePanelState { return HomePanelState(isPrivate: isPrivateMode, selectedIndex: selectedPanel?.rawValue ?? 0) } override func viewDidLoad() { view.backgroundColor = HomePanelViewControllerUX.BackgroundColorNormalMode let blur: UIVisualEffectView? = DeviceInfo.isBlurSupported() ? UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light)) : nil if let blur = blur { view.addSubview(blur) } buttonContainerView = UIView() buttonContainerView.backgroundColor = HomePanelViewControllerUX.BackgroundColorNormalMode buttonContainerView.clipsToBounds = true buttonContainerView.accessibilityNavigationStyle = .combined buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarsk, history, remote tabs, reading list).") view.addSubview(buttonContainerView) self.buttonContainerBottomBorderView = UIView() buttonContainerView.addSubview(buttonContainerBottomBorderView) buttonContainerBottomBorderView.backgroundColor = HomePanelViewControllerUX.ButtonContainerBorderColor controllerContainerView = UIView() view.addSubview(controllerContainerView) blur?.snp.makeConstraints { make in make.edges.equalTo(self.view) } buttonContainerView.snp.makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight) } buttonContainerBottomBorderView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom).offset(-1) make.left.right.bottom.equalTo(self.buttonContainerView) } controllerContainerView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } self.panels = HomePanels().enabledPanels updateButtons() // Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomePanelViewController.SELhandleDismissKeyboardGestureRecognizer(_:))) dismissKeyboardGestureRecognizer.cancelsTouchesInView = false buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer) // Invalidate our activity stream data sources whenever we open up the home panels self.profile.panelDataObservers.activityStream.invalidate(highlights: false) } fileprivate func updateAppState() { let state = mainStore.updateState(.homePanels(homePanelState: homePanelState)) self.appStateDelegate?.appDidUpdateState(state) } func SELhandleDismissKeyboardGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) { view.window?.rootViewController?.view.endEditing(true) } var selectedPanel: HomePanelType? = nil { didSet { if oldValue == selectedPanel { // Prevent flicker, allocations, and disk access: avoid duplicate view controllers. return } if let index = oldValue?.rawValue { if index < buttons.count { let currentButton = buttons[index] currentButton.isSelected = false currentButton.isUserInteractionEnabled = true } } hideCurrentPanel() if let index = selectedPanel?.rawValue { if index < buttons.count { let newButton = buttons[index] newButton.isSelected = true newButton.isUserInteractionEnabled = false } if index < panels.count { let panel = self.panels[index].makeViewController(profile) let accessibilityLabel = self.panels[index].accessibilityLabel if let panelController = panel as? UINavigationController, let rootPanel = panelController.viewControllers.first { setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel) self.showPanel(panelController) } else { setupHomePanel(panel, accessibilityLabel: accessibilityLabel) self.showPanel(panel) } } } self.updateButtonTints() self.updateAppState() } } func setupHomePanel(_ panel: UIViewController, accessibilityLabel: String) { (panel as? HomePanel)?.homePanelDelegate = self panel.view.accessibilityNavigationStyle = .combined panel.view.accessibilityLabel = accessibilityLabel } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } fileprivate func hideCurrentPanel() { if let panel = childViewControllers.first { panel.willMove(toParentViewController: nil) panel.beginAppearanceTransition(false, animated: false) panel.view.removeFromSuperview() panel.endAppearanceTransition() panel.removeFromParentViewController() } } fileprivate func showPanel(_ panel: UIViewController) { addChildViewController(panel) panel.beginAppearanceTransition(true, animated: false) controllerContainerView.addSubview(panel.view) panel.endAppearanceTransition() panel.view.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } panel.didMove(toParentViewController: self) } func SELtappedButton(_ sender: UIButton!) { for (index, button) in buttons.enumerated() where button == sender { selectedPanel = HomePanelType(rawValue: index) delegate?.homePanelViewController(self, didSelectPanel: index) break } } fileprivate func updateButtons() { // Remove any existing buttons if we're rebuilding the toolbar. for button in buttons { button.removeFromSuperview() } buttons.removeAll() var prev: UIView? = nil for panel in panels { let button = UIButton() buttonContainerView.addSubview(button) button.addTarget(self, action: #selector(HomePanelViewController.SELtappedButton(_:)), for: UIControlEvents.touchUpInside) if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)") { button.setImage(image, for: UIControlState.normal) } if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)Selected") { button.setImage(image, for: UIControlState.selected) } button.accessibilityLabel = panel.accessibilityLabel button.accessibilityIdentifier = panel.accessibilityIdentifier buttons.append(button) button.snp.remakeConstraints { make in let left = prev?.snp.right ?? self.view.snp.left make.left.equalTo(left) make.height.centerY.equalTo(self.buttonContainerView) make.width.equalTo(self.buttonContainerView).dividedBy(self.panels.count) } prev = button } } func updateButtonTints() { for (index, button) in self.buttons.enumerated() { if index == self.selectedPanel?.rawValue { button.tintColor = isPrivateMode ? UIConstants.PrivateModePurple : UIConstants.HighlightBlue } else { button.tintColor = isPrivateMode ? HomePanelViewControllerUX.ToolbarButtonDeselectedColorPrivateMode : HomePanelViewControllerUX.ToolbarButtonDeselectedColorNormalMode } } } func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) { // If we can't get a real URL out of what should be a URL, we let the user's // default search engine give it a shot. // Typically we'll be in this state if the user has tapped a bookmarked search template // (e.g., "http://foo.com/bar/?query=%s"), and this will get them the same behavior as if // they'd copied and pasted into the URL bar. // See BrowserViewController.urlBar:didSubmitText:. guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else { Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.") return } return self.homePanel(homePanel, didSelectURL: url, visitType: visitType) } func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) { delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType) dismiss(animated: true, completion: nil) } func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToCreateAccount(self) } func homePanelDidRequestToSignIn(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToSignIn(self) } func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { delegate?.homePanelViewControllerDidRequestToOpenInNewTab(url, isPrivate: isPrivate) } } protocol HomePanelContextMenu { func getSiteDetails(for indexPath: IndexPath) -> Site? func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [ActionOverlayTableViewAction]? func presentContextMenu(for indexPath: IndexPath) func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> ActionOverlayTableViewController?) } extension HomePanelContextMenu { func presentContextMenu(for indexPath: IndexPath) { guard let site = getSiteDetails(for: indexPath) else { return } presentContextMenu(for: site, with: indexPath, completionHandler: { return self.contextMenu(for: site, with: indexPath) }) } func contextMenu(for site: Site, with indexPath: IndexPath) -> ActionOverlayTableViewController? { guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil } let contextMenu = ActionOverlayTableViewController(site: site, actions: actions) contextMenu.modalPresentationStyle = .overFullScreen contextMenu.modalTransitionStyle = .crossDissolve return contextMenu } func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [ActionOverlayTableViewAction]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewTabContextMenuTitle, iconString: "") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } return [openInNewTabAction, openInNewPrivateTabAction] } }
ecdd0b43ec1713ce5c50718bf1d7e8e2
42.295129
243
0.691926
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Frontend/Browser/AboutHomeHandler.swift
mpl-2.0
2
/* 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/. */ /** * Handles the page request to about/home/ so that the page loads and does not throw an error (404) on initialization */ import GCDWebServers struct AboutHomeHandler { static func register(_ webServer: WebServer) { webServer.registerHandlerForMethod("GET", module: "about", resource: "home") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in return GCDWebServerResponse(statusCode: 200) } } } struct AboutLicenseHandler { static func register(_ webServer: WebServer) { webServer.registerHandlerForMethod("GET", module: "about", resource: "license") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in let path = Bundle.main.path(forResource: "Licenses", ofType: "html") do { let html = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) as String return GCDWebServerDataResponse(html: html) } catch { debugPrint("Unable to register webserver \(error)") } return GCDWebServerResponse(statusCode: 200) } } } struct AboutEulaHandler { static func register(_ webServer: WebServer) { webServer.registerHandlerForMethod("GET", module: "about", resource: "eula") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in let path = Bundle.main.path(forResource: "Eula", ofType: "html") do { let html = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) as String return GCDWebServerDataResponse(html: html) } catch { debugPrint("Unable to register webserver \(error)") } return GCDWebServerResponse(statusCode: 200) } } } extension GCDWebServerDataResponse { convenience init(XHTML: String) { let data = XHTML.data(using: String.Encoding.utf8, allowLossyConversion: false) self.init(data: data, contentType: "application/xhtml+xml; charset=utf-8") } }
8665be7953a86fcd14b674c89af08673
41.509434
149
0.654683
false
false
false
false
Chuck8080/ios-swift-sugar-record
refs/heads/master
library/CoreData/Base/SugarRecordCDContext.swift
mit
1
// // SugarRecordCDContext.swift // SugarRecord // // Created by Pedro Piñera Buendía on 11/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation import CoreData public class SugarRecordCDContext: SugarRecordContext { /// NSManagedObjectContext context let contextCD: NSManagedObjectContext /** SugarRecordCDContext initializer passing the CoreData context :param: context NSManagedObjectContext linked to this SugarRecord context :returns: Initialized SugarRecordCDContext */ init (context: NSManagedObjectContext) { self.contextCD = context } /** Notifies the context that you're going to start an edition/removal/saving operation */ public func beginWriting() { // CD begin writing does nothing } /** Notifies the context that you've finished an edition/removal/saving operation */ public func endWriting() { var error: NSError? self.contextCD.save(&error) if error != nil { let exception: NSException = NSException(name: "Database operations", reason: "Couldn't perform your changes in the context", userInfo: ["error": error!]) SugarRecord.handle(exception) } } /** * Asks the context for writing cancellation */ public func cancelWriting() { self.contextCD.rollback() } /** Creates and object in the context (without saving) :param: objectClass Class of the created object :returns: The created object in the context */ public func createObject(objectClass: AnyClass) -> AnyObject? { let managedObjectClass: NSManagedObject.Type = objectClass as NSManagedObject.Type var object: AnyObject = NSEntityDescription.insertNewObjectForEntityForName(managedObjectClass.modelName(), inManagedObjectContext: self.contextCD) return object } /** Insert an object in the context :param: object NSManagedObject to be inserted in the context */ public func insertObject(object: AnyObject) { moveObject(object as NSManagedObject, inContext: self.contextCD) } /** Find NSManagedObject objects in the database using the passed finder :param: finder SugarRecordFinder usded for querying (filtering/sorting) :returns: Objects fetched */ public func find<T>(finder: SugarRecordFinder<T>) -> SugarRecordResults<T> { let fetchRequest: NSFetchRequest = SugarRecordCDContext.fetchRequest(fromFinder: finder) var error: NSError? var objects: [AnyObject]? = self.contextCD.executeFetchRequest(fetchRequest, error: &error) SugarRecordLogger.logLevelInfo.log("Found \((objects == nil) ? 0 : objects!.count) objects in database") if objects == nil { return SugarRecordResults(coredataResults: [NSManagedObject](), finder: finder) } else { return SugarRecordResults(coredataResults: objects as [NSManagedObject], finder: finder) } } /** Returns the NSFetchRequest from a given Finder :param: finder SugarRecord finder with the information about the filtering and sorting :returns: Created NSFetchRequest */ public class func fetchRequest<T>(fromFinder finder: SugarRecordFinder<T>) -> NSFetchRequest { let objectClass: NSObject.Type = finder.objectClass! let managedObjectClass: NSManagedObject.Type = objectClass as NSManagedObject.Type let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName()) fetchRequest.predicate = finder.predicate var sortDescriptors: [NSSortDescriptor] = finder.sortDescriptors switch finder.elements { case .first: fetchRequest.fetchLimit = 1 case .last: if !sortDescriptors.isEmpty{ sortDescriptors[0] = NSSortDescriptor(key: sortDescriptors.first!.key!, ascending: !(sortDescriptors.first!.ascending)) } fetchRequest.fetchLimit = 1 case .firsts(let number): fetchRequest.fetchLimit = number case .lasts(let number): if !sortDescriptors.isEmpty{ sortDescriptors[0] = NSSortDescriptor(key: sortDescriptors.first!.key!, ascending: !(sortDescriptors.first!.ascending)) } fetchRequest.fetchLimit = number case .all: break } fetchRequest.sortDescriptors = sortDescriptors return fetchRequest } /** Deletes a given object :param: object NSManagedObject to be deleted :returns: If the object has been properly deleted */ public func deleteObject<T>(object: T) -> SugarRecordContext { let managedObject: NSManagedObject? = object as? NSManagedObject let objectInContext: NSManagedObject? = moveObject(managedObject!, inContext: contextCD) if objectInContext == nil { let exception: NSException = NSException(name: "Database operations", reason: "Imposible to remove object \(object)", userInfo: nil) SugarRecord.handle(exception) } SugarRecordLogger.logLevelInfo.log("Object removed from database") self.contextCD.deleteObject(managedObject!) return self } /** Deletes NSManagedObject objecs from an array :param: objects NSManagedObject objects to be dleeted :returns: If the deletion has been successful */ public func deleteObjects<T>(objects: SugarRecordResults<T>) -> () { var objectsDeleted: Int = 0 for (var index = 0; index < Int(objects.count) ; index++) { let object: T! = objects[index] if (object != nil) { let _ = deleteObject(object) } } SugarRecordLogger.logLevelInfo.log("Deleted \(objects.count) objects") } /** * Count the number of entities of the given type */ public func count(objectClass: AnyClass, predicate: NSPredicate? = nil) -> Int { let managedObjectClass: NSManagedObject.Type = objectClass as NSManagedObject.Type let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName()) fetchRequest.predicate = predicate var error: NSError? var count = self.contextCD.countForFetchRequest(fetchRequest, error: &error) SugarRecordLogger.logLevelInfo.log("Found \(count) objects in database") return count } //MARK: - HELPER METHODS /** Moves an NSManagedObject from one context to another :param: object NSManagedObject to be moved :param: context NSManagedObjectContext where the object is going to be moved to :returns: NSManagedObject in the new context */ func moveObject(object: NSManagedObject, inContext context: NSManagedObjectContext) -> NSManagedObject? { var error: NSError? let objectInContext: NSManagedObject? = context.existingObjectWithID(object.objectID, error: &error)? if error != nil { let exception: NSException = NSException(name: "Database operations", reason: "Couldn't move the object into the new context", userInfo: nil) SugarRecord.handle(exception) return nil } else { return objectInContext } } }
4d9703c1568d256101239e689a41bde1
33.87037
166
0.655291
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKit/model/CoreData/StopLocation.swift
apache-2.0
1
// // StopLocation.swift // TripKit // // Created by Adrian Schoenig on 30/6/17. // Copyright © 2017 SkedGo. All rights reserved. // import Foundation import MapKit extension StopLocation { @objc public var timeZone: TimeZone? { location?.timeZone ?? region?.timeZone } @objc public var region: TKRegion? { if let code = regionName { return TKRegionManager.shared.localRegion(code: code) } else { let region = location?.regions.first regionName = region?.code return region } } @objc public var modeTitle: String { return stopModeInfo?.alt ?? "" } } // MARK: - MKAnnotation extension StopLocation: MKAnnotation { public var title: String? { return name } public var subtitle: String? { return location?.subtitle } public var coordinate: CLLocationCoordinate2D { return location?.coordinate ?? kCLLocationCoordinate2DInvalid } } // MARK: - UIActivityItemSource #if os(iOS) extension StopLocation: UIActivityItemSource { public func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { // Note: We used to return 'nil' if we don't have `lastStopVisit`, but the protocol doesn't allow that return "" } public func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? { guard let last = lastStopVisit else { return nil } var output: String = self.title ?? "" if let filter = filter, !filter.isEmpty { output.append(" (filter: \(filter)") } let predicate = departuresPredicate(from: last.departure) let visits = managedObjectContext?.fetchObjects(StopVisits.self, sortDescriptors: [NSSortDescriptor(key: "departure", ascending: true)], predicate: predicate, relationshipKeyPathsForPrefetching: nil, fetchLimit: 10) ?? [] output.append("\n") output.append(visits.localizedShareString) return output } } extension Array where Element: StopVisits { public var localizedShareString: String { var output = "" let _ = self.reduce(output) { (current, next) -> String in guard let smsString = next.smsString else { return current } output.append(smsString) output.append("\n") return output } if output.contains("*") { output.append("* real-time") } return output } } #endif
9c238d181319f1cf8abd9ddc2803767e
25.458333
227
0.659449
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Blockchain/UserPropertyRecorder/AnalyticsUserPropertyRecorder.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import DIKit import FirebaseAnalytics import PlatformKit import ToolKit /// Records user properties using external analytics client final class AnalyticsUserPropertyRecorder: UserPropertyRecording { // MARK: - Types struct UserPropertyErrorEvent: AnalyticsEvent { let name = "user_property_format_error" let params: [String: String]? } // MARK: - Properties private let logger: Logger private let validator: AnalyticsUserPropertyValidator private let analyticsRecorder: AnalyticsEventRecorderAPI // MARK: - Setup init( validator: AnalyticsUserPropertyValidator = AnalyticsUserPropertyValidator(), analyticsRecorder: AnalyticsEventRecorderAPI = resolve(), logger: Logger = .shared ) { self.validator = validator self.analyticsRecorder = analyticsRecorder self.logger = logger } // MARK: - API func record(id: String) { Analytics.setUserID(id.sha256) } /// Records a standard user property func record(_ property: StandardUserProperty) { record(property: property) } /// Records a hashed user property func record(_ property: HashedUserProperty) { record(property: property) } // MARK: - Accessors private func record(property: UserProperty) { let name = property.key.rawValue let value: String if property.truncatesValueIfNeeded { value = validator.truncated(value: property.value) } else { value = property.value } do { try validator.validate(name: name) try validator.validate(value: value) Analytics.setUserProperty(value, forName: name) } catch { // Catch the error and record it using analytics event recorder defer { logger.error("could not send user property \(name)! \(value) received error: \(String(describing: error))") } guard let error = error as? AnalyticsUserPropertyValidator.UserPropertyError else { return } let errorName = validator.truncated(name: error.rawValue) let errorValue = validator.truncated(value: name) let event = UserPropertyErrorEvent(params: [errorName: errorValue]) analyticsRecorder.record(event: event) } } }
8e59510a05d5f99199e9159f1312c236
29.9375
123
0.647273
false
false
false
false
AndreMuis/STGTISensorTag
refs/heads/master
STGTISensorTag/STGSimpleKeysService.swift
mit
1
// // STGSimpleKeysService.swift // STGTISensorTag // // Created by Andre Muis on 5/14/16. // Copyright © 2016 Andre Muis. All rights reserved. // import CoreBluetooth public class STGSimpleKeysService { weak var delegate : STGSimpleKeysServiceDelegate! let serviceUUID : CBUUID var service : CBService? let dataCharacteristicUUID : CBUUID var dataCharacteristic : CBCharacteristic? init(delegate : STGSimpleKeysServiceDelegate) { self.delegate = delegate self.serviceUUID = CBUUID(string: STGConstants.SimpleKeysService.serviceUUIDString) self.service = nil self.dataCharacteristicUUID = CBUUID(string: STGConstants.SimpleKeysService.dataCharacteristicUUIDString) self.dataCharacteristic = nil } public func enable() { self.delegate.simpleKeysServiceEnable(self) } public func disable() { self.delegate.simpleKeysServiceDisable(self) } func characteristicUpdated(characteristic : CBCharacteristic) { if let value = characteristic.value { if characteristic.UUID == self.dataCharacteristicUUID { let state : STGSimpleKeysState? = self.simpleKeysStateWithCharacteristicValue(value) self.delegate.simpleKeysService(self, didUpdateState: state) } } } func simpleKeysStateWithCharacteristicValue(characteristicValue : NSData) -> STGSimpleKeysState? { let bytes : [UInt8] = characteristicValue.unsignedIntegers let simpleKeysState = STGSimpleKeysState(rawValue: bytes[0]) return simpleKeysState } }
639367cd889c31bd1161a5a2812c378c
21.113924
113
0.65312
false
false
false
false
blitzagency/amigo-swift
refs/heads/master
Amigo/AmigoMetaData.swift
mit
1
// // AmigoMeta.swift // Amigo // // Created by Adam Venturella on 7/1/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation import CoreData public class AmigoMetaData{ var tables = [String:MetaModel]() public init(_ managedObjectModel: NSManagedObjectModel){ self.initialize(managedObjectModel) } public func metaModelForType<T: AmigoModel>(type: T.Type) -> MetaModel{ let key = type.description() return metaModelForName(key) } public func metaModelForName(name: String) -> MetaModel{ return tables[name]! } func initialize(managedObjectModel: NSManagedObjectModel){ let lookup = managedObjectModel.entitiesByName // there may be a better way here, right now we ensure we have // all the models, then we need to go do some additional passes // to ensure the ForeignKey Relationships (ToOne) and the Many To Many // relationships (ToMany). // // the N*3 loops hurts my heart, but for now, it'a only done // on initialization. lookup.map{metaModelFromEntity($1)} zip(lookup.values, tables.values).map(initializeRelationships) // lookup.map{registerModel($1)} // zip(lookup.values, tables.values).map(initializeRelationships) // initializeRelationships($0, model: $1) // } // join.map{(x, y) -> String in // print(99) // return "" // }.count } func initializeRelationships(entity:NSEntityDescription, model: MetaModel){ var columns = [Column]() var foreignKeys = [ForeignKey]() // sqlite supports FK's with actions: // https://www.sqlite.org/foreignkeys.html#fk_actions // TODO determine if iOS 9+ sqlite supports this // adjust column creation accordingly entity.relationshipsByName .filter{ $1.toMany == false } .map{ _, relationship -> Void in let target = relationship.destinationEntity! let targetModel = metaModelForName(target.managedObjectClassName) let foreignKey = ForeignKey( label: relationship.name, type: targetModel.primaryKey.type, relatedType: targetModel.table.type, optional: relationship.optional) let column = Column( label: "\(relationship.name)_id", type: targetModel.primaryKey.type, primaryKey: false, indexed: true, optional: relationship.optional, unique: false, foreignKey: foreignKey) columns.append(column) foreignKeys.append(foreignKey) } let model = MetaModel( table: model.table, columns: model.columns + columns, primaryKey: model.primaryKey, foreignKeys: foreignKeys) tables[String(model.table.type)] = model } func registerModel(model: MetaModel){ } func metaModelFromEntity(entityDescription: NSEntityDescription){ let model: MetaModel var primaryKey: Column? let table = Table.fromEntityDescription(entityDescription) var columns = entityDescription.attributesByName.map { Column.fromAttributeDescription($1) } primaryKey = columns.filter{ $0.primaryKey }.first if primaryKey == nil{ primaryKey = Column.defaultPrimaryKey() columns = [primaryKey!] + columns } model = MetaModel(table: table, columns: columns, primaryKey: primaryKey!) tables[String(table.type)] = model } func createAll(engine: Engine){ } }
978622b43dbe4b4245cd0f451ee8bea9
29.207692
85
0.582781
false
false
false
false
grd888/ios_uicollectionview_2nd_edition_source_code
refs/heads/master
Chapter 1/Swift/Chapter 1 Project 1/Chapter 1 Project 1/AFViewController.swift
apache-2.0
1
// // AFViewController.swift // Chapter 1 Project 1 // // Created by Greg Delgado on 26/10/2017. // Copyright © 2017 Greg Delgado. All rights reserved. // import UIKit private let kCellIdentifier = "Cell Identifier" class AFViewController: UICollectionViewController { var colorArray = [UIColor]() override func viewDidLoad() { super.viewDidLoad() self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCellIdentifier) let numberOfColors = 100; var tempArray = [UIColor]() for _ in 0..<numberOfColors { let redValue = Double(arc4random() % 255) / 255.0 let blueValue = Double(arc4random() % 255) / 255.0 let greenValue = Double(arc4random() % 255) / 255.0 tempArray.append(UIColor.init(red: CGFloat(redValue), green: CGFloat(greenValue), blue: CGFloat(blueValue), alpha: 1.0)) } colorArray = tempArray } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colorArray.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellIdentifier, for: indexPath) cell.backgroundColor = colorArray[indexPath.item] return cell } }
ce7646c8c996c8dd0460e5c5d589711d
28.75
132
0.658048
false
false
false
false
doronkatz/firefox-ios
refs/heads/master
Client/Frontend/Settings/ClearPrivateDataTableViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared private let SectionToggles = 0 private let SectionButton = 1 private let NumberOfSections = 2 private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier" private let TogglesPrefKey = "clearprivatedata.toggles" private let log = Logger.browserLogger private let HistoryClearableIndex = 0 class ClearPrivateDataTableViewController: UITableViewController { fileprivate var clearButton: UITableViewCell? var profile: Profile! var tabManager: TabManager! fileprivate typealias DefaultCheckedState = Bool fileprivate lazy var clearables: [(clearable: Clearable, checked: DefaultCheckedState)] = { return [ (HistoryClearable(profile: self.profile), true), (CacheClearable(tabManager: self.tabManager), true), (CookiesClearable(tabManager: self.tabManager), true), (SiteDataClearable(tabManager: self.tabManager), true), ] }() fileprivate lazy var toggles: [Bool] = { if let savedToggles = self.profile.prefs.arrayForKey(TogglesPrefKey) as? [Bool] { return savedToggles } return self.clearables.map { $0.checked } }() fileprivate var clearButtonEnabled = true { didSet { clearButton?.textLabel?.textColor = clearButtonEnabled ? UIConstants.DestructiveRed : UIColor.lightGray } } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsClearPrivateDataTitle tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: UIConstants.TableViewHeaderFooterHeight)) footer.showBottomBorder = false tableView.tableFooterView = footer } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) if indexPath.section == SectionToggles { cell.textLabel?.text = clearables[indexPath.item].clearable.label let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(ClearPrivateDataTableViewController.switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = toggles[indexPath.item] cell.accessoryView = control cell.selectionStyle = .none control.tag = indexPath.item } else { assert(indexPath.section == SectionButton) cell.textLabel?.text = Strings.SettingsClearPrivateDataClearButton cell.textLabel?.textAlignment = NSTextAlignment.center cell.textLabel?.textColor = UIConstants.DestructiveRed cell.accessibilityTraits = UIAccessibilityTraitButton cell.accessibilityIdentifier = "ClearPrivateData" clearButton = cell } return cell } override func numberOfSections(in tableView: UITableView) -> Int { return NumberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionToggles { return clearables.count } assert(section == SectionButton) return 1 } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { guard indexPath.section == SectionButton else { return false } // Highlight the button only if it's enabled. return clearButtonEnabled } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == SectionButton else { return } func clearPrivateData(_ action: UIAlertAction) { let toggles = self.toggles self.clearables .enumerated() .flatMap { (i, pair) in guard toggles[i] else { return nil } log.debug("Clearing \(pair.clearable).") return pair.clearable.clear() } .allSucceed() .upon { result in assert(result.isSuccess, "Private data cleared successfully") //LeanplumIntegration.sharedInstance.track(eventName: .clearPrivateData) self.profile.prefs.setObject(self.toggles, forKey: TogglesPrefKey) DispatchQueue.main.async { // Disable the Clear Private Data button after it's clicked. self.clearButtonEnabled = false self.tableView.deselectRow(at: indexPath, animated: true) } } } // We have been asked to clear history and we have an account. // (Whether or not it's in a good state is irrelevant.) if self.toggles[HistoryClearableIndex] && profile.hasAccount() { profile.syncManager.hasSyncedHistory().uponQueue(DispatchQueue.main) { yes in // Err on the side of warning, but this shouldn't fail. let alert: UIAlertController if yes.successValue ?? true { // Our local database contains some history items that have been synced. // Warn the user before clearing. alert = UIAlertController.clearSyncedHistoryAlert(okayCallback: clearPrivateData) } else { alert = UIAlertController.clearPrivateDataAlert(okayCallback: clearPrivateData) } self.present(alert, animated: true, completion: nil) return } } else { let alert = UIAlertController.clearPrivateDataAlert(okayCallback: clearPrivateData) self.present(alert, animated: true, completion: nil) } tableView.deselectRow(at: indexPath, animated: false) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderFooterIdentifier) as! SettingsTableSectionHeaderFooterView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UIConstants.TableViewHeaderFooterHeight } @objc func switchValueChanged(_ toggle: UISwitch) { toggles[toggle.tag] = toggle.isOn // Dim the clear button if no clearables are selected. clearButtonEnabled = toggles.contains(true) } }
08521af058a5343178ef0b4c96ed2be0
40.039773
164
0.65333
false
false
false
false
JGiola/swift-package-manager
refs/heads/main
Sources/Basic/RegEx.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation /// A helpful wrapper around NSRegularExpression. /// - SeeAlso: NSRegularExpression public struct RegEx { private let regex: NSRegularExpression public typealias Options = NSRegularExpression.Options /// Creates a new Regex using `pattern`. /// /// - Parameters: /// - pattern: A valid Regular Expression pattern /// - options: NSRegularExpression.Options on how the RegEx should be processed. /// - Note: Deliminators must be double escaped. Once for Swift and once for RegEx. /// Example, to math a negative integer: `RegEx(pattern: "-\d")` -> `RegEx(pattern: "-\\d")` /// - SeeAlso: NSRegularExpression /// - Throws: An Error if `pattern` is an invalid Regular Expression. public init(pattern: String, options: Options = []) throws { self.regex = try NSRegularExpression(pattern: pattern, options: options) } /// Returns match groups for every match of the Regex. /// /// For every match in the string, it constructs the collection /// of groups matched. /// /// RegEx(pattern: "([a-z]+)([0-9]+)").matchGroups(in: "foo1 bar2 baz3") /// /// Returns `[["foo", "1"], ["bar", "2"], ["baz", "3"]]`. /// /// - Parameters: /// - in: A string to check for matches to the whole Regex. /// - Returns: A collection where each elements is the collection of matched groups. public func matchGroups(in string: String) -> [[String]] { let nsString = NSString(string: string) return regex.matches(in: string, options: [], range: NSMakeRange(0, nsString.length)).map{ match -> [String] in return (1 ..< match.numberOfRanges).map { idx -> String in let range = match.range(at: idx) return range.location == NSNotFound ? "" : nsString.substring(with: range) } } } }
19aace5692bf446eee0d4aa2ecafebe9
40.407407
119
0.635063
false
false
false
false
PerfectlySoft/Perfect-Authentication
refs/heads/master
Sources/LocalAuthentication/Routing/webroutes/WebHandlers.registerCompletion.swift
apache-2.0
1
// // WebHandlers.registerCompletion.swift // Perfect-OAuth2-Server // // Created by Jonathan Guthrie on 2017-04-26. // // import PerfectHTTP import PerfectSession import PerfectCrypto import PerfectSessionPostgreSQL extension WebHandlers { // registerCompletion static func registerCompletion(data: [String:Any]) throws -> RequestHandler { return { request, response in let t = request.session?.data["csrf"] as? String ?? "" if let i = request.session?.userid, !i.isEmpty { response.redirect(path: "/") } var context: [String : Any] = ["title": "Perfect Authentication Server"] if let v = request.param(name: "passvalidation"), !(v as String).isEmpty { let acc = Account(validation: v) if acc.id.isEmpty { context["msg_title"] = "Account Validation Error." context["msg_body"] = "" response.render(template: "views/msg", context: context) return } else { if let p1 = request.param(name: "p1"), !(p1 as String).isEmpty, let p2 = request.param(name: "p2"), !(p2 as String).isEmpty, p1 == p2 { if let digestBytes = p1.digest(.sha256), let hexBytes = digestBytes.encode(.hex), let hexBytesStr = String(validatingUTF8: hexBytes) { print(hexBytesStr) acc.password = hexBytesStr // let digestBytes2 = p1.digest(.sha256) // let hexBytes2 = digestBytes2?.encode(.hex) // let hexBytesStr2 = String(validatingUTF8: hexBytes2!) // print(hexBytesStr2) } // acc.password = BCrypt.hash(password: p1) acc.usertype = .standard do { try acc.save() request.session?.userid = acc.id context["msg_title"] = "Account Validated and Completed." context["msg_body"] = "<p><a class=\"button\" href=\"/\">Click to continue</a></p>" response.render(template: "views/msg", context: context) } catch { print(error) } } else { context["msg_body"] = "<p>Account Validation Error: The passwords must not be empty, and must match.</p>" context["passvalidation"] = v context["csrfToken"] = t response.render(template: "views/registerComplete", context: context) return } } } else { context["msg_title"] = "Account Validation Error." context["msg_body"] = "Code not found." response.render(template: "views/msg", context: context) } } } }
0f14ec974f2fffd755c516f06efcae80
29.64557
111
0.623296
false
false
false
false
CodaFi/Algebra
refs/heads/master
Algebra/Module.swift
mit
2
// // Module.swift // Algebra // // Created by Robert Widmann on 11/22/14. // Copyright (c) 2014 TypeLift. All rights reserved. // /// If R is a Ring and M is an abelian group, a Left Module defines a binary operation R *<> M -> M. public struct LeftModule<R: Semiring, A: Additive> { public let multiply: (R, A) -> A } public enum LeftModules { public static let int = LeftModule<Int, Int>(multiply: *) public static let int8 = LeftModule<Int, Int8>(multiply: { Int8($0) * $1 }) public static let int16 = LeftModule<Int, Int16>(multiply: { Int16($0) * $1 }) public static let int32 = LeftModule<Int, Int32>(multiply: { Int32($0) * $1 }) public static let int64 = LeftModule<Int, Int64>(multiply: { Int64($0) * $1 }) } /// If R is a Ring and M is an abelian group, a Right Module defines a binary operation M <>* R -> M. public struct RightModule<A: Additive, R: Semiring> { public let multiply: (A, R) -> A } public enum RightModules { public static let int = RightModule<Int, Int>(multiply: *) public static let int8 = RightModule<Int8, Int>(multiply: { $0 * Int8($1) }) public static let int16 = RightModule<Int16, Int>(multiply: { $0 * Int16($1) }) public static let int32 = RightModule<Int32, Int>(multiply: { $0 * Int32($1) }) public static let int64 = RightModule<Int64, Int>(multiply: { $0 * Int64($1) }) } /// A bimodule is a module with compatible left and right operations. public struct Bimodule<R: Semiring, A: Additive> { public let left: LeftModule<R, A> public let right: RightModule<A, R> } enum Bimodules { public static let int = Bimodule(left: LeftModules.int, right: RightModules.int) public static let int8 = Bimodule(left: LeftModules.int8, right: RightModules.int8) public static let int16 = Bimodule(left: LeftModules.int16, right: RightModules.int16) public static let int32 = Bimodule(left: LeftModules.int32, right: RightModules.int32) public static let int64 = Bimodule(left: LeftModules.int64, right: RightModules.int64) }
6da0421721fb3c3ee70c18f9025d78e0
45.204545
101
0.684211
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Client/Frontend/Browser/WindowCloseHelper.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol WindowCloseHelperDelegate: class { func windowCloseHelper(windowCloseHelper: WindowCloseHelper, didRequestToCloseTab tab: Tab) } class WindowCloseHelper: TabHelper { weak var delegate: WindowCloseHelperDelegate? private weak var tab: Tab? required init(tab: Tab) { self.tab = tab if let path = NSBundle.mainBundle().pathForResource("WindowCloseHelper", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } } func scriptMessageHandlerName() -> String? { return "windowCloseHelper" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab { dispatch_async(dispatch_get_main_queue()) { self.delegate?.windowCloseHelper(self, didRequestToCloseTab: tab) } } } class func name() -> String { return "WindowCloseHelper" } }
76c0688e6e04b4b24106e6bb712d5aec
35.97561
141
0.687335
false
false
false
false
slavapestov/swift
refs/heads/master
stdlib/public/core/AssertCommon.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation Note: this file intentionally uses very LOW-LEVEL // CONSTRUCTS, so that assert and fatal may be used liberally in // building library abstractions without fear of infinite recursion. // // FIXME: We could go farther with this simplification, e.g. avoiding // UnsafeMutablePointer @_transparent @warn_unused_result public // @testable func _isDebugAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 0 } @_transparent @warn_unused_result internal func _isReleaseAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 1 } @_transparent @warn_unused_result public // @testable func _isFastAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 2 } @_transparent @warn_unused_result public // @testable func _isStdlibInternalChecksEnabled() -> Bool { #if INTERNAL_CHECKS_ENABLED return true #else return false #endif } @_transparent @warn_unused_result internal func _fatalErrorFlags() -> UInt32 { // The current flags are: // (1 << 0): Report backtrace on fatal error #if os(iOS) || os(tvOS) || os(watchOS) return 0 #else return _isDebugAssertConfiguration() ? 1 : 0 #endif } @_silgen_name("_swift_stdlib_reportFatalErrorInFile") func _reportFatalErrorInFile( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportFatalError") func _reportFatalError( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportUnimplementedInitializerInFile") func _reportUnimplementedInitializerInFile( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, _ column: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportUnimplementedInitializer") func _reportUnimplementedInitializer( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, flags: UInt32) /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in message.withUTF8Buffer { (message) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line, flags: flags) Builtin.int_trap() } } } Builtin.int_trap() } /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: String, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in let messageUTF8 = message.nulTerminatedUTF8 messageUTF8.withUnsafeBufferPointer { (messageUTF8) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), messageUTF8.baseAddress, UInt(messageUTF8.count), file.baseAddress, UInt(file.count), line, flags: flags) } } } Builtin.int_trap() } /// This function should be used only in the implementation of stdlib /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") @_semantics("arc.programtermination_point") func _fatalErrorMessage( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { #if INTERNAL_CHECKS_ENABLED prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in file.withUTF8Buffer { (file) in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line, flags: flags) } } } #else prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in _reportFatalError( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), flags: flags) } } #endif Builtin.int_trap() } /// Prints a fatal error message when an unimplemented initializer gets /// called by the Objective-C runtime. @_transparent @noreturn public // COMPILER_INTRINSIC func _unimplemented_initializer(className: StaticString, initName: StaticString = #function, file: StaticString = #file, line: UInt = #line, column: UInt = #column) { // This function is marked @_transparent so that it is inlined into the caller // (the initializer stub), and, depending on the build configuration, // redundant parameter values (#file etc.) are eliminated, and don't leak // information about the user's source. if _isDebugAssertConfiguration() { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in file.withUTF8Buffer { (file) in _reportUnimplementedInitializerInFile( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), file.baseAddress, UInt(file.count), line, column, flags: 0) } } } } else { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in _reportUnimplementedInitializer( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), flags: 0) } } } Builtin.int_trap() } @noreturn public // COMPILER_INTRINSIC func _undefined<T>( @autoclosure message: () -> String = String(), file: StaticString = #file, line: UInt = #line ) -> T { _assertionFailed("fatal error", message(), file, line, flags: 0) }
fb4ac4e555f5dce842848ce28898a74a
28.1341
80
0.657943
false
false
false
false
sssbohdan/Design-Patterns-In-Swift
refs/heads/master
Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
gpl-3.0
2
//: Behavioral | //: [Creational](Creational) | //: [Structural](Structural) /*: Behavioral ========== >In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. > >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern) */ import Swift import Foundation /*: 🐝 Chain Of Responsibility -------------------------- The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler. ### Example: */ class MoneyPile { let value: Int var quantity: Int var nextPile: MoneyPile? init(value: Int, quantity: Int, nextPile: MoneyPile?) { self.value = value self.quantity = quantity self.nextPile = nextPile } func canWithdraw(v: Int) -> Bool { var v = v func canTakeSomeBill(want: Int) -> Bool { return (want / self.value) > 0 } var q = self.quantity while canTakeSomeBill(v) { if q == 0 { break } v -= self.value q -= 1 } if v == 0 { return true } else if let next = self.nextPile { return next.canWithdraw(v) } return false } } class ATM { private var hundred: MoneyPile private var fifty: MoneyPile private var twenty: MoneyPile private var ten: MoneyPile private var startPile: MoneyPile { return self.hundred } init(hundred: MoneyPile, fifty: MoneyPile, twenty: MoneyPile, ten: MoneyPile) { self.hundred = hundred self.fifty = fifty self.twenty = twenty self.ten = ten } func canWithdraw(value: Int) -> String { return "Can withdraw: \(self.startPile.canWithdraw(value))" } } /*: ### Usage */ // Create piles of money and link them together 10 < 20 < 50 < 100.** let ten = MoneyPile(value: 10, quantity: 6, nextPile: nil) let twenty = MoneyPile(value: 20, quantity: 2, nextPile: ten) let fifty = MoneyPile(value: 50, quantity: 2, nextPile: twenty) let hundred = MoneyPile(value: 100, quantity: 1, nextPile: fifty) // Build ATM. var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten) atm.canWithdraw(310) // Cannot because ATM has only 300 atm.canWithdraw(100) // Can withdraw - 1x100 atm.canWithdraw(165) // Cannot withdraw because ATM doesn't has bill with value of 5 atm.canWithdraw(30) // Can withdraw - 1x20, 2x10 /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility) */ /*: 👫 Command ---------- The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use. ### Example: */ protocol DoorCommand { func execute() -> String } class OpenCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Opened \(doors)" } } class CloseCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Closed \(doors)" } } class HAL9000DoorsOperations { let openCommand: DoorCommand let closeCommand: DoorCommand init(doors: String) { self.openCommand = OpenCommand(doors:doors) self.closeCommand = CloseCommand(doors:doors) } func close() -> String { return closeCommand.execute() } func open() -> String { return openCommand.execute() } } /*: ### Usage: */ let podBayDoors = "Pod Bay Doors" let doorModule = HAL9000DoorsOperations(doors:podBayDoors) doorModule.open() doorModule.close() /*: 🎶 Interpreter -------------- The interpreter pattern is used to evaluate sentences in a language. ### Example */ protocol IntegerExp { func evaluate(context: IntegerContext) -> Int func replace(character: Character, integerExp: IntegerExp) -> IntegerExp func copy() -> IntegerExp } class IntegerContext { private var data: [Character:Int] = [:] func lookup(name: Character) -> Int { return self.data[name]! } func assign(integerVarExp: IntegerVarExp, value: Int) { self.data[integerVarExp.name] = value } } class IntegerVarExp: IntegerExp { let name: Character init(name: Character) { self.name = name } func evaluate(context: IntegerContext) -> Int { return context.lookup(self.name) } func replace(name: Character, integerExp: IntegerExp) -> IntegerExp { if name == self.name { return integerExp.copy() } else { return IntegerVarExp(name: self.name) } } func copy() -> IntegerExp { return IntegerVarExp(name: self.name) } } class AddExp: IntegerExp { private var operand1: IntegerExp private var operand2: IntegerExp init(op1: IntegerExp, op2: IntegerExp) { self.operand1 = op1 self.operand2 = op2 } func evaluate(context: IntegerContext) -> Int { return self.operand1.evaluate(context) + self.operand2.evaluate(context) } func replace(character: Character, integerExp: IntegerExp) -> IntegerExp { return AddExp(op1: operand1.replace(character, integerExp: integerExp), op2: operand2.replace(character, integerExp: integerExp)) } func copy() -> IntegerExp { return AddExp(op1: self.operand1, op2: self.operand2) } } /*: ### Usage */ var expression: IntegerExp? var intContext = IntegerContext() var a = IntegerVarExp(name: "A") var b = IntegerVarExp(name: "B") var c = IntegerVarExp(name: "C") expression = AddExp(op1: a, op2: AddExp(op1: b, op2: c)) // a + (b + c) intContext.assign(a, value: 2) intContext.assign(b, value: 1) intContext.assign(c, value: 3) var result = expression?.evaluate(intContext) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter) */ /*: 🍫 Iterator ----------- The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure. ### Example: */ struct NovellasCollection<T> { let novellas: [T] } extension NovellasCollection: SequenceType { typealias Generator = AnyGenerator<T> func generate() -> AnyGenerator<T> { var i = 0 return AnyGenerator { i += 1; return i >= self.novellas.count ? nil : self.novellas[i] } } } /*: ### Usage */ let greatNovellas = NovellasCollection(novellas:["Mist"]) for novella in greatNovellas { print("I've read: \(novella)") } /*: 💐 Mediator ----------- The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object. ### Example */ class Colleague { let name: String let mediator: Mediator init(name: String, mediator: Mediator) { self.name = name self.mediator = mediator } func send(message: String) { mediator.send(message, colleague: self) } func receive(message: String) { assert(false, "Method should be overriden") } } protocol Mediator { func send(message: String, colleague: Colleague) } class MessageMediator: Mediator { private var colleagues: [Colleague] = [] func addColleague(colleague: Colleague) { colleagues.append(colleague) } func send(message: String, colleague: Colleague) { for c in colleagues { if c !== colleague { //for simplicity we compare object references c.receive(message) } } } } class ConcreteColleague: Colleague { override func receive(message: String) { print("Colleague \(name) received: \(message)") } } /*: ### Usage */ let messagesMediator = MessageMediator() let user0 = ConcreteColleague(name: "0", mediator: messagesMediator) let user1 = ConcreteColleague(name: "1", mediator: messagesMediator) messagesMediator.addColleague(user0) messagesMediator.addColleague(user1) user0.send("Hello") // user1 receives message /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator) */ /*: 💾 Memento ---------- The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation. ### Example */ typealias Memento = Dictionary<NSObject, AnyObject> let DPMementoKeyChapter = "com.valve.halflife.chapter" let DPMementoKeyWeapon = "com.valve.halflife.weapon" let DPMementoGameState = "com.valve.halflife.state" /*: Originator */ class GameState { var chapter: String = "" var weapon: String = "" func toMemento() -> Memento { return [ DPMementoKeyChapter:chapter, DPMementoKeyWeapon:weapon ] } func restoreFromMemento(memento: Memento) { chapter = memento[DPMementoKeyChapter] as? String ?? "n/a" weapon = memento[DPMementoKeyWeapon] as? String ?? "n/a" } } /*: Caretaker */ enum CheckPoint { static func saveState(memento: Memento, keyName: String = DPMementoGameState) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(memento, forKey: keyName) defaults.synchronize() } static func restorePreviousState(keyName keyName: String = DPMementoGameState) -> Memento { let defaults = NSUserDefaults.standardUserDefaults() return defaults.objectForKey(keyName) as? Memento ?? Memento() } } /*: ### Usage */ var gameState = GameState() gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Black Mesa Inbound" gameState.weapon = "Crowbar" CheckPoint.saveState(gameState.toMemento()) gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.saveState(gameState.toMemento()) gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2")) /*: 👓 Observer ----------- The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes. ### Example */ protocol PropertyObserver : class { func willChangePropertyName(propertyName:String, newPropertyValue:AnyObject?) func didChangePropertyName(propertyName:String, oldPropertyValue:AnyObject?) } class TestChambers { weak var observer:PropertyObserver? var testChamberNumber: Int = 0 { willSet(newValue) { observer?.willChangePropertyName("testChamberNumber", newPropertyValue:newValue) } didSet { observer?.didChangePropertyName("testChamberNumber", oldPropertyValue:oldValue) } } } class Observer : PropertyObserver { func willChangePropertyName(propertyName: String, newPropertyValue: AnyObject?) { if newPropertyValue as? Int == 1 { print("Okay. Look. We both said a lot of things that you're going to regret.") } } func didChangePropertyName(propertyName: String, oldPropertyValue: AnyObject?) { if oldPropertyValue as? Int == 0 { print("Sorry about the mess. I've really let the place go since you killed me.") } } } /*: ### Usage */ var observerInstance = Observer() var testChambers = TestChambers() testChambers.observer = observerInstance testChambers.testChamberNumber++ /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer) */ /*: 🐉 State --------- The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time. ### Example */ class Context { private var state: State = UnauthorizedState() var isAuthorized: Bool { get { return state.isAuthorized(self) } } var userId: String? { get { return state.userId(self) } } func changeStateToAuthorized(userId userId: String) { state = AuthorizedState(userId: userId) } func changeStateToUnauthorized() { state = UnauthorizedState() } } protocol State { func isAuthorized(context: Context) -> Bool func userId(context: Context) -> String? } class UnauthorizedState: State { func isAuthorized(context: Context) -> Bool { return false } func userId(context: Context) -> String? { return nil } } class AuthorizedState: State { let userId: String init(userId: String) { self.userId = userId } func isAuthorized(context: Context) -> Bool { return true } func userId(context: Context) -> String? { return userId } } /*: ### Usage */ let context = Context() (context.isAuthorized, context.userId) context.changeStateToAuthorized(userId: "admin") (context.isAuthorized, context.userId) // now logged in as "admin" context.changeStateToUnauthorized() (context.isAuthorized, context.userId) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State) */ /*: 💡 Strategy ----------- The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time. ### Example */ protocol PrintStrategy { func printString(string: String) -> String } class Printer { let strategy: PrintStrategy func printString(string: String) -> String { return self.strategy.printString(string) } init(strategy: PrintStrategy) { self.strategy = strategy } } class UpperCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.uppercaseString } } class LowerCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.lowercaseString } } /*: ### Usage */ var lower = Printer(strategy:LowerCaseStrategy()) lower.printString("O tempora, o mores!") var upper = Printer(strategy:UpperCaseStrategy()) upper.printString("O tempora, o mores!") /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy) */ /*: 🏃 Visitor ---------- The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold. ### Example */ protocol PlanetVisitor { func visit(planet: PlanetAlderaan) func visit(planet: PlanetCoruscant) func visit(planet: PlanetTatooine) } protocol Planet { func accept(visitor: PlanetVisitor) } class PlanetAlderaan: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class PlanetCoruscant: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class PlanetTatooine: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class NameVisitor: PlanetVisitor { var name = "" func visit(planet: PlanetAlderaan) { name = "Alderaan" } func visit(planet: PlanetCoruscant) { name = "Coruscant" } func visit(planet: PlanetTatooine) { name = "Tatooine" } } /*: ### Usage */ let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine()] let names = planets.map { (planet: Planet) -> String in let visitor = NameVisitor() planet.accept(visitor) return visitor.name } names /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor) */
e0dba1e230a8147de50864dcd04ded47
24.518167
245
0.672692
false
false
false
false
idomizrachi/Regen
refs/heads/master
regen/Dependencies/Colors/Colors.swift
mit
1
// // Colors.swift // Colors // // Created by Chad Scira on 3/3/15. // // https://github.com/icodeforlove/Colors import Foundation var colorCodes:[String:Int] = [ "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37 ] var bgColorCodes:[String:Int] = [ "blackBackground": 40, "redBackground": 41, "greenBackground": 42, "yellowBackground": 43, "blueBackground": 44, "magentaBackground": 45, "cyanBackground": 46, "whiteBackground": 47 ] var styleCodes:[String:Int] = [ "reset": 0, "bold": 1, "italic": 3, "underline": 4, "inverse": 7, "strikethrough": 9, "boldOff": 22, "italicOff": 23, "underlineOff": 24, "inverseOff": 27, "strikethroughOff": 29 ] func getCode(_ key: String) -> Int? { if colorCodes[key] != nil { return colorCodes[key] } else if bgColorCodes[key] != nil { return bgColorCodes[key] } else if styleCodes[key] != nil { return styleCodes[key] } return nil } func addCodeToCodesArray(_ codes: Array<Int>, code: Int) -> Array<Int> { var result:Array<Int> = codes if colorCodes.values.contains(code) { result = result.filter { !colorCodes.values.contains($0) } } else if bgColorCodes.values.contains(code) { result = result.filter { !bgColorCodes.values.contains($0) } } else if code == 0 { return [] } if !result.contains(code) { result.append(code) } return result } func matchesForRegexInText(_ regex: String!, text: String!, global: Bool = false) -> [String] { let regex = try! NSRegularExpression(pattern: regex, options: []) let nsString = text as NSString let results = regex.matches(in: nsString as String, options: [], range: NSMakeRange(0, nsString.length)) if !global && results.count == 1 { var result:[String] = [] for i in 0..<results[0].numberOfRanges { result.append(nsString.substring(with: results[0].range(at: i))) } return result } else { return results.map { nsString.substring(with: $0.range) } } } struct ANSIGroup { var codes:[Int] var string:String func toString() -> String { let codeStrings = codes.map { String($0) } return "\u{001B}[" + codeStrings.joined(separator: ";") + "m" + string + "\u{001B}[0m" } } func parseExistingANSI(_ string: String) -> [ANSIGroup] { var results:[ANSIGroup] = [] let matches = matchesForRegexInText("\\u001B\\[([^m]*)m(.+?)\\u001B\\[0m", text: string, global: true) for match in matches { var parts = matchesForRegexInText("\\u001B\\[([^m]*)m(.+?)\\u001B\\[0m", text: match), codes = parts[1].split {$0 == ";"}.map { String($0) }, string = parts[2] results.append(ANSIGroup(codes: codes.filter { Int($0) != nil }.map { Int($0)! }, string: string)) } return results } func format(_ string: String, _ command: String) -> String { if (ProcessInfo.processInfo.environment["DEBUG"] != nil && ProcessInfo.processInfo.environment["DEBUG"]! as String == "true" && (ProcessInfo.processInfo.environment["TEST"] == nil || ProcessInfo.processInfo.environment["TEST"]! as String == "false")) { return string } let code = getCode(command) let existingANSI = parseExistingANSI(string) if code == nil { return string } else if existingANSI.count > 0 { return existingANSI.map { return ANSIGroup(codes: addCodeToCodesArray($0.codes, code: code!), string: $0.string).toString() }.joined(separator: "") } else { let group = ANSIGroup(codes: [code!], string: string) return group.toString() } } public extension String { // foregrounds var black: String { return format(self, "black") } var red: String { return format(self, "red") } var green: String { return format(self, "green") } var yellow: String { return format(self, "yellow") } var blue: String { return format(self, "blue") } var magenta: String { return format(self, "magenta") } var cyan: String { return format(self, "cyan") } var white: String { return format(self, "white") } // backgrounds var blackBackground: String { return format(self, "blackBackground") } var redBackground: String { return format(self, "redBackground") } var greenBackground: String { return format(self, "greenBackground") } var yellowBackground: String { return format(self, "yellowBackground") } var blueBackground: String { return format(self, "blueBackground") } var magentaBackground: String { return format(self, "magentaBackground") } var cyanBackground: String { return format(self, "cyanBackground") } var whiteBackground: String { return format(self, "whiteBackground") } // formats var bold: String { return format(self, "bold") } var italic: String { return format(self, "italic") } var underline: String { return format(self, "underline") } var reset: String { return format(self, "reset") } var inverse: String { return format(self, "inverse") } var strikethrough: String { return format(self, "strikethrough") } var boldOff: String { return format(self, "boldOff") } var italicOff: String { return format(self, "italicOff") } var underlineOff: String { return format(self, "underlineOff") } var inverseOff: String { return format(self, "inverseOff") } var strikethroughOff: String { return format(self, "strikethroughOff") } }
082ac9c60b71c9bd8d5661f93288116e
23.812245
256
0.575424
false
false
false
false
jeffreybergier/Hipstapaper
refs/heads/main
Hipstapaper/Packages/V3Style/Sources/V3Style/PropertyWrappers/DetailTable.swift
mit
1
// // Created by Jeffrey Bergier on 2022/07/30. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 SwiftUI import Umbrella @propertyWrapper public struct DetailTable: DynamicProperty { public struct Value { public var date: some ViewModifier = DetailTableDateText() public var url: some ViewModifier = DetailTableURLText() public var title: some ViewModifier = DetailTableTitleText() public var hack_edit: some ActionStyle = ActionStyleImp(labelStyle: .titleOnly) public var hack_done: some ActionStyle = JSBToolbarButtonStyleDone public var columnWidthDate: CGFloat = .dateColumnWidthMax public var columnWidthThumbnail: CGFloat = .thumbnailColumnWidth public func thumbnail(_ data: Data?) -> some View { ThumbnailImage(data) .frame(width: .thumbnailSmall, height: .thumbnailSmall) .cornerRadius(.cornerRadiusSmall) } public func syncIndicator(_ progress: Progress) -> some ViewModifier { SyncIndicator(progress) } } public init() {} public var wrappedValue: Value { Value() } }
9ea1934ad9c817a5c6d81918f8c72f66
39.137931
88
0.690722
false
false
false
false
jaredsinclair/sodes-audio-example
refs/heads/master
Sodes/SodesAudio/ScratchFileInfo.swift
mit
1
// // ScratchFileInfo.swift // SodesAudio // // Created by Jared Sinclair on 8/16/16. // // import Foundation import SwiftableFileHandle import SodesFoundation /// Info for the current scratch file for ResourceLoaderDelegate. class ScratchFileInfo { /// Cache validation info. struct CacheInfo { let contentLength: Int64? let etag: String? let lastModified: Date? } /// The remote URL from which the file should be downloaded. let resourceUrl: URL /// The subdirectory for this scratch file and its metadata. let directory: URL /// The file url to the scratch file itself. let scratchFileUrl: URL /// The file url to the metadata for the scratch file. let metaDataUrl: URL /// The file handle used for reading/writing bytes to the scratch file. let fileHandle: SODSwiftableFileHandle /// The most recent cache validation info. var cacheInfo: CacheInfo /// The byte ranges for the scratch file that have been saved thus far. var loadedByteRanges: [ByteRange] /// Designated initializer. init(resourceUrl: URL, directory: URL, scratchFileUrl: URL, metaDataUrl: URL, fileHandle: SODSwiftableFileHandle, cacheInfo: CacheInfo, loadedByteRanges: [ByteRange]) { self.resourceUrl = resourceUrl self.directory = directory self.scratchFileUrl = scratchFileUrl self.metaDataUrl = metaDataUrl self.fileHandle = fileHandle self.cacheInfo = cacheInfo self.loadedByteRanges = loadedByteRanges } } extension ScratchFileInfo.CacheInfo { static let none = ScratchFileInfo.CacheInfo( contentLength: nil, etag: nil, lastModified: nil ) func isStillValid(comparedTo otherInfo: ScratchFileInfo.CacheInfo) -> Bool { if let old = self.etag, let new = otherInfo.etag { return old == new } else if let old = lastModified, let new = otherInfo.lastModified { return old == new } else { return false } } }
f0b7dc397e8773aa8964cd748897d696
27.213333
172
0.652647
false
false
false
false
carabina/SwiftMock
refs/heads/master
Pod/Classes/MockExpectation.swift
mit
1
// // MockExpectation.swift // SwiftMock // // Created by Matthew Flint on 13/09/2015. // // import Foundation public class MockExpectation { public var functionName: String? var args: [Any?] /// the return value for this expectation, if any public var returnValue: Any? public init() { args = [Any?]() } public func call<T>(value: T) -> MockActionable<T> { return MockActionable(value, self) } /// record the function name and arguments during the expectation-setting phase public func acceptExpected(functionName theFunctionName: String, args theArgs: Any?...) -> Bool { // do we already have a function? if so, we can't accept this call as an expectation let result = functionName == nil if result { functionName = theFunctionName args = theArgs } return result } public func isComplete() -> Bool { return functionName != nil } /// offer this function, and its arguments, to the expectation to see if it matches public func satisfy(functionName theFunctionName: String, args theArgs: Any?...) -> Bool { return functionName == theFunctionName && match(args, theArgs) } func match(firstAnyOptional: Any?, _ secondAnyOptional: Any?) -> Bool { if firstAnyOptional == nil && secondAnyOptional == nil { return true } if firstAnyOptional == nil || secondAnyOptional == nil { return false } let firstAny = firstAnyOptional! let secondAny = secondAnyOptional! // there must be a better way to match two Any? values :-/ var result = false switch(firstAny) { case let firstArray as Array<Any?>: if let secondArray = secondAny as? Array<Any?> { result = matchArraysOfOptionals(firstArray, secondArray) } case let firstArray as Array<Any>: if let secondArray = secondAny as? Array<Any> { result = matchArrays(firstArray, secondArray) } case let first as String: if let second = secondAny as? String { result = first == second } case let first as Int: if let second = secondAny as? Int { result = first == second } case let first as Double: if let second = secondAny as? Double { result = first == second } case let first as Bool: if let second = secondAny as? Bool { result = first == second } default: break } return result } func matchArraysOfOptionals(firstArray: Array<Any?>, _ secondArray: Array<Any?>) -> Bool { var result = true if firstArray.count != secondArray.count { result = false } for var index=0; index<firstArray.count && result; index++ { result = match(firstArray[index], secondArray[index]) } return result } func matchArrays(firstArray: Array<Any>, _ secondArray: Array<Any>) -> Bool { var result = true if firstArray.count != secondArray.count { result = false } for var index=0; index<firstArray.count && result; index++ { result = match(firstArray[index], secondArray[index]) } return result } }
cb6e981cf6b77b96db7efa4f0bbc4ee5
29.655172
101
0.558931
false
false
false
false
salemoh/GoldenQuraniOS
refs/heads/master
GRDB/Core/RowAdapter.swift
mit
2
import Foundation /// LayoutedColumnMapping is a type that supports the RowAdapter protocol. public struct LayoutedColumnMapping { /// An array of (baseIndex, mappedName) pairs, where baseIndex is the index /// of a column in a base row, and mappedName the mapped name of /// that column. public let layoutColumns: [(Int, String)] /// A cache for layoutIndex(ofColumn:) let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex] /// Creates an LayoutedColumnMapping from an array of (baseIndex, mappedName) /// pairs. In each pair: /// /// - baseIndex is the index of a column in a base row /// - name is the mapped name of the column /// /// For example, the following LayoutedColumnMapping defines two columns, "foo" /// and "bar", based on the base columns at indexes 1 and 2: /// /// LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")]) /// /// Use it in your custom RowAdapter type: /// /// struct FooBarAdapter : RowAdapter { /// func layoutAdapter(layout: RowLayout) throws -> LayoutedRowAdapter { /// return LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")]) /// } /// } /// /// // <Row foo:"foo" bar: "bar"> /// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) { self.layoutColumns = Array(layoutColumns) self.lowercaseColumnIndexes = Dictionary(keyValueSequence: layoutColumns .enumerated() .map { ($1.1.lowercased(), $0) } .reversed()) // reversed() so that the the dictionary caches leftmost indexes } func baseColumnIndex(atMappingIndex index: Int) -> Int { return layoutColumns[index].0 } func columnName(atMappingIndex index: Int) -> String { return layoutColumns[index].1 } } /// LayoutedColumnMapping adopts LayoutedRowAdapter extension LayoutedColumnMapping : LayoutedRowAdapter { /// Part of the LayoutedRowAdapter protocol; returns self. public var mapping: LayoutedColumnMapping { return self } /// Part of the LayoutedRowAdapter protocol; returns the empty dictionary. public var scopes: [String: LayoutedRowAdapter] { return [:] } } extension LayoutedColumnMapping : RowLayout { /// Part of the RowLayout protocol; returns the index of the leftmost column /// named `name`, in a case-insensitive way. public func layoutIndex(ofColumn name: String) -> Int? { if let index = lowercaseColumnIndexes[name] { return index } return lowercaseColumnIndexes[name.lowercased()] } } /// LayoutedRowAdapter is a protocol that supports the RowAdapter protocol. /// /// GRBD ships with a ready-made type that adopts this protocol: /// LayoutedColumnMapping. public protocol LayoutedRowAdapter { /// A LayoutedColumnMapping that defines how to map a column name to a /// column in a base row. var mapping: LayoutedColumnMapping { get } /// The layouted row adapters for each scope. var scopes: [String: LayoutedRowAdapter] { get } } /// RowLayout is a protocol that supports the RowAdapter protocol. It describes /// a layout of a base row. public protocol RowLayout { /// An array of (baseIndex, name) pairs, where baseIndex is the index /// of a column in a base row, and name the name of that column. var layoutColumns: [(Int, String)] { get } /// Returns the index of the leftmost column named `name`, in a /// case-insensitive way. func layoutIndex(ofColumn name: String) -> Int? } extension SelectStatement : RowLayout { /// Part of the RowLayout protocol. public var layoutColumns: [(Int, String)] { return Array(columnNames.enumerated()) } /// Part of the RowLayout protocol. public func layoutIndex(ofColumn name: String) -> Int? { return index(ofColumn: name) } } /// RowAdapter is a protocol that helps two incompatible row interfaces working /// together. /// /// GRDB ships with four concrete types that adopt the RowAdapter protocol: /// /// - ColumnMapping: renames row columns /// - SuffixRowAdapter: hides the first columns of a row /// - RangeRowAdapter: only exposes a range of columns /// - ScopeAdapter: groups several adapters together to define named scopes /// /// To use a row adapter, provide it to any method that fetches: /// /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// /// // <Row baz:3> /// try Row.fetchOne(db, sql, adapter: adapter) public protocol RowAdapter { /// You never call this method directly. It is called for you whenever an /// adapter has to be applied. /// /// The result is a value that adopts LayoutedRowAdapter, such as /// LayoutedColumnMapping. /// /// For example: /// /// // An adapter that turns any row to a row that contains a single /// // column named "foo" whose value is the leftmost value of the /// // base row. /// struct FirstColumnAdapter : RowAdapter { /// func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { /// return LayoutedColumnMapping(layoutColumns: [(0, "foo")]) /// } /// } /// /// // <Row foo:1> /// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter()) func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter } extension RowAdapter { /// Returns an adapter based on self, with added scopes. /// /// If self already defines scopes, the added scopes replace /// eventual existing scopes with the same name. /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter { return ScopeAdapter(mainAdapter: self, scopes: scopes) } } extension RowAdapter { func baseColumnIndex(atIndex index: Int, layout: RowLayout) throws -> Int { return try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index) } } /// ColumnMapping is a row adapter that maps column names. /// /// let adapter = ColumnMapping(["foo": "bar"]) /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz" /// /// // <Row foo:"bar"> /// try Row.fetchOne(db, sql, adapter: adapter) public struct ColumnMapping : RowAdapter { /// A dictionary from mapped column names to column names in a base row. let mapping: [String: String] /// Creates a ColumnMapping with a dictionary from mapped column names to /// column names in a base row. public init(_ mapping: [String: String]) { self.mapping = mapping } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutColumns = try mapping .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout.layoutIndex(ofColumn: baseColumn) else { let columnNames = layout.layoutColumns.map { $0.1 } throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).") } let baseIndex = layout.layoutColumns[index].0 return (baseIndex, mappedColumn) } .sorted { $0.0 < $1.0 } // preserve ordering of base columns return LayoutedColumnMapping(layoutColumns: layoutColumns) } } /// SuffixRowAdapter is a row adapter that hides the first columns in a row. /// /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// /// // <Row baz:3> /// try Row.fetchOne(db, sql, adapter: adapter) public struct SuffixRowAdapter : RowAdapter { /// The suffix index let index: Int /// Creates a SuffixRowAdapter that hides all columns before the /// provided index. /// /// If index is 0, the layout row is identical to the base row. public init(fromIndex index: Int) { GRDBPrecondition(index >= 0, "Negative column index is out of range") self.index = index } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index)) } } /// RangeRowAdapter is a row adapter that only exposes a range of columns. /// /// let adapter = RangeRowAdapter(1..<3) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux" /// /// // <Row bar:2 baz: 3> /// try Row.fetchOne(db, sql, adapter: adapter) public struct RangeRowAdapter : RowAdapter { /// The range let range: CountableRange<Int> /// Creates a RangeRowAdapter that only exposes a range of columns. public init(_ range: CountableRange<Int>) { GRDBPrecondition(range.lowerBound >= 0, "Negative column index is out of range") self.range = range } /// Creates a RangeRowAdapter that only exposes a range of columns. public init(_ range: CountableClosedRange<Int>) { GRDBPrecondition(range.lowerBound >= 0, "Negative column index is out of range") self.range = range.lowerBound..<(range.upperBound + 1) } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range]) } } /// ScopeAdapter is a row adapter that lets you define scopes on rows. /// /// // Two adapters /// let fooAdapter = ColumnMapping(["value": "foo"]) /// let barAdapter = ColumnMapping(["value": "bar"]) /// /// // Define scopes /// let adapter = ScopeAdapter([ /// "foo": fooAdapter, /// "bar": barAdapter]) /// /// // Fetch /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// /// // Scoped rows: /// if let fooRow = row.scoped(on: "foo") { /// fooRow.value(named: "value") // "foo" /// } /// if let barRow = row.scopeed(on: "bar") { /// barRow.value(named: "value") // "bar" /// } public struct ScopeAdapter : RowAdapter { /// The main adapter let mainAdapter: RowAdapter /// The scope adapters let scopes: [String: RowAdapter] /// Creates a scoped adapter. /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. public init(_ scopes: [String: RowAdapter]) { self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter self.scopes = scopes } init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) { self.mainAdapter = mainAdapter self.scopes = scopes } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout) var layoutedScopes = layoutedAdapter.scopes for (name, adapter) in scopes { try layoutedScopes[name] = adapter.layoutedAdapter(from: layout) } return LayoutedScopeAdapter( mapping: layoutedAdapter.mapping, scopes: layoutedScopes) } } /// The LayoutedRowAdapter for ScopeAdapter struct LayoutedScopeAdapter : LayoutedRowAdapter { let mapping: LayoutedColumnMapping let scopes: [String: LayoutedRowAdapter] } struct ChainedAdapter : RowAdapter { let first: RowAdapter let second: RowAdapter func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) } } extension Row { /// Creates a row from a base row and a statement adapter convenience init(base: Row, adapter: LayoutedRowAdapter) { self.init(impl: AdapterRowImpl(base: base, adapter: adapter)) } /// Returns self if adapter is nil func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row { guard let adapter = adapter else { return self } return try Row(base: self, adapter: adapter.layoutedAdapter(from: layout)) } } struct AdapterRowImpl : RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping init(base: Row, adapter: LayoutedRowAdapter) { self.base = base self.adapter = adapter self.mapping = adapter.mapping } var count: Int { return mapping.layoutColumns.count } var isFetched: Bool { return base.isFetched } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { return base.value(atIndex: mapping.baseColumnIndex(atMappingIndex: index)) } func dataNoCopy(atUncheckedIndex index:Int) -> Data? { return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index)) } func columnName(atUncheckedIndex index: Int) -> String { return mapping.columnName(atMappingIndex: index) } func index(ofColumn name: String) -> Int? { return mapping.layoutIndex(ofColumn: name) } func scoped(on name: String) -> Row? { guard let adapter = adapter.scopes[name] else { return nil } return Row(base: base, adapter: adapter) } var scopeNames: Set<String> { return Set(adapter.scopes.keys) } func copy(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } }
c83828f8c2da5aee76161eb541c1cf32
34.739899
192
0.640359
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
validation-test/stdlib/OpenCLSDKOverlay.swift
apache-2.0
1
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=macosx // Translated from standard OpenCL hello.c program // Abstract: A simple "Hello World" compute example showing basic usage of OpenCL which // calculates the mathematical square (X[i] = pow(X[i],2)) for a buffer of // floating point values. // // // Version: <1.0> // // Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") // in consideration of your agreement to the following terms, and your use, // installation, modification or redistribution of this Apple software // constitutes acceptance of these terms. If you do not agree with these // terms, please do not use, install, modify or redistribute this Apple // software. // // In consideration of your agreement to abide by the following terms, and // subject to these terms, Apple grants you a personal, non - exclusive // license, under Apple's copyrights in this original Apple software ( the // "Apple Software" ), to use, reproduce, modify and redistribute the Apple // Software, with or without modifications, in source and / or binary forms // provided that if you redistribute the Apple Software in its entirety and // without modifications, you must retain this notice and the following text // and disclaimers in all such redistributions of the Apple Software. Neither // the name, trademarks, service marks or logos of Apple Inc. may be used to // endorse or promote products derived from the Apple Software without specific // prior written permission from Apple. Except as expressly stated in this // notice, no other rights or licenses, express or implied, are granted by // Apple herein, including but not limited to any patent rights that may be // infringed by your derivative works or by other works in which the Apple // Software may be incorporated. // // The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO // WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED // WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION // ALONE OR IN COMBINATION WITH YOUR PRODUCTS. // // IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR // CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION // AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER // UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR // OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright ( C ) 2008 Apple Inc. All Rights Reserved. // import OpenCL import StdlibUnittest import Foundation import Darwin let KernelSource = "\n" + "__kernel void square( \n" + " __global float* input, \n" + " __global float* output, \n" + " const unsigned int count) \n" + "{ \n" + " int i = get_global_id(0); \n" + " if(i < count) \n" + " output[i] = input[i] * input[i]; \n" + "} \n" + "\n" let DATA_SIZE = 1024 var tests = TestSuite("MiscSDKOverlay") tests.test("clSetKernelArgsListAPPLE") { var err: cl_int // error code returned from api calls var data = [Float](count: DATA_SIZE, repeatedValue: 0) // original data set given to device var results = [Float](count: DATA_SIZE, repeatedValue: 0) // results returned from device var correct: Int // number of correct results returned var global: size_t // global domain size for our calculation var local: size_t = 0 // local domain size for our calculation var device_id: cl_device_id = nil // compute device id var context: cl_context // compute context var commands: cl_command_queue // compute command queue var program: cl_program // compute program var kernel: cl_kernel // compute kernel var input: cl_mem // device memory used for the input array var output: cl_mem // device memory used for the output array // Fill our data set with random float values // var i = 0 var count = DATA_SIZE for i = 0; i < count; i++ { data[i] = Float(rand()) / Float(RAND_MAX) } // Connect to a compute device // var gpu = 1 err = clGetDeviceIDs(nil, cl_device_type(gpu != 0 ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU), 1, &device_id, nil) if (err != CL_SUCCESS) { print("Error: Failed to create a device group!") exit(EXIT_FAILURE) } // Create a compute context // context = clCreateContext(nil, 1, &device_id, nil, nil, &err) if (context == nil) { print("Error: Failed to create a compute context!") exit(EXIT_FAILURE) } // Create a command commands // commands = clCreateCommandQueue(context, device_id, 0, &err) if (commands == nil) { print("Error: Failed to create a command commands!") exit(EXIT_FAILURE) } // Create the compute program from the source buffer // program = KernelSource.withCString { (s: UnsafePointer<CChar>)->cl_program in var s = s return withUnsafeMutablePointer(&s) { return clCreateProgramWithSource(context, 1, $0, nil, &err) } } if (program == nil) { print("Error: Failed to create compute program!") exit(EXIT_FAILURE) } // Build the program executable // err = clBuildProgram(program, 0, nil, nil, nil, nil) if (err != CL_SUCCESS) { var len: Int = 0 var buffer = [CChar](count:2048, repeatedValue: 0) print("Error: Failed to build program executable!") clGetProgramBuildInfo( program, device_id, cl_program_build_info(CL_PROGRAM_BUILD_LOG), 2048, &buffer, &len) print("\(String.fromCString(buffer)!)") exit(1) } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, "square", &err) if (kernel == nil || err != cl_int(CL_SUCCESS)) { print("Error: Failed to create compute kernel!") exit(1) } // Create the input and output arrays in device memory for our calculation // input = clCreateBuffer(context, cl_mem_flags(CL_MEM_READ_ONLY), sizeof(Float.self) * count, nil, nil) output = clCreateBuffer(context, cl_mem_flags(CL_MEM_WRITE_ONLY), sizeof(Float.self) * count, nil, nil) if (input == nil || output == nil) { print("Error: Failed to allocate device memory!") exit(1) } // Write our data set into the input array in device memory // err = clEnqueueWriteBuffer(commands, input, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, data, 0, nil, nil) if (err != CL_SUCCESS) { print("Error: Failed to write to source array!") exit(1) } // Set the arguments to our compute kernel // err = 0 err = withUnsafePointers(&input, &output, &count) { inputPtr, outputPtr, countPtr in clSetKernelArgsListAPPLE( kernel, 3, 0, sizeof(cl_mem.self), inputPtr, 1, sizeof(cl_mem.self), outputPtr, 2, sizeofValue(count), countPtr) } if (err != CL_SUCCESS) { print("Error: Failed to set kernel arguments! \(err)") exit(1) } // Get the maximum work group size for executing the kernel on the device // err = clGetKernelWorkGroupInfo(kernel, device_id, cl_kernel_work_group_info(CL_KERNEL_WORK_GROUP_SIZE), sizeofValue(local), &local, nil) if (err != CL_SUCCESS) { print("Error: Failed to retrieve kernel work group info! \(err)") exit(1) } // Execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // global = count err = clEnqueueNDRangeKernel(commands, kernel, 1, nil, &global, &local, 0, nil, nil) if (err != 0) { print("Error: Failed to execute kernel!") exit(EXIT_FAILURE) } // Wait for the command commands to get serviced before reading back results // clFinish(commands) // Read back the results from the device to verify the output // err = clEnqueueReadBuffer( commands, output, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, &results, cl_uint(0), nil, nil ) if (err != CL_SUCCESS) { print("Error: Failed to read output array! \(err)") exit(1) } // Validate our results // correct = 0 for(i = 0; i < count; i++) { if(results[i] == data[i] * data[i]){ correct += 1 } } // Print a brief summary detailing the results // print("Computed '\(correct)/\(count)' correct values!") // Shutdown and cleanup // clReleaseMemObject(input) clReleaseMemObject(output) clReleaseProgram(program) clReleaseKernel(kernel) clReleaseCommandQueue(commands) clReleaseContext(context) } runAllTests()
b6a93dc33f6218add594586d512b1ac6
35.775281
138
0.608209
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/CollectionKit-master/Examples/ReloadDataExample/ReloadDataViewController.swift
mit
1
// // ReloadDataViewController.swift // CollectionKit // // Created by yansong li on 2017-09-04. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit import CollectionKit class ReloadDataViewController: CollectionViewController { let dataProvider = ArrayDataProvider<Int>(data: Array(0..<5)) { (_, data) in return "\(data)" } let addButton: UIButton = { let button = UIButton() button.setTitle("+", for: .normal) button.titleLabel?.font = .boldSystemFont(ofSize: 20) button.backgroundColor = UIColor(hue: 0.6, saturation: 0.68, brightness: 0.98, alpha: 1) button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOffset = CGSize(width: 0, height: -12) button.layer.shadowRadius = 10 button.layer.shadowOpacity = 0.1 return button }() var currentMax: Int = 5 override func viewDidLoad() { super.viewDidLoad() addButton.addTarget(self, action: #selector(add), for: .touchUpInside) view.addSubview(addButton) collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10) let layout = FlowLayout<Int>(lineSpacing: 15, interitemSpacing: 15, justifyContent: .spaceAround, alignItems: .center, alignContent: .center) let presenter = CollectionPresenter() presenter.insertAnimation = .scale presenter.deleteAnimation = .scale presenter.updateAnimation = .normal let provider = CollectionProvider( dataProvider: dataProvider, viewUpdater: { (view: UILabel, data: Int, index: Int) in view.backgroundColor = UIColor(hue: CGFloat(data) / 30, saturation: 0.68, brightness: 0.98, alpha: 1) view.textColor = .white view.textAlignment = .center view.layer.cornerRadius = 4 view.layer.masksToBounds = true view.text = "\(data)" } ) provider.layout = layout provider.sizeProvider = { (index, data, _) in return CGSize(width: 80, height: data % 3 == 0 ? 120 : 80) } provider.presenter = presenter provider.tapHandler = { [weak self] (view, index, _) in self?.dataProvider.data.remove(at: index) } self.provider = provider } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let viewWidth = view.bounds.width let viewHeight = view.bounds.height addButton.frame = CGRect(x: 0, y: viewHeight - 44, width: viewWidth, height: 44) collectionView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight - 44) } @objc func add() { dataProvider.data.append(currentMax) currentMax += 1 // NOTE: Call reloadData() directly will make collectionView update immediately, so that contentSize // of collectionView will be updated. collectionView.reloadData() collectionView.scrollTo(edge: .bottom, animated:true) } }
79b75a141ab1e709aa3fbcedb391a82d
33.303371
104
0.627579
false
false
false
false
SwifterSwift/SwifterSwift
refs/heads/master
Sources/SwifterSwift/UIKit/UITextViewExtensions.swift
mit
1
// UITextViewExtensions.swift - Copyright 2020 SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Methods public extension UITextView { /// SwifterSwift: Clear text. func clear() { text = "" attributedText = NSAttributedString(string: "") } /// SwifterSwift: Scroll to the bottom of text view. func scrollToBottom() { let range = NSRange(location: (text as NSString).length - 1, length: 1) scrollRangeToVisible(range) } /// SwifterSwift: Scroll to the top of text view. func scrollToTop() { let range = NSRange(location: 0, length: 1) scrollRangeToVisible(range) } /// SwifterSwift: Wrap to the content (Text / Attributed Text). func wrapToContent() { contentInset = .zero scrollIndicatorInsets = .zero contentOffset = .zero textContainerInset = .zero textContainer.lineFragmentPadding = 0 sizeToFit() } } #endif
66984a988b0f99fdbcccc6d749824809
24.973684
79
0.632219
false
false
false
false
Khan/swiftz
refs/heads/master
swiftz/TupleExt.swift
bsd-3-clause
2
// // TupleExt.swift // swiftz // // Created by Maxwell Swadling on 7/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation // the standard library has _.1, _.2 functions // these functions are more useful when "doing fp" (point-free-ish forms) public func fst<A, B>(ab: (A, B)) -> A { switch ab { case let (a, _): return a } } public func fst<A, B, C>() -> Lens<(A, C), (B, C), A, B> { return Lens { (x, y) in IxStore(x) { ($0, y) } } } public func snd<A, B>(ab: (A, B)) -> B { switch ab { case let (_, b): return b } } public func snd<A, B, C>() -> Lens<(A, B), (A, C), B, C> { return Lens { (x, y) in IxStore(y) { (x, $0) } } } //Not possible to extend like this currently. //extension () : Equatable {} //extension (T:Equatable, U:Equatable) : Equatable {} public func ==(lhs: (), rhs: ()) -> Bool { return true } public func !=(lhs: (), rhs: ()) -> Bool { return false } // Unlike Python a 1-tuple is just it's contained element. public func == <T:Equatable,U:Equatable>(lhs: (T,U), rhs: (T,U)) -> Bool { let (l0,l1) = lhs let (r0,r1) = rhs return l0 == r0 && l1 == r1 } public func != <T:Equatable,U:Equatable>(lhs: (T,U), rhs: (T,U)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable>(lhs: (T,U,V), rhs: (T,U,V)) -> Bool { let (l0,l1,l2) = lhs let (r0,r1,r2) = rhs return l0 == r0 && l1 == r1 && l2 == r2 } public func != <T:Equatable,U:Equatable,V:Equatable>(lhs: (T,U,V), rhs: (T,U,V)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable>(lhs: (T,U,V,W), rhs: (T,U,V,W)) -> Bool { let (l0,l1,l2,l3) = lhs let (r0,r1,r2,r3) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable>(lhs: (T,U,V,W), rhs: (T,U,V,W)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable>(lhs: (T,U,V,W,X), rhs: (T,U,V,W,X)) -> Bool { let (l0,l1,l2,l3,l4) = lhs let (r0,r1,r2,r3,r4) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 && l4 == r4 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable>(lhs: (T,U,V,W,X), rhs: (T,U,V,W,X)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable,Z:Equatable>(lhs: (T,U,V,W,X,Z), rhs: (T,U,V,W,X,Z)) -> Bool { let (l0,l1,l2,l3,l4,l5) = lhs let (r0,r1,r2,r3,r4,r5) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 && l4 == r4 && l5 == r5 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable,Z:Equatable>(lhs: (T,U,V,W,X,Z), rhs: (T,U,V,W,X,Z)) -> Bool { return !(lhs==rhs) }
cad0ccd052626db9e2e5a889b773e848
30.755814
138
0.576346
false
false
false
false
HuylensHu/realm-cocoa
refs/heads/master
RealmSwift-swift1.2/RealmConfiguration.swift
apache-2.0
3
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private extension Realm { /** A `Configuration` is used to describe the different options used to create a `Realm` instance. */ public struct Configuration { // MARK: Default Configuration /// Returns the default Configuration used to create Realms when no other /// configuration is explicitly specified (i.e. `Realm()`). public static var defaultConfiguration: Configuration { get { return fromRLMRealmConfiguration(RLMRealmConfiguration.defaultConfiguration()) } set { RLMRealmConfiguration.setDefaultConfiguration(newValue.rlmConfiguration) } } // MARK: Initialization /** Initializes a `Configuration`, suitable for creating new `Realm` instances. :param: path The path to the realm file. :param: inMemoryIdentifier A string used to identify a particular in-memory Realm. :param: encryptionKey 64-byte key to use to encrypt the data. :param: readOnly Whether the Realm is read-only (must be true for read-only files). :param: schemaVersion The current schema version. :param: migrationBlock The block which migrates the Realm to the current version. :returns: An initialized `Configuration`. */ public init(path: String? = RLMRealmConfiguration.defaultRealmPath(), inMemoryIdentifier: String? = nil, encryptionKey: NSData? = nil, readOnly: Bool = false, schemaVersion: UInt64 = 0, migrationBlock: MigrationBlock? = nil) { self.path = path self.inMemoryIdentifier = inMemoryIdentifier self.encryptionKey = encryptionKey self.readOnly = readOnly self.schemaVersion = schemaVersion self.migrationBlock = migrationBlock } // MARK: Configuration Properties /// The path to the realm file. /// Mutually exclusive with `inMemoryIdentifier`. public var path: String? { set { if newValue != nil { inMemoryIdentifier = nil } _path = newValue } get { return _path } } private var _path: String? /// A string used to identify a particular in-memory Realm. /// Mutually exclusive with `path`. public var inMemoryIdentifier: String? { set { if newValue != nil { path = nil } _inMemoryIdentifier = newValue } get { return _inMemoryIdentifier } } private var _inMemoryIdentifier: String? = nil /// 64-byte key to use to encrypt the data. public var encryptionKey: NSData? { set { _encryptionKey = RLMRealmValidatedEncryptionKey(newValue) } get { return _encryptionKey } } private var _encryptionKey: NSData? = nil /// Whether the Realm is read-only (must be true for read-only files). public var readOnly: Bool = false /// The current schema version. public var schemaVersion: UInt64 = 0 /// The block which migrates the Realm to the current version. public var migrationBlock: MigrationBlock? = nil // MARK: Private Methods internal var rlmConfiguration: RLMRealmConfiguration { let configuration = RLMRealmConfiguration() configuration.path = self.path configuration.inMemoryIdentifier = self.inMemoryIdentifier configuration.encryptionKey = self.encryptionKey configuration.readOnly = self.readOnly configuration.schemaVersion = self.schemaVersion configuration.migrationBlock = self.migrationBlock.map { accessorMigrationBlock($0) } return configuration } internal static func fromRLMRealmConfiguration(rlmConfiguration: RLMRealmConfiguration) -> Configuration { return Configuration(path: rlmConfiguration.path, inMemoryIdentifier: rlmConfiguration.inMemoryIdentifier, encryptionKey: rlmConfiguration.encryptionKey, readOnly: rlmConfiguration.readOnly, schemaVersion: UInt64(rlmConfiguration.schemaVersion), migrationBlock: map(rlmConfiguration.migrationBlock) { rlmMigration in return { migration, schemaVersion in rlmMigration(migration.rlmMigration, schemaVersion) } }) } } } // MARK: Printable extension Realm.Configuration: Printable { /// Returns a human-readable description of the configuration. public var description: String { return gsub("\\ARLMRealmConfiguration", "Configuration", rlmConfiguration.description) ?? "" } }
b1db9de2addbd2a918cf47feb9a2dffe
34.428571
112
0.61413
false
true
false
false
luanlzsn/pos
refs/heads/master
pos/Classes/pos/Payment/Controller/MergeBillController.swift
mit
1
// // MergeBillController.swift // pos // // Created by luan on 2017/5/30. // Copyright © 2017年 luan. All rights reserved. // import UIKit class MergeBillController: AntController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { @IBOutlet weak var orderNum: UILabel!//订单号 @IBOutlet weak var orderTableView: UITableView!//点单信息 @IBOutlet weak var billTableView: UITableView!//账单信息 @IBOutlet weak var inputLabel: UILabel!//输入 @IBOutlet weak var subTotal: UILabel!//小计 @IBOutlet weak var discountView: UIView!//折扣信息 @IBOutlet weak var discount: UILabel!//折扣 @IBOutlet weak var afterDiscount: UILabel!//折后价 @IBOutlet weak var taxLabel: UILabel!//税率 @IBOutlet weak var taxTop: NSLayoutConstraint! @IBOutlet weak var taxMoney: UILabel!//税额 @IBOutlet weak var total: UILabel!//总计 @IBOutlet weak var receive: UILabel!//收到 @IBOutlet weak var cashMoney: UILabel!//现金 @IBOutlet weak var cardMoney: UILabel!//卡 @IBOutlet weak var remainingTitle: UILabel!//剩余、找零 @IBOutlet weak var remaining: UILabel!//剩余、找零 @IBOutlet weak var tipMoney: UILabel!//小费 @IBOutlet weak var cardBtn: UIButton!//卡按钮 @IBOutlet weak var cashBtn: UIButton!//现金按钮 @IBOutlet weak var calculatorCollection: UICollectionView! var tableNoArray = [Int]() var modelDic = [Int : OrderModel]()//订单信息 var orderItemDic = [Int : [OrderItemModel]]()//已点数组 let calculatorArray = ["1","2","3","4","5","6","7","8","9","0",".","Back",NSLocalizedString("默认", comment: ""),NSLocalizedString("清空", comment: ""),NSLocalizedString("输入", comment: "")] override func viewDidLoad() { super.viewDidLoad() orderTableView.separatorInset = UIEdgeInsets.zero orderTableView.layoutMargins = UIEdgeInsets.zero orderTableView.rowHeight = UITableViewAutomaticDimension orderTableView.estimatedRowHeight = 60 billTableView.rowHeight = UITableViewAutomaticDimension billTableView.estimatedRowHeight = 60 for tableNo in tableNoArray { getOrderInfo(tableNo: tableNo) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() calculatorCollection.reloadData() billTableView.reloadData() } @IBAction func homeClick() { navigationController?.popToRootViewController(animated: true) } // MARK: 获取订单信息 func getOrderInfo(tableNo: Int) { weak var weakSelf = self AntManage.postRequest(path: "tables/getOrderInfoByTable", params: ["table":tableNo, "type":"D", "access_token":AntManage.userModel!.token], successResult: { (response) in weakSelf?.modelDic[tableNo] = OrderModel.mj_object(withKeyValues: response["Order"]) weakSelf?.orderItemDic[tableNo] = OrderItemModel.mj_objectArray(withKeyValuesArray: response["OrderItem"]) as? [OrderItemModel] weakSelf?.refreshOrderInfo() }, failureResult: { weakSelf?.navigationController?.popViewController(animated: true) }) } // MARK: 应用折扣 func discountApple(orderModel: OrderModel) { UIApplication.shared.keyWindow?.endEditing(true) let discount = orderModel.inputDiscount let type = orderModel.inputDiscountType if !discount.isEmpty { weak var weakSelf = self AntManage.postRequest(path: "discountHandler/addDiscount", params: ["order_no":orderModel.order_no, "access_token":AntManage.userModel!.token, "discountType":type, "discountValue":discount, "cashier_id":AntManage.userModel!.cashier_id], successResult: { (_) in weakSelf?.getOrderInfo(tableNo: orderModel.table_no) }, failureResult: {}) } else { AntManage.showDelayToast(message: NSLocalizedString("请输入折扣。", comment: "")) } } // MARK: 删除折扣 func removeDiscount(orderModel: OrderModel) { weak var weakSelf = self AntManage.postRequest(path: "discountHandler/removeDiscount", params: ["order_no":orderModel.order_no, "access_token":AntManage.userModel!.token], successResult: { (_) in weakSelf?.getOrderInfo(tableNo: orderModel.table_no) }, failureResult: {}) } // MARK: 打印收据 @IBAction func printPayBillClick() { var order_ids = [Int]() for model in modelDic.values { order_ids.append(model.orderId) } AntManage.postRequest(path: "print/printMergeBill", params: ["restaurant_id":AntManage.userModel!.restaurant_id, "order_ids":order_ids, "access_token":AntManage.userModel!.token], successResult: { (_) in AntManage.showDelayToast(message: NSLocalizedString("打印收据成功。", comment: "")) }, failureResult: {}) } // MARK: 选择卡支付 @IBAction func cardClick() { cardBtn.isSelected = true cashBtn.isSelected = false cardBtn.backgroundColor = UIColor.init(rgb: 0xC30E22) cashBtn.backgroundColor = UIColor.init(rgb: 0xF4D6D5) inputLabel.text = "" } // MARK: 选择现金支付 @IBAction func cashClick() { cardBtn.isSelected = false cashBtn.isSelected = true cardBtn.backgroundColor = UIColor.init(rgb: 0xF4D6D5) cashBtn.backgroundColor = UIColor.init(rgb: 0xC30E22) inputLabel.text = "" } // MARK: 确认支付 @IBAction func confirmClick() { if !cardBtn.isSelected, !cashBtn.isSelected { AntManage.showDelayToast(message: NSLocalizedString("请选择卡或现金付款方式。", comment: "")) return } if remainingTitle.text == NSLocalizedString("找零", comment: "") { var order_ids = [Int]() var table_merge = "" for model in modelDic.values { order_ids.append(model.orderId) table_merge += "\(model.table_no)," } table_merge.remove(at: table_merge.index(before: table_merge.endIndex)) let main_order_id = modelDic[tableNoArray.first!]!.orderId var params: [String : Any] = ["order_ids":order_ids, "table":tableNoArray.first!, "cashier_id":AntManage.userModel!.cashier_id, "restaurant_id":AntManage.userModel!.restaurant_id, "access_token":AntManage.userModel!.token, "main_order_id":main_order_id, "table_merge":table_merge] params["paid_by"] = cardBtn.isSelected ? "card" : "cash" params["pay"] = receive.text!.components(separatedBy: "$").last! if remaining.text!.components(separatedBy: "$").last! == "0.00" { params["change"] = "" } else { params["change"] = remaining.text!.components(separatedBy: "$").last! } params["card_val"] = cardMoney.text!.components(separatedBy: "$").last! params["cash_val"] = cashMoney.text!.components(separatedBy: "$").last! if tipMoney.text!.components(separatedBy: "$").last! == "0.00" { params["tip_paid_by"] = "" params["tip_val"] = "" } else { params["tip_paid_by"] = "CARD" params["tip_val"] = tipMoney.text!.components(separatedBy: "$").last! } weak var weakSelf = self AntManage.postRequest(path: "payHandler/completeMergeOrder", params: params, successResult: { (_) in weakSelf?.printMergeReceipt(orderIds: order_ids) }, failureResult: {}) } else { AntManage.showDelayToast(message: NSLocalizedString("金额无效,请检查再次验证。", comment: "")) } } func printMergeReceipt(orderIds: [Int]) { weak var weakSelf = self AntManage.postRequest(path: "print/printMergeReceipt", params: ["restaurant_id":AntManage.userModel!.restaurant_id, "order_ids":orderIds, "access_token":AntManage.userModel!.token], successResult: { (_) in weakSelf?.homeClick() }, failureResult: {}) } func refreshOrderInfo() { var orderNo = ""//订单号 var tableNo = ""//餐桌号 var subtotal = 0.0 var tax = 0 var tax_amount = 0.0 var totalFloat = 0.0 var remainingFloat = 0.0 var discount_value = 0.0 var after_discount = 0.0 for tableNumber in tableNoArray { if let orderModel = modelDic[tableNumber] { orderNo += orderModel.order_no + " " subtotal += orderModel.subtotal tax = orderModel.tax tax_amount += orderModel.tax_amount totalFloat += orderModel.total remainingFloat += orderModel.total discount_value += orderModel.discount_value after_discount += orderModel.after_discount } if tableNumber == tableNoArray.first { tableNo += "#\(tableNumber) " + NSLocalizedString("和", comment: "") } else { tableNo += "#\(tableNumber) " } } orderNo.remove(at: orderNo.index(before: orderNo.endIndex)) let orderNumStr = NSLocalizedString("订单号", comment: "") + " \(orderNo)," + NSLocalizedString("桌", comment: "") + "[[\(NSLocalizedString("堂食", comment: ""))]]\(tableNo)" + NSLocalizedString("合并", comment: "") orderNum.text = orderNumStr subTotal.text = "$" + String(format: "%.2f", subtotal) taxLabel.text = NSLocalizedString("税", comment: "") + "(\(tax)%)" taxMoney.text = "$" + String(format: "%.2f", tax_amount) total.text = "$" + String(format: "%.2f", totalFloat) remaining.text = "$" + String(format: "%.2f", remainingFloat) if discount_value > 0 { taxTop.constant = 61 discountView.isHidden = false discount.text = "$" + String(format: "%.2f", discount_value) afterDiscount.text = "$" + String(format: "%.2f", after_discount) } else { taxTop.constant = 0 discountView.isHidden = true } orderTableView.reloadData() billTableView.reloadData() checkReceiveMoney() } // MARK: 处理收到的金额 func checkReceiveMoney() { let card = (cardMoney.text!.components(separatedBy: "$").last! as NSString).doubleValue let cash = (cashMoney.text!.components(separatedBy: "$").last! as NSString).doubleValue receive.text = "$" + String(format: "%.2f", card + cash) let totalDouble = (total.text!.substring(from: total.text!.index(after: total.text!.startIndex)) as NSString).doubleValue let tip = (String(format: "%.2f", card - totalDouble) as NSString).floatValue if tip >= 0 { tipMoney.text = "$" + String(format: "%.2f", fabs(card - totalDouble)) remainingTitle.text = NSLocalizedString("找零", comment: "") remaining.text = "$" + String(format: "%.2f", cash) } else { tipMoney.text = "$0.00" let remainingF = (String(format: "%.2f", card + cash - totalDouble) as NSString).floatValue if remainingF >= 0 { remainingTitle.text = NSLocalizedString("找零", comment: "") remaining.text = "$" + String(format: "%.2f", fabs(card + cash - totalDouble)) } else { remainingTitle.text = NSLocalizedString("剩余", comment: "") remaining.text = "$" + String(format: "%.2f", totalDouble - (card + cash)) } } } // MARK: UITableViewDelegate,UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return tableNoArray.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == orderTableView { if orderItemDic.keys.contains(tableNoArray[section]) { return orderItemDic[tableNoArray[section]]!.count } else { return 0 } } else { if modelDic.keys.contains(tableNoArray[section]) { return 1 } else { return 0 } } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView == orderTableView { return 30 } else { return 0.01 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if tableView == orderTableView { return 0.01 } else { return 10 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView == orderTableView { return tableView.rowHeight } else { let model = modelDic[tableNoArray[indexPath.section]]! if model.discount_value > 0.0 { return 210 } else { if model.isAddDiscount { return 250 } else { return 160 } } } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView == orderTableView { return "#\(tableNoArray[section]) BILL" } else { return nil } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == orderTableView { let cell: PaymentOrderCell = tableView.dequeueReusableCell(withIdentifier: "PaymentOrderCell", for: indexPath) as! PaymentOrderCell let model = orderItemDic[tableNoArray[indexPath.section]]![indexPath.row] cell.nameLabel.text = model.name_en + "\n" + model.name_xh var extrasStr = "" if model.selected_extras.count > 0 { for extras in model.selected_extras { if extras == model.selected_extras.last { extrasStr += extras.name } else { extrasStr += "\(extras.name)," } } } cell.extrasLabel.text = extrasStr if model.qty > 1 { cell.priceLabel.text = "$\(model.price)x\(model.qty)" } else { cell.priceLabel.text = "$\(model.price)" } return cell } else { let cell: MergeBillCell = tableView.dequeueReusableCell(withIdentifier: "MergeBillCell", for: indexPath) as! MergeBillCell let model = modelDic[tableNoArray[indexPath.section]]! cell.refreshOrderBill(model: model) weak var weakSelf = self cell.checkDiscount = { (type) in if (type as! Int) == 1 { if model.discount_value > 0 { weakSelf?.removeDiscount(orderModel: model) } else { model.isAddDiscount = !model.isAddDiscount tableView.reloadData() } } else { weakSelf?.discountApple(orderModel: model) } } return cell } } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = (collectionView.height - 4.0) / 5.0 let width = (collectionView.width - 2.0) / 3.0 return CGSize(width: width, height: height) } // MARK: UICollectionViewDelegate,UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return calculatorArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: CalculatorCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalculatorCell", for: indexPath) as! CalculatorCell cell.calculatorTitle.text = calculatorArray[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if cardBtn.isSelected || cashBtn.isSelected { if indexPath.row <= 9 { inputLabel.text! += calculatorArray[indexPath.row] } else if indexPath.row == 10 { if !inputLabel.text!.contains(calculatorArray[indexPath.row]) { inputLabel.text! += calculatorArray[indexPath.row] } } else if indexPath.row == 11 { if !inputLabel.text!.isEmpty { inputLabel.text!.remove(at: inputLabel.text!.index(before: inputLabel.text!.endIndex)) } } else if indexPath.row == 12 { let totalDouble = (total.text!.substring(from: total.text!.index(after: total.text!.startIndex)) as NSString).doubleValue inputLabel.text = String(format: "%.2f", totalDouble) } else if indexPath.row == 13 { if cardBtn.isSelected { cardMoney.text = NSLocalizedString("卡", comment: "") + ":$0.00" } else { cashMoney.text = NSLocalizedString("现金", comment: "") + ":$0.00" } inputLabel.text = "" checkReceiveMoney() } else if indexPath.row == 14 { if cardBtn.isSelected { cardMoney.text = NSLocalizedString("卡", comment: "") + String(format: ":$%.2f", (inputLabel.text! as NSString).floatValue) } else { cashMoney.text = NSLocalizedString("现金", comment: "") + String(format: ":$%.2f", (inputLabel.text! as NSString).floatValue) } checkReceiveMoney() } } else { AntManage.showDelayToast(message: NSLocalizedString("请选择支付方式 卡/现金。", comment: "")) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
1c310459b4fb706ba57f3b8633e8b4e3
42.765116
292
0.588235
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Mocks/MockOfferingsManager.swift
mit
1
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // MockOfferingsManager.swift // // Created by Juanpe Catalán on 8/8/21. import Foundation @testable import RevenueCat // swiftlint:disable identifier_name // Note: this class is implicitly `@unchecked Sendable` through its parent // even though it's not actually thread safe. class MockOfferingsManager: OfferingsManager { typealias OfferingsCompletion = @MainActor @Sendable (Result<Offerings, Error>) -> Void var invokedOfferings = false var invokedOfferingsCount = 0 var invokedOfferingsParameters: (appUserID: String, fetchPolicy: FetchPolicy, completion: OfferingsCompletion?)? var invokedOfferingsParametersList = [(appUserID: String, fetchPolicy: FetchPolicy, completion: OfferingsCompletion??)]() var stubbedOfferingsCompletionResult: Result<Offerings, Error>? override func offerings(appUserID: String, fetchPolicy: FetchPolicy, completion: (@MainActor @Sendable (Result<Offerings, Error>) -> Void)?) { self.invokedOfferings = true self.invokedOfferingsCount += 1 self.invokedOfferingsParameters = (appUserID, fetchPolicy, completion) self.invokedOfferingsParametersList.append((appUserID, fetchPolicy, completion)) OperationDispatcher.dispatchOnMainActor { [result = self.stubbedOfferingsCompletionResult] in completion?(result!) } } struct InvokedUpdateOfferingsCacheParameters { let appUserID: String let isAppBackgrounded: Bool let fetchPolicy: OfferingsManager.FetchPolicy let completion: (@MainActor @Sendable (Result<Offerings, Error>) -> Void)? } var invokedUpdateOfferingsCache = false var invokedUpdateOfferingsCacheCount = 0 var invokedUpdateOfferingsCacheParameters: InvokedUpdateOfferingsCacheParameters? var invokedUpdateOfferingsCachesParametersList = [InvokedUpdateOfferingsCacheParameters]() var stubbedUpdateOfferingsCompletionResult: Result<Offerings, Error>? override func updateOfferingsCache( appUserID: String, isAppBackgrounded: Bool, fetchPolicy: OfferingsManager.FetchPolicy, completion: (@MainActor @Sendable (Result<Offerings, Error>) -> Void)? ) { self.invokedUpdateOfferingsCache = true self.invokedUpdateOfferingsCacheCount += 1 let parameters = InvokedUpdateOfferingsCacheParameters( appUserID: appUserID, isAppBackgrounded: isAppBackgrounded, fetchPolicy: fetchPolicy, completion: completion ) self.invokedUpdateOfferingsCacheParameters = parameters self.invokedUpdateOfferingsCachesParametersList.append(parameters) OperationDispatcher.dispatchOnMainActor { [result = self.stubbedUpdateOfferingsCompletionResult] in completion?(result!) } } var invokedInvalidateAndReFetchCachedOfferingsIfAppropiate = false var invokedInvalidateAndReFetchCachedOfferingsIfAppropiateCount = 0 var invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParameters: String? var invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParametersList = [String]() override func invalidateAndReFetchCachedOfferingsIfAppropiate(appUserID: String) { invokedInvalidateAndReFetchCachedOfferingsIfAppropiate = true invokedInvalidateAndReFetchCachedOfferingsIfAppropiateCount += 1 invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParameters = appUserID invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParametersList.append(appUserID) } }
f881208872878065be465af12c80a481
40.649485
107
0.713119
false
false
false
false
JGiola/swift
refs/heads/main
test/Distributed/SIL/distributed_actor_default_init_sil_6.swift
apache-2.0
5
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -module-name default_deinit -primary-file %s -emit-sil -verify -disable-availability-checking -I %t | %FileCheck %s --enable-var-scope --dump-input=fail // REQUIRES: concurrency // REQUIRES: distributed /// The convention in this test is that the Swift declaration comes before its FileCheck lines. import Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ---------------------------------------------------------------------------------------------------------------- class SomeClass {} enum Err : Error { case blah } func getSystem() throws -> FakeActorSystem { throw Err.blah } distributed actor MyDistActor { init() throws { self.actorSystem = try getSystem() } // CHECK: sil hidden @$s14default_deinit11MyDistActorCACyKcfc : $@convention(method) (@owned MyDistActor) -> (@owned MyDistActor, @error Error) { // CHECK: bb0([[SELF:%[0-9]+]] : $MyDistActor): // CHECK: builtin "initializeDefaultActor"([[SELF]] : $MyDistActor) // CHECK: try_apply {{%[0-9]+}}() : $@convention(thin) () -> (@owned FakeActorSystem, @error Error), normal [[SUCCESS_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // CHECK: [[SUCCESS_BB]]([[SYSTEM_VAL:%[0-9]+]] : $FakeActorSystem): // *** save system *** // CHECK: [[TP_FIELD1:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.actorSystem // CHECK: store [[SYSTEM_VAL]] to [[TP_FIELD1]] : $*FakeActorSystem // *** obtain an identity *** // CHECK: [[TP_FIELD2:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.actorSystem // CHECK: [[RELOADED_SYS1:%[0-9]+]] = load [[TP_FIELD2]] : $*FakeActorSystem // CHECK: [[SELF_METATYPE:%[0-9]+]] = metatype $@thick MyDistActor.Type // CHECK: [[ASSIGN_ID_FN:%[0-9]+]] = function_ref @$s27FakeDistributedActorSystems0aC6SystemV8assignIDyAA0C7AddressVxm0B00bC0RzAF0G0RtzlF // CHECK: [[ID:%[0-9]+]] = apply [[ASSIGN_ID_FN]]<MyDistActor>([[SELF_METATYPE]], [[RELOADED_SYS1]]) // *** save identity *** // CHECK: [[ID_FIELD:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.id // CHECK: store [[ID]] to [[ID_FIELD]] : $*ActorAddress // *** invoke actorReady *** // CHECK: [[TP_FIELD3:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.actorSystem // CHECK: [[RELOADED_SYS2:%[0-9]+]] = load [[TP_FIELD3]] : $*FakeActorSystem // CHECK: [[READY_FN:%[0-9]+]] = function_ref @$s27FakeDistributedActorSystems0aC6SystemV10actorReadyyyx0B00bC0RzAA0C7AddressV2IDRtzlF // CHECK: = apply [[READY_FN]]<MyDistActor>([[SELF]], [[RELOADED_SYS2]]) // CHECK: return [[SELF]] // CHECK: [[ERROR_BB]]([[ERRVAL:%[0-9]+]] : $Error): // CHECK-NEXT: = metatype $@thick MyDistActor.Type // CHECK-NEXT: = builtin "destroyDefaultActor"([[SELF]] : $MyDistActor) : $() // CHECK-NEXT: dealloc_partial_ref [[SELF]] // CHECK: throw [[ERRVAL]] : $Error // CHECK: } // end sil function '$s14default_deinit11MyDistActorCACyKcfc' }
c574d796743b6cbbb2f7c2a895cd870e
50.369231
222
0.630428
false
false
false
false
Authman2/Pix
refs/heads/0331
CD/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift
apache-2.0
35
// // IQTitleBarButtonItem.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit private var kIQBarTitleInvocationTarget = "kIQBarTitleInvocationTarget" private var kIQBarTitleInvocationSelector = "kIQBarTitleInvocationSelector" open class IQTitleBarButtonItem: IQBarButtonItem { open var font : UIFont? { didSet { if let unwrappedFont = font { _titleButton?.titleLabel?.font = unwrappedFont } else { _titleButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13) } } } override open var title: String? { didSet { _titleButton?.setTitle(title, for: UIControlState()) } } /** selectableTextColor to be used for displaying button text when button is enabled. */ open var selectableTextColor : UIColor? { didSet { if let color = selectableTextColor { _titleButton?.setTitleColor(color, for:UIControlState()) } else { _titleButton?.setTitleColor(UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1), for:UIControlState()) } } } /** Optional target & action to behave toolbar title button as clickable button @param target Target object. @param action Target Selector. */ open func setTitleTarget(_ target: AnyObject?, action: Selector?) { titleInvocation = (target, action) } /** Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method. */ open var titleInvocation : (target: AnyObject?, action: Selector?) { get { let target: AnyObject? = objc_getAssociatedObject(self, &kIQBarTitleInvocationTarget) as AnyObject? var action : Selector? if let selectorString = objc_getAssociatedObject(self, &kIQBarTitleInvocationSelector) as? String { action = NSSelectorFromString(selectorString) } return (target: target, action: action) } set(newValue) { objc_setAssociatedObject(self, &kIQBarTitleInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let unwrappedSelector = newValue.action { objc_setAssociatedObject(self, &kIQBarTitleInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &kIQBarTitleInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } if (newValue.target == nil || newValue.action == nil) { self.isEnabled = false _titleButton?.isEnabled = false _titleButton?.removeTarget(nil, action: nil, for: .touchUpInside) } else { self.isEnabled = true _titleButton?.isEnabled = true _titleButton?.addTarget(newValue.target, action: newValue.action!, for: .touchUpInside) } } } fileprivate var _titleButton : UIButton? fileprivate var _titleView : UIView? override init() { super.init() } init(title : String?) { self.init(title: nil, style: UIBarButtonItemStyle.plain, target: nil, action: nil) _titleView = UIView() _titleView?.backgroundColor = UIColor.clear _titleView?.autoresizingMask = [.flexibleWidth,.flexibleHeight] _titleButton = UIButton(type: .system) _titleButton?.isEnabled = false _titleButton?.titleLabel?.numberOfLines = 3 _titleButton?.setTitleColor(UIColor.lightGray, for:.disabled) _titleButton?.setTitleColor(UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1), for:UIControlState()) _titleButton?.backgroundColor = UIColor.clear _titleButton?.titleLabel?.textAlignment = .center _titleButton?.setTitle(title, for: UIControlState()) _titleButton?.autoresizingMask = [.flexibleWidth,.flexibleHeight] font = UIFont.systemFont(ofSize: 13.0) _titleButton?.titleLabel?.font = self.font _titleView?.addSubview(_titleButton!) customView = _titleView } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
36cd7c536340f17e038e6f3ac6f086a6
38.8125
177
0.64748
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
brave/src/frontend/sync/SyncCodewordsView.swift
mpl-2.0
1
/* 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 Shared class SyncCodewordsView: UIView, UITextViewDelegate { lazy var field: UITextView = { let textView = UITextView() textView.autocapitalizationType = .none textView.autocorrectionType = .yes textView.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightMedium) textView.textColor = BraveUX.GreyJ return textView }() lazy var placeholder: UILabel = { let label = UILabel() label.text = Strings.CodeWordInputHelp label.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular) label.textColor = BraveUX.GreyE label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 return label }() var wordCountChangeCallback: ((_ count: Int) -> Void)? var currentWordCount = 0 convenience init(data: [String]) { self.init() translatesAutoresizingMaskIntoConstraints = false addSubview(field) addSubview(placeholder) setCodewords(data: data) field.snp.makeConstraints { (make) in make.edges.equalTo(self).inset(20) } placeholder.snp.makeConstraints { (make) in make.top.left.right.equalTo(field).inset(UIEdgeInsetsMake(8, 4, 0, 0)) } field.delegate = self } func setCodewords(data: [String]) { field.text = data.count > 0 ? data.joined(separator: " ") : "" updateWordCount() } func codeWords() -> [String] { return field.text.separatedBy(" ").filter { $0.count > 0 } } func wordCount() -> Int { return codeWords().count } func updateWordCount() { placeholder.isHidden = (field.text.count != 0) let wordCount = self.wordCount() if wordCount != currentWordCount { currentWordCount = wordCount wordCountChangeCallback?(wordCount) } } @discardableResult override func becomeFirstResponder() -> Bool { field.becomeFirstResponder() return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return text != "\n" } func textViewDidChange(_ textView: UITextView) { updateWordCount() } }
a3a00ebcf642663382f41f6fb7c3218d
29.447059
198
0.603555
false
false
false
false
ixx1232/FoodTrackerStudy
refs/heads/master
FoodTracker/FoodTracker/MealViewController.swift
mit
1
// // ViewController.swift // FoodTracker // // Created by apple on 15/12/22. // Copyright © 2015年 www.ixx.com. All rights reserved. // import UIKit class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK:Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var ratingControl: RatingControl! @IBOutlet weak var saveButton: UIBarButtonItem! var meal: Meal? override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self if let meal = meal { navigationItem.title = meal.name nameTextField.text = meal.name photoImageView.image = meal.photo ratingControl.rating = meal.rating } checkValidMealName() } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { saveButton.enabled = false } func checkValidMealName() { let text = nameTextField.text ?? "" saveButton.enabled = !text.isEmpty } func textFieldDidEndEditing(textField: UITextField) { checkValidMealName() navigationItem.title = textField.text } // MARK:UIImagePickerControllerDelegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage photoImageView.image = selectedImage dismissViewControllerAnimated(true, completion: nil) } @IBAction func cancel(sender: AnyObject) { let isPresentingInAddMealMode = presentingViewController is UINavigationController if isPresentingInAddMealMode { dismissViewControllerAnimated(true, completion: nil) } else { navigationController!.popViewControllerAnimated(true) } } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if saveButton === sender { let name = nameTextField.text ?? "" let photo = photoImageView.image let rating = ratingControl.rating meal = Meal(name: name, photo: photo, rating: rating) } } // MARK: Actions @IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) { nameTextField.resignFirstResponder() let imagePickerController = UIImagePickerController() imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePickerController.delegate = self presentViewController(imagePickerController, animated: true, completion: nil) } }
a4f361e44bc043d9259cdf4e3805836a
27.277311
130
0.633878
false
false
false
false
omaralbeik/SwifterSwift
refs/heads/master
Sources/Extensions/UIKit/UITableViewExtensions.swift
mit
1
// // UITableViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Properties public extension UITableView { /// SwifterSwift: Index path of last row in tableView. public var indexPathForLastRow: IndexPath? { return indexPathForLastRow(inSection: lastSection) } /// SwifterSwift: Index of last section in tableView. public var lastSection: Int { return numberOfSections > 0 ? numberOfSections - 1 : 0 } } // MARK: - Methods public extension UITableView { /// SwifterSwift: Number of all rows in all sections of tableView. /// /// - Returns: The count of all rows in the tableView. public func numberOfRows() -> Int { var section = 0 var rowCount = 0 while section < numberOfSections { rowCount += numberOfRows(inSection: section) section += 1 } return rowCount } /// SwifterSwift: IndexPath for last row in section. /// /// - Parameter section: section to get last row in. /// - Returns: optional last indexPath for last row in section (if applicable). public func indexPathForLastRow(inSection section: Int) -> IndexPath? { guard section >= 0 else { return nil } guard numberOfRows(inSection: section) > 0 else { return IndexPath(row: 0, section: section) } return IndexPath(row: numberOfRows(inSection: section) - 1, section: section) } /// Reload data with a completion handler. /// /// - Parameter completion: completion handler to run after reloadData finishes. public func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /// SwifterSwift: Remove TableFooterView. public func removeTableFooterView() { tableFooterView = nil } /// SwifterSwift: Remove TableHeaderView. public func removeTableHeaderView() { tableHeaderView = nil } /// SwifterSwift: Scroll to bottom of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). public func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// SwifterSwift: Scroll to top of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). public func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint.zero, animated: animated) } /// SwifterSwift: Dequeue reusable UITableViewCell using class name /// /// - Parameter name: UITableViewCell type /// - Returns: UITableViewCell object with associated class name. public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name))") } return cell } /// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath /// /// - Parameters: /// - name: UITableViewCell type. /// - indexPath: location of cell in tableView. /// - Returns: UITableViewCell object with associated class name. public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name))") } return cell } /// SwifterSwift: Dequeue reusable UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type /// - Returns: UITableViewHeaderFooterView object with associated class name. public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T { guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name))") } return headerFooterView } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameters: /// - nib: Nib file used to create the header or footer view. /// - name: UITableViewHeaderFooterView type. public func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) { register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type public func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) { register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameter name: UITableViewCell type public func register<T: UITableViewCell>(cellWithClass name: T.Type) { register(T.self, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameters: /// - nib: Nib file used to create the tableView cell. /// - name: UITableViewCell type. public func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) { register(nib, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class. /// Assumes that the .xib filename and cell class has the same name. /// /// - Parameters: /// - name: UITableViewCell type. /// - bundleClass: Class in which the Bundle instance will be based on. public func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) { let identifier = String(describing: name) var bundle: Bundle? if let bundleName = bundleClass { bundle = Bundle(for: bundleName) } register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier) } /// SwifterSwift: Check whether IndexPath is valid within the tableView /// /// - Parameter indexPath: An IndexPath to check /// - Returns: Boolean value for valid or invalid IndexPath public func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section) } /// SwifterSwift: Safely scroll to possibly invalid IndexPath /// /// - Parameters: /// - indexPath: Target IndexPath to scroll to /// - scrollPosition: Scroll position /// - animated: Whether to animate or not public func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { guard indexPath.section < numberOfSections else { return } guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return } scrollToRow(at: indexPath, at: scrollPosition, animated: animated) } } #endif
e9bcffc1aa9f6cef4075c8e41758a5f6
38.091837
123
0.670843
false
false
false
false
d-soto11/MaterialTB
refs/heads/master
MaterialTapBar/Helper/Extensions.swift
mit
1
// // Extensions.swift // MaterialTapBar // // Created by Daniel Soto on 9/25/17. // Copyright © 2017 Tres Astronautas. All rights reserved. // import Foundation extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } } extension UIView { func addNormalShadow() { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) self.layer.shadowOpacity = 0.1 self.layer.shadowPath = shadowPath.cgPath } func addInvertedShadow() { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: -2.0) self.layer.shadowOpacity = 0.1 self.layer.shadowPath = shadowPath.cgPath } func addSpecialShadow(size: CGSize, opacitiy: Float = 0.15) { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = size self.layer.shadowOpacity = opacitiy self.layer.shadowPath = shadowPath.cgPath } func addLightShadow() { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) self.layer.shadowOpacity = 0.05 self.layer.shadowPath = shadowPath.cgPath } func clearShadows() { self.layer.shadowOpacity = 0.0 } func roundCorners(radius: CGFloat) { self.layer.cornerRadius = radius self.layer.shadowRadius = radius } func bordered(color:UIColor) { self.layer.borderColor = color.cgColor self.layer.borderWidth = 1.0 } func addInnerShadow() { self.layer.borderColor = UIColor(netHex:0x545454).withAlphaComponent(0.3).cgColor self.layer.borderWidth = 1.0 } } extension NSLayoutConstraint { func setMultiplier(multiplier:CGFloat) -> NSLayoutConstraint { let newConstraint = NSLayoutConstraint( item: firstItem!, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) newConstraint.priority = priority newConstraint.shouldBeArchived = self.shouldBeArchived newConstraint.identifier = self.identifier UIView.animate(withDuration: 0.3) { NSLayoutConstraint.deactivate([self]) NSLayoutConstraint.activate([newConstraint]) } return newConstraint } } extension UIViewController { func canPerformSegue(id: String) -> Bool { let segues = self.value(forKey: "storyboardSegueTemplates") as? [NSObject] let filtered = segues?.filter({ $0.value(forKey: "identifier") as? String == id }) return (filtered?.count ?? 0 > 0) } // Just so you dont have to check all the time func performSpecialSegue(id: String, sender: AnyObject?) -> Void { if canPerformSegue(id: id) { self.performSegue(withIdentifier: id, sender: sender) } } } extension UIImage { func maskWithColor(color: UIColor) -> UIImage? { let maskImage = cgImage! let width = size.width let height = size.height let bounds = CGRect(x: 0, y: 0, width: width, height: height) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! context.clip(to: bounds, mask: maskImage) context.setFillColor(color.cgColor) context.fill(bounds) if let cgImage = context.makeImage() { let coloredImage = UIImage(cgImage: cgImage) return coloredImage } else { return nil } } }
bddc11891a130fd5757a6738b58b23c0
32.258278
172
0.621466
false
false
false
false
AshuMishra/iAppStreetDemo
refs/heads/master
iAppStreet App/Utility/Paginator.swift
mit
1
// // Paginator.swift // iAppStreet App // // Created by Ashutosh Mishra on 19/07/15. // Copyright (c) 2015 Ashutosh Mishra. All rights reserved. // import Foundation import UIKit import IJReachability import Alamofire import SwiftyJSON class Paginator: NSObject { var url: String var parameters: [String:String] private var finalResult: [String] var pageCount = 0 var nextPageToken: NSString? var isCallInProgress:Bool = false var allPagesLoaded:Bool = false typealias RequestCompletionBlock = (result: [String]?, error: NSError?,allPagesLoaded:Bool) -> () init(urlString:NSString,queryParameters:[String:String]?) { url = urlString as String parameters = queryParameters! finalResult = [String]() } func reset() { self.pageCount = 0 self.finalResult = [] } func shouldLoadNext()-> Bool { return !(allPagesLoaded && isCallInProgress) } func loadFirst(completionBlock:RequestCompletionBlock) { //Load the first page of search results var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork() if checkInternetConnection { self.reset() var params = parameters let page = 1 params["page"] = String(page) self.finalResult = [String]() isCallInProgress = false HUDController.sharedController.contentView = HUDContentView.ProgressView() HUDController.sharedController.show() Alamofire.request(.GET, baseURL, parameters: params, encoding: ParameterEncoding.URL).responseJSON { (request, response, data , error) -> Void in if data != nil { let jsonData = JSON(data!) let photos: Array<JSON> = jsonData["photos"].arrayValue for photo in photos { let dict:Dictionary = photo.dictionaryValue var URLString:String = dict["image_url"]!.stringValue self.finalResult.append(URLString) } HUDController.sharedController.hide(animated: true) completionBlock(result: self.finalResult,error: error,allPagesLoaded:false) self.isCallInProgress = false }else { HUDController.sharedController.hide(animated: true) } } }else { // self.showNetworkError() HUDController.sharedController.hide(animated: true) var error = NSError(domain: "Network error", code: 1, userInfo: nil) completionBlock(result: nil, error: error, allPagesLoaded: false) isCallInProgress = false } } func showNetworkError() { UIAlertView(title: "Error", message: "Device is not connected to internet. Please check connection and try again.", delegate: nil, cancelButtonTitle: "OK").show() } func loadNext(completionBlock:RequestCompletionBlock) { if (self.isCallInProgress) {return} var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork() if checkInternetConnection { var params = parameters self.pageCount = self.pageCount + 1 params["page"] = String(self.pageCount) isCallInProgress = true Alamofire.request(.GET, baseURL, parameters: params, encoding: ParameterEncoding.URL).responseJSON { (request, response, data , error) -> Void in let jsonData = JSON(data!) let photos: Array<JSON> = jsonData["photos"].arrayValue for photo in photos { let dict:Dictionary = photo.dictionaryValue var URLString:String = dict["image_url"]!.stringValue self.finalResult.append(URLString) } completionBlock(result: self.finalResult,error: error,allPagesLoaded:false) self.isCallInProgress = false } }else { // self.showNetworkError() completionBlock(result: self.finalResult, error: nil, allPagesLoaded: false) isCallInProgress = false } } }
e02a3a522e1070fe6514bde2c7e6f21c
29.581197
164
0.722952
false
false
false
false
ahayman/RxStream
refs/heads/master
RxStreamTests/ColdTests.swift
mit
1
// // ColdTests.swift // RxStream // // Created by Aaron Hayman on 3/22/17. // Copyright © 2017 Aaron Hayman. All rights reserved. // import XCTest import Rx class ColdTests: XCTestCase { func testRequestSuccess() { var responses = [String]() var errors = [Error]() var terms = [Termination]() let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in response(.success(request + 1)) } let cold = coldTask .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } cold.request(1) XCTAssertEqual(responses, ["2"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) cold.request(2) XCTAssertEqual(responses, ["2", "3"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) cold.request(4) XCTAssertEqual(responses, ["2", "3", "5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["2", "3", "5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) cold.request(5) XCTAssertEqual(responses, ["2", "3", "5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) } func testRequestErrors() { var responses = [String]() var errors = [Error]() var terms = [Termination]() let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in if request % 2 == 0 { response(.success(request + 1)) } else { response(.failure(TestError())) } } let cold = coldTask .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } cold.request(1) XCTAssertEqual(responses, []) XCTAssertEqual(errors.count, 1) XCTAssertEqual(terms, []) cold.request(2) XCTAssertEqual(responses, ["3"]) XCTAssertEqual(errors.count, 1) XCTAssertEqual(terms, []) cold.request(4) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 1) XCTAssertEqual(terms, []) cold.request(7) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 2) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 2) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) cold.request(5) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 2) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) } func testBranchIsolation() { let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in if request % 2 == 0 { response(.success(request + 1)) } else { response(.failure(TestError())) } } var branchAResponses = [String]() var branchAErrors = [Error]() var branchATerms = [Termination]() let branchA = coldTask .map{ "\($0)" } .on{ branchAResponses.append($0) } .onError{ branchAErrors.append($0) } .onTerminate{ branchATerms.append($0) } var branchBResponses = [String]() var branchBErrors = [Error]() var branchBTerms = [Termination]() let branchB = coldTask .map{ "\($0)" } .on{ branchBResponses.append($0) } .onError{ branchBErrors.append($0) } .onTerminate{ branchBTerms.append($0) } branchA.request(2) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 0) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, []) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) branchA.request(3) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, []) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) branchB.request(2) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) branchB.request(3) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, [.completed]) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, [.completed]) } func testBranchSharing() { let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in if request % 2 == 0 { response(.success(request + 1)) } else { response(.failure(TestError())) } } var branchAResponses = [String]() var branchAErrors = [Error]() var branchATerms = [Termination]() coldTask .map{ "\($0)" } .on{ branchAResponses.append($0) } .onError{ branchAErrors.append($0) } .onTerminate{ branchATerms.append($0) } var branchBResponses = [String]() var branchBErrors = [Error]() var branchBTerms = [Termination]() coldTask .map{ "\($0)" } .on{ branchBResponses.append($0) } .onError{ branchBErrors.append($0) } .onTerminate{ branchBTerms.append($0) } coldTask.request(2, share: true) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 0) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) coldTask.request(3, share: true) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, []) coldTask.request(2, share: true) XCTAssertEqual(branchAResponses, ["3", "3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3", "3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, []) coldTask.request(3, share: true) XCTAssertEqual(branchAResponses, ["3", "3"]) XCTAssertEqual(branchAErrors.count, 2) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3", "3"]) XCTAssertEqual(branchBErrors.count, 2) XCTAssertEqual(branchBTerms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(branchAResponses, ["3", "3"]) XCTAssertEqual(branchAErrors.count, 2) XCTAssertEqual(branchATerms, [.completed]) XCTAssertEqual(branchBResponses, ["3", "3"]) XCTAssertEqual(branchBErrors.count, 2) XCTAssertEqual(branchBTerms, [.completed]) } func testRequestMapping() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Double, Double> { _, request, respond in respond(.success(request + 0.5)) } let branch = coldTask .mapRequest{ (request: Int) in return Double(request) } .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["1.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(3) XCTAssertEqual(responses, ["1.5", "3.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(10) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testMultipleEventsFromFlatten() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Int, [String]> { _, request, respond in let responses = (0..<request).map{ "\($0)" } respond(.success(responses)) } let branch = coldTask .flatten() .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["0"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] branch.request(3) XCTAssertEqual(responses, ["0", "1", "2"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] branch.request(10) XCTAssertEqual(responses, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, []) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testTieredMultiEventsUsingFlatten() { var responses = [String]() var tier2 = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Int, [String]> { _, request, respond in let responses = (0..<request).map{ "\($0)" } respond(.success(responses)) } let branch = coldTask .flatten() .on{ responses.append($0) } .flatMap{ return [$0, $0] } .on{ tier2.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["0"]) XCTAssertEqual(tier2, ["0", "0"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] tier2 = [] branch.request(3) XCTAssertEqual(responses, ["0", "1", "2"]) XCTAssertEqual(tier2, ["0", "0", "1", "1", "2", "2"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] tier2 = [] branch.request(10) XCTAssertEqual(responses, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]) XCTAssertEqual(tier2, ["0", "0", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6", "7", "7", "8", "8", "9", "9"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] tier2 = [] coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, []) XCTAssertEqual(tier2, []) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testTaskMultipleResponseBlock() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Double, Double> { _, request, respond in respond(.success(request + 0.5)) respond(.success(request + 100)) // Secondary response should be ignored } let branch = coldTask .mapRequest{ (request: Int) in return Double(request) } .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["1.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(3) XCTAssertEqual(responses, ["1.5", "3.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(10) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testTaskMultipleResponseAsyncBlock() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Double, Double> { _, request, respond in respond(.success(request + 0.5)) respond(.success(request + 100)) // Secondary response should be ignored }.dispatch(.async(on: .main)) let branch = coldTask .mapRequest{ (request: Int) in return Double(request) } .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) wait(for: 0.01) XCTAssertEqual(responses, ["1.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(3) wait(for: 0.01) XCTAssertEqual(responses, ["1.5", "3.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(10) wait(for: 0.01) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) wait(for: 0.01) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } }
505ad7eb7fdcc6a5817887535359033d
29.344444
127
0.616697
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Views/Maps Tab/Map/MapImageSizable.swift
mit
1
// // MapImageSizable.swift // MEGameTracker // // Created by Emily Ivie on 12/29/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit public protocol MapImageSizable: class { var map: Map? { get } var mapImageScrollView: UIScrollView? { get } var mapImageScrollHeightConstraint: NSLayoutConstraint? { get set } var mapImageWrapperView: UIView? { get set } var lastMapImageName: String? { get set } func setupMapImage(baseView: UIView?, competingView: UIView?) func resizeMapImage(baseView: UIView?, competingView: UIView?) } extension MapImageSizable { public func setupMapImage(baseView: UIView?, competingView: UIView?) { guard map?.image?.isEmpty == false, let mapImageWrapperView = mapImageWrapper() else { return } self.mapImageWrapperView = mapImageWrapperView // clean old subviews mapImageScrollView?.subviews.forEach { $0.removeFromSuperview() } // size scrollView mapImageScrollView?.contentSize = mapImageWrapperView.bounds.size mapImageScrollView?.addSubview(mapImageWrapperView) // mapImageWrapperView.fillView(mapImageScrollView) // don't do this! sizeMapImage(baseView: baseView, competingView: competingView) shiftMapImage(baseView: baseView, competingView: competingView) } public func resizeMapImage(baseView: UIView?, competingView: UIView?) { sizeMapImage(baseView: baseView, competingView: competingView) shiftMapImage(baseView: baseView, competingView: competingView) } private func sizeMapImage(baseView: UIView?, competingView: UIView?) { if mapImageScrollHeightConstraint == nil { mapImageScrollHeightConstraint = mapImageScrollView?.superview?.heightAnchor .constraint(equalToConstant: 10000) mapImageScrollHeightConstraint?.isActive = true } else { mapImageScrollHeightConstraint?.constant = 10000 } guard let mapImageScrollView = mapImageScrollView, let mapImageScrollHeightConstraint = mapImageScrollHeightConstraint, let _ = mapImageWrapperView else { return } baseView?.layoutIfNeeded() mapImageScrollView.superview?.isHidden = false let maxHeight = (baseView?.bounds.height ?? 0) - (competingView?.bounds.height ?? 0) mapImageScrollHeightConstraint.constant = maxHeight mapImageScrollView.superview?.layoutIfNeeded() mapImageScrollView.minimumZoomScale = currentImageRatio( baseView: baseView, competingView: competingView ) ?? 0.01 mapImageScrollView.maximumZoomScale = 10 mapImageScrollView.zoomScale = mapImageScrollView.minimumZoomScale } private func mapImageWrapper() -> UIView? { if lastMapImageName == map?.image && self.mapImageWrapperView != nil { return self.mapImageWrapperView } else { // clear out old values self.mapImageWrapperView?.subviews.forEach { $0.removeFromSuperview() } } guard let filename = map?.image, let basePath = Bundle.currentAppBundle.path(forResource: "Maps", ofType: nil), let pdfView = UIPDFView(url: URL(fileURLWithPath: basePath).appendingPathComponent(filename)) else { return nil } let mapImageWrapperView = UIView(frame: pdfView.bounds) mapImageWrapperView.accessibilityIdentifier = "Map Image" mapImageWrapperView.addSubview(pdfView) lastMapImageName = map?.image return mapImageWrapperView } private func shiftMapImage(baseView: UIView?, competingView: UIView?) { guard let mapImageScrollView = mapImageScrollView, let mapImageWrapperView = mapImageWrapperView, let currentImageRatio = currentImageRatio(baseView: baseView, competingView: competingView) else { return } // center in window let differenceX: CGFloat = { let x = mapImageScrollView.bounds.width - (mapImageWrapperView.bounds.width * currentImageRatio) return max(0, x) }() mapImageScrollView.contentInset.left = floor(differenceX / 2) mapImageScrollView.contentInset.right = mapImageScrollView.contentInset.left let differenceY: CGFloat = { let y = mapImageScrollView.bounds.height - (mapImageWrapperView.bounds.height * currentImageRatio) return max(0, y) }() mapImageScrollView.contentInset.top = floor(differenceY / 2) mapImageScrollView.contentInset.bottom = mapImageScrollView.contentInset.top } private func currentImageRatio(baseView: UIView?, competingView: UIView?) -> CGFloat? { guard let mapImageWrapperView = self.mapImageWrapperView, mapImageWrapperView.bounds.height > 0 else { return nil } let maxWidth = baseView?.bounds.width ?? 0 let maxHeight = (baseView?.bounds.height ?? 0) - (competingView?.bounds.height ?? 0) return min(maxWidth / mapImageWrapperView.bounds.width, maxHeight / mapImageWrapperView.bounds.height) } }
047486bb8a7dc98a7a0b57b485648582
36.41129
110
0.764173
false
false
false
false
wibosco/WhiteBoardCodingChallenges
refs/heads/main
WhiteBoardCodingChallenges/Challenges/HackerRank/TimeConverter/TimeConverter.swift
mit
1
// // TimeConverter.swift // WhiteBoardCodingChallenges // // Created by Boles on 07/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //https://www.hackerrank.com/challenges/time-conversion class TimeConverter: NSObject { class func convertFrom12HourTo24HourUsingDateManipulation(time: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm:ssa" let date12 = dateFormatter.date(from: time) dateFormatter.dateFormat = "HH:mm:ss" let date24 = dateFormatter.string(from: date12!) return date24 } }
7994afc4635ed5cb4c56d15728e681a5
24.88
87
0.659969
false
false
false
false
luinily/hOme
refs/heads/master
hOme/UI/SequenceViewController.swift
mit
1
// // SequenceViewController.swift // hOme // // Created by Coldefy Yoann on 2016/02/10. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class SequenceViewController: UITableViewController { @IBOutlet weak var table: UITableView! private let _sectionProperties = 0 private let _sectionCommands = 1 private let _sectionAddCommand = 2 private var _sequence: Sequence? private var _commands = [(time: Int, command: CommandProtocol)]() override func viewDidLoad() { table.delegate = self table.dataSource = self } func setSequence(_ sequence: Sequence) { _sequence = sequence makeSequenceArray(sequence) } func makeSequenceArray(_ sequence: Sequence) { let commands = sequence.getCommands() var sequenceArray = [(time: Int, command: CommandProtocol)]() commands.forEach { (time, commands) in for command in commands { sequenceArray.append((time, command)) } } _commands = sequenceArray } //MARK: - Table Data Source //MARK: Sections override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case _sectionProperties: return 1 case _sectionCommands: return _commands.count case _sectionAddCommand: return 1 default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case _sectionProperties: return "Name" case _sectionCommands: return "Commands" case _sectionAddCommand: return "" default: return "" } } //MARK: Cells override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell? if (indexPath as NSIndexPath).section == _sectionProperties { cell = tableView.dequeueReusableCell(withIdentifier: "SequenceNameCell") if let cell = cell as? NameEditCell { cell.nameAble = _sequence } } else if (indexPath as NSIndexPath).section == _sectionCommands { cell = tableView.dequeueReusableCell(withIdentifier: "SequenceCommandCell") if let cell = cell as? SequenceCommandCell { cell.setCommand(_commands[(indexPath as NSIndexPath).row]) } } else { cell = tableView.dequeueReusableCell(withIdentifier: "AddSequenceCommandCell") if let cell = cell { if let label = cell.textLabel { label.text = "Add New Command..." } } } if let cell = cell { return cell } else { return UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell") } } //MARK: - Table Delegate override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if (indexPath as NSIndexPath).section == _sectionCommands { let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, indexPath in if let cell = tableView.cellForRow(at: indexPath) as? SequenceCommandCell { if let sequence = self._sequence, let command = cell.command { sequence.removeCommand(time: command.time, commandToRemove: command.command) tableView.reloadData() } } } return [delete] } else { return [] } } }
d71dde6009058cae5ee39cfda8855f23
25.15748
121
0.704094
false
false
false
false
PokeMapCommunity/PokeMap-iOS
refs/heads/master
Pods/Moya/Source/Response.swift
mit
2
import Foundation public final class Response: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: NSData public let response: NSURLResponse? public init(statusCode: Int, data: NSData, response: NSURLResponse? = nil) { self.statusCode = statusCode self.data = data self.response = response } public var description: String { return "Status Code: \(statusCode), Data Length: \(data.length)" } public var debugDescription: String { return description } } public func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } public extension Response { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. public func filterStatusCodes(range: ClosedInterval<Int>) throws -> Response { guard range.contains(statusCode) else { throw Error.StatusCode(self) } return self } public func filterStatusCode(code: Int) throws -> Response { return try filterStatusCodes(code...code) } public func filterSuccessfulStatusCodes() throws -> Response { return try filterStatusCodes(200...299) } public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filterStatusCodes(200...399) } /// Maps data received from the signal into a UIImage. func mapImage() throws -> Image { guard let image = Image(data: data) else { throw Error.ImageMapping(self) } return image } /// Maps data received from the signal into a JSON object. func mapJSON() throws -> AnyObject { do { return try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch { throw Error.Underlying(error as NSError) } } /// Maps data received from the signal into a String. func mapString() throws -> String { guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else { throw Error.StringMapping(self) } return string as String } }
6587d6334fab07f58ee6061214b00c9f
29.426667
116
0.645048
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/Blueprints-master/Example-OSX/Common/Extensions/UIEdgeInsetsExtensions.swift
mit
1
import Cocoa extension NSEdgeInsets { init?(top: String?, left: String?, bottom: String?, right: String?) { guard let topSectionInset = CGFloat(top), let leftSectionInset = CGFloat(left), let bottomSectionInset = CGFloat(bottom), let rightSectionInset = CGFloat(right) else { return nil } self = NSEdgeInsets(top: topSectionInset, left: leftSectionInset, bottom: bottomSectionInset, right: rightSectionInset) } }
9ade4170471a5a05670853a2c0e79cd9
29.65
57
0.522023
false
false
false
false
PANDA-Guide/PandaGuideApp
refs/heads/master
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/UIColor+Tweaks.swift
gpl-3.0
1
// // UIColor+Tweaks.swift // SwiftTweaks // // Created by Bryan Clark on 11/16/15. // Copyright © 2015 Khan Academy. All rights reserved. // import UIKit // info via http://arstechnica.com/apple/2009/02/iphone-development-accessing-uicolor-components/ internal extension UIColor { /// Creates a UIColor with a given hex string (e.g. "#FF00FF") // NOTE: Would use a failable init (e.g. `UIColor(hexString: _)` but have to wait until Swift 2.2.1 https://github.com/Khan/SwiftTweaks/issues/38 internal static func colorWithHexString(_ hexString: String) -> UIColor? { // Strip whitespace, "#", "0x", and make uppercase let hexString = hexString .trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) .trimmingCharacters(in: NSCharacterSet(charactersIn: "#") as CharacterSet) .replacingOccurrences(of: "0x", with: "") .uppercased() // We should have 6 or 8 characters now. let hexStringLength = hexString.characters.count if (hexStringLength != 6) && (hexStringLength != 8) { return nil } // Break the string into its components let hexStringContainsAlpha = (hexStringLength == 8) let colorStrings: [String] = [ hexString[hexString.startIndex...hexString.characters.index(hexString.startIndex, offsetBy: 1)], hexString[hexString.characters.index(hexString.startIndex, offsetBy: 2)...hexString.characters.index(hexString.startIndex, offsetBy: 3)], hexString[hexString.characters.index(hexString.startIndex, offsetBy: 4)...hexString.characters.index(hexString.startIndex, offsetBy: 5)], hexStringContainsAlpha ? hexString[hexString.characters.index(hexString.startIndex, offsetBy: 6)...hexString.characters.index(hexString.startIndex, offsetBy: 7)] : "FF" ] // Convert string components into their CGFloat (r,g,b,a) components let colorFloats: [CGFloat] = colorStrings.map { var componentInt: CUnsignedInt = 0 Scanner(string: $0).scanHexInt32(&componentInt) return CGFloat(componentInt) / CGFloat(255.0) } return UIColor(red: colorFloats[0], green: colorFloats[1], blue: colorFloats[2], alpha: colorFloats[3]) } internal convenience init(hex: UInt32, alpha: CGFloat = 1) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat((hex & 0x0000FF)) / 255.0, alpha: alpha ) } internal var alphaValue: CGFloat { var white: CGFloat = 0 var alpha: CGFloat = 0 getWhite(&white, alpha: &alpha) return alpha } internal var hexString: String { assert(canProvideRGBComponents, "Must be an RGB color to use UIColor.hexValue") var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return String(format: "#%02x%02x%02x", arguments: [ Int(red * 255.0), Int(green * 255.0), Int(blue * 255.0) ]).uppercased() } private var canProvideRGBComponents: Bool { switch self.cgColor.colorSpace!.model { case .rgb, .monochrome: return true default: return false } } }
c1f48eb1693cb9bb0aef37a6f614488b
33.055556
171
0.706036
false
false
false
false
open-telemetry/opentelemetry-swift
refs/heads/main
Sources/OpenTelemetrySdk/Metrics/DoubleObserverMetricHandle.swift
apache-2.0
1
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetryApi class DoubleObserverMetricSdk: DoubleObserverMetric { public private(set) var observerHandles = [LabelSet: DoubleObserverMetricHandleSdk]() let metricName: String var callback: (DoubleObserverMetric) -> Void init(metricName: String, callback: @escaping (DoubleObserverMetric) -> Void) { self.metricName = metricName self.callback = callback } func observe(value: Double, labels: [String: String]) { observe(value: value, labelset: LabelSet(labels: labels)) } func observe(value: Double, labelset: LabelSet) { var boundInstrument = observerHandles[labelset] if boundInstrument == nil { boundInstrument = DoubleObserverMetricHandleSdk() observerHandles[labelset] = boundInstrument } boundInstrument?.observe(value: value) } func invokeCallback() { callback(self) } }
bfc904ca2e81a5e86230a95608d448ff
28.428571
89
0.683495
false
false
false
false
therealbnut/PeekSequence
refs/heads/master
PeekSequence.swift
mit
1
// // PeekSequence.swift // PeekSequence // // Created by Andrew Bennett on 26/01/2016. // Copyright © 2016 Andrew Bennett. All rights reserved. // public struct PeekSequence<T>: SequenceType { public typealias Generator = AnyGenerator<T> private var _sequence: AnySequence<T> private var _peek: T? public init<S: SequenceType where S.Generator.Element == T>( _ sequence: S ) { _sequence = AnySequence(sequence) _peek = nil } public func generate() -> AnyGenerator<T> { var peek = _peek, generator = _sequence.generate() return anyGenerator { let element = peek ?? generator.next() peek = nil return element } } public func underestimateCount() -> Int { return _peek == nil ? 0 : 1 } public mutating func peek() -> T? { if let element = _peek { return element } _peek = _sequence.generate().next() return _peek } } public func nonEmptySequence<S: SequenceType>(sequence: S) -> AnySequence<S.Generator.Element>? { var sequence = PeekSequence(sequence) if sequence.peek() != nil { return AnySequence(sequence) } else { return nil } }
3b635346ce38d6e3fd94ea592cb93350
24.346939
97
0.594203
false
false
false
false
AndreaMiotto/NASApp
refs/heads/master
Alamofire-master/Tests/TLSEvaluationTests.swift
apache-2.0
11
// // TLSEvaluationTests.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 Alamofire import Foundation import XCTest private struct TestCertificates { static let rootCA = TestCertificates.certificate(withFileName: "expired.badssl.com-root-ca") static let intermediateCA1 = TestCertificates.certificate(withFileName: "expired.badssl.com-intermediate-ca-1") static let intermediateCA2 = TestCertificates.certificate(withFileName: "expired.badssl.com-intermediate-ca-2") static let leaf = TestCertificates.certificate(withFileName: "expired.badssl.com-leaf") static func certificate(withFileName fileName: String) -> SecCertificate { class Locater {} let filePath = Bundle(for: Locater.self).path(forResource: fileName, ofType: "cer")! let data = try! Data(contentsOf: URL(fileURLWithPath: filePath)) let certificate = SecCertificateCreateWithData(nil, data as CFData)! return certificate } } // MARK: - private struct TestPublicKeys { static let rootCA = TestPublicKeys.publicKey(for: TestCertificates.rootCA) static let intermediateCA1 = TestPublicKeys.publicKey(for: TestCertificates.intermediateCA1) static let intermediateCA2 = TestPublicKeys.publicKey(for: TestCertificates.intermediateCA2) static let leaf = TestPublicKeys.publicKey(for: TestCertificates.leaf) static func publicKey(for certificate: SecCertificate) -> SecKey { let policy = SecPolicyCreateBasicX509() var trust: SecTrust? SecTrustCreateWithCertificates(certificate, policy, &trust) let publicKey = SecTrustCopyPublicKey(trust!)! return publicKey } } // MARK: - class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase { let urlString = "https://expired.badssl.com/" let host = "expired.badssl.com" var configuration: URLSessionConfiguration! // MARK: Setup and Teardown override func setUp() { super.setUp() configuration = URLSessionConfiguration.ephemeral } // MARK: Default Behavior Tests func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() { // Given weak var expectation = self.expectation(description: "\(urlString)") let manager = SessionManager(configuration: configuration) var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error) if let error = error as? URLError { XCTAssertEqual(error.code, .serverCertificateUntrusted) } else if let error = error as? NSError { XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String) XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue)) } else { XCTFail("error should be a URLError or NSError from CFNetwork") } } // MARK: Server Trust Policy - Perform Default Tests func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() { // Given let policies = [host: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } // MARK: Server Trust Policy - Certificate Pinning Tests func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() { // Given let certificates = [TestCertificates.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() { // Given let certificates = [ TestCertificates.leaf, TestCertificates.intermediateCA1, TestCertificates.intermediateCA2, TestCertificates.rootCA ] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.intermediateCA2] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.rootCA] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then #if os(iOS) || os(macOS) if #available(iOS 10.1, macOS 10.12.0, *) { XCTAssertNotNil(error, "error should not be nil") } else { XCTAssertNil(error, "error should be nil") } #else XCTAssertNil(error, "error should be nil") #endif } // MARK: Server Trust Policy - Public Key Pinning Tests func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.intermediateCA2] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.rootCA] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then #if os(iOS) || os(macOS) if #available(iOS 10.1, macOS 10.12.0, *) { XCTAssertNotNil(error, "error should not be nil") } else { XCTAssertNil(error, "error should be nil") } #else XCTAssertNil(error, "error should be nil") #endif } // MARK: Server Trust Policy - Disabling Evaluation Tests func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() { // Given let policies = [host: ServerTrustPolicy.disableEvaluation] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } // MARK: Server Trust Policy - Custom Evaluation Tests func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() { // Given let policies = [ host: ServerTrustPolicy.customEvaluation { _, _ in // Implement a custom evaluation routine here... return true } ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() { // Given let policies = [ host: ServerTrustPolicy.customEvaluation { _, _ in // Implement a custom evaluation routine here... return false } ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } }
836a24fc225495791bb41f90865ab008
33.05104
123
0.636429
false
true
false
false
inacioferrarini/glasgow
refs/heads/master
Glasgow/Classes/CoreData/Stack/CoreDataStack.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 Inácio Ferrarini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import CoreData /** The `Core Data` stack. */ open class CoreDataStack { // MARK: - Properties /** Name of Core Data model file. */ open let modelFileName: String /** Name of Data Base file. */ open let databaseFileName: String /** Bundle where the model is located. */ open let bundle: Bundle? // MARK: - Initialization /** Convenience init. - parameter modelFileName: `Core Data` model file name. - parameter databaseFileName: `Core Data` database file name. */ public convenience init(modelFileName: String, databaseFileName: String) { self.init(modelFileName: modelFileName, databaseFileName: databaseFileName, bundle: nil) } /** Inits the `Core Data` stack. - parameter modelFileName: `Core Data` model file name. - parameter databaseFileName: `Core Data` database file name. - parameter bundle: Bundle where `Core Data` `model file` is located. */ public init(modelFileName: String, databaseFileName: String, bundle: Bundle?) { self.modelFileName = modelFileName self.databaseFileName = databaseFileName self.bundle = bundle } // MARK: - Lazy Helper Properties lazy var applicationDocumentsDirectory: URL? = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls.last }() lazy var managedObjectModel: NSManagedObjectModel? = { var modelURL = Bundle.main.url(forResource: self.modelFileName, withExtension: "momd") if let bundle = self.bundle { modelURL = bundle.url(forResource: self.modelFileName, withExtension: "momd") } guard let url = modelURL else { return nil } return NSManagedObjectModel(contentsOf: url) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { guard let model = self.managedObjectModel else { return nil } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) guard let documentsDirectory = self.applicationDocumentsDirectory else { return nil } let url = documentsDirectory.appendingPathComponent("\(self.databaseFileName).sqlite") var failureReason = "There was an error creating or loading the application's saved data." let isRunningUnitTests = NSClassFromString("XCTest") != nil let storeType = isRunningUnitTests ? NSInMemoryStoreType : NSSQLiteStoreType _ = try? coordinator.addPersistentStore(ofType: storeType, configurationName: nil, at: url, options: nil) return coordinator }() /** The `Core Data` `ManagedObjectContext`. */ open lazy var managedObjectContext: NSManagedObjectContext? = { guard let coordinator = self.persistentStoreCoordinator else { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support /** Saves the `Core Data` context, if there is changes to be saved. ### If you do not want to handle any exception that may happen, you can use: ### ```` try? coreDataStack.saveContext() ```` ### If you want to handle any exception that may happen, you can use: ### ```` do { try coreDataStack.saveContext() } catch let error as NSError { print("Error: \(error)") } ```` */ open func saveContext() throws { guard let managedObjectContext = self.managedObjectContext else { return } if managedObjectContext.hasChanges { try managedObjectContext.save() } } }
ee1eebec947fec2997a179c6f0701483
33.636986
113
0.671544
false
false
false
false
CosmicMind/MaterialKit
refs/heads/master
Sources/iOS/Device.swift
bsd-3-clause
1
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(DeviceModel) public enum DeviceModel: Int { case iPodTouch5 case iPodTouch6 case iPhone4s case iPhone5 case iPhone5c case iPhone5s case iPhone6 case iPhone6Plus case iPhone6s case iPhone6sPlus case iPhone7 case iPhone7Plus case iPhone8 case iPhone8Plus case iPhoneX case iPhoneSE case iPad2 case iPad3 case iPad4 case iPadAir case iPadAir2 case iPadMini case iPadMini2 case iPadMini3 case iPadMini4 case iPadPro case iPadProLarge case iPad5 case iPadPro2 case iPadProLarge2 case iPad6 case simulator case unknown } public struct Device { /// Gets the Device identifier String. public static var identifier: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { (identifier, element) in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier } /// Gets the model name for the device. public static var model: DeviceModel { switch identifier { case "iPod5,1": return .iPodTouch5 case "iPod7,1": return .iPodTouch6 case "iPhone4,1": return .iPhone4s case "iPhone5,1", "iPhone5,2": return .iPhone5 case "iPhone5,3", "iPhone5,4": return .iPhone5c case "iPhone6,1", "iPhone6,2": return .iPhone5s case "iPhone7,2": return .iPhone6 case "iPhone7,1": return .iPhone6Plus case "iPhone8,1": return .iPhone6s case "iPhone8,2": return .iPhone6sPlus case "iPhone8,3", "iPhone8,4": return .iPhoneSE case "iPhone9,1", "iPhone9,3": return .iPhone7 case "iPhone9,2", "iPhone9,4": return .iPhone7Plus case "iPhone10,1", "iPhone10,4": return .iPhone8 case "iPhone10,2", "iPhone10,5": return .iPhone8Plus case "iPhone10,3","iPhone10,6": return .iPhoneX case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad2 case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad3 case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad4 case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir case "iPad5,3", "iPad5,4": return .iPadAir2 case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini2 case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini3 case "iPad5,1", "iPad5,2": return .iPadMini4 case "iPad6,3", "iPad6,4": return .iPadPro case "iPad6,7", "iPad6,8": return .iPadProLarge case "iPad6,11", "iPad6,12": return .iPad5 case "iPad7,3", "iPad7,4": return .iPadPro2 case "iPad7,1", "iPad7,2": return .iPadProLarge2 case "iPad7,5", "iPad7,6": return .iPad6 case "i386", "x86_64": return .simulator default: return .unknown } } /// Retrieves the current device type. public static var userInterfaceIdiom: UIUserInterfaceIdiom { return UIDevice.current.userInterfaceIdiom } } public func ==(lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.rawValue == rhs.rawValue } public func !=(lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.rawValue != rhs.rawValue }
7bbe0bb281bec0ce7db97bbc4497e849
39.42446
88
0.607048
false
false
false
false
mariedm/PermissionPopup
refs/heads/master
PermissionPopup/PermissionPopup.swift
mit
1
// // PermissionPopup.swift // Stwories // // Created by Marie Denis-Massé on 11/11/2016. // Copyright © 2016 Many. All rights reserved. // import UIKit import AVFoundation import Photos import Contacts /*** DELEGATES ***/ protocol DidAskCameraDelegate{ func didAskForCamera(_ granted:Bool) } protocol DidAskMicDelegate{ func didAskForMic(_ granted:Bool) } protocol DidAskLibraryDelegate{ func didAskForLibrary(_ granted:Bool) } protocol DidAskContactsDelegate{ func didAskForContacts(_ granted:Bool) } protocol DidAskNotificationsDelegate{ func didAskForNotifications(_ granted:Bool) } /*** VIEW CONTROLLER ***/ class PermissionPopup:UIViewController{ //outlets @IBOutlet weak var mainImage: UIImageView! @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var noButton: UIButton! @IBOutlet weak var yesButton: UIButton! var popupType=PopupType.camera var micDelegate:DidAskMicDelegate? var camDelegate:DidAskCameraDelegate? var libraryDelegate:DidAskLibraryDelegate? var contactsDelegate:DidAskContactsDelegate? var notifDelegate:DidAskNotificationsDelegate? /*** INIT ***/ class func ofType(_ type:PopupType, from viewController:UIViewController)->PermissionPopup{ let popup=UINib(nibName: "PermissionPopup", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! PermissionPopup popup.popupType=type return popup } override func viewDidLoad(){ super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { initUi() } func initUi(){ mainLabel.text=popupType.mainLabel mainImage.image=popupType.mainImage noButton.setTitle(popupType.no, for: .normal) yesButton.setTitle(popupType.yes, for: .normal) setNeedsStatusBarAppearanceUpdate() } /*** SAID YES ***/ @IBAction func saidYes(_ sender: Any){ //ask autho switch popupType{ case .camera: askForCamera() case .mic: askForMic() case .contacts: askForContacts() case .libraryPickup, .librarySave: askForLibrary() case .notifications: askForNotifications() } } func askForCamera(){ AVCaptureDevice.requestAccess(for: AVMediaType.video){granted in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ weak.camDelegate?.didAskForCamera(granted) } } } } func askForContacts(){ CNContactStore().requestAccess(for: .contacts){granted, error in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ weak.contactsDelegate?.didAskForContacts(granted) } } } } func askForLibrary(){ PHPhotoLibrary.requestAuthorization{status in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ if status==PHAuthorizationStatus.authorized{ weak.libraryDelegate?.didAskForLibrary(true) }else{ weak.libraryDelegate?.didAskForLibrary(false) } } } } } func askForMic(){ AVAudioSession.sharedInstance().requestRecordPermission(){granted in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ weak.micDelegate?.didAskForMic(granted) } } } } func askForNotifications(){ //print("ask_notifs") //notif_api.setup_notifications() close{} } /*** SAID NO ***/ @IBAction func saidNo(_ sender: Any){ switch popupType{ case .camera: close{ self.camDelegate?.didAskForCamera(false) } case .contacts: close{ self.contactsDelegate?.didAskForContacts(false) } case .libraryPickup, .librarySave: close{ self.libraryDelegate?.didAskForLibrary(false) } case .mic: close{ self.micDelegate?.didAskForMic(false) } case .notifications: close{ self.notifDelegate?.didAskForNotifications(false) } } } /*** CLOSE ***/ func close(completion:@escaping ()->()){ UIView.animate(withDuration: 0.2, animations: { self.view.alpha=0 }, completion: {_ in self.dismiss(animated: false, completion: completion) }) } override var prefersStatusBarHidden:Bool{ return true } } /*** AUTHORIZATION TYPES ***/ struct UIConfig{ var main_label:String var image:UIImage var no:String var yes:String } enum PopupType:String{ case camera="camera", mic="mic", libraryPickup="libraryPickup", librarySave="librarySave", contacts="contacts", notifications="notifications" var mainLabel:String{ switch self{ case .camera: return "Activate your camera to take a picture." case .mic: return "Activate your mic to record your voice." case .libraryPickup: return "Give access to your library to pick a nice pic." case .librarySave: return "Give access to your library so that we can save images." case .contacts: return "Share your contacts to invite them." case .notifications: return "Receive notifications to get the best experience." } } var mainImage:UIImage{ switch self{ case .camera: return UIImage(named: "popupCamera")! case .mic: return UIImage(named: "popupMic")! case .libraryPickup, .librarySave: return UIImage(named: "popupLibrary")! case .contacts: return UIImage(named: "popupContacts")! case .notifications: return UIImage(named: "popupNotifications")! } } var no:String{ switch self{ case .camera: return "I'm too shy" case .mic: return "Nope" case .libraryPickup, .librarySave: return "No thanks" case .contacts: return "I stay alone" case .notifications: return "Nevermind" } } var yes:String{ switch self{ case .camera: return "Let's do this" case .mic: return "Alright" case .libraryPickup, .librarySave: return "Lets' go" case .contacts: return "Lets' go" case .notifications: return "Yes, sure!" } } }
6b878a292e74ca6993a078180be58c71
29.087336
145
0.589695
false
false
false
false
lynnleelhl/InfinitePageView
refs/heads/master
InfinitePageView/ViewController.swift
mit
1
// // ViewController.swift // InfinitePageView // // Created by hli on 13/02/2017. // Copyright © 2017 hli. All rights reserved. // import UIKit class CustomView: UIInfinitePageView, UIInfinitePageViewDelegate { override init(frame: CGRect) { super.init(frame: frame) } convenience init() { self.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 250)) self.delegate = self //self.isAutoScroll = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func numberOfViews() -> Int { return 3 } func InfinitePageView(viewForIndexAt index: Int) -> UIView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: "\(index).jpg") return imageView } } class ViewController: UIViewController, UIInfinitePageViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let customView = CustomView() self.view.addSubview(customView) customView.reloadData() let customVerticalView = UIInfinitePageView() customVerticalView.delegate = self customVerticalView.scrollDirection = .vertical customVerticalView.duringTime = 3.0 self.view.addSubview(customVerticalView) customVerticalView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.height.equalTo(32) make.width.equalTo(320) } customVerticalView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // returns the number of pages you have func numberOfViews() -> Int { return 3 } // returns every page in your infinite page view func InfinitePageView(viewForIndexAt index: Int) -> UIView { let label = UILabel() label.textAlignment = .center label.text = "Notice: This is vertical page \(index)" return label } }
5670bd36087b894002547379b19f938b
25.701149
92
0.619027
false
false
false
false
longsirhero/DinDinShop
refs/heads/master
DinDinShopDemo/DinDinShopDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // DinDinShopDemo // // Created by longsirHERO on 2017/8/10. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window?.frame = UIScreen.main.bounds self.window?.rootViewController = WCTabBarController() self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "DinDinShopDemo") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { if #available(iOS 10.0, *) { if persistentContainer.viewContext.hasChanges { do { try persistentContainer.viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } else { // Fallback on earlier versions } } }
5e60be5bc66b231b9bb6debd2fc3a371
48.19802
285
0.676595
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/AssistantV2/Models/RuntimeResponseGenericRuntimeResponseTypeVideo.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2022. * * 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 IBMSwiftSDKCore /** RuntimeResponseGenericRuntimeResponseTypeVideo. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeVideo: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeVideo: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The `https:` URL of the video. */ public var source: String /** The title or introductory text to show before the response. */ public var title: String? /** The description to show with the the response. */ public var description: String? /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? /** For internal use only. */ public var channelOptions: [String: JSON]? /** Descriptive text that can be used for screen readers or other situations where the video cannot be seen. */ public var altText: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case source = "source" case title = "title" case description = "description" case channels = "channels" case channelOptions = "channel_options" case altText = "alt_text" } }
7f3e130bf486144c2068d8267c561daf
29.526316
114
0.693966
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Config/CameraConfiguration.swift
mit
1
// // CameraConfiguration.swift // HXPHPicker // // Created by Slience on 2021/8/30. // import UIKit import AVFoundation // MARK: 相机配置类 public class CameraConfiguration: BaseConfiguration { /// 相机类型 public var cameraType: CameraController.CameraType = .normal /// 相机分辨率 public var sessionPreset: Preset = .hd1280x720 /// 摄像头默认位置 public var position: DevicePosition = .back /// 默认闪光灯模式 public var flashMode: AVCaptureDevice.FlashMode = .auto /// 录制视频时设置的 `AVVideoCodecType` /// iPhone7 以下为 `.h264` public var videoCodecType: AVVideoCodecType = .h264 /// 视频最大录制时长 /// takePhotoMode = .click 支持不限制最大时长 (0 - 不限制) /// takePhotoMode = .press 最小 1 public var videoMaximumDuration: TimeInterval = 60 /// 视频最短录制时长 public var videoMinimumDuration: TimeInterval = 1 /// 拍照方式 public var takePhotoMode: TakePhotoMode = .press /// 主题色 public var tintColor: UIColor = .systemTintColor { didSet { #if HXPICKER_ENABLE_EDITOR setupEditorColor() #endif } } /// 摄像头最大缩放比例 public var videoMaxZoomScale: CGFloat = 6 /// 默认滤镜对应滤镜数组的下标,为 -1 默认不加滤镜 public var defaultFilterIndex: Int = -1 /// 切换滤镜显示名称 public var changeFilterShowName: Bool = true /// 拍照时的滤镜数组,请与 videoFilters 效果保持一致 /// 左滑/右滑切换滤镜 public lazy var photoFilters: [CameraFilter] = [ InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] /// 录制视频的滤镜数组,请与 photoFilters 效果保持一致 /// 左滑/右滑切换滤镜 public lazy var videoFilters: [CameraFilter] = [ InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] #if HXPICKER_ENABLE_EDITOR /// 允许编辑 /// true: 拍摄完成后会跳转到编辑界面 public var allowsEditing: Bool = true /// 照片编辑器配置 public lazy var photoEditor: PhotoEditorConfiguration = .init() /// 视频编辑器配置 public lazy var videoEditor: VideoEditorConfiguration = .init() #endif /// 允许启动定位 public var allowLocation: Bool = true public override init() { super.init() /// shouldAutorotate 能够旋转 /// supportedInterfaceOrientations 支持的方向 /// 隐藏状态栏 prefersStatusBarHidden = true appearanceStyle = .normal #if HXPICKER_ENABLE_EDITOR photoEditor.languageType = languageType videoEditor.languageType = languageType photoEditor.indicatorType = indicatorType videoEditor.indicatorType = indicatorType photoEditor.appearanceStyle = appearanceStyle videoEditor.appearanceStyle = appearanceStyle #endif } #if HXPICKER_ENABLE_EDITOR public override var languageType: LanguageType { didSet { photoEditor.languageType = languageType videoEditor.languageType = languageType } } public override var indicatorType: BaseConfiguration.IndicatorType { didSet { photoEditor.indicatorType = indicatorType videoEditor.indicatorType = indicatorType } } public override var appearanceStyle: AppearanceStyle { didSet { photoEditor.appearanceStyle = appearanceStyle videoEditor.appearanceStyle = appearanceStyle } } #endif } extension CameraConfiguration { public enum DevicePosition { /// 后置 case back /// 前置 case front } public enum TakePhotoMode { /// 长按 case press /// 点击(支持不限制最大时长) case click } public enum Preset { case vga640x480 case iFrame960x540 case hd1280x720 case hd1920x1080 case hd4K3840x2160 var system: AVCaptureSession.Preset { switch self { case .vga640x480: return .vga640x480 case .iFrame960x540: return .iFrame960x540 case .hd1280x720: return .hd1280x720 case .hd1920x1080: return .hd1920x1080 case .hd4K3840x2160: return .hd4K3840x2160 } } var size: CGSize { switch self { case .vga640x480: return CGSize(width: 480, height: 640) case .iFrame960x540: return CGSize(width: 540, height: 960) case .hd1280x720: return CGSize(width: 720, height: 1280) case .hd1920x1080: return CGSize(width: 1080, height: 1920) case .hd4K3840x2160: return CGSize(width: 2160, height: 3840) } } } #if HXPICKER_ENABLE_EDITOR fileprivate func setupEditorColor() { videoEditor.cropConfirmView.finishButtonBackgroundColor = tintColor videoEditor.cropConfirmView.finishButtonDarkBackgroundColor = tintColor videoEditor.cropSize.aspectRatioSelectedColor = tintColor videoEditor.toolView.finishButtonBackgroundColor = tintColor videoEditor.toolView.finishButtonDarkBackgroundColor = tintColor videoEditor.toolView.toolSelectedColor = tintColor videoEditor.toolView.musicSelectedColor = tintColor videoEditor.music.tintColor = tintColor videoEditor.text.tintColor = tintColor videoEditor.filter = .init( infos: videoEditor.filter.infos, selectedColor: tintColor ) photoEditor.toolView.toolSelectedColor = tintColor photoEditor.toolView.finishButtonBackgroundColor = tintColor photoEditor.toolView.finishButtonDarkBackgroundColor = tintColor photoEditor.cropConfimView.finishButtonBackgroundColor = tintColor photoEditor.cropConfimView.finishButtonDarkBackgroundColor = tintColor photoEditor.cropping.aspectRatioSelectedColor = tintColor photoEditor.filter = .init( infos: photoEditor.filter.infos, selectedColor: tintColor ) photoEditor.text.tintColor = tintColor } #endif }
22d7d006899754aa5fe07624b0d024c4
28.393365
79
0.618671
false
false
false
false
atrick/swift
refs/heads/main
test/Generics/unify_protocol_composition.swift
apache-2.0
3
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s class C<T> {} protocol P0 {} protocol P1 { associatedtype T where T == C<U> & P0 associatedtype U } protocol P2 { associatedtype T where T == C<Int> & P0 } // CHECK-LABEL: .P3@ // CHECK-NEXT: Requirement signature: <Self where Self.[P3]T : P1, Self.[P3]T : P2> protocol P3 { associatedtype T : P1 & P2 where T.U == Int }
4932b883b373d479036a20bae5601e52
22.5
135
0.671642
false
false
false
false
voloshynslavik/MVx-Patterns-In-Swift
refs/heads/master
MVX Patterns In Swift/Patterns/MVVM/MVVMViewController.swift
mit
1
// // MVVMViewController.swift // MVX Patterns In Swift // // Created by Yaroslav Voloshyn on 17/07/2017. // import UIKit private let cellId = "500px_image_cell" final class MVVMViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! fileprivate var cachedImages: [String: UIImage] = [:] var viewModel: ViewModel! override func viewDidLoad() { super.viewDidLoad() collectionView.register(UINib(nibName: "ImageCell", bundle: nil), forCellWithReuseIdentifier: cellId) viewModel.loadMoreItems() } } // MARK: - UICollectionViewDataSource extension MVVMViewController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.photosCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? ImageCell else { return UICollectionViewCell() } cell.nameLabel.text = viewModel.getPhotoAuthor(for: indexPath.row) cell.imageView.image = getImage(for: indexPath) return cell } private func getImage(for indexPath: IndexPath) -> UIImage? { let size = collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: indexPath) guard let imageData = viewModel.getPhotoData(for: indexPath.row, width: Int(size.width), height: Int(size.height)) else { return nil } return UIImage(data: imageData) } } // MARK: - UICollectionViewDelegateFlowLayout extension MVVMViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let countOfCollumns: CGFloat = 3 let widthCollectionView = collectionView.frame.width let widthCell = (widthCollectionView - (countOfCollumns - 1.0))/countOfCollumns return CGSize(width: widthCell, height: widthCell) } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { viewModel.stopLoadPhoto(for: indexPath.row, width: Int(cell.frame.width), height: Int(cell.frame.height)) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if (indexPath.row + 1) == viewModel.photosCount { viewModel.loadMoreItems() } } } // MARK: - ViewModelDelegate extension MVVMViewController: ViewModelDelegate { func didLoadingStateChanged(in viewModel: ViewModel, from oldState: Bool, to newState:Bool) { UIApplication.shared.isNetworkActivityIndicatorVisible = newState } func didUpdatedData(in viewModel: ViewModel) { collectionView.reloadData() } func didDownloadPhoto(in viewMode: ViewModel, with index: Int) { let indexPath = IndexPath(row: index, section: 0) collectionView.reloadItems(at: [indexPath]) } }
48d301f2586fa99d2834584799966cd9
33.904255
160
0.721122
false
false
false
false
wwu-pi/md2-framework
refs/heads/master
de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2StringRangeValidator.swift
apache-2.0
1
// // MD2StringRangeValidator.swift // md2-ios-library // // Created by Christoph Rieger on 23.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /** Validator to check for a given string range. */ class MD2StringRangeValidator: MD2Validator { /// Unique identification string. let identifier: MD2String /// Custom message to display. var message: (() -> MD2String)? /// Default message to display. var defaultMessage: MD2String { get { return MD2String("This value must be between \(minLength) and \(maxLength) characters long!") } } /// The minimum allowed length. var minLength: MD2Integer /// The maximum allowed length. var maxLength: MD2Integer /** Default initializer. :param: identifier The unique validator identifier. :param: message Closure of the custom method to display. :param: minLength The minimum length of a valid string. :param: maxLength The maximum langth of a valid string. */ init(identifier: MD2String, message: (() -> MD2String)?, minLength: MD2Integer, maxLength: MD2Integer) { self.identifier = identifier self.message = message self.minLength = minLength self.maxLength = maxLength } /** Validate a value. :param: value The value to check. :return: Validation result */ func isValid(value: MD2Type) -> Bool { if !(value is MD2String) || !((value as! MD2String).isSet()) || !(maxLength.isSet()) { return false } // Set default minimum length if minLength.isSet() == false { minLength.platformValue = 0 } let stringValue = (value as! MD2String).platformValue! if count(stringValue) >= minLength.platformValue! && count(stringValue) <= maxLength.platformValue! { return true } else { return false } } /** Return the message to display on wrong validation. Use custom method if set or else use default message. */ func getMessage() -> MD2String { if let _ = message { return message!() } else { return defaultMessage } } }
3af24d8ebf5586e828e32be039e0454f
26.011236
108
0.573034
false
false
false
false
Pluto-tv/RxSwift
refs/heads/dev
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxDataSourceStarterKit/Changeset.swift
apache-2.0
20
// // Changeset.swift // RxCocoa // // Created by Krunoslav Zaher on 5/30/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import CoreData #if !RX_NO_MODULE import RxSwift import RxCocoa #endif struct ItemPath : CustomStringConvertible { let sectionIndex: Int let itemIndex: Int var description : String { get { return "(\(sectionIndex), \(itemIndex))" } } } public struct Changeset<S: SectionModelType> : CustomStringConvertible { typealias I = S.Item var finalSections: [S] = [] var insertedSections: [Int] = [] var deletedSections: [Int] = [] var movedSections: [(from: Int, to: Int)] = [] var updatedSections: [Int] = [] var insertedItems: [ItemPath] = [] var deletedItems: [ItemPath] = [] var movedItems: [(from: ItemPath, to: ItemPath)] = [] var updatedItems: [ItemPath] = [] public static func initialValue(sections: [S]) -> Changeset<S> { var initialValue = Changeset<S>() initialValue.insertedSections = Array(0 ..< sections.count) initialValue.finalSections = sections return initialValue } public var description : String { get { let serializedSections = "[\n" + finalSections.map { "\($0)" }.joinWithSeparator(",\n") + "\n]\n" return " >> Final sections" + " \n\(serializedSections)" + (insertedSections.count > 0 || deletedSections.count > 0 || movedSections.count > 0 || updatedSections.count > 0 ? "\nSections:" : "") + (insertedSections.count > 0 ? "\ninsertedSections:\n\t\(insertedSections)" : "") + (deletedSections.count > 0 ? "\ndeletedSections:\n\t\(deletedSections)" : "") + (movedSections.count > 0 ? "\nmovedSections:\n\t\(movedSections)" : "") + (updatedSections.count > 0 ? "\nupdatesSections:\n\t\(updatedSections)" : "") + (insertedItems.count > 0 || deletedItems.count > 0 || movedItems.count > 0 || updatedItems.count > 0 ? "\nItems:" : "") + (insertedItems.count > 0 ? "\ninsertedItems:\n\t\(insertedItems)" : "") + (deletedItems.count > 0 ? "\ndeletedItems:\n\t\(deletedItems)" : "") + (movedItems.count > 0 ? "\nmovedItems:\n\t\(movedItems)" : "") + (updatedItems.count > 0 ? "\nupdatedItems:\n\t\(updatedItems)" : "") } } }
63b7b9e48125180bb33241b33fc6c3b7
35.651515
148
0.592807
false
false
false
false
emenegro/space-cells-ios
refs/heads/master
SpaceCells/Sources/Utils/Collectionable.swift
mit
1
import Foundation typealias Section = Int protocol CollectionableViewModelCellConfigurable { associatedtype CollectionableViewModelType: CollectionableViewModel func configure(viewModel: CollectionableViewModelType?) } protocol CollectionableViewModel { func onRowSelected() } protocol Collectionable { associatedtype Item: CollectionableViewModel func items() -> [Section: [Item]]? func numberOfSections() -> Section func numberOfRows(inSection section: Section) -> Int func viewModelForRowAtIndexPath<Item>(indexPath: IndexPath) -> Item? func rowSelectedAtIndexPath(indexPath: IndexPath) } extension Collectionable { func numberOfSections() -> Section { return items()?.count ?? 0 } func numberOfRows(inSection section: Section) -> Int { return items()?[section]?.count ?? 0 } func viewModelForRowAtIndexPath<Item>(indexPath: IndexPath) -> Item? { let sectionItems = items()?[indexPath.section] return sectionItems?[indexPath.row] as? Item } func rowSelectedAtIndexPath(indexPath: IndexPath) { if let viewModel: Item = viewModelForRowAtIndexPath(indexPath: indexPath) { viewModel.onRowSelected() } } } class AnyCollectionable<Item>: Collectionable where Item: CollectionableViewModel { private let _items: (() -> [Section: [Item]]?) private let _numberOfSections: (() -> Section) private let _numberOfRows: ((_ section: Section) -> Int) private let _viewModelForRowAtIndexPath: ((_ indexPath: IndexPath) -> Item?) private let _rowSelectedAtIndexPath: ((_ indexPath: IndexPath) -> Void) init<C: Collectionable>(_ collectionable: C) where C.Item == Item { _items = collectionable.items _numberOfSections = collectionable.numberOfSections _numberOfRows = collectionable.numberOfRows _viewModelForRowAtIndexPath = collectionable.viewModelForRowAtIndexPath _rowSelectedAtIndexPath = collectionable.rowSelectedAtIndexPath } func items() -> [Section: [Item]]? { return _items() } func numberOfSections() -> Section { return _numberOfSections() } func numberOfRows(inSection section: Section) -> Int { return _numberOfRows(section) } func viewModelForRowAtIndexPath<Item>(indexPath: IndexPath) -> Item? { return _viewModelForRowAtIndexPath(indexPath) as? Item } func rowSelectedAtIndexPath(indexPath: IndexPath) { _rowSelectedAtIndexPath(indexPath) } }
652dd4444e2ab89d52f34fde617eacfc
30.91358
83
0.685106
false
false
false
false
tbkka/swift-protobuf
refs/heads/master
Sources/SwiftProtobuf/TimeUtils.swift
apache-2.0
1
// Sources/SwiftProtobuf/TimeUtils.swift - Generally useful time/calendar functions // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Generally useful time/calendar functions and constants /// // ----------------------------------------------------------------------------- let minutesPerDay: Int32 = 1440 let minutesPerHour: Int32 = 60 let secondsPerDay: Int32 = 86400 let secondsPerHour: Int32 = 3600 let secondsPerMinute: Int32 = 60 let nanosPerSecond: Int32 = 1000000000 internal func timeOfDayFromSecondsSince1970(seconds: Int64) -> (hh: Int32, mm: Int32, ss: Int32) { let secondsSinceMidnight = Int32(mod(seconds, Int64(secondsPerDay))) let ss = mod(secondsSinceMidnight, secondsPerMinute) let mm = mod(div(secondsSinceMidnight, secondsPerMinute), minutesPerHour) let hh = Int32(div(secondsSinceMidnight, secondsPerHour)) return (hh: hh, mm: mm, ss: ss) } internal func julianDayNumberFromSecondsSince1970(seconds: Int64) -> Int64 { // January 1, 1970 is Julian Day Number 2440588. // See http://aa.usno.navy.mil/faq/docs/JD_Formula.php return div(seconds + 2440588 * Int64(secondsPerDay), Int64(secondsPerDay)) } internal func gregorianDateFromSecondsSince1970(seconds: Int64) -> (YY: Int32, MM: Int32, DD: Int32) { // The following implements Richards' algorithm (see the Wikipedia article // for "Julian day"). // If you touch this code, please test it exhaustively by playing with // Test_Timestamp.testJSON_range. let JJ = julianDayNumberFromSecondsSince1970(seconds: seconds) let f = JJ + 1401 + div(div(4 * JJ + 274277, 146097) * 3, 4) - 38 let e = 4 * f + 3 let g = Int64(div(mod(e, 1461), 4)) let h = 5 * g + 2 let DD = div(mod(h, 153), 5) + 1 let MM = mod(div(h, 153) + 2, 12) + 1 let YY = div(e, 1461) - 4716 + div(12 + 2 - MM, 12) return (YY: Int32(YY), MM: Int32(MM), DD: Int32(DD)) } internal func nanosToString(nanos: Int32) -> String { if nanos == 0 { return "" } else if nanos % 1000000 == 0 { return ".\(threeDigit(abs(nanos) / 1000000))" } else if nanos % 1000 == 0 { return ".\(sixDigit(abs(nanos) / 1000))" } else { return ".\(nineDigit(abs(nanos)))" } }
72f9bbf78e3bda7cc5b27b27f6274260
37.338462
102
0.637896
false
false
false
false
nodekit-io/nodekit-darwin
refs/heads/master
src/nodekit/NKCore/NKCSocket/NKC_SocketTCP.swift
apache-2.0
1
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /* * Creates _tcp javascript value that inherits from EventEmitter * _tcp.on("connection", function(_tcp)) * _tcp.on("afterConnect", function()) * _tcp.on('data', function(chunk)) * _tcp.on('end') * _tcp.writeBytes(data) * _tcp.fd returns {fd} * _tcp.remoteAddress returns {String addr, int port} * _tcp.localAddress returns {String addr, int port} * _tcp.bind(String addr, int port) * _tcp.listen(int backlog) * _tcp.connect(String addr, int port) * _tcp.close() * */ class NKC_SocketTCP: NSObject, NKScriptExport { // NKScripting class func attachTo(context: NKScriptContext) { context.loadPlugin(NKC_SocketTCP.self, namespace: "io.nodekit.platform.TCP", options: [String:AnyObject]()) } class func rewriteGeneratedStub(stub: String, forKey: String) -> String { switch (forKey) { case ".global": return NKStorage.getPluginWithStub(stub, "lib-core.nkar/lib-core/platform/tcp.js", NKC_SocketTCP.self) default: return stub } } private static let exclusion: Set<String> = { var methods = NKInstanceMethods(forProtocol: NKC_SwiftSocketProtocol.self) return Set<String>(methods.union([ ]).map({selector in return selector.description })) }() class func isExcludedFromScript(selector: String) -> Bool { return exclusion.contains(selector) } class func rewriteScriptNameForKey(name: String) -> String? { return (name == "initWithOptions:" ? "" : nil) } // local variables and init private let connections: NSMutableSet = NSMutableSet() private var _socket: NKC_SwiftSocket? private var _server: NKC_SocketTCP? override init() { self._socket = NKC_SwiftSocket(domain: NKC_DomainAddressFamily.INET, type: NKC_SwiftSocketType.Stream, proto: NKC_CommunicationProtocol.TCP) super.init() self._socket!.setDelegate(self, delegateQueue: NKScriptContextFactory.defaultQueue ) } init(options: AnyObject) { self._socket = NKC_SwiftSocket(domain: NKC_DomainAddressFamily.INET, type: NKC_SwiftSocketType.Stream, proto: NKC_CommunicationProtocol.TCP) super.init() self._socket!.setDelegate(self, delegateQueue: NKScriptContextFactory.defaultQueue ) } init(socket: NKC_SwiftSocket, server: NKC_SocketTCP?) { self._socket = socket self._server = server super.init() } // public methods func bindSync(address: String, port: Int) -> Int { do { try self._socket!.bind(host: address, port: Int32(port)) } catch let error as NKC_Error { print("!Socket Bind Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") return error.associated.value as? Int ?? 500 } catch { fatalError() } return 0 } func connect(address: String, port: Int) -> Void { do { try self._socket!.connect(host: address, port: Int32(port)) } catch let error as NKC_Error { print("!Socket Connect Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func listen(backlog: Int) -> Void { do { try self._socket!.listen(Int32(backlog)) } catch let error as NKC_Error { print("!Socket Connect Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func fdSync() -> Int { return Int(self._socket!.fd) } func remoteAddressSync() -> Dictionary<String, AnyObject> { let address: String = self._socket?.connectedHost ?? "" let port: Int = Int(self._socket?.connectedPort ?? 0) return ["address": address, "port": port] } func localAddressSync() -> Dictionary<String, AnyObject> { let address: String = self._socket!.localHost ?? "" let port: Int = Int(self._socket!.localPort ?? 0) return ["address": address, "port": port] } func writeString(string: String) -> Void { guard let data = NSData(base64EncodedString: string, options: NSDataBase64DecodingOptions(rawValue: 0)) else {return;} do { try self._socket?.write(data) } catch let error as NKC_Error { print("!Socket Send Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func close() -> Void { if (self._socket !== nil) { do { try self._socket!.close() } catch let error as NKC_Error { print("!Socket Close Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } if (self._server !== nil) { self._server!.close() } self._socket = nil self._server = nil } } // DELEGATE METHODS FOR NKC_SwiftSocket extension NKC_SocketTCP: NKC_SwiftSocketProtocol { func socket(socket: NKC_SwiftSocket, didAcceptNewSocket newSocket: NKC_SwiftSocket) { let socketConnection = NKC_SocketTCP(socket: newSocket, server: self) connections.addObject(socketConnection) newSocket.setDelegate(socketConnection, delegateQueue: NKScriptContextFactory.defaultQueue ) self.emitConnection(socketConnection) do { try newSocket.beginReceiving(tag: 1) } catch let error as NKC_Error { print("!Socket Accept Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func socket(socket: NKC_SwiftSocket, didConnectToHost host: String!, port: Int32) { self.emitAfterConnect(host, port: Int(port)) do { try socket.beginReceiving(tag: 1) } catch let error as NKC_Error { print("!Socket Connect Receive Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func socket(socket: NKC_SwiftSocket, didReceiveData data: NSData!, withTag tag: Int) { self.emitData(data) } func socket(socket: NKC_SwiftSocket, didReceiveData data: NSData!, sender host: String?, port: Int32) { self.emitData(data) } func socket(socket: NKC_SwiftSocket, didDisconnectWithError err: NSError) { self._socket = nil self.emitEnd() if (self._server != nil) { self._server!.connectionDidClose(self) } self._server = nil } // private methods private func connectionDidClose(socketConnection: NKC_SocketTCP) { connections.removeObject(socketConnection) } private func emitConnection(tcp: NKC_SocketTCP) -> Void { self.NKscriptObject?.invokeMethod("emit", withArguments: ["connection", tcp], completionHandler: nil) } private func emitAfterConnect(host: String, port: Int) { self.NKscriptObject?.invokeMethod("emit", withArguments:["afterConnect", host, port], completionHandler: nil) } private func emitData(data: NSData!) { let str: NSString! = data.base64EncodedStringWithOptions([]) self.NKscriptObject?.invokeMethod("emit", withArguments: ["data", str], completionHandler: nil) } private func emitEnd() { self.NKscriptObject?.invokeMethod("emit", withArguments: ["end", ""], completionHandler: nil) } }
9e81a421c9d35df094ce12657254f841
33.312253
148
0.604884
false
false
false
false
gregomni/swift
refs/heads/main
test/SILGen/objc_async.swift
apache-2.0
2
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -I %S/Inputs/custom-modules -disable-availability-checking %s -verify | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-cpu %s // REQUIRES: concurrency // REQUIRES: objc_interop import Foundation import ObjCConcurrency // CHECK-LABEL: sil {{.*}}@${{.*}}14testSlowServer func testSlowServer(slowServer: SlowServer) async throws { // CHECK: [[RESUME_BUF:%.*]] = alloc_stack $Int // CHECK: [[STRINGINIT:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : // CHECK: [[ARG:%.*]] = apply [[STRINGINIT]] // CHECK: [[METHOD:%.*]] = objc_method {{.*}} $@convention(objc_method) (NSString, @convention(block) (Int) -> (), SlowServer) -> () // CHECK: [[CONT:%.*]] = get_async_continuation_addr Int, [[RESUME_BUF]] // CHECK: [[WRAPPED:%.*]] = struct $UnsafeContinuation<Int, Never> ([[CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage UnsafeContinuation<Int, Never> // CHECK: [[CONT_SLOT:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK: store [[WRAPPED]] to [trivial] [[CONT_SLOT]] // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[INT_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<Int, Never>, Int) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] {{.*}}, invoke [[BLOCK_IMPL]] // CHECK: apply [[METHOD]]([[ARG]], [[BLOCK]], %0) // CHECK: [[COPY:%.*]] = copy_value [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: await_async_continuation [[CONT]] {{.*}}, resume [[RESUME:bb[0-9]+]] // CHECK: [[RESUME]]: // CHECK: [[RESULT:%.*]] = load [trivial] [[RESUME_BUF]] // CHECK: fix_lifetime [[COPY]] // CHECK: destroy_value [[COPY]] // CHECK: dealloc_stack [[RESUME_BUF]] let _: Int = await slowServer.doSomethingSlow("mail") let _: Int = await slowServer.doSomethingSlowNullably("mail") // CHECK: [[RESUME_BUF:%.*]] = alloc_stack $String // CHECK: [[METHOD:%.*]] = objc_method {{.*}} $@convention(objc_method) (@convention(block) (Optional<NSString>, Optional<NSError>) -> (), SlowServer) -> () // CHECK: [[CONT:%.*]] = get_async_continuation_addr [throws] String, [[RESUME_BUF]] // CHECK: [[WRAPPED:%.*]] = struct $UnsafeContinuation<String, Error> ([[CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage UnsafeContinuation<String, Error> // CHECK: [[CONT_SLOT:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK: store [[WRAPPED]] to [trivial] [[CONT_SLOT]] // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[STRING_COMPLETION_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<String, Error>, Optional<NSString>, Optional<NSError>) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] {{.*}}, invoke [[BLOCK_IMPL]] // CHECK: apply [[METHOD]]([[BLOCK]], %0) // CHECK: await_async_continuation [[CONT]] {{.*}}, resume [[RESUME:bb[0-9]+]], error [[ERROR:bb[0-9]+]] // CHECK: [[RESUME]]: // CHECK: [[RESULT:%.*]] = load [take] [[RESUME_BUF]] // CHECK: destroy_value [[RESULT]] // CHECK: dealloc_stack [[RESUME_BUF]] let _: String = try await slowServer.findAnswer() // CHECK: objc_method {{.*}} $@convention(objc_method) (NSString, @convention(block) () -> (), SlowServer) -> () // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[VOID_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<(), Never>) -> () await slowServer.serverRestart("somewhere") // CHECK: function_ref @[[STRING_NONZERO_FLAG_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<String, Error>, {{.*}}Bool, Optional<NSString>, Optional<NSError>) -> () let _: String = try await slowServer.doSomethingFlaggy() // CHECK: function_ref @[[STRING_ZERO_FLAG_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<String, Error>, Optional<NSString>, {{.*}}Bool, Optional<NSError>) -> () let _: String = try await slowServer.doSomethingZeroFlaggy() // CHECK: function_ref @[[STRING_STRING_ZERO_FLAG_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<(String, String), Error>, {{.*}}Bool, Optional<NSString>, Optional<NSError>, Optional<NSString>) -> () let _: (String, String) = try await slowServer.doSomethingMultiResultFlaggy() // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[NSSTRING_INT_THROW_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<(String, Int), Error>, Optional<NSString>, Int, Optional<NSError>) -> () let (_, _): (String, Int) = try await slowServer.findMultipleAnswers() let (_, _): (Bool, Bool) = try await slowServer.findDifferentlyFlavoredBooleans() // CHECK: [[ERROR]]([[ERROR_VALUE:%.*]] : @owned $Error): // CHECK: dealloc_stack [[RESUME_BUF]] // CHECK: br [[THROWBB:bb[0-9]+]]([[ERROR_VALUE]] // CHECK: [[THROWBB]]([[ERROR_VALUE:%.*]] : @owned $Error): // CHECK: throw [[ERROR_VALUE]] let _: String = await slowServer.findAnswerNullably("foo") let _: String = try await slowServer.doSomethingDangerousNullably("foo") let _: NSObject? = try await slowServer.stopRecording() let _: NSObject = try await slowServer.someObject() let _: () -> Void = await slowServer.performVoid2Void() let _: (Any) -> Void = await slowServer.performId2Void() let _: (Any) -> Any = await slowServer.performId2Id() let _: (String) -> String = await slowServer.performNSString2NSString() let _: ((String) -> String, String) = await slowServer.performNSString2NSStringNSString() let _: ((Any) -> Void, (Any) -> Void) = await slowServer.performId2VoidId2Void() let _: String = try await slowServer.findAnswerFailingly() let _: () -> Void = try await slowServer.obtainClosure() let _: Flavor = try await slowServer.iceCreamFlavor() } func testGeneric<T: AnyObject>(x: GenericObject<T>) async throws { let _: T? = try await x.doSomething() let _: GenericObject<T>? = await x.doAnotherThing() } func testGeneric2<T: AnyObject, U>(x: GenericObject<T>, y: U) async throws { let _: T? = try await x.doSomething() let _: GenericObject<T>? = await x.doAnotherThing() } // CHECK: sil{{.*}}@[[INT_COMPLETION_BLOCK]] // CHECK: [[CONT_ADDR:%.*]] = project_block_storage %0 // CHECK: [[CONT:%.*]] = load [trivial] [[CONT_ADDR]] // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $Int // CHECK: store %1 to [trivial] [[RESULT_BUF]] // CHECK: [[RESUME:%.*]] = function_ref @{{.*}}resumeUnsafeContinuation // CHECK: apply [[RESUME]]<Int>([[CONT]], [[RESULT_BUF]]) // CHECK: sil{{.*}}@[[STRING_COMPLETION_THROW_BLOCK]] // CHECK: [[RESUME_IN:%.*]] = copy_value %1 // CHECK: [[ERROR_IN:%.*]] = copy_value %2 // CHECK: [[CONT_ADDR:%.*]] = project_block_storage %0 // CHECK: [[CONT:%.*]] = load [trivial] [[CONT_ADDR]] // CHECK: [[ERROR_IN_B:%.*]] = begin_borrow [[ERROR_IN]] // CHECK: switch_enum [[ERROR_IN_B]] : {{.*}}, case #Optional.some!enumelt: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[RESUME_BB:bb[0-9]+]] // CHECK: [[RESUME_BB]]: // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $String // CHECK: [[RESUME_CP:%.*]] = copy_value [[RESUME_IN]] // CHECK: [[BRIDGE:%.*]] = function_ref @{{.*}}unconditionallyBridgeFromObjectiveC // CHECK: [[BRIDGED_RESULT:%.*]] = apply [[BRIDGE]]([[RESUME_CP]] // CHECK: store [[BRIDGED_RESULT]] to [init] [[RESULT_BUF]] // CHECK: [[RESUME:%.*]] = function_ref @{{.*}}resumeUnsafeThrowingContinuation // CHECK: apply [[RESUME]]<String>([[CONT]], [[RESULT_BUF]]) // CHECK: br [[END_BB:bb[0-9]+]] // CHECK: [[END_BB]]: // CHECK: return // CHECK: [[ERROR_BB]]([[ERROR_IN_UNWRAPPED:%.*]] : @guaranteed $NSError): // CHECK: [[ERROR:%.*]] = init_existential_ref [[ERROR_IN_UNWRAPPED]] // CHECK: [[RESUME_WITH_ERROR:%.*]] = function_ref @{{.*}}resumeUnsafeThrowingContinuationWithError // CHECK: [[ERROR_COPY:%.*]] = copy_value [[ERROR]] // CHECK: apply [[RESUME_WITH_ERROR]]<String>([[CONT]], [[ERROR_COPY]]) // CHECK: br [[END_BB]] // CHECK: sil {{.*}} @[[VOID_COMPLETION_BLOCK]] // CHECK: [[CONT_ADDR:%.*]] = project_block_storage %0 // CHECK: [[CONT:%.*]] = load [trivial] [[CONT_ADDR]] // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $() // CHECK: [[RESUME:%.*]] = function_ref @{{.*}}resumeUnsafeContinuation // CHECK: apply [[RESUME]]<()>([[CONT]], [[RESULT_BUF]]) // CHECK: sil{{.*}}@[[STRING_NONZERO_FLAG_THROW_BLOCK]] // CHECK: [[ZERO:%.*]] = integer_literal {{.*}}, 0 // CHECK: switch_value {{.*}}, case [[ZERO]]: [[ZERO_BB:bb[0-9]+]], default [[NONZERO_BB:bb[0-9]+]] // CHECK: [[ZERO_BB]]: // CHECK: function_ref{{.*}}33_resumeUnsafeThrowingContinuation // CHECK: [[NONZERO_BB]]: // CHECK: function_ref{{.*}}42_resumeUnsafeThrowingContinuationWithError // CHECK: sil{{.*}}@[[STRING_ZERO_FLAG_THROW_BLOCK]] // CHECK: [[ZERO:%.*]] = integer_literal {{.*}}, 0 // CHECK: switch_value {{.*}}, case [[ZERO]]: [[ZERO_BB:bb[0-9]+]], default [[NONZERO_BB:bb[0-9]+]] // CHECK: [[NONZERO_BB]]: // CHECK: function_ref{{.*}}33_resumeUnsafeThrowingContinuation // CHECK: [[ZERO_BB]]: // CHECK: function_ref{{.*}}42_resumeUnsafeThrowingContinuationWithError // CHECK: sil{{.*}}@[[STRING_STRING_ZERO_FLAG_THROW_BLOCK]] // CHECK: [[ZERO:%.*]] = integer_literal {{.*}}, 0 // CHECK: switch_value {{.*}}, case [[ZERO]]: [[ZERO_BB:bb[0-9]+]], default [[NONZERO_BB:bb[0-9]+]] // CHECK: [[NONZERO_BB]]: // CHECK: function_ref{{.*}}33_resumeUnsafeThrowingContinuation // CHECK: [[ZERO_BB]]: // CHECK: function_ref{{.*}}42_resumeUnsafeThrowingContinuationWithError // CHECK: sil{{.*}}@[[NSSTRING_INT_THROW_COMPLETION_BLOCK]] // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $(String, Int) // CHECK: [[RESULT_0_BUF:%.*]] = tuple_element_addr [[RESULT_BUF]] {{.*}}, 0 // CHECK: [[BRIDGE:%.*]] = function_ref @{{.*}}unconditionallyBridgeFromObjectiveC // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE]] // CHECK: store [[BRIDGED]] to [init] [[RESULT_0_BUF]] // CHECK: [[RESULT_1_BUF:%.*]] = tuple_element_addr [[RESULT_BUF]] {{.*}}, 1 // CHECK: store %2 to [trivial] [[RESULT_1_BUF]] // CHECK-LABEL: sil {{.*}}@${{.*}}22testSlowServerFromMain @MainActor func testSlowServerFromMain(slowServer: SlowServer) async throws { // CHECK: hop_to_executor %6 : $MainActor // CHECK: [[RESUME_BUF:%.*]] = alloc_stack $Int // CHECK: [[STRINGINIT:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : // CHECK: [[ARG:%.*]] = apply [[STRINGINIT]] // CHECK: [[METHOD:%.*]] = objc_method {{.*}} $@convention(objc_method) (NSString, @convention(block) (Int) -> (), SlowServer) -> () // CHECK: [[CONT:%.*]] = get_async_continuation_addr Int, [[RESUME_BUF]] // CHECK: [[WRAPPED:%.*]] = struct $UnsafeContinuation<Int, Never> ([[CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage UnsafeContinuation<Int, Never> // CHECK: [[CONT_SLOT:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK: store [[WRAPPED]] to [trivial] [[CONT_SLOT]] // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[INT_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<Int, Never>, Int) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] {{.*}}, invoke [[BLOCK_IMPL]] // CHECK: apply [[METHOD]]([[ARG]], [[BLOCK]], %0) // CHECK: [[COPY:%.*]] = copy_value [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: await_async_continuation [[CONT]] {{.*}}, resume [[RESUME:bb[0-9]+]] // CHECK: [[RESUME]]: // CHECK: [[RESULT:%.*]] = load [trivial] [[RESUME_BUF]] // CHECK: hop_to_executor %6 : $MainActor // CHECK: fix_lifetime [[COPY]] // CHECK: destroy_value [[COPY]] // CHECK: dealloc_stack [[RESUME_BUF]] let _: Int = await slowServer.doSomethingSlow("mail") } // CHECK-LABEL: sil {{.*}}@${{.*}}26testThrowingMethodFromMain @MainActor func testThrowingMethodFromMain(slowServer: SlowServer) async -> String { // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $String // CHECK: [[STRING_ARG:%.*]] = apply {{%.*}}({{%.*}}) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: [[METH:%.*]] = objc_method {{%.*}} : $SlowServer, #SlowServer.doSomethingDangerous!foreign // CHECK: [[RAW_CONT:%.*]] = get_async_continuation_addr [throws] String, [[RESULT_BUF]] : $*String // CHECK: [[CONT:%.*]] = struct $UnsafeContinuation<String, Error> ([[RAW_CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[STORE_ALLOC:%.*]] = alloc_stack $@block_storage UnsafeContinuation<String, Error> // CHECK: [[PROJECTED:%.*]] = project_block_storage [[STORE_ALLOC]] : $*@block_storage // CHECK: store [[CONT]] to [trivial] [[PROJECTED]] : $*UnsafeContinuation<String, Error> // CHECK: [[INVOKER:%.*]] = function_ref @$sSo8NSStringCSgSo7NSErrorCSgIeyByy_SSTz_ // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[STORE_ALLOC]] {{.*}}, invoke [[INVOKER]] // CHECK: [[OPTIONAL_BLK:%.*]] = enum {{.*}}, #Optional.some!enumelt, [[BLOCK]] // CHECK: %28 = apply [[METH]]([[STRING_ARG]], [[OPTIONAL_BLK]], {{%.*}}) : $@convention(objc_method) (NSString, Optional<@convention(block) (Optional<NSString>, Optional<NSError>) -> ()>, SlowServer) -> () // CHECK: [[STRING_ARG_COPY:%.*]] = copy_value [[STRING_ARG]] : $NSString // CHECK: dealloc_stack [[STORE_ALLOC]] : $*@block_storage UnsafeContinuation<String, Error> // CHECK: destroy_value [[STRING_ARG]] : $NSString // CHECK: await_async_continuation [[RAW_CONT]] : $Builtin.RawUnsafeContinuation, resume [[RESUME:bb[0-9]+]], error [[ERROR:bb[0-9]+]] // CHECK: [[RESUME]] // CHECK: {{.*}} = load [take] [[RESULT_BUF]] : $*String // CHECK: hop_to_executor {{%.*}} : $MainActor // CHECK: fix_lifetime [[STRING_ARG_COPY]] : $NSString // CHECK: destroy_value [[STRING_ARG_COPY]] : $NSString // CHECK: dealloc_stack [[RESULT_BUF]] : $*String // CHECK: [[ERROR]] // CHECK: hop_to_executor {{%.*}} : $MainActor // CHECK: fix_lifetime [[STRING_ARG_COPY]] : $NSString // CHECK: destroy_value [[STRING_ARG_COPY]] : $NSString // CHECK: dealloc_stack [[RESULT_BUF]] : $*String do { return try await slowServer.doSomethingDangerous("run-with-scissors") } catch { return "none" } }
fc00f40c8907bac359a28e5c16a2082e
57.917695
241
0.627226
false
false
false
false
Esri/tips-and-tricks-ios
refs/heads/master
DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/SimulatedLocation/SimulatedLocationVC.swift
apache-2.0
1
// Copyright 2015 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class SimulatedLocationVC: UIViewController { @IBOutlet var mapView: AGSMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let mapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer") let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl); self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer") } @IBAction func startSimulation(sender: AnyObject) { // get the path to our GPX file let gpxPath = NSBundle.mainBundle().pathForResource("toughmudder2012", ofType: "gpx") // create our data source let gpxLDS = AGSGPXLocationDisplayDataSource(path: gpxPath) // tell the AGSLocationDisplay to use our data source self.mapView.locationDisplay.dataSource = gpxLDS; // enter nav mode so we can play it back oriented in the same way we would be if it // were happening "live" self.mapView.locationDisplay.autoPanMode = .Default; // we have to start the datasource in order to play it back self.mapView.locationDisplay.startDataSource() } @IBAction func stopSimulation(sender: AnyObject) { self.mapView.locationDisplay.stopDataSource() } }
869cc3fd4f279127021860a19b09136b
35.481481
115
0.687817
false
false
false
false
teaxus/TSAppEninge
refs/heads/master
Source/Tools/InformationManage/DateManage.swift
mit
1
// // DateManage.swift // TSAppEngine // // Created by teaxus on 15/12/7. // Copyright © 2015年 teaxus. All rights reserved. // import Foundation extension Date{ public func changeDateToLocalData(date:Date)->Date{ let zone = NSTimeZone.system let interval = zone.secondsFromGMT(for: date) return date.addingTimeInterval(Double(interval)) } public var age:String{ // 出生日期转换 年月日 var set_calendar = Set<Calendar.Component>() set_calendar.insert(Calendar.Component.year) set_calendar.insert(Calendar.Component.month) set_calendar.insert(Calendar.Component.day) let components1 = Calendar.current.dateComponents(set_calendar, from: self) let brithDateYear = components1.year! let brithDateDay = components1.day! let brithDateMonth = components1.month! let components2 = Calendar.current.dateComponents(set_calendar, from: Date()) let currentDateYear = components2.year! let currentDateDay = components2.day! let currentDateMonth = components2.month! // 计算年龄 var iAge = currentDateYear - brithDateYear - 1; if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) { iAge += 1 } return "\(iAge)" } //两个时间相差的 public func deltaDay(day:NSDate) -> DateComponents{ let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let unit = NSCalendar.Unit(rawValue: NSCalendar.Unit.day.rawValue | NSCalendar.Unit.hour.rawValue | NSCalendar.Unit.minute.rawValue | NSCalendar.Unit.second.rawValue) // return calendar.components(unit, from: self, to: day as Date, options: .WrapComponents) return calendar.components(unit, from: self, to: day as Date, options: NSCalendar.Options.wrapComponents) } public func dateWithformatter(string_formatter:String)->String{ let formatter = DateFormatter() formatter.dateFormat = string_formatter return formatter.string(from: self as Date) } } extension Double{ public var toDate:NSDate{ return NSDate(timeIntervalSince1970: self) } }
d07ddaafb6b9541fe7804fff53c8d640
28.3
124
0.647611
false
false
false
false
madoffox/Stretching
refs/heads/master
Stretching/Stretching/AppDelegate.swift
mit
1
// // AppDelegate.swift // Stretching // // Created by Admin on 16.12.16. // Copyright © 2016 Admin. All rights reserved. // import UIKit import CoreData @available(iOS 10.0, *) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Stretching") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
88900e4a00f8df75871a2be6c06fdd2a
47.578947
285
0.684074
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/PopTipTransitionAnimation.swift
mit
1
// // PopTipTransitionAnimation.swift // TransitionTreasury // // Created by DianQK on 12/29/15. // Copyright © 2016 TransitionTreasury. All rights reserved. // import UIKit //import TransitionTreasury /// Pop Your Tip ViewController. public class PopTipTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning { public var transitionStatus: TransitionStatus public var transitionContext: UIViewControllerContextTransitioning? public var cancelPop: Bool = false public var interacting: Bool = false private var mainVC: UIViewController? lazy private var tapGestureRecognizer: UITapGestureRecognizer = { let tap = UITapGestureRecognizer(target: self, action: #selector(PopTipTransitionAnimation.tapDismiss(_:))) return tap }() lazy private var maskView: UIView = { let view = UIView() view.backgroundColor = UIColor.black return view }() public private(set) var visibleHeight: CGFloat private let bounce: Bool public init(visibleHeight height: CGFloat, bounce: Bool = false, status: TransitionStatus = .present) { transitionStatus = status visibleHeight = height self.bounce = bounce super.init() } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext var fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) var toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containView = transitionContext.containerView let screenBounds = UIScreen.main.bounds var startFrame = screenBounds.offsetBy(dx: 0, dy: screenBounds.size.height) var finalFrame = screenBounds.offsetBy(dx: 0, dy: screenBounds.height - visibleHeight) var startOpacity: CGFloat = 0 var finalOpacity: CGFloat = 0.3 containView.addSubview(fromVC!.view) if transitionStatus == .dismiss { swap(&fromVC, &toVC) swap(&startFrame, &finalFrame) swap(&startOpacity, &finalOpacity) } else if transitionStatus == .present { let bottomView = UIView(frame: screenBounds) bottomView.layer.contents = { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(fromVC!.view.bounds.size, true, scale) fromVC!.view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image?.cgImage }() bottomView.addGestureRecognizer(tapGestureRecognizer) containView.addSubview(bottomView) maskView.frame = screenBounds maskView.alpha = startOpacity bottomView.addSubview(maskView) mainVC = fromVC } toVC?.view.layer.frame = startFrame containView.addSubview(toVC!.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: (bounce ? 0.8 : 1), initialSpringVelocity: (bounce ? 0.6 : 1), options: .curveEaseInOut, animations: { toVC?.view.layer.frame = finalFrame self.maskView.alpha = finalOpacity }) { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } func tapDismiss(_ tap: UITapGestureRecognizer) { mainVC?.presentedViewController?.transitioningDelegate = nil mainVC?.dismiss(animated: true, completion: nil) } }
3d2e1da143c30ab6784c9dc8589bd179
37.009524
219
0.662741
false
false
false
false
PerfectlySoft/Perfect-Authentication
refs/heads/master
Sources/LocalAuthentication/Schema/AccessToken.swift
apache-2.0
1
// // AccessToken.swift // Perfect-OAuth2-Server // // Created by Jonathan Guthrie on 2017-02-06. // // import StORM import PostgresStORM import Foundation import SwiftRandom import SwiftMoment public class AccessToken: PostgresStORM { public var accesstoken = "" public var refreshtoken = "" public var userid = "" public var expires = 0 public var scope = "" var _rand = URandom() public override init(){} public init(userid u: String, expiration: Int, scope s: [String] = [String]()) { accesstoken = _rand.secureToken refreshtoken = _rand.secureToken userid = u let th = moment() expires = Int(th.epoch()) + (expiration * 1000) scope = s.isEmpty ? "" : s.joined(separator: " ") } override public func to(_ this: StORMRow) { accesstoken = this.data["accesstoken"] as? String ?? "" refreshtoken = this.data["refreshtoken"] as? String ?? "" userid = this.data["userid"] as? String ?? "" expires = this.data["expires"] as? Int ?? 0 scope = this.data["scope"] as? String ?? "" } func rows() -> [AccessToken] { var rows = [AccessToken]() for i in 0..<self.results.rows.count { let row = AccessToken() row.to(self.results.rows[i]) rows.append(row) } return rows } }
c4ae645ae229372b657455e020adb0d0
22.54717
81
0.645032
false
false
false
false
atomkirk/TouchForms
refs/heads/master
TouchForms/Source/MessageChildFormCell.swift
mit
1
// // MessageChildFormCell.swift // TouchForms // // Created by Adam Kirk on 7/25/15. // Copyright (c) 2015 Adam Kirk. All rights reserved. // import Foundation private let red = UIColor(red: 215.0/255.0, green: 0, blue: 0, alpha: 1) private let green = UIColor(red: 0, green: 215.0/255.0, blue: 0, alpha: 1) class MessageChildFormCell: FormCell { var type: ChildFormElementType = .Loading @IBOutlet weak var messageLabel: UILabel! override func layoutSubviews() { super.layoutSubviews() switch type { case .Error: messageLabel.textColor = red case .ValidationError: messageLabel.textColor = red case .Success: messageLabel.textColor = green default: messageLabel.textColor = UIColor.blackColor() } } override func drawRect(rect: CGRect) { super.drawRect(rect) if type == .Error { let point1 = CGPointMake(20, (self.frame.size.height / 2.0) - 5) let point2 = CGPointMake(30, (self.frame.size.height / 2.0) + 5) let point3 = CGPointMake(20, (self.frame.size.height / 2.0) + 5) let point4 = CGPointMake(30, (self.frame.size.height / 2.0) - 5) let path = UIBezierPath() path.moveToPoint(point1) path.addLineToPoint(point2) path.moveToPoint(point3) path.addLineToPoint(point4) red.setStroke() path.stroke(); } else if type == .ValidationError { let point1 = CGPointMake(25, self.frame.size.height / 2.0) let point2 = CGPointMake(20, point1.y) let point3 = CGPointMake(point2.x, 0) let path = UIBezierPath() path.moveToPoint(point1) path.addLineToPoint(point2) path.addLineToPoint(point3) red.setStroke() path.stroke() } else if type == .Success { let point1 = CGPointMake(22, (self.frame.size.height / 2.0)) let point2 = CGPointMake(point1.x + 4, point1.y + 5) let point3 = CGPointMake(point2.x + 4, point2.y - 12) let path = UIBezierPath() path.moveToPoint(point1) path.addLineToPoint(point2) path.addLineToPoint(point3) green.setStroke() path.stroke() } } }
54628a87616797a09861c2c3d1a2819e
31.876712
76
0.571488
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 3 - Alien Adventure 1/Strings/Strings_Recap.playground/Pages/What are Strings made of_ .xcplaygroundpage/Contents.swift
mit
1
//: ## What are Strings made of? import UIKit //: ### Defining variables and constants using string literals let monkeyString = "I saw a monkey." let thiefString = "He stole my iPhone." //: ### Emojis in Strings var monkeyStringWithEmoji = "I saw a 🐒." var thiefStringWithEmoji = "He stole my 📱." //: ### The characters property of the String struct let gString = "Gary's giraffe gobbled gooseberries greedily" var count = 0 for character in gString.characters { if character == "g" || character == "G" { count += 1 } } //: [Next](@next)
ea1acab2dc6129047a4350043934a6bb
23.347826
62
0.666071
false
false
false
false
glassonion1/R9MIDISequencer
refs/heads/master
Sources/R9MIDISequencer/Sequencer.swift
mit
1
// // Sequencer.swift // R9MIDISequencer // // Created by Taisuke Fujita on 2016/02/03. // Copyright © 2016年 Taisuke Fujita. All rights reserved. // import AVFoundation import CoreMIDI import AudioToolbox @available(iOS 9.0, *) @available(OSX 10.11, *) open class Sequencer { let callBack: @convention(c) (UnsafeMutableRawPointer?, MusicSequence, MusicTrack, MusicTimeStamp, UnsafePointer<MusicEventUserData>, MusicTimeStamp, MusicTimeStamp) -> Void = { (obj, seq, mt, timestamp, userData, timestamp2, timestamp3) in // Cタイプ関数なのでselfを使えません unowned let mySelf: Sequencer = unsafeBitCast(obj, to: Sequencer.self) if mySelf.enableLooping { return } OperationQueue.main.addOperation({ mySelf.delegate?.midiSequenceDidFinish() if let player = mySelf.musicPlayer { MusicPlayerSetTime(player, 0) } }) } var musicSequence: MusicSequence? var musicPlayer: MusicPlayer? var midiClient = MIDIClientRef() var midiDestination = MIDIEndpointRef() public private(set) var lengthInSeconds: TimeInterval = 0.0 // Beats Per Minute public private(set) var bpm: TimeInterval = 0.0 weak public var delegate: MIDIMessageListener? public var enableLooping = false public var currentPositionInSeconds: TimeInterval { get { guard let player = musicPlayer else { return 0.0 } var time: MusicTimeStamp = 0.0 MusicPlayerGetTime(player, &time) return time } } public init() { var result = OSStatus(noErr) result = NewMusicPlayer(&musicPlayer) if result != OSStatus(noErr) { print("error creating player : \(result)") return } let destinationCount = MIDIGetNumberOfDestinations() print("DestinationCount: \(destinationCount)") result = MIDIClientCreateWithBlock("MIDI Client" as CFString, &midiClient) { midiNotification in print(midiNotification) } if result != OSStatus(noErr) { print("error creating client : \(result)") } Thread.sleep(forTimeInterval: 0.2) // スリープを入れないとDestinationのコールバックが呼ばれない createMIDIDestination() } deinit { stop() if let player = musicPlayer { DisposeMusicPlayer(player) } MIDIEndpointDispose(midiDestination) MIDIClientDispose(midiClient) } public func loadMIDIURL(_ midiFileUrl: URL) { // 再生中だったら止める stop() var result = NewMusicSequence(&musicSequence) guard let sequence = musicSequence else { print("error creating sequence : \(result)") return } // MIDIファイルの読み込み MusicSequenceFileLoad(sequence, midiFileUrl as CFURL, .midiType, MusicSequenceLoadFlags.smf_ChannelsToTracks) // bpmの取得 MusicSequenceGetBeatsForSeconds(sequence, 60, &bpm) // シーケンサにEndPointをセットする // trackが決まってからセットしないとだめ result = MusicSequenceSetMIDIEndpoint(sequence, midiDestination); if result != OSStatus(noErr) { print("error creating endpoint : \(result)") } var musicTrack: MusicTrack? = nil var sequenceLength: MusicTimeStamp = 0 var trackCount: UInt32 = 0 MusicSequenceGetTrackCount(sequence, &trackCount) for i in 0 ..< trackCount { var trackLength: MusicTimeStamp = 0 var trackLengthSize: UInt32 = 0 MusicSequenceGetIndTrack(sequence, i, &musicTrack) MusicTrackGetProperty(musicTrack!, kSequenceTrackProperty_TrackLength, &trackLength, &trackLengthSize) if sequenceLength < trackLength { sequenceLength = trackLength } if enableLooping { var loopInfo = MusicTrackLoopInfo(loopDuration: trackLength, numberOfLoops: 0) let lisize: UInt32 = 0 let status = MusicTrackSetProperty(musicTrack!, kSequenceTrackProperty_LoopInfo, &loopInfo, lisize ) if status != OSStatus(noErr) { print("Error setting loopinfo on track \(status)") } } } lengthInSeconds = sequenceLength // 曲の最後にコールバックを仕込む result = MusicSequenceSetUserCallback(sequence, callBack, unsafeBitCast(self, to: UnsafeMutableRawPointer.self)) if result != OSStatus(noErr) { print("error set user callback : \(result)") } let userData: UnsafeMutablePointer<MusicEventUserData> = UnsafeMutablePointer.allocate(capacity: 1) result = MusicTrackNewUserEvent(musicTrack!, sequenceLength, userData) if result != OSStatus(noErr) { print("error new user event : \(result)") } } public func play() { guard let sequence = musicSequence else { return } guard let player = musicPlayer else { return } MusicPlayerSetSequence(player, sequence) MusicPlayerPreroll(player) MusicPlayerStart(player) } public func playWithMIDIURL(_ midiFileUrl: URL) { loadMIDIURL(midiFileUrl) play() } public func stop() { if let sequence = musicSequence { DisposeMusicSequence(sequence) } if let player = musicPlayer { MusicPlayerStop(player) MusicPlayerSetTime(player, 0) } } public func addMIDINoteEvent(trackNumber: UInt32, noteNumber: UInt8, velocity: UInt8, position: MusicTimeStamp, duration: Float32, channel: UInt8 = 0) { guard let sequence = musicSequence else { return } var musicTrack: MusicTrack? = nil var result = MusicSequenceGetIndTrack(sequence, trackNumber, &musicTrack) if result != OSStatus(noErr) { print("error get track index: \(trackNumber) \(result)") } guard let track = musicTrack else { return } var message = MIDINoteMessage(channel: channel, note: noteNumber, velocity: velocity, releaseVelocity: 0, duration: duration) result = MusicTrackNewMIDINoteEvent(track, position, &message) if result != OSStatus(noErr) { print("error creating midi note event \(result)") } } private func createMIDIDestination() { /// This block will be method then memory leak /// @see https://github.com/genedelisa/Swift2MIDI/blob/master/Swift2MIDI/ViewController.swift /// - parameter packet: パケットデータ let handleMIDIMessage = { [weak self] (packet: MIDIPacket) in guard let localSelf = self else { return } let status = UInt8(packet.data.0) let d1 = UInt8(packet.data.1) let d2 = UInt8(packet.data.2) let rawStatus = status & 0xF0 // without channel let channel = UInt8(status & 0x0F) switch rawStatus { case 0x80, 0x90: // weak delegateにしないとメモリリークする OperationQueue.main.addOperation({ [weak delegate = localSelf.delegate] in if rawStatus == 0x90 { delegate?.midiNoteOn(d1, velocity: d2, channel: channel) } else { delegate?.midiNoteOff(d1, channel: channel) } }) case 0xA0: print("Polyphonic Key Pressure (Aftertouch). Channel \(channel) note \(d1) pressure \(d2)") case 0xB0: print("Control Change. Channel \(channel) controller \(d1) value \(d2)") case 0xC0: print("Program Change. Channel \(channel) program \(d1)") case 0xD0: print("Channel Pressure (Aftertouch). Channel \(channel) pressure \(d1)") case 0xE0: print("Pitch Bend Change. Channel \(channel) lsb \(d1) msb \(d2)") default: print("Unhandled message \(status)") } } var result = OSStatus(noErr) let name = R9Constants.midiDestinationName as CFString result = MIDIDestinationCreateWithBlock(midiClient, name, &midiDestination) { (packetList, srcConnRefCon) in let packets = packetList.pointee let packet: MIDIPacket = packets.packet var packetPtr: UnsafeMutablePointer<MIDIPacket> = UnsafeMutablePointer.allocate(capacity: 1) packetPtr.initialize(to: packet) for _ in 0 ..< packets.numPackets { handleMIDIMessage(packetPtr.pointee) packetPtr = MIDIPacketNext(packetPtr) } } if result != OSStatus(noErr) { print("error creating destination : \(result)") } } }
9cdd4394e8b6cee7bc351ab922737da6
34.734848
181
0.569112
false
false
false
false
adriankrupa/swift3D
refs/heads/master
Source/Vector.swift
mit
1
// // Created by Adrian Krupa on 30.11.2015. // Copyright (c) 2015 Adrian Krupa. All rights reserved. // import Foundation import simd public extension float3 { public init(_ v: float4) { self.init(v.x, v.y, v.z) } } public extension float4 { public init(_ v: float3, _ vw: Float) { self.init() x = v.x y = v.y z = v.z w = vw } public init(_ v: float3) { self.init() x = v.x y = v.y z = v.z w = 0 } public init(_ q: quat) { self.init() x = q.x y = q.y z = q.z w = q.w } } public extension double3 { public init(_ v: double4) { self.init(v.x, v.y, v.z) } } public extension double4 { public init(_ v: double3, _ vw: Double) { self.init() x = v.x y = v.y z = v.z w = vw } public init(_ v: double3) { self.init() x = v.x y = v.y z = v.z w = 0 } public init(_ q: dquat) { self.init() x = q.x y = q.y z = q.z w = q.w } } public func ==(a: float4, b: float4) -> Bool { for i in 0..<4 { if(a[i] != b[i]) { return false } } return true } public func !=(a: float4, b: float4) -> Bool { return !(a==b) } public func ==(a: float3, b: float3) -> Bool { for i in 0..<3 { if(a[i] != b[i]) { return false } } return true } public func !=(a: float3, b: float3) -> Bool { return !(a==b) } public func ==(a: float2, b: float2) -> Bool { for i in 0..<2 { if(a[i] != b[i]) { return false } } return true } public func !=(a: float2, b: float2) -> Bool { return !(a==b) } public func ==(a: double4, b: double4) -> Bool { for i in 0..<4 { if(a[i] != b[i]) { return false } } return true } public func !=(a: double4, b: double4) -> Bool { return !(a==b) } public func ==(a: double3, b: double3) -> Bool { for i in 0..<3 { if(a[i] != b[i]) { return false } } return true } public func !=(a: double3, b: double3) -> Bool { return !(a==b) } public func ==(a: double2, b: double2) -> Bool { for i in 0..<2 { if(a[i] != b[i]) { return false } } return true } public func !=(a: double2, b: double2) -> Bool { return !(a==b) }
9a72469baec5e21b3a77d6efcbc52979
15.581699
56
0.428628
false
false
false
false
drewag/Swiftlier
refs/heads/master
Sources/Swiftlier/Errors/GenericSwiftlierError.swift
mit
1
// // GenericSwiftlierError.swift // Swiftlier // // Created by Andrew J Wagner on 7/30/19. // import Foundation /// Basic codable implementation of SwiftlierError public struct GenericSwiftlierError: SwiftlierError { public let title: String public let alertMessage: String public let details: String? public let isInternal: Bool public let backtrace: [String]? public let extraInfo: [String:String] public var description: String { return "\(self.title): \(self.alertMessage)" } public init(title: String, alertMessage: String, details: String?, isInternal: Bool, backtrace: [String]? = Thread.callStackSymbols, extraInfo: [String:String] = [:]) { self.title = title self.alertMessage = alertMessage self.details = details self.isInternal = isInternal self.backtrace = backtrace self.extraInfo = extraInfo } public init<E: SwiftlierError>(_ error: E) { self.title = error.title self.alertMessage = error.alertMessage self.details = error.details self.isInternal = error.isInternal self.backtrace = error.backtrace self.extraInfo = error.getExtraInfo() } public init(while operation: String, reason: String, details: String? = nil, backtrace: [String]? = Thread.callStackSymbols, extraInfo: [String:String] = [:]) { self.title = "Error \(operation.titleCased)" self.alertMessage = "Internal Error. Please try again. If the problem persists please contact support with the following description: \(reason)" self.details = details self.isInternal = true self.backtrace = backtrace self.extraInfo = extraInfo } public init(userErrorWhile operation: String, reason: String, details: String? = nil, backtrace: [String]? = Thread.callStackSymbols, extraInfo: [String:String] = [:]) { self.title = "Error \(operation.titleCased)" self.alertMessage = reason self.details = details self.isInternal = false self.backtrace = backtrace self.extraInfo = extraInfo } public init(_ doing: String, because: String, byUser: Bool = false) { self.title = "Error \(doing.titleCased)" if byUser { self.isInternal = false self.alertMessage = because } else { self.alertMessage = "Internal Error. Please try again. If the problem persists please contact support with the following description: \(because)" self.isInternal = true } self.details = nil self.backtrace = Thread.callStackSymbols self.extraInfo = [:] } public func getExtraInfo() -> [String : String] { return self.extraInfo } } extension GenericSwiftlierError: Codable { enum CodingKeys: String, CodingKey { // Core case title, alertMessage, details, isInternal, backtrace, extraInfo // ReportableError backwards compatability case doing, because, perpitrator, message } struct VariableKey: CodingKey { let stringValue: String let intValue: Int? init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } init?(intValue: Int) { return nil } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let title = try container.decodeIfPresent(String.self, forKey: .title) { // Current Swiftlier Error self.title = title self.alertMessage = try container.decode(String.self, forKey: .alertMessage) self.isInternal = try container.decode(Bool.self, forKey: .isInternal) self.details = try container.decodeIfPresent(String.self, forKey: .details) } else { // ReportableError backwards capatability let perpetrator = try container.decode(String.self, forKey: .perpitrator) let doing = try container.decode(String.self, forKey: .doing) let reason = try container.decode(String.self, forKey: .because) self.title = "Error \(doing.capitalized)" if perpetrator == "system" { self.alertMessage = "Internal Error. Please try again. If the problem persists please contact support with the following description: \(reason)" self.isInternal = true } else { self.alertMessage = reason self.isInternal = false } self.details = nil } self.backtrace = try container.decodeIfPresent([String].self, forKey: .backtrace) self.extraInfo = try container.decodeIfPresent([String:String].self, forKey: .extraInfo) ?? [:] } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.title, forKey: .title) try container.encode(self.alertMessage, forKey: .alertMessage) try container.encode(self.details, forKey: .details) try container.encode(self.isInternal, forKey: .isInternal) try container.encode(self.backtrace, forKey: .backtrace) try container.encode(self.extraInfo, forKey: .extraInfo) // Backwards compatability try container.encode(self.title, forKey: .doing) try container.encode(self.alertMessage, forKey: .because) try container.encode(self.isInternal ? "system" : "user", forKey: .perpitrator) try container.encode(self.description, forKey: .message) var variableContainer = encoder.container(keyedBy: VariableKey.self) for (key, value) in self.extraInfo { guard let key = VariableKey(stringValue: key) else { continue } try variableContainer.encode(value, forKey: key) } } }
6a988718c799a61af627b3b6aababd9d
37.22293
173
0.636894
false
false
false
false