repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Yurssoft/QuickFile
Carthage/Checkouts/LNPopupController/LNPopupControllerExample/LNPopupControllerExample/DemoMusicPlayerController.swift
1
2729
// // DemoMusicPlayerController.swift // LNPopupControllerExample // // Created by Leo Natan on 8/8/15. // Copyright © 2015 Leo Natan. All rights reserved. // import UIKit import LNPopupController class DemoMusicPlayerController: UIViewController { @IBOutlet weak var songNameLabel: UILabel! @IBOutlet weak var albumNameLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var albumArtImageView: UIImageView! let accessibilityDateComponentsFormatter = DateComponentsFormatter() var timer : Timer? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let pause = UIBarButtonItem(image: UIImage(named: "pause"), style: .plain, target: nil, action: nil) pause.accessibilityLabel = NSLocalizedString("Pause", comment: "") let next = UIBarButtonItem(image: UIImage(named: "nextFwd"), style: .plain, target: nil, action: nil) next.accessibilityLabel = NSLocalizedString("Next Track", comment: "") self.popupItem.leftBarButtonItems = [ pause ] self.popupItem.rightBarButtonItems = [ next ] accessibilityDateComponentsFormatter.unitsStyle = .spellOut timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(DemoMusicPlayerController._timerTicked(_:)), userInfo: nil, repeats: true) } var songTitle: String = "" { didSet { if isViewLoaded { songNameLabel.text = songTitle } popupItem.title = songTitle } } var albumTitle: String = "" { didSet { if isViewLoaded { albumNameLabel.text = albumTitle } if ProcessInfo.processInfo.operatingSystemVersion.majorVersion <= 9 { popupItem.subtitle = albumTitle } } } var albumArt: UIImage = UIImage() { didSet { if isViewLoaded { albumArtImageView.image = albumArt } popupItem.image = albumArt popupItem.accessibilityImageLabel = NSLocalizedString("Album Art", comment: "") } } override func viewDidLoad() { super.viewDidLoad() songNameLabel.text = songTitle albumNameLabel.text = albumTitle albumArtImageView.image = albumArt } @objc func _timerTicked(_ timer: Timer) { popupItem.progress += 0.0002; popupItem.accessibilityProgressLabel = NSLocalizedString("Playback Progress", comment: "") let totalTime = TimeInterval(250) popupItem.accessibilityProgressValue = "\(accessibilityDateComponentsFormatter.string(from: TimeInterval(popupItem.progress) * totalTime)!) \(NSLocalizedString("of", comment: "")) \(accessibilityDateComponentsFormatter.string(from: totalTime)!)" progressView.progress = popupItem.progress if popupItem.progress >= 1.0 { timer.invalidate() popupPresentationContainer?.dismissPopupBar(animated: true, completion: nil) } } }
mit
5a1d9242c48478e5a4fe737861f8e3cc
28.978022
247
0.732405
4.071642
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Discover/CustomView/PlayVC.swift
3
4048
// // PlayVC.swift // iOSStar // // Created by sum on 2017/8/16. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import PLShortVideoKit class PlayVC: UIViewController { var asset : AVAsset? var settings : [String : AnyObject]? var shortVideoRecorder : PLShortVideoEditor? var groupLb : UILabel? var totaltime : CGFloat = 0 var timer : Timer? var start : UIButton? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // self.navigationController?.setNavigationBarHidden(false, animated: false) } override func viewDidLoad() { super.viewDidLoad() self.shortVideoRecorder = PLShortVideoEditor.init(asset: asset) self.shortVideoRecorder?.player.preview?.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight) self.view.addSubview((self.shortVideoRecorder?.player.preview!)!) self.shortVideoRecorder?.player.play() gettotal() initUI() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateGrogress), userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initUI(){ let share = UIButton.init(type: .custom) share.frame = CGRect.init(x: kScreenWidth - 100, y: 80, width: 70, height: 30) share.setTitle("关闭", for: .normal) share.titleLabel?.font = UIFont.systemFont(ofSize: 15) share.setTitleColor(UIColor.init(hexString: AppConst.Color.main), for: .normal) // share.addTarget(self, action: #selector(publish), for: .touchUpInside) self.view.addSubview(share) start = UIButton.init(type: .custom) start?.frame = CGRect.init(x:view.center.x - 35, y: view.center.y, width: 70, height: 70) start?.setTitle("播放", for: .normal) start?.titleLabel?.font = UIFont.systemFont(ofSize: 15) start?.backgroundColor = UIColor.white start?.setTitleColor(UIColor.init(hexString: AppConst.Color.main), for: .normal) // share.addTarget(self, action: #selector(publish), for: .touchUpInside) self.view.addSubview(start!) start?.addTarget(self , action: #selector(dobegain), for: .touchUpInside) start?.isHidden = true } func dobegain(){ self.shortVideoRecorder?.player.setItemBy(asset) self.shortVideoRecorder?.player.play() groupLb?.frame = CGRect.init(x: 20, y: 30, width: 0 , height: 5) totaltime = 0 timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateGrogress), userInfo: nil, repeats: true) start?.isHidden = true } func updateGrogress(){ if let total = self.settings?["PLSDurationKey"] as? CGFloat{ let progress = (kScreenWidth - 40) / total if (totaltime < total){ totaltime = totaltime + 0.1 if (totaltime * progress > (kScreenWidth - 40)){ groupLb?.frame = CGRect.init(x: 20, y: 30, width: kScreenWidth - 40 , height: 5) }else{ groupLb?.frame = CGRect.init(x: 20, y: 30, width: totaltime * progress , height: 5) } }else{ timer?.invalidate() // self.shortVideoRecorder?.player.pause() start?.isHidden = false } } } func gettotal(){ let bgLabel = UILabel.init(frame: CGRect.init(x: 20, y: 30, width: self.view.frame.size.width - 40, height: 5)) bgLabel.backgroundColor = UIColor.init(red: 255, green: 255, blue: 255, alpha: 0.5) self.view.addSubview(bgLabel) groupLb = UILabel.init(frame: CGRect.init(x: 20, y: 30, width: 00, height: 5)) groupLb?.backgroundColor = UIColor.init(hexString: "FB9938") self.view.addSubview(groupLb!) } }
gpl-3.0
ab9bc2493332a85a27b8db6d1b00249b
38.970297
136
0.620015
4.028942
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/Departure/Filter/BusStopFilterViewController.swift
1
4753
// // BusstopFilterViewController.swift // SASAbus // // Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]> // // This file is part of SASAbus. // // SASAbus is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SASAbus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with SASAbus. If not, see <http://www.gnu.org/licenses/>. // import UIKit class BusStopFilterViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIToolbarDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var enableAllButton: UIBarButtonItem! @IBOutlet weak var disableAllButton: UIBarButtonItem! fileprivate var filteredLines: [BusLineFilter] = [] init() { super.init(nibName: "BusStopFilterViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() title = L10n.Departures.Filter.title collectionView.register(UINib(nibName: "BusStopFilterCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BusStopFilterCollectionViewCell") collectionView.contentInset = UIEdgeInsetsMake(8, 8, 8, 8) enableAllButton.action = #selector(enableAllLines) enableAllButton.title = L10n.Departures.Filter.enableAll enableAllButton.tintColor = Theme.orange disableAllButton.action = #selector(disableAllLines) disableAllButton.title = L10n.Departures.Filter.disableAll disableAllButton.tintColor = Theme.orange loadAllLines() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let lines = filteredLines.filter { !$0.active }.map { $0.line } UserRealmHelper.setDisabledDepartures(lines: lines) let viewController = navigationController?.viewControllers[0] as! BusStopViewController viewController.updateFilter() } func loadAllLines() { let lines = Lines.ORDER let disabledLines = UserRealmHelper.getDisabledDepartures() for line in lines { let filter = BusLineFilter(line: line) filter.active = !disabledLines.contains(line) filteredLines.append(filter) } self.collectionView.reloadData() } func setFilterActive(_ sender: UISwitch) { filteredLines[sender.tag].active = !filteredLines[sender.tag].active } func enableAllLines() { for filter in filteredLines { filter.active = true } for cell in collectionView.visibleCells as! [BusStopFilterCollectionViewCell] { cell.filterSwitch.setOn(true, animated: true) } } func disableAllLines() { for filter in filteredLines { filter.active = false } for cell in collectionView.visibleCells as! [BusStopFilterCollectionViewCell] { cell.filterSwitch.setOn(false, animated: true) } } } extension BusStopFilterViewController { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return filteredLines.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let busLineFilter: BusLineFilter = self.filteredLines[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BusStopFilterCollectionViewCell", for: indexPath) as! BusStopFilterCollectionViewCell cell.busLineLabel.textColor = Theme.darkGrey cell.filterSwitch.onTintColor = Theme.orange cell.filterSwitch.tag = indexPath.row cell.filterSwitch.setOn(busLineFilter.active, animated: false) cell.filterSwitch.addTarget(self, action: #selector(setFilterActive(_:)), for: UIControlEvents.valueChanged) cell.filterSwitch.accessibilityLabel = Lines.lidToName(id: busLineFilter.line) cell.busLineLabel.text = L10n.General.line(Lines.lidToName(id: busLineFilter.line)) return cell } }
gpl-3.0
f2221728d9a3f5be63bd4305f54a05d7
31.772414
126
0.691077
4.84898
false
false
false
false
therealbnut/swift
stdlib/public/SDK/Foundation/ReferenceConvertible.swift
6
932
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module /// Decorates types which are backed by a Foundation reference type. /// /// All `ReferenceConvertible` types are hashable, equatable, and provide description functions. public protocol ReferenceConvertible : _ObjectiveCBridgeable, CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable { associatedtype ReferenceType : NSObject, NSCopying }
apache-2.0
2f8fb9f13c107e65e093b14e937ea2e6
45.6
138
0.642704
5.78882
false
false
false
false
Instagram/IGListKit
Examples/Examples-iOS/IGListKitExamples/SectionControllers/RemoveSectionController.swift
1
1318
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import IGListKit import IGListSwiftKit protocol RemoveSectionControllerDelegate: class { func removeSectionControllerWantsRemoved(_ sectionController: RemoveSectionController) } final class RemoveSectionController: ListSectionController, RemoveCellDelegate { weak var delegate: RemoveSectionControllerDelegate? private var number: Int? override init() { super.init() inset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) } override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { let cell: RemoveCell = collectionContext.dequeueReusableCell(for: self, at: index) cell.text = "Cell: \((number ?? 0) + 1)" cell.delegate = self return cell } override func didUpdate(to object: Any) { number = object as? Int } // MARK: RemoveCellDelegate func removeCellDidTapButton(_ cell: RemoveCell) { delegate?.removeSectionControllerWantsRemoved(self) } }
mit
ea6d10dd52a84b95d244fd3d4a4fd683
27.652174
90
0.69651
4.673759
false
false
false
false
ivanbruel/SwipeIt
SwipeIt/ViewModels/MultiredditList/MultiredditListItemViewModel.swift
1
1133
// // MultiredditListItemViewModel.swift // Reddit // // Created by Ivan Bruel on 06/05/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import Foundation class MultiredditListItemViewModel: ViewModel { // MARK: Private Properties private let user: User private let accessToken: AccessToken private let multireddit: Multireddit let name: String let subreddits: String var linkSwipeViewModel: LinkSwipeViewModel { return LinkSwipeViewModel(user: user, accessToken: accessToken, multireddit: multireddit) } init(user: User, accessToken: AccessToken, multireddit: Multireddit) { self.user = user self.accessToken = accessToken self.multireddit = multireddit name = multireddit.name subreddits = MultiredditListItemViewModel.subredditString(multireddit.subreddits) } } // MARK: Helpers extension MultiredditListItemViewModel { private class func subredditString(subreddits: [String]) -> String { switch subreddits.count { case 0..<4: return subreddits.joinWithSeparator(", ") default: return "\(subreddits.count) subreddits" } } }
mit
694cbd86b96dba361e04f4064185a51b
23.085106
93
0.731449
4.101449
false
false
false
false
dkarsh/SwiftGoal
SwiftGoal/Models/Ranking.swift
2
1302
// // Ranking.swift // SwiftGoal // // Created by Martin Richter on 24/07/15. // Copyright (c) 2015 Martin Richter. All rights reserved. // import Argo import Curry struct Ranking { let player: Player let rating: Float static func contentMatches(lhs: Ranking, _ rhs: Ranking) -> Bool { return Player.contentMatches(lhs.player, rhs.player) && lhs.rating == rhs.rating } static func contentMatches(lhs: [Ranking], _ rhs: [Ranking]) -> Bool { // Make sure arrays have same size guard lhs.count == rhs.count else { return false } // Look at pairs of rankings let hasMismatch = zip(lhs, rhs) .map { contentMatches($0, $1) } // Apply content matcher to each .contains(false) // Check for mismatches return !hasMismatch } } // MARK: Equatable func ==(lhs: Ranking, rhs: Ranking) -> Bool { return lhs.player == rhs.player } // MARK: Decodable extension Ranking: Decodable { static func decode(json: JSON) -> Decoded<Ranking> { return curry(Ranking.init) <^> json <| "player" <*> json <| "rating" } } // MARK: Hashable extension Ranking: Hashable { var hashValue: Int { return player.identifier.hashValue ^ rating.hashValue } }
mit
c60e99f02653f89c88325abf46629fd6
22.672727
76
0.609831
3.933535
false
false
false
false
dkarsh/SwiftGoal
SwiftGoal/Models/Player.swift
2
1559
// // Player.swift // SwiftGoal // // Created by Martin Richter on 02/06/15. // Copyright (c) 2015 Martin Richter. All rights reserved. // import Argo import Curry struct Player { let identifier: String let name: String static private let identifierKey = "id" static private let nameKey = "name" init(identifier: String, name: String) { self.identifier = identifier self.name = name } static func contentMatches(lhs: Player, _ rhs: Player) -> Bool { return lhs.identifier == rhs.identifier && lhs.name == rhs.name } static func contentMatches(lhs: [Player], _ rhs: [Player]) -> Bool { if lhs.count != rhs.count { return false } for (index, player) in lhs.enumerate() { if !contentMatches(rhs[index], player) { return false } } return true } } // MARK: Equatable func ==(lhs: Player, rhs: Player) -> Bool { return lhs.identifier == rhs.identifier } // MARK: Hashable extension Player: Hashable { var hashValue: Int { return identifier.hashValue } } // MARK: Decodable extension Player: Decodable { static func decode(json: JSON) -> Decoded<Player> { return curry(Player.init) <^> json <| identifierKey <*> json <| nameKey } } // MARK: Encodable extension Player: Encodable { func encode() -> [String: AnyObject] { return [ Player.identifierKey: identifier, Player.nameKey: name ] } }
mit
126b485447426dd173635bd92a4abbf5
19.786667
72
0.58499
4.091864
false
false
false
false
MenloHacks/ios-app
Menlo Hacks/Pods/Parchment/Parchment/Extensions/UIView+constraints.swift
1
1122
import UIKit extension UIView { func constrainToEdges(_ subview: UIView) { subview.translatesAutoresizingMaskIntoConstraints = false let topContraint = NSLayoutConstraint( item: subview, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0) let bottomConstraint = NSLayoutConstraint( item: subview, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0) let leadingContraint = NSLayoutConstraint( item: subview, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0) let trailingContraint = NSLayoutConstraint( item: subview, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0) addConstraints([ topContraint, bottomConstraint, leadingContraint, trailingContraint]) } }
mit
6ebe248d33d61361985fa2a502498f94
20.576923
61
0.602496
4.794872
false
false
false
false
instacrate/Subber-api
Sources/App/Controllers/CustomerController.swift
2
3221
// // UserController.swift // subber-api // // Created by Hakon Hanesand on 11/12/16. // // import Foundation import Vapor import HTTP enum FetchType: String, TypesafeOptionsParameter { case stripe case shipping static let key = "type" static let values = [FetchType.stripe.rawValue, FetchType.shipping.rawValue] static var defaultValue: FetchType? = nil } extension Customer { func shouldAllow(request: Request) throws { switch request.sessionType { case .none: throw try Abort.custom(status: .forbidden, message: "Must authenticate as Customer(\(throwableId()) to perform \(request.method) on it.") case .vendor: let vendor = try request.vendor() throw try Abort.custom(status: .forbidden, message: "Vendor(\(vendor.throwableId()) can not perform \(request.method) on Customer(\(throwableId())).") case .customer: let customer = try request.customer() guard try customer.throwableId() == throwableId() else { throw try Abort.custom(status: .forbidden, message: "Customer(\(customer.throwableId()) can not perform \(request.method) on Customer(\(throwableId()).") } } } } final class CustomerController { func detail(_ request: Request) throws -> ResponseRepresentable { let customer = try request.customer() var customerNode = try customer.makeNode() guard let stripe_id = customer.stripe_id else { throw Abort.custom(status: .badRequest, message: "User is missing a stripe id.") } let options = try request.extract() as [FetchType] if options.contains(.stripe) { // TODO : is card needed here, and update documentation if let card = request.query?["card"]?.string { let cards = try Stripe.shared.paymentInformation(for: stripe_id) customerNode["card"] = try cards.filter { $0.id == card }.first?.makeNode() } else { let stripeData = try Stripe.shared.customerInformation(for: stripe_id) customerNode["stripe"] = try stripeData.makeNode() } } if options.contains(.shipping) { let shipping = try customer.shippingAddresses().all() customerNode["shipping"] = try shipping.makeNode() } return try customerNode.makeJSON() } func create(_ request: Request) throws -> ResponseRepresentable { var customer: Customer = try request.extractModel() try customer.save() return customer } func modify(_ request: Request, customer: Customer) throws -> ResponseRepresentable { try customer.shouldAllow(request: request) var customer: Customer = try request.patchModel(customer) try customer.save() return try Response(status: .ok, json: customer.makeJSON()) } } extension CustomerController: ResourceRepresentable { func makeResource() -> Resource<Customer> { return Resource( index: detail, store: create, modify: modify ) } }
mit
c911d877ad94be235df147aa1436e198
30.891089
169
0.612853
4.709064
false
false
false
false
ZhengShouDong/CloudPacker
Sources/CloudPacker/Libraries/CryptoSwift/SHA3.swift
1
10379
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf // http://keccak.noekeon.org/specs_summary.html // #if os(Linux) || os(Android) || os(FreeBSD) import Glibc #else import Darwin #endif public final class SHA3: DigestType { let round_constants: Array<UInt64> = [ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, ] public let blockSize: Int public let digestLength: Int public let markByte: UInt8 fileprivate var accumulated = Array<UInt8>() fileprivate var accumulatedHash: Array<UInt64> public enum Variant { case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512 var digestLength: Int { return 100 - (blockSize / 2) } var blockSize: Int { return (1600 - outputLength * 2) / 8 } var markByte: UInt8 { switch self { case .sha224, .sha256, .sha384, .sha512: return 0x06 // 0x1F for SHAKE case .keccak224, .keccak256, .keccak384, .keccak512: return 0x01 } } public var outputLength: Int { switch self { case .sha224, .keccak224: return 224 case .sha256, .keccak256: return 256 case .sha384, .keccak384: return 384 case .sha512, .keccak512: return 512 } } } public init(variant: SHA3.Variant) { blockSize = variant.blockSize digestLength = variant.digestLength markByte = variant.markByte accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength) } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { return [] } } /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z<w, let /// C[x,z]=A[x, 0,z] ⊕ A[x, 1,z] ⊕ A[x, 2,z] ⊕ A[x, 3,z] ⊕ A[x, 4,z]. /// 2. For all pairs (x, z) such that 0≤x<5 and 0≤z<w let /// D[x,z]=C[(x1) mod 5, z] ⊕ C[(x+1) mod 5, (z –1) mod w]. /// 3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let /// A′[x, y,z] = A[x, y,z] ⊕ D[x,z]. private func θ(_ a: inout Array<UInt64>) { let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5) c.initialize(to: 0, count: 5) defer { c.deinitialize(count: 5) c.deallocate(capacity: 5) } let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5) d.initialize(to: 0, count: 5) defer { d.deinitialize(count: 5) d.deallocate(capacity: 5) } for i in 0..<5 { c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20] } d[0] = rotateLeft(c[1], by: 1) ^ c[4] d[1] = rotateLeft(c[2], by: 1) ^ c[0] d[2] = rotateLeft(c[3], by: 1) ^ c[1] d[3] = rotateLeft(c[4], by: 1) ^ c[2] d[4] = rotateLeft(c[0], by: 1) ^ c[3] for i in 0..<5 { a[i] ^= d[i] a[i &+ 5] ^= d[i] a[i &+ 10] ^= d[i] a[i &+ 15] ^= d[i] a[i &+ 20] ^= d[i] } } /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z] private func π(_ a: inout Array<UInt64>) { let a1 = a[1] a[1] = a[6] a[6] = a[9] a[9] = a[22] a[22] = a[14] a[14] = a[20] a[20] = a[2] a[2] = a[12] a[12] = a[13] a[13] = a[19] a[19] = a[23] a[23] = a[15] a[15] = a[4] a[4] = a[24] a[24] = a[21] a[21] = a[8] a[8] = a[16] a[16] = a[5] a[5] = a[3] a[3] = a[18] a[18] = a[17] a[17] = a[11] a[11] = a[7] a[7] = a[10] a[10] = a1 } /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let /// A′[x, y,z] = A[x, y,z] ⊕ ((A[(x+1) mod 5, y, z] ⊕ 1) ⋅ A[(x+2) mod 5, y, z]) private func χ(_ a: inout Array<UInt64>) { for i in stride(from: 0, to: 25, by: 5) { let a0 = a[0 &+ i] let a1 = a[1 &+ i] a[0 &+ i] ^= ~a1 & a[2 &+ i] a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i] a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i] a[3 &+ i] ^= ~a[4 &+ i] & a0 a[4 &+ i] ^= ~a0 & a1 } } private func ι(_ a: inout Array<UInt64>, round: Int) { a[0] ^= round_constants[round] } fileprivate func process(block chunk: ArraySlice<UInt64>, currentHash hh: inout Array<UInt64>) { // expand hh[0] ^= chunk[0].littleEndian hh[1] ^= chunk[1].littleEndian hh[2] ^= chunk[2].littleEndian hh[3] ^= chunk[3].littleEndian hh[4] ^= chunk[4].littleEndian hh[5] ^= chunk[5].littleEndian hh[6] ^= chunk[6].littleEndian hh[7] ^= chunk[7].littleEndian hh[8] ^= chunk[8].littleEndian if blockSize > 72 { // 72 / 8, sha-512 hh[9] ^= chunk[9].littleEndian hh[10] ^= chunk[10].littleEndian hh[11] ^= chunk[11].littleEndian hh[12] ^= chunk[12].littleEndian if blockSize > 104 { // 104 / 8, sha-384 hh[13] ^= chunk[13].littleEndian hh[14] ^= chunk[14].littleEndian hh[15] ^= chunk[15].littleEndian hh[16] ^= chunk[16].littleEndian if blockSize > 136 { // 136 / 8, sha-256 hh[17] ^= chunk[17].littleEndian // FULL_SHA3_FAMILY_SUPPORT if blockSize > 144 { // 144 / 8, sha-224 hh[18] ^= chunk[18].littleEndian hh[19] ^= chunk[19].littleEndian hh[20] ^= chunk[20].littleEndian hh[21] ^= chunk[21].littleEndian hh[22] ^= chunk[22].littleEndian hh[23] ^= chunk[23].littleEndian hh[24] ^= chunk[24].littleEndian } } } } // Keccak-f for round in 0..<24 { θ(&hh) hh[1] = rotateLeft(hh[1], by: 1) hh[2] = rotateLeft(hh[2], by: 62) hh[3] = rotateLeft(hh[3], by: 28) hh[4] = rotateLeft(hh[4], by: 27) hh[5] = rotateLeft(hh[5], by: 36) hh[6] = rotateLeft(hh[6], by: 44) hh[7] = rotateLeft(hh[7], by: 6) hh[8] = rotateLeft(hh[8], by: 55) hh[9] = rotateLeft(hh[9], by: 20) hh[10] = rotateLeft(hh[10], by: 3) hh[11] = rotateLeft(hh[11], by: 10) hh[12] = rotateLeft(hh[12], by: 43) hh[13] = rotateLeft(hh[13], by: 25) hh[14] = rotateLeft(hh[14], by: 39) hh[15] = rotateLeft(hh[15], by: 41) hh[16] = rotateLeft(hh[16], by: 45) hh[17] = rotateLeft(hh[17], by: 15) hh[18] = rotateLeft(hh[18], by: 21) hh[19] = rotateLeft(hh[19], by: 8) hh[20] = rotateLeft(hh[20], by: 18) hh[21] = rotateLeft(hh[21], by: 2) hh[22] = rotateLeft(hh[22], by: 61) hh[23] = rotateLeft(hh[23], by: 56) hh[24] = rotateLeft(hh[24], by: 14) π(&hh) χ(&hh) ι(&hh, round: round) } } } extension SHA3: Updatable { public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { accumulated += bytes if isLast { // Add padding let markByteIndex = accumulated.count // We need to always pad the input. Even if the input is a multiple of blockSize. let r = blockSize * 8 let q = (r / 8) - (accumulated.count % (r / 8)) accumulated += Array<UInt8>(repeating: 0, count: q) accumulated[markByteIndex] |= markByte accumulated[self.accumulated.count - 1] |= 0x80 } var processedBytes = 0 for chunk in accumulated.batched(by: blockSize) { if isLast || (accumulated.count - processedBytes) >= blockSize { process(block: chunk.toUInt64Array().slice, currentHash: &accumulatedHash) processedBytes += chunk.count } } accumulated.removeFirst(processedBytes) // TODO: verify performance, reduce vs for..in let result = accumulatedHash.reduce(Array<UInt8>()) { (result, value) -> Array<UInt8> in return result + value.bigEndian.bytes() } // reset hash value for instance if isLast { accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength) } return Array(result[0..<self.digestLength]) } }
apache-2.0
8c142d462c0186b5bb86b0e7cc3448eb
34.593103
217
0.512594
3.402109
false
false
false
false
cikelengfeng/Jude
Jude/Antlr4/atn/LexerActionExecutor.swift
2
8122
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// Represents an executor for a sequence of lexer actions which traversed during /// the matching operation of a lexer rule (token). /// /// <p>The executor tracks position information for position-dependent lexer actions /// efficiently, ensuring that actions appearing only at the end of the rule do /// not cause bloating of the {@link org.antlr.v4.runtime.dfa.DFA} created for the lexer.</p> /// /// - Sam Harwell /// - 4.2 public class LexerActionExecutor: Hashable { fileprivate final var lexerActions: [LexerAction] /// Caches the result of {@link #hashCode} since the hash code is an element /// of the performance-critical {@link org.antlr.v4.runtime.atn.LexerATNConfig#hashCode} operation. fileprivate final var hashCode: Int /// Constructs an executor for a sequence of {@link org.antlr.v4.runtime.atn.LexerAction} actions. /// - parameter lexerActions: The lexer actions to execute. public init(_ lexerActions: [LexerAction]) { self.lexerActions = lexerActions var hash: Int = MurmurHash.initialize() for lexerAction: LexerAction in lexerActions { hash = MurmurHash.update(hash, lexerAction) } self.hashCode = MurmurHash.finish(hash, lexerActions.count) } /// Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which executes the actions for /// the input {@code lexerActionExecutor} followed by a specified /// {@code lexerAction}. /// /// - parameter lexerActionExecutor: The executor for actions already traversed by /// the lexer while matching a token within a particular /// {@link org.antlr.v4.runtime.atn.LexerATNConfig}. If this is {@code null}, the method behaves as /// though it were an empty executor. /// - parameter lexerAction: The lexer action to execute after the actions /// specified in {@code lexerActionExecutor}. /// /// - returns: A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} for executing the combine actions /// of {@code lexerActionExecutor} and {@code lexerAction}. public static func append(_ lexerActionExecutor: LexerActionExecutor?, _ lexerAction: LexerAction) -> LexerActionExecutor { if lexerActionExecutor == nil { return LexerActionExecutor([lexerAction]) } //var lexerActions : [LexerAction] = lexerActionExecutor.lexerActions, //lexerActionExecutor.lexerActions.length + 1); var lexerActions: [LexerAction] = lexerActionExecutor!.lexerActions lexerActions.append(lexerAction) //lexerActions[lexerActions.length - 1] = lexerAction; return LexerActionExecutor(lexerActions) } /// Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which encodes the current offset /// for position-dependent lexer actions. /// /// <p>Normally, when the executor encounters lexer actions where /// {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}, it calls /// {@link org.antlr.v4.runtime.IntStream#seek} on the input {@link org.antlr.v4.runtime.CharStream} to set the input /// position to the <em>end</em> of the current token. This behavior provides /// for efficient DFA representation of lexer actions which appear at the end /// of a lexer rule, even when the lexer rule matches a variable number of /// characters.</p> /// /// <p>Prior to traversing a match transition in the ATN, the current offset /// from the token start index is assigned to all position-dependent lexer /// actions which have not already been assigned a fixed offset. By storing /// the offsets relative to the token start index, the DFA representation of /// lexer actions which appear in the middle of tokens remains efficient due /// to sharing among tokens of the same length, regardless of their absolute /// position in the input stream.</p> /// /// <p>If the current executor already has offsets assigned to all /// position-dependent lexer actions, the method returns {@code this}.</p> /// /// - parameter offset: The current offset to assign to all position-dependent /// lexer actions which do not already have offsets assigned. /// /// - returns: A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which stores input stream offsets /// for all position-dependent lexer actions. public func fixOffsetBeforeMatch(_ offset: Int) -> LexerActionExecutor { var updatedLexerActions: [LexerAction]? = nil let length = lexerActions.count for i in 0..<length { if lexerActions[i].isPositionDependent() && !(lexerActions[i] is LexerIndexedCustomAction) { if updatedLexerActions == nil { updatedLexerActions = lexerActions //lexerActions.clone(); } updatedLexerActions![i] = LexerIndexedCustomAction(offset, lexerActions[i]) } } if updatedLexerActions == nil { return self } return LexerActionExecutor(updatedLexerActions!) } /// Gets the lexer actions to be executed by this executor. /// - returns: The lexer actions to be executed by this executor. public func getLexerActions() -> [LexerAction] { return lexerActions } /// Execute the actions encapsulated by this executor within the context of a /// particular {@link org.antlr.v4.runtime.Lexer}. /// /// <p>This method calls {@link org.antlr.v4.runtime.IntStream#seek} to set the position of the /// {@code input} {@link org.antlr.v4.runtime.CharStream} prior to calling /// {@link org.antlr.v4.runtime.atn.LexerAction#execute} on a position-dependent action. Before the /// method returns, the input position will be restored to the same position /// it was in when the method was invoked.</p> /// /// - parameter lexer: The lexer instance. /// - parameter input: The input stream which is the source for the current token. /// When this method is called, the current {@link org.antlr.v4.runtime.IntStream#index} for /// {@code input} should be the start of the following token, i.e. 1 /// character past the end of the current token. /// - parameter startIndex: The token start index. This value may be passed to /// {@link org.antlr.v4.runtime.IntStream#seek} to set the {@code input} position to the beginning /// of the token. public func execute(_ lexer: Lexer, _ input: CharStream, _ startIndex: Int) throws { var requiresSeek: Bool = false var stopIndex: Int = input.index() defer { if requiresSeek { try! input.seek(stopIndex) } } //try { for var lexerAction: LexerAction in self.lexerActions { if let runLexerAction = lexerAction as? LexerIndexedCustomAction { let offset: Int = runLexerAction.getOffset() try input.seek(startIndex + offset) lexerAction = runLexerAction.getAction() requiresSeek = (startIndex + offset) != stopIndex } else { if lexerAction.isPositionDependent() { try input.seek(stopIndex) requiresSeek = false } } try lexerAction.execute(lexer) } //} } public var hashValue: Int { return self.hashCode } } public func ==(lhs: LexerActionExecutor, rhs: LexerActionExecutor) -> Bool { if lhs === rhs { return true } if lhs.lexerActions.count != rhs.lexerActions.count { return false } let length = lhs.lexerActions.count for i in 0..<length { if !(lhs.lexerActions[i] == rhs.lexerActions[i]) { return false } } return lhs.hashCode == rhs.hashCode }
mit
9b74fb0cd6377e8bb0e1786c5f3d1876
42.433155
127
0.660552
4.474931
false
false
false
false
Juan-Sanchez/Supporting_Classes
AnchorConstraintFactory.swift
1
2247
// // AnchorConstraintFactory.swift // Created by juan sanchez on 4/12/17. // import Foundation import UIKit class AnchorConstraintFactory { // Fill the parent view with subview. class func constrain(View subView: UIView, toFillParent parentView: UIView) { subView.translatesAutoresizingMaskIntoConstraints = false // Vertical subView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true subView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true // Horizontal subView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true subView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } // Constrian to parent view with top constrained to top layout guide. class func constrain(View subView: UIView, toFillParent parentView: UIView, withTopLayoutGuide guide: UILayoutSupport) { subView.translatesAutoresizingMaskIntoConstraints = false // Vertical subView.topAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true // bottom of nav bar subView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true // Horizontal subView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true subView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } // Constrain to parent view with top constrained to top and bottom layout guide. class func constrain(View subView: UIView, toFillParent parentView: UIView, withTopLayoutGuide top: UILayoutSupport, andBottomLayoutGuide bottom: UILayoutSupport) { subView.translatesAutoresizingMaskIntoConstraints = false // Vertical subView.topAnchor.constraint(equalTo: top.bottomAnchor).isActive = true // bottom of nav bar subView.bottomAnchor.constraint(equalTo: bottom.bottomAnchor).isActive = true // Horizontal subView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true subView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } }
mit
f385e54d3b01c5505107e4f0e4612172
44.857143
168
0.726302
5.589552
false
false
false
false
mzp/OctoEye
Sources/OctoEye/Controller/AddRepositoryViewController.swift
1
4417
// // AddRepositoryViewController.swift // OctoEye // // Created by mzp on 2017/08/01. // Copyright © 2017 mzp. All rights reserved. // import Ikemen import ReactiveSwift import Result import UIKit internal class AddRepositoryViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate { let added: Signal<RepositoryObject, NoError> private let addedObserver: Signal<RepositoryObject, NoError>.Observer private let indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) // MARK: - data source private lazy var github: GithubClient = { // When GithubClient.shared is null, login view must be shown // swiftlint:disable:next force_unwrapping GithubClient.shared! }() private lazy var ownDataSource: PagingDataSource = { OwnRepositoriesDataSource(github: github) }() private lazy var searchDataSource: SearchRepositoriesDataSource = { SearchRepositoriesDataSource(github: github) }() private var currentDataSource: PagingDataSource? { didSet { tableView.dataSource = currentDataSource tableView.reloadData() } } // MARK: - ViewController init() { let (signal, observer) = Signal<RepositoryObject, NoError>.pipe() self.added = signal self.addedObserver = observer super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "Add repository" indicator.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44) indicator.hidesWhenStopped = true tableView.tableFooterView = indicator navigationItem.searchController = UISearchController(searchResultsController: nil) ※ { $0.searchResultsUpdater = self $0.delegate = self $0.obscuresBackgroundDuringPresentation = false } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Signal .merge([ownDataSource.reactive, searchDataSource.reactive]) .take(during: self.reactive.lifetime) .observeResult { switch $0 { case .success(.loading): self.startLoadig() case .success(.completed): self.stopLoading() self.tableView.reloadData() case .failure(let error): self.stopLoading() self.presentError(title: "cannot fetch repositories", error: error) } } currentDataSource = ownDataSource currentDataSource?.invokePaging() } // MARK: - ScrollVeiw override func scrollViewDidScroll(_ scrollView: UIScrollView) { if tableView.contentOffset.y >= (tableView.contentSize.height - tableView.bounds.size.height) { currentDataSource?.invokePaging() } } // MARK: - TableView override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let value = currentDataSource?[indexPath.row] { addedObserver.send(value: value) addedObserver.sendCompleted() } navigationItem.searchController?.isActive = false navigationController?.popViewController(animated: true) } // MARK: - SearchController func updateSearchResults(for searchController: UISearchController) { searchDataSource.search(query: searchController.searchBar.text ?? "") } func willPresentSearchController(_ searchController: UISearchController) { currentDataSource = searchDataSource } func didDismissSearchController(_ searchController: UISearchController) { currentDataSource = ownDataSource } // MARK: - utilities private func startLoadig() { DispatchQueue.main.async { self.indicator.startAnimating() UIApplication.shared.isNetworkActivityIndicatorVisible = true } } private func stopLoading() { DispatchQueue.main.async { self.indicator.stopAnimating() UIApplication.shared.isNetworkActivityIndicatorVisible = false } } }
mit
db592eeef67aca94b4053a92567f91f7
31.696296
120
0.647485
5.476427
false
false
false
false
hetefe/HTF_sina_swift
sina_htf/sina_htf/Classes/Model/Status.swift
1
3870
// // Status.swift // sina_htf // // Created by 赫腾飞 on 15/12/18. // Copyright © 2015年 hetefe. All rights reserved. // /** 返回值字段 字段类型 字段说明 created_at string 微博创建时间 id int64 微博ID text string 微博信息内容 source string 微博来源 favorited boolean 是否已收藏,true:是,false:否 truncated boolean 是否被截断,true:是,false:否 in_reply_to_status_id string (暂未支持)回复ID in_reply_to_user_id string (暂未支持)回复人UID in_reply_to_screen_name string (暂未支持)回复人昵称 thumbnail_pic string 缩略图片地址,没有时不返回此字段 bmiddle_pic string 中等尺寸图片地址,没有时不返回此字段 original_pic string 原始图片地址,没有时不返回此字段 geo object 地理信息字段 详细 user object 微博作者的用户信息字段 详细 retweeted_status object 被转发的原微博信息字段,当该微博为转发微博时返回 详细 reposts_count int 转发数 comments_count int 评论数 attitudes_count int 表态数 mlevel int 暂未支持 visible object 微博的可见性及指定可见分组信息。该object中type取值,0:普通微博,1:私密微博,3:指定分组微博,4:密友微博;list_id为分组的组号 pic_ids object 微博配图ID。多图时返回多图ID,用来拼接图片url。用返回字段thumbnail_pic的地址配上该返回字段的图片ID,即可得到多个图片url。 ad object array 微博流内的推广微博ID */ import UIKit class Status: NSObject { //微博创建时间 var created_at: String? //int64 微博ID 在iPhone 5c一下的设备上 会导致整形数据被截掉 var id: Int64 = 0 //text string 微博信息内容 var text: String? //source string 微博来源 var source: String? //用户模型 var user: User? //配图数据 var pic_urls: [[String: String]]?{ didSet{ guard let array = pic_urls else { return } //遍历数组 //将数组实例化 imageURLs = [NSURL]() for item in array{ //一定能够显示 var urlString = item["thumbnail_pic"]! urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "square") let url = NSURL(string: urlString) //添加URL imageURLs!.append(url!) } } } //将获取的数组数据, 转换成URL对象 var imageURLs: [NSURL]? //转发微博模型 var retweeted_status: Status? //构造方法 kvc设置 init(dict: [String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forKey key: String) { if key == "user" { //字典转模型 if let dict = value as? [String : AnyObject]{ user = User(dict: dict) } //需要加return 否则白做了 return } //转发微博 if key == "retweeted_status" { if let dict = value as? [String: AnyObject] { retweeted_status = Status(dict: dict) return } } super.setValue(value, forKey: key) } //过滤未使用字段 override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override var description: String { let keys = ["created_at", "id", "text", "source","user"] return dictionaryWithValuesForKeys(keys).description } }
mit
196b6fad283b50f69cf88d6f1f92c28a
22.007576
109
0.572605
3.423901
false
false
false
false
nodes-vapor/admin-panel-provider
Sources/AdminPanelProvider/Tags/Leaf/TextGroup.swift
1
4763
import Leaf import Vapor /// #form:textgroup(**key**, **value**, **fieldset**, classes *(optional)*, attributes *(optional)*) /// /// Arguments: /// /// [0] = The name of the input (the key that gets posted) (1) /// /// [1] = The value of the input (the value that gets posted) (defaults to empty string) (2) /// /// [2] = The VaporForms Fieldset of the entire model (1, 2) /// /// **1** - All the arguments are actually required. We need to throw exceptions at people if they don't supply all of them /// /// **2** - It would be awesome if you could only post the exact Field of the Fieldset so we don't need to find it in this code (its gonna get repetetive) /// /// The <label> will get its value from the Fieldset /// /// If the Fieldset has the "errors" property the form-group will get the has-error css class and all errors will be added as help-block's to the form-group /// /// given input: /// /// ``` /// let fieldset = Node([ /// "name": StringField( /// label: "Name" /// ]) /// /// #form:textgroup("name", "John Doe", fieldset) /// ``` /// /// expected output if fieldset is valid: /// /// ``` /// <div class="form-group"> /// <label class="control-label" for="name">Name</label> /// <input class="form-control" type="text" id="name" name="name" value="John Doe" /> /// </div> /// ``` /// /// expected output for `#form:textgroup("name", "John Doe", fieldset, "center-text dark", "a='hello',b='world'")`: /// /// ``` /// <div class="form-group"> /// <label class="control-label" for="name">Name</label> /// <input class="form-control center-text dark" type="text" id="name" name="name" value="John Doe" a='hello' b='world'/> /// </div> /// ``` /// /// expected output if fieldset is invalid: /// /// ``` /// <div class="form-group has-error"> /// <label class="control-label" for="name">Name</label> /// <input class="form-control" type="text" id="name" name="name" value="John Doe" /> /// <span class="help-block">...validation message</span> /// </div> /// ``` public func this(_ lhs: String?, or rhs: String?) -> String { if let lhs = lhs, !lhs.isEmpty { return lhs } if let rhs = rhs, !rhs.isEmpty { return rhs } return "" } public final class TextGroup: BasicTag { public init() {} public let name = "form:textgroup" public func run(arguments: ArgumentList) throws -> Node? { guard arguments.count >= 2, case .variable(let fieldsetPathNodes, value: let fieldset) = arguments.list[0], let fieldsetPath = fieldsetPathNodes.last else { throw Abort(.internalServerError, reason: "TextGroup parse error, expecting: #form:textgroup(\"fieldset.name\", \"default\", \"classes\", \"attributes\")") } // Retrieve input value, value from fieldset else passed default value let inputValue = this(fieldset?["value"]?.string, or: arguments[1]?.string) let label = fieldset?["label"]?.string ?? fieldsetPath // This is not a required property let errors = fieldset?["errors"]?.array let hasErrors = !(errors?.isEmpty ?? true) // Start constructing the template var template = [String]() var classes = "form-control " if let customClasses = arguments[2]?.string { classes.append(customClasses) } template.append("<div class='form-group \(hasErrors ? "has-error" : "")'>") template.append("<label class='control-label' for='\(fieldsetPath)'>\(label)</label>") template.append("<input class='\(classes)' type='text' id='\(fieldsetPath)' name='\(fieldsetPath)' value='\(inputValue)' ") if let attributesNode = arguments[3] { let attributes: [String] if let attrArray = attributesNode.array { attributes = attrArray.flatMap { $0.string } } else if let attrStr = attributesNode.string { attributes = attrStr.components(separatedBy: ",") } else { throw Abort(.internalServerError, reason: "FormTextGroup parse error, expecting: an array or comma separated list of custom attributes") } template.append(contentsOf: attributes) } template.append("/>") // If Fieldset has errors then loop through them and add help-blocks if let errors = errors { for e in errors { guard let errorString = e.string else { continue } template.append("<span class='help-block'>\(errorString)</span>") } } template.append("</div>") // Return template return .bytes(template.joined().bytes) } }
mit
3f3e118ba11496c9a0b91eb9ab7d4a84
33.021429
167
0.590594
3.965862
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift
4
12806
// // YAxisRendererHorizontalBarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class YAxisRendererHorizontalBarChart: YAxisRenderer { public override init(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, transformer: Transformer?) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. open override func computeAxis(min: Double, max: Double, inverted: Bool) { guard let viewPortHandler = self.viewPortHandler, let transformer = self.transformer else { return } var min = min, max = max // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if !inverted { min = Double(p1.x) max = Double(p2.x) } else { min = Double(p2.x) max = Double(p1.x) } } computeAxisValues(min: min, max: max) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = axis as? YAxis, let viewPortHandler = self.viewPortHandler else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let lineHeight = yAxis.labelFont.lineHeight let baseYOffset: CGFloat = 2.5 let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var yPos: CGFloat = 0.0 if dependency == .left { if labelPosition == .outsideChart { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if labelPosition == .outsideChart { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels( context: context, fixedPosition: yPos, positions: transformedPositions(), offset: yAxis.yOffset) } open override func renderAxisLine(context: CGContext) { guard let yAxis = axis as? YAxis, let viewPortHandler = self.viewPortHandler else { return } if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if yAxis.axisLineDashLengths != nil { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if yAxis.axisDependency == .left { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.strokePath() } else { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } /// draws the y-labels on the specified x-position @objc open func drawYLabels( context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { guard let yAxis = axis as? YAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1 let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1) for i in stride(from: from, to: to, by: 1) { let text = yAxis.getFormattedLabel(i) ChartUtils.drawText( context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [NSAttributedStringKey.font: labelFont, NSAttributedStringKey.foregroundColor: labelTextColor]) } } open override var gridClippingRect: CGRect { var contentRect = viewPortHandler?.contentRect ?? CGRect.zero let dx = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.x -= dx / 2.0 contentRect.size.width += dx return contentRect } open override func drawGridLine( context: CGContext, position: CGPoint) { guard let viewPortHandler = self.viewPortHandler else { return } context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.strokePath() } open override func transformedPositions() -> [CGPoint] { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return [CGPoint]() } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entryCount) let entries = yAxis.entries for i in stride(from: 0, to: yAxis.entryCount, by: 1) { positions.append(CGPoint(x: entries[i], y: 0.0)) } transformer.pointValuesToPixel(&positions) return positions } /// Draws the zero line at the specified position. open override func drawZeroLine(context: CGContext) { guard let yAxis = self.axis as? YAxis, let viewPortHandler = self.viewPortHandler, let transformer = self.transformer, let zeroLineColor = yAxis.zeroLineColor else { return } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.x -= yAxis.zeroLineWidth / 2.0 clippingRect.size.width += yAxis.zeroLineWidth context.clip(to: clippingRect) context.setStrokeColor(zeroLineColor.cgColor) context.setLineWidth(yAxis.zeroLineWidth) let pos = transformer.pixelForValues(x: 0.0, y: 0.0) if yAxis.zeroLineDashLengths != nil { context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.move(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentBottom)) context.drawPath(using: CGPathDrawingMode.stroke) } fileprivate var _limitLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderLimitLines(context: CGContext) { guard let yAxis = axis as? YAxis, let viewPortHandler = self.viewPortHandler, let transformer = self.transformer else { return } var limitLines = yAxis.limitLines if limitLines.count <= 0 { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.x -= l.lineWidth / 2.0 clippingRect.size.width += l.lineWidth context.clip(to: clippingRect) position.x = CGFloat(l.limit) position.y = 0.0 position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.characters.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = l.lineWidth + l.xOffset let yOffset: CGFloat = 2.0 + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } } } context.restoreGState() } }
apache-2.0
a7b2c2132789fa602825c5904092cd32
32.52356
135
0.541621
5.567826
false
false
false
false
EurekaCommunity/GenericPasswordRow
Sources/DefaultPasswordStrengthView.swift
1
3787
// // PasswordStrengthView.swift // GenericPasswordRow // // Created by Diego Ernst on 9/1/16. // Copyright © 2016 Diego Ernst. All rights reserved. // import UIKit open class DefaultPasswordStrengthView: PasswordStrengthView { public typealias StrengthView = (view: UIView, p: CGFloat, color: UIColor) open var strengthViews: [StrengthView]! open var validator: PasswordValidator! open var progressView: UIView! open var progress: CGFloat = 0 open var borderColor = UIColor.lightGray.withAlphaComponent(0.2) open var borderWidth = CGFloat(1) open var cornerRadius = CGFloat(3) open var animationTime = TimeInterval(0.3) public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override open func setPasswordValidator(_ validator: PasswordValidator) { self.validator = validator let colorsForStrenghts = validator.colorsForStrengths().sorted { $0.0 < $1.0 } strengthViews = colorsForStrenghts.enumerated().map { index, element in let view = UIView() view.layer.borderColor = borderColor.cgColor view.layer.borderWidth = borderWidth view.backgroundColor = backgroundColorForStrenghColor(element.1) let r = index < colorsForStrenghts.count - 1 ? colorsForStrenghts[index+1].0 : validator.maxStrength return (view: view, p: CGFloat(r / validator.maxStrength), color: element.1) } strengthViews.reversed().forEach { addSubview($0.view) } bringSubviewToFront(progressView) } open func backgroundColorForStrenghColor(_ color: UIColor) -> UIColor { var h = CGFloat(0), s = CGFloat(0), b = CGFloat(0), alpha = CGFloat(0) color.getHue(&h, saturation: &s, brightness: &b, alpha: &alpha) return UIColor(hue: h, saturation: 0.06, brightness: 1, alpha: alpha) } open func setup() { clipsToBounds = true layer.cornerRadius = cornerRadius progressView = UIView() progressView.layer.borderColor = borderColor.cgColor progressView.layer.borderWidth = borderWidth addSubview(progressView) progress = 0 } override open func updateStrength(password: String, animated: Bool = true) { let strength = validator.strengthForPassword(password) progress = CGFloat(strength / validator.maxStrength) updateView(animated: animated) } open func colorForProgress() -> UIColor { for strengthView in strengthViews { if progress <= strengthView.p { return strengthView.color } } return strengthViews.last?.color ?? .clear } open func updateView(animated: Bool) { setNeedsLayout() if animated { UIView.animate(withDuration: animationTime, animations: { [weak self] in self?.layoutIfNeeded() }, completion: { [weak self] _ in UIView.animate(withDuration: self?.animationTime ?? 0.3, animations: { [weak self] in self?.progressView?.backgroundColor = self?.colorForProgress() }) }) } else { layoutIfNeeded() } } override open func layoutSubviews() { super.layoutSubviews() var size = frame.size size.width = size.width * progress progressView.frame = CGRect(origin: CGPoint.zero, size: size) strengthViews.forEach { view, p, _ in var size = frame.size size.width = size.width * p view.frame = CGRect(origin: CGPoint.zero, size: size) } } }
mit
6d8db62ce8a04ba7b266fd850fa08ca0
33.733945
112
0.628368
4.577993
false
false
false
false
XiaoChenYung/GitSwift
GitSwift/ViewModel/ViewModel.swift
1
1126
// // ViewModel.swift // GitSwift // // Created by tm on 2017/7/19. // Copyright © 2017年 tm. All rights reserved. // import Foundation import RxSwift import RxCocoa import Domain protocol ViewModelType { associatedtype Input associatedtype Output func transform(input: Input) -> Output } enum TitleViewType { case TitleViewTypeDefault //Single title case TitleViewTypeDoubleTitle //Double title case TitleViewTypeLoadingTitle //Loading title } class ViewModel: NSObject { var title: Variable<String> = Variable("") //主标题 var subtitle: Variable<String> = Variable("") //副标题 var titleType: Variable<TitleViewType> = Variable(TitleViewType.TitleViewTypeDefault) //标题类型 var service: ViewModelServiceImp var params: Dictionary<String, Any>? var provider: Domain.UseCaseProvider? init(service: ViewModelServiceImp, params: Dictionary<String, Any>? = nil, provider: Domain.UseCaseProvider? = nil) { self.service = service self.params = params self.provider = provider super.init() } }
mit
ff78b075c04767aa3c5c32ef60cb1184
22.978261
121
0.689937
4.291829
false
false
false
false
mukyasa/MMTextureChat
Pods/Toolbar/Toolbar/Toolbar.swift
1
5895
// // Toolbar.swift // Toolbar // // Created by 1amageek on 2017/04/20. // Copyright © 2017年 Stamp Inc. All rights reserved. // import UIKit public class Toolbar: UIView { public enum LayoutMode { case auto case munual } public override class var requiresConstraintBasedLayout: Bool { return true } public static let defaultHeight: CGFloat = 44 /** Toolbar layout mode When frame is set, it becomes manual mode Setting .zero in frame sets it to auto mode */ private(set) var layoutMode: LayoutMode = .auto /// Maximum value of high value of toolbar public var maximumHeight: CGFloat = UIScreen.main.bounds.height public var minimumHeight: CGFloat = Toolbar.defaultHeight private(set) var items: [ToolbarItem] = [] // MARK: - Constraint private var minimumHeightConstraint: NSLayoutConstraint? private var maximumHeightConstraint: NSLayoutConstraint? private var leadingConstraint: NSLayoutConstraint? private var trailingConstraint: NSLayoutConstraint? // MARK: - // manual mode layout frame.size.width private var widthConstraint: NSLayoutConstraint? // manual mode layout frame.origin.y private var topConstraint: NSLayoutConstraint? public override var frame: CGRect { didSet { if frame != .zero { self.layoutMode = .munual } self.setNeedsLayout() } } // MARK: - Init /** Initialize in autolayout mode. */ public convenience init() { self.init(frame: .zero) } public override init(frame: CGRect) { super.init(frame: frame) if frame != .zero { self.layoutMode = .munual } self.addSubview(backgroundView) self.addSubview(stackView) self.backgroundColor = .clear self.isOpaque = false self.translatesAutoresizingMaskIntoConstraints = false backgroundView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true backgroundView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true backgroundView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true backgroundView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func updateConstraints() { self.removeConstraints([self.minimumHeightConstraint, self.maximumHeightConstraint, self.leadingConstraint, self.trailingConstraint, self.topConstraint, self.widthConstraint ].flatMap({ return $0 })) self.minimumHeightConstraint = self.heightAnchor.constraint(greaterThanOrEqualToConstant: self.minimumHeight) self.maximumHeightConstraint = self.heightAnchor.constraint(lessThanOrEqualToConstant: self.maximumHeight) self.minimumHeightConstraint?.isActive = true self.maximumHeightConstraint?.isActive = true switch self.layoutMode { case .munual: self.topConstraint = self.topAnchor.constraint(equalTo: self.superview!.topAnchor, constant: frame.origin.y) self.leadingConstraint = self.leadingAnchor.constraint(equalTo: self.superview!.leadingAnchor, constant: frame.origin.x) self.widthConstraint = self.widthAnchor.constraint(equalToConstant: frame.size.width) self.topConstraint?.isActive = true self.leadingConstraint?.isActive = true self.widthConstraint?.isActive = true case .auto: self.leadingConstraint = self.leadingAnchor.constraint(equalTo: self.superview!.leadingAnchor) self.trailingConstraint = self.trailingAnchor.constraint(equalTo: self.superview!.trailingAnchor) self.leadingConstraint?.isActive = true self.trailingConstraint?.isActive = true } super.updateConstraints() } // MARK: - public func setItems(_ items: [ToolbarItem], animated: Bool) { self.stackView.arrangedSubviews.forEach { (view) in self.stackView.removeArrangedSubview(view) view.removeFromSuperview() } items.forEach { (view) in self.stackView.addArrangedSubview(view) } } // MARK: - private(set) lazy var stackView: UIStackView = { let view: UIStackView = UIStackView(frame: self.bounds) view.axis = .horizontal view.translatesAutoresizingMaskIntoConstraints = false view.distribution = .fillProportionally view.alignment = .bottom view.spacing = 0 return view }() private(set) lazy var backgroundView: UIVisualEffectView = { let blurEffect: UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight) let view: UIVisualEffectView = UIVisualEffectView(effect: blurEffect) view.translatesAutoresizingMaskIntoConstraints = false view.frame = self.bounds return view }() }
mit
ab7cdd70ba0f8c2103e4ede58fc4fc7a
34.281437
132
0.642057
5.48093
false
false
false
false
ddaguro/clintonconcord
OIMApp/DashboardViewController.swift
1
25674
// // DashboardViewController.swift // OIMApp // // Created by Linh NGUYEN on 5/19/15. // Copyright (c) 2015 Persistent Systems. All rights reserved. // import UIKit import LocalAuthentication class DashboardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let screenSize: CGRect = UIScreen.mainScreen().bounds var colorValues : [UIColor]? var arcSize : Double? @IBOutlet var dashView: UIView! var nagivationStyleToPresent : String? @IBOutlet weak var lblTotalCounts: UILabel! @IBOutlet var labelTitle: UILabel! @IBOutlet var tableView: UITableView! @IBOutlet var menuItem: UIBarButtonItem! @IBOutlet var toolbar: UIToolbar! @IBOutlet var recentActivityLabel: UILabel! var users : [Users]! var activities : [Activities]! var api : API! let transitionOperator = TransitionOperator() var refreshControl:UIRefreshControl! var isFirstTime = true //---> For Pagination var cursor = 1; let limit = 7; override func viewDidLoad() { super.viewDidLoad() //println("----->>> DashboardViewController") if myFIDO == false { showAlert() } menuItem.image = UIImage(named: "menu") toolbar.clipsToBounds = true labelTitle.text = "Dashboard" tableView.delegate = self tableView.dataSource = self getPendingCounts(myLoginId) var requestorUserId : String! requestorUserId = NSUserDefaults.standardUserDefaults().objectForKey("requestorUserId") as! String myRequestorId = requestorUserId self.users = [Users]() self.activities = [Activities]() self.api = API() //let url = myAPIEndpoint + "/users/" + requestorUserId //api.loadUser(requestorUserId, apiUrl: url, completion : didLoadUsers) //let url2 = myAPIEndpoint + "/users/" + myLoginId + "/recentactivity?limit=10" //let url2 = myAPIEndpoint + "/users/" + myLoginId + "/requests?limit=10&filter=reqCreationDate%20ge%202016-01-01" let url2 = myAPIEndpoint + "/users/" + myLoginId + "/requests?requestsForGivenDays=5&filter=reqCreationDate%20ge%202016-01-01&cursor=\(self.cursor)&limit=\(self.limit)" api.loadActivities(myLoginId, apiUrl: url2, completion : didLoadActivities) /* if myActivities.count == 0 { println("load from api") api.loadActivities(myLoginId, apiUrl: url2, completion : didLoadActivities) } else { println("load from storage") } */ refreshControl = UIRefreshControl() refreshControl.tintColor = UIColor.redColor() refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refreshControl) //---> PanGestureRecognizer let recognizer = UIPanGestureRecognizer(target: self, action: "panGestureRecognized:") self.view.addGestureRecognizer(recognizer) } func refresh(){ //let url2 = myAPIEndpoint + "/users/" + myLoginId + "/requests?limit=10&filter=reqCreationDate%20ge%202016-01-01" let url2 = myAPIEndpoint + "/users/" + myLoginId + "/requests?requestsForGivenDays=5&filter=reqCreationDate%20ge%202016-01-01&cursor=\(self.cursor)&limit=\(self.limit)" api.loadActivities(myLoginId, apiUrl: url2, completion : didLoadActivities) SoundPlayer.play("upvote.wav") } func showAlert(){ let createAccountErrorAlert: UIAlertView = UIAlertView() createAccountErrorAlert.delegate = self createAccountErrorAlert.title = "" createAccountErrorAlert.message = "Would you like to register for FIDO biometric authentication?" createAccountErrorAlert.addButtonWithTitle("Cancel") createAccountErrorAlert.addButtonWithTitle("OK") createAccountErrorAlert.show() } func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){ switch buttonIndex{ case 0: //NSLog("Cancel"); break; case 1: //NSLog("OK"); let context = LAContext() var error: NSError? // check if Touch ID is available if context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "Authenticate with Touch ID" context.evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: {(succes: Bool, error: NSError?) in dispatch_async(dispatch_get_main_queue(), { if succes { myFIDO = true let alert = UIAlertView(title: "Success \u{1F44D}", message: "FIDO UAF Authentication Succeeded", delegate: nil, cancelButtonTitle: "Okay") alert.show() } else { self.showAlertController("Touch ID Authentication Failed") } }) }) } break; default: NSLog("Default"); break; } } func showAlertController(message: String) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alertController, animated: true, completion: nil) } func appBtnTouched(sender:UIButton!) { let btnsendtag:UIButton = sender if btnsendtag.tag == 1 { //println("Button tapped pending approvals") self.performSegueWithIdentifier("SegueApprovals", sender: self) } } func reqBtnTouched(sender:UIButton!) { let btnsendtag:UIButton = sender if btnsendtag.tag == 2 { //println("Button tapped pending requests") self.performSegueWithIdentifier("SegueRequests", sender: self) } } func certBtnTouched(sender:UIButton!) { let btnsendtag:UIButton = sender if btnsendtag.tag == 3 { //println("Button tapped pending certifications") self.performSegueWithIdentifier("SegueCerts", sender: self) } } // MARK: swipe gestures func panGestureRecognized(sender: UIPanGestureRecognizer) { self.view.endEditing(true) self.frostedViewController.view.endEditing(true) self.frostedViewController.panGestureRecognized(sender) } /* func didLoadUsers(loadedUsers: [Users]){ for usr in loadedUsers { self.users.append(usr) } tableView.reloadData() } */ func didLoadActivities(loadedActivities: [Activities]){ self.activities = [Activities]() for act in loadedActivities { self.activities.append(act) } activities.sortInPlace({ $0.reqModifiedOnDate > $1.reqModifiedOnDate }) tableView.reloadData() view.hideLoading() if isFirstTime { self.view.showLoading() } self.tableView.reloadData() self.view.hideLoading() self.refreshControl?.endRefreshing() } func getPendingCounts(requestorUserId: String) { view.showDashLoading() self.lblTotalCounts.layer.cornerRadius = 9; lblTotalCounts.layer.masksToBounds = true; arcSize = degreesToRadians(360) let arcStart = 3/4 * M_PI let arcEnd = 3 * M_PI api = API() let url = myAPIEndpoint + "/users/" + requestorUserId + "/pendingoperationscount" api.getDashboardCount(myLoginId, apiUrl: url, completion: { (success) -> () in // --> Total Pending totalCounter = (myCertificates + myApprovals + myRequest) if (totalCounter > 0) { self.lblTotalCounts.hidden = false self.lblTotalCounts.layer.cornerRadius = 9 self.lblTotalCounts.layer.masksToBounds = true self.lblTotalCounts.text = "\(totalCounter)" } else { self.lblTotalCounts.hidden = true } // --> Chart Pending Approvals let apptotcnt = myApprovals == 0 ? 0 : myApprovals + totalCounter/2 let arcValues = [apptotcnt,0,totalCounter] let appradius = 90.0 let appCenter = CGPointMake(CGFloat(self.screenSize.width/2.0), CGFloat(85.0)) self.createArc(appCenter, radius: appradius, startAngle: arcStart, endAngle: arcEnd, color: self.UIColorFromHex(0xeeeeee, alpha: 1.0).CGColor) self.animateArcs(arcValues, radius: appradius, center: appCenter, color: self.UIColorFromHex(0x9777a8, alpha: 1.0).CGColor) let appcntlabel = UILabel(frame: CGRectMake(0, 0, 200, 200)) appcntlabel.center = CGPointMake(CGFloat(self.screenSize.width/2.0) , CGFloat(85.0)) appcntlabel.textAlignment = NSTextAlignment.Center appcntlabel.font = UIFont(name: MegaTheme.fontName, size: 40) appcntlabel.textColor = self.UIColorFromHex(0xa6afaa, alpha: 1.0) appcntlabel.text = "\(myApprovals)" self.dashView.addSubview(appcntlabel) let applabel = UILabel(frame: CGRectMake(0, 0, 200, 200)) applabel.center = CGPointMake(CGFloat(self.screenSize.width/2.0) , CGFloat(120.0)) applabel.textAlignment = NSTextAlignment.Center applabel.font = UIFont(name: MegaTheme.fontName, size: 12) applabel.textColor = self.UIColorFromHex(0xa6afaa, alpha: 1.0) applabel.numberOfLines = 2 applabel.text = "PENDING\nAPPROVALS" self.dashView.addSubview(applabel) let appButton = UIButton(type: UIButtonType.System) appButton.frame = CGRectMake(0, 0, 200, 200) appButton.center = CGPointMake(CGFloat(self.screenSize.width/2.0) , CGFloat(85.0)) appButton.addTarget(self, action: "appBtnTouched:", forControlEvents: UIControlEvents.TouchUpInside) appButton.tag = 1 self.dashView.addSubview(appButton) // --> Chart Pending Requests let reqtotcnt = myRequest == 0 ? 0 : myRequest + totalCounter/2 let arcValues2 = [reqtotcnt,10,totalCounter] let reqradius = 50.0 let reqCenter = CGPointMake(CGFloat(self.screenSize.width/2.0) - CGFloat(75.0) , CGFloat(260.0)) self.createArc(reqCenter, radius: reqradius, startAngle: arcStart, endAngle: arcEnd, color: self.UIColorFromHex(0xeeeeee, alpha: 1.0).CGColor) self.animateArcs(arcValues2, radius: reqradius, center: reqCenter, color: self.UIColorFromHex(0x4a90e2, alpha: 1.0).CGColor) let reqcntlabel = UILabel(frame: CGRectMake(0, 0, 200, 200)) reqcntlabel.center = CGPointMake(CGFloat(self.screenSize.width/2.0) - CGFloat(75.0) , CGFloat(260.0)) reqcntlabel.textAlignment = NSTextAlignment.Center reqcntlabel.font = UIFont(name: MegaTheme.fontName, size: 30) reqcntlabel.textColor = self.UIColorFromHex(0xa6afaa, alpha: 1.0) reqcntlabel.text = "\(myRequest)" self.dashView.addSubview(reqcntlabel) let reqlabel = UILabel(frame: CGRectMake(0, 0, 200, 200)) reqlabel.center = CGPointMake(CGFloat(self.screenSize.width/2.0) - CGFloat(75.0) , CGFloat(340.0)) reqlabel.textAlignment = NSTextAlignment.Center reqlabel.font = UIFont(name: MegaTheme.fontName, size: 12) reqlabel.textColor = self.UIColorFromHex(0xa6afaa, alpha: 1.0) reqlabel.numberOfLines = 2 reqlabel.text = "PENDING\nREQUESTS" self.dashView.addSubview(reqlabel) let reqButton = UIButton(type: UIButtonType.System) reqButton.frame = CGRectMake(0, 0, 100, 100) reqButton.center = CGPointMake(CGFloat(self.screenSize.width/2.0) - CGFloat(75.0) , CGFloat(260.0)) reqButton.addTarget(self, action: "reqBtnTouched:", forControlEvents: UIControlEvents.TouchUpInside) reqButton.tag = 2 self.tableView.addSubview(reqButton) // --> Chart Pending Certfications let certtotcnt = myCertificates == 0 ? 0 : myCertificates + totalCounter/2 let arcValues3 = [certtotcnt,10,totalCounter] let certradius = 50.0 let certCenter = CGPointMake(CGFloat(self.screenSize.width/2.0) + CGFloat(75.0) , CGFloat(260.0)) self.createArc(certCenter, radius: certradius, startAngle: arcStart, endAngle: arcEnd, color: self.UIColorFromHex(0xeeeeee, alpha: 1.0).CGColor) self.animateArcs(arcValues3, radius: certradius, center: certCenter,color: self.UIColorFromHex(0x88c057, alpha: 1.0).CGColor) let certcntlabel = UILabel(frame: CGRectMake(0, 0, 200, 200)) certcntlabel.center = CGPointMake(CGFloat(self.screenSize.width/2.0) + CGFloat(75.0) , CGFloat(260.0)) certcntlabel.textAlignment = NSTextAlignment.Center certcntlabel.font = UIFont(name: MegaTheme.fontName, size: 30) certcntlabel.textColor = self.UIColorFromHex(0xa6afaa, alpha: 1.0) certcntlabel.text = "\(myCertificates)" self.dashView.addSubview(certcntlabel) let certlabel = UILabel(frame: CGRectMake(0, 0, 200, 200)) certlabel.center = CGPointMake(CGFloat(self.screenSize.width/2.0) + CGFloat(75.0) , CGFloat(340.0)) certlabel.textAlignment = NSTextAlignment.Center certlabel.font = UIFont(name: MegaTheme.fontName, size: 12) certlabel.textColor = self.UIColorFromHex(0xa6afaa, alpha: 1.0) certlabel.numberOfLines = 2 certlabel.text = "PENDING\nCERTIFICATIONS" self.dashView.addSubview(certlabel) let certButton = UIButton(type: UIButtonType.System) certButton.frame = CGRectMake(0, 0, 100, 100) certButton.center = CGPointMake(CGFloat(self.screenSize.width/2.0) + CGFloat(75.0) , CGFloat(260.0)) certButton.addTarget(self, action: "certBtnTouched:", forControlEvents: UIControlEvents.TouchUpInside) certButton.tag = 3 self.dashView.addSubview(certButton) let lblHeading : UILabel! = UILabel(frame: CGRectMake(0, CGFloat(360.0), self.view.frame.size.width, 30)) lblHeading.backgroundColor = UIColor(red: 236.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, alpha: 1) //lblHeading.layer.borderWidth = 1 //lblHeading.layer.borderColor = UIColor.lightGrayColor().CGColor lblHeading.font = UIFont.systemFontOfSize(12) lblHeading.textColor = UIColor.darkGrayColor() lblHeading.text = " Recent Activity" self.dashView.addSubview(lblHeading) // --> Recent Activity /* let recentimage = UIImage(named: "recentactivity") let recentimageView = UIImageView(image: recentimage!) recentimageView.frame = CGRect(x: 0, y: CGFloat(self.screenSize.height/2.0) + CGFloat(380.0), width: self.screenSize.width, height: self.screenSize.height) recentimageView.contentMode = UIViewContentMode.ScaleAspectFill self.tableView.addSubview(recentimageView) */ }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return users.count; return activities.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DashboardCell") as! DashboardCell let info = activities[indexPath.row] if info.requester.lowercaseString == "kevin clark" { cell.profileImage.image = UIImage(named: "kclark") } else if info.requester.lowercaseString == "grace davis" { cell.profileImage.image = UIImage(named: "gdavis") } else if info.requester.lowercaseString == "danny crane" { cell.profileImage.image = UIImage(named: "dcrane") } else { cell.profileImage.image = UIImage(named: "profileBlankPic") } //cell.profileImage.image = UIImage(named: "dcrane") var titleText = "" for ent in info.reqTargetEntities { if titleText.isEmpty { titleText = ent.entityname } else { titleText += " , \(ent.entityname)" } } cell.titleLabel.text = titleText //cell.titleLabel.adjustsFontSizeToFitWidth = true //cell.statusImage.image = info.reqStatus == "Request Completed" ? UIImage(named: "badge-new") : UIImage(named: "Badge-Assigned") cell.statusLabel.text = " " + info.reqStatus.stringByReplacingOccurrencesOfString("Request ", withString: "") + " " var statuscolor : UIColor switch info.reqStatus { case "Request Rejected": statuscolor = self.UIColorFromHex(0xed7161, alpha: 1.0) break; case "Request Awaiting Approval": statuscolor = self.UIColorFromHex(0xeeaf4b, alpha: 1.0) break; case "Request Completed": statuscolor = self.UIColorFromHex(0x88c057, alpha: 1.0) break; case "Request Awaiting Child Requests Completion": statuscolor = self.UIColorFromHex(0x47a0db, alpha: 1.0) break; case "Request Approved Fulfillment Pending": statuscolor = self.UIColorFromHex(0x9777a8, alpha: 1.0) break; case "Request Awaiting Dependent Request Completion": statuscolor = self.UIColorFromHex(0x47a0db, alpha: 1.0) break; default: statuscolor = self.UIColorFromHex(0x546979, alpha: 1.0) break; } cell.statusLabel.backgroundColor = statuscolor //cell.statusLabel.adjustsFontSizeToFitWidth = true //cell.subtitleLabel.text = "Request ID " + info.reqId cell.assigneeHeadingLabel.text = "Assignees" var assigneeText = "" for assign in info.reqBeneficiaryList { if assigneeText.isEmpty { assigneeText = assign.beneficiary } else { assigneeText += " , \(assign.beneficiary)" } } cell.assigneeLabel.text = assigneeText cell.dateLabel.text = info.reqModifiedOnDate /* var approverText = "" for approve in info.currentApprovers { if approverText.isEmpty { approverText = approve.approvers } } */ cell.descriptionLabel.text = " ID: " + info.reqId + " | Type: " + info.reqType //let info = users[indexPath.row] //cell.titleLabel.text = info.DisplayName //cell.subtitleLabel.text = info.Email //NSUserDefaults.standardUserDefaults().setObject(info.DisplayName, forKey: "DisplayName") //NSUserDefaults.standardUserDefaults().setObject(info.Title, forKey: "Title") //NSUserDefaults.standardUserDefaults().synchronize() return cell; } @IBAction func presentNavigation(sender: AnyObject) { self.view.endEditing(true) self.frostedViewController.view.endEditing(true) self.frostedViewController.presentMenuViewController() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let toViewController = segue.destinationViewController self.modalPresentationStyle = UIModalPresentationStyle.Custom toViewController.transitioningDelegate = self.transitionOperator } /* Circle Chart */ func animateArcs(arcValues:Array<Int>, radius: Double, center: CGPoint, color: CGColor) { let sum = arcValues.reduce(0,combine: +) var currentOffset = 0 var currentStartAngle : Double? var currentEndAngle : Double? var currentDelay : Double = 0 for var i = 0; i < arcValues.count; i++ { let duration = Double(CGFloat(arcValues[i])/CGFloat(sum)) if currentEndAngle == nil { currentStartAngle = degreesToRadians(120) } else { currentStartAngle = currentEndAngle } if (CGFloat(self.arcSize!) * CGFloat(duration) + CGFloat(currentStartAngle!)) > CGFloat(M_PI*2) { currentEndAngle = Double((CGFloat(self.arcSize!) * CGFloat(duration) + CGFloat(currentStartAngle!)) - CGFloat(M_PI*2)) } else { currentEndAngle = Double((CGFloat(self.arcSize!) * CGFloat(duration) + CGFloat(currentStartAngle!))) } var currentDelaySeconds = currentDelay as Double var time = dispatch_time(DISPATCH_TIME_NOW, Int64(currentDelay * Double(NSEC_PER_SEC))) var currentColor : CGColor? if i % 2 == 0 { currentColor = color } else { currentColor = UIColor.redColor().CGColor } self.createAnimatedArc(center, radius: radius, startAngle: currentStartAngle!, endAngle: currentEndAngle!, color: currentColor!, duration: duration, beginTime: currentDelay, z: CGFloat(-1 * i)) currentDelay += duration } } func createArc(center: CGPoint, radius: Double, startAngle : Double, endAngle : Double, color : CGColor) { let arc = CAShapeLayer() arc.lineCap = kCALineCapRound //arc.zPosition = -1000 arc.path = UIBezierPath(arcCenter: center, radius: CGFloat(radius), startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true).CGPath arc.fillColor = UIColor.whiteColor().CGColor arc.strokeColor = color arc.lineWidth = 14 arc.strokeEnd = CGFloat(2.5 * M_PI) self.dashView.layer.addSublayer(arc) } func createAnimatedArc(center: CGPoint, radius: Double, startAngle : Double, endAngle : Double, color : CGColor, duration: Double, beginTime: Double, z: CGFloat) { let arc = CAShapeLayer() arc.zPosition = z arc.path = UIBezierPath(arcCenter: center, radius: CGFloat(radius), startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true).CGPath arc.fillColor = UIColor.clearColor().CGColor arc.strokeColor = color arc.lineCap = kCALineCapRound arc.lineWidth = 14 var originalStrokeEnd = 0 arc.strokeStart = 0 arc.strokeEnd = 0 let arcAnimation = CABasicAnimation(keyPath:"strokeEnd") arcAnimation.fromValue = NSNumber(double: 0) arcAnimation.toValue = NSNumber(double: 1) arcAnimation.duration = duration arcAnimation.beginTime = CFTimeInterval(CACurrentMediaTime() + beginTime) arcAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) arc.addAnimation(arcAnimation, forKey: "drawCircleAnimation") self.dashView.layer.addSublayer(arc) let delay = (duration + beginTime - 0.07) * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { let finalArc = CAShapeLayer() finalArc.zPosition = z finalArc.lineCap = kCALineCapRound finalArc.path = UIBezierPath(arcCenter: center, radius: CGFloat(radius), startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true).CGPath finalArc.fillColor = UIColor.clearColor().CGColor finalArc.strokeColor = color finalArc.lineWidth = 14 var originalStrokeEnd = 0 finalArc.strokeStart = 0 finalArc.strokeEnd = 1 self.dashView.layer.addSublayer(finalArc) }) } func degreesToRadians(degrees: Double) -> Double { return degrees / 180.0 * M_PI } func radiansToDegrees(radians: Double) -> Double { return radians * (180.0 / M_PI) } func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor { let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha)) } }
mit
f1314e78efda549e2ab4d4c0a080cc7e
42.222222
205
0.61054
4.66122
false
false
false
false
GabrielGhe/SwiftProjects
App13CardTilt/CardTilt/MainViewController.swift
1
1794
// // MainViewController.swift // CardTilt // // Created by Ray Fix on 6/25/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import UIKit class MainViewController: UITableViewController { var members:[Member] = [] // MARK: - Model func loadModel() { let path = NSBundle.mainBundle().pathForResource("TeamMembers", ofType: "json") members = Member.loadMembersFromFile(path!) } // MARK: - View Lifetime override func viewDidLoad() { super.viewDidLoad() // appearance and layout customization self.tableView.backgroundView = UIImageView(image:UIImage(named:"background")) self.tableView.estimatedRowHeight = 280 self.tableView.rowHeight = UITableViewAutomaticDimension // load our model loadModel(); } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return members.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Card", forIndexPath: indexPath) as CardTableViewCell let member = members[indexPath.row] cell.useMember(member) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { TipInCellAnimator.animateByRotating(cell) } }
mit
10fc2dd8ad11d149ab2621a282f3202e
28.9
134
0.675585
5.339286
false
false
false
false
nicolasgomollon/LPRTableView
ReorderTest/ReorderTest/MasterViewController.swift
1
5083
// // MasterViewController.swift // ReorderTest // // Created by Nicolas Gomollon on 6/17/14. // Copyright (c) 2014 Techno-Magic. All rights reserved. // import UIKit class MasterViewController: LPRTableViewController { var objects: Array<Date> = .init() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.leftBarButtonItem = editButtonItem navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func insertNewObject(_ sender: AnyObject) { objects.insert(Date(), at: 0) let indexPath: IndexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object: Date = objects[indexPath.row] cell.textLabel?.text = object.description // // Reset any possible modifications made in `tableView:draggingCell:atIndexPath:` // to avoid reusing the modified cell. // // cell.backgroundColor = .white return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let object: Date = objects[indexPath.row] let detailViewController: DetailViewController = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController detailViewController.detailItem = object as AnyObject? navigationController?.pushViewController(detailViewController, animated: true) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "showDetail", let indexPath: IndexPath = tableView.indexPathForSelectedRow else { return } let object: Date = objects[indexPath.row] (segue.destination as! DetailViewController).detailItem = object as AnyObject? } // MARK: - Long Press Reorder // // Important: Update your data source after the user reorders a cell. // override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { objects.insert(objects.remove(at: sourceIndexPath.row), at: destinationIndexPath.row) } // // Optional: Modify the cell (visually) before dragging occurs. // // NOTE: Any changes made here should be reverted in `tableView:cellForRowAtIndexPath:` // to avoid accidentally reusing the modifications. // override func tableView(_ tableView: UITableView, draggingCell cell: UITableViewCell, at indexPath: IndexPath) -> UITableViewCell { // cell.backgroundColor = UIColor(red: 165.0/255.0, green: 228.0/255.0, blue: 255.0/255.0, alpha: 1.0) return cell } // // Optional: Called within an animation block when the dragging view is about to show. // override func tableView(_ tableView: UITableView, showDraggingView view: UIView, at indexPath: IndexPath) { print("The dragged cell is about to be animated!") } // // Optional: Called within an animation block when the dragging view is about to hide. // override func tableView(_ tableView: UITableView, hideDraggingView view: UIView, at indexPath: IndexPath) { print("The dragged cell is about to be dropped.") } }
mit
4840c07b2e4e39162eed9f73fd2cd249
37.801527
161
0.664962
5.176171
false
false
false
false
blinker13/UI
Sources/Geometry/Shapes/Rectangle.swift
1
2262
public struct Rectangle : Equatable, Shape { public let origin: Point public let size: Size public init(origin: Point = .zero, size: Size) { self.origin = origin self.size = size } } // MARK: - public extension Rectangle { @inlinable static var zero: Self { .init(origin: .zero, size: .zero) } @inlinable static var null: Self { .init(origin: .infinity, size: .zero) } @inlinable var x: Scalar { origin.x } @inlinable var y: Scalar { origin.y } @inlinable var width: Scalar { abs(size.width) } @inlinable var height: Scalar { abs(size.height) } @inlinable var minX: Scalar { min(x, x + size.width) } @inlinable var minY: Scalar { min(y, y + size.height) } @inlinable var midX: Scalar { (minX + maxX) * 0.5 } @inlinable var midY: Scalar { (minY + maxY) * 0.5 } @inlinable var maxX: Scalar { max(x, x + size.width) } @inlinable var maxY: Scalar { max(y, y + size.height) } @inlinable var center: Point { .init(x: midX, y: midY) } @inlinable var horizontal: Range<Scalar> { minX ..< maxX } @inlinable var vertical: Range<Scalar> { minY ..< maxY } @inlinable var isNull: Bool { x == .infinity || y == .infinity } @inlinable var isEmpty: Bool { isNull || size.isEmpty } @inlinable var path: Path { [ .move(to: .init(x: minX, y: minY)), .line(to: .init(x: maxX, y: minY)), .line(to: .init(x: maxX, y: maxY)), .line(to: .init(x: minX, y: maxY)), .close ] } @inlinable init(x: Scalar = .zero, y: Scalar = .zero, width: Scalar, height: Scalar) { (self.origin, self.size) = (.init(x: x, y: y), .init(width: width, height: height)) } @inlinable init(origin: Point = .zero, sides: Scalar) { (self.origin, self.size) = (origin, .init(sides: sides)) } @inlinable func contains(_ point: Point) -> Bool { vertical.contains(point.x) && horizontal.contains(point.y) } @inlinable func inset(_ space: Space) -> Self { let new = Point(origin.storage + space.storage.highHalf) return .init(origin: new, size: size.inseted(by: space)) } } // MARK: - // //extension Rectangle : Transformable { // public func applying(_ transform: Transform) -> Self { // let newOrigin = origin.applying(transform) // let newSize = size.applying(transform) // return .init(origin: newOrigin, size: newSize) // } //}
mit
a372e00428b12b7250ce893de2347adf
28
87
0.645004
2.984169
false
false
false
false
Roche/viper-module-generator
VIPERGenDemo/VIPERGenDemo/Application/AppDelegate.swift
4
2596
// // AppDelegate.swift // VIPERGenDemo // // Created by AUTHOR on 22/08/14. // Copyright (c) 2014 ___PPinera___. All rights reserved. // import UIKit import SwifteriOS @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) setupStorage() self.launchRootViewDependingOnLoggedStatus() window!.makeKeyAndVisible() return true } func application(application: UIApplication!, openURL url: NSURL!, sourceApplication: String!, annotation: AnyObject!) -> Bool { TwitterClient.handleOpenURL(url) return true } // MARK - Helpers /** Check the account status and presents (Login | Home) */ func launchRootViewDependingOnLoggedStatus() { if TwitterAccountManager.isUserLogged() { let twitterClientSetup: Bool = self.setupTwitterClient() if (!twitterClientSetup) { TwitterLoginWireFrame.presentTwitterLoginModule(inWindow: window!) } else { TwitterListWireFrame.presentTwitterListModule(inWindow: window!) } } else { TwitterLoginWireFrame.presentTwitterLoginModule(inWindow: window!) } } /** Restores the user account in case of having the credentials locally :returns: Bool indicating if the TwitterClient credentials has been properly restored */ func setupTwitterClient() -> Bool { let key: String? = TwitterAccountManager.attribute(TwitterAccountAttribute.TwitterAccountAttributeKey) as? String let secret: String? = TwitterAccountManager.attribute(TwitterAccountAttribute.TwitterAccountAttributeSecret) as? String if (key == nil || secret == nil) { return false } else { TwitterClient.sharedInstance.client.credential = SwifterCredential(accessToken: SwifterCredential.OAuthAccessToken(key: key!, secret: secret!)) return true } } func applicationWillResignActive(application: UIApplication!) { SugarRecord.applicationWillResignActive() } func applicationWillEnterForeground(application: UIApplication!) { SugarRecord.applicationWillEnterForeground() } func applicationWillTerminate(application: UIApplication!) { SugarRecord.applicationWillTerminate() } }
mit
5f524205d40895fd58d540c511877304
31.860759
155
0.672958
5.558887
false
false
false
false
larryhou/swift
TexasHoldem/TexasHoldem/PatternTableViewCell.swift
1
1635
// // HandPatternTableCellView.swift // TexasHoldem // // Created by larryhou on 12/3/2016. // Copyright © 2016 larryhou. All rights reserved. // import Foundation import UIKit class PatternTableViewCell: UITableViewCell { private static var color_hash: [HandPattern: UIColor] { var hash: [HandPattern: UIColor] = [:] hash[.highCard] = UIColor(white: 0.90, alpha: 1.0) hash[.onePair] = UIColor(white: 0.75, alpha: 1.0) hash[.twoPair] = UIColor(white: 0.50, alpha: 1.0) hash[.threeOfKind] = UIColor(white: 0.00, alpha: 1.0) hash[.straight] = UIColor.green() hash[.flush] = UIColor.blue() hash[.fullHouse] = UIColor(red: 0.5, green: 0.0, blue: 1.0, alpha: 1.0) hash[.fourOfKind] = UIColor.orange() hash[.straightFlush] = UIColor.red() return hash } @IBOutlet weak var id: UILabel! @IBOutlet weak var pattern: UILabel! @IBOutlet weak var givenCards: UILabel! @IBOutlet weak var tableCards: UILabel! @IBOutlet weak var matchCards: UILabel! private var hand: PokerHand = PokerHand() func renderView(_ data: RawPokerHand) { PokerHand.parse(data.data, hand: hand) hand.evaluate() id.text = String(format: "%07d", data.index + 1) pattern.text = hand.pattern.description pattern.textColor = PatternTableViewCell.color_hash[hand.pattern] givenCards.text = hand.givenCards.toString() tableCards.text = hand.tableCards.toString() matchCards.text = hand.matches.toString() } }
mit
72d48d0df8aa00e0373cd6a3936b831d
33.041667
86
0.616279
3.705215
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieCore/Compression/CompressionCodec.swift
1
2753
// // CompressionCodec.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public protocol CompressionCodec: AnyObject { func update(_ source: UnsafeBufferPointer<UInt8>, _ callback: (UnsafeBufferPointer<UInt8>) throws -> Void) throws func finalize(_ callback: (UnsafeBufferPointer<UInt8>) throws -> Void) throws func process<C: RangeReplaceableCollection>(_ source: Data, _ output: inout C) throws where C.Element == UInt8 } extension CompressionCodec { @inlinable public func update<S: DataProtocol>(_ source: S, _ callback: (UnsafeBufferPointer<UInt8>) throws -> Void) throws { try source.regions.forEach { try $0.withUnsafeBytes { try update($0.bindMemory(to: UInt8.self), callback) } } } @inlinable public func update<S: DataProtocol, C: RangeReplaceableCollection>(_ source: S, _ output: inout C) throws where C.Element == UInt8 { try update(source) { output.append(contentsOf: $0) } } @inlinable public func finalize<C: RangeReplaceableCollection>(_ output: inout C) throws where C.Element == UInt8 { try finalize { output.append(contentsOf: $0) } } } extension CompressionCodec { @inlinable public func process<C: RangeReplaceableCollection>(_ source: Data, _ output: inout C) throws where C.Element == UInt8 { try self.update(source, &output) try self.finalize(&output) } @inlinable public func process(_ source: Data) throws -> Data { var result = Data(capacity: source.count) try self.process(source, &result) return result } }
mit
be37c572fc43b09ea2694756af498d25
40.089552
136
0.701417
4.342271
false
false
false
false
kbelter/SnazzyList
SnazzyList/Classes/src/Helpers/extensions/UICollectionView.swift
1
1546
// // UICollectionView.swift // Noteworth2 // // Created by Kevin on 12/20/18. // Copyright © 2018 Noteworth. All rights reserved. // import UIKit extension UICollectionView { public static func getDefault(adjustmentBehavior: UIScrollView.ContentInsetAdjustmentBehavior = .automatic, direction: UICollectionView.ScrollDirection = .vertical, itemSpacing: CGFloat = 0, lineSpacing: CGFloat = 0, pinHeader: Bool = false, alwaysBounceVertical: Bool = true, contentInset: UIEdgeInsets = .zero, isPagingEnabled: Bool = false) -> UICollectionView { let layout = UICollectionViewFlowLayout() layout.scrollDirection = direction layout.minimumInteritemSpacing = itemSpacing layout.minimumLineSpacing = lineSpacing layout.sectionHeadersPinToVisibleBounds = pinHeader let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.allowsMultipleSelection = false collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = alwaysBounceVertical collectionView.contentInset = contentInset collectionView.isPagingEnabled = isPagingEnabled collectionView.contentInsetAdjustmentBehavior = adjustmentBehavior collectionView.isAccessibilityElement = false return collectionView } }
apache-2.0
55a2bdc0ed447010c632a98d01996dac
47.28125
369
0.756634
6.410788
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/iPhone/Classes/Animations/EventsToEventDetailTransition.swift
1
9624
// // EventsToEventDetailTransition.swift // AllStarsV2 // // Created by Javier Siancas Fajardo on 9/25/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class EventsToEventDetailInteractiveTransition : InteractiveTransition { var initialScale: CGFloat = 0 @objc func gestureTransitionMethod(_ gesture : UIPanGestureRecognizer){ let view = self.navigationController.view! if gesture.state == .began { self.interactiveTransition = UIPercentDrivenInteractiveTransition() self.navigationController.popViewController(animated: true) } else if gesture.state == .changed { let translation = gesture.translation(in: view) let delta = fabs(translation.x / view.bounds.width) self.interactiveTransition?.update(delta) } else { self.interactiveTransition?.finish() self.interactiveTransition = nil } } } class EventsToEventDetailTransition: ControllerTransition { override func createInteractiveTransition(navigationController: UINavigationController) -> InteractiveTransition? { let interactiveTransition = EventsToEventDetailInteractiveTransition() interactiveTransition.navigationController = navigationController interactiveTransition.gestureTransition = UIPanGestureRecognizer(target: interactiveTransition, action: #selector(interactiveTransition.gestureTransitionMethod(_:))) interactiveTransition.navigationController.view.addGestureRecognizer(interactiveTransition.gestureTransition!) return interactiveTransition } override func animatePush(toContext context : UIViewControllerContextTransitioning) { let eventsViewController = self.controllerOrigin as! EventsViewController let eventDetailViewController = self.controllerDestination as! EventDetailViewController let frameForEventImageViewSelected = eventsViewController.frameForEventImageViewSelected let containerView = context.containerView containerView.backgroundColor = .white let fromView = context.view(forKey: .from)! fromView.frame = UIScreen.main.bounds containerView.addSubview(fromView) let toView = context.view(forKey: .to)! toView.frame = UIScreen.main.bounds toView.backgroundColor = .clear containerView.addSubview(toView) eventsViewController.headerView.alpha = 0.0 eventsViewController.cellSelected.alpha = 0.0 eventDetailViewController.headerView.alpha = 1.0 eventDetailViewController.eventInformationView.alpha = 0.0 eventDetailViewController.eventInformationBackgroundView.alpha = 0.0 eventDetailViewController.buttonsSectionView.alpha = 0.0 eventDetailViewController.scrollContent.alpha = 0.0 eventDetailViewController.imgEvent.layer.cornerRadius = 8.0 eventDetailViewController.eventInformationBackgroundView.layer.cornerRadius = 8.0 eventDetailViewController.buttonsSectionsViewTopConstraint.constant = 50.0 eventDetailViewController.eventTitleLabelTopConstraint.constant = 58.0 eventDetailViewController.backgroundImageViewLeadingConstraint.constant = frameForEventImageViewSelected!.origin.x eventDetailViewController.backgroundImageViewTopConstraint.constant = frameForEventImageViewSelected!.origin.y eventDetailViewController.backgroundImageViewWidthConstraint.constant = frameForEventImageViewSelected!.width eventDetailViewController.backgroundImageViewHeightConstraint.constant = frameForEventImageViewSelected!.height containerView.layoutIfNeeded() eventDetailViewController.view.layoutIfNeeded() UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { fromView.alpha = 0.0 toView.backgroundColor = .white eventDetailViewController.eventInformationBackgroundView.layer.cornerRadius = 0.0 eventDetailViewController.imgEvent.layer.cornerRadius = 0.0 eventDetailViewController.backgroundImageViewLeadingConstraint.constant = 0.0 eventDetailViewController.backgroundImageViewTopConstraint.constant = 0.0 eventDetailViewController.backgroundImageViewWidthConstraint.constant = UIScreen.main.bounds.width eventDetailViewController.backgroundImageViewHeightConstraint.constant = 180.0 eventDetailViewController.view.layoutIfNeeded() }, completion: nil) UIView.animate(withDuration: 0.5, delay: 0.1, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { eventDetailViewController.headerView.alpha = 1.0 eventDetailViewController.eventInformationBackgroundView.alpha = 1.0 eventDetailViewController.buttonsSectionsViewTopConstraint.constant = 0.0 eventDetailViewController.eventTitleLabelTopConstraint.constant = 8.0 eventDetailViewController.view.layoutIfNeeded() }, completion: nil) UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseOut, animations: { eventDetailViewController.eventInformationView.alpha = 1.0 eventDetailViewController.buttonsSectionView.alpha = 1.0 eventDetailViewController.scrollContent.alpha = 1.0 }) { (_) in context.completeTransition(true) } } override func animatePop(toContext context : UIViewControllerContextTransitioning) { let eventDetailViewController = self.controllerOrigin as! EventDetailViewController let eventsViewController = self.controllerDestination as! EventsViewController let frameForEventImageViewSelected = eventsViewController.frameForEventImageViewSelected let containerView = context.containerView containerView.backgroundColor = .white let toView = context.view(forKey: .to)! toView.frame = UIScreen.main.bounds toView.backgroundColor = .white toView.alpha = 1.0 containerView.addSubview(toView) let fromView = context.view(forKey: .from)! fromView.frame = UIScreen.main.bounds fromView.backgroundColor = .clear containerView.addSubview(fromView) eventsViewController.headerView.alpha = 1.0 eventDetailViewController.headerView.alpha = 0.0 eventDetailViewController.eventInformationView.alpha = 0.0 eventDetailViewController.buttonsSectionView.alpha = 0.0 eventDetailViewController.scrollContent.alpha = 0.0 eventDetailViewController.imgEvent.layer.cornerRadius = 8.0 eventDetailViewController.eventInformationBackgroundView.layer.cornerRadius = 8.0 eventDetailViewController.buttonsSectionsViewTopConstraint.constant = 50.0 eventDetailViewController.eventTitleLabelTopConstraint.constant = 58.0 eventDetailViewController.view.layoutIfNeeded() UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { eventDetailViewController.eventInformationBackgroundView.alpha = 0.0 eventDetailViewController.backgroundImageViewLeadingConstraint.constant = frameForEventImageViewSelected!.origin.x eventDetailViewController.backgroundImageViewTopConstraint.constant = frameForEventImageViewSelected!.origin.y eventDetailViewController.backgroundImageViewWidthConstraint.constant = frameForEventImageViewSelected!.width eventDetailViewController.backgroundImageViewHeightConstraint.constant = frameForEventImageViewSelected!.height eventDetailViewController.view.layoutIfNeeded() }, completion: nil) UIView.animate(withDuration: 0.15, delay: 0.45, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { eventsViewController.cellSelected.alpha = 1.0 }, completion: { (_) in context.completeTransition(true) }) } override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.6 } }
apache-2.0
613e92ffbb1b6bba9db71f020c4d58fe
47.60101
173
0.646576
6.364418
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
examples/swift-tool/MapReduce.playground/Contents.swift
1
1426
import Foundation // --- Map --- let things = Array(arrayLiteral: ["apple", "pear", "banana"]) let fruits = ["apple", "pear", "banana"] let capitalizedFruits = fruits.map { $0.capitalizedString } print(capitalizedFruits) // prints "[Apple, Pear, Banana]" let veggies = ["onion", "carrot", "celery"] let foodGroups = [fruits, veggies] let foods = foodGroups.flatMap { $0.map { $0.capitalizedString } } print(foods) // prints "[Apple, Pear, Banana, Onion, Carrot, Celery]" let sortedFoods = foods.sort { $0 < $1 } print(sortedFoods) // prints "[Apple, Banana, Carrot, Celery, Onion, Pear]" // --- Reduce --- var ints = [Int]() ints.appendContentsOf(1...5) let sum = ints.reduce(0) { currSum, currVal in return currSum + currVal } print(sum) // prints 15 let sum2 = ints.reduce(0) { $0 + $1 } print(sum2) let sum3 = ints.reduce(0, combine: +) let factorial = ints.reduce(1) { currTotal, currVal in return currTotal * currVal } let fact = ints.reduce(1, combine: *) //prints 120 let string = fruits.reduce("favorites: ") { text, fruit in return "\(text)\(fruit), " } print(string) // prints "favorites: apple, pear, banana, " let fruitsText = fruits.reduce("favorites: ") { "\($0)\($1), " } print(fruitsText) // prints "favorites: apple, pear, banana, " let fruitsText2 = fruits.reduce("favorites: ") { $0 + $1 + ", " } print(fruitsText2) // prints "favorites: apple, pear, banana, "
mit
ad6b4283c8f8851bdacbf74204c897ac
17.763158
66
0.645161
3.073276
false
false
false
false
sbutler2901/IPCanary
IPCanary/MainViewController.swift
1
2145
// // MainViewController.swift // IPCanary // // Created by Seth Butler on 12/15/16. // Copyright © 2016 SBSoftware. All rights reserved. // import UIKit import UserNotifications class MainViewController: UIViewController , ViewModelUpdatable { // MARK: - Class Variables private let mainViewModel: MainViewModel // MARK: - IBOutlets @IBOutlet var currentIPLabel: UILabel! @IBOutlet var cityLabel: UILabel! @IBOutlet var countryLabel: UILabel! @IBOutlet var hostnameLabel: UILabel! @IBOutlet var ipLastUpdateLabel: UILabel! @IBOutlet var ipLastChangedLabel: UILabel! @IBOutlet var refreshBtn: UIButton! // MARK: - IBActions @IBAction func refreshPressed(_ sender: Any) { mainViewModel.refreshIP() } // MARK: - MVVM Functions func viewModelDidUpdate() { currentIPLabel.text = mainViewModel.currentIP cityLabel.text = mainViewModel.city countryLabel.text = mainViewModel.country hostnameLabel.text = mainViewModel.hostname ipLastUpdateLabel.text = mainViewModel.ipLastUpdate ipLastChangedLabel.text = mainViewModel.ipLastChanged } // MARK: - View Controller Methods init(mainViewModel: MainViewModel) { self.mainViewModel = mainViewModel super.init(nibName: "MainView", bundle: nil) self.mainViewModel.delegate = self } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModelDidUpdate() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //mainViewModel.refreshIP() refreshBtn.layer.cornerRadius = 7.0 refreshBtn.layer.borderWidth = 1 refreshBtn.layer.borderColor = UIColor.white.cgColor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
4ef79bb24ff0d32f7c9f65246c06ae81
26.487179
80
0.665578
5.056604
false
false
false
false
mattrajca/swift-corelibs-foundation
Foundation/NSNumber.swift
2
36520
// 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 // import CoreFoundation #if os(OSX) || os(iOS) internal let kCFNumberSInt8Type = CFNumberType.sInt8Type internal let kCFNumberSInt16Type = CFNumberType.sInt16Type internal let kCFNumberSInt32Type = CFNumberType.sInt32Type internal let kCFNumberSInt64Type = CFNumberType.sInt64Type internal let kCFNumberFloat32Type = CFNumberType.float32Type internal let kCFNumberFloat64Type = CFNumberType.float64Type internal let kCFNumberCharType = CFNumberType.charType internal let kCFNumberShortType = CFNumberType.shortType internal let kCFNumberIntType = CFNumberType.intType internal let kCFNumberLongType = CFNumberType.longType internal let kCFNumberLongLongType = CFNumberType.longLongType internal let kCFNumberFloatType = CFNumberType.floatType internal let kCFNumberDoubleType = CFNumberType.doubleType internal let kCFNumberCFIndexType = CFNumberType.cfIndexType internal let kCFNumberNSIntegerType = CFNumberType.nsIntegerType internal let kCFNumberCGFloatType = CFNumberType.cgFloatType internal let kCFNumberSInt128Type = CFNumberType(rawValue: 17)! #else internal let kCFNumberSInt128Type: CFNumberType = 17 #endif extension Int8 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int8Value } public init(truncating number: NSNumber) { self = number.int8Value } public init?(exactly number: NSNumber) { let value = number.int8Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int8?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int8?) -> Bool { guard let value = Int8(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int8 { var result: Int8? guard let src = source else { return Int8(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int8(0) } return result! } } extension UInt8 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint8Value } public init(truncating number: NSNumber) { self = number.uint8Value } public init?(exactly number: NSNumber) { let value = number.uint8Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt8?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt8?) -> Bool { guard let value = UInt8(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt8 { var result: UInt8? guard let src = source else { return UInt8(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt8(0) } return result! } } extension Int16 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int16Value } public init(truncating number: NSNumber) { self = number.int16Value } public init?(exactly number: NSNumber) { let value = number.int16Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int16?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int16?) -> Bool { guard let value = Int16(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int16 { var result: Int16? guard let src = source else { return Int16(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int16(0) } return result! } } extension UInt16 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint16Value } public init(truncating number: NSNumber) { self = number.uint16Value } public init?(exactly number: NSNumber) { let value = number.uint16Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt16?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt16?) -> Bool { guard let value = UInt16(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt16 { var result: UInt16? guard let src = source else { return UInt16(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt16(0) } return result! } } extension Int32 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int32Value } public init(truncating number: NSNumber) { self = number.int32Value } public init?(exactly number: NSNumber) { let value = number.int32Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int32?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int32?) -> Bool { guard let value = Int32(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int32 { var result: Int32? guard let src = source else { return Int32(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int32(0) } return result! } } extension UInt32 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint32Value } public init(truncating number: NSNumber) { self = number.uint32Value } public init?(exactly number: NSNumber) { let value = number.uint32Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt32?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt32?) -> Bool { guard let value = UInt32(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt32 { var result: UInt32? guard let src = source else { return UInt32(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt32(0) } return result! } } extension Int64 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.int64Value } public init(truncating number: NSNumber) { self = number.int64Value } public init?(exactly number: NSNumber) { let value = number.int64Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int64?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int64?) -> Bool { guard let value = Int64(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int64 { var result: Int64? guard let src = source else { return Int64(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int64(0) } return result! } } extension UInt64 : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uint64Value } public init(truncating number: NSNumber) { self = number.uint64Value } public init?(exactly number: NSNumber) { let value = number.uint64Value guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt64?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt64?) -> Bool { guard let value = UInt64(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt64 { var result: UInt64? guard let src = source else { return UInt64(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt64(0) } return result! } } extension Int : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.intValue } public init(truncating number: NSNumber) { self = number.intValue } public init?(exactly number: NSNumber) { let value = number.intValue guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int?) -> Bool { guard let value = Int(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int { var result: Int? guard let src = source else { return Int(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int(0) } return result! } } extension UInt : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.uintValue } public init(truncating number: NSNumber) { self = number.uintValue } public init?(exactly number: NSNumber) { let value = number.uintValue guard NSNumber(value: value) == number else { return nil } self = value } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt?) -> Bool { guard let value = UInt(exactly: x) else { return false } result = value return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt { var result: UInt? guard let src = source else { return UInt(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt(0) } return result! } } extension Float : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.floatValue } public init(truncating number: NSNumber) { self = number.floatValue } public init?(exactly number: NSNumber) { let type = number.objCType.pointee if type == 0x49 || type == 0x4c || type == 0x51 { guard let result = Float(exactly: number.uint64Value) else { return nil } self = result } else if type == 0x69 || type == 0x6c || type == 0x71 { guard let result = Float(exactly: number.int64Value) else { return nil } self = result } else { guard let result = Float(exactly: number.doubleValue) else { return nil } self = result } } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Float?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Float?) -> Bool { if x.floatValue.isNaN { result = x.floatValue return true } result = Float(exactly: x) return result != nil } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Float { var result: Float? guard let src = source else { return Float(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Float(0) } return result! } } extension Double : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.doubleValue } public init(truncating number: NSNumber) { self = number.doubleValue } public init?(exactly number: NSNumber) { let type = number.objCType.pointee if type == 0x51 { guard let result = Double(exactly: number.uint64Value) else { return nil } self = result } else if type == 0x71 { guard let result = Double(exactly: number.int64Value) else { return nil } self = result } else { // All other integer types and single-precision floating points will // fit in a `Double` without truncation. guard let result = Double(exactly: number.doubleValue) else { return nil } self = result } } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(value: self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Double?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Double?) -> Bool { if x.doubleValue.isNaN { result = x.doubleValue return true } result = Double(exactly: x) return result != nil } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Double { var result: Double? guard let src = source else { return Double(0) } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Double(0) } return result! } } extension Bool : _ObjectTypeBridgeable { @available(swift, deprecated: 4, renamed: "init(truncating:)") public init(_ number: NSNumber) { self = number.boolValue } public init(truncating number: NSNumber) { self = number.boolValue } public init?(exactly number: NSNumber) { if number === kCFBooleanTrue || NSNumber(value: 1) == number { self = true } else if number === kCFBooleanFalse || NSNumber(value: 0) == number { self = false } else { return nil } } public func _bridgeToObjectiveC() -> NSNumber { return unsafeBitCast(self ? kCFBooleanTrue : kCFBooleanFalse, to: NSNumber.self) } public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Bool?) { result = _unconditionallyBridgeFromObjectiveC(x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Bool?) -> Bool { result = x.boolValue return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Bool { var result: Bool? guard let src = source else { return false } guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return false } return result! } } extension Bool : _CFBridgeable { typealias CFType = CFBoolean var _cfObject: CFType { return self ? kCFBooleanTrue : kCFBooleanFalse } } extension NSNumber : ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral { } private struct CFSInt128Struct { var high: Int64 var low: UInt64 } open class NSNumber : NSValue { typealias CFType = CFNumber // This layout MUST be the same as CFNumber so that they are bridgeable private var _base = _CFInfo(typeID: CFNumberGetTypeID()) private var _pad: UInt64 = 0 internal var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Int: return intValue == other case let other as Double: return doubleValue == other case let other as Bool: return boolValue == other case let other as NSNumber: return compare(other) == .orderedSame default: return false } } open override var objCType: UnsafePointer<Int8> { func _objCType(_ staticString: StaticString) -> UnsafePointer<Int8> { return UnsafeRawPointer(staticString.utf8Start).assumingMemoryBound(to: Int8.self) } let numberType = _CFNumberGetType2(_cfObject) switch numberType { case kCFNumberSInt8Type: return _objCType("c") case kCFNumberSInt16Type: return _objCType("s") case kCFNumberSInt32Type: return _objCType("i") case kCFNumberSInt64Type: return _objCType("q") case kCFNumberFloat32Type: return _objCType("f") case kCFNumberFloat64Type: return _objCType("d") case kCFNumberSInt128Type: return _objCType("Q") default: fatalError("unsupported CFNumberType: '\(numberType)'") } } deinit { _CFDeinit(self) } private convenience init(bytes: UnsafeRawPointer, numberType: CFNumberType) { let cfnumber = CFNumberCreate(nil, numberType, bytes) self.init(factory: { unsafeBitCast(cfnumber, to: NSNumber.self) }) } public convenience init(value: Int8) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt8Type) } public convenience init(value: UInt8) { var value = Int16(value) self.init(bytes: &value, numberType: kCFNumberSInt16Type) } public convenience init(value: Int16) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt16Type) } public convenience init(value: UInt16) { var value = Int32(value) self.init(bytes: &value, numberType: kCFNumberSInt32Type) } public convenience init(value: Int32) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt32Type) } public convenience init(value: UInt32) { var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) } public convenience init(value: Int) { var value = value #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) self.init(bytes: &value, numberType: kCFNumberSInt64Type) #elseif arch(i386) || arch(arm) self.init(bytes: &value, numberType: kCFNumberSInt32Type) #endif } public convenience init(value: UInt) { #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) if value > UInt64(Int64.max) { var value = CFSInt128Struct(high: 0, low: UInt64(value)) self.init(bytes: &value, numberType: kCFNumberSInt128Type) } else { var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) } #elseif arch(i386) || arch(arm) var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) #endif } public convenience init(value: Int64) { var value = value self.init(bytes: &value, numberType: kCFNumberSInt64Type) } public convenience init(value: UInt64) { if value > UInt64(Int64.max) { var value = CFSInt128Struct(high: 0, low: UInt64(value)) self.init(bytes: &value, numberType: kCFNumberSInt128Type) } else { var value = Int64(value) self.init(bytes: &value, numberType: kCFNumberSInt64Type) } } public convenience init(value: Float) { var value = value self.init(bytes: &value, numberType: kCFNumberFloatType) } public convenience init(value: Double) { var value = value self.init(bytes: &value, numberType: kCFNumberDoubleType) } public convenience init(value: Bool) { self.init(factory: value._bridgeToObjectiveC) } override internal init() { super.init() } public required convenience init(bytes buffer: UnsafeRawPointer, objCType: UnsafePointer<Int8>) { guard let type = _NSSimpleObjCType(UInt8(objCType.pointee)) else { fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'") } switch type { case .Bool: self.init(value:buffer.load(as: Bool.self)) case .Char: self.init(value:buffer.load(as: Int8.self)) case .UChar: self.init(value:buffer.load(as: UInt8.self)) case .Short: self.init(value:buffer.load(as: Int16.self)) case .UShort: self.init(value:buffer.load(as: UInt16.self)) case .Int, .Long: self.init(value:buffer.load(as: Int32.self)) case .UInt, .ULong: self.init(value:buffer.load(as: UInt32.self)) case .LongLong: self.init(value:buffer.load(as: Int64.self)) case .ULongLong: self.init(value:buffer.load(as: UInt64.self)) case .Float: self.init(value:buffer.load(as: Float.self)) case .Double: self.init(value:buffer.load(as: Double.self)) default: fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'") } } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.number") { let number = aDecoder._decodePropertyListForKey("NS.number") if let val = number as? Double { self.init(value:val) } else if let val = number as? Int { self.init(value:val) } else if let val = number as? Bool { self.init(value:val) } else { return nil } } else { if aDecoder.containsValue(forKey: "NS.boolval") { self.init(value: aDecoder.decodeBool(forKey: "NS.boolval")) } else if aDecoder.containsValue(forKey: "NS.intval") { self.init(value: aDecoder.decodeInt64(forKey: "NS.intval")) } else if aDecoder.containsValue(forKey: "NS.dblval") { self.init(value: aDecoder.decodeDouble(forKey: "NS.dblval")) } else { return nil } } } open var int8Value: Int8 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint8Value: UInt8 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var int16Value: Int16 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint16Value: UInt16 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var int32Value: Int32 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint32Value: UInt32 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var int64Value: Int64 { var value: Int64 = 0 CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value) return .init(truncatingIfNeeded: value) } open var uint64Value: UInt64 { var value = CFSInt128Struct(high: 0, low: 0) CFNumberGetValue(_cfObject, kCFNumberSInt128Type, &value) return .init(truncatingIfNeeded: value.low) } private var int128Value: CFSInt128Struct { var value = CFSInt128Struct(high: 0, low: 0) CFNumberGetValue(_cfObject, kCFNumberSInt128Type, &value) return value } open var floatValue: Float { var value: Float = 0 CFNumberGetValue(_cfObject, kCFNumberFloatType, &value) return value } open var doubleValue: Double { var value: Double = 0 CFNumberGetValue(_cfObject, kCFNumberDoubleType, &value) return value } open var boolValue: Bool { // Darwin Foundation NSNumber appears to have a bug and return false for NSNumber(value: Int64.min).boolValue, // even though the documentation says: // "A 0 value always means false, and any nonzero value is interpreted as true." return (int64Value != 0) && (int64Value != Int64.min) } open var intValue: Int { var val: Int = 0 withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int>) -> Void in CFNumberGetValue(_cfObject, kCFNumberLongType, value) } return val } open var uintValue: UInt { var val: UInt = 0 withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt>) -> Void in CFNumberGetValue(_cfObject, kCFNumberLongType, value) } return val } open var stringValue: String { return description(withLocale: nil) } /// Create an instance initialized to `value`. public required convenience init(integerLiteral value: Int) { self.init(value: value) } /// Create an instance initialized to `value`. public required convenience init(floatLiteral value: Double) { self.init(value: value) } /// Create an instance initialized to `value`. public required convenience init(booleanLiteral value: Bool) { self.init(value: value) } open func compare(_ otherNumber: NSNumber) -> ComparisonResult { switch (_cfNumberType(), otherNumber._cfNumberType()) { case (kCFNumberFloatType, _), (_, kCFNumberFloatType): fallthrough case (kCFNumberDoubleType, _), (_, kCFNumberDoubleType): let (lhs, rhs) = (doubleValue, otherNumber.doubleValue) // Apply special handling for NaN as <, >, == always return false // when comparing with NaN if lhs.isNaN && rhs.isNaN { return .orderedSame } if lhs.isNaN { return .orderedAscending } if rhs.isNaN { return .orderedDescending } if lhs < rhs { return .orderedAscending } if lhs > rhs { return .orderedDescending } return .orderedSame default: // For signed and unsigned integers expand upto S128Int let (lhs, rhs) = (int128Value, otherNumber.int128Value) if lhs.high < rhs.high { return .orderedAscending } if lhs.high > rhs.high { return .orderedDescending } if lhs.low < rhs.low { return .orderedAscending } if lhs.low > rhs.low { return .orderedDescending } return .orderedSame } } private static let _numberFormatterForNilLocale: CFNumberFormatter = { let formatter: CFNumberFormatter formatter = CFNumberFormatterCreate(nil, CFLocaleCopyCurrent(), kCFNumberFormatterNoStyle) CFNumberFormatterSetProperty(formatter, kCFNumberFormatterMaxFractionDigits, 15._bridgeToObjectiveC()) return formatter }() open func description(withLocale locale: Locale?) -> String { // CFNumberFormatterCreateStringWithNumber() does not like numbers of type // SInt128Type, as it loses the type when looking it up and treats it as // an SInt64Type, so special case them. if _CFNumberGetType2(_cfObject) == kCFNumberSInt128Type { return String(format: "%@", unsafeBitCast(_cfObject, to: UnsafePointer<CFNumber>.self)) } let aLocale = locale let formatter: CFNumberFormatter if (aLocale == nil) { formatter = NSNumber._numberFormatterForNilLocale } else { formatter = CFNumberFormatterCreate(nil, aLocale?._cfObject, kCFNumberFormatterDecimalStyle) } return CFNumberFormatterCreateStringWithNumber(nil, formatter, self._cfObject)._swiftObject } override open var _cfTypeID: CFTypeID { return CFNumberGetTypeID() } open override var description: String { return description(withLocale: nil) } internal func _cfNumberType() -> CFNumberType { switch objCType.pointee { case 0x42: return kCFNumberCharType case 0x63: return kCFNumberCharType case 0x43: return kCFNumberShortType case 0x73: return kCFNumberShortType case 0x53: return kCFNumberIntType case 0x69: return kCFNumberIntType case 0x49: return Int(uint32Value) < Int(Int32.max) ? kCFNumberIntType : kCFNumberLongLongType case 0x6C: return kCFNumberLongType case 0x4C: return uintValue < UInt(Int.max) ? kCFNumberLongType : kCFNumberLongLongType case 0x66: return kCFNumberFloatType case 0x64: return kCFNumberDoubleType case 0x71: return kCFNumberLongLongType case 0x51: return kCFNumberLongLongType default: fatalError() } } internal func _getValue(_ valuePtr: UnsafeMutableRawPointer, forType type: CFNumberType) -> Bool { switch type { case kCFNumberSInt8Type: valuePtr.assumingMemoryBound(to: Int8.self).pointee = int8Value break case kCFNumberSInt16Type: valuePtr.assumingMemoryBound(to: Int16.self).pointee = int16Value break case kCFNumberSInt32Type: valuePtr.assumingMemoryBound(to: Int32.self).pointee = int32Value break case kCFNumberSInt64Type: valuePtr.assumingMemoryBound(to: Int64.self).pointee = int64Value break case kCFNumberSInt128Type: struct CFSInt128Struct { var high: Int64 var low: UInt64 } let val = int64Value valuePtr.assumingMemoryBound(to: CFSInt128Struct.self).pointee = CFSInt128Struct.init(high: (val < 0) ? -1 : 0, low: UInt64(bitPattern: val)) break case kCFNumberFloat32Type: valuePtr.assumingMemoryBound(to: Float.self).pointee = floatValue break case kCFNumberFloat64Type: valuePtr.assumingMemoryBound(to: Double.self).pointee = doubleValue default: fatalError() } return true } open override func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if let keyedCoder = aCoder as? NSKeyedArchiver { keyedCoder._encodePropertyList(self) } else { if CFGetTypeID(self) == CFBooleanGetTypeID() { aCoder.encode(boolValue, forKey: "NS.boolval") } else { switch objCType.pointee { case 0x42: aCoder.encode(boolValue, forKey: "NS.boolval") break case 0x63: fallthrough case 0x43: fallthrough case 0x73: fallthrough case 0x53: fallthrough case 0x69: fallthrough case 0x49: fallthrough case 0x6C: fallthrough case 0x4C: fallthrough case 0x71: fallthrough case 0x51: aCoder.encode(int64Value, forKey: "NS.intval") case 0x66: fallthrough case 0x64: aCoder.encode(doubleValue, forKey: "NS.dblval") default: break } } } } open override var classForCoder: AnyClass { return NSNumber.self } } extension CFNumber : _NSBridgeable { typealias NSType = NSNumber internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } } internal func _CFSwiftNumberGetType(_ obj: CFTypeRef) -> CFNumberType { return unsafeBitCast(obj, to: NSNumber.self)._cfNumberType() } internal func _CFSwiftNumberGetValue(_ obj: CFTypeRef, _ valuePtr: UnsafeMutableRawPointer, _ type: CFNumberType) -> Bool { return unsafeBitCast(obj, to: NSNumber.self)._getValue(valuePtr, forType: type) } internal func _CFSwiftNumberGetBoolValue(_ obj: CFTypeRef) -> Bool { return unsafeBitCast(obj, to: NSNumber.self).boolValue }
apache-2.0
032714ed9d2a742ba3c4fcb31d5bdcde
33.747859
153
0.631763
4.574721
false
false
false
false
ShinCurry/Maria
Maria/SettingsGeneralViewController.swift
1
2532
// // SettingsGeneralViewController.swift // Maria // // Created by ShinCurry on 16/4/16. // Copyright © 2016年 ShinCurry. All rights reserved. // import Cocoa class SettingsGeneralViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. userDefaultsInit() } let defaults = MariaUserDefault.auto // little bug -- use a new thread? @IBOutlet weak var enableSpeedStatusBar: NSButton! @IBOutlet weak var enableStatusBarMode: NSButton! @IBOutlet weak var enableYouGet: NSButton! @IBOutlet weak var webAppPathButton: NSPopUpButton! @IBAction func switchOptions(_ sender: NSButton) { let appDelegate = NSApplication.shared.delegate as! AppDelegate let boolValue = sender.state == .on ? true : false switch sender { case enableSpeedStatusBar: defaults[.enableSpeedStatusBar] = boolValue appDelegate.updateStatusBarStatus() case enableStatusBarMode: defaults[.enableStatusBarMode] = boolValue appDelegate.updateStatusBarStatus() case enableYouGet: defaults[.enableYouGet] = boolValue default: break } } @IBAction func finishEditing(_ sender: NSTextField) { defaults[.webAppPath] = sender.stringValue defaults.synchronize() } @IBAction func selectFilePath(_ sender: NSMenuItem) { webAppPathButton.selectItem(at: 0) let openPanel = NSOpenPanel() openPanel.title = NSLocalizedString("selectWebUIPath.openPanel.title", comment: "") openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.showsHiddenFiles = true openPanel.beginSheetModal(for: self.view.window!, completionHandler: { key in if key.rawValue == 1, let url = openPanel.url?.relativePath { self.defaults[.webAppPath] = url self.webAppPathButton.item(at: 0)!.title = url } }) } } extension SettingsGeneralViewController { func userDefaultsInit() { if let value = defaults[.webAppPath] { webAppPathButton.item(at: 0)!.title = value } enableSpeedStatusBar.state = defaults[.enableSpeedStatusBar] ? .on : .off enableStatusBarMode.state = defaults[.enableStatusBarMode] ? .on : .off enableYouGet.state = defaults[.enableYouGet] ? .on : .off } }
gpl-3.0
e847e2d7fe55f851d4562817fc102a06
31.423077
91
0.643733
4.789773
false
false
false
false
con-beo-vang/Spendy
Spendy/Views/Add Edit Transaction/SelectAccountOrCategoryCell.swift
1
1307
// // SelectAccountOrCategoryCell.swift // Spendy // // Created by Dave Vo on 9/16/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit class SelectAccountOrCategoryCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! var itemClass: String! var itemTypeFilter: String? var category: Category? { didSet { guard let category = category else { return } titleLabel.text = "Category" typeLabel.text = category.name itemTypeFilter = category.type print("[SelectAccountOrCategoryCell] itemTypeFilter = \(itemTypeFilter)") } } var account: Account? { didSet { titleLabel.text = "Account" typeLabel.text = account?.name ?? "None" itemTypeFilter = "Account" } } var fromAccount: Account? { didSet { titleLabel.text = "From Account" typeLabel.text = fromAccount?.name ?? "None" itemTypeFilter = "FromAccount" } } var toAccount: Account? { didSet { guard let account = toAccount else { titleLabel.text = "To Account" typeLabel.text = "None" return } titleLabel.text = "To Account" typeLabel.text = account.name itemTypeFilter = "ToAccount" } } }
mit
67693562d3b1d8eebdf542ec34f22441
21.929825
79
0.629686
4.285246
false
false
false
false
andrebocchini/SwiftChatty
SwiftChatty/Common Models/Mappable/Thread.swift
1
6466
// // ChattyThread.swift // SwiftChatty // // Created by Andre Bocchini on 1/16/16. // Copyright © 2016 Andre Bocchini. All rights reserved.// import Freddy /// Models a Chatty thread, which is nothing more than a thread ID, and a list of posts. public struct ChattyThread { public let id: Int public let posts: [Post] public init(id: Int, posts: [Post]) { self.id = id self.posts = posts } } extension ChattyThread: CommonMappableModel { public init(json: JSON) throws { let threadIdString: String = try json.decode(at: "threadId") if let id = Int(threadIdString) { self.id = id } else { throw ChattyError.mappingError } self.posts = try json.decodedArray(at: "posts") } public func rootPost() -> Post { if let rootPost = (self.posts.filter { $0.id == self.id }).first { return rootPost } else { return Post(id: 0, date: "", author: "", category: nil, body: "", threadId: 0, parentId: 0, lols: [LOL]()) } } public func isParticipant(_ username: String) -> Bool { return self.posts.filter( { $0.author == username } ).count > 0 } /// Calculates how many subthreads deep a particular post is /// /// - parameter post: Post that we want to calculate the depth for /// - returns: An integer representing how many subthreads deep a post is into this thread. public func depth(of post: Post) -> Int { var parentId = post.parentId var levels = 0 while parentId != self.id { guard let parentPost = (self.posts.filter { $0.id == parentId }).first else { return 0 } parentId = parentPost.parentId levels += 1 } return levels } /// Determines the parent post for another post /// /// - parameter post: The post whose parent we want to determine /// - return: The parent post, or nil if the current post is the root of the thread public func parent(of post: Post) -> Post? { return (self.posts.filter { $0.id == post.parentId }).first } /// Finds all of the posts that were made after a certain post in the same thread (or any of its /// subthreads) /// /// - parameter post: The post whose descendants we want to find /// - returns: An array of posts containing any descendants found public func descendants(of post: Post) -> [Post] { var descendantPosts = self.posts.filter { ($0.parentId == post.id) } if descendantPosts.count > 0 { for descendantPost in descendantPosts { descendantPosts.append(contentsOf: descendants(of: descendantPost)) } } return descendantPosts } /// Finds all posts immediately below (in a hierarchical thread) another post. /// /// - parameter posts: The list of posts to search through /// - parameter post: The post under which we want to find the top level posts /// - returns: An array of posts consisting of the top level posts under the post passed in as /// a parameter. public func topLevelPosts(_ posts: [Post], under root: Post) -> [Post] { var topLevelPosts = [Post]() for post in posts { if post.parentId == root.id { topLevelPosts.append(post) } } return topLevelPosts } public func sort(_ order: ThreadSortOrder) -> [Post] { switch(order) { case .flatNewestFirst: fallthrough case .flatOldestFirst: return flatSort(order) case .threadedNewestFirst: fallthrough case .threadedOldestFirst: return threadedSort(order) } } private func flatSort(_ order: ThreadSortOrder) -> [Post] { if (order == .threadedOldestFirst) { return self.posts.sorted { return $0.older(than: $1) } } else { return self.posts.sorted { return $0.newer(than: $1) } } } private func threadedSort(_ order: ThreadSortOrder) -> [Post] { let postsArrayWithoutRootPost = self.posts.filter( { $0.id != self.id } ) let rootPost = self.rootPost() var threadedPosts = [Post]() var topLevelPosts = self.topLevelPosts(postsArrayWithoutRootPost, under: rootPost) if (order == .threadedOldestFirst) { topLevelPosts.sort( by: { return $0.older(than: $1) } ) } else { topLevelPosts.sort( by: { return $0.newer(than: $1) } ) } threadedPosts.append(rootPost) for topLevelPost in topLevelPosts { threadedPosts.append(topLevelPost) threadedPosts.append(contentsOf: orderedThread(postsArrayWithoutRootPost, root: topLevelPost)) } return threadedPosts } fileprivate func orderedThread(_ posts: [Post], root: Post) -> [Post] { var topLevelPosts = self.topLevelPosts(posts, under: root) var result = [Post]() topLevelPosts.sort( by: { $0.older(than: $1) } ) for topLevelPost in topLevelPosts { result.append(topLevelPost) result.append(contentsOf: orderedThread(posts, root: topLevelPost)) } return result } } public enum ThreadSortOrder { /// All posts sorted by date only, with the newer ones first case flatNewestFirst /// All posts sorted by date only, with the older ones first case flatOldestFirst /// All replies directly below the root post sorted by date with the newer ones first, /// and all of the replies below those organized by threads with the older /// ones first. The root post is always the first post in the thread. case threadedNewestFirst /// All replies directly below the root post sorted by date with the older ones first, /// and all of the replies below those organized by threads with the older /// ones first. The root post is always the first post in the thread. case threadedOldestFirst }
mit
f19b01b4bf099f1d49f7d80600e6173a
33.206349
106
0.577572
4.495828
false
false
false
false
github4484/sweme2
Sweme2/ViewController.swift
1
1130
// // ViewController.swift // Sweme2 // // Copyright (c) 2014 [email protected] All rights reserved. // import UIKit class ViewController: UIViewController { let evaluator = Evaluator() @IBOutlet weak var textView: UITextView! @IBOutlet weak var webView: UIWebView! @IBOutlet weak var codeTextView: UITextView! @IBAction func button() { let expression = evaluator.parse(codeTextView.text) let evaluated = evaluator.eval(expression!) textView.text = evaluated.toString() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //let url: NSURL = NSURL(string: "http://www.yahoo.com")! let path = NSBundle.mainBundle().pathForResource("a", ofType: "html") let requestURL = NSURL(string: path!) let request = NSURLRequest(URL: requestURL!) webView.loadRequest(request) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1c3042b0949afc1ef45e492a64e0bba8
27.25
80
0.652212
4.612245
false
false
false
false
lyimin/EyepetizerApp
EyepetizerApp/EyepetizerApp/Controllers/PopularViewController/EYEPopularMonthController.swift
1
4543
// // EYEPopularMonthController.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/21. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit import Alamofire class EYEPopularMonthController: UIViewController, LoadingPresenter { /// 加载view var loaderView : EYELoaderView! override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(collectionView) setupLoaderView() getData() } //MARK: --------------------------- Private Methods -------------------------- private func getData() { setLoaderViewHidden(false) Alamofire.request(.GET, EYEAPIHeaper.API_Popular_Monthly).responseSwiftyJSON ({ [unowned self](request, response, json, error) -> Void in // 字典转模型 刷新数据 if json != .null && error == nil { let dataDict = json.rawValue as! NSDictionary let itemArray = dataDict["videoList"] as! NSArray self.modelList = itemArray.map({ (dict) -> ItemModel in ItemModel(dict: dict as? NSDictionary) }) self.collectionView.reloadData() } self.setLoaderViewHidden(true) }) } //MARK: --------------------------- Getter or Setter -------------------------- // 模型 var modelList : [ItemModel] = [ItemModel]() /// collectionView private lazy var collectionView : EYECollectionView = { let rect = CGRectMake(0, 0, UIConstant.SCREEN_WIDTH, UIConstant.SCREEN_HEIGHT-UIConstant.UI_TAB_HEIGHT-UIConstant.UI_CHARTS_HEIGHT-UIConstant.UI_NAV_HEIGHT) var collectionView : EYECollectionView = EYECollectionView(frame: rect, collectionViewLayout:EYECollectionLayout()) // 注册header collectionView.registerClass(EYEChoiceHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier) collectionView.registerClass(EYEPopularFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: EYEPopularFooterView.reuseIdentifier) let layout = collectionView.collectionViewLayout as! EYECollectionLayout layout.footerReferenceSize = CGSize(width: collectionView.width, height: 50) collectionView.registerClass(EYEPopularFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: EYEPopularFooterView.reuseIdentifier) collectionView.delegate = self collectionView.dataSource = self return collectionView }() } extension EYEPopularMonthController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return modelList.count } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let cell = cell as! EYEChoiceCell cell.model = modelList[indexPath.row] cell.index = "\(indexPath.row+1)" } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EYEChoiceCell.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceCell return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if self.parentViewController is EYEPopularController { (parentViewController as! EYEPopularController).selectCell = collectionView.cellForItemAtIndexPath(indexPath) as! EYEChoiceCell } let model = modelList[indexPath.row] self.navigationController?.pushViewController(EYEVideoDetailController(model: model), animated: true) } /** * section FootView */ func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let footView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: EYEPopularFooterView.reuseIdentifier, forIndexPath: indexPath) return footView } }
mit
00c093f9b757e1d1aba487d9a4e9daa3
43.156863
198
0.689165
5.997337
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Roland TB-303 Filter.xcplaygroundpage/Contents.swift
2
650
//: ## Roland TB-303 Filter //: import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var filter = AKRolandTB303Filter(player) filter.cutoffFrequency = 1350 filter.resonance = 0.8 AudioKit.output = filter AudioKit.start() player.play() var time = 0.0 let timeStep = 0.02 let hz = 2.0 AKPlaygroundLoop(every: timeStep) { filter.cutoffFrequency = (1.0 - cos(2 * 3.14 * hz * time)) * 600 + 700 time += timeStep } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
10c8175ca491b0c7267c53bc47f07b02
20.666667
74
0.704615
3.693182
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Core/ViewModels/GasViewModel.swift
1
1252
// Copyright DApps Platform Inc. All rights reserved. import Foundation import BigInt struct GasViewModel { let fee: BigInt let server: RPCServer let store: TokensDataStore let formatter: EtherNumberFormatter init( fee: BigInt, server: RPCServer, store: TokensDataStore, formatter: EtherNumberFormatter = .full ) { self.fee = fee self.server = server self.store = store self.formatter = formatter } var etherFee: String { let gasFee = formatter.string(from: fee) return "\(gasFee.description) \(server.symbol)" } var feeCurrency: Double? { guard let price = store.coinTicker(by: server.priceID)?.price else { return .none } return FeeCalculator.estimate(fee: formatter.string(from: fee), with: price) } var monetaryFee: String? { guard let feeInCurrency = feeCurrency, let fee = FeeCalculator.format(fee: feeInCurrency) else { return .none } return fee } var feeText: String { var text = etherFee if let monetaryFee = monetaryFee { text += "(\(monetaryFee))" } return text } }
gpl-3.0
06b40c67ac2317246ff4da123c1c7888
23.54902
84
0.591853
4.287671
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Formatters/Implementations/PreFormatter.swift
1
1931
import Foundation import UIKit // MARK: - Pre Formatter // open class PreFormatter: ParagraphAttributeFormatter { /// Font to be used /// let monospaceFont: UIFont /// Attributes to be added by default /// let placeholderAttributes: [NSAttributedString.Key: Any]? /// Designated Initializer /// init(monospaceFont: UIFont = FontProvider.shared.monospaceFont, placeholderAttributes: [NSAttributedString.Key : Any]? = nil) { self.monospaceFont = monospaceFont self.placeholderAttributes = placeholderAttributes } // MARK: - Overwriten Methods func apply(to attributes: [NSAttributedString.Key: Any], andStore representation: HTMLRepresentation?) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes let newParagraphStyle = attributes.paragraphStyle() newParagraphStyle.appendProperty(HTMLPre(with: representation)) let defaultFont = attributes[.font] resultingAttributes[.paragraphStyle] = newParagraphStyle resultingAttributes[.font] = Configuration.useDefaultFont ? defaultFont : monospaceFont return resultingAttributes } func remove(from attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { guard let placeholderAttributes = placeholderAttributes else { return attributes } var resultingAttributes = attributes for (key, value) in placeholderAttributes { resultingAttributes[key] = value } return resultingAttributes } func present(in attributes: [NSAttributedString.Key : Any]) -> Bool { guard let paragraphStyle = attributes[.paragraphStyle] as? ParagraphStyle else { return false } return paragraphStyle.hasProperty(where: { (property) -> Bool in return property.isMember(of: HTMLPre.self) }) } }
mpl-2.0
091ddb4608b86b5581817df0dac82b9a
29.650794
141
0.679441
5.34903
false
false
false
false
TotalDigital/People-iOS
Pods/p2.OAuth2/Sources/Base/OAuth2Error.swift
2
11269
// // OAuth2Error.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. 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 /** All errors that might occur. The response errors return a description as defined in the spec: http://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ public enum OAuth2Error: Error, CustomStringConvertible, Equatable { /// An error for which we don't have a specific one. case generic(String) /// An error holding on to an NSError. case nsError(Foundation.NSError) /// Invalid URL components, failed to create a URL case invalidURLComponents(URLComponents) // MARK: - Client errors /// There is no client id. case noClientId /// There is no client secret. case noClientSecret /// There is no redirect URL. case noRedirectURL /// There is no username. case noUsername /// There is no password. case noPassword /// The client is already authorizing. case alreadyAuthorizing /// There is no authorization context. case noAuthorizationContext /// The authorization context is invalid. case invalidAuthorizationContext /// The redirect URL is invalid; with explanation. case invalidRedirectURL(String) /// There is no access token. case noAccessToken /// There is no refresh token. case noRefreshToken /// There is no registration URL. case noRegistrationURL /// The login controller does not have a valid type case invalidLoginController(actualType: String, expectedType: String) /// There is no delegate associated with the password grant flow instance. case noPasswordGrantDelegate // MARK: - Request errors /// The request is not using SSL/TLS. case notUsingTLS /// Unable to open the authorize URL. case unableToOpenAuthorizeURL /// The request is invalid. case invalidRequest /// The request was cancelled. case requestCancelled // MARK: - Response Errors /// There was no token type in the response. case noTokenType /// The token type is not supported. case unsupportedTokenType(String) /// There was no data in the response. case noDataInResponse /// Some prerequisite failed; with explanation. case prerequisiteFailed(String) /// The state parameter was missing in the response. case missingState /// The state parameter was invalid. case invalidState /// The JSON response could not be parsed. case jsonParserError /// Unable to UTF-8 encode. case utf8EncodeError /// Unable to decode to UTF-8. case utf8DecodeError // MARK: - OAuth2 errors /// The client is unauthorized (HTTP status 401). case unauthorizedClient /// The request was forbidden (HTTP status 403). case forbidden /// Username or password was wrong (HTTP status 403 on password grant). case wrongUsernamePassword /// Access was denied. case accessDenied /// Response type is not supported. case unsupportedResponseType /// Scope was invalid. case invalidScope /// A 500 was thrown. case serverError /// The service is temporarily unavailable. case temporarilyUnavailable /// Other response error, as defined in its String. case responseError(String) /** Instantiate the error corresponding to the OAuth2 response code, if it is known. - parameter code: The code, like "access_denied", that should be interpreted - parameter fallback: The error string to use in case the error code is not known - returns: An appropriate OAuth2Error */ public static func fromResponseError(_ code: String, fallback: String? = nil) -> OAuth2Error { switch code { case "invalid_request": return .invalidRequest case "unauthorized_client": return .unauthorizedClient case "access_denied": return .accessDenied case "unsupported_response_type": return .unsupportedResponseType case "invalid_scope": return .invalidScope case "server_error": return .serverError case "temporarily_unavailable": return .temporarilyUnavailable default: return .responseError(fallback ?? "Authorization error: \(code)") } } /// Human understandable error string. public var description: String { switch self { case .generic(let message): return message case .nsError(let error): return error.localizedDescription case .invalidURLComponents(let components): return "Failed to create URL from components: \(components)" case .noClientId: return "Client id not set" case .noClientSecret: return "Client secret not set" case .noRedirectURL: return "Redirect URL not set" case .noUsername: return "No username" case .noPassword: return "No password" case .invalidLoginController(let expectedType, let actualType): return "The login controller of type \(actualType) cannot be displayed. Expecting a \(expectedType)." case .noPasswordGrantDelegate: return "The password grant flow needs to be set a delegate to present the login controller." case .alreadyAuthorizing: return "The client is already authorizing, wait for it to finish or abort authorization before trying again" case .noAuthorizationContext: return "No authorization context present" case .invalidAuthorizationContext: return "Invalid authorization context" case .invalidRedirectURL(let url): return "Invalid redirect URL: \(url)" case .noAccessToken: return "I don't have an access token, cannot sign request" case .noRefreshToken: return "I don't have a refresh token, not trying to refresh" case .noRegistrationURL: return "No registration URL defined" case .notUsingTLS: return "You MUST use HTTPS/SSL/TLS" case .unableToOpenAuthorizeURL: return "Cannot open authorize URL" case .invalidRequest: return "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed." case .requestCancelled: return "The request has been cancelled" case .noTokenType: return "No token type received, will not use the token" case .unsupportedTokenType(let message): return message case .noDataInResponse: return "No data in the response" case .prerequisiteFailed(let message): return message case .missingState: return "The state parameter was missing in the response" case .invalidState: return "The state parameter did not check out" case .jsonParserError: return "Error parsing JSON" case .utf8EncodeError: return "Failed to UTF-8 encode the given string" case .utf8DecodeError: return "Failed to decode given data as a UTF-8 string" case .unauthorizedClient: return "Unauthorized" case .forbidden: return "Forbidden" case .wrongUsernamePassword: return "The username or password is incorrect" case .accessDenied: return "The resource owner or authorization server denied the request." case .unsupportedResponseType: return "The authorization server does not support obtaining an access token using this method." case .invalidScope: return "The requested scope is invalid, unknown, or malformed." case .serverError: return "The authorization server encountered an unexpected condition that prevented it from fulfilling the request." case .temporarilyUnavailable: return "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server." case .responseError(let message): return message } } // MARK: - Equatable public static func ==(lhs: OAuth2Error, rhs: OAuth2Error) -> Bool { switch (lhs, rhs) { case (.generic(let lhm), .generic(let rhm)): return lhm == rhm case (.nsError(let lhe), .nsError(let rhe)): return lhe.isEqual(rhe) case (.invalidURLComponents(let lhe), .invalidURLComponents(let rhe)): return (lhe == rhe) case (.noClientId, .noClientId): return true case (.noClientSecret, .noClientSecret): return true case (.noRedirectURL, .noRedirectURL): return true case (.noUsername, .noUsername): return true case (.noPassword, .noPassword): return true case (.alreadyAuthorizing, .alreadyAuthorizing): return true case (.noAuthorizationContext, .noAuthorizationContext): return true case (.invalidAuthorizationContext, .invalidAuthorizationContext): return true case (.invalidRedirectURL(let lhu), .invalidRedirectURL(let rhu)): return lhu == rhu case (.noAccessToken, .noAccessToken): return true case (.noRefreshToken, .noRefreshToken): return true case (.notUsingTLS, .notUsingTLS): return true case (.unableToOpenAuthorizeURL, .unableToOpenAuthorizeURL): return true case (.invalidRequest, .invalidRequest): return true case (.requestCancelled, .requestCancelled): return true case (.noTokenType, .noTokenType): return true case (.unsupportedTokenType(let lhm), .unsupportedTokenType(let rhm)): return lhm == rhm case (.noDataInResponse, .noDataInResponse): return true case (.prerequisiteFailed(let lhm), .prerequisiteFailed(let rhm)): return lhm == rhm case (.missingState, .missingState): return true case (.invalidState, .invalidState): return true case (.jsonParserError, .jsonParserError): return true case (.utf8EncodeError, .utf8EncodeError): return true case (.utf8DecodeError, .utf8DecodeError): return true case (.unauthorizedClient, .unauthorizedClient): return true case (.forbidden, .forbidden): return true case (.wrongUsernamePassword, .wrongUsernamePassword): return true case (.accessDenied, .accessDenied): return true case (.unsupportedResponseType, .unsupportedResponseType): return true case (.invalidScope, .invalidScope): return true case (.serverError, .serverError): return true case (.temporarilyUnavailable, .temporarilyUnavailable): return true case (.responseError(let lhm), .responseError(let rhm)): return lhm == rhm default: return false } } } public extension Error { /** Convenience getter to easily retrieve an OAuth2Error from any Error. */ public var asOAuth2Error: OAuth2Error { if let oaerror = self as? OAuth2Error { return oaerror } return OAuth2Error.nsError(self as NSError) } }
apache-2.0
7b910f37723c311efb00bf34d5376072
32.238938
157
0.701012
4.287671
false
false
false
false
kapilbhalla/letsTweetAgain
letsTweetAgain/TwitterClient.swift
1
8346
// // TwitterClient.swift // letsTweetAgain // // Created by Bhalla, Kapil on 4/16/17. // Copyright © 2017 Bhalla, Kapil. All rights reserved. // import UIKit import BDBOAuth1Manager class TwitterClient: BDBOAuth1SessionManager { // Single client that can be used throughout the application static let sharedInstance = TwitterClient (baseURL: NSURL(string: "https://api.twitter.com") as! URL, consumerKey: "ZAGlDoZ4vkMoi7VtNRnogjJEE", consumerSecret: "l48UW8Ze1ciCg7sHpPwhVGhzCzyNJEPGen5LYevfEBPimjsIoG") // the hometime line api interacts to the server to fetch the tweets. // in case of success the function will call a callback and return an array of tweets // in case of failure we would call the error callback func homeTimeLine (successCB: @escaping ([Tweet]) -> (), failureCB: @escaping (Error) -> ()) { get("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask, response:Any?) in // print ("tweets") let tweetDictionaries = response as! [NSDictionary] let tweets = Tweet.tweetsWithArray(tweetDictionaries: tweetDictionaries) successCB(tweets) }, failure: { (task: URLSessionDataTask?, error: Error) in failureCB(error) }) } let twitterMentionsPath = "1.1/statuses/mentions_timeline.json" func mentions(parameters: [String: AnyObject]? ,success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { get(twitterMentionsPath, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let dictionariesArray = response as! [NSDictionary] let tweets = Tweet.tweetsWithArray(tweetDictionaries: dictionariesArray) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error?) in failure(error!) }) } let twitterUserTimeLinePath = "1.1/statuses/user_timeline.json" func userTimeline(parameters: [String: AnyObject]? ,success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { get(twitterUserTimeLinePath, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let tweetDictionaries = response as! [NSDictionary] let tweets = Tweet.tweetsWithArray(tweetDictionaries: tweetDictionaries) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error?) in failure(error!) }) } func validateUser(successCB: @escaping (User) -> (), failuerCB: @escaping (Error) -> ()) { get("1.1/account/verify_credentials.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask, response: Any?) -> Void in print("account: \(response)") let responseDictionary = response as! NSDictionary let user = User(userDictionary: responseDictionary) successCB(user) }, failure: { (task: URLSessionDataTask?, error: Error) in failuerCB(error) }) } var loginSuccess: (()->())? var loginFailure: ((Error)->())? /* The login function is responsible to execute the Oauth1.0a protocol and call the completion handler as required */ func login (success: @escaping ()->(), failure: @escaping (Error)->()){ loginSuccess = success loginFailure = failure // There is a bug in BDBOAuth1Manager that needs the session to be cleaned before the login. deauthorize() // 2. prove to twitter that we are the letsTweetAgain app. // https://api.twitter.com/oauth/request_token fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL: NSURL(string:"letstweetagain://oauth") as! URL, scope: nil, success: { (oauthToken: BDBOAuth1Credential?) -> Void in print ("i have got the token") // now we need to authorize the session with the token let oToken = oauthToken?.token let authorizeQueryParameter = ("https://api.twitter.com/oauth/authorize?oauth_token="+oToken!) as String //let url = NSURL(string: "https://api.twitter.com/oauth/authorize\(authorizeQueryParameter)") let authorizeUrl = NSURL(string: authorizeQueryParameter) // open the url in the url handling client in ios UIApplication.shared.openURL(authorizeUrl! as URL) }, failure: { (error: Error?) -> Void in print ("error: \(error?.localizedDescription)") if let errorUnwrapped = error { self.loginFailure?(errorUnwrapped) } }) } private let createNewTweetEndpoint = "1.1/statuses/update.json" func createNewTweet(withMessage text: String, success: @escaping (Tweet) -> () , failure: @escaping (Error) -> ()) { let param: [String: Any] = ["status": text] post(createNewTweetEndpoint, parameters: param, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let tweet = Tweet(tweetDictionary: response as! NSDictionary) success(tweet) }) { (task: URLSessionDataTask?, error: Error) in failure(error) } } private let retweetEndpoint = "1.1/statuses/retweet/:id.json" func retweeting(withID id: NSNumber, success: @escaping (Tweet) -> (), failure: @escaping (Error) -> ()) { let retweetingEndpoint = retweetEndpoint.replacingOccurrences(of: ":id", with: "\(id)") let param: [String: Any] = ["id": id] post(retweetingEndpoint, parameters: param, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let tweet = Tweet(tweetDictionary: response as! NSDictionary) success(tweet) }) { (task: URLSessionDataTask?, error: Error) in failure(error) } } private let markAsFavoriteEndpoint = "1.1/favorites/create.json" func markAsFavorite(withID id: NSNumber, success: @escaping (Tweet) -> (), failure: @escaping (Error) -> ()) { let param: [String: Any] = ["id": id] post(markAsFavoriteEndpoint, parameters: param, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in let tweet = Tweet(tweetDictionary: response as! NSDictionary) success(tweet) }) { (task: URLSessionDataTask?, error: Error) in failure(error) } } func logout() { User.currentUser = nil deauthorize() // Go back to the Login window NotificationCenter.default.post(name: NSNotification.Name(User.didLogOutNotification), object: nil) } /* Handle open url function is called from the appDelegate when the system notifies that a command handling request is being posted. On this we have already saved callback handlers when the original login was requested. we will use the preseaved call back handlers to complete this functionality. */ func handleOpenURL (open url: URL) { let requestToken = BDBOAuth1Credential (queryString: url.query) fetchAccessToken(withPath: "/oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken: BDBOAuth1Credential?) in // print ("I got the access token") self.loginSuccess?() }, failure: { (error: Error?) in print (error?.localizedDescription) if let errorUnwrapped = error { self.loginFailure?(errorUnwrapped) } }) } }
apache-2.0
5d2eabf04f39c08b5b2566f2a3802aef
41.576531
217
0.584661
4.885831
false
false
false
false
PJayRushton/stats
Stats/StatType.swift
1
5091
// // StatType.swift // Stats // // Created by Parker Rushton on 4/25/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import Foundation enum StatType: String { case atBats case battingAverage case doubles case gamesPlayed case grandSlams case hits case hitByPitches case homeRuns case itpHRs case onBasePercentage case plateAppearances case rbis case reachOnError case singles case slugging case strikeOuts case triples case walks static let allValues = [StatType.battingAverage, .slugging, .onBasePercentage, .hits, .atBats, .plateAppearances, .singles, .doubles, .triples, .homeRuns, .itpHRs, .grandSlams, .rbis, .walks, .strikeOuts, .reachOnError] var abbreviation: String { switch self { case .atBats: return "AB" case .battingAverage: return "BA" case .doubles: return "2B" case .gamesPlayed: return "G" case .grandSlams: return "GS" case .hits: return "H" case .hitByPitches: return "HBP" case .homeRuns: return "HR" case .itpHRs: return "HR(ITP)" case .onBasePercentage: return "OBP" case .plateAppearances: return "PA" case .rbis: return "RBIs" case .reachOnError: return "ROE" case .singles: return "1B" case .slugging: return "SLG" case .strikeOuts: return "K" case .triples: return "3B" case .walks: return "W" } } func displayString(isSingular: Bool = false) -> String { switch self { case .atBats: return isSingular ? "At Bat" : "At Bats" case .battingAverage, .onBasePercentage, .reachOnError, .slugging: return abbreviation case .doubles: return isSingular ? "Double" : "Doubles" case .gamesPlayed: return isSingular ? "Game" : "Games" case .grandSlams: return isSingular ? "Grand Slam" : "Grand Slams" case .hits: return isSingular ? "Hit" : "Hits" case .hitByPitches: return isSingular ? "Hit by Pitch" : "Hit by Pitches" case .homeRuns: return isSingular ? "Home Run" : "Home Runs" case .itpHRs: return isSingular ? "HR-ITP" : "HRs-ITP" case .plateAppearances: return isSingular ? "Plate Appearance" : "Plate Appearances" case .rbis: return isSingular ? "RBI" : "RBIs" case .singles: return isSingular ? "Single" : "Singles" case .strikeOuts: return isSingular ? "Strike Out" : "Strike Outs" case .triples: return isSingular ? "Triple" : "Triples" case .walks: return isSingular ? "Walk" : "Walks" } } func statValue(from atBats: [AtBat]) -> Double { switch self { case .atBats: return atBats.battingAverageCount.doubleValue case .battingAverage: guard atBats.battingAverageCount > 0 else { return 0 } let hits = atBats.hitCount.doubleValue return hits / atBats.battingAverageCount.doubleValue case .doubles: return atBats.withResult(.double).count.doubleValue case .gamesPlayed: return Set(atBats.map { $0.gameId }).count.doubleValue case .grandSlams: let hrs = atBats.withResults([.hr, .hrITP]) return hrs.filter { $0.rbis == 4 }.count.doubleValue case .hits: return atBats.hitCount.doubleValue case .hitByPitches: return atBats.withResult(.hbp).count.doubleValue case .homeRuns: return atBats.withResults([.hr, .hrITP]).count.doubleValue case .itpHRs: return atBats.withResult(.hrITP).count.doubleValue case .onBasePercentage: guard atBats.count > 0 else { return 0 } let onBaseBatCount = atBats.filter { $0.resultCode.gotOnBase }.count.doubleValue return onBaseBatCount / atBats.count.doubleValue case .plateAppearances: return atBats.count.doubleValue case .rbis: return atBats.reduce(0, { $0 + $1.rbis }).doubleValue case .reachOnError: return atBats.withResult(.roe).count.doubleValue case .singles: return atBats.withResult(.single).count.doubleValue case .slugging: guard atBats.sluggingCount > 0 else { return 0 } return atBats.sluggingCount / atBats.battingAverageCount.doubleValue case .strikeOuts: return atBats.withResult(.k).count.doubleValue case .triples: return atBats.withResult(.triple).count.doubleValue case .walks: return atBats.withResult(.w).count.doubleValue } } }
mit
7cd28fd215ea1d77e9ba6a485aa875d8
31.628205
223
0.571316
4.062251
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/ParticleStyle.swift
1
6838
// // Created by Raimundas Sakalauskas on 18/09/2018. // Copyright (c) 2018 Particle. All rights reserved. // import Foundation class ParticleStyle { //fonts static var RegularFont: String = "AvenirNext-Regular" static var ItalicFont: String = "AvenirNext-Italic" static var BoldFont: String = "AvenirNext-DemiBold" //text sizes static var DetailSize = 12 static var SmallSize = 14 static var RegularSize = 16 static var LargeSize = 18 static var ExtraLargeSize = 22 static var PriceSize = 48 //colors static var PrimaryTextColor = UIColor(rgb: 0x333333) static var SecondaryTextColor = UIColor(rgb: 0xB1B1B1) static var DetailsTextColor = UIColor(rgb: 0x8A8A8F) static var RedTextColor = UIColor(rgb: 0xED1C24) static var DisclosureIndicatorColor = UIColor(rgb: 0xB1B1B1) static var BillingTextColor = UIColor(rgb: 0x76777A) static var StrikeThroughColor = UIColor(rgb: 0x002F87) static var DisabledTextColor = UIColor(rgb: 0xA9A9A9) static var PlaceHolderTextColor = UIColor(rgb: 0xA9A9A9) static var InputTitleColor = UIColor(rgb: 0x777777) static var NoteBackgroundColor = UIColor(rgb: 0xF7F7F7) static var NoteBorderColor = UIColor(rgb: 0xC7C7C7) static var ProgressBarProgressColor = UIColor(rgb: 0x02ADEF) static var ProgressBarTrackColor = UIColor(rgb: 0xF5F5F5) static var EthernetToggleBackgroundColor = UIColor(rgb: 0xF5F5F5) static var ViewBackgroundColor = UIColor(rgb: 0xFFFFFF) static var AlternativeButtonColor = UIColor(rgb: 0xFFFFFF) static var AlternativeButtonBorderColor = UIColor(rgb: 0x02ADEF) static var AlternativeButtonTitleColor = UIColor(rgb: 0x02ADEF) static var ButtonColor = UIColor(rgb: 0x02ADEF) static var ButtonRedColor = UIColor(rgb: 0xED1C24) static var ButtonTitleColor = UIColor(rgb: 0xFFFFFF) static var TableViewBackgroundColor = UIColor(rgb: 0xEFEFF4) static var CellSeparatorColor = UIColor(rgb: 0xBCBBC1) static var CellHighlightColor = UIColor(rgb: 0xF5F5F5) static var PairingActivityIndicatorColor = UIColor(rgb: 0x02ADEF) static var NetworkScanActivityIndicatorColor = UIColor(rgb: 0x333333) static var NetworkJoinActivityIndicatorColor = UIColor(rgb: 0x333333) static var ProgressActivityIndicatorColor = UIColor(rgb: 0x333333) static var ClearButtonColor = UIColor(rgb: 0x999999) static var FilterBorderColor = UIColor(rgb: 0xD9D8D6) } class ParticleLabel: UILabel { func setStyle(font: String, size: Int, color: UIColor) { self.textColor = color self.font = UIFont(name: font, size: CGFloat(size)) } } class ParticleSegmentedControl: UISegmentedControl { func setStyle(font: String, size: Int, color: UIColor) { self.tintColor = color self.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: font, size: CGFloat(size))], for: .normal) } } class ParticleTextField: UITextField { func setStyle(font: String, size: Int, color: UIColor) { self.textColor = color self.font = UIFont(name: font, size: CGFloat(size)) } override func awakeFromNib() { super.awakeFromNib() superview?.layer.cornerRadius = 3 superview?.layer.borderColor = ParticleStyle.NoteBorderColor.cgColor superview?.layer.borderWidth = 1 } } class ParticleTextView: UITextView { func setStyle(font: String, size: Int, color: UIColor) { self.textColor = color self.font = UIFont(name: font, size: CGFloat(size)) } } @IBDesignable class ParticleCustomButton: UIButton { @IBInspectable public var upperCase: Bool = true override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 3.0 } override func setTitle(_ title: String?, for state: State) { if (self.upperCase) { super.setTitle(title?.uppercased(), for: state) } else { super.setTitle(title, for: state) } } func setTitle(_ title: String?, for state: UIControl.State, upperCase: Bool = true) { self.upperCase = upperCase self.setTitle(title, for: state) } func setStyle(font: String, size: Int, color: UIColor) { self.titleLabel?.font = UIFont(name: font, size: CGFloat(size)) self.setTitleColor(color, for: .normal) self.setTitleColor(color, for: .selected) self.setTitleColor(color, for: .highlighted) self.setTitleColor(color.withAlphaComponent(0.5), for: .disabled) DispatchQueue.main.async{ self.tintColor = color self.imageView?.tintColor = color } } } class ParticleButton: ParticleCustomButton { override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = ParticleStyle.ButtonColor self.layer.applySketchShadow(color: .black, alpha: 0.3, x: 0, y: 1, blur: 2, spread: 0) } func setStyle(font: String, size: Int) { self.setStyle(font: font, size: size, color: ParticleStyle.ButtonTitleColor) } } class ParticleDestructiveButton: ParticleButton { override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = ParticleStyle.ButtonRedColor } } class ParticleAlternativeButton: ParticleCustomButton { override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = ParticleStyle.AlternativeButtonColor self.layer.borderColor = ParticleStyle.AlternativeButtonBorderColor.cgColor self.layer.borderWidth = 1 self.layer.applySketchShadow(color: .black, alpha: 0.3, x: 0, y: 1, blur: 2, spread: 0) } func setStyle(font: String, size: Int) { self.setStyle(font: font, size: size, color: ParticleStyle.AlternativeButtonTitleColor) } } class ParticleCheckBoxButton: UIButton { override func awakeFromNib() { super.awakeFromNib() self.imageEdgeInsets = UIEdgeInsets(top: -15, left: -15, bottom: -15, right: 15) self.setBackgroundImage(UIImage(named: "Gen3SetupCheckBox"), for: .normal) self.setBackgroundImage(UIImage(named: "Gen3SetupCheckBoxSelected"), for: .selected) self.setBackgroundImage(UIImage(named: "Gen3SetupCheckBoxSelected"), for: .highlighted) self.tintColor = .clear } override func backgroundRect(forBounds bounds: CGRect) -> CGRect { return CGRect(x: 0, y: (bounds.height-20)/2, width: 20, height: 20) } } class ParticleNoteView: UIView { override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 3 self.backgroundColor = ParticleStyle.NoteBackgroundColor self.layer.borderColor = ParticleStyle.NoteBorderColor.cgColor self.layer.borderWidth = 1 } }
apache-2.0
02023e677f025b288a66c04fd3a509a8
30.223744
121
0.693331
4.126735
false
false
false
false
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Scenes/Licenses/LicensesViewController.swift
1
1117
// // Created by Maxim Pervushin on 05/02/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit class LicensesViewController: ThemedViewController { @IBOutlet weak var tableView: UITableView! private let dataSource = LicensesDataSource() override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 50 } } extension LicensesViewController: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataSource.numberOfLicenses } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let license = dataSource.licenseAtIndex(indexPath.section) let cell = tableView.dequeueReusableCellWithIdentifier(LicenseCell.defaultReuseIdentifier, forIndexPath: indexPath) as! LicenseCell cell.license = license return cell } }
mit
9a78488df721e6f40edb40ec51c02627
29.189189
139
0.731423
5.613065
false
false
false
false
y-hryk/MVVM_Demo
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift
2
6796
// // TableViewWithEditingCommandsViewController.swift // RxExample // // Created by carlos on 26/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif /** Another way to do "MVVM". There are different ideas what does MVVM mean depending on your background. It's kind of similar like FRP. In the end, it doesn't really matter what jargon are you using. This would be the ideal case, but it's really hard to model complex views this way because it's not possible to observe partial model changes. */ struct TableViewEditingCommandsViewModel { let favoriteUsers: [User] let users: [User] func executeCommand(_ command: TableViewEditingCommand) -> TableViewEditingCommandsViewModel { switch command { case let .setUsers(users): return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users) case let .setFavoriteUsers(favoriteUsers): return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users) case let .deleteUser(indexPath): var all = [self.favoriteUsers, self.users] all[indexPath.section].remove(at: indexPath.row) return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1]) case let .moveUser(from, to): var all = [self.favoriteUsers, self.users] let user = all[from.section][from.row] all[from.section].remove(at: from.row) all[to.section].insert(user, at: to.row) return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1]) } } } enum TableViewEditingCommand { case setUsers(users: [User]) case setFavoriteUsers(favoriteUsers: [User]) case deleteUser(indexPath: IndexPath) case moveUser(from: IndexPath, to: IndexPath) } class TableViewWithEditingCommandsViewController: ViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let dataSource = TableViewWithEditingCommandsViewController.configureDataSource() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.editButtonItem let superMan = User( firstName: "Super", lastName: "Man", imageURL: "http://nerdreactor.com/wp-content/uploads/2015/02/Superman1.jpg" ) let watMan = User(firstName: "Wat", lastName: "Man", imageURL: "http://www.iri.upc.edu/files/project/98/main.GIF" ) let loadFavoriteUsers = RandomUserAPI.sharedAPI .getExampleUserResultSet() .map(TableViewEditingCommand.setUsers) let initialLoadCommand = Observable.just(TableViewEditingCommand.setFavoriteUsers(favoriteUsers: [superMan, watMan])) .concat(loadFavoriteUsers) .observeOn(MainScheduler.instance) let deleteUserCommand = tableView.rx.itemDeleted.map(TableViewEditingCommand.deleteUser) let moveUserCommand = tableView .rx.itemMoved // This is needed because rx.itemMoved is being performed before delegate method is // delegated to RxDataSource. // This observeOn makes sure data is rebound after automatic move is performed in data source. // This will be improved in RxSwift 3.0 when order will be inversed. .observeOn(MainScheduler.asyncInstance) .map(TableViewEditingCommand.moveUser) let initialState = TableViewEditingCommandsViewModel(favoriteUsers: [], users: []) let viewModel = Observable.of(initialLoadCommand, deleteUserCommand, moveUserCommand) .merge() .scan(initialState) { $0.executeCommand($1) } .shareReplay(1) viewModel .map { [ SectionModel(model: "Favorite Users", items: $0.favoriteUsers), SectionModel(model: "Normal Users", items: $0.users) ] } .bindTo(tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) tableView.rx.itemSelected .withLatestFrom(viewModel) { i, viewModel in let all = [viewModel.favoriteUsers, viewModel.users] return all[i.section][i.row] } .subscribe(onNext: { [weak self] user in self?.showDetailsForUser(user) }) .addDisposableTo(disposeBag) // customization using delegate // RxTableViewDelegateBridge will forward correct messages tableView.rx.setDelegate(self) .addDisposableTo(disposeBag) } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.isEditing = editing } // MARK: Table view delegate ;) func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let title = dataSource.sectionAtIndex(section) let label = UILabel(frame: CGRect.zero) // hacky I know :) label.text = " \(title)" label.textColor = UIColor.white label.backgroundColor = UIColor.darkGray label.alpha = 0.9 return label } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } // MARK: Navigation private func showDetailsForUser(_ user: User) { let storyboard = UIStoryboard(name: "Main", bundle: Bundle(identifier: "RxExample-iOS")) let viewController = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController viewController.user = user self.navigationController?.pushViewController(viewController, animated: true) } // MARK: Work over Variable static func configureDataSource() -> RxTableViewSectionedReloadDataSource<SectionModel<String, User>> { let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>() dataSource.configureCell = { (_, tv, ip, user: User) in let cell = tv.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = user.firstName + " " + user.lastName return cell } dataSource.titleForHeaderInSection = { dataSource, sectionIndex in return dataSource.sectionAtIndex(sectionIndex).model } dataSource.canEditRowAtIndexPath = { (ds, ip) in return true } dataSource.canMoveRowAtIndexPath = { _ in return true } return dataSource } }
mit
a0b21cde954851f91ae35b4fb8a17821
35.143617
130
0.652833
4.877961
false
false
false
false
recruit-lifestyle/Smile-Lock
SmileLock/Classes/PasswordInputView.swift
2
7690
// // PasswordInputView.swift // // Created by rain on 4/21/16. // Copyright © 2016 Recruit Lifestyle Co., Ltd. All rights reserved. // import UIKit public protocol PasswordInputViewTappedProtocol: class { func passwordInputView(_ passwordInputView: PasswordInputView, tappedString: String) } @IBDesignable open class PasswordInputView: UIView { //MARK: Property open weak var delegate: PasswordInputViewTappedProtocol? let circleView = UIView() let button = UIButton() public let label = UILabel() open var labelFont: UIFont? fileprivate let fontSizeRatio: CGFloat = 46 / 40 fileprivate let borderWidthRatio: CGFloat = 1 / 26 fileprivate var touchUpFlag = true fileprivate(set) open var isAnimating = false var isVibrancyEffect = false @IBInspectable open var numberString = "2" { didSet { label.text = numberString } } @IBInspectable open var borderColor = UIColor.darkGray { didSet { backgroundColor = borderColor } } @IBInspectable open var circleBackgroundColor = UIColor.white { didSet { circleView.backgroundColor = circleBackgroundColor } } @IBInspectable open var textColor = UIColor.darkGray { didSet { label.textColor = textColor } } @IBInspectable open var highlightBackgroundColor = UIColor.red @IBInspectable open var highlightTextColor = UIColor.white //MARK: Life Cycle #if TARGET_INTERFACE_BUILDER open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configureSubviews() } #else override open func awakeFromNib() { super.awakeFromNib() configureSubviews() } #endif @objc func touchDown() { //delegate callback delegate?.passwordInputView(self, tappedString: numberString) //now touch down, so set touch up flag --> false touchUpFlag = false touchDownAnimation() } @objc func touchUp() { //now touch up, so set touch up flag --> true touchUpFlag = true //only show touch up animation when touch down animation finished if !isAnimating { touchUpAnimation() } } open override func layoutSubviews() { super.layoutSubviews() updateUI() } fileprivate func getLabelFont() -> UIFont { if labelFont != nil { return labelFont! } let width = bounds.width let height = bounds.height let radius = min(width, height) / 2 return UIFont.systemFont(ofSize: radius * fontSizeRatio, weight: touchUpFlag ? UIFont.Weight.thin : UIFont.Weight.regular) } fileprivate func updateUI() { //prepare calculate let width = bounds.width let height = bounds.height let center = CGPoint(x: width/2, y: height/2) let radius = min(width, height) / 2 let borderWidth = radius * borderWidthRatio let circleRadius = radius - borderWidth //update label label.text = numberString label.font = getLabelFont() label.textColor = textColor //update circle view circleView.frame = CGRect(x: 0, y: 0, width: 2 * circleRadius, height: 2 * circleRadius) circleView.center = center circleView.layer.cornerRadius = circleRadius circleView.backgroundColor = circleBackgroundColor //circle view border circleView.layer.borderWidth = isVibrancyEffect ? borderWidth : 0 //update mask let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: 2.0 * CGFloat(Double.pi), clockwise: false) let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath layer.mask = maskLayer //update color backgroundColor = borderColor } } private extension PasswordInputView { //MARK: Awake func configureSubviews() { addSubview(circleView) //configure label NSLayoutConstraint.addEqualConstraintsFromSubView(label, toSuperView: self) label.textAlignment = .center label.isAccessibilityElement = false //configure button NSLayoutConstraint.addEqualConstraintsFromSubView(button, toSuperView: self) button.isExclusiveTouch = true button.addTarget(self, action: #selector(PasswordInputView.touchDown), for: [.touchDown]) button.addTarget(self, action: #selector(PasswordInputView.touchUp), for: [.touchUpInside, .touchDragOutside, .touchCancel, .touchDragExit]) button.accessibilityValue = numberString } //MARK: Animation func touchDownAction() { label.font = getLabelFont() label.textColor = highlightTextColor if !self.isVibrancyEffect { backgroundColor = highlightBackgroundColor } circleView.backgroundColor = highlightBackgroundColor } func touchUpAction() { label.font = getLabelFont() label.textColor = textColor backgroundColor = borderColor circleView.backgroundColor = circleBackgroundColor } func touchDownAnimation() { isAnimating = true tappedAnimation(animations: { self.touchDownAction() }) { if self.touchUpFlag { self.touchUpAnimation() } else { self.isAnimating = false } } } func touchUpAnimation() { isAnimating = true tappedAnimation(animations: { self.touchUpAction() }) { self.isAnimating = false } } func tappedAnimation(animations: @escaping () -> (), completion: (() -> ())?) { UIView.animate(withDuration: 0.25, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: animations) { _ in completion?() } } } internal extension NSLayoutConstraint { class func addConstraints(fromView view: UIView, toView baseView: UIView, constraintInsets insets: UIEdgeInsets) { baseView.topAnchor.constraint(equalTo: view.topAnchor, constant: -insets.top) let topConstraint = baseView.topAnchor.constraint(equalTo: view.topAnchor, constant: -insets.top) let bottomConstraint = baseView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: insets.bottom) let leftConstraint = baseView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: -insets.left) let rightConstraint = baseView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: insets.right) NSLayoutConstraint.activate([topConstraint, bottomConstraint, leftConstraint, rightConstraint]) } class func addEqualConstraintsFromSubView(_ subView: UIView, toSuperView superView: UIView) { superView.addSubview(subView) subView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.addConstraints(fromView: subView, toView: superView, constraintInsets: UIEdgeInsets.zero) } class func addConstraints(fromSubview subview: UIView, toSuperView superView: UIView, constraintInsets insets: UIEdgeInsets) { superView.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.addConstraints(fromView: subview, toView: superView, constraintInsets: insets) } }
apache-2.0
ab5b1575505b0bc77f3b8e03c7a396eb
31.858974
148
0.642346
5.388227
false
false
false
false
realtime-framework/realtime-news-swift
Realtime/Realtime/TabBarViewController.swift
1
21165
// // TabBarViewController.swift // RealtimeNews // // Created by Joao Caixinha on 24/02/15. // Copyright (c) 2015 Realtime. All rights reserved. // import UIKit var currentSearchMonth:String? class TabBarViewController: UITabBarController, UITabBarControllerDelegate, UINavigationControllerDelegate, OptionsViewProtocol, SMProtocol{ struct Static { static var onceToken: dispatch_once_t = 0 } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } @IBOutlet weak var filterButton: UIBarButtonItem! @IBOutlet weak var optionButton: UIBarButtonItem! var isFiltred:Bool = false var filter:String = "" var optionsView:OptionsViewController? var entrys:NSMutableArray? var statusView:UIView? var statusLabel:UILabel? var activity:UIActivityIndicatorView? var viewframe:CGRect? var connect:Bool? var connectFrame:CGRect? var disconnectFrame:CGRect? var viewDidAppear:Bool = false var swipeLeft:UISwipeGestureRecognizer? var swipeRight:UISwipeGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.configStatusView() self.setOptionsView() self.setActivityView() self.verifyAuth() self.title = "Recent" self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(20)] NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("setViewFrame"), name: "fromBackground", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("verifyAuth"), name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("showActivityView"), name: "startLoad", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("hideActivityView"), name: "endLoad", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("verifyAuth"), name: kReachabilityChangedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("getData"), name: "getData", object: nil) self.swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("swipeLeft:")) self.swipeLeft!.direction = UISwipeGestureRecognizerDirection.Left self.view.addGestureRecognizer(self.swipeLeft!) self.swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("swipeRight:")) self.swipeRight!.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(self.swipeRight!) } func swipeRight(recognizer:UIGestureRecognizer) { if self.optionsView?.isVisible == nil || self.optionsView?.isVisible == false { self.toggleMenu() } } func swipeLeft(recognizer:UIGestureRecognizer) { if self.optionsView?.isVisible == true { self.toggleMenu() } } func setActivityView() { self.activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) self.activity?.color = UIColor.redColor() self.hideActivityView() let activityButton:UIBarButtonItem = UIBarButtonItem(customView: self.activity!) self.navigationItem.leftBarButtonItems = [self.optionButton, activityButton] } func showActivityView(){ self.activity?.hidden = false self.activity?.startAnimating() } func hideActivityView(){ self.activity?.hidden = true self.activity?.stopAnimating() } func updateConnectionStatus(){ if self.viewDidAppear == true{ let internetStatus:NetworkStatus = networkReachability.currentReachabilityStatus() if internetStatus != NetworkStatus.NotReachable && isConnected == true{ self.setStatus(true) }else{ self.setStatus(false) } } } func verifyAuth(){ Utils.reAuth ({ (result:Bool) -> Void in if result == false || storage == nil{ if storage != nil { storage!.removeListeners() storage!.contentsTableRef!.disableListeners() storage!.tagsTableRef!.disableListeners() } storage = Storage(contentsDelegate: self, tagsDelegate: self.optionsView!) self.getData() } NSNotificationCenter.defaultCenter().postNotificationName("reAuthenticate", object: nil, userInfo: nil) self.setStatus(true) }, errorCallBack: {() ->Void in if storage == nil { let contents:SM = SM(tableName: TABCONTENTS, storageRef: nil) contents.delegate = self contents.loadOffLineData() let options:SM = SM(tableName: TABTAGS, storageRef: nil) options.delegate = self.optionsView options.loadOffLineMenu() }else{ storage?.contentsTableRef?.loadOffLineData() storage?.tagsTableRef?.loadOffLineMenu() } self.setStatus(false) }) } func onReconnected() { NSLog("( onReconnected )") storage?.contentsTableRef?.reset() self.getData() self.setStatus(true) } func onReconnecting() { storage?.contentsTableRef?.loadOffLineData() self.setStatus(false) } func loadFirstMonthYear() { let data:NSData? = Utils.firstMonthYear() if data != nil { let temp:String = NSString(data: data!, encoding: NSUTF8StringEncoding)! as String Utils.jsonDictionaryFromString(temp, onCompletion: { (dict:NSDictionary) -> Void in firstMonthYear = dict.objectForKey("firstMonthYear") as! String! }) { (error:NSError) -> Void in } } } func getData() { dispatch_semaphore_wait(flag, DISPATCH_TIME_FOREVER) if storage?.contentsTableRef?.processing == false{ if firstMonthYear == nil || firstMonthYear == "" { currentSearchMonth = nil scrollLimit = limit lastTimestamp = nil self.loadFirstMonthYear() } if currentSearchMonth != firstMonthYear { if currentSearchMonth == nil { currentSearchMonth = Utils.getCurrentMonthYear() }else if(currentSearchMonth != nil && storage?.contentsTableRef?.lastCount < limit){ currentSearchMonth = Utils.getPreviousMonth(currentSearchMonth!) } storage?.contentsTableRef?.resetFilter() storage?.contentsTableRef?.appendFilter(currentSearchMonth!, field: "MonthYear") if lastTimestamp != nil { storage?.contentsTableRef?.appendFilterLesser(lastTimestamp!, field: "Timestamp") } storage?.contentsTableRef?.getData() } } dispatch_semaphore_signal(flag) } func didReceivedData(data:NSMutableArray) { self.entrys = Utils.orderTopics(data) if self.entrys != nil && self.entrys!.count > 0{ let last:DataObject = self.entrys!.objectAtIndex(self.entrys!.count - 1) as! DataObject lastTimestamp = last.timestamp as? String } if self.entrys?.count < scrollLimit && currentSearchMonth != firstMonthYear { dispatch_semaphore_signal(flag) self.getData() return } let array = self.viewControllers as [AnyObject]? for view in array! { view.didReceivedData!(self.entrys!) } // if self.entrys != nil && self.entrys?.count > 0{ // //let item:DataObject = self.entrys!.objectAtIndex(0) as! DataObject // } dispatch_semaphore_signal(flag) let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { sleep(1) dispatch_async(dispatch_get_main_queue()) { self.processPush() } } } func setViewFrame(){ dispatch_async(dispatch_get_main_queue(), { if (!CGRectIsNull(self.viewframe!)) { self.view.frame = self.viewframe! } }); } func configStatusView(){ let barFrame:CGRect! = self.navigationController?.navigationBar.frame self.viewframe = self.view.frame self.statusView = UIView(frame: CGRectMake(barFrame.origin.x, barFrame.size.height, self.view.frame.size.width, 20)) self.statusLabel = UILabel(frame: CGRectMake(0, 0, self.statusView!.frame.size.width, 20)) self.statusLabel?.textAlignment = NSTextAlignment.Center self.statusLabel?.font = UIFont.boldSystemFontOfSize(10) self.statusLabel?.textColor = UIColor.whiteColor() self.statusView?.addSubview(self.statusLabel!) self.view?.addSubview(self.statusView!) self.disconnectFrame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + self.statusView!.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.statusView!.frame.size.height) self.connectFrame = CGRectMake(self.disconnectFrame!.origin.x, self.disconnectFrame!.origin.y - self.statusView!.frame.size.height, self.disconnectFrame!.size.width,self.disconnectFrame!.size.height + self.statusView!.frame.size.height); } func setStatus(connect:Bool) { dispatch_async(queue){ while self.viewDidAppear == false { sleep(1) } dispatch_async(dispatch_get_main_queue(), { if (connect == true) { self.statusView?.backgroundColor = UIColor.greenColor() self.statusLabel?.text = "Connected"; UIView.animateWithDuration(1.0, animations: { () -> Void in self.view.frame = self.connectFrame! }, completion: { (finish) -> Void in self.viewframe = self.view.frame }) }else if(connect == false) { self.statusView?.backgroundColor = UIColor.redColor() self.statusLabel?.text = "Not Connected"; UIView.animateWithDuration(1.0, animations: { () -> Void in self.view.frame = self.disconnectFrame! }, completion: { (finish) -> Void in self.viewframe = self.view.frame }) } }); } } func filterData(view:SMProtocol, filter:NSString?) { if (filter != nil) { let res:NSArray = Utils.performSearch(self.entrys!, name: filter, key: "tag") view.didReceivedData!(NSMutableArray(array: res)) view.isFiltred = true view.filter = filter! as String }else { view.didReceivedData!(self.entrys!) } self.setFiltredButton(view) } func removeFilter() { let view:SMProtocol = self.selectedViewController as! SMProtocol view.isFiltred = false; self.filterData(view, filter: nil); } func setFiltredButton(view:SMProtocol) { if (view.isFiltred == false) { self.filterButton.enabled = false; self.filterButton.tintColor = UIColor.clearColor() }else { self.filterButton.enabled = true self.filterButton.tintColor = nil } } override func viewWillAppear(animated: Bool) { let view = self.selectedViewController as? SMProtocol if view != nil { self.setFiltredButton(view!) }else { self.filterButton.enabled = false; self.filterButton.tintColor = UIColor.clearColor() } } override func viewDidAppear(animated: Bool) { self.viewDidAppear = true self.navigationController?.delegate = self self.setViewFrame() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func processPush() { var temp:NSMutableDictionary? var dicKey:NSString? for (key, _) in notifications { dicKey = key as? NSString temp = notifications.objectForKey(key) as? NSMutableDictionary break; } if dicKey == nil { return } for it in self.entrys! { let item:DataObject = it as! DataObject if ("\(item.type!)-\(item.timestamp!)" == dicKey! as String) { temp?.setObject(item, forKey: "DataObject") break; } } if (temp!.objectForKey("DataObject") != nil) { let array:NSArray = self.viewControllers! as NSArray let recent = array.objectAtIndex(0) as! RecentsViewController self.selectedViewController = recent recent.notificationItem = temp!.objectForKey("DataObject") array.objectAtIndex(0).performSegueWithIdentifier("contentView", sender:self) } } func didReceivedItem(item:DataObject) { let obj:DataObject? = storage?.contentsTableRef?.dataIndex!.objectForKey("\(item.type!)-\(item.timestamp!)") as? DataObject if (obj != nil) { obj!.updateItem(item) self.setUpdated(obj!) }else{ self.entrys!.addObject(item) //var test:NSMutableDictionary = storage?.contentsTableRef?.dataIndex as NSMutableDictionary! storage?.contentsTableRef?.dataIndex!.setObject(item, forKey:"\(item.type!)-\(item.timestamp!)") self.setNew(item) } self.entrys = Utils.orderTopics(self.entrys!) let array:NSArray = self.viewControllers! as NSArray let recent = array.objectAtIndex(0) as! SMProtocol recent.didReceivedData!(self.entrys!) let blog:SMProtocol = array.objectAtIndex(1) as! SMProtocol blog.didReceivedData!(self.entrys!) let white:SMProtocol = array.objectAtIndex(2) as! SMProtocol white.didReceivedData!(self.entrys!) let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { sleep(1) dispatch_async(dispatch_get_main_queue()) { self.processPush() } } } func setNew(item:DataObject) { item.isNew = true; let array:NSArray = self.viewControllers! as NSArray if (item.type == "Blog") { array.objectAtIndex(1).tabBarItem!.badgeValue = "New"; } if (item.type == "White Papers") { array.objectAtIndex(2).tabBarItem!.badgeValue = "New"; } } func setUpdated(item:DataObject) { item.isUpdated = true let array:NSArray = self.viewControllers! as NSArray if (item.type == "Blog") { array.objectAtIndex(1).tabBarItem!.badgeValue = "Updated"; } if (item.type == "White Papers") { array.objectAtIndex(2).tabBarItem!.badgeValue = "Updated"; } } func didDeleteItem(item:DataObject) { //let dict:NSMutableDictionary = storage?.contentsTableRef?.dataIndex as NSMutableDictionary! let entry:DataObject? = storage?.contentsTableRef?.dataIndex!.objectForKey("\(item.type!)-\(item.timestamp!)") as? DataObject if (entry != nil) { entry!.removeFromDisk() self.entrys!.removeObject(entry!) storage?.contentsTableRef?.dataIndex!.removeObjectForKey("\(item.type!)-\(item.timestamp!)") storage?.contentsTableRef?.data!.removeObject(entry!) let onDisk:NSMutableDictionary = contentsOnDiskData onDisk.removeObjectForKey("\(item.type!)-\(item.timestamp!)") DataObject.writeContentOndisk() let array:NSArray = self.viewControllers! as NSArray self.entrys = Utils.orderTopics(self.entrys!) if (item.type == "Blog") { let blog:SMProtocol = array.objectAtIndex(1) as! SMProtocol blog.didReceivedData!(self.entrys!) } if (item.type == "White Papers") { let blog:SMProtocol = array.objectAtIndex(2) as! SMProtocol blog.didReceivedData!(self.entrys!) } let blog:SMProtocol = array.objectAtIndex(0) as! SMProtocol blog.didReceivedData!(self.entrys!) } } func setOptionsView(){ self.optionsView = OptionsViewController(nibName: "OptionsViewController", bundle: NSBundle.mainBundle()) self.optionsView!.delegate = self; let selfFrame:CGRect = self.view.frame; self.optionsView!.view.frame = CGRectMake(selfFrame.size.width * (-1), selfFrame.origin.y, selfFrame.size.width, selfFrame.size.height - self.tabBar.frame.size.height) self.view.addSubview(self.optionsView!.view) } func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) { self.title = viewController.title self.setFiltredButton(viewController as! SMProtocol) } @IBAction func actionRemoveFilter(sender: AnyObject) { self.removeFilter() } func didTap(option: NSString, onSection: NSString) { if (onSection == "Session") { self.toggleMenu() if (option == "Logout") { storage?.contentsTableRef?.data = NSMutableArray() Utils.goToLogin() } return; } self.removeFilter() let array:NSArray = self.viewControllers! as NSArray for view in array { if (view.title == onSection) { self.toggleMenu() self.filterData(view as! SMProtocol, filter: option) self.selectedViewController = view as? UIViewController self.title = view.title } } } @IBAction func action_SplitView(sender: AnyObject) { self.toggleMenu() } func toggleMenu() { if (self.optionsView!.isAnimating == true) { return; } self.optionsView!.isAnimating = true let selfFrame:CGRect = self.view.frame let optionFrame:CGRect = self.optionsView!.view.frame let tableFrame:CGRect = self.optionsView!.table_Options.frame if (self.optionsView!.isVisible == true) { UIView.animateWithDuration(0.5, animations: { () -> Void in self.optionsView!.view.frame = CGRectMake(selfFrame.size.width * (-1), selfFrame.origin.y, selfFrame.size.width, selfFrame.size.height - self.tabBar.frame.size.height) }, completion: { (finish) -> Void in self.optionsView!.isVisible = false self.optionsView!.isAnimating = false }) }else { UIView.animateWithDuration(0.5, animations: { () -> Void in self.optionsView!.view.frame = CGRectMake(tableFrame.origin.x * (-1), selfFrame.origin.y, optionFrame.size.width, selfFrame.size.height - self.tabBar.frame.size.height) }, completion: { (finish) -> Void in self.optionsView!.isVisible = true self.optionsView!.isAnimating = false }) } } func navigationControllerSupportedInterfaceOrientations(navigationController: UINavigationController) -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } }
mit
4a0e2bd52c887fc7a0e4521e20387939
34.812183
245
0.584408
5.036887
false
false
false
false
siberianisaev/NeutronBarrel
NeutronBarrel/SearchCriteria.swift
1
4792
// // SearchCriteria.swift // NeutronBarrel // // Created by Andrey Isaev on 13/06/2018. // Copyright © 2018 Flerov Laboratory. All rights reserved. // import Foundation class SearchCriteria { var resultsFolderName: String = "" var wellParticleBackType: SearchType = .fission var neutronsDetectorEfficiency: Double = 0 var neutronsDetectorEfficiencyError: Double = 0 var placedSFSource: SFSource? var startParticleType: SearchType = .fission var startParticleBackType: SearchType = .fission var summarizeFissionsAlphaFront = false var fissionAlphaFrontMinEnergy: Double = 0 var fissionAlphaFrontMaxEnergy: Double = 0 var fissionAlphaBackMinEnergy: Double = 0 var fissionAlphaBackMaxEnergy: Double = 0 var fissionAlphaWellMinEnergy: Double = 0 var fissionAlphaWellMaxEnergy: Double = 0 var fissionAlphaWellMaxAngle: Double = 0 var searchFissionAlphaBackByFact: Bool = true var summarizeFissionsAlphaBack = false var recoilFrontMinEnergy: Double = 0 var recoilFrontMaxEnergy: Double = 0 var recoilBackMinEnergy: Double = 0 var recoilBackMaxEnergy: Double = 0 var searchRecoilBackByFact: Bool = false var minTOFValue: Double = 0 var maxTOFValue: Double = 0 var recoilMinTime: CUnsignedLongLong = 0 var recoilMaxTime: CUnsignedLongLong = 0 var recoilBackMaxTime: CUnsignedLongLong = 0 var fissionAlphaMaxTime: CUnsignedLongLong = 0 var recoilBackBackwardMaxTime: CUnsignedLongLong = 0 var fissionAlphaBackBackwardMaxTime: CUnsignedLongLong = 0 var fissionAlphaWellBackwardMaxTime: CUnsignedLongLong = 0 var maxTOFTime: CUnsignedLongLong = 0 var maxVETOTime: CUnsignedLongLong = 0 var maxGammaTime: CUnsignedLongLong = 0 var maxGammaBackwardTime: CUnsignedLongLong = 0 var minNeutronTime: CUnsignedLongLong = 0 var maxNeutronTime: CUnsignedLongLong = 0 var maxNeutronBackwardTime: CUnsignedLongLong = 0 var checkNeutronMaxDeltaTimeExceeded: Bool = true var recoilFrontMaxDeltaStrips: Int = 0 var recoilBackMaxDeltaStrips: Int = 0 var searchFirstRecoilOnly = false var requiredFissionAlphaBack = false var requiredRecoilBack = false var requiredRecoil = false var requiredGamma = false var requiredGammaOrWell = false var simplifyGamma = false var requiredWell = false var wellRecoilsAllowed = false var searchExtraFromLastParticle = false var inBeamOnly = false var overflowOnly = false var requiredTOF = false var useTOF2 = false var requiredVETO = false var searchVETO = false var trackBeamEnergy = false var trackBeamCurrent = false var trackBeamBackground = false var trackBeamIntegral = false var trackBeamState: Bool { return trackBeamEnergy || trackBeamCurrent || trackBeamBackground || trackBeamIntegral } var searchNeutrons = false var neutronsBackground = false var simultaneousDecaysFilterForNeutrons = false var mixingTimesFilterForNeutrons = false var neutronsPositions = false var next = [Int: SearchNextCriteria]() func nextMaxIndex() -> Int? { return Array(next.keys).max() } var searchSpecialEvents = false var specialEventIds = Set<Int>() var gammaEncodersOnly = false var gammaEncoderIds = Set<Int>() var searchWell = true var unitsTOF: TOFUnits = .channels var recoilType: SearchType = .recoil var recoilBackType: SearchType = .recoil func startFromRecoil() -> Bool { return startParticleType == .recoil || startParticleType == .heavy } } class SearchNextCriteria { var summarizeFront = false var frontMinEnergy: Double = 0 var frontMaxEnergy: Double = 0 var backMinEnergy: Double = 0 var backMaxEnergy: Double = 0 var minTime: CUnsignedLongLong = 0 var maxTime: CUnsignedLongLong = 0 var maxDeltaStrips: Int = 0 var backByFact: Bool = true var frontType: SearchType = .fission var backType: SearchType = .fission init(summarizeFront: Bool, frontMinEnergy: Double, frontMaxEnergy: Double, backMinEnergy: Double, backMaxEnergy: Double, minTime: CUnsignedLongLong, maxTime: CUnsignedLongLong, maxDeltaStrips: Int, backByFact: Bool, frontType: SearchType, backType: SearchType) { self.summarizeFront = summarizeFront self.frontMinEnergy = frontMinEnergy self.frontMaxEnergy = frontMaxEnergy self.backMinEnergy = backMinEnergy self.backMaxEnergy = backMaxEnergy self.minTime = minTime self.maxTime = maxTime self.maxDeltaStrips = maxDeltaStrips self.backByFact = backByFact self.frontType = frontType self.backType = backType } }
mit
c28aa9653db8447714f5caf4a39d439b
34.753731
266
0.720518
4.151646
false
false
false
false
64characters/Telephone
Domain/SimpleUserAgentAudioDevice.swift
1
1067
// // SimpleUserAgentAudioDevice.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public struct SimpleUserAgentAudioDevice: UserAgentAudioDevice { public let identifier: Int public let name: String public let inputs: Int public let outputs: Int public let isNil = false public init(identifier: Int, name: String, inputs: Int, outputs: Int) { self.identifier = identifier self.name = name self.inputs = inputs self.outputs = outputs } }
gpl-3.0
c8324e9e9fe350b9b85a082f0c49dd9c
32.28125
75
0.710798
4.329268
false
false
false
false
AlexChekanov/Gestalt
Gestalt/UI/Guides/Tools/Guides.TextStyles.Tools.swift
1
6697
// // Guides.TextStyles.Tools.swift // Prcess // // Created by Alexey Chekanov on 7/21/17. // Copyright © 2017 Alexey Chekanov. All rights reserved. // import Foundation import UIKit // MARK: - TextStyles struct extension Guides { struct TextStyle { var font: UIFont? var fontColor: UIColor? var fontBackgroundColor: UIColor? var baselineOffset: NSNumber? var strikethroughStyle: NSNumber? var strikethroughColorAttributeName: UIColor? var underlineStyle: NSNumber? var underlineColor: UIColor? var strokeWidth: NSNumber? // NSNumber. In the negative fills the text var strokeColor: UIColor? var textEffectAttributeName: String? // f.e.: NSTextEffectLetterpressStyle as NSString var ligature: NSNumber? var kern: NSNumber? // Paragraph var lineBreakMode: NSLineBreakMode? var allowsDefaultTighteningForTruncation: Bool? var hyphenationFactor: Float? // 0.0—1.0 var alignment: NSTextAlignment? var lineHeightMultiple: CGFloat? // Shadow var shadowColor: UIColor? var shadowBlurRadius: CGFloat? var shadowOffset: CGSize? } } // MARK: - Basic style extension Guides.TextStyle { static let basic: Guides.TextStyle = Guides.TextStyle ( font: nil, fontColor: nil, fontBackgroundColor: nil, baselineOffset: 0, strikethroughStyle: nil, strikethroughColorAttributeName: nil, underlineStyle: nil, underlineColor: nil, strokeWidth: nil, strokeColor: nil, textEffectAttributeName: nil, ligature: 1, kern: nil, lineBreakMode: NSLineBreakMode.byWordWrapping, allowsDefaultTighteningForTruncation: true, hyphenationFactor: 0.0, alignment: NSTextAlignment.natural, lineHeightMultiple: nil, shadowColor: nil, shadowBlurRadius: nil, shadowOffset: nil ) } // MARK: - Empty template extension Guides.TextStyle { static var empty: Guides.TextStyle { return Guides.TextStyle( font: nil, fontColor: nil, fontBackgroundColor: nil, baselineOffset: nil, strikethroughStyle: nil, strikethroughColorAttributeName: nil, underlineStyle: nil, underlineColor: nil, strokeWidth: nil, strokeColor: nil, textEffectAttributeName: nil, ligature: nil, kern: nil, lineBreakMode: nil, allowsDefaultTighteningForTruncation: true, hyphenationFactor: nil, alignment: nil, lineHeightMultiple: nil, shadowColor: nil, shadowBlurRadius: nil, shadowOffset: nil ) } } // MARK: - NSMutableAttributedString extension extension NSMutableAttributedString { private struct AssociatedKey { static var style: Guides.TextStyle? = nil } var style: Guides.TextStyle { get { if let result: Guides.TextStyle = objc_getAssociatedObject(self, &AssociatedKey.style) as? Guides.TextStyle { return result } else { let result = self.style self.style = result return result } } set { objc_setAssociatedObject(self, &AssociatedKey.style, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC); self.applyAttributes(ofStyle: self.style) } } func applyAttributes(ofStyle style: Guides.TextStyle) { var attributes = [String:Any]() if style.font != nil { attributes [NSFontAttributeName] = style.font } if style.fontColor != nil { attributes [NSForegroundColorAttributeName] = style.fontColor } if style.fontBackgroundColor != nil { attributes [NSBackgroundColorAttributeName] = style.fontBackgroundColor } if style.baselineOffset != nil { attributes [NSBaselineOffsetAttributeName] = style.baselineOffset } if style.strikethroughStyle != nil { attributes [NSStrikethroughStyleAttributeName] = style.strikethroughStyle } if style.strikethroughColorAttributeName != nil { attributes [NSStrikethroughColorAttributeName] = style.strikethroughColorAttributeName } if style.underlineStyle != nil { attributes [NSUnderlineStyleAttributeName] = style.underlineStyle } if style.underlineColor != nil { attributes [NSUnderlineColorAttributeName] = style.underlineColor } if style.strokeWidth != nil { attributes [NSStrokeWidthAttributeName] = style.strokeWidth } if style.strokeColor != nil { attributes [NSStrokeColorAttributeName] = style.strokeColor } if style.textEffectAttributeName != nil { attributes [NSTextEffectAttributeName] = style.textEffectAttributeName } if style.ligature != nil { attributes [NSLigatureAttributeName] = style.ligature } if style.kern != nil { attributes [NSKernAttributeName] = style.kern } let paragraphStyle = NSMutableParagraphStyle() if style.lineBreakMode != nil { paragraphStyle.lineBreakMode = style.lineBreakMode! } if style.allowsDefaultTighteningForTruncation != nil { paragraphStyle.allowsDefaultTighteningForTruncation = style.allowsDefaultTighteningForTruncation! } if style.hyphenationFactor != nil { paragraphStyle.hyphenationFactor = style.hyphenationFactor! } if style.alignment != nil { paragraphStyle.alignment = style.alignment! } if style.lineHeightMultiple != nil { paragraphStyle.lineHeightMultiple = style.lineHeightMultiple! } attributes [NSParagraphStyleAttributeName] = paragraphStyle let shadowStyle = NSShadow() if style.shadowColor != nil { shadowStyle.shadowColor = style.shadowColor } if style.shadowBlurRadius != nil { shadowStyle.shadowBlurRadius = style.shadowBlurRadius! } if style.shadowOffset != nil { shadowStyle.shadowOffset = style.shadowOffset!} attributes [NSShadowAttributeName] = shadowStyle self.addAttributes(attributes, range: NSMakeRange(0, self.length)) } }
apache-2.0
0b6466df93b75b0adc1fc2a42b6fe616
31.338164
162
0.621004
5.908208
false
false
false
false
remind101/AutoGraph
AutoGraphTests/Requests/FilmRequest.swift
1
2051
@testable import AutoGraphQL import Foundation import JSONValueRX class FilmRequest: Request { /* query film { film(id: "ZmlsbXM6MQ==") { id title episodeID director openingCrawl } } */ let queryDocument = Operation(type: .query, name: "film", selectionSet: [ Object(name: "film", alias: nil, arguments: ["id" : "ZmlsbXM6MQ=="], selectionSet: [ "id", Scalar(name: "title", alias: nil), Scalar(name: "episodeID", alias: nil), Scalar(name: "director", alias: nil), Scalar(name: "openingCrawl", alias: nil)]) ]) let variables: [AnyHashable : Any]? = nil let rootKeyPath: String = "data.film" public func willSend() throws { } public func didFinishRequest(response: HTTPURLResponse?, json: JSONValue) throws { } public func didFinish(result: AutoGraphResult<Film>) throws { } } class FilmStub: Stub { override var jsonFixtureFile: String? { get { return "Film" } set { } } override var urlPath: String? { get { return "/graphql" } set { } } override var graphQLQuery: String { get { return "query film {\n" + "film(id: \"ZmlsbXM6MQ==\") {\n" + "id\n" + "title\n" + "episodeID\n" + "director\n" + "openingCrawl\n" + "}\n" + "}\n" } set { } } }
mit
d2b87c563b0b5e4a2828eb13f116e6de
30.075758
88
0.37884
5.232143
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Data/Model/SurveyItem.swift
1
4078
// // SurveyItem.swift // SASAbus // // Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]> // // This file is part of SASAbus. // // SASAbus is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SASAbus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with SASAbus. If not, see <http://www.gnu.org/licenses/>. // import Foundation import SwiftyJSON final class SurveyItem: JSONable, JSONCollection { var id: Int! var enabled: Bool! var firstQuestionGerman: String! var firstQuestionEnglish: String! var firstQuestionItalian: String! var firstQuestionPlaceholderGerman: String! var firstQuestionPlaceholderEnglish: String! var firstQuestionPlaceholderItalian: String! var secondQuestionGerman: String! var secondQuestionEnglish: String! var secondQuestionItalian: String! var status: String! required init(parameter: JSON) { self.status = parameter["status"].stringValue if (self.status == "success") { let dataArray = parameter["data"].arrayValue let data = dataArray[0] self.id = data["id"].intValue self.enabled = data["enabled"].stringValue == "y" self.firstQuestionGerman = data["first_question_de"].stringValue self.firstQuestionGerman = data["first_question_de"].stringValue self.firstQuestionEnglish = data["first_question_en"].stringValue self.firstQuestionItalian = data["first_question_it"].stringValue self.firstQuestionPlaceholderGerman = data["first_question_placeholder_de"].stringValue self.firstQuestionPlaceholderEnglish = data["first_question_placeholder_en"].stringValue self.firstQuestionPlaceholderItalian = data["first_question_placeholder_it"].stringValue self.secondQuestionGerman = data["second_question_de"].stringValue self.secondQuestionEnglish = data["second_question_en"].stringValue self.secondQuestionItalian = data["second_question_it"].stringValue } } static func collection(parameter: JSON) -> [SurveyItem] { var items: [SurveyItem] = [] for itemRepresentation in parameter.arrayValue { items.append(SurveyItem(parameter: itemRepresentation)) } return items } func getFirstQuestionLocalized() -> String { let language = (Locale.current as NSLocale).object(forKey: NSLocale.Key.languageCode)! if language as! String == "it" { return self.firstQuestionItalian } else if language as! String == "en" { return self.firstQuestionEnglish } else { return self.firstQuestionGerman } } func getSecondQuestionLocalized() -> String { let language = (Locale.current as NSLocale).object(forKey: NSLocale.Key.languageCode)! if language as! String == "it" { return self.secondQuestionItalian } else if language as! String == "en" { return self.secondQuestionEnglish } else { return self.secondQuestionGerman } } func getFirstQuestionPlaceholderLocalized() -> String { let language = (Locale.current as NSLocale).object(forKey: NSLocale.Key.languageCode)! if language as! String == "it" { return self.firstQuestionPlaceholderItalian } else if language as! String == "en" { return self.firstQuestionPlaceholderEnglish } else { return self.firstQuestionPlaceholderGerman } } }
gpl-3.0
1a30ef8c05a033d9dcecbb53110b6db1
36.40367
118
0.672799
4.611991
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/Core/HTTP/MMResponses.swift
1
4517
// // MMResponses.swift // MobileMessaging // // Created by Andrey K. on 23/02/16. // // enum MMResult<ValueType> { case Success(ValueType) case Failure(NSError?) case Cancel var value: ValueType? { switch self { case .Success(let value): return value case .Failure, .Cancel: return nil } } var error: NSError? { switch self { case .Success, .Cancel: return nil case .Failure(let error): return error } } } struct EmptyResponse { } struct BaseUrlResponse { let baseUrl: String? } struct GeoEventReportingResponse { let finishedCampaignIds: [String]? let suspendedCampaignIds: [String]? let tempMessageIdRealMessageId: [String: String] } struct LibraryVersionResponse { let platformType : String let libraryVersion : String let updateUrl : String } struct MessagesSyncResponse { let messages: [MM_MTMessage]? } struct MOMessageSendingResponse { let messages: [MM_MOMessage] } //MARK: - Request results typealias MessagesSyncResult = MMResult<MessagesSyncResponse> typealias SeenStatusSendingResult = MMResult<EmptyResponse> typealias UserSessionSendingResult = MMResult<EmptyResponse> typealias CustomEventResult = MMResult<EmptyResponse> typealias DepersonalizeResult = MMResult<EmptyResponse> typealias MOMessageSendingResult = MMResult<MOMessageSendingResponse> typealias LibraryVersionResult = MMResult<LibraryVersionResponse> typealias BaseUrlResult = MMResult<BaseUrlResponse> typealias GeoEventReportingResult = MMResult<GeoEventReportingResponse> typealias FetchUserDataResult = MMResult<MMUser> typealias UpdateUserDataResult = MMResult<EmptyResponse> typealias FetchInstanceDataResult = MMResult<MMInstallation> typealias UpdateInstanceDataResult = MMResult<EmptyResponse> typealias PersonalizeResult = MMResult<MMUser> typealias DeliveryReportResult = MMResult<EmptyResponse> public struct MMRequestError { public let messageId: String public let text: String var foundationError: NSError { var userInfo = [String: Any]() userInfo[NSLocalizedDescriptionKey] = text userInfo[Consts.APIKeys.errorText] = text userInfo[Consts.APIKeys.errorMessageId] = messageId return NSError(domain: Consts.APIKeys.backendErrorDomain, code: Int(messageId) ?? 0, userInfo: userInfo) } } //MARK: - JSON encoding/decoding protocol JSONDecodable { init?(json: JSON) } protocol JSONEncodable { func toJSON() -> JSON } extension EmptyResponse: JSONDecodable { init?(json value: JSON) { } } extension MMRequestError: JSONDecodable { init?(json value: JSON) { let serviceException = value[Consts.APIKeys.requestError][Consts.APIKeys.serviceException] guard let text = serviceException[Consts.APIKeys.errorText].string, let messageId = serviceException[Consts.APIKeys.errorMessageId].string else { return nil } self.messageId = messageId self.text = text } } extension GeoEventReportingResponse: JSONDecodable { init?(json value: JSON) { guard let tempMessageIdRealMessageId = value[Consts.GeoReportingAPIKeys.messageIdsMap].dictionaryObject as? [String: String] else { return nil } self.tempMessageIdRealMessageId = tempMessageIdRealMessageId self.finishedCampaignIds = value[Consts.GeoReportingAPIKeys.finishedCampaignIds].arrayObject as? [String] self.suspendedCampaignIds = value[Consts.GeoReportingAPIKeys.suspendedCampaignIds].arrayObject as? [String] } } extension LibraryVersionResponse: JSONDecodable { init?(json value: JSON) { guard let platformType = value[Consts.VersionCheck.platformType].rawString(), let libraryVersion = value[Consts.VersionCheck.libraryVersion].rawString(), let updateUrl = value[Consts.VersionCheck.libraryVersionUpdateUrl].rawString() else { return nil } self.platformType = platformType self.libraryVersion = libraryVersion self.updateUrl = updateUrl } } extension BaseUrlResponse: JSONDecodable { init?(json value: JSON) { self.baseUrl = value[Consts.BaseUrlRecovery.baseUrl].string } } extension MessagesSyncResponse: JSONDecodable{ init?(json value: JSON) { self.messages = value[Consts.APNSPayloadKeys.payloads].arrayValue.compactMap { MM_MTMessage(messageSyncResponseJson: $0) } } } extension Substring { var isNumber: Bool { return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits) != nil } } extension MOMessageSendingResponse: JSONDecodable { init?(json value: JSON) { self.messages = value[Consts.APIKeys.MO.messages].arrayValue.compactMap({MM_MOMessage.init(moResponseJson: $0)}) } }
apache-2.0
1a530c5bf52e4cbb3bb014468c655e59
26.210843
133
0.774186
3.907439
false
false
false
false
scymen/sockettool
sockettool/sockettool/MySocket.swift
1
8556
// // MySocket.swift // sockettool // // Created by Abu on 16/7/9. // Copyright © 2016年 sockettool. All rights reserved. // import Foundation import SocksCore import Socks class MySocket :NSObject{ var exit:Bool = false var th:Thread? = nil var isWorking:Bool = false var thisSocket:TCPInternetSocket? = nil var socketList:[Descriptor:Connection] = [:] var socketDelegate:SocketDelegate? override init() { } func start2Work() { guard !isWorking else {return} exit = false if Paras.isClientMode { th = Thread(target: self, selector: #selector(MySocket.startClient), object: nil) th!.start() } else { th = Thread(target: self, selector: #selector(MySocket.startServer), object: nil) th!.start() } } func stopWorking(){ exit = true isWorking = false socketDelegate?.setButtonEnable(id: "btnOK", enable: true) if th != nil { th?.cancel() } for (d:s) in socketList { do { try s.value.socket.close() s.value.set(status: .close, bytes: []) NSLog("-> \(s.value)") socketDelegate?.action(conn: s.value) } catch { print("\(error)") } } socketList.removeAll() do { if thisSocket != nil { socketDelegate?.action(conn: Connection(socket: thisSocket!, status: .close, bytes: [])) try thisSocket?.close() } }catch { NSLog("\(error)" ) socketDelegate?.action(msg: "\(error)") } } enum MyError: ErrorProtocol { case descriptorReuse } enum HandleResult { case keepAlive case close } func send(b: [UInt8]){ guard thisSocket != nil else { return } send(descriptor: (thisSocket?.descriptor)!,b: b) } func send(descriptor:[Descriptor],b :[UInt8]) { if descriptor.count <= 0 { return } for i in descriptor { send(descriptor: Descriptor(i),b:b) } } func send(descriptor : Descriptor ,b: [UInt8]){ guard socketList.keys.contains(descriptor) else {return } do { let cnn = socketList[descriptor]! cnn.set(status: .send, bytes: b) NSLog("-> \(cnn)") socketDelegate?.action(conn: cnn) try cnn.socket.send(data: b) }catch { NSLog("error \(error)") socketDelegate?.action(msg:"\(error)" ) } } func handleMessage(client: TCPInternetSocket) throws -> HandleResult { let b = try client.recvAll() guard b.count > 0 else {return .close } let cnn = socketList[client.descriptor]! cnn.set(status: .receive, bytes:b) NSLog("-> \(cnn)") socketDelegate?.action(conn: cnn) return .keepAlive } func closeSocket(descriptor:Descriptor) throws { guard socketList.keys.contains(descriptor) else { return } let cnn = socketList.removeValue(forKey: descriptor) if cnn != nil { try cnn?.socket.close() cnn?.set(status: .close, bytes: []) NSLog("-> \(cnn)") socketDelegate?.action(conn: cnn!) } } func startClient(arg:AnyObject ) { do{ let client = try TCPInternetSocket(address: Paras.addr!) try client.connect(withTimeout: 3) thisSocket = client let c = Connection( socket: client, status:.connecting,bytes: []) socketList[client.descriptor] = c NSLog("--> \(c) OK ") isWorking = true socketDelegate?.action(conn: c) socketDelegate?.setButtonEnable(id: "btnOK", enable: false) let time = timeval(tv_sec: 0, tv_usec: 500) while !exit { let flag = try client.waitForReadableData(timeout: time) //print("client loop have readable bytes \(flag) client close =\(client.closed)") if flag { let b = try client.recvAll() if b.count <= 0 { // it seems that socket is closed stopWorking() exit = true } else { c.set(status: .receive, bytes:b) NSLog("<-- \(c)") socketDelegate?.action(conn: c) } } } }catch { exit = true NSLog("\(error)") socketDelegate?.action(msg: "\(error)") socketDelegate?.setButtonEnable(id: "btnOK", enable: true) } } func startServer(arg: AnyObject){ do { let address = Paras.addr! let server = try TCPInternetSocket(address: address) thisSocket = server NSLog("Start \(Paras.isClientMode ? "client":"server" ) mode") if Paras.isClientMode { try server.connect(withTimeout: 3) let c = Connection( socket: server, status:.connecting,bytes: []) socketList[server.descriptor] = c socketDelegate?.action(conn: Connection(socket: server, status: .connecting, bytes: [])) NSLog("Socket(\(server.descriptor)) connect to \( server.address ) ") } else { try server.bind() try server.listen() socketDelegate?.action(conn: Connection(socket: server, status: .startListening, bytes: [])) NSLog("Socket(\(server.descriptor)) listening on \( server.address ) ") } socketDelegate?.setButtonEnable(id: "btnOK", enable: false) isWorking = true while true { guard !exit else { break } //Wait for data on either the server socket and connected clients let watchedReads = Array(socketList.keys) + [server.descriptor] let (reads, writes, errors) = try select(reads: watchedReads, errors: watchedReads ) //first handle any existing connections try reads.filter { $0 != server.descriptor }.forEach { let client = socketList[$0]! do { let result = try handleMessage(client: client.socket) switch result { case .close: try closeSocket(descriptor: client.descriptor) case .keepAlive: break } } catch { print("Error: \(error)") try closeSocket(descriptor: client.descriptor) } } //then only continue if there's data on the server listening socket guard Set(reads).contains(server.descriptor) else { continue } let socket = try server.accept() socket.keepAlive = true guard socketList[socket.descriptor] == nil else { throw MyError.descriptorReuse } let c = Connection( socket: socket, status: .new,bytes: []) socketList[socket.descriptor] = c NSLog("--> \(c)") socketDelegate?.action(conn: c) NSLog("total connection = \(socketList.count) ") //try socket.send(data: "hello".toBytes() ) } NSLog("loop break, try to close server sockets") try server.close() } catch { exit = true socketDelegate?.setButtonEnable(id: "btnOK", enable: true) print("catch Error \(error) <-----") } NSLog(" end of method") } }
lgpl-3.0
72b7b0911f114fa2f59bf4fb5e90895d
30.677778
108
0.475272
5.022314
false
false
false
false
mahjouri/pokedex
pokedex-by-saamahn/Pokemon.swift
1
6923
// // Pokemon.swift // pokedex-by-saamahn // // Created by Saamahn Mahjouri on 3/6/16. // Copyright © 2016 Saamahn Mahjouri. All rights reserved. // import Foundation import Alamofire class Pokemon { private var _name: String! private var _pokedexId: Int! private var _description: String! private var _type: String! private var _defense: String! private var _weight: String! private var _height: String! private var _attack: String! private var _nextEvolutionTxt: String! private var _nextEvolutionId: String! private var _nextEvolutionLvl: String! private var _pokemonUrl: String! var nextEvolutionLvl: String { get { if _nextEvolutionLvl == nil { _nextEvolutionLvl = "" } return _nextEvolutionLvl } } var nextEvolutionTxt: String { if _nextEvolutionTxt == nil { _nextEvolutionTxt = "" } return _nextEvolutionTxt } var nextEvolutionId: String { if _nextEvolutionId == nil { _nextEvolutionId = "" } return _nextEvolutionId } var description: String { if _description == nil { _description = "" } return _description } var type: String { if _type == nil { _type = "" } return _type } var defense: String { if _defense == nil { _defense = "" } return _defense } var weight: String { if _weight == nil { _weight = "" } return _weight } var height: String { if _height == nil { _height = "" } return _height } var attack: String { if _attack == nil { _attack = "" } return _attack } var name: String { return _name } var pokedexId: Int { return _pokedexId } init(name: String, pokedexId: Int) { self._name = name self._pokedexId = pokedexId _pokemonUrl = "\(URL_BASE)\(URL_POKEMON)\(self._pokedexId)/" } func downloadPokemonDetails(completed: DownloadComplete) { let url = NSURL(string: _pokemonUrl)! Alamofire.request(.GET, url).responseJSON { (request: NSURLRequest?, response: NSHTTPURLResponse?, result: Result<AnyObject>) -> Void in if let dict = result.value as? Dictionary<String, AnyObject> { if let weight = dict["weight"] as? String { self._weight = weight } if let height = dict["height"] as? String { self._height = height } if let attack = dict["attack"] as? Int { self._attack = "\(attack)" } if let defense = dict["defense"] as? Int { self._defense = "\(defense)" } print(self._weight) print(self._height) print(self._attack) print(self._defense) if let types = dict["types"] as? [Dictionary<String, String>] where types.count > 0 { if let name = types[0]["name"] { self._type = name.capitalizedString } if types.count > 1 { for var x = 1; x < types.count; x++ { if let name = types[x]["name"] { self._type! += "/\(name.capitalizedString)" } } } } else { self._type = "" } print(self._type) if let descArr = dict["descriptions"] as? [Dictionary<String, String>] where descArr.count > 0 { if let url = descArr[0]["resource_uri"] { let nsurl = NSURL(string: "\(URL_BASE)\(url)")! Alamofire.request(.GET, nsurl).responseJSON { (request: NSURLRequest?, response: NSHTTPURLResponse?, result: Result<AnyObject>) -> Void in if let descDict = result.value as? Dictionary<String, AnyObject> { if let description = descDict["description"] as? String { self._description = description print(self._description) } } completed() } } } else { self._description = "" } if let evolutions = dict["evolutions"] as? [Dictionary<String, AnyObject>] where evolutions.count > 0 { if let to = evolutions[0]["to"] as? String { // Can't support mega pokemon right now but // api still has mega data if to.rangeOfString("mega") == nil { if let uri = evolutions[0]["resource_uri"] as? String { let newStr = uri.stringByReplacingOccurrencesOfString("/api/v1/pokemon/", withString: "") let num = newStr.stringByReplacingOccurrencesOfString("/", withString: "") self._nextEvolutionId = num self._nextEvolutionTxt = to if let lvl = evolutions[0]["level"] as? Int { self._nextEvolutionLvl = "\(lvl)" } // print(self._nextEvolutionId) // print(self._nextEvolutionTxt) // print(self._nextEvolutionLvl) } } } } } } } }
bsd-3-clause
9587624e206f9cec21b5190aca390386
30.611872
162
0.39425
5.802179
false
false
false
false
prosperence/prosperence-ios
Prosperance/Prosperance/WebServices.swift
1
2226
import Foundation func getSessionId(profile: Profile) -> (success: String, error: String) { // Get host from environment variables let dict = NSProcessInfo.processInfo().environment let host = dict["HOST"] as? String ///////////////////////////// // Build http post request // ///////////////////////////// var url = host! + "/auth/local" let jsonString = "{\"email\": \"\( profile.username )\", \"password\": \"\( profile.password)\"}" var request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) if let responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:nil) as NSData! { if let responseDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData,options: NSJSONReadingOptions.MutableContainers, error:nil) as? NSDictionary { if let token: String? = responseDict.valueForKey("token") as? String { return(token!, "") } else { /////////////////////////////////////////////////////////////////// // Application / Auth error - did not receive a proper UUID back // /////////////////////////////////////////////////////////////////// return("", "Did not receive a proper token back") } } else { //////////////////////////////////////////////////////// // System error - did not receive valid json response // //////////////////////////////////////////////////////// return("", "Did not receive a valid json response") } } else { ///////////////////////////////////////////////////////////////////// // Local connection issue - could not get ahold of the outside URL // ///////////////////////////////////////////////////////////////////// return("", "Could not get ahold of the outside URL") } }
mit
0e11c0a730d4ae0e1418cd97790db9f1
41.826923
172
0.466757
6.235294
false
false
false
false
Antuaaan/ECWeather
ECWeather/Pods/Spring/Spring/Spring.swift
2
23925
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // 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 @objc public protocol Springable { var autostart: Bool { get set } var autohide: Bool { get set } var animation: String { get set } var force: CGFloat { get set } var delay: CGFloat { get set } var duration: CGFloat { get set } var damping: CGFloat { get set } var velocity: CGFloat { get set } var repeatCount: Float { get set } var x: CGFloat { get set } var y: CGFloat { get set } var scaleX: CGFloat { get set } var scaleY: CGFloat { get set } var rotate: CGFloat { get set } var opacity: CGFloat { get set } var animateFrom: Bool { get set } var curve: String { get set } // UIView var layer : CALayer { get } var transform : CGAffineTransform { get set } var alpha : CGFloat { get set } func animate() func animateNext(completion: @escaping () -> ()) func animateTo() func animateToNext(completion: @escaping () -> ()) } public class Spring : NSObject { private unowned var view : Springable private var shouldAnimateAfterActive = false private var shouldAnimateInLayoutSubviews = true init(_ view: Springable) { self.view = view super.init() commonInit() } func commonInit() { NotificationCenter.default.addObserver(self, selector: #selector(Spring.didBecomeActiveNotification(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } func didBecomeActiveNotification(_ notification: NSNotification) { if shouldAnimateAfterActive { alpha = 0 animate() shouldAnimateAfterActive = false } } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } private var autostart: Bool { set { self.view.autostart = newValue } get { return self.view.autostart }} private var autohide: Bool { set { self.view.autohide = newValue } get { return self.view.autohide }} private var animation: String { set { self.view.animation = newValue } get { return self.view.animation }} private var force: CGFloat { set { self.view.force = newValue } get { return self.view.force }} private var delay: CGFloat { set { self.view.delay = newValue } get { return self.view.delay }} private var duration: CGFloat { set { self.view.duration = newValue } get { return self.view.duration }} private var damping: CGFloat { set { self.view.damping = newValue } get { return self.view.damping }} private var velocity: CGFloat { set { self.view.velocity = newValue } get { return self.view.velocity }} private var repeatCount: Float { set { self.view.repeatCount = newValue } get { return self.view.repeatCount }} private var x: CGFloat { set { self.view.x = newValue } get { return self.view.x }} private var y: CGFloat { set { self.view.y = newValue } get { return self.view.y }} private var scaleX: CGFloat { set { self.view.scaleX = newValue } get { return self.view.scaleX }} private var scaleY: CGFloat { set { self.view.scaleY = newValue } get { return self.view.scaleY }} private var rotate: CGFloat { set { self.view.rotate = newValue } get { return self.view.rotate }} private var opacity: CGFloat { set { self.view.opacity = newValue } get { return self.view.opacity }} private var animateFrom: Bool { set { self.view.animateFrom = newValue } get { return self.view.animateFrom }} private var curve: String { set { self.view.curve = newValue } get { return self.view.curve }} // UIView private var layer : CALayer { return view.layer } private var transform : CGAffineTransform { get { return view.transform } set { view.transform = newValue }} private var alpha: CGFloat { get { return view.alpha } set { view.alpha = newValue } } public enum AnimationPreset: String { case SlideLeft = "slideLeft" case SlideRight = "slideRight" case SlideDown = "slideDown" case SlideUp = "slideUp" case SqueezeLeft = "squeezeLeft" case SqueezeRight = "squeezeRight" case SqueezeDown = "squeezeDown" case SqueezeUp = "squeezeUp" case FadeIn = "fadeIn" case FadeOut = "fadeOut" case FadeOutIn = "fadeOutIn" case FadeInLeft = "fadeInLeft" case FadeInRight = "fadeInRight" case FadeInDown = "fadeInDown" case FadeInUp = "fadeInUp" case ZoomIn = "zoomIn" case ZoomOut = "zoomOut" case Fall = "fall" case Shake = "shake" case Pop = "pop" case FlipX = "flipX" case FlipY = "flipY" case Morph = "morph" case Squeeze = "squeeze" case Flash = "flash" case Wobble = "wobble" case Swing = "swing" } public enum AnimationCurve: String { case EaseIn = "easeIn" case EaseOut = "easeOut" case EaseInOut = "easeInOut" case Linear = "linear" case Spring = "spring" case EaseInSine = "easeInSine" case EaseOutSine = "easeOutSine" case EaseInOutSine = "easeInOutSine" case EaseInQuad = "easeInQuad" case EaseOutQuad = "easeOutQuad" case EaseInOutQuad = "easeInOutQuad" case EaseInCubic = "easeInCubic" case EaseOutCubic = "easeOutCubic" case EaseInOutCubic = "easeInOutCubic" case EaseInQuart = "easeInQuart" case EaseOutQuart = "easeOutQuart" case EaseInOutQuart = "easeInOutQuart" case EaseInQuint = "easeInQuint" case EaseOutQuint = "easeOutQuint" case EaseInOutQuint = "easeInOutQuint" case EaseInExpo = "easeInExpo" case EaseOutExpo = "easeOutExpo" case EaseInOutExpo = "easeInOutExpo" case EaseInCirc = "easeInCirc" case EaseOutCirc = "easeOutCirc" case EaseInOutCirc = "easeInOutCirc" case EaseInBack = "easeInBack" case EaseOutBack = "easeOutBack" case EaseInOutBack = "easeInOutBack" } func animatePreset() { alpha = 0.99 if let animation = AnimationPreset(rawValue: animation) { switch animation { case .SlideLeft: x = 300*force case .SlideRight: x = -300*force case .SlideDown: y = -300*force case .SlideUp: y = 300*force case .SqueezeLeft: x = 300 scaleX = 3*force case .SqueezeRight: x = -300 scaleX = 3*force case .SqueezeDown: y = -300 scaleY = 3*force case .SqueezeUp: y = 300 scaleY = 3*force case .FadeIn: opacity = 0 case .FadeOut: animateFrom = false opacity = 0 case .FadeOutIn: let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.timingFunction = getTimingFunction(curve: curve) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.autoreverses = true layer.add(animation, forKey: "fade") case .FadeInLeft: opacity = 0 x = 300*force case .FadeInRight: x = -300*force opacity = 0 case .FadeInDown: y = -300*force opacity = 0 case .FadeInUp: y = 300*force opacity = 0 case .ZoomIn: opacity = 0 scaleX = 2*force scaleY = 2*force case .ZoomOut: animateFrom = false opacity = 0 scaleX = 2*force scaleY = 2*force case .Fall: animateFrom = false rotate = 15 * CGFloat(CGFloat.pi/180) y = 600*force case .Shake: let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 30*force, -30*force, 30*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve: curve) animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "shake") case .Pop: let animation = CAKeyframeAnimation() animation.keyPath = "transform.scale" animation.values = [0, 0.2*force, -0.2*force, 0.2*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve: curve) animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "pop") case .FlipX: rotate = 0 scaleX = 1 scaleY = 1 var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(caTransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(caTransform3D: CATransform3DConcat(perspective, CATransform3DMakeRotation(CGFloat.pi, 0, 1, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve: curve) layer.add(animation, forKey: "3d") case .FlipY: var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(caTransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(caTransform3D: CATransform3DConcat(perspective,CATransform3DMakeRotation(CGFloat.pi, 1, 0, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve: curve) layer.add(animation, forKey: "3d") case .Morph: let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.3*force, 0.7, 1.3*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve: curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.7, 1.3*force, 0.7, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve: curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphY, forKey: "morphY") case .Squeeze: let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.5*force, 0.5, 1.5*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve: curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.5, 1, 0.5, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve: curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphY, forKey: "morphY") case .Flash: let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.duration = CFTimeInterval(duration) animation.repeatCount = repeatCount * 2.0 animation.autoreverses = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "flash") case .Wobble: let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "wobble") let x = CAKeyframeAnimation() x.keyPath = "position.x" x.values = [0, 30*force, -30*force, 30*force, 0] x.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] x.timingFunction = getTimingFunction(curve: curve) x.duration = CFTimeInterval(duration) x.isAdditive = true x.repeatCount = repeatCount x.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(x, forKey: "x") case .Swing: let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "swing") } } } func getTimingFunction(curve: String) -> CAMediaTimingFunction { if let curve = AnimationCurve(rawValue: curve) { switch curve { case .EaseIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case .EaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case .EaseInOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) case .Linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case .Spring: return CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1) case .EaseInSine: return CAMediaTimingFunction(controlPoints: 0.47, 0, 0.745, 0.715) case .EaseOutSine: return CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1) case .EaseInOutSine: return CAMediaTimingFunction(controlPoints: 0.445, 0.05, 0.55, 0.95) case .EaseInQuad: return CAMediaTimingFunction(controlPoints: 0.55, 0.085, 0.68, 0.53) case .EaseOutQuad: return CAMediaTimingFunction(controlPoints: 0.25, 0.46, 0.45, 0.94) case .EaseInOutQuad: return CAMediaTimingFunction(controlPoints: 0.455, 0.03, 0.515, 0.955) case .EaseInCubic: return CAMediaTimingFunction(controlPoints: 0.55, 0.055, 0.675, 0.19) case .EaseOutCubic: return CAMediaTimingFunction(controlPoints: 0.215, 0.61, 0.355, 1) case .EaseInOutCubic: return CAMediaTimingFunction(controlPoints: 0.645, 0.045, 0.355, 1) case .EaseInQuart: return CAMediaTimingFunction(controlPoints: 0.895, 0.03, 0.685, 0.22) case .EaseOutQuart: return CAMediaTimingFunction(controlPoints: 0.165, 0.84, 0.44, 1) case .EaseInOutQuart: return CAMediaTimingFunction(controlPoints: 0.77, 0, 0.175, 1) case .EaseInQuint: return CAMediaTimingFunction(controlPoints: 0.755, 0.05, 0.855, 0.06) case .EaseOutQuint: return CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1) case .EaseInOutQuint: return CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1) case .EaseInExpo: return CAMediaTimingFunction(controlPoints: 0.95, 0.05, 0.795, 0.035) case .EaseOutExpo: return CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1) case .EaseInOutExpo: return CAMediaTimingFunction(controlPoints: 1, 0, 0, 1) case .EaseInCirc: return CAMediaTimingFunction(controlPoints: 0.6, 0.04, 0.98, 0.335) case .EaseOutCirc: return CAMediaTimingFunction(controlPoints: 0.075, 0.82, 0.165, 1) case .EaseInOutCirc: return CAMediaTimingFunction(controlPoints: 0.785, 0.135, 0.15, 0.86) case .EaseInBack: return CAMediaTimingFunction(controlPoints: 0.6, -0.28, 0.735, 0.045) case .EaseOutBack: return CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.275) case .EaseInOutBack: return CAMediaTimingFunction(controlPoints: 0.68, -0.55, 0.265, 1.55) } } return CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) } func getAnimationOptions(curve: String) -> UIViewAnimationOptions { if let curve = AnimationCurve(rawValue: curve) { switch curve { case .EaseIn: return UIViewAnimationOptions.curveEaseIn case .EaseOut: return UIViewAnimationOptions.curveEaseOut case .EaseInOut: return UIViewAnimationOptions() default: break } } return UIViewAnimationOptions.curveLinear } public func animate() { animateFrom = true animatePreset() setView {} } public func animateNext(completion: @escaping () -> ()) { animateFrom = true animatePreset() setView { completion() } } public func animateTo() { animateFrom = false animatePreset() setView {} } public func animateToNext(completion: @escaping () -> ()) { animateFrom = false animatePreset() setView { completion() } } public func customAwakeFromNib() { if autohide { alpha = 0 } } public func customLayoutSubviews() { if shouldAnimateInLayoutSubviews { shouldAnimateInLayoutSubviews = false if autostart { if UIApplication.shared.applicationState != .active { shouldAnimateAfterActive = true return } alpha = 0 animate() } } } func setView(completion: @escaping () -> ()) { if animateFrom { let translate = CGAffineTransform(translationX: self.x, y: self.y) let scale = CGAffineTransform(scaleX: self.scaleX, y: self.scaleY) let rotate = CGAffineTransform(rotationAngle: self.rotate) let translateAndScale = translate.concatenating(scale) self.transform = rotate.concatenating(translateAndScale) self.alpha = self.opacity } UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [getAnimationOptions(curve: curve), UIViewAnimationOptions.allowUserInteraction], animations: { [weak self] in if let _self = self { if _self.animateFrom { _self.transform = CGAffineTransform.identity _self.alpha = 1 } else { let translate = CGAffineTransform(translationX: _self.x, y: _self.y) let scale = CGAffineTransform(scaleX: _self.scaleX, y: _self.scaleY) let rotate = CGAffineTransform(rotationAngle: _self.rotate) let translateAndScale = translate.concatenating(scale) _self.transform = rotate.concatenating(translateAndScale) _self.alpha = _self.opacity } } }, completion: { [weak self] finished in completion() self?.resetAll() }) } func reset() { x = 0 y = 0 opacity = 1 } func resetAll() { x = 0 y = 0 animation = "" opacity = 1 scaleX = 1 scaleY = 1 rotate = 0 damping = 0.7 velocity = 0.7 repeatCount = 1 delay = 0 duration = 0.7 } }
mit
c496db8e5d0432b611e69a514b9aeb28
44.226843
182
0.572497
4.908699
false
false
false
false
eeschimosu/SwiftPages
Pod/Classes/SwiftPages.swift
2
12033
// // SwiftPages.swift // SwiftPages // // Created by Gabriel Alvarado on 6/27/15. // Copyright (c) 2015 Gabriel Alvarado. All rights reserved. // import UIKit class SwiftPages: UIView, UIScrollViewDelegate { //Items variables private var containerView: UIView! private var scrollView: UIScrollView! private var topBar: UIView! private var animatedBar: UIView! private var viewControllerIDs: [String] = [] private var buttonTitles: [String] = [] private var buttonImages: [UIImage] = [] private var pageViews: [UIViewController?] = [] //Container view position variables private var xOrigin: CGFloat = 0 private var yOrigin: CGFloat = 64 private var distanceToBottom: CGFloat = 0 //Color variables private var animatedBarColor = UIColor(red: 28/255, green: 95/255, blue: 185/255, alpha: 1) private var topBarBackground = UIColor.whiteColor() private var buttonsTextColor = UIColor.grayColor() private var containerViewBackground = UIColor.whiteColor() //Item size variables private var topBarHeight: CGFloat = 52 private var animatedBarHeight: CGFloat = 3 //Bar item variables private var aeroEffectInTopBar: Bool = false //This gives the top bap a blurred effect, also overlayes the it over the VC's private var buttonsWithImages: Bool = false private var barShadow: Bool = true private var buttonsTextFontAndSize: UIFont = UIFont(name: "HelveticaNeue-Light", size: 20)! // MARK: - Positions Of The Container View API - func setOriginX (origin : CGFloat) { xOrigin = origin } func setOriginY (origin : CGFloat) { yOrigin = origin } func setDistanceToBottom (distance : CGFloat) { distanceToBottom = distance } // MARK: - API's - func setAnimatedBarColor (color : UIColor) { animatedBarColor = color } func setTopBarBackground (color : UIColor) { topBarBackground = color } func setButtonsTextColor (color : UIColor) { buttonsTextColor = color } func setContainerViewBackground (color : UIColor) { containerViewBackground = color } func setTopBarHeight (pointSize : CGFloat) { topBarHeight = pointSize} func setAnimatedBarHeight (pointSize : CGFloat) { animatedBarHeight = pointSize} func setButtonsTextFontAndSize (fontAndSize : UIFont) { buttonsTextFontAndSize = fontAndSize} func enableAeroEffectInTopBar (boolValue : Bool) { aeroEffectInTopBar = boolValue} func enableButtonsWithImages (boolValue : Bool) { buttonsWithImages = boolValue} func enableBarShadow (boolValue : Bool) { barShadow = boolValue} override func drawRect(rect: CGRect) { // MARK: - Size Of The Container View - var pagesContainerHeight = self.frame.height - yOrigin - distanceToBottom var pagesContainerWidth = self.frame.width //Set the containerView, every item is constructed relative to this view containerView = UIView(frame: CGRectMake(xOrigin, yOrigin, pagesContainerWidth, pagesContainerHeight)) containerView.backgroundColor = containerViewBackground self.addSubview(containerView) //Set the scrollview if (aeroEffectInTopBar) { scrollView = UIScrollView(frame: CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height)) } else { scrollView = UIScrollView(frame: CGRectMake(0, topBarHeight, containerView.frame.size.width, containerView.frame.size.height - topBarHeight)) } scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.delegate = self scrollView.backgroundColor = UIColor.clearColor() containerView.addSubview(scrollView) //Set the top bar topBar = UIView(frame: CGRectMake(0, 0, containerView.frame.size.width, topBarHeight)) topBar.backgroundColor = topBarBackground if (aeroEffectInTopBar) { //Create the blurred visual effect //You can choose between ExtraLight, Light and Dark topBar.backgroundColor = UIColor.clearColor() let blurEffect: UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = topBar.bounds blurView.setTranslatesAutoresizingMaskIntoConstraints(false) topBar.addSubview(blurView) } containerView.addSubview(topBar) //Set the top bar buttons var buttonsXPosition: CGFloat = 0 var buttonNumber = 0 //Check to see if the top bar will be created with images ot text if (!buttonsWithImages) { for item in buttonTitles { var barButton: UIButton! barButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, containerView.frame.size.width/(CGFloat)(viewControllerIDs.count), topBarHeight)) barButton.backgroundColor = UIColor.clearColor() barButton.titleLabel!.font = buttonsTextFontAndSize barButton.setTitle(buttonTitles[buttonNumber], forState: UIControlState.Normal) barButton.setTitleColor(buttonsTextColor, forState: UIControlState.Normal) barButton.tag = buttonNumber barButton.addTarget(self, action: "barButtonAction:", forControlEvents: UIControlEvents.TouchUpInside) topBar.addSubview(barButton) buttonsXPosition = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count) + buttonsXPosition buttonNumber++ } } else { for item in buttonImages { var barButton: UIButton! barButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, containerView.frame.size.width/(CGFloat)(viewControllerIDs.count), topBarHeight)) barButton.backgroundColor = UIColor.clearColor() barButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit barButton.setImage(item, forState: .Normal) barButton.tag = buttonNumber barButton.addTarget(self, action: "barButtonAction:", forControlEvents: UIControlEvents.TouchUpInside) topBar.addSubview(barButton) buttonsXPosition = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count) + buttonsXPosition buttonNumber++ } } //Set up the animated UIView animatedBar = UIView(frame: CGRectMake(0, topBarHeight - animatedBarHeight + 1, (containerView.frame.size.width/(CGFloat)(viewControllerIDs.count))*0.8, animatedBarHeight)) animatedBar.center.x = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count * 2) animatedBar.backgroundColor = animatedBarColor containerView.addSubview(animatedBar) //Add the bar shadow (set to true or false with the barShadow var) if (barShadow) { var shadowView = UIView(frame: CGRectMake(0, topBarHeight, containerView.frame.size.width, 4)) var gradient: CAGradientLayer = CAGradientLayer() gradient.frame = shadowView.bounds gradient.colors = [UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 0.28).CGColor, UIColor.clearColor().CGColor] shadowView.layer.insertSublayer(gradient, atIndex: 0) containerView.addSubview(shadowView) } let pageCount = viewControllerIDs.count //Fill the array containing the VC instances with nil objects as placeholders for _ in 0..<pageCount { pageViews.append(nil) } //Defining the content size of the scrollview let pagesScrollViewSize = scrollView.frame.size scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageCount), height: pagesScrollViewSize.height) //Load the pages to show initially loadVisiblePages() } // MARK: - Initialization Functions - func initializeWithVCIDsArrayAndButtonTitlesArray (VCIDsArray: [String], buttonTitlesArray: [String]) { //Important - Titles Array must Have The Same Number Of Items As The viewControllerIDs Array if VCIDsArray.count == buttonTitlesArray.count { viewControllerIDs = VCIDsArray buttonTitles = buttonTitlesArray buttonsWithImages = false } else { println("Initilization failed, the VC ID array count does not match the button titles array count.") } } func initializeWithVCIDsArrayAndButtonImagesArray (VCIDsArray: [String], buttonImagesArray: [UIImage]) { //Important - Images Array must Have The Same Number Of Items As The viewControllerIDs Array if VCIDsArray.count == buttonImagesArray.count { viewControllerIDs = VCIDsArray buttonImages = buttonImagesArray buttonsWithImages = true } else { println("Initilization failed, the VC ID array count does not match the button images array count.") } } func loadPage(page: Int) { if page < 0 || page >= viewControllerIDs.count { // If it's outside the range of what you have to display, then do nothing return } //Use optional binding to check if the view has already been loaded if let pageView = pageViews[page] { // Do nothing. The view is already loaded. } else { println("Loading Page \(page)") //The pageView instance is nil, create the page var frame = scrollView.bounds frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0.0 //Create the variable that will hold the VC being load var newPageView: UIViewController //Look for the VC by its identifier in the storyboard and add it to the scrollview newPageView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(viewControllerIDs[page]) as! UIViewController newPageView.view.frame = frame scrollView.addSubview(newPageView.view) //Replace the nil in the pageViews array with the VC just created pageViews[page] = newPageView } } func loadVisiblePages() { // First, determine which page is currently visible let pageWidth = scrollView.frame.size.width let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) // Work out which pages you want to load let firstPage = page - 1 let lastPage = page + 1 // Load pages in our range for index in firstPage...lastPage { loadPage(index) } } func barButtonAction(sender: UIButton?) { var index: Int = sender!.tag let pagesScrollViewSize = scrollView.frame.size [scrollView .setContentOffset(CGPointMake(pagesScrollViewSize.width * (CGFloat)(index), 0), animated: true)] } func scrollViewDidScroll(scrollView: UIScrollView) { // Load the pages that are now on screen loadVisiblePages() //The calculations for the animated bar's movements //The offset addition is based on the width of the animated bar (button width times 0.8) var offsetAddition = (containerView.frame.size.width/(CGFloat)(viewControllerIDs.count))*0.1 animatedBar.frame = CGRectMake((offsetAddition + (scrollView.contentOffset.x/(CGFloat)(viewControllerIDs.count))), animatedBar.frame.origin.y, animatedBar.frame.size.width, animatedBar.frame.size.height); } }
mit
366ff8f605c4f664a7067bdd85d9934c
45.46332
212
0.659021
5.162162
false
false
false
false
cpimhoff/AntlerKit
Framework/AntlerKit/Animation/Animator.swift
1
4416
// // Animator.swift // AntlerKit // // Created by Charlie Imhoff on 1/23/17. // import Foundation import SpriteKit /// An `Animator` is a special object which can be attached to a `GameObject.animator` /// property to enable frame based animation. open class Animator { internal weak var gameObject : GameObject? public let sheetName : String /// cache for animations private var animations = [String: Animation]() public init(sheetName: String) { self.sheetName = sheetName } convenience public init(sheetName: String, cacheImmediately: [String]? = nil) { self.init(sheetName: sheetName) if cacheImmediately != nil { self.cache(animationsNamed: cacheImmediately!) } } } // MARK: - Running animations extension Animator { private var loopingAnimationKey : String { return "AK- Looping Animation" } private var singleAnimationKey : String { return "AK- Single Animation" } /// Runs the animation at the specified rate. /// When the animation ends, return to the previous looping animation (if there was one). /// /// - Parameters: /// - animationName: Animation to run /// - fps: The amount of frames to play each second open func runOnce(animation: Animation, fps: Double) { guard let primitive = self.gameObject?.primitive else { return } // save (and then stop) current looping animation let previousAnimation = primitive.action(forKey: loopingAnimationKey) primitive.removeAction(forKey: loopingAnimationKey) // construct one-off action let frameTime : TimeInterval = 1.0 / fps let singleAnimation = SKAction.animate(with: animation.frames, timePerFrame: frameTime) let returnToPreviousAnimation = SKAction.run { if previousAnimation != nil { primitive.run(previousAnimation!, withKey: self.loopingAnimationKey) } } let sequence = SKAction.sequence([singleAnimation, returnToPreviousAnimation]) primitive.run(sequence, withKey: self.singleAnimationKey) } /// Runs the animation on the reciever's sheet, at the specified rate. /// When the animation ends, return to the previous looping animation (if there was one). /// /// - Parameters: /// - animationName: Name of the animation on the reciever's sheet to run /// - fps: The amount of frames to play each second open func runOnce(animationNamed animationName: String, fps: Double) { guard let animation = self.load(animationNamed: animationName) else { return } self.runOnce(animation: animation, fps: fps) } /// Loops the animation at the specified rate. /// /// - Parameters: /// - animation: Animation to run /// - fps: The amount of frames to play each second open func transition(to animation: Animation, fps: Double) { guard let primitive = self.gameObject?.primitive else { return } // cancel a midflight one-off immediately (its `previousAnimation` would be out of date) primitive.removeAction(forKey: singleAnimationKey) // construct a looping action let frameTime : TimeInterval = 1.0 / fps let singleAnimation = SKAction.animate(with: animation.frames, timePerFrame: frameTime) let loopingAnimation = SKAction.repeatForever(singleAnimation) primitive.run(loopingAnimation, withKey: loopingAnimationKey) } /// Loops the animation on the reciever's sheet, at the specified rate. /// /// - Parameters: /// - animationName: Name of the animation on the reciever's sheet to run /// - fps: The amount of frames to play each second open func transition(toAnimationNamed animationName: String, fps: Double) { guard let animation = self.load(animationNamed: animationName) else { return } self.transition(to: animation, fps: fps) } } // MARK: - Loading animations extension Animator { /// Loads all the specified animations on the reciever's sheet to memory, /// accelerating access to them later. /// /// - Parameter animationNames: names of animations to load open func cache(animationsNamed animationNames: [String]) { for animation in animationNames { self.load(animationNamed: animation) } } @discardableResult private func load(animationNamed animationName: String) -> Animation? { if let fromCache = self.animations[animationName] { return fromCache } guard let animation = Animation(sheetName: self.sheetName, animationName: animationName) else { return nil } self.animations[animationName] = animation return animation } }
mit
7ea2bc82dee98ee9324ec26210c641e7
30.319149
90
0.726902
3.960538
false
false
false
false
davejlin/treehouse
swift/swift2/fotofun/Pods/ReactiveCocoa/ReactiveCocoa/Swift/DynamicProperty.swift
21
3123
import Foundation import enum Result.NoError /// Wraps a `dynamic` property, or one defined in Objective-C, using Key-Value /// Coding and Key-Value Observing. /// /// Use this class only as a last resort! `MutableProperty` is generally better /// unless KVC/KVO is required by the API you're using (for example, /// `NSOperation`). @objc public final class DynamicProperty: RACDynamicPropertySuperclass, MutablePropertyType { public typealias Value = AnyObject? private weak var object: NSObject? private let keyPath: String private var property: MutableProperty<AnyObject?>? /// The current value of the property, as read and written using Key-Value /// Coding. public var value: AnyObject? { @objc(rac_value) get { return object?.valueForKeyPath(keyPath) } @objc(setRac_value:) set(newValue) { object?.setValue(newValue, forKeyPath: keyPath) } } /// A producer that will create a Key-Value Observer for the given object, /// send its initial value then all changes over time, and then complete /// when the observed object has deallocated. /// /// By definition, this only works if the object given to init() is /// KVO-compliant. Most UI controls are not! public var producer: SignalProducer<AnyObject?, NoError> { return property?.producer ?? .empty } public var signal: Signal<AnyObject?, NoError> { return property?.signal ?? .empty } /// Initializes a property that will observe and set the given key path of /// the given object. `object` must support weak references! public init(object: NSObject?, keyPath: String) { self.object = object self.keyPath = keyPath self.property = MutableProperty(nil) /// DynamicProperty stay alive as long as object is alive. /// This is made possible by strong reference cycles. super.init() object?.rac_valuesForKeyPath(keyPath, observer: nil)? .toSignalProducer() .start { event in switch event { case let .Next(newValue): self.property?.value = newValue case let .Failed(error): fatalError("Received unexpected error from KVO signal: \(error)") case .Interrupted, .Completed: self.property = nil } } } } // MARK: Operators /// Binds a signal to a `DynamicProperty`, automatically bridging values to Objective-C. public func <~ <S: SignalType where S.Value: _ObjectiveCBridgeable, S.Error == NoError>(property: DynamicProperty, signal: S) -> Disposable { return property <~ signal.map { $0._bridgeToObjectiveC() } } /// Binds a signal producer to a `DynamicProperty`, automatically bridging values to Objective-C. public func <~ <S: SignalProducerType where S.Value: _ObjectiveCBridgeable, S.Error == NoError>(property: DynamicProperty, producer: S) -> Disposable { return property <~ producer.map { $0._bridgeToObjectiveC() } } /// Binds `destinationProperty` to the latest values of `sourceProperty`, automatically bridging values to Objective-C. public func <~ <Source: PropertyType where Source.Value: _ObjectiveCBridgeable>(destinationProperty: DynamicProperty, sourceProperty: Source) -> Disposable { return destinationProperty <~ sourceProperty.producer }
unlicense
c63fe5e3e02f839706aee5569c3b7a57
35.741176
157
0.731028
4.125495
false
false
false
false
cocoaheadsru/server
Sources/App/Models/EventReg/EventReg.swift
1
1700
import Vapor import FluentProvider // sourcery: AutoModelGeneratable // sourcery: toJSON, Preparation, Updateable, ResponseRepresentable final class EventReg: Model { let storage = Storage() var regFormId: Identifier var userId: Identifier // sourcery: enum, waiting, rejected, approved, canceled, skipped var status: RegistrationStatus = .waiting init(regFormId: Identifier, userId: Identifier, status: RegistrationStatus = .waiting) { self.regFormId = regFormId self.userId = userId self.status = status } // sourcery:inline:auto:EventReg.AutoModelGeneratable init(row: Row) throws { regFormId = try row.get(Keys.regFormId) userId = try row.get(Keys.userId) status = RegistrationStatus(try row.get(Keys.status)) } func makeRow() throws -> Row { var row = Row() try row.set(Keys.regFormId, regFormId) try row.set(Keys.userId, userId) try row.set(Keys.status, status.string) return row } // sourcery:end } extension EventReg { func regForm() throws -> RegForm? { return try children().first() } func eventRegAnswers() throws -> [EventRegAnswer] { return try children().all() } static func duplicationCheck(regFormId: Identifier, userId: Identifier) throws -> Bool { return try EventReg.makeQuery() .filter(EventReg.Keys.regFormId, regFormId) .filter(EventReg.Keys.userId, userId) .filter(EventReg.Keys.status, in: [ EventReg.RegistrationStatus.waiting.string, EventReg.RegistrationStatus.approved.string]) .all().isEmpty } func willDelete() throws { try eventRegAnswers() .forEach { try $0.delete() } } }
mit
5765e945c35feb92126d1bc945f6eefd
25.153846
90
0.68
3.89016
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Models/UserModel.swift
1
955
// // UserModel.swift // GitHubStar // // Created by midoks on 2017/6/19. // Copyright © 2017年 midoks. All rights reserved. // import UIKit class UserModel: NSObject, NSCoding { var id:Int64 var user:String var token:String var info:String var main:Int64 required init?(coder aDecoder: NSCoder) { //super.init() id = aDecoder.decodeInt64(forKey: "id") user = aDecoder.decodeObject(forKey: "user") as! String token = aDecoder.decodeObject(forKey: "token") as! String info = aDecoder.decodeObject(forKey: "token") as! String main = aDecoder.decodeInt64(forKey: "main") } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(user, forKey: "user") aCoder.encode(token, forKey: "token") aCoder.encode(info, forKey: "info") aCoder.encode(main, forKey: "main") } }
apache-2.0
1ac71f7743563b8d6360aeecb40b146b
23.410256
65
0.603992
3.854251
false
false
false
false
mukeshthawani/Swift-Algo-DS
Merge Sort/MergeSort.playground/Contents.swift
1
2105
//: Playground - noun: a place where people can play class MergeSort<T where T: Comparable> { var list:Array<T> init(list: Array<T>) { self.list = list } /// Sorts the subarray of a given array. func mergeSort(left: Int, right: Int){ let middle = (left + right)/2 if left < right { mergeSort(left: left, right: middle) mergeSort(left: middle+1, right: right) merge(left: left, middle: middle, right: right) } } /// Merges the two subarrays. private func merge(left: Int, middle: Int, right: Int) { let diff = (right - left) var tempArray = Array<T>() var leftIndex = left var rightIndex = middle + 1 // Compare the elements and copy them. while leftIndex <= middle && rightIndex <= right { let currentLeftElement = list[leftIndex] let currentRightElement = list[rightIndex] if currentLeftElement < currentRightElement { tempArray.append(currentLeftElement) leftIndex += 1 } else if currentLeftElement > currentRightElement { tempArray.append(currentRightElement) rightIndex += 1 } else { tempArray.append(currentLeftElement) tempArray.append(currentRightElement) leftIndex += 1 rightIndex += 1 } } // Copy remaining elements. if leftIndex <= middle { let remainingList = list[leftIndex...middle] tempArray = tempArray + remainingList } else if rightIndex <= right { let remainingList = list[rightIndex...right] tempArray = tempArray + remainingList } // Updates the list. let start = tempArray.startIndex list[left...right] = tempArray[start...diff] } } // Examples let firstList = [1,8,2,3,0,19,11,13,14] let merge = MergeSort<Int>(list: firstList) merge.mergeSort(left: 0, right: firstList.count-1) print(merge.list) // [0,1,2,3,8,11,13,14,19] let secondList = [1,3,8,2,4,5] merge.list = secondList merge.mergeSort(left: 0, right: 5) print(merge.list) // [1,2,3,4,5,8]
mit
5abf403ef4de5f82d87ce3133f0b910b
28.661972
78
0.614252
3.841241
false
false
false
false
zisko/swift
test/SILGen/guaranteed_self.swift
1
26195
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s protocol Fooable { init() func foo(_ x: Int) mutating func bar() mutating func bas() var prop1: Int { get set } var prop2: Int { get set } var prop3: Int { get nonmutating set } } protocol Barrable: class { init() func foo(_ x: Int) func bar() func bas() var prop1: Int { get set } var prop2: Int { get set } var prop3: Int { get set } } struct S: Fooable { var x: C? // Make the type nontrivial, so +0/+1 is observable. // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S init() {} // TODO: Way too many redundant r/r pairs here. Should use +0 rvalues. // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () { // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: copy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF]] func foo(_ x: Int) { self.foo(x) } func foooo(_ x: (Int, Bool)) { self.foooo(x) } // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> () // CHECK: bb0([[SELF:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF]] mutating func bar() { self.bar() } // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> () // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: copy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF]] func bas() { self.bas() } var prop1: Int = 0 // Getter for prop1 // CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop1Sivg : $@convention(method) (@guaranteed S) -> Int // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] // Setter for prop1 // CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop1Sivs : $@convention(method) (Int, @inout S) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: load [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // materializeForSet for prop1 // CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop1Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: load [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] var prop2: Int { // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop2Sivg : $@convention(method) (@guaranteed S) -> Int // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] get { return 0 } // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop2Sivs : $@convention(method) (Int, @inout S) -> () // CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop2Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) set { } } var prop3: Int { // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop3Sivg : $@convention(method) (@guaranteed S) -> Int // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] get { return 0 } // CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop3Sivs : $@convention(method) (Int, @guaranteed S) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] // CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop3Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] nonmutating set { } } } // Witness thunk for nonmutating 'foo' // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for mutating 'bar' // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () { // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: load [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for 'bas', which is mutating in the protocol, but nonmutating // in the implementation // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP3bas{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK: end_borrow [[SELF]] // CHECK-NOT: destroy_value [[SELF]] // Witness thunk for prop1 getter // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop1SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF]] // Witness thunk for prop1 setter // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop1SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop1 materializeForSet // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop1SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop2 getter // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop2SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop2 setter // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop2SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop2 materializeForSet // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop2SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop3 getter // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop3 nonmutating setter // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivsTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop3 nonmutating materializeForSet // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK: } // end sil function '$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW' // // TODO: Expected output for the other cases // struct AO<T>: Fooable { var x: T? init() {} // CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK: apply {{.*}} [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK: } func foo(_ x: Int) { self.foo(x) } mutating func bar() { self.bar() } // CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> () // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] func bas() { self.bas() } var prop1: Int = 0 var prop2: Int { // CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV5prop2Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int { // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] get { return 0 } set { } } var prop3: Int { // CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV5prop3Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] get { return 0 } // CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV5prop3Sivs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self2AOV5prop3Sivm : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed AO<T>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK: } nonmutating set { } } } // Witness for nonmutating 'foo' // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self2AOVyxGAA7FooableA2aEP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (Int, @in_guaranteed AO<τ_0_0>) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>): // CHECK: apply {{.*}} [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness for 'bar', which is mutating in protocol but nonmutating in impl // CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self2AOVyxGAA7FooableA2aEP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (@inout AO<τ_0_0>) -> () // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>): // -- NB: This copy is not necessary, since we're willing to assume an inout // parameter is not mutably aliased. // CHECK: apply {{.*}}([[SELF_ADDR]]) // CHECK-NOT: destroy_addr [[SELF_ADDR]] class C: Fooable, Barrable { // Allocating initializer // CHECK-LABEL: sil hidden @$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C // CHECK: [[SELF1:%.*]] = alloc_ref $C // CHECK-NOT: [[SELF1]] // CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]]) // CHECK-NOT: [[SELF2]] // CHECK: return [[SELF2]] // Initializing constructors still have the +1 in, +1 out convention. // CHECK-LABEL: sil hidden @$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C { // CHECK: bb0([[SELF:%.*]] : @owned $C): // CHECK: [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]] // CHECK: [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]] // CHECK: destroy_value [[MARKED_SELF]] // CHECK: return [[MARKED_SELF_RESULT]] // CHECK: } // end sil function '$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc' // @objc thunk for initializing constructor // CHECK-LABEL: sil hidden [thunk] @$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C // CHECK: bb0([[SELF:%.*]] : @owned $C): // CHECK-NOT: copy_value [[SELF]] // CHECK: [[SELF2:%.*]] = apply {{%.*}}([[SELF]]) // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF2]] // CHECK: return [[SELF2]] // CHECK: } // end sil function '$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo' @objc required init() {} // CHECK-LABEL: sil hidden @$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $C): // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: } // end sil function '$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden [thunk] @$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () { // CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: apply {{.*}}({{.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK: } // end sil function '$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo' @objc func foo(_ x: Int) { self.foo(x) } @objc func bar() { self.bar() } @objc func bas() { self.bas() } // CHECK-LABEL: sil hidden [transparent] [thunk] @$S15guaranteed_self1CC5prop1SivgTo : $@convention(objc_method) (C) -> Int // CHECK: bb0([[SELF:%.*]] : @unowned $C): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: apply {{.*}}([[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-LABEL: sil hidden [transparent] [thunk] @$S15guaranteed_self1CC5prop1SivsTo : $@convention(objc_method) (Int, C) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: apply {{.*}} [[BORROWED_SELF_COPY]] // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK: } @objc var prop1: Int = 0 @objc var prop2: Int { get { return 0 } set {} } @objc var prop3: Int { get { return 0 } set {} } } class D: C { // CHECK-LABEL: sil hidden @$S15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D // CHECK: [[SELF1:%.*]] = alloc_ref $D // CHECK-NOT: [[SELF1]] // CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]]) // CHECK-NOT: [[SELF1]] // CHECK-NOT: [[SELF2]] // CHECK: return [[SELF2]] // CHECK-LABEL: sil hidden @$S15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D // CHECK: bb0([[SELF:%.*]] : @owned $D): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var D } // CHECK-NEXT: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK-NEXT: store [[SELF]] to [init] [[PB]] // CHECK-NOT: [[PB]] // CHECK: [[SELF1:%.*]] = load [take] [[PB]] // CHECK-NEXT: [[SUPER1:%.*]] = upcast [[SELF1]] // CHECK-NOT: [[PB]] // CHECK: [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]]) // CHECK-NEXT: [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]] // CHECK-NEXT: store [[SELF2]] to [init] [[PB]] // CHECK-NOT: [[PB]] // CHECK-NOT: [[SELF1]] // CHECK-NOT: [[SUPER1]] // CHECK-NOT: [[SELF2]] // CHECK-NOT: [[SUPER2]] // CHECK: [[SELF_FINAL:%.*]] = load [copy] [[PB]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[SELF_FINAL]] required init() { super.init() } // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$S15guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $D): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK: } dynamic override func foo(_ x: Int) { self.foo(x) } } func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) { return (S.foo /*, s.foo*/) } func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) { return (AO.foo /*, ao.foo*/) } // ---------------------------------------------------------------------------- // Make sure that we properly translate in_guaranteed parameters // correctly if we are asked to. // ---------------------------------------------------------------------------- // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$S15guaranteed_self9FakeArrayVAA8SequenceA2aDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Sequence) (@in FakeElement, @in_guaranteed FakeArray) -> () { // CHECK: bb0([[ARG0_PTR:%.*]] : @trivial $*FakeElement, [[ARG1_PTR:%.*]] : @trivial $*FakeArray): // CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]] // CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement // CHECK: [[FUN:%.*]] = function_ref @{{.*}} // CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[ARG1_PTR]]) class Z {} public struct FakeGenerator {} public struct FakeArray { var z = Z() } public struct FakeElement {} public protocol FakeGeneratorProtocol { associatedtype Element } extension FakeGenerator : FakeGeneratorProtocol { public typealias Element = FakeElement } public protocol SequenceDefaults { associatedtype Element associatedtype Generator : FakeGeneratorProtocol } extension SequenceDefaults { public func _constrainElement(_: FakeGenerator.Element) {} } public protocol Sequence : SequenceDefaults { func _constrainElement(_: Element) } extension FakeArray : Sequence { public typealias Element = FakeElement public typealias Generator = FakeGenerator func _containsElement(_: Element) {} } // ----------------------------------------------------------------------------- // Make sure that we do not emit extra copy_values when accessing let fields of // guaranteed parameters. // ----------------------------------------------------------------------------- class Kraken { func enrage() {} } func destroyShip(_ k: Kraken) {} class LetFieldClass { let letk = Kraken() var vark = Kraken() // CHECK-LABEL: sil hidden @$S15guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () { // CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass): // CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = load_borrow [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Kraken // CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]] // CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]]) // CHECK-NEXT: end_borrow [[KRAKEN]] from [[WRITE]] // CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Kraken // CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]] // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken } // CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]] // CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken // CHECK-NEXT: [[KRAKEN2:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Kraken // CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]] // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Kraken // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: destroy_value [[KRAKEN_BOX]] // CHECK-NEXT: destroy_value [[KRAKEN]] // CHECK-NEXT: tuple // CHECK-NEXT: return func letkMethod() { letk.enrage() let ll = letk destroyShip(ll) var lv = letk destroyShip(lv) } // CHECK-LABEL: sil hidden @$S15guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () { // CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass): // CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]]) // CHECK-NEXT: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[BORROWED_KRAKEN]] // CHECK-NEXT: apply [[KRAKEN_METH]]([[BORROWED_KRAKEN]]) // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]] // CHECK-NEXT: destroy_value [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]]) // CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]] // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken } // CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]] // CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken // CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]]) // CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]] // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Kraken // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: destroy_value [[KRAKEN_BOX]] // CHECK-NEXT: destroy_value [[KRAKEN]] // CHECK-NEXT: tuple // CHECK-NEXT: return func varkMethod() { vark.enrage() let vl = vark destroyShip(vl) var vv = vark destroyShip(vv) } } // ----------------------------------------------------------------------------- // Make sure that in all of the following cases find has only one copy_value in it. // ----------------------------------------------------------------------------- class ClassIntTreeNode { let value : Int let left, right : ClassIntTreeNode init() {} // CHECK-LABEL: sil hidden @$S15guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode { // CHECK-NOT: destroy_value // CHECK: copy_value // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: return func find(_ v : Int) -> ClassIntTreeNode { if v == value { return self } if v < value { return left.find(v) } return right.find(v) } }
apache-2.0
f2aa14356645a8b636d2f110a91b495d
46.443841
267
0.591737
3.419822
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/PointerType.swift
1
1929
#if SWIFT_PACKAGE import cllvm #endif /// `PointerType` is used to specify memory locations. Pointers are commonly /// used to reference objects in memory. /// /// `PointerType` may have an optional address space attribute defining the /// numbered address space where the pointed-to object resides. The default /// address space is number zero. The semantics of non-zero address spaces are /// target-specific. /// /// Note that LLVM does not permit pointers to void `(void*)` nor does it permit /// pointers to labels `(label*)`. Use `i8*` instead. public struct PointerType: IRType { /// Retrieves the type of the value being pointed to. public let pointee: IRType /// Retrieves the address space where the pointed-to object resides. public let addressSpace: AddressSpace /// Creates a `PointerType` from a pointee type and an optional address space. /// /// - parameter pointee: The type of the pointed-to object. /// - parameter addressSpace: The optional address space where the pointed-to /// object resides. /// - note: The context of this type is taken from it's pointee public init(pointee: IRType, addressSpace: AddressSpace = .zero) { // FIXME: This class of invalid reference is not caught by Module.verify(), // only `lli`. if pointee is VoidType { fatalError("Attempted to form pointer to VoidType - use pointer to IntType.int8 instead") } self.pointee = pointee self.addressSpace = addressSpace } //// Creates a type that simulates a pointer to void `(void*)`. public static let toVoid = PointerType(pointee: IntType.int8) /// Retrieves the underlying LLVM type object. public func asLLVM() -> LLVMTypeRef { return LLVMPointerType(pointee.asLLVM(), UInt32(addressSpace.rawValue)) } } extension PointerType: Equatable { public static func == (lhs: PointerType, rhs: PointerType) -> Bool { return lhs.asLLVM() == rhs.asLLVM() } }
mit
b59323a3df89cf6a59790dd315d5c51b
36.823529
95
0.712805
4.21179
false
false
false
false
kristopherjohnson/KJLunarLander
KJLunarLander/HUD.swift
1
3940
// // HUD.swift // KJLunarLander // // Copyright © 2016 Kristopher Johnson. All rights reserved. // import SpriteKit /// Node that displays text over the screen. final class HUD: SKNode { static let spriteName = "hud" private static let fontName = "Orbitron-Light" private static let fontSize: CGFloat = Constant.sceneSize.height / 36 private var altitude: SKLabelNode! private var horizontalSpeed: SKLabelNode! private var verticalSpeed: SKLabelNode! private var thrust: SKLabelNode! /// Constructor for HUD. /// /// This constructor automatically adds the HUD nodes to the /// specified parent node. convenience init(parent: SKNode) { self.init() name = HUD.spriteName self.zPosition = ZPosition.hud parent.addChild(self) // Create SKLabelNodes for text elements. let altitudeLabel = addLabelNode( text: NSLocalizedString("Altitude", comment: "Altitude")) altitude = addValueNode() let horizontalSpeedLabel = addLabelNode( text: NSLocalizedString("Horizontal Speed", comment: "Horizontal Speed")) horizontalSpeed = addValueNode() let verticalSpeedLabel = addLabelNode( text: NSLocalizedString("Vertical Speed", comment: "Vertical Speed")) verticalSpeed = addValueNode() let thrustLabel = addLabelNode( text: NSLocalizedString("Thrust", comment: "Thrust")) thrust = addValueNode() // Lay out the labels. let sceneSize = Constant.sceneSize let upperRightCorner = CGPoint(x: sceneSize.width / 2, y: sceneSize.height / 2) let columnLayouts: [ColumnLayout] = [ .right(width: 100), // label .right(width: 50), // value .left(width: 20) // optional additional indicator ] let rows: [[SKLabelNode]] = [ [altitudeLabel, altitude], [horizontalSpeedLabel, horizontalSpeed], [verticalSpeedLabel, verticalSpeed], [thrustLabel, thrust] ] let _ = layoutGrid(left: upperRightCorner.x - 200, top: upperRightCorner.y - 2 * HUD.fontSize, horizontalPadding: 6, verticalPadding: 6, rowHeight: HUD.fontSize, columnLayouts: columnLayouts, rows: rows) } /// Update the values displayed in the HUD func updateDisplayValues(lander: LanderSprite, altitude: CGFloat) { self.altitude.text = format(value: altitude) if let body = lander.physicsBody { // TODO: Display directional arrows instead of +/- horizontalSpeed.text = format(value: body.velocity.dx) verticalSpeed.text = format(value: body.velocity.dy) } thrust.text = format(value: lander.thrustLevel * 100) } /// Format a value for display in the HUD private func format(value: CGFloat) -> String { return String(format: "%d", Int(roundf(Float(value)))) } /// Create a text node to be used as a label. private func addLabelNode(text: String) -> SKLabelNode { let node = SKLabelNode(fontNamed: HUD.fontName) node.fontSize = HUD.fontSize node.fontColor = Color.hud node.text = text addChild(node) return node } /// Create a text node to be used to display a value. private func addValueNode() -> SKLabelNode { let node = SKLabelNode(fontNamed: HUD.fontName) node.fontSize = HUD.fontSize node.fontColor = Color.hud addChild(node) return node } }
mit
1bf7cf3addaf8fc304914eb42d80aacc
32.381356
73
0.574257
4.917603
false
false
false
false
jphacks/KB_01
jphacks/ViewController/SearchViewController/SpotOptionButton.swift
1
1400
// // SpotOptionButton.swift // jphacks // // Created by SakuragiYoshimasa on 2015/11/28. // Copyright © 2015年 at. All rights reserved. // import Foundation import UIKit class SpotOptionButton : UIButton { var imageId: Int = 0 var tapGestureRecognizer: UITapGestureRecognizer! = nil private var _selected: Bool = false var hilightened: Bool { set{ _selected = newValue if newValue { print("on" + String(imageId)) self.setImage(UIImage(named: "on-" + String(imageId)), forState: UIControlState.Normal) } else { print("off" + String(imageId)) self.setImage(UIImage(named: "off-" + String(imageId)), forState: UIControlState.Normal) } } get{ return _selected } } func tapped() { print("tap") hilightened = !hilightened } override init(frame: CGRect) { super.init(frame: frame) tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped") self.addGestureRecognizer(tapGestureRecognizer) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped") self.addGestureRecognizer(tapGestureRecognizer) } }
mit
004c2554cbfd62b44921637f69465c29
26.411765
104
0.599857
4.719595
false
false
false
false
andela-jejezie/FlutterwavePaymentManager
Rave/Rave/FWModel/FlutterwavePaymentResult.swift
1
4098
// // PayResponse.swift // flutterwave // // Created by Johnson Ejezie on 15/12/2016. // Copyright © 2016 johnsonejezie. All rights reserved. // import UIKit struct RavePaymentResult { var status:String var message:String let data:RaveResponseData } struct RaveResponseData { var id:NSNumber = 0 var txRef:String = "" var amount:Int16 = 0 var chargeResponseCode:String = "" var chargeResponseMessage:String = "" var authModelUsed:AuthModelUsed = .VBVSECURECODE var flwRef = "" var currency:String = "" var IP:String = "" var narration:String = "" var status:String = "" var vbvrespmessage:String = "" var authurl:String = "" var vbvrespcode:String = "" var acctvalrespmsg:String = "" var acctvalrespcode:String = "" var createdAt:String = "" var paymentType:String = "" var chargeToken:ChargeToken? } extension RaveResponseData { init?(json:JSONDictionary) { if let id = json["id"] as? NSNumber { self.id = id } if let txRef = json["txRef"] as? String { self.txRef = txRef } if let amount = json["amount"] as? Int16 { self.amount = amount } if let chargeResponseCode = json["chargeResponseCode"] as? String { self.chargeResponseCode = chargeResponseCode } if let flwRef = json["flwRef"] as? String { self.flwRef = flwRef } if let chargeResponseMessage = json["chargeResponseMessage"] as? String { self.chargeResponseMessage = chargeResponseMessage } if let authModelUsed = json["authModelUsed"] as? String { self.authModelUsed = AuthModelUsed.build(rawValue: authModelUsed) } if let currency = json["currency"] as? String { self.currency = currency } if let IP = json["IP"] as? String { self.IP = IP } if let narration = json["narration"] as? String { self.narration = narration } if let status = json["status"] as? String { self.status = status } if let vbvrespmessage = json["vbvrespmessage"] as? String { self.vbvrespmessage = vbvrespmessage } if let authurl = json["authurl"] as? String { self.authurl = authurl } if let vbvrespcode = json["vbvrespcode"] as? String { self.vbvrespcode = vbvrespcode } if let acctvalrespmsg = json["acctvalrespmsg"] as? String { self.acctvalrespmsg = acctvalrespmsg } if let acctvalrespcode = json["acctvalrespcode"] as? String { self.acctvalrespcode = acctvalrespcode } if let createdAt = json["createdAt"] as? String { self.createdAt = createdAt } if let paymentType = json["paymentType"] as? String { self.paymentType = paymentType } if let chargeToken = json["chargeToken"] as? JSONDictionary { self.chargeToken = ChargeToken(json: chargeToken) } } } enum AuthModelUsed:String { case VBVSECURECODE = "VBVSECURECODE" case NOAUTH = "NOAUTH" case RANDOMDEBIT = "RANDOM_DEBIT" case PIN = "PIN" static func build(rawValue:String) -> AuthModelUsed { return AuthModelUsed(rawValue: rawValue) ?? .VBVSECURECODE } } struct ChargeToken { var shortcode:String = "" var embedToken:String = "" } extension ChargeToken { init?(json:JSONDictionary) { if let shortcode = json["user_token"] as? String { self.shortcode = shortcode } if let embedToken = json["embed_token"] as? String { self.embedToken = embedToken } } } struct Bank { var code:String = "" var name:String = "" } extension Bank { init?(json:JSONDictionary) { if let code = json["code"] as? String { self.code = code } if let name = json["name"] as? String { self.name = name } } }
mit
975ffb6ebb6738a43756990a97bcecd5
27.65035
81
0.584574
3.916826
false
false
false
false
SmallPlanetSwift/PlanetSwift
Sources/PlanetSwift/ImageCache.swift
1
4150
// // ImageCache.swift // PlanetSwift // // Created by Brad Bambara on 1/20/15. // Copyright (c) 2015 Small Planet. All rights reserved. // import UIKit private let imageCacheShared = ImageCache() public typealias ImageCacheCompletionBlock = ((UIImage?) -> Void) typealias ImageCacheDownloadBlock = ((_ success: Bool) -> Void) public class ImageCache { // MARK: - public API public class var sharedInstance: ImageCache { return imageCacheShared } public func get(_ url: URL, completion: @escaping ImageCacheCompletionBlock) { let imageKey = url.absoluteString if let memCacheImage = memoryCache.object(forKey: imageKey as NSString) as? UIImage { completion(memCacheImage) return } if url.isFileURL { if let image = UIImage(contentsOfFile: imageKey) { memoryCache.setObject(image, forKey: imageKey as NSString) completion(image) return } } var cacheRequest: ImageCacheRequest! if let activeRequest = activeRequestForKey(imageKey) { cacheRequest = activeRequest } else { cacheRequest = ImageCacheRequest(url: url, completion: { [weak self] (success: Bool) in if self != nil { var image: UIImage? if success { image = UIImage(data: cacheRequest.imageData as Data) if image != nil { self!.memoryCache.setObject(image!, forKey: imageKey as NSString) } } var index = 0 for request in self!.activeNetworkRequests { if request === cacheRequest { break } index += 1 } self!.activeNetworkRequests.remove(at: index) //call all completion blocks for block in cacheRequest.completionBlocks { block(image) } } }) activeNetworkRequests.append(cacheRequest) } //append our completion block to this already-in-progress request cacheRequest.completionBlocks.append(completion) } public func get(_ key: AnyObject) -> UIImage? { return memoryCache.object(forKey: key) as? UIImage } public func set(_ image: UIImage, key: AnyObject) { memoryCache.setObject(image, forKey: key) } // MARK: - private private let memoryCache = NSCache<AnyObject, AnyObject>() private var activeNetworkRequests = [ImageCacheRequest]() private func activeRequestForKey(_ key: String) -> ImageCacheRequest? { for request in activeNetworkRequests where request.request.url!.absoluteString == key { return request } return nil } } internal class ImageCacheRequest: NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate { var completionBlocks = [ImageCacheCompletionBlock]() let request: URLRequest var connection: NSURLConnection? let completionBlock: ImageCacheDownloadBlock let imageData: NSMutableData init(url: URL, completion: @escaping ImageCacheDownloadBlock) { completionBlock = completion request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 60) imageData = NSMutableData() connection = NSURLConnection() super.init() connection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.common) connection?.start() if connection == nil { completionBlock(false) } } // MARK: - NSURLConnectionDelegate private func connection(_ connection: NSURLConnection, didFailWithError error: NSError) { completionBlock(false) } // MARK: - NSURLConnectionDataDelegate func connection(_ connection: NSURLConnection, didReceive data: Data) { imageData.append(data) } func connectionDidFinishLoading(_ connection: NSURLConnection) { completionBlock(true) } }
mit
7eb28fa2b9d223ad848c711f280c4427
28.432624
99
0.629398
4.917062
false
false
false
false
natecook1000/swift
stdlib/public/SDK/Foundation/NSStringAPI.swift
3
76841
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Important Note // ============== // // This file is shared between two projects: // // 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation // 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation // // If you change this file, you must update it in both places. #if !DEPLOYMENT_RUNTIME_SWIFT @_exported import Foundation // Clang module #endif // Open Issues // =========== // // Property Lists need to be properly bridged // func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.add(f(s)) } return result } #if !DEPLOYMENT_RUNTIME_SWIFT // We only need this for UnsafeMutablePointer, but there's not currently a way // to write that constraint. extension Optional { /// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the /// address of `object` to `body`. /// /// This is intended for use with Foundation APIs that return an Objective-C /// type via out-parameter where it is important to be able to *ignore* that /// parameter by passing `nil`. (For some APIs, this may allow the /// implementation to avoid some work.) /// /// In most cases it would be simpler to just write this code inline, but if /// `body` is complicated than that results in unnecessarily repeated code. internal func _withNilOrAddress<NSType : AnyObject, ResultType>( of object: inout NSType?, _ body: (AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType ) -> ResultType { return self == nil ? body(nil) : body(&object) } } #endif extension String { //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // @property (class) const NSStringEncoding *availableStringEncodings; /// An array of the encodings that strings support in the application's /// environment. public static var availableStringEncodings: [Encoding] { var result = [Encoding]() var p = NSString.availableStringEncodings while p.pointee != 0 { result.append(Encoding(rawValue: p.pointee)) p += 1 } return result } // @property (class) NSStringEncoding defaultCStringEncoding; /// The C-string encoding assumed for any method accepting a C string as an /// argument. public static var defaultCStringEncoding: Encoding { return Encoding(rawValue: NSString.defaultCStringEncoding) } // + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding /// Returns a human-readable string giving the name of the specified encoding. /// /// - Parameter encoding: A string encoding. For possible values, see /// `String.Encoding`. /// - Returns: A human-readable string giving the name of `encoding` in the /// current locale. public static func localizedName( of encoding: Encoding ) -> String { return NSString.localizedName(of: encoding.rawValue) } // + (instancetype)localizedStringWithFormat:(NSString *)format, ... /// Returns a string created by using a given format string as a /// template into which the remaining argument values are substituted /// according to the user's default locale. public static func localizedStringWithFormat( _ format: String, _ arguments: CVarArg... ) -> String { return String(format: format, locale: Locale.current, arguments: arguments) } //===--------------------------------------------------------------------===// // NSString factory functions that have a corresponding constructor // are omitted. // // + (instancetype)string // // + (instancetype) // stringWithCharacters:(const unichar *)chars length:(NSUInteger)length // // + (instancetype)stringWithFormat:(NSString *)format, ... // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithCString:(const char *)cString // encoding:(NSStringEncoding)enc //===--------------------------------------------------------------------===// //===--- Adds nothing for String beyond what String(s) does -------------===// // + (instancetype)stringWithString:(NSString *)aString //===--------------------------------------------------------------------===// // + (instancetype)stringWithUTF8String:(const char *)bytes /// Creates a string by copying the data from a given /// C array of UTF8-encoded bytes. public init?(utf8String bytes: UnsafePointer<CChar>) { if let ns = NSString(utf8String: bytes) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } } extension String { //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Creates a new string equivalent to the given bytes interpreted in the /// specified encoding. /// /// - Parameters: /// - bytes: A sequence of bytes to interpret using `encoding`. /// - encoding: The ecoding to use to interpret `bytes`. public init? <S: Sequence>(bytes: S, encoding: Encoding) where S.Iterator.Element == UInt8 { let byteArray = Array(bytes) if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of bytes from the /// given buffer, interpreted in the specified encoding, and optionally /// frees the buffer. /// /// - Warning: This initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding.rawValue, freeWhenDone: flag) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Creates a new string that contains the specified number of characters /// from the given C array of Unicode characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count)) } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of characters /// from the given C array of UTF-16 code units. public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = String._unconditionallyBridgeFromObjectiveC(NSString( charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag)) } //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // /// Produces a string created by reading data from the file at a /// given path interpreted using a given encoding. public init( contentsOfFile path: String, encoding enc: Encoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from the file at /// a given path and returns by reference the encoding used to /// interpret the file. public init( contentsOfFile path: String, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOfFile: path, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOfFile path: String ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError**)error /// Produces a string created by reading data from a given URL /// interpreted using a given encoding. Errors are written into the /// inout `error` argument. public init( contentsOf url: URL, encoding enc: Encoding ) throws { let ns = try NSString(contentsOf: url, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from a given URL /// and returns by reference the encoding used to interpret the /// data. Errors are written into the inout `error` argument. public init( contentsOf url: URL, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOf url: URL ) throws { let ns = try NSString(contentsOf: url, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithCString:(const char *)nullTerminatedCString // encoding:(NSStringEncoding)encoding /// Produces a string containing the bytes in a given C array, /// interpreted according to a given encoding. public init?( cString: UnsafePointer<CChar>, encoding enc: Encoding ) { if let ns = NSString(cString: cString, encoding: enc.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // FIXME: handle optional locale with default arguments // - (instancetype) // initWithData:(NSData *)data // encoding:(NSStringEncoding)encoding /// Returns a `String` initialized by converting given `data` into /// Unicode characters using a given `encoding`. public init?(data: Data, encoding: Encoding) { guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil } self = String._unconditionallyBridgeFromObjectiveC(s) } // - (instancetype)initWithFormat:(NSString *)format, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted. public init(format: String, _ arguments: CVarArg...) { self = String(format: format, arguments: arguments) } // - (instancetype) // initWithFormat:(NSString *)format // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to the user's default locale. public init(format: String, arguments: [CVarArg]) { self = String(format: format, locale: nil, arguments: arguments) } // - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: String, locale: Locale?, _ args: CVarArg...) { self = String(format: format, locale: locale, arguments: args) } // - (instancetype) // initWithFormat:(NSString *)format // locale:(id)locale // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: String, locale: Locale?, arguments: [CVarArg]) { #if DEPLOYMENT_RUNTIME_SWIFT self = withVaList(arguments) { String._unconditionallyBridgeFromObjectiveC( NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0) ) } #else self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } #endif } } extension StringProtocol where Index == String.Index { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. // FIXME(strings): There is probably a better way to bridge Self to NSString var _ns: NSString { return self._ephemeralString._bridgeToObjectiveC() } // self can be a Substring so we need to subtract/add this offset when // passing _ns to the Foundation APIs. Will be 0 if self is String. @inlinable internal var _substringOffset: Int { return self.startIndex.encodedOffset } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. func _index(_ utf16Index: Int) -> Index { return Index(encodedOffset: utf16Index + _substringOffset) } @inlinable internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange { return NSRange( location: r.lowerBound.encodedOffset - _substringOffset, length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. func _range(_ r: NSRange) -> Range<Index> { return _index(r.location)..<_index(r.location + r.length) } /// Return a `Range<Index>?` corresponding to the given `NSRange` of /// our UTF-16 representation. func _optionalRange(_ r: NSRange) -> Range<Index>? { if r.location == NSNotFound { return nil } return _range(r) } /// Invoke `body` on an `Int` buffer. If `index` was converted from /// non-`nil`, convert the buffer to an `Index` and write it into the /// memory referred to by `index` func _withOptionalOutParameter<Result>( _ index: UnsafeMutablePointer<Index>?, _ body: (UnsafeMutablePointer<Int>?) -> Result ) -> Result { var utf16Index: Int = 0 let result = (index != nil ? body(&utf16Index) : body(nil)) index?.pointee = _index(utf16Index) return result } /// Invoke `body` on an `NSRange` buffer. If `range` was converted /// from non-`nil`, convert the buffer to a `Range<Index>` and write /// it into the memory referred to by `range` func _withOptionalOutParameter<Result>( _ range: UnsafeMutablePointer<Range<Index>>?, _ body: (UnsafeMutablePointer<NSRange>?) -> Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = (range != nil ? body(&nsRange) : body(nil)) range?.pointee = self._range(nsRange) return result } //===--- Instance Methods/Properties-------------------------------------===// //===--------------------------------------------------------------------===// //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // @property BOOL boolValue; // - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding /// Returns a Boolean value that indicates whether the string can be /// converted to the specified encoding without loss of information. /// /// - Parameter encoding: A string encoding. /// - Returns: `true` if the string can be encoded in `encoding` without loss /// of information; otherwise, `false`. public func canBeConverted(to encoding: String.Encoding) -> Bool { return _ns.canBeConverted(to: encoding.rawValue) } // @property NSString* capitalizedString /// A copy of the string with each word changed to its corresponding /// capitalized spelling. /// /// This property performs the canonical (non-localized) mapping. It is /// suitable for programming operations that require stable results not /// depending on the current locale. /// /// A capitalized string is a string with the first character in each word /// changed to its corresponding uppercase value, and all remaining /// characters set to their corresponding lowercase values. A "word" is any /// sequence of characters delimited by spaces, tabs, or line terminators. /// Some common word delimiting punctuation isn't considered, so this /// property may not generally produce the desired results for multiword /// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for /// additional information. /// /// Case transformations aren’t guaranteed to be symmetrical or to produce /// strings of the same lengths as the originals. public var capitalized: String { return _ns.capitalized as String } // @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0); /// A capitalized representation of the string that is produced /// using the current locale. @available(macOS 10.11, iOS 9.0, *) public var localizedCapitalized: String { return _ns.localizedCapitalized } // - (NSString *)capitalizedStringWithLocale:(Locale *)locale /// Returns a capitalized representation of the string /// using the specified locale. public func capitalized(with locale: Locale?) -> String { return _ns.capitalized(with: locale) as String } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. public func caseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.caseInsensitiveCompare(aString._ephemeralString) } //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // - (unichar)characterAtIndex:(NSUInteger)index // // We have a different meaning for "Character" in Swift, and we are // trying not to expose error-prone UTF-16 integer indexes // - (NSString *) // commonPrefixWithString:(NSString *)aString // options:(StringCompareOptions)mask /// Returns a string containing characters this string and the /// given string have in common, starting from the beginning of each /// up to the first characters that aren't equivalent. public func commonPrefix< T : StringProtocol >(with aString: T, options: String.CompareOptions = []) -> String { return _ns.commonPrefix(with: aString._ephemeralString, options: options) } // - (NSComparisonResult) // compare:(NSString *)aString // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range locale:(id)locale /// Compares the string using the specified options and /// returns the lexical ordering for the range. public func compare<T : StringProtocol>( _ aString: T, options mask: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil ) -> ComparisonResult { // According to Ali Ozer, there may be some real advantage to // dispatching to the minimal selector for the supplied options. // So let's do that; the switch should compile away anyhow. let aString = aString._ephemeralString return locale != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange( range ?? startIndex..<endIndex ), locale: locale?._bridgeToObjectiveC() ) : range != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange(range!) ) : !mask.isEmpty ? _ns.compare(aString, options: mask) : _ns.compare(aString) } // - (NSUInteger) // completePathIntoString:(NSString **)outputName // caseSensitive:(BOOL)flag // matchesIntoArray:(NSArray **)outputArray // filterTypes:(NSArray *)filterTypes /// Interprets the string as a path in the file system and /// attempts to perform filename completion, returning a numeric /// value that indicates whether a match was possible, and by /// reference the longest path that matches the string. /// /// - Returns: The actual number of matching paths. public func completePath( into outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { #if DEPLOYMENT_RUNTIME_SWIFT var outputNamePlaceholder: String? var outputArrayPlaceholder = [String]() let res = self._ns.completePath( into: &outputNamePlaceholder, caseSensitive: caseSensitive, matchesInto: &outputArrayPlaceholder, filterTypes: filterTypes ) if let n = outputNamePlaceholder { outputName?.pointee = n } else { outputName?.pointee = "" } outputArray?.pointee = outputArrayPlaceholder return res #else // DEPLOYMENT_RUNTIME_SWIFT var nsMatches: NSArray? var nsOutputName: NSString? let result: Int = outputName._withNilOrAddress(of: &nsOutputName) { outputName in outputArray._withNilOrAddress(of: &nsMatches) { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 let outputNonOptionalName = unsafeBitCast( outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self) let outputNonOptionalArray = unsafeBitCast( outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, matchesInto: outputNonOptionalArray, filterTypes: filterTypes ) } } if let matches = nsMatches { // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion outputArray?.pointee = matches as! [String] } if let n = nsOutputName { outputName?.pointee = n as String } return result #endif // DEPLOYMENT_RUNTIME_SWIFT } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the string /// that have been divided by characters in the given set. public func components(separatedBy separator: CharacterSet) -> [String] { return _ns.components(separatedBy: separator) } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the string that have been /// divided by the given separator. /// /// The substrings in the resulting array appear in the same order as the /// original string. Adjacent occurrences of the separator string produce /// empty strings in the result. Similarly, if the string begins or ends /// with the separator, the first or last substring, respectively, is empty. /// The following example shows this behavior: /// /// let list1 = "Karin, Carrie, David" /// let items1 = list1.components(separatedBy: ", ") /// // ["Karin", "Carrie", "David"] /// /// // Beginning with the separator: /// let list2 = ", Norman, Stanley, Fletcher" /// let items2 = list2.components(separatedBy: ", ") /// // ["", "Norman", "Stanley", "Fletcher" /// /// If the list has no separators, the array contains only the original /// string itself. /// /// let name = "Karin" /// let list = name.components(separatedBy: ", ") /// // ["Karin"] /// /// - Parameter separator: The separator string. /// - Returns: An array containing substrings that have been divided from the /// string using `separator`. // FIXME(strings): now when String conforms to Collection, this can be // replaced by split(separator:maxSplits:omittingEmptySubsequences:) public func components< T : StringProtocol >(separatedBy separator: T) -> [String] { return _ns.components(separatedBy: separator._ephemeralString) } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the string as a C string /// using a given encoding. public func cString(using encoding: String.Encoding) -> [CChar]? { return withExtendedLifetime(_ns) { (s: NSString) -> [CChar]? in _persistCString(s.cString(using: encoding.rawValue)) } } // - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding // // - (NSData *) // dataUsingEncoding:(NSStringEncoding)encoding // allowLossyConversion:(BOOL)flag /// Returns a `Data` containing a representation of /// the `String` encoded using a given encoding. public func data( using encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { return _ns.data( using: encoding.rawValue, allowLossyConversion: allowLossyConversion) } // @property NSString* decomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KD. public var decomposedStringWithCompatibilityMapping: String { return _ns.decomposedStringWithCompatibilityMapping } //===--- Importing Foundation should not affect String printing ---------===// // Therefore, we're not exposing this: // // @property NSString* description //===--- Omitted for consistency with API review results 5/20/2014 -----===// // @property double doubleValue; // - (void) // enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block /// Enumerates all the lines in a string. public func enumerateLines( invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void ) { _ns.enumerateLines { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line, &stop_) if stop_ { stop.pointee = true } } } // @property NSStringEncoding fastestEncoding; /// The fastest encoding to which the string can be converted without loss /// of information. public var fastestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.fastestEncoding) } // - (BOOL) // getCString:(char *)buffer // maxLength:(NSUInteger)maxBufferCount // encoding:(NSStringEncoding)encoding /// Converts the `String`'s content to a given encoding and /// stores them in a buffer. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. public func getCString( _ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding ) -> Bool { return _ns.getCString(&buffer, maxLength: Swift.min(buffer.count, maxLength), encoding: encoding.rawValue) } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. public func lengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.lengthOfBytes(using: encoding.rawValue) } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and the given string using a case-insensitive, /// localized, comparison. public func localizedCaseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and the given string using a localized comparison. public func localizedCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCompare(aString._ephemeralString) } /// Compares the string and the given string as sorted by the Finder. public func localizedStandardCompare< T : StringProtocol >(_ string: T) -> ComparisonResult { return _ns.localizedStandardCompare(string._ephemeralString) } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property long long longLongValue // @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0); /// A lowercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedLowercase: String { return _ns.localizedLowercase } // - (NSString *)lowercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to lowercase, taking into account the specified /// locale. public func lowercased(with locale: Locale?) -> String { return _ns.lowercased(with: locale) } // - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the maximum number of bytes needed to store the /// `String` in a given encoding. public func maximumLengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.maximumLengthOfBytes(using: encoding.rawValue) } // @property NSString* precomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } #if !DEPLOYMENT_RUNTIME_SWIFT // - (id)propertyList /// Parses the `String` as a text representation of a /// property list, returning an NSString, NSData, NSArray, or /// NSDictionary object, according to the topmost element. public func propertyList() -> Any { return _ns.propertyList() } // - (NSDictionary *)propertyListFromStringsFileFormat /// Returns a dictionary object initialized with the keys and /// values found in the `String`. public func propertyListFromStringsFileFormat() -> [String : String] { return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:] } #endif // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns a Boolean value indicating whether the string contains the given /// string, taking the current locale into account. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardContains< T : StringProtocol >(_ string: T) -> Bool { return _ns.localizedStandardContains(string._ephemeralString) } // @property NSStringEncoding smallestEncoding; /// The smallest encoding to which the string can be converted without /// loss of information. public var smallestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.smallestEncoding) } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string created by replacing all characters in the string /// not in the specified set with percent encoded characters. public func addingPercentEncoding( withAllowedCharacters allowedCharacters: CharacterSet ) -> String? { // FIXME: the documentation states that this method can return nil if the // transformation is not possible, without going into further details. The // implementation can only return nil if malloc() returns nil, so in // practice this is not possible. Still, to be consistent with // documentation, we declare the method as returning an optional String. // // <rdar://problem/17901698> Docs for -[NSString // stringByAddingPercentEncodingWithAllowedCharacters] don't precisely // describe when return value is nil return _ns.addingPercentEncoding(withAllowedCharacters: allowedCharacters ) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string created by appending a string constructed from a given /// format string and the following arguments. public func appendingFormat< T : StringProtocol >( _ format: T, _ arguments: CVarArg... ) -> String { return _ns.appending( String(format: format._ephemeralString, arguments: arguments)) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string created by appending the given string. // FIXME(strings): shouldn't it be deprecated in favor of `+`? public func appending< T : StringProtocol >(_ aString: T) -> String { return _ns.appending(aString._ephemeralString) } /// Returns a string with the given character folding options /// applied. public func folding( options: String.CompareOptions = [], locale: Locale? ) -> String { return _ns.folding(options: options, locale: locale) } // - (NSString *)stringByPaddingToLength:(NSUInteger)newLength // withString:(NSString *)padString // startingAtIndex:(NSUInteger)padIndex /// Returns a new string formed from the `String` by either /// removing characters from the end, or by appending as many /// occurrences as necessary of a given pad string. public func padding< T : StringProtocol >( toLength newLength: Int, withPad padString: T, startingAt padIndex: Int ) -> String { return _ns.padding( toLength: newLength, withPad: padString._ephemeralString, startingAt: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// A new string made from the string by replacing all percent encoded /// sequences with the matching UTF-8 characters. public var removingPercentEncoding: String? { return _ns.removingPercentEncoding } // - (NSString *) // stringByReplacingCharactersInRange:(NSRange)range // withString:(NSString *)replacement /// Returns a new string in which the characters in a /// specified range of the `String` are replaced by a given string. public func replacingCharacters< T : StringProtocol, R : RangeExpression >(in range: R, with replacement: T) -> String where R.Bound == Index { return _ns.replacingCharacters( in: _toRelativeNSRange(range.relative(to: self)), with: replacement._ephemeralString) } // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // options:(StringCompareOptions)options // range:(NSRange)searchRange /// Returns a new string in which all occurrences of a target /// string in a specified range of the string are replaced by /// another given string. public func replacingOccurrences< Target : StringProtocol, Replacement : StringProtocol >( of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { let target = target._ephemeralString let replacement = replacement._ephemeralString return (searchRange != nil) || (!options.isEmpty) ? _ns.replacingOccurrences( of: target, with: replacement, options: options, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ) ) : _ns.replacingOccurrences(of: target, with: replacement) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a new string made by replacing in the `String` /// all percent escapes with the matching characters as determined /// by a given encoding. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func replacingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.replacingPercentEscapes(using: encoding.rawValue) } #endif // - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set /// Returns a new string made by removing from both ends of /// the `String` characters contained in a given character set. public func trimmingCharacters(in set: CharacterSet) -> String { return _ns.trimmingCharacters(in: set) } // @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0); /// An uppercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedUppercase: String { return _ns.localizedUppercase as String } // - (NSString *)uppercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to uppercase, taking into account the specified /// locale. public func uppercased(with locale: Locale?) -> String { return _ns.uppercased(with: locale) } //===--- Omitted due to redundancy with "utf8" property -----------------===// // - (const char *)UTF8String // - (BOOL) // writeToFile:(NSString *)path // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to a file at a given /// path using a given encoding. public func write< T : StringProtocol >( toFile path: T, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( toFile: path._ephemeralString, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (BOOL) // writeToURL:(NSURL *)url // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to the URL specified /// by url using the specified encoding. public func write( to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); #if !DEPLOYMENT_RUNTIME_SWIFT /// Perform string transliteration. @available(macOS 10.11, iOS 9.0, *) public func applyingTransform( _ transform: StringTransform, reverse: Bool ) -> String? { return _ns.applyingTransform(transform, reverse: reverse) } // - (void) // enumerateLinguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // usingBlock:( // void (^)( // NSString *tag, NSRange tokenRange, // NSRange sentenceRange, BOOL *stop) // )block /// Performs linguistic analysis on the specified string by /// enumerating the specific range of the string, providing the /// Block with the located tags. public func enumerateLinguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, invoking body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) where R.Bound == Index { let range = range.relative(to: self) _ns.enumerateLinguisticTags( in: _toRelativeNSRange(range), scheme: tagScheme._ephemeralString, options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { $3.pointee = true } } } #endif // - (void) // enumerateSubstringsInRange:(NSRange)range // options:(NSStringEnumerationOptions)opts // usingBlock:( // void (^)( // NSString *substring, // NSRange substringRange, // NSRange enclosingRange, // BOOL *stop) // )block /// Enumerates the substrings of the specified type in the specified range of /// the string. /// /// Mutation of a string value while enumerating its substrings is not /// supported. If you need to mutate a string from within `body`, convert /// your string to an `NSMutableString` instance and then call the /// `enumerateSubstrings(in:options:using:)` method. /// /// - Parameters: /// - range: The range within the string to enumerate substrings. /// - opts: Options specifying types of substrings and enumeration styles. /// If `opts` is omitted or empty, `body` is called a single time with /// the range of the string specified by `range`. /// - body: The closure executed for each substring in the enumeration. The /// closure takes four arguments: /// - The enumerated substring. If `substringNotRequired` is included in /// `opts`, this parameter is `nil` for every execution of the /// closure. /// - The range of the enumerated substring in the string that /// `enumerate(in:options:_:)` was called on. /// - The range that includes the substring as well as any separator or /// filler characters that follow. For instance, for lines, /// `enclosingRange` contains the line terminators. The enclosing /// range for the first string enumerated also contains any characters /// that occur before the string. Consecutive enclosing ranges are /// guaranteed not to overlap, and every single character in the /// enumerated range is included in one and only one enclosing range. /// - An `inout` Boolean value that the closure can use to stop the /// enumeration by setting `stop = true`. public func enumerateSubstrings< R : RangeExpression >( in range: R, options opts: String.EnumerationOptions = [], _ body: @escaping ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) where R.Bound == Index { _ns.enumerateSubstrings( in: _toRelativeNSRange(range.relative(to: self)), options: opts) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property float floatValue; // - (BOOL) // getBytes:(void *)buffer // maxLength:(NSUInteger)maxBufferCount // usedLength:(NSUInteger*)usedBufferCount // encoding:(NSStringEncoding)encoding // options:(StringEncodingConversionOptions)options // range:(NSRange)range // remainingRange:(NSRangePointer)leftover /// Writes the given `range` of characters into `buffer` in a given /// `encoding`, without any allocations. Does not NULL-terminate. /// /// - Parameter buffer: A buffer into which to store the bytes from /// the receiver. The returned bytes are not NUL-terminated. /// /// - Parameter maxBufferCount: The maximum number of bytes to write /// to buffer. /// /// - Parameter usedBufferCount: The number of bytes used from /// buffer. Pass `nil` if you do not need this value. /// /// - Parameter encoding: The encoding to use for the returned bytes. /// /// - Parameter options: A mask to specify options to use for /// converting the receiver's contents to `encoding` (if conversion /// is necessary). /// /// - Parameter range: The range of characters in the receiver to get. /// /// - Parameter leftover: The remaining range. Pass `nil` If you do /// not need this value. /// /// - Returns: `true` iff some characters were converted. /// /// - Note: Conversion stops when the buffer fills or when the /// conversion isn't possible due to the chosen encoding. /// /// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes. public func getBytes< R : RangeExpression >( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: R, remaining leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool where R.Bound == Index { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: Swift.min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding.rawValue, options: options, range: _toRelativeNSRange(range.relative(to: self)), remaining: $0) } } // - (void) // getLineStart:(NSUInteger *)startIndex // end:(NSUInteger *)lineEndIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first line and /// the end of the last line touched by the given range. public func getLineStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } // - (void) // getParagraphStart:(NSUInteger *)startIndex // end:(NSUInteger *)endIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first paragraph /// and the end of the last paragraph touched by the given range. public func getParagraphStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } //===--- Already provided by core Swift ---------------------------------===// // - (instancetype)initWithString:(NSString *)aString //===--- Initializers that can fail dropped for factory functions -------===// // - (instancetype)initWithUTF8String:(const char *)bytes //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property NSInteger integerValue; // @property Int intValue; //===--- Omitted by apparent agreement during API review 5/20/2014 ------===// // @property BOOL absolutePath; // - (BOOL)isEqualToString:(NSString *)aString // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. public func lineRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _range(_ns.lineRange( for: _toRelativeNSRange(aRange.relative(to: self)))) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSArray *) // linguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // tokenRanges:(NSArray**)tokenRanges /// Returns an array of linguistic tags for the specified /// range and requested tags within the receiving string. public func linguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil? ) -> [String] where R.Bound == Index { var nsTokenRanges: NSArray? let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) { self._ns.linguisticTags( in: _toRelativeNSRange(range.relative(to: self)), scheme: tagScheme._ephemeralString, options: opts, orthography: orthography, tokenRanges: $0) as NSArray } if let nsTokenRanges = nsTokenRanges { tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map { self._range($0.rangeValue) } } return result as! [String] } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. public func paragraphRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _range( _ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self)))) } #endif // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // range:(NSRange)aRange /// Finds and returns the range in the `String` of the first /// character from a given character set found in a given range with /// given options. public func rangeOfCharacter( from aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { return _optionalRange( _ns.rangeOfCharacter( from: aSet, options: mask, range: _toRelativeNSRange( aRange ?? startIndex..<endIndex ) ) ) } // - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex /// Returns the range in the `String` of the composed /// character sequence located at a given index. public func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> { return _range( _ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset)) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. public func rangeOfComposedCharacterSequences< R : RangeExpression >( for range: R ) -> Range<Index> where R.Bound == Index { // Theoretically, this will be the identity function. In practice // I think users will be able to observe differences in the input // and output ranges due (if nothing else) to locale changes return _range( _ns.rangeOfComposedCharacterSequences( for: _toRelativeNSRange(range.relative(to: self)))) } // - (NSRange)rangeOfString:(NSString *)aString // // - (NSRange) // rangeOfString:(NSString *)aString options:(StringCompareOptions)mask // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)aRange // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)searchRange // locale:(Locale *)locale /// Finds and returns the range of the first occurrence of a /// given string within a given range of the `String`, subject to /// given options, using the specified locale, if any. public func range< T : StringProtocol >( of aString: T, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { let aString = aString._ephemeralString return _optionalRange( locale != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ), locale: locale ) : searchRange != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange(searchRange!) ) : !mask.isEmpty ? _ns.range(of: aString, options: mask) : _ns.range(of: aString) ) } // - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Finds and returns the range of the first occurrence of a given string, /// taking the current locale into account. Returns `nil` if the string was /// not found. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardRange< T : StringProtocol >(of string: T) -> Range<Index>? { return _optionalRange( _ns.localizedStandardRange(of: string._ephemeralString)) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` using a given /// encoding to determine the percent escapes necessary to convert /// the `String` into a legal URL string. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.") public func addingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.addingPercentEscapes(using: encoding.rawValue) } #endif //===--- From the 10.10 release notes; not in public documentation ------===// // No need to make these unavailable on earlier OSes, since they can // forward trivially to rangeOfString. /// Returns `true` iff `other` is non-empty and contained within /// `self` by case-sensitive, non-literal search. /// /// Equivalent to `self.rangeOfString(other) != nil` public func contains<T : StringProtocol>(_ other: T) -> Bool { let r = self.range(of: other) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.contains(other._ephemeralString)) } return r } /// Returns a Boolean value indicating whether the given string is non-empty /// and contained within this string by case-insensitive, non-literal /// search, taking into account the current locale. /// /// Locale-independent case-insensitive operation, and other needs, can be /// achieved by calling `range(of:options:range:locale:)`. /// /// Equivalent to: /// /// range(of: other, options: .caseInsensitiveSearch, /// locale: Locale.current) != nil public func localizedCaseInsensitiveContains< T : StringProtocol >(_ other: T) -> Bool { let r = self.range( of: other, options: .caseInsensitive, locale: Locale.current ) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.localizedCaseInsensitiveContains(other._ephemeralString)) } return r } } // Deprecated slicing extension StringProtocol where Index == String.Index { // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range from' operator.") public func substring(from index: Index) -> String { return _ns.substring(from: index.encodedOffset) } // - (NSString *)substringToIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` up to, but not including, the one at a given index. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range upto' operator.") public func substring(to index: Index) -> String { return _ns.substring(to: index.encodedOffset) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript.") public func substring(with aRange: Range<Index>) -> String { return _ns.substring(with: _toRelativeNSRange(aRange)) } } extension StringProtocol { // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public var fileSystemRepresentation: [CChar] { fatalError("unavailable function can't be called") } // - (BOOL) // getFileSystemRepresentation:(char *)buffer // maxLength:(NSUInteger)maxLength /// Interprets the `String` as a system-independent path and /// fills a buffer with a C-string in a format and encoding suitable /// for use with file-system calls. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public func getFileSystemRepresentation( _ buffer: inout [CChar], maxLength: Int) -> Bool { fatalError("unavailable function can't be called") } //===--- Kept for consistency with API review results 5/20/2014 ---------===// // We decided to keep pathWithComponents, so keeping this too // @property NSString lastPathComponent; /// Returns the last path component of the `String`. @available(*, unavailable, message: "Use lastPathComponent on URL instead.") public var lastPathComponent: String { fatalError("unavailable function can't be called") } //===--- Renamed by agreement during API review 5/20/2014 ---------------===// // @property NSUInteger length; /// Returns the number of Unicode characters in the `String`. @available(*, unavailable, message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count") public var utf16Count: Int { fatalError("unavailable function can't be called") } // @property NSArray* pathComponents /// Returns an array of NSString objects containing, in /// order, each path component of the `String`. @available(*, unavailable, message: "Use pathComponents on URL instead.") public var pathComponents: [String] { fatalError("unavailable function can't be called") } // @property NSString* pathExtension; /// Interprets the `String` as a path and returns the /// `String`'s extension, if any. @available(*, unavailable, message: "Use pathExtension on URL instead.") public var pathExtension: String { fatalError("unavailable function can't be called") } // @property NSString *stringByAbbreviatingWithTildeInPath; /// Returns a new string that replaces the current home /// directory portion of the current path with a tilde (`~`) /// character. @available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.") public var abbreviatingWithTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathComponent:(NSString *)aString /// Returns a new string made by appending to the `String` a given string. @available(*, unavailable, message: "Use appendingPathComponent on URL instead.") public func appendingPathComponent(_ aString: String) -> String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathExtension:(NSString *)ext /// Returns a new string made by appending to the `String` an /// extension separator followed by a given extension. @available(*, unavailable, message: "Use appendingPathExtension on URL instead.") public func appendingPathExtension(_ ext: String) -> String? { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingLastPathComponent; /// Returns a new string made by deleting the last path /// component from the `String`, along with any final path /// separator. @available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.") public var deletingLastPathComponent: String { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingPathExtension; /// Returns a new string made by deleting the extension (if /// any, and only the last) from the `String`. @available(*, unavailable, message: "Use deletingPathExtension on URL instead.") public var deletingPathExtension: String { fatalError("unavailable function can't be called") } // @property NSString* stringByExpandingTildeInPath; /// Returns a new string made by expanding the initial /// component of the `String` to its full path value. @available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.") public var expandingTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *) // stringByFoldingWithOptions:(StringCompareOptions)options // locale:(Locale *)locale @available(*, unavailable, renamed: "folding(options:locale:)") public func folding( _ options: String.CompareOptions = [], locale: Locale? ) -> String { fatalError("unavailable function can't be called") } // @property NSString* stringByResolvingSymlinksInPath; /// Returns a new string made from the `String` by resolving /// all symbolic links and standardizing path. @available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.") public var resolvingSymlinksInPath: String { fatalError("unavailable property") } // @property NSString* stringByStandardizingPath; /// Returns a new string made by removing extraneous path /// components from the `String`. @available(*, unavailable, message: "Use standardizingPath on URL instead.") public var standardizingPath: String { fatalError("unavailable function can't be called") } // - (NSArray *)stringsByAppendingPaths:(NSArray *)paths /// Returns an array of strings made by separately appending /// to the `String` each string in a given array. @available(*, unavailable, message: "Map over paths with appendingPathComponent instead.") public func strings(byAppendingPaths paths: [String]) -> [String] { fatalError("unavailable function can't be called") } } // Pre-Swift-3 method names extension String { @available(*, unavailable, renamed: "localizedName(of:)") public static func localizedNameOfStringEncoding( _ encoding: String.Encoding ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func pathWithComponents(_ components: [String]) -> String { fatalError("unavailable function can't be called") } // + (NSString *)pathWithComponents:(NSArray *)components /// Returns a string built from the strings in a given array /// by concatenating them with a path separator between each pair. @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func path(withComponents components: [String]) -> String { fatalError("unavailable function can't be called") } } extension StringProtocol { @available(*, unavailable, renamed: "canBeConverted(to:)") public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "capitalizedString(with:)") public func capitalizedStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "commonPrefix(with:options:)") public func commonPrefixWith( _ aString: String, options: String.CompareOptions) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)") public func completePathInto( _ outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedByCharactersIn( _ separator: CharacterSet ) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedBy(_ separator: String) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "cString(usingEncoding:)") public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)") public func dataUsingEncoding( _ encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)") public func enumerateLinguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)") public func enumerateSubstringsIn( _ range: Range<Index>, options opts: String.EnumerationOptions = [], _ body: ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") public func getBytes( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)") public func getLineStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)") public func getParagraphStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lengthOfBytes(using:)") public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lineRange(for:)") public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)") public func linguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil ) -> [String] { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "lowercased(with:)") public func lowercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "maximumLengthOfBytes(using:)") public func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "paragraphRange(for:)") public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)") public func rangeOfCharacterFrom( _ aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)") public func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)") public func rangeOfComposedCharacterSequencesFor( _ range: Range<Index> ) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "range(of:options:range:locale:)") public func rangeOf( _ aString: String, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "localizedStandardRange(of:)") public func localizedStandardRangeOf(_ string: String) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)") public func addingPercentEncodingWithAllowedCharacters( _ allowedCharacters: CharacterSet ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEscapes(using:)") public func addingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "appendingFormat") public func stringByAppendingFormat( _ format: String, _ arguments: CVarArg... ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "padding(toLength:with:startingAt:)") public func byPaddingToLength( _ newLength: Int, withString padString: String, startingAt padIndex: Int ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingCharacters(in:with:)") public func replacingCharactersIn( _ range: Range<Index>, withString replacement: String ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)") public func replacingOccurrencesOf( _ target: String, withString replacement: String, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)") public func replacingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "trimmingCharacters(in:)") public func byTrimmingCharactersIn(_ set: CharacterSet) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "strings(byAppendingPaths:)") public func stringsByAppendingPaths(_ paths: [String]) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(from:)") public func substringFrom(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(to:)") public func substringTo(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(with:)") public func substringWith(_ aRange: Range<Index>) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "uppercased(with:)") public func uppercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(toFile:atomically:encoding:)") public func writeToFile( _ path: String, atomically useAuxiliaryFile:Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(to:atomically:encoding:)") public func writeToURL( _ url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } }
apache-2.0
f6814cc5f0068a469b66259125e2374d
34.442343
279
0.677078
4.781816
false
false
false
false
lieven/fietsknelpunten-ios
App/Extensions/UIViewController+PhotosAuthorization.swift
1
1821
// // UIViewController+PhotosAuthorization.swift // Fietsknelpunten // // Created by Lieven Dekeyser on 14/11/16. // Copyright © 2016 Fietsknelpunten. All rights reserved. // import UIKit import Photos extension UIViewController { func checkPhotosAuthorization(denied: (()->())? = nil, authorized: @escaping ()->()) { let status = PHPhotoLibrary.authorizationStatus() let handleDeterminedStatus = { [weak self] (status: PHAuthorizationStatus) in switch status { case .authorized: authorized() case .restricted: fallthrough case .denied: if let denied = denied { denied() } else { self?.showPhotosAuthorizationDeniedAlert() } default: break } } if status == .notDetermined { PHPhotoLibrary.requestAuthorization(handleDeterminedStatus) } else { handleDeterminedStatus(status) } } private func showPhotosAuthorizationDeniedAlert() { let title = NSLocalizedString("PHOTOS_DENIED_TITLE", value: "Photos Access Disabled", comment: "Title for the alert shown when a user wants to use photos from their library but has previously denied access. Should be short.") let message = NSLocalizedString("PHOTOSO_DENIED_MESSAGE", value: "Photo library access is disabled for this application. You can change this in Settings > Privacy > Photos", comment: "Alert message shown when a user wants to use photos from their library but has previously denied access") let OK = NSLocalizedString("OK_BUTTON", value: "OK", comment: "OK Button. Should be very short.") let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: OK, style: .default, handler: nil)) present(alert, animated: true, completion: nil) } }
mit
83afb408f0904ec8e087ad2c236542c8
26.575758
291
0.701648
4.080717
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 11/Builder/Builder/Food.swift
1
1276
class Burger { let customerName:String; let veggieProduct:Bool; let patties:Int; let pickles:Bool; let mayo:Bool; let ketchup:Bool; let lettuce:Bool; let cook:Cooked; let bacon:Bool; enum Cooked : String { case RARE = "Rare"; case NORMAL = "Normal"; case WELLDONE = "Well Done"; } init(name:String, veggie:Bool, patties:Int, pickles:Bool, mayo:Bool, ketchup:Bool, lettuce:Bool, cook:Cooked, bacon:Bool) { self.customerName = name; self.veggieProduct = veggie; self.patties = patties; self.pickles = pickles; self.mayo = mayo; self.ketchup = ketchup; self.lettuce = lettuce; self.cook = cook; self.bacon = bacon; } func printDescription() { println("Name \(self.customerName)"); println("Veggie: \(self.veggieProduct)"); println("Patties: \(self.patties)"); println("Pickles: \(self.pickles)"); println("Mayo: \(self.mayo)"); println("Ketchup: \(self.ketchup)"); println("Lettuce: \(self.lettuce)"); println("Cook: \(self.cook.rawValue)"); println("Bacon: \(self.bacon)"); } }
mit
9e36e44621410429c18613f0d71a50ca
28.674419
72
0.547022
3.486339
false
false
false
false
daniel-c/iSimulatorExplorer
iSimulatorExplorer/DCImportCertificateWindowController.swift
1
5855
// // DCImportCertificateWindowController.swift // iSimulatorExplorer // // Created by Daniel Cerutti on 11.10.14. // Copyright (c) 2014 Daniel Cerutti. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // import Cocoa class DCImportCertificateWindowController: NSWindowController, NSWindowDelegate, NSTableViewDelegate, NSTableViewDataSource, NSTextFieldDelegate, NSURLConnectionDelegate, NSURLConnectionDataDelegate { @IBOutlet weak var urlTextField: NSTextField! @IBOutlet weak var infoTextField: NSTextField! @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var importButton: NSButton! @IBOutlet weak var getServerDataButton: NSButton! private var certificates : [SecCertificate]? var certificate : SecCertificate? override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. self.window!.delegate = self enableButtons() enableGetServerDataButton() } func enableButtons() { importButton.isEnabled = (tableView.selectedRow >= 0) } func enableGetServerDataButton() { getServerDataButton.isEnabled = (urlTextField.stringValue != "") } @IBAction func cancelButtonPressed(_ sender: AnyObject) { NSApplication.shared().stopModal(withCode: 1) window!.close(); } func windowShouldClose(_ sender: Any) -> Bool { NSApplication.shared().stopModal(withCode: 2) return true } @IBAction func importButtonPressed(_ sender: AnyObject) { if tableView.selectedRow >= 0 { certificate = certificates?[tableView.selectedRow] } NSApplication.shared().stopModal(withCode: 0) window!.close(); } @IBAction func getServerDataButtonPressed(_ sender: AnyObject) { if let url = URL(string: "https://" + urlTextField.stringValue) { print("url scheme: \(url.scheme) absolute: \(url.absoluteString)", terminator: "\n") let request = URLRequest(url: url) if let connection = NSURLConnection(request: request, delegate: self, startImmediately: false) { connection.schedule(in: RunLoop.current, forMode: RunLoopMode.commonModes) connection.start() print("Connection started", terminator: "\n") infoTextField.stringValue = "Connecting..." } } } func connection(_ connection: NSURLConnection, didFailWithError error: Error) { infoTextField.textColor = NSColor.red infoTextField.stringValue = error.localizedDescription } func connectionDidFinishLoading(_ connection: NSURLConnection) { infoTextField.textColor = NSColor.textColor infoTextField.stringValue = "Successful" } func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge) { NSLog("willSendRequestForAuthenticationChallenge for \(challenge.protectionSpace.authenticationMethod)") if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let serverTrust = challenge.protectionSpace.serverTrust { var evaluateResult : SecTrustResultType = .invalid; let status = SecTrustEvaluate(serverTrust, &evaluateResult); if (status == errSecSuccess) && (evaluateResult == .proceed || evaluateResult == .unspecified ) { NSLog("Certificate is trusted") } else { NSLog("Certificate is not trusted") } certificates = [SecCertificate]() let certCount = SecTrustGetCertificateCount(serverTrust) NSLog("number certificate in serverTrust: \(certCount)"); for index in 0 ..< certCount { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, index) { let summary = SecCertificateCopySubjectSummary(serverCertificate) NSLog(" server certificate: \(summary)") let cdata = SecCertificateCopyData(serverCertificate) if let cert = SecCertificateCreateWithData(nil, cdata) { certificates!.append(cert) } } } tableView.reloadData() enableButtons() } } challenge.sender?.performDefaultHandling!(for: challenge) } func numberOfRows(in tableView: NSTableView) -> Int { return certificates?.count ?? 0 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if let result = tableView.make(withIdentifier: "DataCell", owner: self) as? NSTableCellView { if certificates != nil { let summary = SecCertificateCopySubjectSummary(certificates![row]) as String result.textField!.stringValue = summary } return result } return nil } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return nil; } func tableViewSelectionDidChange(_ notification: Notification) { enableButtons() } override func controlTextDidChange(_ obj: Notification) { enableGetServerDataButton() } }
mit
bbb0c0e9d05611a33e5075568fed61ad
37.519737
200
0.618275
5.932118
false
false
false
false
ypopovych/Boilerplate
Sources/Boilerplate/Null.swift
1
1587
//===--- Null.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 public enum Null { case null } extension Null : ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = .null } } public protocol NullEquatable { static func ==(lhs: Self, rhs: Null) -> Bool } public func !=<NC : NullEquatable>(lhs: NC, rhs: Null) -> Bool { return !(lhs == rhs) } public func ==<T : NullEquatable>(lhs: Optional<T>, rhs: Null) -> Bool { return lhs.map { value in value == rhs } ?? true } public func !=<T : NullEquatable>(lhs: Optional<T>, rhs: Null) -> Bool { return !(lhs == rhs) } public func ==<T>(lhs: T?, rhs: Null) -> Bool { return lhs == nil } public func !=<T>(lhs: T?, rhs: Null) -> Bool { return lhs != nil } extension Null : NullEquatable { } public func ==(lhs: Null, rhs: Null) -> Bool { return lhs == rhs }
apache-2.0
00df85cd67cfb47d4299a990b7b35805
25.45
80
0.597353
3.987437
false
false
false
false
marsal-silveira/iStackOS
iStackOS/src/Utils/Utils.swift
1
3893
// // Utils.swift // iStackOS // // Created by Marsal on 13/03/16. // Copyright © 2016 Marsal Silveira. All rights reserved. // import UIKit struct Utils { private enum DateType { case Asked case Answered } static func showSimpleAlertWithTitle(title: String!, message: String, viewController: UIViewController) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Cancel, handler: nil) alert.addAction(action) viewController.presentViewController(alert, animated: true, completion: nil) } static func getDisplayForAskedDate(askedDate: NSDate) -> String? { return getDisplayForDate(.Asked, date: askedDate) } static func getDisplayAnsweredDate(answeredDate: NSDate) -> String? { return getDisplayForDate(.Answered, date: answeredDate) } private static func getDisplayForDate(dateType: DateType, date: NSDate) -> String? { var result: String? = nil; // if asked today = "Asked XX hours ago" if (date.dateToString() == NSDate().dateToString()) { let calendar = NSCalendar.currentCalendar() // get creation and current hour and minute var components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date) let creationHour = components.hour let creationMinute = components.minute components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: NSDate()) let currentHour = components.hour let currentMinute = components.minute // var period = 0 var periodStr: String! = nil if (creationHour != currentHour) { period = currentHour-creationHour periodStr = "\(period) \(period == 1 ? NSLocalizedString("[hour]", comment: "") : NSLocalizedString("[hours]", comment: ""))" } else { period = currentMinute-creationMinute periodStr = "\(period) \(period == 1 ? NSLocalizedString("[minute]", comment: "") : NSLocalizedString("[minutes]", comment: ""))" } result = dateType == .Asked ? "[Asked Today]" : "[Answered Today]" result = String.localizedStringWithFormat(NSLocalizedString(result!, comment: ""), periodStr) } // if asked yesterday = "Asked yesterday at hh:mm:ss" else if (date.dateToString() == Utils.getYesterday().dateToString()) { result = dateType == .Asked ? "[Asked Yesterday]" : "[Answered Yesterday]" result = String.localizedStringWithFormat(NSLocalizedString(result!, comment: ""), date.timeToString()) } // otherwise = "Asked at dd de MMMM de yyyy" else { let formatter = NSDateFormatter() formatter.dateStyle = NSDateFormatterStyle.MediumStyle formatter.timeStyle = NSDateFormatterStyle.ShortStyle result = dateType == .Asked ? "[Asked Month]" : "[Answered Month]" result = String.localizedStringWithFormat(NSLocalizedString(result!, comment: ""), formatter.stringFromDate(date)) } return result; } private static func getYesterday() -> NSDate { let now = NSDate() let components = NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: now) components.day = -1 // create a calendar and return yesterday NSDate value let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) return (gregorian?.dateByAddingComponents(components, toDate: now, options:NSCalendarOptions(rawValue: 0)))! } }
mit
413313a32a9841c36a9d8d6e0ce7230e
39.978947
145
0.617677
5.141347
false
false
false
false
honghaoz/FidoUsage
FidoUsage/FidoUsage/FidoUsage/Components/Login/LoginViewController.swift
1
3360
// // LoginViewController.swift // FidoUsage // // Created by Honghao Zhang on 2015-09-22. // Copyright © 2015 Honghao Zhang. All rights reserved. // import UIKit import Client import ChouTi import LTMorphingLabel class LoginViewController: UIViewController { @IBOutlet weak var numberField: TextField! @IBOutlet weak var passwordField: TextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var separatorView: UIView! @IBOutlet weak var separatorViewHeightConstraint: NSLayoutConstraint! let user = Locator.user let animator = DropPresentingAnimator() override func viewDidLoad() { super.viewDidLoad() animator.animationDuration = 0.75 animator.shouldDismissOnTappingOutsideView = false animator.presentingViewSize = CGSize(width: ceil(screenWidth * 0.7), height: 160) setupViews() loadFromUser() } private func setupViews() { view.layer.cornerRadius = 10.0 numberField.layer.cornerRadius = 4.0 numberField.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) passwordField.layer.cornerRadius = 4.0 passwordField.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) view.clipsToBounds = false view.layer.shadowColor = UIColor.blackColor().CGColor view.layer.shadowOffset = CGSizeZero view.layer.shadowRadius = 15.0 view.layer.shadowOpacity = 0.8 numberField.keyboardType = .PhonePad numberField.font = UIFont.systemFontOfSize(20) passwordField.secureTextEntry = true passwordField.font = UIFont.systemFontOfSize(20) separatorViewHeightConstraint.constant = 0.5 separatorView.backgroundColor = UIColor(white: 0.9, alpha: 1.0) loginButton.titleLabel?.tintColor = UIColor.fidoTealColor() view.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.layer.shadowPath = UIBezierPath(rect: view.bounds).CGPath } private func loadFromUser() { if user.load() { numberField.text = user.number passwordField.text = user.password } } @IBAction func loginButtonTapped(sender: UIButton) { guard let number = numberField.text, password = passwordField.text where !number.isEmpty && !password.isEmpty else { log.error("Number/Password invalid") return } log.info("Login with number: \(number)") Locator.client.loginWithNumber(number, password: password) {[unowned self] (succeed, resultDict) in if succeed { log.debug("Login Results: \(resultDict)") self.user.isLoggedIn = true self.user.number = number self.user.password = password self.user.save() self.dismissViewControllerAnimated(true, completion: {_ in Locator.usageContainerViewController.loadData() }) } else { log.error("Login failed") } } } } extension LoginViewController : UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = true return animator } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = false return animator } }
mit
3f5bd1bf47a6fecbf45d28fc9f0960e8
27.956897
214
0.745758
4.193508
false
false
false
false
plenprojectcompany/plen-Scenography_iOS
PLENConnect/Connect/Entities/PlenFunction.swift
1
569
// // PlenFunction.swift // Scenography // // Created by PLEN Project on 2016/03/08. // Copyright © 2016年 PLEN Project. All rights reserved. // import Foundation struct PlenFunction: Hashable { var motion: PlenMotion var loopCount: Int var hashValue: Int { return HashableUtil.combine(motion.hashValue, loopCount) } static let Nop = PlenFunction(motion: PlenMotion.None, loopCount: 0) } func ==(lhs: PlenFunction, rhs: PlenFunction) -> Bool { return lhs.motion == rhs.motion && lhs.loopCount == rhs.loopCount }
mit
489ab918aa789afba90152c4e6df81c2
20.769231
72
0.671378
3.773333
false
false
false
false
samantharachelb/todolist
todolist/View Controllers/HomeViewController.swift
1
7511
// // HomeViewController.swift // todolist // // Created by Samantha Emily-Rachel Belnavis on 2017-10-02. // Copyright © 2017 Samantha Emily-Rachel Belnavis. All rights reserved. // import Foundation import UIKit import Firebase import GoogleSignIn import HealthKit import SwiftyPlistManager import Alamofire import AlamofireImage class HomeViewController: UINavigationController, UINavigationControllerDelegate, GIDSignInUIDelegate{ // global variables var plistManager = SwiftyPlistManager.shared var userPrefs = "UserPrefs" var themesPlist = "ThemesList" var couldConnect: Bool! // true: display debugging information // false: don't display debugging information var debugMode: Bool = true // user info and preferences var userID = String() var userName = String() var userNameLabel: UILabel? var userEmail = String() //var userPhoto: UIImageView? var userPhotoUrl: URL! var userAvatarButtonItem: UIBarButtonItem! var userGender = String() var userSelectedTheme = String() var hasRunBefore = Bool() // style preferences var headerBarColour = String() var headerTextColour = String() var bodyTextColour = "0x3E3C3D" var textHighlightColour = String() var highlightedTextColour = String() // database reference var databaseRef: DatabaseReference! // link to AppDelgate let appDelegate = UIApplication.shared.delegate as! AppDelegate // MARK: Properties @IBOutlet weak var navItem: UINavigationItem? @IBOutlet weak var userAvatarButton: UIBarButtonItem! @IBOutlet weak var userNameButton: UIBarButtonItem! @IBOutlet weak var settingsButton: UIBarButtonItem! private enum IdentifyingDataFields: Int { case DateOfBirth, BiologicalSex func data() -> (title: String, value: String?) { let healthKitManager = HealthKitManager.sharedInstance switch self { case .DateOfBirth: return("Date of Birth", healthKitManager.dateOfBirth) case .BiologicalSex: return("Gender" , healthKitManager.biologicalSex) } } } // check if we can reach the internet func checkInternet() { guard let status = Network.reachability?.status else { return } switch status { case .unreachable: print("Internet unreachable") return couldConnect = false case .wifi: print("Internet reachable") return couldConnect = true case .wwan: print("Internet reachable") return couldConnect = true } } override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().signInSilently() // get theme name from plist guard let themeName = plistManager.fetchValue(for: "selectedAppTheme", fromPlistWithName: userPrefs) as! String! else { return } // get colours from the respective theme guard let headerBarColour = plistManager.fetchValue(for: "headerBarColour", fromPlistWithName: themeName) as! String! else { return } guard let headerTextColour = plistManager.fetchValue(for: "headerTextColour", fromPlistWithName: themeName) as! String! else { return } // check if we should use the "light" status bar or not guard let statusBarCheck = plistManager.fetchValue(for: "useLightStatusBar", fromPlistWithName: themeName) as! Bool! else { return } if (statusBarCheck) { UIApplication.shared.statusBarStyle = .lightContent } view.backgroundColor = UIColor.white let homeViewTableViewController = storyboard?.instantiateViewController(withIdentifier: "HomeViewTableViewController") as! HomeViewTableViewController } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // database reference databaseRef = Database.database().reference() if (GIDSignIn.sharedInstance().hasAuthInKeychain()) { retrieveUserInfo() Alamofire.request(userPhotoUrl).responseImage { response in debugPrint(response) print(response.request) print(response.response) debugPrint(response.result) if let image = response.result.value { print("image downloaded: \(image)") //let circleAvatar = image.af_imageRoundedIntoCircle() let photoSize = CGSize(width: 30, height: 30) let scaledToFit = image.af_imageAspectScaled(toFit: photoSize) let circleAvatar = scaledToFit.af_imageRoundedIntoCircle() let userAvatarButton: UIButton = UIButton(type: UIButtonType.custom) userAvatarButton.setImage(circleAvatar, for: UIControlState.normal) userAvatarButton.addTarget(self, action: #selector(HomeViewController.userInfoButtonsPressed), for: UIControlEvents.touchUpInside) userAvatarButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34) //userAvatarButton.contentMode = .scaleAspectFit let userAvatarButtonItem = UIBarButtonItem(customView: userAvatarButton) let userNameButton: UIButton = UIButton(type: UIButtonType.custom) userNameButton.setTitle(self.userName, for: UIControlState.normal) userNameButton.titleLabel?.textColor = UIColor().hexToColour(hexString: self.headerTextColour) userNameButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) userNameButton.addTarget(self, action: #selector(HomeViewController.userInfoButtonsPressed), for: UIControlEvents.touchUpInside) let userNameButtonItem = UIBarButtonItem(customView: userNameButton) self.navItem?.leftBarButtonItems = [userAvatarButtonItem, userNameButtonItem] } } let settingsButton: UIButton = UIButton(type: UIButtonType.custom) settingsButton.setImage(UIImage(named: "settings"), for: UIControlState.normal) settingsButton.addTarget(self, action: #selector(HomeViewController.settingsButtonPressed), for: UIControlEvents.touchUpInside) settingsButton.tintColor = UIColor().hexToColour(hexString: self.headerTextColour) settingsButton.frame = CGRect(x: 0, y:0, width: 10, height: 10) settingsButton.contentMode = .scaleAspectFit let settingsButtonItem = UIBarButtonItem(customView: settingsButton) self.navItem?.rightBarButtonItem = settingsButtonItem } } // left navbar item action controller func userInfoButtonsPressed() { performSegue(withIdentifier: "goToProfile", sender: self) } func settingsButtonPressed() { print("Settings button was pressed") performSegue(withIdentifier: "goToSettings", sender: self) } // retrieve user data func retrieveUserInfo() { userID = plistManager.fetchValue(for: "userID", fromPlistWithName: userPrefs) as! String! userName = plistManager.fetchValue(for: "userName", fromPlistWithName: userPrefs) as! String! userEmail = plistManager.fetchValue(for: "userEmail", fromPlistWithName: userPrefs) as! String! userPhotoUrl = URL(string: plistManager.fetchValue(for: "userPhoto", fromPlistWithName: userPrefs) as! String!) // display debugging information if (debugMode == true) { debugPrint("stored user id: " + userID) debugPrint("stored user name: " + userName) debugPrint("stored user email: " + userEmail) debugPrint("stored user photo url: \(String(describing: userPhotoUrl!))") } } @IBAction func unwindToHomeVC(segue:UIStoryboardSegue) {} }
mit
3cbe7653bda55ae3cf242b84336f36d5
36.55
154
0.711451
4.947299
false
false
false
false
Daij-Djan/GitLogView
GitLogView/GTTreeEntry+EntryWithSHA.swift
1
1530
// // GTTreeEntry+EntryWithSHA.swift // GitLogView // // Created by Dominik Pich on 11/24/15. // Copyright © 2015 Dominik Pich. All rights reserved. // import Foundation import ObjectiveGit extension GTTree { /// Get an entry by it's BLOBs sha /// /// SHA - the SHA of the entry's blob /// /// returns a GTTreeEntry and its relative path or nil if there is nothing with the specified Blob SHA public func entryWithBlobSHA(SHA: String) -> (GTTreeEntry, String)? { var item : GTTreeEntry? var path : String? do { try self.enumerateEntriesWithOptions(GTTreeEnumerationOptions.Post, block: { (entry, relativePath, stopPointer) -> Bool in guard entry.type == .Blob else { return false; } let entryPath = relativePath.stringByAppendingString(entry.name) do { let obj = try entry.GTObject() let sha2 = obj.SHA if SHA == sha2 { item = entry path = entryPath stopPointer.memory = true return true } } catch { } return false }) } catch { } if item != nil && path != nil { return (item!, path!) } return nil } }
mit
1dea8cc4683b940d7aa23b5617519b49
26.321429
134
0.469588
4.916399
false
false
false
false
vishalvshekkar/realmDemo
RealmDemo/ContactsTableViewCell.swift
1
985
// // ContactsTableViewCell.swift // RealmDemo // // Created by Vishal V Shekkar on 10/08/16. // Copyright © 2016 Vishal. All rights reserved. // import UIKit class ContactsTableViewCell: UITableViewCell { @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var otherLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() leftImageView.layer.cornerRadius = 26.5 leftImageView.layer.borderColor = UIColor(colorType: .PinkishRed).CGColor leftImageView.layer.borderWidth = 1 self.backgroundColor = UIColor.clearColor() } override func setHighlighted(highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) if highlighted { self.backgroundColor = UIColor(colorType: .PinkishRedWith15Alpha) } else { self.backgroundColor = UIColor.clearColor() } } }
mit
4aad23da604629a73b65388f0c98c40f
27.941176
81
0.676829
4.619718
false
false
false
false
merlos/iOS-Open-GPX-Tracker
Pods/CoreGPX/Classes/GPXPoint.swift
1
2474
// // GPXPoint.swift // GPXKit // // Created by Vincent on 23/11/18. // import Foundation /** * This class (`ptType`) is added to conform with the GPX v1.1 schema. `ptType` of GPX schema. Not supported in GPXRoot, nor GPXParser's parsing. */ open class GPXPoint: GPXElement, Codable { /// Elevation Value in (metre, m) public var elevation: Double? /// Time/Date of creation public var time: Date? /// Latitude of point public var latitude: Double? /// Longitude of point public var longitude: Double? // MARK:- Instance /// Default Initializer. required public init() { super.init() } /// Initialize with latitude and longitude public init(latitude: Double, longitude: Double) { super.init() self.latitude = latitude self.longitude = longitude } /// Inits native element from raw parser value /// /// - Parameters: /// - raw: Raw element expected from parser init(raw: GPXRawElement) { self.latitude = Convert.toDouble(from: raw.attributes["lat"]) self.longitude = Convert.toDouble(from: raw.attributes["lon"]) for child in raw.children { switch child.name { case "ele": self.elevation = Convert.toDouble(from: child.text) case "time": self.time = GPXDateParser().parse(date: child.text) default: continue } } } // MARK:- Tag override func tagName() -> String { return "pt" } // MARK: GPX override func addOpenTag(toGPX gpx: NSMutableString, indentationLevel: Int) { let attribute = NSMutableString(string: "") if let latitude = latitude { attribute.append(" lat=\"\(latitude)\"") } if let longitude = longitude { attribute.append(" lon=\"\(longitude)\"") } gpx.appendOpenTag(indentation: indent(forIndentationLevel: indentationLevel), tag: tagName(), attribute: attribute) } override func addChildTag(toGPX gpx: NSMutableString, indentationLevel: Int) { super.addChildTag(toGPX: gpx, indentationLevel: indentationLevel) self.addProperty(forDoubleValue: elevation, gpx: gpx, tagName: "ele", indentationLevel: indentationLevel) self.addProperty(forValue: Convert.toString(from: time), gpx: gpx, tagName: "time", indentationLevel: indentationLevel) } }
gpl-3.0
7fe36b40708d777f66c46cb882ed7c8e
29.170732
127
0.613581
4.514599
false
false
false
false
OperatorFoundation/Postcard
Postcard/Postcard/Controllers/ViewControllers/PenPalsViewController.swift
1
6821
// // PenPalsViewController.swift // Postcard // // Created by Adelita Schule on 5/13/16. // Copyright © 2016 operatorfoundation.org. All rights reserved. // import Cocoa class PenPalsViewController: NSViewController, NSTableViewDelegate { @IBOutlet weak var penPalsTableView: NSTableView! @IBOutlet var penPalsArrayController: NSArrayController! var managedContext = (NSApplication.shared.delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() //Setup Array Controller Contents if let currentUser = GlobalVars.currentUser { let predicate = NSPredicate(format: "owner == %@", currentUser) penPalsArrayController.fetchPredicate = predicate let hasKeySortDescriptor = NSSortDescriptor(key: "key", ascending: false) let invitedSortDescriptor = NSSortDescriptor(key: "sentKey", ascending: false) let nameSortDescriptor = NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:))) let emailSortDescriptor = NSSortDescriptor(key: "email", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:))) penPalsArrayController.sortDescriptors = [hasKeySortDescriptor, invitedSortDescriptor, nameSortDescriptor, emailSortDescriptor] } penPalsTableView.target = self penPalsTableView.doubleAction = #selector(doubleClickComposeEmail) } @objc func doubleClickComposeEmail() { if let thisPenPal = penPalsArrayController.selectedObjects[0] as? PenPal { if thisPenPal.sentKey == true { performSegue(withIdentifier: "Email PenPal", sender: self) } } } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if segue.identifier == "Email PenPal" { if let composeVC = segue.destinationController as? ComposeViewController { if let thisPenPal = penPalsArrayController.selectedObjects[0] as? PenPal { let email = thisPenPal.email composeVC.sendTo = email } } } } } //MARK: TableCellView class PenPalTableCell: NSTableCellView { @IBOutlet weak var nameField: NSTextField! @IBOutlet weak var subtitleLabel: NSTextField! @IBOutlet weak var penPalImageView: NSImageView! @IBOutlet weak var actionButton: NSButton! @IBOutlet weak var backgroundView: DesignableView! var actionTitle = "" var managedContext = (NSApplication.shared.delegate as! AppDelegate).managedObjectContext override var objectValue: Any? { didSet { //Set up the action button based on penpal status if let penPal = objectValue as? PenPal { //Button Appearance let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center var buttonFont = NSFont.boldSystemFont(ofSize: 13) if let maybeFont = NSFont(name: PostcardUI.boldFutura, size: 13) { buttonFont = maybeFont } let attributes = [convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): NSColor.white,convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): paragraphStyle, convertFromNSAttributedStringKey(NSAttributedString.Key.font): buttonFont] let altAttributes = [convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): PostcardUI.blue, convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): paragraphStyle, convertFromNSAttributedStringKey(NSAttributedString.Key.font): buttonFont] if penPal.key != nil && penPal.sentKey == false { //They sent a key, but we have not actionTitle = localizedAddButtonTitle actionButton.image = NSImage(named: "greenButton") actionButton.target = self actionButton.action = #selector(addAction) backgroundView.viewColor = NSColor.white actionButton.isHidden = false } else if penPal.key != nil && penPal.sentKey == true { //They have sent a key and so have we, these are Postcard Contacts actionButton.isHidden = true backgroundView.viewColor = PostcardUI.gray } else //penPal.key == nil && penPal.sentKey == false { //We have not sent an invite, and neither have they actionTitle = localizedInviteButtonTitle actionButton.image = NSImage(named: "redButton") actionButton.target = self actionButton.action = #selector(inviteAction) backgroundView.viewColor = PostcardUI.gray actionButton.isHidden = false } actionButton.attributedTitle = NSAttributedString(string: actionTitle, attributes: convertToOptionalNSAttributedStringKeyDictionary(attributes)) actionButton.attributedAlternateTitle = NSAttributedString(string: actionTitle, attributes: convertToOptionalNSAttributedStringKeyDictionary(altAttributes)) } } } //We already have their key, but they don't have ours @objc func addAction() { //Send key email to this user if let penPal = objectValue as? PenPal { KeyController.sharedInstance.sendKey(toPenPal: penPal) } actionButton.isHidden = true } //We don't have their key, and they don't have ours @objc func inviteAction() { //Send key email to this user if let penPal = objectValue as? PenPal { KeyController.sharedInstance.sendKey(toPenPal: penPal) } actionButton.isHidden = true } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
mit
06a5d7de9a0179073f7a4177324f74cf
40.084337
291
0.631818
5.558272
false
false
false
false
pksprojects/ElasticSwift
Sources/ElasticSwift/Requests/Suggesters.swift
1
58404
// // Suggesters.swift // // // Created by Prafull Kumar Soni on 11/1/20. // import ElasticSwiftCodableUtils import ElasticSwiftCore import ElasticSwiftQueryDSL import Foundation import NIOHTTP1 public protocol SuggestionBuilder: ElasticSwiftTypeBuilder where ElasticSwiftType: Suggestion { var field: String? { get } var text: String? { get } var prefix: String? { get } var regex: String? { get } var analyzer: String? { get } var size: Int? { get } var shardSize: Int? { get } @discardableResult func set(field: String) -> Self @discardableResult func set(text: String) -> Self @discardableResult func set(prefix: String) -> Self @discardableResult func set(regex: String) -> Self @discardableResult func set(analyzer: String) -> Self @discardableResult func set(size: Int) -> Self @discardableResult func set(shardSize: Int) -> Self } public protocol Suggestion: Codable { var suggestionType: SuggestionType { get } var field: String { get } var text: String? { get set } var prefix: String? { get set } var regex: String? { get set } var analyzer: String? { get set } var size: Int? { get set } var shardSize: Int? { get set } func isEqualTo(_ other: Suggestion) -> Bool } public extension Suggestion where Self: Equatable { func isEqualTo(_ other: Suggestion) -> Bool { if let o = other as? Self { return self == o } return false } } public func isEqualSuggestions(_ lhs: Suggestion?, _ rhs: Suggestion?) -> Bool { if lhs == nil, rhs == nil { return true } if let lhs = lhs, let rhs = rhs { return lhs.isEqualTo(rhs) } return false } public enum SuggestionType: String, Codable { case term case phrase case completion } public extension SuggestionType { var metaType: Suggestion.Type { switch self { case .term: return TermSuggestion.self case .phrase: return PhraseSuggestion.self case .completion: return CompletionSuggestion.self } } } public struct SuggestSource { public var globalText: String? public var suggestions: [String: Suggestion] } extension SuggestSource: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) var sDic = [String: Suggestion]() for key in container.allKeys { if key.stringValue == CodingKeys.globalText.rawValue { globalText = try container.decodeStringIfPresent(forKey: .key(named: CodingKeys.globalText.rawValue)) } else { let suggestion = try container.decodeSuggestion(forKey: key) sDic[key.stringValue] = suggestion } } suggestions = sDic } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) try container.encodeIfPresent(globalText, forKey: .key(named: CodingKeys.globalText.rawValue)) for (k, v) in suggestions { try container.encode(v, forKey: .key(named: k)) } } internal enum CodingKeys: String, CodingKey { case globalText = "text" } } extension SuggestSource: Equatable { public static func == (lhs: SuggestSource, rhs: SuggestSource) -> Bool { guard lhs.suggestions.count == rhs.suggestions.count else { return false } return lhs.globalText == rhs.globalText && lhs.suggestions.keys.allSatisfy { rhs.suggestions.keys.contains($0) && isEqualSuggestions(lhs.suggestions[$0], rhs.suggestions[$0]) } } } public class BaseSuggestionBuilder { private var _field: String? private var _text: String? private var _prefix: String? private var _regex: String? private var _analyzer: String? private var _size: Int? private var _shardSize: Int? fileprivate init() {} @discardableResult public func set(field: String) -> Self { _field = field return self } @discardableResult public func set(text: String) -> Self { _text = text return self } @discardableResult public func set(prefix: String) -> Self { _prefix = prefix return self } @discardableResult public func set(regex: String) -> Self { _regex = regex return self } @discardableResult public func set(analyzer: String) -> Self { _analyzer = analyzer return self } @discardableResult public func set(size: Int) -> Self { _size = size return self } @discardableResult public func set(shardSize: Int) -> Self { _shardSize = shardSize return self } public var field: String? { return _field } public var text: String? { return _text } public var prefix: String? { return _prefix } public var regex: String? { return _regex } public var analyzer: String? { return _analyzer } public var size: Int? { return _size } public var shardSize: Int? { return _shardSize } } public class TermSuggestionBuilder: BaseSuggestionBuilder, SuggestionBuilder { public typealias ElasticSwiftType = TermSuggestion private var _sort: TermSuggestion.SortBy? private var _suggestMode: SuggestMode? private var _accuracy: Decimal? private var _maxEdits: Int? private var _maxInspections: Int? private var _maxTermFreq: Decimal? private var _prefixLength: Int? private var _minWordLength: Int? private var _minDocFreq: Decimal? private var _stringDistance: TermSuggestion.StringDistance? override public init() { super.init() } @discardableResult public func set(sort: TermSuggestion.SortBy) -> Self { _sort = sort return self } @discardableResult public func set(suggestMode: SuggestMode) -> Self { _suggestMode = suggestMode return self } @discardableResult public func set(accuracy: Decimal) -> Self { _accuracy = accuracy return self } @discardableResult public func set(maxEdits: Int) -> Self { _maxEdits = maxEdits return self } @discardableResult public func set(maxInspections: Int) -> Self { _maxInspections = maxInspections return self } @discardableResult public func set(maxTermFreq: Decimal) -> Self { _maxTermFreq = maxTermFreq return self } @discardableResult public func set(prefixLength: Int) -> Self { _prefixLength = prefixLength return self } @discardableResult public func set(minWordLength: Int) -> Self { _minWordLength = minWordLength return self } @discardableResult public func set(minDocFreq: Decimal) -> Self { _minDocFreq = minDocFreq return self } @discardableResult public func set(stringDistance: TermSuggestion.StringDistance) -> Self { _stringDistance = stringDistance return self } public var sort: TermSuggestion.SortBy? { return _sort } public var suggestMode: SuggestMode? { return _suggestMode } public var accuracy: Decimal? { return _accuracy } public var maxEdits: Int? { return _maxEdits } public var maxInspections: Int? { return _maxInspections } public var maxTermFreq: Decimal? { return _maxTermFreq } public var prefixLength: Int? { return _prefixLength } public var minWordLength: Int? { return _minWordLength } public var minDocFreq: Decimal? { return _minDocFreq } public var stringDistance: TermSuggestion.StringDistance? { return _stringDistance } public func build() throws -> TermSuggestion { return try TermSuggestion(withBuilder: self) } } public struct TermSuggestion: Suggestion { public let suggestionType: SuggestionType = .term public var field: String public var text: String? public var prefix: String? public var regex: String? public var analyzer: String? public var size: Int? public var shardSize: Int? public var sort: SortBy? public var suggestMode: SuggestMode? public var accuracy: Decimal? public var maxEdits: Int? public var maxInspections: Int? public var maxTermFreq: Decimal? public var prefixLength: Int? public var minWordLength: Int? public var minDocFreq: Decimal? public var stringDistance: StringDistance? public init(field: String, text: String? = nil, prefix: String? = nil, regex: String? = nil, analyzer: String? = nil, size: Int? = nil, shardSize: Int? = nil, sort: SortBy? = nil, suggestMode: SuggestMode? = nil, accuracy: Decimal? = nil, maxEdits: Int? = nil, maxInspections: Int? = nil, maxTermFreq: Decimal? = nil, prefixLength: Int? = nil, minWordLength: Int? = nil, minDocFreq: Decimal? = nil, stringDistance: StringDistance? = nil) { self.field = field self.text = text self.prefix = prefix self.regex = regex self.analyzer = analyzer self.size = size self.shardSize = shardSize self.sort = sort self.suggestMode = suggestMode self.accuracy = accuracy self.maxEdits = maxEdits self.maxInspections = maxInspections self.maxTermFreq = maxTermFreq self.prefixLength = prefixLength self.minWordLength = minWordLength self.minDocFreq = minDocFreq self.stringDistance = stringDistance } internal init(withBuilder builder: TermSuggestionBuilder) throws { guard let field = builder.field else { throw SuggestionBuilderError.missingRequiredField("field") } self.init(field: field, text: builder.text, prefix: builder.prefix, regex: builder.regex, analyzer: builder.analyzer, size: builder.size, shardSize: builder.shardSize, sort: builder.sort, suggestMode: builder.suggestMode, accuracy: builder.accuracy, maxEdits: builder.maxEdits, maxInspections: builder.maxInspections, maxTermFreq: builder.maxTermFreq, prefixLength: builder.prefixLength, minWordLength: builder.minWordLength, minDocFreq: builder.minDocFreq, stringDistance: builder.stringDistance) } } public extension TermSuggestion { init(from decoder: Decoder) throws { let contianer = try decoder.container(keyedBy: DynamicCodingKeys.self) let namedContianer = try contianer.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: suggestionType)) field = try namedContianer.decodeString(forKey: .field) text = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.text.rawValue)) prefix = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.prefix.rawValue)) regex = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.regex.rawValue)) analyzer = try namedContianer.decodeStringIfPresent(forKey: .analyzer) size = try namedContianer.decodeIntIfPresent(forKey: .size) shardSize = try namedContianer.decodeIntIfPresent(forKey: .shardSize) sort = try namedContianer.decodeIfPresent(SortBy.self, forKey: .sort) suggestMode = try namedContianer.decodeIfPresent(SuggestMode.self, forKey: .suggestMode) accuracy = try namedContianer.decodeDecimalIfPresent(forKey: .accuracy) maxEdits = try namedContianer.decodeIntIfPresent(forKey: .maxEdits) maxInspections = try namedContianer.decodeIntIfPresent(forKey: .maxInspections) maxTermFreq = try namedContianer.decodeDecimalIfPresent(forKey: .maxTermFreq) prefixLength = try namedContianer.decodeIntIfPresent(forKey: .prefixLength) minWordLength = try namedContianer.decodeIntIfPresent(forKey: .minWordLength) minDocFreq = try namedContianer.decodeDecimalIfPresent(forKey: .minDocFreq) stringDistance = try namedContianer.decodeIfPresent(StringDistance.self, forKey: .stringDistance) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) try container.encodeIfPresent(text, forKey: .key(named: CodingKeys.text.rawValue)) try container.encodeIfPresent(prefix, forKey: .key(named: CodingKeys.prefix.rawValue)) try container.encodeIfPresent(regex, forKey: .key(named: CodingKeys.regex.rawValue)) var namedContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: suggestionType)) try namedContainer.encode(field, forKey: .field) try namedContainer.encodeIfPresent(analyzer, forKey: .analyzer) try namedContainer.encodeIfPresent(size, forKey: .size) try namedContainer.encodeIfPresent(shardSize, forKey: .shardSize) try namedContainer.encodeIfPresent(sort, forKey: .sort) try namedContainer.encodeIfPresent(suggestMode, forKey: .suggestMode) try namedContainer.encodeIfPresent(accuracy, forKey: .accuracy) try namedContainer.encodeIfPresent(maxEdits, forKey: .maxEdits) try namedContainer.encodeIfPresent(maxInspections, forKey: .maxInspections) try namedContainer.encodeIfPresent(maxTermFreq, forKey: .maxTermFreq) try namedContainer.encodeIfPresent(prefixLength, forKey: .prefixLength) try namedContainer.encodeIfPresent(minWordLength, forKey: .minWordLength) try namedContainer.encodeIfPresent(minDocFreq, forKey: .minDocFreq) try namedContainer.encodeIfPresent(stringDistance, forKey: .stringDistance) } internal enum CodingKeys: String, CodingKey { case field case text case prefix case regex case analyzer case size case shardSize = "shard_size" case sort case suggestMode = "suggest_mode" case accuracy case maxEdits = "max_edits" case maxInspections = "max_inspections" case maxTermFreq = "max_term_freq" case prefixLength = "prefix_length" case minWordLength = "min_word_length" case minDocFreq = "min_doc_freq" case stringDistance = "string_distance" } } public extension TermSuggestion { enum SortBy: String, Codable { case score case frequency } enum StringDistance: String, Codable { case `internal` case damerauLevenshtein = "damerau_levenshtein" case levenshtein case jaroWinkler = "jaro_winkler" case ngram } } extension TermSuggestion: Equatable {} public enum SuggestMode: String, Codable { case missing case popular case always } public enum SuggestionBuilderError: Error { case missingRequiredField(String) } public class PhraseSuggestionBuilder: BaseSuggestionBuilder, SuggestionBuilder { public typealias ElasticSwiftType = PhraseSuggestion private var _maxErrors: Decimal? private var _separator: String? private var _realWordErrorLikelihood: Decimal? private var _confidence: Decimal? private var _gramSize: Int? private var _forceUnigrams: Bool? private var _tokenLimit: Int? private var _highlight: PhraseSuggestion.Highlight? private var _collate: PhraseSuggestion.Collate? private var _smoothing: SmoothingModel? private var _directGenerators: [PhraseSuggestion.DirectCandidateGenerator]? override public init() { super.init() } @discardableResult public func set(maxErrors: Decimal) -> Self { _maxErrors = maxErrors return self } @discardableResult public func set(separator: String) -> Self { _separator = separator return self } @discardableResult public func set(realWordErrorLikelihood: Decimal) -> Self { _realWordErrorLikelihood = realWordErrorLikelihood return self } @discardableResult public func set(confidence: Decimal) -> Self { _confidence = confidence return self } @discardableResult public func set(gramSize: Int) -> Self { _gramSize = gramSize return self } @discardableResult public func set(forceUnigrams: Bool) -> Self { _forceUnigrams = forceUnigrams return self } @discardableResult public func set(tokenLimit: Int) -> Self { _tokenLimit = tokenLimit return self } @discardableResult public func set(highlight: PhraseSuggestion.Highlight) -> Self { _highlight = highlight return self } @discardableResult public func set(collate: PhraseSuggestion.Collate) -> Self { _collate = collate return self } @discardableResult public func set(smoothing: SmoothingModel) -> Self { _smoothing = smoothing return self } @discardableResult public func set(directGenerators: [PhraseSuggestion.DirectCandidateGenerator]) -> Self { _directGenerators = directGenerators return self } @discardableResult public func add(directGenerator: PhraseSuggestion.DirectCandidateGenerator) -> Self { if _directGenerators != nil { _directGenerators?.append(directGenerator) } else { _directGenerators = [directGenerator] } return self } public var maxErrors: Decimal? { return _maxErrors } public var separator: String? { return _separator } public var realWordErrorLikelihood: Decimal? { return _realWordErrorLikelihood } public var confidence: Decimal? { return _confidence } public var gramSize: Int? { return _gramSize } public var forceUnigrams: Bool? { return _forceUnigrams } public var tokenLimit: Int? { return _tokenLimit } public var highlight: PhraseSuggestion.Highlight? { return _highlight } public var collate: PhraseSuggestion.Collate? { return _collate } public var smoothing: SmoothingModel? { return _smoothing } public var directGenerators: [PhraseSuggestion.DirectCandidateGenerator]? { return _directGenerators } public func build() throws -> PhraseSuggestion { return try PhraseSuggestion(withBuilder: self) } } public struct PhraseSuggestion: Suggestion { public let suggestionType: SuggestionType = .phrase public var field: String public var text: String? public var prefix: String? public var regex: String? public var analyzer: String? public var size: Int? public var shardSize: Int? public var maxErrors: Decimal? public var separator: String? public var realWordErrorLikelihood: Decimal? public var confidence: Decimal? public var gramSize: Int? public var forceUnigrams: Bool? public var tokenLimit: Int? public var highlight: Highlight? public var collate: Collate? public var smoothing: SmoothingModel? public var directGenerators: [DirectCandidateGenerator]? public init(field: String, text: String? = nil, prefix: String? = nil, regex: String? = nil, analyzer: String? = nil, size: Int? = nil, shardSize: Int? = nil, maxErrors: Decimal? = nil, separator: String? = nil, realWordErrorLikelihood: Decimal? = nil, confidence: Decimal? = nil, gramSize: Int? = nil, forceUnigrams: Bool? = nil, tokenLimit: Int? = nil, highlight: PhraseSuggestion.Highlight? = nil, collate: Collate? = nil, smoothing: SmoothingModel? = nil, directGenerators: [DirectCandidateGenerator]? = nil) { self.field = field self.text = text self.prefix = prefix self.regex = regex self.analyzer = analyzer self.size = size self.shardSize = shardSize self.maxErrors = maxErrors self.separator = separator self.realWordErrorLikelihood = realWordErrorLikelihood self.confidence = confidence self.gramSize = gramSize self.forceUnigrams = forceUnigrams self.tokenLimit = tokenLimit self.highlight = highlight self.collate = collate self.smoothing = smoothing self.directGenerators = directGenerators } internal init(withBuilder builder: PhraseSuggestionBuilder) throws { guard let field = builder.field else { throw SuggestionBuilderError.missingRequiredField("field") } self.init(field: field, text: builder.text, prefix: builder.prefix, regex: builder.regex, analyzer: builder.analyzer, size: builder.size, shardSize: builder.shardSize, maxErrors: builder.maxErrors, separator: builder.separator, realWordErrorLikelihood: builder.realWordErrorLikelihood, confidence: builder.confidence, gramSize: builder.gramSize, forceUnigrams: builder.forceUnigrams, tokenLimit: builder.tokenLimit, highlight: builder.highlight, collate: builder.collate, smoothing: builder.smoothing, directGenerators: builder.directGenerators) } } public extension PhraseSuggestion { init(from decoder: Decoder) throws { let contianer = try decoder.container(keyedBy: DynamicCodingKeys.self) let namedContianer = try contianer.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: suggestionType)) field = try namedContianer.decodeString(forKey: .field) text = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.text.rawValue)) prefix = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.prefix.rawValue)) regex = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.regex.rawValue)) analyzer = try namedContianer.decodeStringIfPresent(forKey: .analyzer) size = try namedContianer.decodeIntIfPresent(forKey: .size) shardSize = try namedContianer.decodeIntIfPresent(forKey: .shardSize) maxErrors = try namedContianer.decodeDecimalIfPresent(forKey: .maxErrors) separator = try namedContianer.decodeStringIfPresent(forKey: .separator) realWordErrorLikelihood = try namedContianer.decodeDecimalIfPresent(forKey: .realWordErrorLikelihood) confidence = try namedContianer.decodeDecimalIfPresent(forKey: .confidence) gramSize = try namedContianer.decodeIntIfPresent(forKey: .gramSize) forceUnigrams = try namedContianer.decodeBoolIfPresent(forKey: .forceUnigrams) tokenLimit = try namedContianer.decodeIntIfPresent(forKey: .tokenLimit) highlight = try namedContianer.decodeIfPresent(PhraseSuggestion.Highlight.self, forKey: .highlight) collate = try namedContianer.decodeIfPresent(PhraseSuggestion.Collate.self, forKey: .collate) smoothing = try namedContianer.decodeSmoothingModelIfPresent(forKey: .smoothing) directGenerators = try namedContianer.decodeIfPresent([DirectCandidateGenerator].self, forKey: .directGenerator) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) try container.encodeIfPresent(text, forKey: .key(named: CodingKeys.text.rawValue)) try container.encodeIfPresent(prefix, forKey: .key(named: CodingKeys.prefix.rawValue)) try container.encodeIfPresent(regex, forKey: .key(named: CodingKeys.regex.rawValue)) var namedContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: suggestionType)) try namedContainer.encode(field, forKey: .field) try namedContainer.encodeIfPresent(analyzer, forKey: .analyzer) try namedContainer.encodeIfPresent(size, forKey: .size) try namedContainer.encodeIfPresent(shardSize, forKey: .shardSize) try namedContainer.encodeIfPresent(confidence, forKey: .confidence) try namedContainer.encodeIfPresent(collate, forKey: .collate) try namedContainer.encodeIfPresent(highlight, forKey: .highlight) try namedContainer.encodeIfPresent(maxErrors, forKey: .maxErrors) try namedContainer.encodeIfPresent(separator, forKey: .separator) try namedContainer.encodeIfPresent(gramSize, forKey: .gramSize) try namedContainer.encodeIfPresent(forceUnigrams, forKey: .forceUnigrams) try namedContainer.encodeIfPresent(tokenLimit, forKey: .tokenLimit) try namedContainer.encodeIfPresent(realWordErrorLikelihood, forKey: .realWordErrorLikelihood) try namedContainer.encodeIfPresent(smoothing, forKey: .smoothing) if let directGenerators = self.directGenerators, directGenerators.count > 0 { try namedContainer.encode(directGenerators, forKey: .directGenerator) } } internal enum CodingKeys: String, CodingKey { case field case text case prefix case regex case analyzer case size case shardSize = "shard_size" case directGenerator = "direct_generator" case highlight case collate case smoothing case gramSize = "gram_size" case forceUnigrams = "force_unigrams" case maxErrors = "max_errors" case tokenLimit = "token_limit" case realWordErrorLikelihood = "real_word_error_likelihood" case separator case confidence } } public extension PhraseSuggestion { struct Highlight { public let preTag: String public let postTag: String public init(preTag: String, postTag: String) { self.preTag = preTag self.postTag = postTag } } struct DirectCandidateGenerator { public var field: String public var preFilter: String? public var postFilter: String? public var suggestMode: String? public var accuracy: Decimal? public var size: Int? public var sort: TermSuggestion.SortBy? public var stringDistance: TermSuggestion.StringDistance? public var maxEdits: Int? public var maxInspections: Int? public var maxTermFreq: Decimal? public var prefixLength: Int? public var minWordLength: Int? public var minDocFreq: Decimal? public init(field: String, preFilter: String? = nil, postFilter: String? = nil, suggestMode: String? = nil, accuracy: Decimal? = nil, size: Int? = nil, sort: TermSuggestion.SortBy? = nil, stringDistance: TermSuggestion.StringDistance? = nil, maxEdits: Int? = nil, maxInspections: Int? = nil, maxTermFreq: Decimal? = nil, prefixLength: Int? = nil, minWordLength: Int? = nil, minDocFreq: Decimal? = nil) { self.field = field self.preFilter = preFilter self.postFilter = postFilter self.suggestMode = suggestMode self.accuracy = accuracy self.size = size self.sort = sort self.stringDistance = stringDistance self.maxEdits = maxEdits self.maxInspections = maxInspections self.maxTermFreq = maxTermFreq self.prefixLength = prefixLength self.minWordLength = minWordLength self.minDocFreq = minDocFreq } } struct Collate { public let query: Script public let params: [String: CodableValue]? public let purne: Bool } } extension PhraseSuggestion.Highlight: Codable { enum CodingKeys: String, CodingKey { case preTag = "pre_tag" case postTag = "post_tag" } } extension PhraseSuggestion.Highlight: Equatable {} extension PhraseSuggestion.DirectCandidateGenerator: Codable { enum CodingKeys: String, CodingKey { case field case preFilter = "pre_filter" case postFilter = "post_filter" case suggestMode = "suggest_mode" case accuracy case size case sort case stringDistance = "string_distance" case maxEdits = "max_edits" case maxInspections = "max_inspections" case maxTermFreq = "max_term_freq" case prefixLength = "prefix_length" case minWordLength = "min_word_length" case minDocFreq = "min_doc_freq" } } extension PhraseSuggestion.DirectCandidateGenerator: Equatable {} extension PhraseSuggestion.Collate: Codable {} extension PhraseSuggestion.Collate: Equatable {} extension PhraseSuggestion: Equatable { public static func == (lhs: PhraseSuggestion, rhs: PhraseSuggestion) -> Bool { return lhs.suggestionType == rhs.suggestionType && lhs.field == rhs.field && lhs.prefix == rhs.prefix && lhs.text == rhs.text && lhs.regex == rhs.regex && lhs.analyzer == rhs.analyzer && lhs.size == rhs.size && lhs.shardSize == rhs.shardSize && lhs.maxErrors == rhs.maxErrors && lhs.separator == rhs.separator && lhs.realWordErrorLikelihood == rhs.realWordErrorLikelihood && lhs.confidence == rhs.confidence && lhs.gramSize == rhs.gramSize && lhs.forceUnigrams == rhs.forceUnigrams && lhs.tokenLimit == rhs.tokenLimit && lhs.highlight == rhs.highlight && lhs.collate == rhs.collate && isEqualSmoothingModels(lhs.smoothing, rhs.smoothing) && lhs.directGenerators == rhs.directGenerators } } public enum SmoothingModelType: String, Codable { case laplace case stupidBackoff = "stupid_backoff" case linearInterpolation = "linear_interpolation" } extension SmoothingModelType { var metaType: SmoothingModel.Type { switch self { case .laplace: return Laplace.self case .stupidBackoff: return StupidBackoff.self case .linearInterpolation: return LinearInterpolation.self } } } public protocol SmoothingModel: Codable { var smoothingModelType: SmoothingModelType { get } func isEqualTo(_ other: SmoothingModel) -> Bool } public extension SmoothingModel where Self: Equatable { func isEqualTo(_ other: SmoothingModel) -> Bool { if let o = other as? Self { return self == o } return false } } public func isEqualSmoothingModels(_ lhs: SmoothingModel?, _ rhs: SmoothingModel?) -> Bool { if lhs == nil, rhs == nil { return true } if let lhs = lhs, let rhs = rhs { return lhs.isEqualTo(rhs) } return false } public struct StupidBackoff: SmoothingModel { public let smoothingModelType: SmoothingModelType = .stupidBackoff public let discount: Decimal } public extension StupidBackoff { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let namedContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: smoothingModelType)) discount = try namedContainer.decodeDecimal(forKey: .discount) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var namedContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: smoothingModelType)) try namedContainer.encode(discount, forKey: .discount) } internal enum CodingKeys: String, CodingKey { case discount } } extension StupidBackoff: Equatable {} public struct Laplace: SmoothingModel { public let smoothingModelType: SmoothingModelType = .laplace public let alpha: Decimal } public extension Laplace { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let namedContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: smoothingModelType)) alpha = try namedContainer.decodeDecimal(forKey: .alpha) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var namedContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: smoothingModelType)) try namedContainer.encode(alpha, forKey: .alpha) } internal enum CodingKeys: String, CodingKey { case alpha } } extension Laplace: Equatable {} public struct LinearInterpolation: SmoothingModel { public let smoothingModelType: SmoothingModelType = .linearInterpolation public let trigramLambda: Decimal public let bigramLambda: Decimal public let unigramLambda: Decimal } public extension LinearInterpolation { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let namedContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: smoothingModelType)) trigramLambda = try namedContainer.decodeDecimal(forKey: .trigramLambda) bigramLambda = try namedContainer.decodeDecimal(forKey: .bigramLambda) unigramLambda = try namedContainer.decodeDecimal(forKey: .unigramLambda) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var namedContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: smoothingModelType)) try namedContainer.encode(trigramLambda, forKey: .trigramLambda) try namedContainer.encode(bigramLambda, forKey: .bigramLambda) try namedContainer.encode(unigramLambda, forKey: .unigramLambda) } internal enum CodingKeys: String, CodingKey { case trigramLambda = "trigram_lambda" case bigramLambda = "bigram_lambda" case unigramLambda = "unigram_lambda" } } extension LinearInterpolation: Equatable {} public class CompletionSuggestionBuilder: BaseSuggestionBuilder, SuggestionBuilder { public typealias ElasticSwiftType = CompletionSuggestion private var _skipDuplicates: Bool? private var _fuzzyOptions: CompletionSuggestion.FuzzyOptions? private var _regexOptions: CompletionSuggestion.RegexOptions? private var _contexts: [String: [CompletionSuggestionQueryContext]]? override public init() { super.init() } @discardableResult public func set(skipDuplicates: Bool) -> Self { _skipDuplicates = skipDuplicates return self } @discardableResult public func set(fuzzyOptions: CompletionSuggestion.FuzzyOptions) -> Self { _fuzzyOptions = fuzzyOptions return self } @discardableResult public func set(regexOptions: CompletionSuggestion.RegexOptions) -> Self { _regexOptions = regexOptions return self } @discardableResult public func set(contexts: [String: [CompletionSuggestionQueryContext]]) -> Self { _contexts = contexts return self } public var skipDuplicates: Bool? { return _skipDuplicates } public var fuzzyOptions: CompletionSuggestion.FuzzyOptions? { return _fuzzyOptions } public var regexOptions: CompletionSuggestion.RegexOptions? { return _regexOptions } public var contexts: [String: [CompletionSuggestionQueryContext]]? { return _contexts } public func build() throws -> CompletionSuggestion { return try CompletionSuggestion(withBuilder: self) } } public struct CompletionSuggestion: Suggestion { public let suggestionType: SuggestionType = .completion public var field: String public var text: String? public var prefix: String? public var regex: String? public var analyzer: String? public var size: Int? public var shardSize: Int? public var skipDuplicates: Bool? public var fuzzyOptions: FuzzyOptions? public var regexOptions: RegexOptions? public var contexts: [String: [CompletionSuggestionQueryContext]]? public init(field: String, text: String? = nil, prefix: String? = nil, regex: String? = nil, analyzer: String? = nil, size: Int? = nil, shardSize: Int? = nil, skipDuplicates: Bool? = nil, fuzzyOptions: FuzzyOptions? = nil, regexOptions: RegexOptions? = nil, contexts: [String: [CompletionSuggestionQueryContext]]? = nil) { self.field = field self.text = text self.prefix = prefix self.analyzer = analyzer self.regex = regex self.size = size self.shardSize = shardSize self.skipDuplicates = skipDuplicates self.fuzzyOptions = fuzzyOptions self.regexOptions = regexOptions self.contexts = contexts } internal init(withBuilder builder: CompletionSuggestionBuilder) throws { guard let field = builder.field else { throw SuggestionBuilderError.missingRequiredField("field") } self.init(field: field, text: builder.text, prefix: builder.prefix, regex: builder.regex, analyzer: builder.analyzer, size: builder.size, shardSize: builder.shardSize, skipDuplicates: builder.skipDuplicates, fuzzyOptions: builder.fuzzyOptions, regexOptions: builder.regexOptions, contexts: builder.contexts) } } public extension CompletionSuggestion { init(from decoder: Decoder) throws { let contianer = try decoder.container(keyedBy: DynamicCodingKeys.self) let namedContianer = try contianer.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: suggestionType)) field = try namedContianer.decodeString(forKey: .field) text = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.text.rawValue)) prefix = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.prefix.rawValue)) regex = try contianer.decodeStringIfPresent(forKey: .key(named: CodingKeys.regex.rawValue)) analyzer = try namedContianer.decodeStringIfPresent(forKey: .analyzer) size = try namedContianer.decodeIntIfPresent(forKey: .size) shardSize = try namedContianer.decodeIntIfPresent(forKey: .shardSize) skipDuplicates = try namedContianer.decodeBoolIfPresent(forKey: .skipDuplicates) fuzzyOptions = try namedContianer.decodeIfPresent(FuzzyOptions.self, forKey: .fuzzyOptions) regexOptions = try namedContianer.decodeIfPresent(RegexOptions.self, forKey: .regex) if namedContianer.contains(.contexts) { let contextsContainer = try namedContianer.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .contexts) var dic = [String: [CompletionSuggestionQueryContext]]() for k in contextsContainer.allKeys { do { let contextValues = try contextsContainer.decodeSuggestionQueryContexts(forKey: k) dic[k.stringValue] = contextValues } catch { let context = try contextsContainer.decodeSuggestionQueryContext(forKey: k) dic[k.stringValue] = [context] } } contexts = dic } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) try container.encodeIfPresent(text, forKey: .key(named: CodingKeys.text.rawValue)) try container.encodeIfPresent(prefix, forKey: .key(named: CodingKeys.prefix.rawValue)) try container.encodeIfPresent(regex, forKey: .key(named: CodingKeys.regex.rawValue)) var namedContainer = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: suggestionType)) try namedContainer.encode(field, forKey: .field) try namedContainer.encodeIfPresent(analyzer, forKey: .analyzer) try namedContainer.encodeIfPresent(size, forKey: .size) try namedContainer.encodeIfPresent(shardSize, forKey: .shardSize) try namedContainer.encodeIfPresent(skipDuplicates, forKey: .skipDuplicates) try namedContainer.encodeIfPresent(fuzzyOptions, forKey: .fuzzyOptions) try namedContainer.encodeIfPresent(regexOptions, forKey: .regex) if let contexts = self.contexts { var contextContainer = namedContainer.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .contexts) for (k, v) in contexts { try contextContainer.encode(v, forKey: .key(named: k)) } } } internal enum CodingKeys: String, CodingKey { case field case text case prefix case regex case analyzer case size case shardSize = "shard_size" case skipDuplicates = "skip_duplicates" case fuzzyOptions = "fuzzy" case contexts } } public extension CompletionSuggestion { struct FuzzyOptions { public var fuzziness: Int? public var transpositions: Bool? public var fuzzyMinLength: Int? public var fuzzyPrefixLength: Int? public var unicodeAware: Bool? public var maxDeterminizedStates: Int? public init(fuzziness: Int? = nil, transpositions: Bool? = nil, fuzzyMinLength: Int? = nil, fuzzyPrefixLength: Int? = nil, unicodeAware: Bool? = nil, maxDeterminizedStates: Int? = nil) { self.fuzziness = fuzziness self.transpositions = transpositions self.fuzzyMinLength = fuzzyMinLength self.fuzzyPrefixLength = fuzzyPrefixLength self.unicodeAware = unicodeAware self.maxDeterminizedStates = maxDeterminizedStates } } struct RegexOptions { public var flags: RegexFlag? public var maxDeterminizedStates: Int? public init(flags: RegexFlag? = nil, maxDeterminizedStates: Int? = nil) { self.flags = flags self.maxDeterminizedStates = maxDeterminizedStates } } enum RegexFlag: String, Codable { case all = "ALL" case anystring = "ANYSTRING" case complement = "COMPLEMENT" case empty = "EMPTY" case intersection = "INTERSECTION" case `internal` = "INTERVAL" case none = "NONE" } } extension CompletionSuggestion.FuzzyOptions: Codable { enum CodingKeys: String, CodingKey { case fuzziness case transpositions case fuzzyMinLength = "min_length" case fuzzyPrefixLength = "prefix_length" case unicodeAware = "unicode_aware" case maxDeterminizedStates = "max_determinized_states" } } extension CompletionSuggestion.FuzzyOptions: Equatable {} extension CompletionSuggestion.RegexOptions: Codable { enum CodingKeys: String, CodingKey { case flags case maxDeterminizedStates = "max_determinized_states" } } extension CompletionSuggestion.RegexOptions: Equatable {} extension CompletionSuggestion: Equatable { public static func == (lhs: CompletionSuggestion, rhs: CompletionSuggestion) -> Bool { return lhs.suggestionType == rhs.suggestionType && lhs.field == rhs.field && lhs.text == rhs.text && lhs.prefix == rhs.prefix && lhs.regex == rhs.regex && lhs.analyzer == rhs.analyzer && lhs.size == rhs.size && lhs.shardSize == rhs.shardSize && lhs.skipDuplicates == rhs.skipDuplicates && lhs.fuzzyOptions == rhs.fuzzyOptions && lhs.regexOptions == rhs.regexOptions && isEqualContextDictionaries(lhs.contexts, rhs.contexts) } } public func isEqualContextDictionaries(_ lhs: [String: [CompletionSuggestionQueryContext]]?, _ rhs: [String: [CompletionSuggestionQueryContext]]?) -> Bool { if lhs == nil, rhs == nil { return true } guard let lhs = lhs, let rhs = rhs, lhs.count == rhs.count else { return false } let result = lhs.map { guard let values = rhs[$0.key], values.count == $0.value.count, values.elementsEqual($0.value, by: { $0.isEqualTo($1) }) else { return false } return true }.reduce(true) { $0 && $1 } return result } public enum CompletionSuggestionQueryContextType: String, Codable, CaseIterable { case geo case category } public extension CompletionSuggestionQueryContextType { var metaType: CompletionSuggestionQueryContext.Type { switch self { case .category: return CategoryQueryContext.self case .geo: return GeoQueryContext.self } } } public protocol CompletionSuggestionQueryContext: Codable { var queryContextType: CompletionSuggestionQueryContextType { get } func isEqualTo(_ other: CompletionSuggestionQueryContext) -> Bool } public extension CompletionSuggestionQueryContext where Self: Equatable { func isEqualTo(_ other: CompletionSuggestionQueryContext) -> Bool { if let o = other as? Self { return self == o } return false } } public struct GeoQueryContext: CompletionSuggestionQueryContext { public let queryContextType: CompletionSuggestionQueryContextType = .geo public let context: GeoPoint public var boost: Int? public var precision: Int? public var neighbours: [Int]? public init(context: GeoPoint, boost: Int? = nil, precision: Int? = nil, neighbours: [Int]? = nil) { self.context = context self.boost = boost self.precision = precision self.neighbours = neighbours } } extension GeoQueryContext: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) context = try container.decode(GeoPoint.self, forKey: .context) boost = try container.decodeIntIfPresent(forKey: .boost) precision = try container.decodeIntIfPresent(forKey: .precision) neighbours = try container.decodeArrayIfPresent(forKey: .neighbours) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(context, forKey: .context) try container.encodeIfPresent(boost, forKey: .boost) try container.encodeIfPresent(precision, forKey: .precision) try container.encodeIfPresent(neighbours, forKey: .neighbours) } enum CodingKeys: String, CodingKey { case context case boost case precision case neighbours } } extension GeoQueryContext: Equatable {} public struct CategoryQueryContext: CompletionSuggestionQueryContext { public let queryContextType: CompletionSuggestionQueryContextType = .category public var context: String public var prefix: Bool? public var boost: Int? public init(context: String, prefix: Bool? = nil, boost: Int? = nil) { self.context = context self.prefix = prefix self.boost = boost } } extension CategoryQueryContext: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) context = try container.decodeString(forKey: .context) prefix = try container.decodeBoolIfPresent(forKey: .prefix) boost = try container.decodeIntIfPresent(forKey: .boost) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(context, forKey: .context) try container.encodeIfPresent(prefix, forKey: .prefix) try container.encodeIfPresent(boost, forKey: .boost) } enum CodingKeys: String, CodingKey { case context case prefix case boost } } extension CategoryQueryContext: Equatable {} /// Extention for DynamicCodingKeys public extension DynamicCodingKeys { static func key(named suggestionType: SuggestionType) -> DynamicCodingKeys { return .key(named: suggestionType.rawValue) } static func key(named smoothingModelType: SmoothingModelType) -> DynamicCodingKeys { return .key(named: smoothingModelType.rawValue) } } // MARK: - Codable Extenstions public extension KeyedEncodingContainer { mutating func encode(_ value: Suggestion, forKey key: KeyedEncodingContainer<K>.Key) throws { try value.encode(to: superEncoder(forKey: key)) } mutating func encode(_ value: SmoothingModel, forKey key: KeyedEncodingContainer<K>.Key) throws { try value.encode(to: superEncoder(forKey: key)) } mutating func encode(_ value: CompletionSuggestionQueryContext, forKey key: KeyedEncodingContainer<K>.Key) throws { try value.encode(to: superEncoder(forKey: key)) } mutating func encode(_ value: [Suggestion], forKey key: KeyedEncodingContainer<K>.Key) throws { let suggestionsEncoder = superEncoder(forKey: key) var suggestionsContainer = suggestionsEncoder.unkeyedContainer() for suggestion in value { let suggestionEncoder = suggestionsContainer.superEncoder() try suggestion.encode(to: suggestionEncoder) } } mutating func encode(_ value: [SmoothingModel], forKey key: KeyedEncodingContainer<K>.Key) throws { let smoothingModelEncoder = superEncoder(forKey: key) var smoothingModelContainer = smoothingModelEncoder.unkeyedContainer() for smoothing in value { let smoothingEncoder = smoothingModelContainer.superEncoder() try smoothing.encode(to: smoothingEncoder) } } mutating func encode(_ value: [CompletionSuggestionQueryContext], forKey key: KeyedEncodingContainer<K>.Key) throws { let queryContextsEncoder = superEncoder(forKey: key) var queryContextsContainer = queryContextsEncoder.unkeyedContainer() for queryContext in value { let queryContextEncoder = queryContextsContainer.superEncoder() try queryContext.encode(to: queryContextEncoder) } } mutating func encodeIfPresent(_ value: Suggestion?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try value.encode(to: superEncoder(forKey: key)) } } mutating func encodeIfPresent(_ value: SmoothingModel?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try value.encode(to: superEncoder(forKey: key)) } } mutating func encodeIfPresent(_ value: CompletionSuggestionQueryContext?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try value.encode(to: superEncoder(forKey: key)) } } mutating func encodeIfPresent(_ value: [Suggestion]?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try encode(value, forKey: key) } } mutating func encodeIfPresent(_ value: [SmoothingModel]?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try encode(value, forKey: key) } } mutating func encodeIfPresent(_ value: [CompletionSuggestionQueryContext]?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try encode(value, forKey: key) } } } public extension KeyedDecodingContainer { func decodeSuggestion(forKey key: KeyedDecodingContainer<K>.Key) throws -> Suggestion { let qContainer = try nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) for sKey in qContainer.allKeys { if let sType = SuggestionType(rawValue: sKey.stringValue) { return try sType.metaType.init(from: superDecoder(forKey: key)) } } throw Swift.DecodingError.typeMismatch(SuggestionType.self, .init(codingPath: codingPath, debugDescription: "Unable to identify suggestion type from key(s) \(qContainer.allKeys)")) } func decodeSmoothingModel(forKey key: KeyedDecodingContainer<K>.Key) throws -> SmoothingModel { let smContainer = try nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) for smKey in smContainer.allKeys { if let smType = SmoothingModelType(rawValue: smKey.stringValue) { return try smType.metaType.init(from: superDecoder(forKey: key)) } } throw Swift.DecodingError.typeMismatch(SmoothingModelType.self, .init(codingPath: codingPath, debugDescription: "Unable to identify smoothing mode type from key(s) \(smContainer.allKeys)")) } func decodeSuggestionQueryContext(forKey key: KeyedDecodingContainer<K>.Key) throws -> CompletionSuggestionQueryContext { for type in CompletionSuggestionQueryContextType.allCases { let result = try? type.metaType.init(from: superDecoder(forKey: key)) if let result = result { if let result = result as? GeoQueryContext { if let geoHash = result.context.geoHash, geoHash.rangeOfCharacter(from: CharacterSet(charactersIn: "ailo").union(CharacterSet.whitespacesAndNewlines)) != nil { continue } } return result } } throw Swift.DecodingError.typeMismatch(CompletionSuggestionQueryContextType.self, .init(codingPath: codingPath, debugDescription: "Unable to decode QueryContext for types \(CompletionSuggestionQueryContextType.allCases)")) } func decodeSuggestionIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> Suggestion? { guard contains(key) else { return nil } return try decodeSuggestion(forKey: key) } func decodeSmoothingModelIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> SmoothingModel? { guard contains(key) else { return nil } return try decodeSmoothingModel(forKey: key) } func decodeSuggestions(forKey key: KeyedDecodingContainer<K>.Key) throws -> [Suggestion] { var arrayContainer = try nestedUnkeyedContainer(forKey: key) var result = [Suggestion]() if let count = arrayContainer.count { while !arrayContainer.isAtEnd { let query = try arrayContainer.decodeSuggestion() result.append(query) } if result.count != count { throw Swift.DecodingError.dataCorrupted(.init(codingPath: arrayContainer.codingPath, debugDescription: "Unable to decode all Suggestions expected: \(count) actual: \(result.count). Probable cause: Unable to determine SuggestionType form key(s)")) } } return result } func decodeSuggestionQueryContexts(forKey key: KeyedDecodingContainer<K>.Key) throws -> [CompletionSuggestionQueryContext] { var arrayContainer = try nestedUnkeyedContainer(forKey: key) var result = [CompletionSuggestionQueryContext]() if let count = arrayContainer.count { while !arrayContainer.isAtEnd { let query = try arrayContainer.decodeSuggestionQueryContext() result.append(query) } if result.count != count { throw Swift.DecodingError.dataCorrupted(.init(codingPath: arrayContainer.codingPath, debugDescription: "Unable to decode all QueryContexts expected: \(count) actual: \(result.count). Probable cause: Unable to determine CompletionSuggestionQueryContextType form key(s)")) } } return result } func decodeSuggestionsIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> [Suggestion]? { guard contains(key) else { return nil } return try decodeSuggestions(forKey: key) } func decodeSuggestionQueryContextsIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> [CompletionSuggestionQueryContext]? { guard contains(key) else { return nil } return try decodeSuggestionQueryContexts(forKey: key) } } extension UnkeyedDecodingContainer { mutating func decodeSuggestion() throws -> Suggestion { var copy = self let elementContainer = try copy.nestedContainer(keyedBy: DynamicCodingKeys.self) for sKey in elementContainer.allKeys { if let sType = SuggestionType(rawValue: sKey.stringValue) { return try sType.metaType.init(from: superDecoder()) } } throw Swift.DecodingError.typeMismatch(SuggestionType.self, .init(codingPath: codingPath, debugDescription: "Unable to identify suggestion type from key(s) \(elementContainer.allKeys)")) } mutating func decodeSmoothingModel() throws -> SmoothingModel { var copy = self let elementContainer = try copy.nestedContainer(keyedBy: DynamicCodingKeys.self) for sKey in elementContainer.allKeys { if let sType = SmoothingModelType(rawValue: sKey.stringValue) { return try sType.metaType.init(from: superDecoder()) } } throw Swift.DecodingError.typeMismatch(SmoothingModelType.self, .init(codingPath: codingPath, debugDescription: "Unable to identify smoothing model type from key(s) \(elementContainer.allKeys)")) } mutating func decodeSuggestionQueryContext() throws -> CompletionSuggestionQueryContext { for c in CompletionSuggestionQueryContextType.allCases { var copy = self let result = try? c.metaType.init(from: copy.superDecoder()) if let result = result { if let result = result as? GeoQueryContext { if let geoHash = result.context.geoHash, geoHash.rangeOfCharacter(from: CharacterSet(charactersIn: "ailo").union(CharacterSet.whitespacesAndNewlines)) != nil { continue } } return try c.metaType.init(from: superDecoder()) } } throw Swift.DecodingError.typeMismatch(CompletionSuggestionQueryContext.self, .init(codingPath: codingPath, debugDescription: "Unable to decode QueryContext types \(CompletionSuggestionQueryContextType.allCases)")) } }
mit
e59cb3ae0dca296dd5188ac82c114ba7
35.163467
553
0.673875
4.569953
false
false
false
false
apple/swift-nio-http2
Sources/NIOHPACK/IntegerCoding.swift
1
5204
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore /* private but tests */ /// Encodes an integer value into a provided memory location. /// /// - Parameters: /// - value: The integer value to encode. /// - buffer: The location at which to begin encoding. /// - prefix: The number of bits available for use in the first byte at `buffer`. /// - prefixBits: Existing bits to place in that first byte of `buffer` before encoding `value`. /// - Returns: Returns the number of bytes used to encode the integer. @discardableResult func encodeInteger(_ value: UInt, to buffer: inout ByteBuffer, prefix: Int, prefixBits: UInt8 = 0) -> Int { assert(prefix <= 8) assert(prefix >= 1) let start = buffer.writerIndex // The prefix is always hard-coded, and must fit within 8, so unchecked math here is definitely safe. let k = (1 &<< prefix) &- 1 var initialByte = prefixBits if value < k { // it fits already! initialByte |= UInt8(truncatingIfNeeded: value) buffer.writeInteger(initialByte) return 1 } // if it won't fit in this byte altogether, fill in all the remaining bits and move // to the next byte. initialByte |= UInt8(truncatingIfNeeded: k) buffer.writeInteger(initialByte) // deduct the initial [prefix] bits from the value, then encode it seven bits at a time into // the remaining bytes. // We can safely use unchecked subtraction here: we know that `k` is zero or greater, and that `value` is // either the same value or greater. As a result, this can be unchecked: it's always safe. var n = value &- UInt(k) while n >= 128 { let nextByte = (1 << 7) | UInt8(truncatingIfNeeded: n & 0x7f) buffer.writeInteger(nextByte) n >>= 7 } buffer.writeInteger(UInt8(truncatingIfNeeded: n)) return buffer.writerIndex &- start } fileprivate let valueMask: UInt8 = 127 fileprivate let continuationMask: UInt8 = 128 /* private but tests */ struct DecodedInteger { var value: Int var bytesRead: Int } /* private but tests */ func decodeInteger(from bytes: ByteBufferView, prefix: Int) throws -> DecodedInteger { precondition((1...8).contains(prefix)) if bytes.isEmpty { throw NIOHPACKErrors.InsufficientInput() } // See RFC 7541 § 5.1 for details of the encoding/decoding. var index = bytes.startIndex // The shifting and arithmetic operate on 'Int' and prefix is 1...8, so these unchecked operations are // fine and the result must fit in a UInt8. let prefixMask = UInt8(truncatingIfNeeded: (1 &<< prefix) &- 1) let prefixBits = bytes[index] & prefixMask if prefixBits != prefixMask { // The prefix bits aren't all '1', so they represent the whole value, we're done. return DecodedInteger(value: Int(prefixBits), bytesRead: 1) } var accumulator = Int(prefixMask) bytes.formIndex(after: &index) // for the remaining bytes, as long as the top bit is set, consume the low seven bits. var shift: Int = 0 var byte: UInt8 = 0 repeat { if index == bytes.endIndex { throw NIOHPACKErrors.InsufficientInput() } byte = bytes[index] let value = Int(byte & valueMask) // The shift cannot overflow: the value of 'shift' is strictly less than 'Int.bitWidth'. let (multiplicationResult, multiplicationOverflowed) = value.multipliedReportingOverflow(by: (1 &<< shift)) if multiplicationOverflowed { throw NIOHPACKErrors.UnrepresentableInteger() } let (additionResult, additionOverflowed) = accumulator.addingReportingOverflow(multiplicationResult) if additionOverflowed { throw NIOHPACKErrors.UnrepresentableInteger() } accumulator = additionResult // Unchecked is fine, there's no chance of it overflowing given the possible values of 'Int.bitWidth'. shift &+= 7 if shift >= Int.bitWidth { throw NIOHPACKErrors.UnrepresentableInteger() } bytes.formIndex(after: &index) } while byte & continuationMask == continuationMask return DecodedInteger(value: accumulator, bytesRead: bytes.distance(from: bytes.startIndex, to: index)) } extension ByteBuffer { mutating func readEncodedInteger(withPrefix prefix: Int) throws -> Int { let result = try decodeInteger(from: self.readableBytesView, prefix: prefix) self.moveReaderIndex(forwardBy: result.bytesRead) return result.value } mutating func write(encodedInteger value: UInt, prefix: Int = 0, prefixBits: UInt8 = 0) { encodeInteger(value, to: &self, prefix: prefix, prefixBits: prefixBits) } }
apache-2.0
22abb80cd7bf55cb5c8edd77c019b38c
34.882759
115
0.651932
4.368598
false
false
false
false
cdw33/BonsaiXML
bonsaiXML/Stack.swift
1
2211
// // Stack.swift // bonsaiXML // // Copyright © 2015 Christopher Wilson. https://github.com/cdw33 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** * This is a generic stack implementation **/ class Stack<Element>{ private var count: Int = 0 private var head: StackNode<Element>! init() { head = nil } func isEmpty() -> Bool { return count == 0 } func push(value: Element) { if isEmpty() { head = StackNode(value: value) } else { let node = StackNode(value: value) node.next = head head = node } count++ } func pop() { if isEmpty() { return } let node = head head = node!.next count-- } func peek() -> Element! { return head.item } func size()->Int{ return count } } class StackNode<Element>{ //Made this a class because Swift does not allow recursive structs var item: Element! var next: StackNode<Element>? init(value: Element) { item = value } }
mit
94d95f9a08b6c77f551863d1208b9b12
25.963415
92
0.629864
4.464646
false
false
false
false
leotumwattana/WWC-Animations
WWC-Animations/BeeCircle.swift
1
3345
// // BeeCircle.swift // WWC-Animations // // Created by Leo Tumwattana on 28/5/15. // Copyright (c) 2015 Innovoso Ltd. All rights reserved. // import UIKit import pop @objc protocol BeeCircleDelegate { func beeCircleChangedActivation(bee: BeeCircle) } class BeeCircle: Circle { // ================== // MARK: - Properties // ================== weak var delegate:BeeCircleDelegate? var activated = false { didSet { delegate?.beeCircleChangedActivation(self) let alpha:CGFloat = activated ? 1 : 0 animateLabelAlpha(alpha) if activated { superview?.bringSubviewToFront(self) } } } private var originalCenter:CGPoint! // ================ // MARK: - Subviews // ================ var label:UILabel! // ============ // MARK: - Init // ============ override func commonInit() { super.commonInit() label = UILabel() label.font = UIFont(name: "ChalkboardSE-Bold", size: 35) label.textColor = UIColor.blackColor() label.textAlignment = .Center label.text = "!" label.alpha = 0 addSubview(label) originalCenter = center } override func layoutSubviews() { super.layoutSubviews() label.frame = bounds } // ====================== // MARK: - Event Handlers // ====================== override func tapped(tap: UITapGestureRecognizer) { activated = !activated } override func longPressed(longPressed: UILongPressGestureRecognizer) { moveToPoint(originalCenter) scale(to: 1) activated = false } // =============== // MARK: - Helpers // =============== func moveToPoint(point:CGPoint) { let toValue = NSValue(CGPoint: point) if let anim = pop_animationForKey("center") as? POPSpringAnimation { anim.toValue = toValue } else { let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter) anim.toValue = toValue anim.springSpeed = 1 anim.springBounciness = 12 pop_addAnimation(anim, forKey: "center") } } private func animateLabelAlpha(alpha:CGFloat) { if let anim = label.pop_animationForKey("alpha") as? POPSpringAnimation { anim.toValue = alpha } else { let anim = POPSpringAnimation(propertyNamed: kPOPViewAlpha) anim.toValue = alpha label.pop_addAnimation(anim, forKey: "alpha") } } func scale(to specifiedScale:CGFloat?) { let s:CGFloat = specifiedScale ?? CGFloat(randomInt(max: 2)) + 0.7 let toValue = NSValue(CGSize: CGSizeMake(s, s)) if let anim = pop_animationForKey("scale") as? POPSpringAnimation { anim.toValue = toValue } else { let anim = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) anim.toValue = toValue pop_addAnimation(anim, forKey: "scale") } if s < 1 { superview?.sendSubviewToBack(self) } else { superview?.bringSubviewToFront(self) } } }
bsd-3-clause
b0fd1037c2e62d46df81f0814379da30
25.338583
81
0.532138
4.977679
false
false
false
false
tonychan818/TCMedia
TCMedia/UIColorExtension.swift
1
2583
// // UIColorExtension.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = advance(rgba.startIndex, 1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (count(hex)) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { println("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } func toHexString() -> String { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 return String(format:"#%06x", rgb) } }
mit
d9a5f95193ed8c37bf055f9c39c5f25f
36.434783
109
0.45451
3.992272
false
false
false
false
muyang00/YEDouYuTV
YEDouYuZB/YEDouYuZB/Main/Models/AnchorModel.swift
1
814
// // AnchorModel.swift // YEDouYuZB // // Created by yongen on 17/2/15. // Copyright © 2017年 yongen. All rights reserved. // import UIKit class AnchorModel: NSObject { //房间ID var room_id : Int = 0 //房间图片对应的URLString var vertical_src : String = "" //判断是手机直播还是电脑直播 //0: 电脑直播(普通房间) 1: 手机直播(秀场房间) var isVertical : Int = 0 //房间名称 var room_name : String = "" //主播昵称 var nick_name : String = "" //观看人数 var online : Int = 0 //所在城市 var anchor_city : String = "" init(dict :[String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
apache-2.0
523efd4a844b6c0bcf10faacd9cdfda2
19.382353
72
0.577201
3.364078
false
false
false
false
mthistle/HockeyTweetSwift
HockeyTweetSwift/ViewControllers/AboutViewController.swift
1
1184
// // AboutViewController.swift // HockeyTweetSwift // // Created by Mark Thistle on 4/17/15. // Copyright (c) 2015 Test. All rights reserved. // import UIKit class AboutViewController: UIViewController { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. webView.loadHTMLString(self.webViewBody(), baseURL: nil) // let buildVersion = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as String // let versionNumber = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as String // self.versionLabel.text = "Version: \(versionNumber) (\(buildVersion))" } func webViewBody() -> String { let bundle = NSBundle.mainBundle() //let pathReachabilityLicense = bundle.pathForResource("Reachability_LICENSE", ofType: "txt") //let ReachabilityLicense = String(contentsOfFile: pathReachabilityLicense!, encoding: NSUTF8StringEncoding, error: nil) let body = "<html><body><h3>Licenses:</h3><ul><li></li></ul></body></html>" return body } }
mit
a60c1a16e4ed4ec5dcd314ecd4efecea
37.225806
128
0.680743
4.607004
false
false
false
false
actorapp/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/ActorCoreExt.swift
2
18299
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import AVFoundation public var Actor : ACCocoaMessenger { get { return ActorSDK.sharedActor().messenger } } public extension ACCocoaMessenger { public func sendUIImage(_ image: Data, peer: ACPeer, animated:Bool) { let imageFromData = UIImage(data:image) let thumb = imageFromData!.resizeSquare(90, maxH: 90); let resized = imageFromData!.resizeOptimize(1200 * 1200); let thumbData = UIImageJPEGRepresentation(thumb, 0.55); let fastThumb = ACFastThumb(int: jint(thumb.size.width), with: jint(thumb.size.height), with: thumbData!.toJavaBytes()) let descriptor = "/tmp/"+UUID().uuidString let path = CocoaFiles.pathFromDescriptor(descriptor); animated ? ((try? image.write(to: URL(fileURLWithPath: path), options: [.atomic])) != nil) : ((try? UIImageJPEGRepresentation(resized, 0.80)!.write(to: URL(fileURLWithPath: path), options: [.atomic])) != nil) animated ? sendAnimation(with: peer, withName: "image.gif", withW: jint(resized.size.width), withH:jint(resized.size.height), with: fastThumb, withDescriptor: descriptor) : sendPhoto(with: peer, withName: "image.jpg", withW: jint(resized.size.width), withH: jint(resized.size.height), with: fastThumb, withDescriptor: descriptor) } public func sendVideo(_ url: URL, peer: ACPeer) { if let videoData = try? Data(contentsOf: url) { // if data have on this local path url go to upload let descriptor = "/tmp/"+UUID().uuidString let path = CocoaFiles.pathFromDescriptor(descriptor); try? videoData.write(to: URL(fileURLWithPath: path), options: [.atomic]) // write to file // get video duration let assetforduration = AVURLAsset(url: url) let videoDuration = assetforduration.duration let videoDurationSeconds = CMTimeGetSeconds(videoDuration) // get thubnail and upload let movieAsset = AVAsset(url: url) // video asset let imageGenerator = AVAssetImageGenerator(asset: movieAsset) var thumbnailTime = movieAsset.duration thumbnailTime.value = 25 let orientation = movieAsset.videoOrientation() do { let imageRef = try imageGenerator.copyCGImage(at: thumbnailTime, actualTime: nil) let thumbnail = UIImage(cgImage: imageRef) var thumb = thumbnail.resizeSquare(90, maxH: 90); let resized = thumbnail.resizeOptimize(1200 * 1200); if (orientation.orientation.isPortrait) == true { thumb = thumb.imageRotatedByDegrees(90, flip: false) } let thumbData = UIImageJPEGRepresentation(thumb, 0.55); // thumbnail binary data let fastThumb = ACFastThumb(int: jint(resized.size.width), with: jint(resized.size.height), with: thumbData!.toJavaBytes()) print("video upload imageRef = \(imageRef)") print("video upload thumbnail = \(thumbnail)") //print("video upload thumbData = \(thumbData)") print("video upload fastThumb = \(fastThumb)") print("video upload videoDurationSeconds = \(videoDurationSeconds)") print("video upload width = \(thumbnail.size.width)") print("video upload height = \(thumbnail.size.height)") if (orientation.orientation.isPortrait == true) { self.sendVideo(with: peer, withName: "video.mp4", withW: jint(thumbnail.size.height/2), withH: jint(thumbnail.size.width/2), withDuration: jint(videoDurationSeconds), with: fastThumb, withDescriptor: descriptor) } else { self.sendVideo(with: peer, withName: "video.mp4", withW: jint(thumbnail.size.width), withH: jint(thumbnail.size.height), withDuration: jint(videoDurationSeconds), with: fastThumb, withDescriptor: descriptor) } } catch { print("can't get thumbnail image") } } } fileprivate func prepareAvatar(_ image: UIImage) -> String { let res = "/tmp/" + UUID().uuidString let avatarPath = CocoaFiles.pathFromDescriptor(res) let thumb = image.resizeSquare(800, maxH: 800); try? UIImageJPEGRepresentation(thumb, 0.8)!.write(to: URL(fileURLWithPath: avatarPath), options: [.atomic]) return res } public func changeOwnAvatar(_ image: UIImage) { changeMyAvatar(withDescriptor: prepareAvatar(image)) } public func changeGroupAvatar(_ gid: jint, image: UIImage) -> String { let fileName = prepareAvatar(image) self.changeGroupAvatar(withGid: gid, withDescriptor: fileName) return fileName } public func requestFileState(_ fileId: jlong, notDownloaded: (()->())?, onDownloading: ((_ progress: Double) -> ())?, onDownloaded: ((_ reference: String) -> ())?) { Actor.requestState(withFileId: fileId, with: AAFileCallback(notDownloaded: notDownloaded, onDownloading: onDownloading, onDownloaded: onDownloaded)) } public func requestFileState(_ fileId: jlong, onDownloaded: ((_ reference: String) -> ())?) { Actor.requestState(withFileId: fileId, with: AAFileCallback(notDownloaded: nil, onDownloading: nil, onDownloaded: onDownloaded)) } } // // Collcections // extension JavaUtilAbstractCollection : Sequence { public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } public extension JavaUtilList { public func toSwiftArray<T>() -> [T] { var res = [T]() for i in 0..<self.size() { res.append(self.getWith(i) as! T) } return res } } public extension IOSObjectArray { public func toSwiftArray<T>() -> [T] { var res = [T]() for i in 0..<self.length() { res.append(self.object(at: UInt(i)) as! T) } return res } } public extension Data { public func toJavaBytes() -> IOSByteArray { return IOSByteArray(bytes: (self as NSData).bytes.bindMemory(to: jbyte.self, capacity: self.count), count: UInt(self.count)) } } // // Entities // public extension ACPeer { public var isGroup: Bool { get { return self.peerType.ordinal() == ACPeerType.group().ordinal() } } public var isPrivate: Bool { get { return self.peerType.ordinal() == ACPeerType.private().ordinal() } } } public extension ACMessage { public var isOut: Bool { get { return Actor.myUid() == self.senderId } } } // // Callbacks // open class AACommandCallback: NSObject, ACCommandCallback { open var resultClosure: ((_ val: Any?) -> ())?; open var errorClosure: ((_ val:JavaLangException?) -> ())?; public init<T>(result: ((_ val:T?) -> ())?, error: ((_ val:JavaLangException?) -> ())?) { super.init() self.resultClosure = { (val: Any!) -> () in (result?(val as? T))! } self.errorClosure = error } open func onResult(_ res: Any!) { resultClosure?(res) } open func onError(_ e: JavaLangException!) { errorClosure?(e) } } class AAUploadFileCallback : NSObject, ACUploadFileCallback { let notUploaded: (()->())? let onUploading: ((_ progress: Double) -> ())? let onUploadedClosure: (() -> ())? init(notUploaded: (()->())?, onUploading: ((_ progress: Double) -> ())?, onUploadedClosure: (() -> ())?) { self.onUploading = onUploading self.notUploaded = notUploaded self.onUploadedClosure = onUploadedClosure; } func onNotUploading() { self.notUploaded?() } func onUploaded() { self.onUploadedClosure?() } func onUploading(_ progress: jfloat) { self.onUploading?(Double(progress)) } } class AAFileCallback : NSObject, ACFileCallback { let notDownloaded: (()->())? let onDownloading: ((_ progress: Double) -> ())? let onDownloaded: ((_ fileName: String) -> ())? init(notDownloaded: (()->())?, onDownloading: ((_ progress: Double) -> ())?, onDownloaded: ((_ reference: String) -> ())?) { self.notDownloaded = notDownloaded; self.onDownloading = onDownloading; self.onDownloaded = onDownloaded; } init(onDownloaded: @escaping (_ reference: String) -> ()) { self.notDownloaded = nil; self.onDownloading = nil; self.onDownloaded = onDownloaded; } func onNotDownloaded() { self.notDownloaded?(); } func onDownloading(_ progress: jfloat) { self.onDownloading?(Double(progress)); } func onDownloaded(_ reference: ARFileSystemReference!) { self.onDownloaded?(reference!.getDescriptor()); } } // // Markdown // open class TextParser { open let textColor: UIColor open let linkColor: UIColor open let fontSize: CGFloat fileprivate let markdownParser = ARMarkdownParser(int: ARMarkdownParser_MODE_FULL) public init(textColor: UIColor, linkColor: UIColor, fontSize: CGFloat) { self.textColor = textColor self.linkColor = linkColor self.fontSize = fontSize } open func parse(_ text: String) -> ParsedText { let doc = markdownParser?.processDocument(with: text) if (doc?.isTrivial())! { let nAttrText = NSMutableAttributedString(string: text) let range = NSRange(location: 0, length: nAttrText.length) nAttrText.yy_setColor(textColor, range: range) nAttrText.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) return ParsedText(attributedText: nAttrText, isTrivial: true, code: []) } var sources = [String]() let sections: [ARMDSection] = doc!.getSections().toSwiftArray() let nAttrText = NSMutableAttributedString() var isFirst = true for s in sections { if !isFirst { nAttrText.append(NSAttributedString(string: "\n")) } isFirst = false if s.getType() == ARMDSection_TYPE_CODE { let str = NSMutableAttributedString(string: AALocalized("ActionOpenCode")) let range = NSRange(location: 0, length: str.length) let highlight = YYTextHighlight() highlight.userInfo = ["url" : "source:///\(sources.count)"] str.yy_setTextHighlight(highlight, range: range) str.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) str.yy_setColor(linkColor, range: range) nAttrText.append(str) sources.append(s.getCode().getCode()) } else if s.getType() == ARMDSection_TYPE_TEXT { let child: [ARMDText] = s.getText().toSwiftArray() for c in child { nAttrText.append(buildText(c, fontSize: fontSize)) } } else { fatalError("Unsupported section type") } } return ParsedText(attributedText: nAttrText, isTrivial: false, code: sources) } fileprivate func buildText(_ text: ARMDText, fontSize: CGFloat) -> NSAttributedString { if let raw = text as? ARMDRawText { let res = NSMutableAttributedString(string: raw.getRawText()) let range = NSRange(location: 0, length: res.length) res.beginEditing() res.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) res.yy_setColor(textColor, range: range) res.endEditing() return res } else if let span = text as? ARMDSpan { let res = NSMutableAttributedString() res.beginEditing() // Processing child texts let child: [ARMDText] = span.getChild().toSwiftArray() for c in child { res.append(buildText(c, fontSize: fontSize)) } // Setting span elements if span.getType() == ARMDSpan_TYPE_BOLD { res.appendFont(UIFont.boldSystemFont(ofSize: fontSize)) } else if span.getType() == ARMDSpan_TYPE_ITALIC { res.appendFont(UIFont.italicSystemFont(ofSize: fontSize)) } else { fatalError("Unsupported span type") } res.endEditing() return res } else if let url = text as? ARMDUrl { // Parsing url element let nsUrl = URL(string: url.getUrl()) if nsUrl != nil { let res = NSMutableAttributedString(string: url.getTitle()) let range = NSRange(location: 0, length: res.length) let highlight = YYTextHighlight() highlight.userInfo = ["url" : url.getUrl()] res.yy_setTextHighlight(highlight, range: range) res.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) res.yy_setColor(linkColor, range: range) return res } else { // Unable to parse: show as text let res = NSMutableAttributedString(string: url.getTitle()) let range = NSRange(location: 0, length: res.length) res.beginEditing() res.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) res.yy_setColor(textColor, range: range) res.endEditing() return res } } else { fatalError("Unsupported text type") } } } open class ParsedText { open let isTrivial: Bool open let attributedText: NSAttributedString open let code: [String] public init(attributedText: NSAttributedString, isTrivial: Bool, code: [String]) { self.attributedText = attributedText self.code = code self.isTrivial = isTrivial } } // // Promises // open class AAPromiseFunc: NSObject, ARPromiseFunc { let closure: (_ resolver: ARPromiseResolver) -> () init(closure: @escaping (_ resolver: ARPromiseResolver) -> ()){ self.closure = closure } open func exec(_ resolver: ARPromiseResolver) { closure(resolver) } } extension ARPromise { convenience init(closure: @escaping (_ resolver: ARPromiseResolver) -> ()) { self.init(executor: AAPromiseFunc(closure: closure)) } } // // Data Binding // open class AABinder { fileprivate var bindings : [BindHolder] = [] public init() { } open func bind<T1,T2,T3>(_ valueModel1:ARValue, valueModel2:ARValue, valueModel3:ARValue, closure: @escaping (_ value1:T1?, _ value2:T2?, _ value3:T3?) -> ()) { let listener1 = BindListener { (_value1) -> () in closure(_value1 as? T1, valueModel2.get() as? T2, valueModel3.get() as? T3) }; let listener2 = BindListener { (_value2) -> () in closure(valueModel1.get() as? T1, _value2 as? T2, valueModel3.get() as? T3) }; let listener3 = BindListener { (_value3) -> () in closure(valueModel1.get() as? T1, valueModel2.get() as? T2, _value3 as? T3) }; bindings.append(BindHolder(valueModel: valueModel1, listener: listener1)) bindings.append(BindHolder(valueModel: valueModel2, listener: listener2)) bindings.append(BindHolder(valueModel: valueModel3, listener: listener3)) valueModel1.subscribe(with: listener1, notify: false) valueModel2.subscribe(with: listener2, notify: false) valueModel3.subscribe(with: listener3, notify: false) closure(valueModel1.get() as? T1, valueModel2.get() as? T2, valueModel3.get() as? T3) } open func bind<T1,T2>(_ valueModel1:ARValue, valueModel2:ARValue, closure: @escaping (_ value1:T1?, _ value2:T2?) -> ()) { let listener1 = BindListener { (_value1) -> () in closure(_value1 as? T1, valueModel2.get() as? T2) }; let listener2 = BindListener { (_value2) -> () in closure(valueModel1.get() as? T1, _value2 as? T2) }; bindings.append(BindHolder(valueModel: valueModel1, listener: listener1)) bindings.append(BindHolder(valueModel: valueModel2, listener: listener2)) valueModel1.subscribe(with: listener1, notify: false) valueModel2.subscribe(with: listener2, notify: false) closure(valueModel1.get() as? T1, valueModel2.get() as? T2) } open func bind<T>(_ value:ARValue, closure: @escaping (_ value: T?)->()) { let listener = BindListener { (value2) -> () in closure(value2 as? T) }; let holder = BindHolder(valueModel: value, listener: listener) bindings.append(holder) value.subscribe(with: listener) } open func unbindAll() { for holder in bindings { holder.valueModel.unsubscribe(with: holder.listener) } bindings.removeAll(keepingCapacity: true) } } class BindListener: NSObject, ARValueChangedListener { var closure: ((_ value: Any?)->())? init(closure: @escaping (_ value: Any?)->()) { self.closure = closure } func onChanged(_ val: Any!, withModel valueModel: ARValue!) { closure?(val) } } class BindHolder { var listener: BindListener var valueModel: ARValue init(valueModel: ARValue, listener: BindListener) { self.valueModel = valueModel self.listener = listener } }
agpl-3.0
39f2819f96091c8d3ab6c16a6402079f
34.394584
337
0.585005
4.502707
false
false
false
false
PrimarySA/Hackaton2015
stocker/BachiTrading/GraphView.swift
1
2353
// // GraphView.swift // BachiTrading // // Created by Emiliano Bivachi on 14/11/15. // Copyright (c) 2015 Emiliano Bivachi. All rights reserved. // import UIKit class GraphView: FSLineChart { var data: [CGFloat]? { didSet { clearChartData() if let data = self.data where data.count > 0 { noDataLabel.hidden = true calcExtremePoints(data) setChartData(data) } else if data?.count == 0 && shouldShowNoDataLabel { noDataLabel.hidden = false } } } var shouldShowNoDataLabel = false private var maxPoint: CGFloat = 1 private var minPoint: CGFloat = -1 private var noDataLabel = UILabel() override var color: UIColor? { didSet { noDataLabel.textColor = color } } override func awakeFromNib() { gridStep = 1 drawInnerGrid = false axisLineWidth = 0 displayDataPoint = false animationDuration = 0.0 fillColor = UIColor.clearColor() clipsToBounds = true configNoDataLabel() } private func configNoDataLabel() { noDataLabel.text = "No hay datos" noDataLabel.backgroundColor = UIColor.whiteColor() self.addSubview(noDataLabel) MiscUtils.addConstraintsToMatchItsSuperView(noDataLabel) layoutIfNeeded() noDataLabel.hidden = true } private func calcExtremePoints(data: [CGFloat]) { var maxPoint = data.first! var minPoint = data.first! for point in data { maxPoint = (point > maxPoint) ? point : maxPoint minPoint = (point < minPoint) ? point : minPoint } if self.maxPoint != 0 && self.minPoint != 0 { self.maxPoint = maxPoint self.minPoint = minPoint } else { self.maxPoint = 1.0 self.minPoint = (-1.0) } } func maxVerticalBound() -> CGFloat { let delta = abs(maxPoint) - abs(minPoint) let point = maxPoint + delta * 0.04 return (point != 0) ? point : 0.01 } func minVerticalBound() -> CGFloat { let delta = abs(maxPoint) - abs(minPoint) let point = minPoint - delta * 0.05 return (point != 0) ? point : -0.01 } }
gpl-3.0
1eb80aa9a0cc0a8e524525654a02a524
27.695122
65
0.562261
4.38175
false
false
false
false
payjp/payjp-ios
Sources/Views/ActionButton.swift
1
1673
// // ActionButton.swift // PAYJP // // Created by TADASHI on 2019/12/03. // Copyright © 2019 PAY, Inc. All rights reserved. // import UIKit class ActionButton: UIButton { @IBInspectable var normalBackgroundColor: UIColor = Style.Color.blue { didSet { if isEnabled { self.backgroundColor = normalBackgroundColor } } } @IBInspectable var disableBackgroundColor: UIColor = Style.Color.gray { didSet { if !isEnabled { self.backgroundColor = disableBackgroundColor } } } @IBInspectable var cornerRadius: CGFloat = Style.Radius.large { didSet { self.layer.cornerRadius = cornerRadius } } // MARK: - Super Class override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder decoder: NSCoder) { super.init(coder: decoder) initialize() } override var isEnabled: Bool { didSet { if isEnabled { self.backgroundColor = self.normalBackgroundColor } else { self.backgroundColor = self.disableBackgroundColor } } } // MARK: - Helper Methods private func initialize() { self.layer.cornerRadius = self.cornerRadius self.setTitleColor(.white, for: .normal) self.setTitleColor(.white, for: .disabled) self.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold) self.backgroundColor = (self.isEnabled) ? self.normalBackgroundColor : self.disableBackgroundColor } }
mit
218a5fb449c93b6c0d8fa8401e1419eb
24.723077
106
0.592105
4.818444
false
false
false
false
Vladlex/BodyBuilder
BodyBuilder/Body.swift
1
1888
// // Body.swift // BodyBuilder // // Created by Aleksei Gordeev on 25/05/2017. // // import Foundation public struct Body: CustomStringConvertible { public var items: [BodyItemRepresentable] = [] public var data: Data { var data = Data.init() items.forEach({ data.append($0.httpRequestBodyData) }) return data } /** * String representaiton of the body. * If you want line-by-line representation in Xcode consle print "po print(body)" */ public var description: String { let itemDescriptions = self.items.map({$0.httpRequestBodyDescription}) return itemDescriptions.joined() } public init(items: [BodyItemRepresentable] = []) { self.items = items } } public extension Body { mutating public func append(byLineBreaks: Int) { guard byLineBreaks > 0 else { return } let string = String.init(repeating: "\r\n", count: byLineBreaks) self.items.append(string) } mutating public func append(byHeaderField: HeaderField, lineBreaks: Int = 1) { self.items.append(byHeaderField) self.append(byLineBreaks: lineBreaks) } mutating public func append(byString: String, lineBreaks: Int = 1) { self.append(by: byString) self.append(byLineBreaks: lineBreaks) } mutating public func append(byItems: [BodyItemRepresentable], lineBreaks: Int = 1) { self.items.append(contentsOf: byItems) self.append(byLineBreaks: lineBreaks) } mutating public func append(byItem: BodyItemRepresentable, lineBreaks: Int = 1) { self.items.append(byItem) self.append(byLineBreaks: lineBreaks) } mutating public func append(by items: BodyItemRepresentable...) { self.append(byItems: items, lineBreaks: 0) } }
apache-2.0
c48e7d53e92f47c0fa57ce66a258a648
26.362319
88
0.631886
4.077754
false
false
false
false
lanserxt/teamwork-ios-sdk
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+CalendarEvents.swift
1
13969
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire extension TWApiClient{ func getEvents(startDate: Date, endDate: Date, showDeleted: Bool = true, eventTypeId: Int = 0, _ responseBlock: @escaping (Bool, Int, [CalendarEvent]?, Error?) -> Void){ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyymmdd" Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getEvents.path, dateFormatter.string(from: startDate), dateFormatter.string(from: endDate), wrapBoolValue(showDeleted), eventTypeId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<CalendarEvent>.init(rootObjectName: TWApiClientConstants.APIPath.getEvents.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) print("\(responseContainer.rootObjects)") } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getCalendarEvent(eventId: String, _ responseBlock: @escaping (Bool, Int, CalendarEvent?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getComment.path, eventId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<CalendarEvent>.init(rootObjectName: TWApiClientConstants.APIPath.getComment.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getEvent(eventId: String, _ responseBlock: @escaping (Bool, Int, CalendarEvent?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getEvent.path, eventId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<CalendarEvent>.init(rootObjectName: TWApiClientConstants.APIPath.getEvent.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func createEvent(event: CalendarEvent, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){ let parameters: [String : Any] = ["event" : event.dictionaryRepresentation() as! [String : Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createEvent.path), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<CalendarEvent>.init(rootObjectName: TWApiClientConstants.APIPath.createEvent.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func updateEvent(event: CalendarEvent, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["event" : event.dictionaryRepresentation() as! [String : Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateEvent.path, event.id!), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.updateEvent.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteEvent(event: CalendarEvent, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteEvent.path, event.id!), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.deleteEvent.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func getCalendarEventTypes(_ responseBlock: @escaping (Bool, Int, [EventType]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getCalendarEventTypes.path), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<EventType>.init(rootObjectName: TWApiClientConstants.APIPath.getCalendarEventTypes.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getEventTypes(_ responseBlock: @escaping (Bool, Int, [EventType]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getEventTypes.path), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<EventType>.init(rootObjectName: TWApiClientConstants.APIPath.getEventTypes.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } }
mit
5b0b3970cfa8a238fe0747509987669b
52.723077
305
0.532574
6.129004
false
false
false
false
gg4acrossover/swiftForFun
Project 01 - GGArtistry/Project 01 - GGArtistry/Models/GGArtistModel.swift
1
2106
// // GGArtistModel.swift // Project 01 - GGArtistry // // Created by viethq on 4/7/17. // Copyright © 2017 viethq. All rights reserved. // import UIKit import ObjectMapper import SwiftyJSON //MARK: - GGArtistModel define class GGArtistModel: NSObject, Mappable { var name : String? var bio : String? var image : String? var works = [GGWorkModel]() var isExpand = false /// get artist from resources static func artistsFromBundle() -> [GGArtistModel]? { // if URL invalid, return nil guard let url = Bundle.main.url(forResource: "artists", withExtension: "json") else { return nil } // create artist container var artists = [GGArtistModel]() // do { let data = try Data(contentsOf: url) //let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any] let json = JSON.init(data: data) guard let artistsDict = json["artists"].arrayObject else { return nil } for item in artistsDict { if let artist = GGArtistModel(JSON:(item as! [String:Any])) { artists.append(artist) } } } catch { debugPrint("error") return nil } return artists } /// implement protocol ObjectMapper required init?(map: Map) { //TODO: init implement for Mappable } /// implement protocol ObjectMapper func mapping(map: Map) { self.name <- map["name"] self.bio <- map["bio"] self.image <- map["image"] self.works <- map["works"] } } //MARK: - display data for GGArtistryCell extension GGArtistModel : GGArtistryCellDisplayProtocol { var icon : String? { return self.image } var introduction : String? { return self.bio } var titleLabel : String? { return self.name } }
mit
8d8beed479827d67a258682a46b1e23c
23.476744
112
0.540143
4.526882
false
false
false
false
acastano/swift-bootstrap
userinterfacekit/Sources/Classes/Controllers/Common/TableViewController.swift
1
2675
import UIKit import CoreData open class TableViewController: ViewController, NSFetchedResultsControllerDelegate { open let cellIdentifier = "cellIdentifier" open let headerIdentifier = "headerIdentifier" @IBOutlet open weak var tableView: UITableView! open override func viewDidLoad() { super.viewDidLoad() #if os(iOS) tableView?.separatorColor = UIColor.clear #endif tableView?.backgroundColor = UIColor.clear } //MARK: NSFetchedResultsControllerDelegate open func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } open func controller(_ controller:NSFetchedResultsController<NSFetchRequestResult>, didChange anObject:Any, at indexPath:IndexPath?, for type:NSFetchedResultsChangeType, newIndexPath:IndexPath?) { switch(type) { case .insert: if let newIndexPath = newIndexPath { tableView.insertRows(at: [newIndexPath], with:.fade) } case .delete: if let indexPath = indexPath { tableView.deleteRows(at: [indexPath], with:.fade) } case .update: break case .move: if let newIndexPath = newIndexPath { tableView.insertRows(at: [newIndexPath], with:.fade) } if let indexPath = indexPath { tableView.deleteRows(at: [indexPath], with:.fade) } } } open func controller(_ controller:NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo:NSFetchedResultsSectionInfo, atSectionIndex sectionIndex:Int, for type:NSFetchedResultsChangeType) { switch(type) { case .move: break case .update: break case .insert: tableView.insertSections(IndexSet(integer:sectionIndex), with:.fade) case .delete: tableView.deleteSections(IndexSet(integer:sectionIndex), with:.fade) } } open func controllerDidChangeContent(_ controller:NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } }
apache-2.0
96fc352a625d381877d30300ac36d79b
25.485149
210
0.537944
7.039474
false
false
false
false
WaterReporter/WaterReporter-iOS
WaterReporter/WaterReporter/LoginTableViewController.swift
1
11918
// // LoginTableViewController.swift // Water-Reporter // // Created by Viable Industries on 9/22/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Alamofire import Foundation import SwiftyJSON import UIKit class LoginTableViewController: UITableViewController { @IBOutlet weak var navigationButtonLogin: UIButton! @IBOutlet weak var navigationButtonSignUp: UIButton! @IBOutlet weak var textfieldEmailAddress: UITextField! @IBOutlet weak var textfieldPassword: UITextField! @IBOutlet weak var buttonForgotYourPassword: UIButton! @IBOutlet weak var buttonLogin: UIButton! @IBOutlet weak var indicatorLogin: UIActivityIndicatorView! override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) if NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") != nil { self.dismissViewControllerAnimated(false, completion: nil); } } override func viewDidLoad() { super.viewDidLoad() // // Make doubly sure that there is no `currentUserAccountAccessToken` // NSUserDefaults.standardUserDefaults().removeObjectForKey("currentUserAccountAccessToken") // // Make sure we are getting 'auto layout' specific sizes // otherwise any math we do will be messed up // self.view.setNeedsLayout() self.view.layoutIfNeeded() // // Restyle the form Log In Navigation button to appear with an underline // let border = CALayer() let buttonWidth = self.navigationButtonLogin.frame.width let borderWidth = buttonWidth/2 border.borderColor = CGColor.colorBrand() border.borderWidth = 3.0 border.frame = CGRectMake(borderWidth/2, self.navigationButtonLogin.frame.size.height - 3.0, borderWidth, self.navigationButtonLogin.frame.size.height) self.navigationButtonLogin.layer.addSublayer(border) self.navigationButtonLogin.layer.masksToBounds = true self.navigationButtonSignUp.addTarget(self, action: #selector(LoginTableViewController.showRegisterViewController(_:)), forControlEvents: .TouchUpInside) // // // if let _email_address = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountEmailAddress") { self.textfieldEmailAddress.text = _email_address as? String } // // Set all table row separators to appear transparent // self.tableView.separatorColor = UIColor(white: 1.0, alpha: 0.0) // // Alter the appearence of the Log In button // self.buttonLogin.layer.borderWidth = 1.0 self.buttonLogin.setTitleColor(UIColor.colorBrand(0.35), forState: .Normal) self.buttonLogin.setTitleColor(UIColor.colorBrand(), forState: .Highlighted) self.buttonLogin.layer.borderColor = CGColor.colorBrand(0.35) self.buttonLogin.layer.cornerRadius = 4.0 buttonLogin.addTarget(self, action: #selector(buttonClickLogin(_:)), forControlEvents: .TouchUpInside) // // Watch the Email Address and Password field's for changes. // We will be enabling and disabling the "Login Button" based // on whether or not the fields contain content. // textfieldEmailAddress.addTarget(self, action: #selector(LoginTableViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged) textfieldPassword.addTarget(self, action: #selector(LoginTableViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged) // // Hide the "Log in attempt" indicator by default, we do not // need this indicator until a user interacts with the login // button // self.isReady() } // // Basic Login Button Feedback States // func isReady() { buttonLogin.hidden = false buttonLogin.enabled = false indicatorLogin.hidden = true } func isLoading() { buttonLogin.hidden = true indicatorLogin.hidden = false indicatorLogin.startAnimating() } func isFinishedLoadingWithError() { buttonLogin.hidden = false indicatorLogin.hidden = true indicatorLogin.stopAnimating() } func enableLoginButton() { buttonLogin.enabled = true self.buttonLogin.setTitleColor(UIColor.colorBrand(), forState: .Normal) } func disableLoginButton() { buttonLogin.enabled = false self.buttonLogin.setTitleColor(UIColor.colorBrand(0.35), forState: .Normal) } func showRegisterViewController(sender: UITabBarItem) { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("RegisterTableViewController") as! RegisterTableViewController self.presentViewController(nextViewController, animated: false, completion: { print("showRegisterViewController > LoginTableViewController > presentViewController") }) } func displayErrorMessage(title: String, message: String) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } // // // func textFieldDidChange(textField: UITextField) { // // - IF a textfield is not an empty string, enable the login button // - ELSE disable the button so that a user cannot tap it to submit an invalid request // if (self.textfieldEmailAddress.text == "" || self.textfieldPassword.text == "") { self.disableLoginButton() } else { self.enableLoginButton() } } // // // func buttonClickLogin(sender:UIButton) { // // Hide the log in button so that the user cannot tap // it more than once. If they did tap it more than once // this would cause multiple requests to be sent to the // server and then multiple responses back to the app // which could cause the wrong `access_token` to be saved // to the user's Locksmith keychain. // self.isLoading() // // Send the email address and password along to the Authentication endpoint // for verification and processing // self.attemptAuthentication(self.textfieldEmailAddress.text!, password: self.textfieldPassword.text!) } func attemptAuthentication(email: String, password: String) { // // Send a request to the defined endpoint with the given parameters // let parameters = [ "email": email, "password": password, "response_type": Environment.RESPONSE_TYPE, "client_id": Environment.CLIENT_ID, "redirect_uri": Environment.REDIRECT_URI, "scope": Environment.SCOPE, "state": Environment.STATE ] Alamofire.request(.POST, Endpoints.POST_AUTH_REMOTE, parameters: parameters, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): print(value) if let responseCode = value["code"] { if responseCode != nil { print("!= nil") self.isFinishedLoadingWithError() self.displayErrorMessage("An Error Occurred", message:"Please check the email address and password you entered and try again.") } else { NSUserDefaults.standardUserDefaults().setValue(value["access_token"], forKeyPath: "currentUserAccountAccessToken") NSUserDefaults.standardUserDefaults().setValue(self.textfieldEmailAddress.text, forKeyPath: "currentUserAccountEmailAddress") self.attemptRetrieveUserID() } } case .Failure(let error): print(error) self.isFinishedLoadingWithError() self.displayErrorMessage("An Error Occurred", message:"Please check the email address and password you entered and try again.") break } } } // // MARK: HTTP Request/Response functionality // func buildRequestHeaders() -> [String: String] { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") return [ "Authorization": "Bearer " + (accessToken! as! String) ] } func attemptRetrieveUserID() { let _headers = buildRequestHeaders() Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: _headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): let json = JSON(value) if let data: AnyObject = json.rawValue { // Set the user id as a number and save it to the application cache // let _user_id = data["id"] as! NSNumber NSUserDefaults.standardUserDefaults().setValue(_user_id, forKeyPath: "currentUserAccountUID") // Continue loading the user profile // self.textfieldPassword.text = "" self.isReady() let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("PrimaryTabBarController") as! UITabBarController self.presentViewController(nextViewController, animated: false, completion: { print("PrimaryTabBarController > presentViewController") }) } case .Failure(let error): print(error) } } } func textFieldShouldReturn(textField: UITextField) -> Bool { let nextTag = textField.tag + 1; let nextResponder=textField.superview?.superview?.superview?.viewWithTag(nextTag) as UIResponder! if (nextResponder != nil){ nextResponder?.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. NSLog("LoginViewController::didReceiveMemoryWarning") } }
agpl-3.0
3db1c6ec842fa90f8e2817b811e3dc92
36.124611
163
0.583872
5.937718
false
false
false
false
brunodlz/Couch
Couch/Couch/Core/Networking/Validate/ValidateProfileJson.swift
1
937
import Foundation import ObjectMapper struct ValidateProfileJson { static func validate(data: RawData) -> Profile? { guard let settings = data as? [String: AnyObject] else { return nil } guard let info = settings["user"] as? [String: AnyObject] else { return nil} let profile = Mapper<Profile>().map(JSONObject: info) if let dateTime = info["joined_at"] as? String { profile?.joined_at = Date().convertDate(To: dateTime) } if let slug = profile?.slug { KeysManager.setUser(slug) UserDefaults.standard.synchronize() } guard let connections = settings["connections"] as? [String:AnyObject] else { return nil } if let connection = Mapper<Connection>().map(JSON: connections) { profile?.connection = connection } return profile } }
mit
8346909d0f842d1ac45d6671efae8578
30.233333
98
0.578442
4.880208
false
false
false
false
RCacheaux/BitbucketKit
Carthage/Checkouts/Swinject/Tests/SynchronizedResolverSpec.swift
1
4588
// // SynchronizedResolverSpec.swift // Swinject // // Created by Yoichi Tagaya on 11/23/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Quick import Nimble @testable import Swinject class SynchronizedResolverSpec: QuickSpec { override func spec() { describe("Multiple threads") { it("can resolve circular dependencies.") { let container = Container() { container in container.register(ParentType.self) { _ in Parent() } .initCompleted { r, s in let parent = s as! Parent parent.child = r.resolve(ChildType.self) } .inObjectScope(.Graph) container.register(ChildType.self) { _ in Child() } .initCompleted { r, s in let child = s as! Child child.parent = r.resolve(ParentType.self)! } .inObjectScope(.Graph) }.synchronize() waitUntil(timeout: 2.0) { done in let queue = dispatch_queue_create("SwinjectTests.SynchronizedContainerSpec.Queue", DISPATCH_QUEUE_CONCURRENT) let totalThreads = 500 // 500 threads are enough to get fail unless the container is thread safe. let counter = Counter(max: 2 * totalThreads) for _ in 0..<totalThreads { dispatch_async(queue) { let parent = container.resolve(ParentType.self) as! Parent let child = parent.child as! Child expect(child.parent as? Parent) === parent counter.increment() if counter.count >= totalThreads { done() } } } } } it("can access parent and child containers without dead lock.") { let runInObjectScope = { (scope: ObjectScope) in let parentContainer = Container() { container in container.register(AnimalType.self) { _ in Cat() } .inObjectScope(scope) } let parentResolver = parentContainer.synchronize() let childResolver = Container(parent: parentContainer).synchronize() waitUntil(timeout: 2.0) { done in let queue = dispatch_queue_create("SwinjectTests.SynchronizedContainerSpec.Queue", DISPATCH_QUEUE_CONCURRENT) let totalThreads = 500 let counter = Counter(max: 2 * totalThreads) for _ in 0..<totalThreads { dispatch_async(queue) { _ = parentResolver.resolve(AnimalType.self) as! Cat if counter.increment() == .ReachedMax { done() } } dispatch_async(queue) { _ = childResolver.resolve(AnimalType.self) as! Cat if counter.increment() == .ReachedMax { done() } } } } } runInObjectScope(.None) runInObjectScope(.Graph) runInObjectScope(.Container) runInObjectScope(.Hierarchy) } } } final class Counter { enum Status { case UnderMax, ReachedMax } private var max: Int private let lock = dispatch_queue_create("SwinjectTests.SynchronizedContainerSpec.Counter.Lock", nil) private var count = 0 init(max: Int) { self.max = max } func increment() -> Status { var status = Status.UnderMax dispatch_sync(lock) { self.count += 1 if self.count >= self.max { status = .ReachedMax } } return status } } }
apache-2.0
ef17a2e99c48d2bac83ea420871c1759
39.59292
133
0.437105
6.06746
false
false
false
false