repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
BalestraPatrick/TweetsCounter
Tweetometer/UserDetailViewController.swift
2
2797
// // UserDetailViewController.swift // TweetsCounter // // Created by Patrick Balestra on 2/6/16. // Copyright © 2016 Patrick Balestra. All rights reserved. // import UIKit import TweetometerKit final class UserDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! let linkOpener = LinkOpener() var element: TwitterTimelineElement? weak var coordinator: UserDetailCoordinator! override func viewDidLoad() { super.viewDidLoad() applyStyle() guard let element = element else { return } setTitleViewContent(element.user.name, screenName: element.user.screenName) tableView.estimatedRowHeight = 50.0 tableView.rowHeight = UITableView.automaticDimension navigationItem.largeTitleDisplayMode = .never } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return element?.tweets.count ?? 0 default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch (indexPath.section, indexPath.row) { case (0, _): let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.UserDetailsCellIdentifier.rawValue, for: indexPath) as! UserDetailsTableViewCell if let element = element { cell.configure(element.user, coordinator: coordinator) } return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.TweetCellIdentifier.rawValue, for: indexPath) as! TweetTableViewCell if let element = element { let tweet = element.tweets[indexPath.row] cell.configure(tweet, indexPath: indexPath, coordinator: coordinator) } return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Open tweet in user's preferred client guard indexPath.section != 0 else { return } if let tweetId = element?.tweets[indexPath.row].idStr, let userId = element?.user.screenName { coordinator.open(tweet: tweetId, user: userId) } } // MARK: IBActions @IBAction func openIn(_ sender: UIBarButtonItem) { if let element = element { coordinator.open(user: element.user.screenName) } } }
mit
1358446b9ae855b8469b55c75c4c5dfa
33.518519
163
0.654864
5.325714
false
false
false
false
123kyky/SteamReader
SteamReader/SteamReader/View/NewsItemHeaderView.swift
1
2509
// // NewsItemHeader.swift // SteamReader // // Created by Kyle Roberts on 4/29/16. // Copyright © 2016 Kyle Roberts. All rights reserved. // import UIKit class NewsItemHeaderView: UIView { @IBOutlet var view: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var feedLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var previewLabel: UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) importView() } init() { super.init(frame: CGRectZero) importView() } func importView() { NSBundle.mainBundle().loadNibNamed("NewsItemHeaderView", owner: self, options: nil) addSubview(view) view.snp_makeConstraints { (make) in make.edges.equalTo(self) } } func configure(newsItem: NewsItem?) { if newsItem == nil { return } let dateFormatter = DateFormatter() // TODO: Move somewhere else var htmlAttributes: NSAttributedString? { guard let data = newsItem!.contents!.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } do { return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil) } catch let error as NSError { print(error.localizedDescription) return nil } } titleLabel.text = newsItem!.title feedLabel.text = newsItem!.feedLabel authorLabel.text = newsItem!.author dateLabel.text = dateFormatter.stringFromDate(newsItem!.date!) previewLabel.text = htmlAttributes?.string ?? "" } } class NewsItemHeaderCell: UITableViewCell { var newsItemView: NewsItemHeaderView? override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) newsItemView = NewsItemHeaderView() contentView.addSubview(newsItemView!) newsItemView?.snp_makeConstraints(closure: { (make) in make.edges.equalTo(self) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
62596d9a09f43fc39dae70ea19c5f8be
29.216867
207
0.622408
5.107943
false
false
false
false
Jubilant-Appstudio/Scuba
ScubaCalendar/View/CountryView/CountryCell.swift
1
1687
// // CountryCell.swift // ScubaCalendar // // Created by Mahipalsinh on 10/29/17. // Copyright © 2017 CodzGarage. All rights reserved. // import UIKit import Kingfisher class CountryCell: UICollectionViewCell { @IBOutlet weak var imgCountry: UIImageView! @IBOutlet weak var lblCountryName: UILabel! override func awakeFromNib() { super.awakeFromNib() imgCountry.alpha = 0.5 lblCountryName.font = CommonMethods.SetFont.RalewaySemiBold?.withSize(CGFloat(CommonMethods.SetFontSize.S12)) lblCountryName.textColor = CommonMethods.SetColor.darkGrayColor } func updateUI(countryData: CountryModel) { lblCountryName.text = countryData.getCountryName imgCountry.kf.indicatorType = .activity let urlAnimal = URL(string: APIList.strBaseUrl+countryData.getCountryMap)! imgCountry.kf.setImage(with: urlAnimal, placeholder: #imageLiteral(resourceName: "logo")) selectedCEllUI(isSelected: countryData.getIsSelected) } func selectedCEllUI(isSelected: Bool) { if isSelected == true { imgCountry.alpha = 1.0 lblCountryName.font = CommonMethods.SetFont.RalewaySemiBold?.withSize(CGFloat(CommonMethods.SetFontSize.S17)) lblCountryName.textColor = CommonMethods.SetColor.whiteColor } else { imgCountry.alpha = 0.5 lblCountryName.font = CommonMethods.SetFont.RalewaySemiBold?.withSize(CGFloat(CommonMethods.SetFontSize.S12)) lblCountryName.textColor = CommonMethods.SetColor.darkGrayColor } } }
mit
049bbbe10746d46723eb85fd8371bfff
30.811321
121
0.66548
4.886957
false
false
false
false
mvandervelden/iOSSystemIntegrationsDemo
SearchDemo/DataModel/Contact.swift
2
1177
import Foundation import CoreData import CoreSpotlight import MobileCoreServices class Contact: NSManagedObject { } extension Contact: Indexable { func index() { let item = CSSearchableItem(uniqueIdentifier: email, domainIdentifier: "com.philips.pins.SearchDemo.contact", attributeSet: attributes()) item.expirationDate = NSDate().dateByAddingTimeInterval(60 * 10) CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { (error) -> Void in if (error != nil) { print(error?.localizedDescription) } } } func attributes() -> CSSearchableItemAttributeSet { let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeContact as String) attributes.title = name if let email = email { attributes.emailAddresses = [email] } if let phone = phone { attributes.phoneNumbers = [phone, "(888) 555-5521"] attributes.supportsPhoneCall = 1 } attributes.contentDescription = phone! + "\n" + email! attributes.keywords = ["contact"] return attributes } }
mit
28e241aa3db8f46638cdfbadd6f23dab
31.722222
145
0.642311
5.185022
false
false
false
false
roadfire/SwiftFonts
SwiftFonts/MasterViewModel.swift
1
1118
// // MasterViewModel.swift // SwiftFonts // // Created by Josh Brown on 6/26/14. // Copyright (c) 2014 Roadfire Software. All rights reserved. // import UIKit class MasterViewModel { var familyNames : [String] var fonts = [String: [String]]() init() { let unsortedFamilyNames = UIFont.familyNames() familyNames = unsortedFamilyNames.sort() let sorter = FontSorter() for familyName in familyNames { let unsortedFontNames = UIFont.fontNamesForFamilyName(familyName) fonts[familyName] = sorter.sortFontNames(unsortedFontNames) } } func numberOfSections() -> Int { return familyNames.count } func numberOfRowsInSection(section: Int) -> Int { let key = familyNames[section] let array = fonts[key]! return array.count } func titleAtIndexPath(indexPath: NSIndexPath) -> String { let key = familyNames[indexPath.section] let array = fonts[key] let fontName = array![indexPath.row] return fontName } }
mit
505d3727acb4a4da26444cbda064a5c2
22.3125
78
0.608229
4.737288
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Profiles/DeviceFirmwareUpdate/ViewConrollers/DFUFileSelector/Utils/FSDataSource.swift
1
3401
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import Foundation import UIKit.UIImage struct FSNodeRepresentation { var node: FSNode var level: Int var name: String var collapsed: Bool var size: Int var image: UIImage var modificationDate: Date? var sizeInfo: String var valid: Bool var isDirectory: Bool } struct FSDataSource { var items: [FSNodeRepresentation] = [] var fileExtensionFilter: String? mutating func updateItems(_ dir: Directory) { items = items(dir, level: 0) } func items(_ dir: Directory, level: Int = 0) -> [FSNodeRepresentation] { dir.nodes.reduce([FSNodeRepresentation]()) { (result, node) in let valid: Bool if node is File, let ext = fileExtensionFilter, node.url.pathExtension != ext { valid = false } else { valid = true } var res = result let image = (node is Directory) ? ImageWrapper(icon: .folder, imageName: "folderEmpty").image : UIImage.icon(forFileURL: node.url, preferredSize: .smallest) let infoText: String if let dir = node as? Directory { infoText = "\(dir.nodes.count) items" } else { infoText = ByteCountFormatter().string(fromByteCount: Int64((node as! File).size)) } res.append(FSNodeRepresentation(node: node, level: level, name: node.name, collapsed: false, size: 0, image: image!, modificationDate: node.resourceModificationDate, sizeInfo: infoText, valid: valid, isDirectory: (node is Directory))) if let dir = node as? Directory { res.append(contentsOf: self.items(dir, level: level + 1)) } return res } } }
bsd-3-clause
295c3bf74f1a00da69d941bc75926331
38.091954
246
0.667451
4.723611
false
false
false
false
uasys/swift
stdlib/public/SDK/AppKit/NSError.swift
32
10456
//===----------------------------------------------------------------------===// // // 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 AppKit extension CocoaError.Code { public static var textReadInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } public static var textWriteInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } public static var serviceApplicationNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } public static var serviceApplicationLaunchFailed: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } public static var serviceRequestTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } public static var serviceInvalidPasteboardData: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } public static var serviceMalformedServiceDictionary: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } public static var serviceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } public static var sharingServiceNotConfigured: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } @available(macOS 10.13, *) public static var fontAssetDownloadError: CocoaError.Code { return CocoaError.Code(rawValue: 66304) } } // Names deprecated late in Swift 3 extension CocoaError.Code { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var textReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var serviceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var serviceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var serviceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var serviceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var serviceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneousError") public static var serviceMiscellaneous: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var sharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError { public static var textReadInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } public static var textWriteInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } public static var serviceApplicationNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } public static var serviceApplicationLaunchFailed: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } public static var serviceRequestTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } public static var serviceInvalidPasteboardData: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } public static var serviceMalformedServiceDictionary: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } public static var serviceMiscellaneous: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } public static var sharingServiceNotConfigured: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } @available(macOS 10.13, *) public static var fontAssetDownloadError: CocoaError.Code { return CocoaError.Code(rawValue: 66304) } } // Names deprecated late in Swift 3 extension CocoaError { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var textReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var serviceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var serviceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var serviceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var serviceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var serviceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var serviceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var sharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError { public var isServiceError: Bool { return code.rawValue >= 66560 && code.rawValue <= 66817 } public var isSharingServiceError: Bool { return code.rawValue >= 67072 && code.rawValue <= 67327 } public var isTextReadWriteError: Bool { return code.rawValue >= 65792 && code.rawValue <= 66303 } @available(macOS 10.13, *) public var isFontError: Bool { return code.rawValue >= 66304 && code.rawValue <= 66335 } } extension CocoaError { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var ServiceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var ServiceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var ServiceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var ServiceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var ServiceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var SharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError.Code { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var ServiceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var ServiceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var ServiceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var ServiceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var ServiceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var SharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } }
apache-2.0
bbc0d01e4dbdd3a9870916b519e5c1d0
39.684825
80
0.761668
5.259557
false
false
false
false
uasys/swift
stdlib/public/core/EmptyCollection.swift
1
4657
//===--- EmptyCollection.swift - A collection with no elements ------------===// // // 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 // //===----------------------------------------------------------------------===// // // Sometimes an operation is best expressed in terms of some other, // larger operation where one of the parameters is an empty // collection. For example, we can erase elements from an Array by // replacing a subrange with the empty collection. // //===----------------------------------------------------------------------===// /// An iterator that never produces an element. public struct EmptyIterator<Element> : IteratorProtocol, Sequence { /// Creates an instance. public init() {} /// Returns `nil`, indicating that there are no more elements. public mutating func next() -> Element? { return nil } } /// A collection whose element type is `Element` but that is always empty. public struct EmptyCollection<Element> : RandomAccessCollection, MutableCollection { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Int public typealias IndexDistance = Int public typealias SubSequence = EmptyCollection<Element> /// Creates an instance. public init() {} /// Always zero, just like `endIndex`. public var startIndex: Index { return 0 } /// Always zero, just like `startIndex`. public var endIndex: Index { return 0 } /// Always traps. /// /// `EmptyCollection` does not have any element indices, so it is not /// possible to advance indices. public func index(after i: Index) -> Index { _preconditionFailure("EmptyCollection can't advance indices") } /// Always traps. /// /// `EmptyCollection` does not have any element indices, so it is not /// possible to advance indices. public func index(before i: Index) -> Index { _preconditionFailure("EmptyCollection can't advance indices") } /// Returns an empty iterator. public func makeIterator() -> EmptyIterator<Element> { return EmptyIterator() } /// Accesses the element at the given position. /// /// Must never be called, since this collection is always empty. public subscript(position: Index) -> Element { get { _preconditionFailure("Index out of range") } set { _preconditionFailure("Index out of range") } } public subscript(bounds: Range<Index>) -> EmptyCollection<Element> { get { _debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0, "Index out of range") return self } set { _debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0, "Index out of range") } } /// The number of elements (always zero). public var count: Int { return 0 } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { _debugPrecondition(i == startIndex && n == 0, "Index out of range") return i } public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { _debugPrecondition(i == startIndex && limit == startIndex, "Index out of range") return n == 0 ? i : nil } /// The distance between two indexes (always zero). public func distance(from start: Index, to end: Index) -> IndexDistance { _debugPrecondition(start == 0, "From must be startIndex (or endIndex)") _debugPrecondition(end == 0, "To must be endIndex (or startIndex)") return 0 } public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { _debugPrecondition(index == 0, "out of bounds") _debugPrecondition(bounds == Range(indices), "invalid bounds for an empty collection") } public func _failEarlyRangeCheck( _ range: Range<Index>, bounds: Range<Index> ) { _debugPrecondition(range == Range(indices), "invalid range for an empty collection") _debugPrecondition(bounds == Range(indices), "invalid bounds for an empty collection") } public typealias Indices = CountableRange<Int> } extension EmptyCollection : Equatable { public static func == ( lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element> ) -> Bool { return true } }
apache-2.0
592ec634db61a9daba3afc6b0a611f26
30.046667
80
0.652351
4.610891
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Components/ChartYAxis.swift
5
9195
// // ChartYAxis.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Class representing the y-axis labels settings and its entries. /// Be aware that not all features the YLabels class provides are suitable for the RadarChart. /// Customizations that affect the value range of the axis need to be applied before setting data for the chart. public class ChartYAxis: ChartAxisBase { @objc public enum YAxisLabelPosition: Int { case OutsideChart case InsideChart } /// Enum that specifies the axis a DataSet should be plotted against, either Left or Right. @objc public enum AxisDependency: Int { case Left case Right } public var entries = [Double]() public var entryCount: Int { return entries.count; } /// the number of y-label entries the y-labels should have, default 6 private var _labelCount = Int(6) /// indicates if the top y-label entry is drawn or not public var drawTopYLabelEntryEnabled = true /// if true, the y-labels show only the minimum and maximum value public var showOnlyMinMaxEnabled = false /// flag that indicates if the axis is inverted or not public var inverted = false /// This property is deprecated - Use `customAxisMin` instead. public var startAtZeroEnabled: Bool { get { return isAxisMinCustom && _axisMinimum == 0.0 } set { if newValue { axisMinValue = 0.0 } else { resetCustomAxisMin() } } } /// if true, the set number of y-labels will be forced public var forceLabelsEnabled = false /// flag that indicates if the zero-line should be drawn regardless of other grid lines public var drawZeroLineEnabled = false /// Color of the zero line public var zeroLineColor: NSUIColor? = NSUIColor.grayColor() /// Width of the zero line public var zeroLineWidth: CGFloat = 1.0 /// This is how much (in pixels) into the dash pattern are we starting from. public var zeroLineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] public var zeroLineDashLengths: [CGFloat]? /// the formatter used to customly format the y-labels public var valueFormatter: NSNumberFormatter? /// the formatter used to customly format the y-labels internal var _defaultValueFormatter = NSNumberFormatter() /// axis space from the largest value to the top in percent of the total axis range public var spaceTop = CGFloat(0.1) /// axis space from the smallest value to the bottom in percent of the total axis range public var spaceBottom = CGFloat(0.1) /// the position of the y-labels relative to the chart public var labelPosition = YAxisLabelPosition.OutsideChart /// the side this axis object represents private var _axisDependency = AxisDependency.Left /// the minimum width that the axis should take /// /// **default**: 0.0 public var minWidth = CGFloat(0) /// the maximum width that the axis can take. /// use Infinity for disabling the maximum. /// /// **default**: CGFloat.infinity public var maxWidth = CGFloat(CGFloat.infinity) /// When true, axis labels are controlled by the `granularity` property. /// When false, axis values could possibly be repeated. /// This could happen if two adjacent axis values are rounded to same value. /// If using granularity this could be avoided by having fewer axis values visible. public var granularityEnabled = true /// The minimum interval between axis values. /// This can be used to avoid label duplicating when zooming in. /// /// **default**: 1.0 public var granularity = Double(1.0) public override init() { super.init() _defaultValueFormatter.minimumIntegerDigits = 1 _defaultValueFormatter.maximumFractionDigits = 1 _defaultValueFormatter.minimumFractionDigits = 1 _defaultValueFormatter.usesGroupingSeparator = true self.yOffset = 0.0 } public init(position: AxisDependency) { super.init() _axisDependency = position _defaultValueFormatter.minimumIntegerDigits = 1 _defaultValueFormatter.maximumFractionDigits = 1 _defaultValueFormatter.minimumFractionDigits = 1 _defaultValueFormatter.usesGroupingSeparator = true self.yOffset = 0.0 } public var axisDependency: AxisDependency { return _axisDependency } public func setLabelCount(count: Int, force: Bool) { _labelCount = count if (_labelCount > 25) { _labelCount = 25 } if (_labelCount < 2) { _labelCount = 2 } forceLabelsEnabled = force } /// the number of label entries the y-axis should have /// max = 25, /// min = 2, /// default = 6, /// be aware that this number is not fixed and can only be approximated public var labelCount: Int { get { return _labelCount } set { setLabelCount(newValue, force: false); } } public func requiredSize() -> CGSize { let label = getLongestLabel() as NSString var size = label.sizeWithAttributes([NSFontAttributeName: labelFont]) size.width += xOffset * 2.0 size.height += yOffset * 2.0 size.width = max(minWidth, min(size.width, maxWidth > 0.0 ? maxWidth : size.width)) return size } public func getRequiredHeightSpace() -> CGFloat { return requiredSize().height } public override func getLongestLabel() -> String { var longest = "" for i in 0 ..< entries.count { let text = getFormattedLabel(i) if (longest.characters.count < text.characters.count) { longest = text } } return longest } /// - returns: the formatted y-label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set). public func getFormattedLabel(index: Int) -> String { if (index < 0 || index >= entries.count) { return "" } return (valueFormatter ?? _defaultValueFormatter).stringFromNumber(entries[index])! } /// - returns: true if this axis needs horizontal offset, false if no offset is needed. public var needsOffset: Bool { if (isEnabled && isDrawLabelsEnabled && labelPosition == .OutsideChart) { return true } else { return false } } public var isInverted: Bool { return inverted; } /// This is deprecated now, use `customAxisMin` @available(*, deprecated=1.0, message="Use customAxisMin instead.") public var isStartAtZeroEnabled: Bool { return startAtZeroEnabled } /// - returns: true if focing the y-label count is enabled. Default: false public var isForceLabelsEnabled: Bool { return forceLabelsEnabled } public var isShowOnlyMinMaxEnabled: Bool { return showOnlyMinMaxEnabled; } public var isDrawTopYLabelEntryEnabled: Bool { return drawTopYLabelEntryEnabled; } /// Calculates the minimum, maximum and range values of the YAxis with the given minimum and maximum values from the chart data. /// - parameter dataMin: the y-min value according to chart data /// - parameter dataMax: the y-max value according to chart public func calcMinMax(min dataMin: Double, max dataMax: Double) { // if custom, use value as is, else use data value var min = _customAxisMin ? _axisMinimum : dataMin var max = _customAxisMax ? _axisMaximum : dataMax // temporary range (before calculations) let range = abs(max - min) // in case all values are equal if range == 0.0 { max = max + 1.0 min = min - 1.0 } // bottom-space only effects non-custom min if !_customAxisMin { let bottomSpace = range * Double(spaceBottom) _axisMinimum = min - bottomSpace } // top-space only effects non-custom max if !_customAxisMax { let topSpace = range * Double(spaceTop) _axisMaximum = max + topSpace } // calc actual range axisRange = abs(_axisMaximum - _axisMinimum) } }
apache-2.0
d214e46801ed5b942a5dc7f83c1ef393
28.95114
145
0.609462
4.98104
false
false
false
false
nitrado/NitrAPI-Swift
Pod/Classes/services/cloudservers/systemd/Systemd.swift
1
7057
import ObjectMapper /// This class represents a Systemd. open class Systemd: Mappable { fileprivate var nitrapi: Nitrapi! fileprivate var id: Int! init() { } required public init?(map: Map) { } public func mapping(map: Map) { } /// This class represents an Unit. open class Unit: Mappable { /// Returns objectPath. open fileprivate(set) var objectPath: String? /// Returns unitState. open fileprivate(set) var unitState: String? /// Returns description. open fileprivate(set) var description: String? /// Returns jobId. open fileprivate(set) var jobId: Int? /// Returns loadState. open fileprivate(set) var loadState: String? /// Returns filename. open fileprivate(set) var filename: String? /// Returns jobType. open fileprivate(set) var jobType: String? /// Returns jobObjectPath. open fileprivate(set) var jobObjectPath: String? /// Returns name. open fileprivate(set) var name: String! /// Returns todo enum. open fileprivate(set) var activeState: String? /// Returns todo enum. open fileprivate(set) var subState: String? /// Returns leader. open fileprivate(set) var leader: String? init() { } required public init?(map: Map) { } public func mapping(map: Map) { objectPath <- map["object_path"] unitState <- map["unit_state"] description <- map["description"] jobId <- map["job_id"] loadState <- map["load_state"] filename <- map["filename"] jobType <- map["job_type"] jobObjectPath <- map["job_object_path"] name <- map["name"] activeState <- map["active_state"] subState <- map["sub_state"] leader <- map["leader"] } } /// Lists all the units Systemd manages. /// - returns: [Unit] open func getUnits() throws -> [Unit]? { let data = try nitrapi.client.dataGet("services/\(id as Int)/cloud_servers/system/units/", parameters: [:]) let units = Mapper<Unit>().mapArray(JSONArray: data?["units"] as! [[String : Any]]) return units } /// Returns a SSE (server-send event) stream URL, which will stream changes on the Systemd services. /// - returns: String open func getChangeFeedUrl() throws -> String? { let data = try nitrapi.client.dataGet("services/\(id as Int)/cloud_servers/system/units/changefeed", parameters: [:]) let tokenurl = (data?["token"] as! [String: Any]) ["url"] as? String return tokenurl } /// Resets all units in failure state back to normal. open func resetAllFailedUnits() throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/reset_all_failed", parameters: [:]) } /// Reload the Systemd daemon. open func reloadDeamon() throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/daemon_reload", parameters: [:]) } /// Returns details for one Systemd unit. /// - parameter unitName: unitName /// - returns: Unit open func getUnit(_ unitName: String) throws -> Unit? { let data = try nitrapi.client.dataGet("services/\(id as Int)/cloud_servers/system/units/\(unitName)", parameters: [:]) let unit = Mapper<Unit>().map(JSON: data?["unit"] as! [String : Any]) return unit } /// Enables a unit so it is automatically run on startup. /// - parameter unitName: unitName open func enableUnit(_ unitName: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/enable", parameters: [:]) } /// Disables a unit so it won't automatically run on startup. /// - parameter unitName: unitName open func disableUnit(_ unitName: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/disable", parameters: [:]) } /// Send a POSIX signal to the process(es) running in a unit. /// - parameter unitName: unitName /// - parameter who: who /// - parameter signal: signal open func killUnit(_ unitName: String, who: String?, signal: Int?) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/kill", parameters: [ "who": who, "signal": signal ]) } /// Masks a unit, preventing its use altogether. /// - parameter unitName: unitName open func maskUnit(_ unitName: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/mask", parameters: [:]) } /// Unmasks a unit. /// - parameter unitName: unitName open func unmaskUnit(_ unitName: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/unmask", parameters: [:]) } /// Reload a unit. /// - parameter unitName: unitName /// - parameter replace: Replace a job that is already running open func reloadUnit(_ unitName: String, replace: Bool) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/reload", parameters: [ "replace": replace ]) } /// Resets the failure state of a unit back to normal. /// - parameter unitName: unitName open func resetUnitFailedState(_ unitName: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/reset_failed", parameters: [:]) } /// Restarts a unit. /// - parameter unitName: unitName /// - parameter replace: Replace a job that is already running open func restartUnit(_ unitName: String, replace: Bool) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/restart", parameters: [ "replace": replace ]) } /// Starts a unit. /// - parameter unitName: unitName /// - parameter replace: Replace a job that is already running open func startUnit(_ unitName: String, replace: Bool) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/start", parameters: [ "replace": replace ]) } /// Stopps a unit. /// - parameter unitName: unitName /// - parameter replace: Replace a job that is already running open func stopUnit(_ unitName: String, replace: Bool) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/cloud_servers/system/units/\(unitName)/stop", parameters: [ "replace": replace ]) } // MARK: - Internally used func postInit(_ nitrapi: Nitrapi, id: Int) { self.nitrapi = nitrapi self.id = id } }
mit
64951ac9dc82424841202a1f7ed2d480
37.145946
133
0.612158
4.396885
false
false
false
false
venkatamacha/google_password_manager
google_password_manager/google_password_manager/Reachability.swift
1
984
import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .Reachable let needsConnection = flags == .ConnectionRequired return isReachable && !needsConnection } }
mit
e22dbe4af8962d49ab3f09181113c1bf
35.481481
143
0.64126
5.290323
false
false
false
false
Zewo/TCPSSL
Source/TCPSSLServer.swift
1
1969
// TCPSSLServer.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. @_exported import TCP @_exported import OpenSSL public struct TCPSSLServer: Host { public let server: TCPServer public let context: Context public init(host: String = "0.0.0.0", port: Int, backlog: Int = 128, reusePort: Bool = false, certificate: String, privateKey: String, certificateChain: String? = nil) throws { self.server = try TCPServer(host: host, port: port, backlog: backlog, reusePort: reusePort) self.context = try Context( certificate: certificate, privateKey: privateKey, certificateChain: certificateChain ) } public func accept(timingOut deadline: Double) throws -> Stream { let stream = try server.accept(timingOut: deadline) return try SSLConnection(context: context, rawStream: stream) } }
mit
5f8c6ef9ce6a13d1a7c2fadccf6fe618
42.755556
180
0.72321
4.516055
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Maps Tab/Map/MapImageSizable.swift
1
4640
// // MapImageSizable.swift // MEGameTracker // // Created by Emily Ivie on 12/29/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit public protocol MapImageSizable: class { var map: Map? { get } var mapImageScrollView: UIScrollView? { get } var mapImageScrollHeightConstraint: NSLayoutConstraint? { get set } var mapImageWrapperView: UIView? { get set } var lastMapImageName: String? { get set } func setupMapImage(baseView: UIView?, competingView: UIView?) func resizeMapImage(baseView: UIView?, competingView: UIView?) } extension MapImageSizable { public func setupMapImage(baseView: UIView?, competingView: UIView?) { guard map?.image?.isEmpty == false, let mapImageWrapperView = mapImageWrapper() else { return } self.mapImageWrapperView = mapImageWrapperView // clean old subviews mapImageScrollView?.subviews.forEach { $0.removeFromSuperview() } // size scrollView mapImageScrollView?.contentSize = mapImageWrapperView.bounds.size mapImageScrollView?.addSubview(mapImageWrapperView) // mapImageWrapperView.fillView(mapImageScrollView) // don't do this! sizeMapImage(baseView: baseView, competingView: competingView) shiftMapImage(baseView: baseView, competingView: competingView) } public func resizeMapImage(baseView: UIView?, competingView: UIView?) { sizeMapImage(baseView: baseView, competingView: competingView) shiftMapImage(baseView: baseView, competingView: competingView) } private func sizeMapImage(baseView: UIView?, competingView: UIView?) { if mapImageScrollHeightConstraint == nil { mapImageScrollHeightConstraint = mapImageScrollView?.superview?.heightAnchor .constraint(equalToConstant: 10000) mapImageScrollHeightConstraint?.isActive = true } else { mapImageScrollHeightConstraint?.constant = 10000 } guard let mapImageScrollView = mapImageScrollView, let mapImageScrollHeightConstraint = mapImageScrollHeightConstraint, let _ = mapImageWrapperView else { return } baseView?.layoutIfNeeded() mapImageScrollView.superview?.isHidden = false let maxHeight = (baseView?.bounds.height ?? 0) - (competingView?.bounds.height ?? 0) mapImageScrollHeightConstraint.constant = maxHeight mapImageScrollView.superview?.layoutIfNeeded() mapImageScrollView.minimumZoomScale = currentImageRatio( baseView: baseView, competingView: competingView ) ?? 0.01 mapImageScrollView.maximumZoomScale = 10 mapImageScrollView.zoomScale = mapImageScrollView.minimumZoomScale } private func mapImageWrapper() -> UIView? { if lastMapImageName == map?.image && self.mapImageWrapperView != nil { return self.mapImageWrapperView } else { // clear out old values self.mapImageWrapperView?.subviews.forEach { $0.removeFromSuperview() } } guard let filename = map?.image, let basePath = Bundle.currentAppBundle.path(forResource: "Maps", ofType: nil), let pdfView = UIPDFView(url: URL(fileURLWithPath: basePath).appendingPathComponent(filename)) else { return nil } let mapImageWrapperView = UIView(frame: pdfView.bounds) mapImageWrapperView.accessibilityIdentifier = "Map Image" mapImageWrapperView.addSubview(pdfView) lastMapImageName = map?.image return mapImageWrapperView } private func shiftMapImage(baseView: UIView?, competingView: UIView?) { guard let mapImageScrollView = mapImageScrollView, let mapImageWrapperView = mapImageWrapperView, let currentImageRatio = currentImageRatio(baseView: baseView, competingView: competingView) else { return } // center in window let differenceX: CGFloat = { let x = mapImageScrollView.bounds.width - (mapImageWrapperView.bounds.width * currentImageRatio) return max(0, x) }() mapImageScrollView.contentInset.left = floor(differenceX / 2) mapImageScrollView.contentInset.right = mapImageScrollView.contentInset.left let differenceY: CGFloat = { let y = mapImageScrollView.bounds.height - (mapImageWrapperView.bounds.height * currentImageRatio) return max(0, y) }() mapImageScrollView.contentInset.top = floor(differenceY / 2) mapImageScrollView.contentInset.bottom = mapImageScrollView.contentInset.top } private func currentImageRatio(baseView: UIView?, competingView: UIView?) -> CGFloat? { guard let mapImageWrapperView = self.mapImageWrapperView, mapImageWrapperView.bounds.height > 0 else { return nil } let maxWidth = baseView?.bounds.width ?? 0 let maxHeight = (baseView?.bounds.height ?? 0) - (competingView?.bounds.height ?? 0) return min(maxWidth / mapImageWrapperView.bounds.width, maxHeight / mapImageWrapperView.bounds.height) } }
mit
047486bb8a7dc98a7a0b57b485648582
36.41129
110
0.764173
4.565945
false
false
false
false
SteeweGriffin/STWPageViewController
Example/Example/AppDelegate.swift
1
7336
// // AppDelegate.swift // Example // // Created by Steewe MacBook Pro on 14/09/17. // Copyright © 2017 Steewe. All rights reserved. // import UIKit import STWPageViewController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) //----------------------------------------------- // DIRECT INIT let firstController = SubViewController(title: "First", color: .orange) let secondController = SubViewController(title: "Second", color: .blue) let thirdController = SubViewController(title: "Third", color: .purple) let fourthController = SubViewController(title: "Fourth", color: .cyan) let pages = [firstController, secondController, thirdController, fourthController] let pageController = ViewController(pages: pages) self.window?.rootViewController = pageController //----------------------------------------------- // //----------------------------------------------- // // DIRECT INIT IN NAVIGATION // // let firstController = SubViewController(title: "First", color: .orange) // let secondController = SubViewController(title: "Second", color: .blue) // let thirdController = SubViewController(title: "Third", color: .purple) // let fourthController = SubViewController(title: "Fourth", color: .cyan) // // let pages = [firstController, secondController, thirdController, fourthController] // // let pageController = ViewController(pages: pages) // let navigationController = UINavigationController(rootViewController: pageController) // // self.window?.rootViewController = navigationController // //----------------------------------------------- // //----------------------------------------------- // // SET PAGES AFTER INIT // // let firstController = SubViewController() // let secondController = SubViewController() // let thirdController = SubViewController() // let fourthController = SubViewController() // // //############################################### // // AUTO CREATE STWPageViewControllerToolBarItem // // firstController.title = "First" // firstController.view.backgroundColor = .orange // secondController.title = "Second" // secondController.view.backgroundColor = .blue // thirdController.title = "Third" // thirdController.view.backgroundColor = .purple // fourthController.title = "Fourth" // fourthController.view.backgroundColor = .cyan // //############################################### // //// //############################################### //// // CUSTOM STWPageViewControllerToolBarItem BY STRING TITLE //// //// firstController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(title: "!First", normalColor: .orange, selectedColor: .red) //// firstController.view.backgroundColor = .orange //// secondController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(title: "*Second", normalColor: .orange, selectedColor: .red) //// secondController.view.backgroundColor = .blue //// thirdController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(title: "@Third", normalColor: .orange, selectedColor: .red) //// thirdController.view.backgroundColor = .purple //// fourthController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(title: "°Fourth", normalColor: .orange, selectedColor: .red) //// fourthController.view.backgroundColor = .cyan //// //############################################### // //// //############################################### //// // CUSTOM STWPageViewControllerToolBarItem BY ICON //// //// firstController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(image: #imageLiteral(resourceName: "icon1Default"), selectedImage: #imageLiteral(resourceName: "icon1Active")) //// firstController.view.backgroundColor = .orange //// secondController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(image: #imageLiteral(resourceName: "icon2Default"), selectedImage: #imageLiteral(resourceName: "icon2Active")) //// secondController.view.backgroundColor = .blue //// thirdController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(image: #imageLiteral(resourceName: "icon3Default"), selectedImage: #imageLiteral(resourceName: "icon3Active")) //// thirdController.view.backgroundColor = .purple //// fourthController.pageViewControllerToolBarItem = STWPageViewControllerToolBarItem(image: #imageLiteral(resourceName: "icon4Default"), selectedImage: #imageLiteral(resourceName: "icon4Active")) //// fourthController.view.backgroundColor = .cyan //// //############################################### // // let pages = [firstController, secondController, thirdController, fourthController] // let pageController = ViewController(pages: pages) // pageController.setPages(pages: pages) // // self.window?.rootViewController = pageController // //----------------------------------------------- //MAKE KEY AND VISIBLE self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
102ee04fa2415c165371d94f8d19658f
52.144928
285
0.64985
5.972313
false
false
false
false
JustHTTP/Just
Sources/Just/Just.swift
2
32131
import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif #if os(Linux) import Dispatch #endif // stolen from python-requests let statusCodeDescriptions = [ // Informational. 100: "continue", 101: "switching protocols", 102: "processing", 103: "checkpoint", 122: "uri too long", 200: "ok", 201: "created", 202: "accepted", 203: "non authoritative info", 204: "no content", 205: "reset content", 206: "partial content", 207: "multi status", 208: "already reported", 226: "im used", // Redirection. 300: "multiple choices", 301: "moved permanently", 302: "found", 303: "see other", 304: "not modified", 305: "use proxy", 306: "switch proxy", 307: "temporary redirect", 308: "permanent redirect", // Client Error. 400: "bad request", 401: "unauthorized", 402: "payment required", 403: "forbidden", 404: "not found", 405: "method not allowed", 406: "not acceptable", 407: "proxy authentication required", 408: "request timeout", 409: "conflict", 410: "gone", 411: "length required", 412: "precondition failed", 413: "request entity too large", 414: "request uri too large", 415: "unsupported media type", 416: "requested range not satisfiable", 417: "expectation failed", 418: "im a teapot", 422: "unprocessable entity", 423: "locked", 424: "failed dependency", 425: "unordered collection", 426: "upgrade required", 428: "precondition required", 429: "too many requests", 431: "header fields too large", 444: "no response", 449: "retry with", 450: "blocked by windows parental controls", 451: "unavailable for legal reasons", 499: "client closed request", // Server Error. 500: "internal server error", 501: "not implemented", 502: "bad gateway", 503: "service unavailable", 504: "gateway timeout", 505: "http version not supported", 506: "variant also negotiates", 507: "insufficient storage", 509: "bandwidth limit exceeded", 510: "not extended", ] public enum HTTPFile { case url(URL, String?) // URL to a file, mimetype case data(String, Foundation.Data, String?) // filename, data, mimetype case text(String, String, String?) // filename, text, mimetype } // Supported request types public enum HTTPMethod: String { case delete = "DELETE" case get = "GET" case head = "HEAD" case options = "OPTIONS" case patch = "PATCH" case post = "POST" case put = "PUT" } extension URLResponse { var HTTPHeaders: [String: String] { return (self as? HTTPURLResponse)?.allHeaderFields as? [String: String] ?? [:] } } public protocol URLComponentsConvertible { var urlComponents: URLComponents? { get } } extension String: URLComponentsConvertible { public var urlComponents: URLComponents? { return URLComponents(string: self) } } extension URL: URLComponentsConvertible { public var urlComponents: URLComponents? { return URLComponents(url: self, resolvingAgainstBaseURL: true) } } /// The only reason this is not a struct is the requirements for /// lazy evaluation of `headers` and `cookies`, which is mutating the /// struct. This would make those properties unusable with `HTTPResult`s /// declared with `let` public final class HTTPResult : NSObject { public final var content: Data? public var response: URLResponse? public var error: Error? public var request: URLRequest? { return task?.originalRequest } public var task: URLSessionTask? public var encoding = String.Encoding.utf8 public var JSONReadingOptions = JSONSerialization.ReadingOptions(rawValue: 0) public var reason: String { if let code = self.statusCode, let text = statusCodeDescriptions[code] { return text } if let error = self.error { return error.localizedDescription } return "Unknown" } public var isRedirect: Bool { if let code = self.statusCode { return code >= 300 && code < 400 } return false } public var isPermanentRedirect: Bool { return self.statusCode == 301 } public override var description: String { if let status = statusCode, let urlString = request?.url?.absoluteString, let method = request?.httpMethod { return "\(method) \(urlString) \(status)" } else { return "<Empty>" } } public init(data: Data?, response: URLResponse?, error: Error?, task: URLSessionTask?) { self.content = data self.response = response self.error = error self.task = task } public var json: Any? { return content.flatMap { try? JSONSerialization.jsonObject(with: $0, options: JSONReadingOptions) } } public var statusCode: Int? { return (self.response as? HTTPURLResponse)?.statusCode } public var text: String? { return content.flatMap { String(data: $0, encoding: encoding) } } public lazy var headers: CaseInsensitiveDictionary<String, String> = { return CaseInsensitiveDictionary<String, String>( dictionary: self.response?.HTTPHeaders ?? [:]) }() public lazy var cookies: [String: HTTPCookie] = { let foundCookies: [HTTPCookie] if let headers = self.response?.HTTPHeaders, let url = self.response?.url { foundCookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url) } else { foundCookies = [] } var result: [String: HTTPCookie] = [:] for cookie in foundCookies { result[cookie.name] = cookie } return result }() public var ok: Bool { return statusCode != nil && !(statusCode! >= 400 && statusCode! < 600) } public var url: URL? { return response?.url } public lazy var links: [String: [String: String]] = { var result = [String: [String: String]]() guard let content = self.headers["link"] else { return result } content.components(separatedBy: ", ").forEach { s in let linkComponents = s.components(separatedBy: ";") .map { $0.trimmingCharacters(in: CharacterSet.whitespaces) } // although a link without a rel is valid, there's no way to reference it. if linkComponents.count > 1 { let url = linkComponents.first! let start = url.index(url.startIndex, offsetBy: 1) let end = url.index(url.endIndex, offsetBy: -1) let urlRange = start..<end var link: [String: String] = ["url": String(url[urlRange])] linkComponents.dropFirst().forEach { s in if let equalIndex = s.firstIndex(of: "=") { let componentKey = String(s[s.startIndex..<equalIndex]) let range = s.index(equalIndex, offsetBy: 1)..<s.endIndex let value = s[range] if value.first == "\"" && value.last == "\"" { let start = value.index(value.startIndex, offsetBy: 1) let end = value.index(value.endIndex, offsetBy: -1) link[componentKey] = String(value[start..<end]) } else { link[componentKey] = String(value) } } } if let rel = link["rel"] { result[rel] = link } } } return result }() public func cancel() { task?.cancel() } } public struct CaseInsensitiveDictionary<Key: Hashable, Value>: Collection, ExpressibleByDictionaryLiteral { private var _data: [Key: Value] = [:] private var _keyMap: [String: Key] = [:] public typealias Element = (key: Key, value: Value) public typealias Index = DictionaryIndex<Key, Value> public var startIndex: Index { return _data.startIndex } public var endIndex: Index { return _data.endIndex } public func index(after: Index) -> Index { return _data.index(after: after) } public var count: Int { assert(_data.count == _keyMap.count, "internal keys out of sync") return _data.count } public var isEmpty: Bool { return _data.isEmpty } public init(dictionaryLiteral elements: (Key, Value)...) { for (key, value) in elements { _keyMap["\(key)".lowercased()] = key _data[key] = value } } public init(dictionary: [Key: Value]) { for (key, value) in dictionary { _keyMap["\(key)".lowercased()] = key _data[key] = value } } public subscript (position: Index) -> Element { return _data[position] } public subscript (key: Key) -> Value? { get { if let realKey = _keyMap["\(key)".lowercased()] { return _data[realKey] } return nil } set(newValue) { let lowerKey = "\(key)".lowercased() if _keyMap[lowerKey] == nil { _keyMap[lowerKey] = key } _data[_keyMap[lowerKey]!] = newValue } } public func makeIterator() -> DictionaryIterator<Key, Value> { return _data.makeIterator() } public var keys: Dictionary<Key, Value>.Keys { return _data.keys } public var values: Dictionary<Key, Value>.Values { return _data.values } } typealias TaskID = Int public typealias Credentials = (username: String, password: String) public typealias TaskProgressHandler = (HTTPProgress) -> Void typealias TaskCompletionHandler = (HTTPResult) -> Void struct TaskConfiguration { let credential: Credentials? let redirects: Bool let originalRequest: URLRequest? var data: Data let progressHandler: TaskProgressHandler? let completionHandler: TaskCompletionHandler? } public struct JustSessionDefaults { public var JSONReadingOptions: JSONSerialization.ReadingOptions public var JSONWritingOptions: JSONSerialization.WritingOptions public var headers: [String: String] public var multipartBoundary: String public var credentialPersistence: URLCredential.Persistence public var encoding: String.Encoding public var cachePolicy: NSURLRequest.CachePolicy public init( JSONReadingOptions: JSONSerialization.ReadingOptions = JSONSerialization.ReadingOptions(rawValue: 0), JSONWritingOptions: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0), headers: [String: String] = [:], multipartBoundary: String = "Ju5tH77P15Aw350m3", credentialPersistence: URLCredential.Persistence = .forSession, encoding: String.Encoding = String.Encoding.utf8, cachePolicy: NSURLRequest.CachePolicy = .reloadIgnoringLocalCacheData) { self.JSONReadingOptions = JSONReadingOptions self.JSONWritingOptions = JSONWritingOptions self.headers = headers self.multipartBoundary = multipartBoundary self.encoding = encoding self.credentialPersistence = credentialPersistence self.cachePolicy = cachePolicy } } public struct HTTPProgress { public enum `Type` { case upload case download } public let type: Type public let bytesProcessed: Int64 public let bytesExpectedToProcess: Int64 public var chunk: Data? public var percent: Float { return Float(bytesProcessed) / Float(bytesExpectedToProcess) } } let errorDomain = "net.justhttp.Just" public protocol JustAdaptor { func request( _ method: HTTPMethod, url: URLComponentsConvertible, params: [String: Any], data: [String: Any], json: Any?, headers: [String: String], files: [String: HTTPFile], auth: Credentials?, cookies: [String: String], redirects: Bool, timeout: Double?, urlQuery: String?, requestBody: Data?, asyncProgressHandler: TaskProgressHandler?, asyncCompletionHandler: ((HTTPResult) -> Void)? ) -> HTTPResult init(session: URLSession?, defaults: JustSessionDefaults?) } public struct JustOf<Adaptor: JustAdaptor> { let adaptor: Adaptor public init(session: URLSession? = nil, defaults: JustSessionDefaults? = nil) { adaptor = Adaptor(session: session, defaults: defaults) } } extension JustOf { @discardableResult public func request( _ method: HTTPMethod, url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( method, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func delete( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .delete, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func get( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .get, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func head( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .head, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func options( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .options, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func patch( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .patch, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func post( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .post, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func put( _ url: URLComponentsConvertible, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, urlQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .put, url: url, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } } public final class HTTP: NSObject, URLSessionDelegate, JustAdaptor { public init(session: URLSession? = nil, defaults: JustSessionDefaults? = nil) { super.init() if let initialSession = session { self.session = initialSession } else { self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) } if let initialDefaults = defaults { self.defaults = initialDefaults } else { self.defaults = JustSessionDefaults() } } var taskConfigs: [TaskID: TaskConfiguration]=[:] var defaults: JustSessionDefaults! var session: URLSession! var invalidURLError = NSError( domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "[Just] URL is invalid"] ) var syncResultAccessError = NSError( domain: errorDomain, code: 1, userInfo: [ NSLocalizedDescriptionKey: "[Just] You are accessing asynchronous result synchronously." ] ) func queryComponents(_ key: String, _ value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [Any] { for value in array { components += queryComponents("\(key)", value) } } else { components.append(( percentEncodeString(key), percentEncodeString("\(value)")) ) } return components } func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for (key, value) in parameters.sorted(by: { $0.key < $1.key }) { components += self.queryComponents(key, value) } return (components.map { "\($0)=\($1)" }).joined(separator: "&") } func percentEncodeString(_ originalObject: Any) -> String { if originalObject is NSNull { return "null" } else { var reserved = CharacterSet.urlQueryAllowed reserved.remove(charactersIn: ": #[]@!$&'()*+, ;=") return String(describing: originalObject) .addingPercentEncoding(withAllowedCharacters: reserved) ?? "" } } func makeTask(_ request: URLRequest, configuration: TaskConfiguration) -> URLSessionDataTask? { let task = session.dataTask(with: request) taskConfigs[task.taskIdentifier] = configuration return task } func synthesizeMultipartBody(_ data: [String: Any], files: [String: HTTPFile]) -> Data? { var body = Data() let boundary = "--\(self.defaults.multipartBoundary)\r\n" .data(using: defaults.encoding)! for (k, v) in data { let valueToSend: Any = v is NSNull ? "null" : v body.append(boundary) body.append("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n" .data(using: defaults.encoding)!) body.append("\(valueToSend)\r\n".data(using: defaults.encoding)!) } for (k, v) in files { body.append(boundary) var partContent: Data? = nil var partFilename: String? = nil var partMimetype: String? = nil switch v { case let .url(URL, mimetype): partFilename = URL.lastPathComponent if let URLContent = try? Data(contentsOf: URL) { partContent = URLContent } partMimetype = mimetype case let .text(filename, text, mimetype): partFilename = filename if let textData = text.data(using: defaults.encoding) { partContent = textData } partMimetype = mimetype case let .data(filename, data, mimetype): partFilename = filename partContent = data partMimetype = mimetype } if let content = partContent, let filename = partFilename { let dispose = "Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(filename)\"\r\n" body.append(dispose.data(using: defaults.encoding)!) if let type = partMimetype { body.append( "Content-Type: \(type)\r\n\r\n".data(using: defaults.encoding)!) } else { body.append("\r\n".data(using: defaults.encoding)!) } body.append(content) body.append("\r\n".data(using: defaults.encoding)!) } } if body.count > 0 { body.append("--\(self.defaults.multipartBoundary)--\r\n" .data(using: defaults.encoding)!) } return body } public func synthesizeRequest( _ method: HTTPMethod, url: URLComponentsConvertible, params: [String: Any], data: [String: Any], json: Any?, headers: CaseInsensitiveDictionary<String, String>, files: [String: HTTPFile], auth: Credentials?, timeout: Double?, urlQuery: String?, requestBody: Data? ) -> URLRequest? { if var urlComponents = url.urlComponents { let queryString = query(params) if queryString.count > 0 { urlComponents.percentEncodedQuery = queryString } var finalHeaders = headers var contentType: String? = nil var body: Data? if let requestData = requestBody { body = requestData } else if files.count > 0 { body = synthesizeMultipartBody(data, files: files) let bound = self.defaults.multipartBoundary contentType = "multipart/form-data; boundary=\(bound)" } else { if let requestJSON = json { contentType = "application/json" body = try? JSONSerialization.data(withJSONObject: requestJSON, options: defaults.JSONWritingOptions) } else { if data.count > 0 { // assume user wants JSON if she is using this header if headers["content-type"]?.lowercased() == "application/json" { body = try? JSONSerialization.data(withJSONObject: data, options: defaults.JSONWritingOptions) } else { contentType = "application/x-www-form-urlencoded" body = query(data).data(using: defaults.encoding) } } } } if let contentTypeValue = contentType { finalHeaders["Content-Type"] = contentTypeValue } if let auth = auth, let utf8 = "\(auth.0):\(auth.1)".data(using: String.Encoding.utf8) { finalHeaders["Authorization"] = "Basic \(utf8.base64EncodedString())" } if let URL = urlComponents.url { var request = URLRequest(url: URL) request.cachePolicy = defaults.cachePolicy request.httpBody = body request.httpMethod = method.rawValue if let requestTimeout = timeout { request.timeoutInterval = requestTimeout } for (k, v) in defaults.headers { request.addValue(v, forHTTPHeaderField: k) } for (k, v) in finalHeaders { request.addValue(v, forHTTPHeaderField: k) } return request } } return nil } public func request( _ method: HTTPMethod, url: URLComponentsConvertible, params: [String: Any], data: [String: Any], json: Any?, headers: [String: String], files: [String: HTTPFile], auth: Credentials?, cookies: [String: String], redirects: Bool, timeout: Double?, urlQuery: String?, requestBody: Data?, asyncProgressHandler: TaskProgressHandler?, asyncCompletionHandler: ((HTTPResult) -> Void)?) -> HTTPResult { let isSynchronous = asyncCompletionHandler == nil let semaphore = DispatchSemaphore(value: 0) var requestResult: HTTPResult = HTTPResult(data: nil, response: nil, error: syncResultAccessError, task: nil) let caseInsensitiveHeaders = CaseInsensitiveDictionary<String, String>( dictionary: headers) guard let request = synthesizeRequest(method, url: url, params: params, data: data, json: json, headers: caseInsensitiveHeaders, files: files, auth: auth, timeout: timeout, urlQuery: urlQuery, requestBody: requestBody) else { let erronousResult = HTTPResult(data: nil, response: nil, error: invalidURLError, task: nil) if let handler = asyncCompletionHandler { handler(erronousResult) } return erronousResult } addCookies(request.url!, newCookies: cookies) let config = TaskConfiguration( credential: auth, redirects: redirects, originalRequest: request, data: Data(), progressHandler: asyncProgressHandler) { result in if let handler = asyncCompletionHandler { handler(result) } if isSynchronous { requestResult = result semaphore.signal() } } if let task = makeTask(request, configuration: config) { task.resume() } if isSynchronous { let timeout = timeout.flatMap { DispatchTime.now() + $0 } ?? DispatchTime.distantFuture _ = semaphore.wait(timeout: timeout) return requestResult } return requestResult } func addCookies(_ URL: Foundation.URL, newCookies: [String: String]) { for (k, v) in newCookies { if let cookie = HTTPCookie(properties: [ HTTPCookiePropertyKey.name: k, HTTPCookiePropertyKey.value: v, HTTPCookiePropertyKey.originURL: URL, HTTPCookiePropertyKey.path: "/" ]) { session.configuration.httpCookieStorage?.setCookie(cookie) } } } } extension HTTP: URLSessionTaskDelegate, URLSessionDataDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var endCredential: URLCredential? = nil if let taskConfig = taskConfigs[task.taskIdentifier], let credential = taskConfig.credential { if !(challenge.previousFailureCount > 0) { endCredential = URLCredential( user: credential.0, password: credential.1, persistence: self.defaults.credentialPersistence ) } } completionHandler(.useCredential, endCredential) } public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { if let allowRedirects = taskConfigs[task.taskIdentifier]?.redirects { if !allowRedirects { completionHandler(nil) return } completionHandler(request) } else { completionHandler(request) } } public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let handler = taskConfigs[task.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .upload, bytesProcessed: totalBytesSent, bytesExpectedToProcess: totalBytesExpectedToSend, chunk: nil ) ) } } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let handler = taskConfigs[dataTask.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .download, bytesProcessed: dataTask.countOfBytesReceived, bytesExpectedToProcess: dataTask.countOfBytesExpectedToReceive, chunk: data ) ) } if taskConfigs[dataTask.taskIdentifier]?.data != nil { taskConfigs[dataTask.taskIdentifier]?.data.append(data) } } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let config = taskConfigs[task.taskIdentifier], let handler = config.completionHandler { let result = HTTPResult( data: config.data, response: task.response, error: error, task: task ) result.JSONReadingOptions = self.defaults.JSONReadingOptions result.encoding = self.defaults.encoding handler(result) } taskConfigs.removeValue(forKey: task.taskIdentifier) } } public let Just = JustOf<HTTP>()
mit
14c4938e9c667bad621a7dedfe1cbfc6
27.434513
99
0.635741
4.526768
false
false
false
false
charmaex/JDTransition
Demo/Demo/ViewController.swift
1
878
// // ViewController.swift // Demo // // Created by Jan Dammshäuser on 29.08.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit import JDTransition class ViewController: UIViewController { @IBAction func upperBtn(_ sender: UIButton) { performSegue(withIdentifier: Segues.ScaleIn.rawValue, sender: sender) } @IBAction func lowerBtn(_ sender: UIButton) { let nextVC = SecondViewController() let segue = JDSegueScaleOut(identifier: nil, source: self, destination: nextVC) segue.animationOrigin = sender.center segue.transitionTime = 2 segue.perform() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segue = segue as? JDSegueScaleIn, let sender = sender as? UIView { segue.animationOrigin = sender.center } } }
mit
de0e00394e70ac8db18269932317b160
24.735294
87
0.667429
4.441624
false
false
false
false
Progeny/Urk
Source/Urk.swift
1
3619
// // Urk.swift // // // Created by Vito Bellini on 12/04/15. // // import Foundation extension NSDate { var formatted: String { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" return formatter.stringFromDate(self) } } public enum LogType: Int { case Info case Success case Warning case Error public static let allValues = [Info, Success, Warning, Error] var description : String { switch self { case .Info: return "Info" case .Success: return "Success" case .Warning: return "Warning" case .Error: return "Error" } } } public class Manager { public var shouldPrintTimestamp: Bool = true public var shouldPrintLogType: Bool = true public var function: Bool = true public var outputLogs: [LogType] = LogType.allValues /** A shared instance of Manager, used by top-level Urk methods. */ public static let sharedInstance: Manager = { return Manager() }() /** Prints a log message. - parameter type: The log type. - parameter message: The message to print. */ func log(type: LogType, message: String, filename: String, line: Int, funcname: String) { var parts: [String] = [] if shouldPrintTimestamp { parts += [NSDate().formatted] } if function { let f = NSURL(fileURLWithPath: filename) if let lastPathComponent = f.lastPathComponent { let part = String(format: "%@(%d) %@", arguments: [lastPathComponent, line, funcname]) parts += [part] } } if shouldPrintLogType { let part = String(format: "%@:", arguments: [type.description.uppercaseString]) parts += [part] } parts += [message] let output = parts.joinWithSeparator(" ") if self.outputLogs.contains(type) { print(output) } } } // MARK: - Log public var shouldPrintTimestamp: Bool { set { Manager.sharedInstance.shouldPrintTimestamp = newValue } get { return Manager.sharedInstance.shouldPrintTimestamp } } public var shouldPrintLogType: Bool { set { Manager.sharedInstance.shouldPrintLogType = newValue } get { return Manager.sharedInstance.shouldPrintLogType } } /** Defines the log's type to print. */ public var outputLogs: [LogType] { set { Manager.sharedInstance.outputLogs = newValue } get { return Manager.sharedInstance.outputLogs } } /** Logs an info message. - parameter message: The message to print. */ public func info(message: String, filename: String = __FILE__, line: Int = __LINE__, funcname: String = __FUNCTION__) { return Manager.sharedInstance.log(LogType.Info, message: message, filename: filename, line: line, funcname: funcname) } /** Logs a success message. - parameter message: The message to print. */ public func success(message: String, filename: String = __FILE__, line: Int = __LINE__, funcname: String = __FUNCTION__) { return Manager.sharedInstance.log(LogType.Success, message: message, filename: filename, line: line, funcname: funcname) } /** Logs a warning message. - parameter message: The message to print. */ public func warning(message: String, filename: String = __FILE__, line: Int = __LINE__, funcname: String = __FUNCTION__) { return Manager.sharedInstance.log(LogType.Warning, message: message, filename: filename, line: line, funcname: funcname) } /** Logs an error message. - parameter message: The message to print. */ public func error(message: String, filename: String = __FILE__, line: Int = __LINE__, funcname: String = __FUNCTION__) { return Manager.sharedInstance.log(LogType.Error, message: message, filename: filename, line: line, funcname: funcname) }
mit
8acf95c82d55d15fe65ba9c62edf34d0
21.208589
122
0.686654
3.600995
false
false
false
false
baottran/nSURE
nSURE/LoginViewController.swift
1
3385
// // LoginViewController.swift // NSURE // // Created by Bao on 6/21/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit import Parse import MBProgressHUD class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() passwordField.secureTextEntry = true usernameField.delegate = self passwordField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(){ print("logging in", terminator: "") let loginModal = MBProgressHUD.showHUDAddedTo(self.view, animated: true) loginModal.labelText = "Logging In" PFUser.logInWithUsernameInBackground(usernameField.text!, password: passwordField.text!) { (user: PFUser?, error: NSError?) -> Void in MBProgressHUD.hideAllHUDsForView(self.view, animated: true) if user != nil { print("login success", terminator: "") dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("toRevealController", sender: self) } } else { print("error: \(error)", terminator: "") let alert = UIAlertController(title: "Error", message: "Login unsuccessful. Please Try Again", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } } @IBAction func signUp(){ print("signup", terminator: "") } @IBAction func loginAsGuest(){ let loginModal = MBProgressHUD.showHUDAddedTo(self.view, animated: true) loginModal.labelText = "Logging In" PFUser.logInWithUsernameInBackground("bao", password: "thisisatest") { (user: PFUser?, error: NSError?) -> Void in MBProgressHUD.hideAllHUDsForView(self.view, animated: true) if user != nil { print("login success", terminator: "") dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("toRevealController", sender: self) } } else { print("error: \(error)", terminator: "") let alert = UIAlertController(title: "Error", message: "Login unsuccessful. Please Try Again", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } } func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField == usernameField){ passwordField.becomeFirstResponder() } else if (textField == passwordField){ login() } return true } }
mit
7d3710666bbb50f0b46543aa981b1f0d
33.540816
156
0.594387
5.468498
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/variables/value_of_optionals/main.swift
2
606
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- struct S { var a: Int8 = 1 var b: Int8 = 1 var c: Int8 = 1 var d: Int8 = 1 } func main() { var s: S? = S() print(s) // break here } main()
apache-2.0
8bac1e9f8112087ded45a02d4ec927b6
23.24
80
0.579208
3.695122
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/NetworkStatus/OfflineBar.swift
1
3011
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireCommonComponents final class OfflineBar: UIView { private let offlineLabel: UILabel private lazy var heightConstraint: NSLayoutConstraint = heightAnchor.constraint(equalToConstant: 0) var state: NetworkStatusViewState = .online { didSet { if oldValue != state { updateView() } } } convenience init() { self.init(frame: .zero) } override init(frame: CGRect) { offlineLabel = UILabel() super.init(frame: frame) backgroundColor = UIColor(rgb: 0xFEBF02, alpha: 1) layer.cornerRadius = CGFloat.OfflineBar.cornerRadius layer.masksToBounds = true offlineLabel.font = FontSpec(FontSize.small, .medium).font offlineLabel.textColor = UIColor.white offlineLabel.text = "system_status_bar.no_internet.title".localized(uppercased: true) addSubview(offlineLabel) createConstraints() updateView() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createConstraints() { offlineLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ offlineLabel.centerXAnchor.constraint(equalTo: centerXAnchor), offlineLabel.centerYAnchor.constraint(equalTo: centerYAnchor), offlineLabel.leftAnchor.constraint(greaterThanOrEqualTo: layoutMarginsGuide.leftAnchor), offlineLabel.rightAnchor.constraint(lessThanOrEqualTo: layoutMarginsGuide.rightAnchor), heightConstraint ]) } private func updateView() { switch state { case .online: heightConstraint.constant = 0 offlineLabel.alpha = 0 layer.cornerRadius = 0 case .onlineSynchronizing: heightConstraint.constant = CGFloat.SyncBar.height offlineLabel.alpha = 0 layer.cornerRadius = CGFloat.SyncBar.cornerRadius case .offlineExpanded: heightConstraint.constant = CGFloat.OfflineBar.expandedHeight offlineLabel.alpha = 1 layer.cornerRadius = CGFloat.OfflineBar.cornerRadius } } }
gpl-3.0
657c8ca2042b8acd094a86c632076a50
31.728261
103
0.675523
5.200345
false
false
false
false
zendobk/SwiftUtils
Sources/Extensions/UIImage.swift
1
985
// // UIImage.swift // SwiftUtils // // Created by DaoNV on 10/23/15. // Copyright © 2016 Asian Tech Co., Ltd. All rights reserved. // import UIKit extension UIImage { public func scaleToSize(_ newSize: CGSize, aspectFill: Bool = false) -> UIImage { let scaleFactorWidth = newSize.width / size.width let scaleFactorHeight = newSize.height / size.height let scaleFactor = aspectFill ? max(scaleFactorWidth, scaleFactorHeight) : min(scaleFactorWidth, scaleFactorHeight) var scaledSize = size scaledSize.width *= scaleFactor scaledSize.height *= scaleFactor UIGraphicsBeginImageContextWithOptions(scaledSize, false, UIScreen.main.scale) let scaledImageRect = CGRect(x: 0.0, y: 0.0, width: scaledSize.width, height: scaledSize.height) draw(in: scaledImageRect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } }
apache-2.0
623948672435ade09ca21cd808ffcf2c
32.931034
122
0.695122
4.776699
false
false
false
false
ianyh/Amethyst
Amethyst/Managers/Windows.swift
1
5410
// // Windows.swift // Amethyst // // Created by Ian Ynda-Hummel on 9/15/19. // Copyright © 2019 Ian Ynda-Hummel. All rights reserved. // import Foundation import Silica extension WindowManager { class Windows { private(set) var windows: [Window] = [] private var activeIDCache: Set<CGWindowID> = Set() private var deactivatedPIDs: Set<pid_t> = Set() private var floatingMap: [Window.WindowID: Bool] = [:] // MARK: Window Filters func window(withID id: Window.WindowID) -> Window? { return windows.first { $0.id() == id } } func windows(forApplicationWithPID applicationPID: pid_t) -> [Window] { return windows.filter { $0.pid() == applicationPID } } func windows(onScreen screen: Screen) -> [Window] { return windows.filter { $0.screen() == screen } } func activeWindows(onScreen screen: Screen) -> [Window] { guard let screenID = screen.screenID() else { return [] } guard let currentSpace = CGSpacesInfo<Window>.currentSpaceForScreen(screen) else { log.warning("Could not find a space for screen: \(screenID)") return [] } let screenWindows = windows.filter { window in let space = CGWindowsInfo.windowSpace(window) guard let windowScreen = window.screen(), currentSpace.id == space else { return false } let isActive = self.isWindowActive(window) let isHidden = self.isWindowHidden(window) let isFloating = self.isWindowFloating(window) return windowScreen.screenID() == screen.screenID() && isActive && !isHidden && !isFloating } return screenWindows } // MARK: Adding and Removing func add(window: Window, atFront shouldInsertAtFront: Bool) { if shouldInsertAtFront { windows.insert(window, at: 0) } else { windows.append(window) } } func remove(window: Window) { guard let windowIndex = windows.index(of: window) else { return } windows.remove(at: windowIndex) } @discardableResult func swap(window: Window, withWindow otherWindow: Window) -> Bool { guard let windowIndex = windows.index(of: window), let otherWindowIndex = windows.index(of: otherWindow) else { return false } guard windowIndex != otherWindowIndex else { return false } windows[windowIndex] = otherWindow windows[otherWindowIndex] = window return true } // MARK: Window States func isWindowTracked(_ window: Window) -> Bool { return windows.contains(window) } func isWindowActive(_ window: Window) -> Bool { return window.isActive() && activeIDCache.contains(window.cgID()) } func isWindowHidden(_ window: Window) -> Bool { return deactivatedPIDs.contains(window.pid()) } func isWindowFloating(_ window: Window) -> Bool { return floatingMap[window.id()] ?? false } func setFloating(_ floating: Bool, forWindow window: Window) { floatingMap[window.id()] = floating } func activateApplication(withPID pid: pid_t) { deactivatedPIDs.remove(pid) } func deactivateApplication(withPID pid: pid_t) { deactivatedPIDs.insert(pid) } func regenerateActiveIDCache() { let windowDescriptions = CGWindowsInfo<Window>(options: .optionOnScreenOnly, windowID: CGWindowID(0)) activeIDCache = windowDescriptions?.activeIDs() ?? Set() } // MARK: Window Sets func windowSet(forWindowsOnScreen screen: Screen) -> WindowSet<Window> { return windowSet(forWindows: windows(onScreen: screen)) } func windowSet(forActiveWindowsOnScreen screen: Screen) -> WindowSet<Window> { return windowSet(forWindows: activeWindows(onScreen: screen)) } func windowSet(forWindows windows: [Window]) -> WindowSet<Window> { let layoutWindows: [LayoutWindow<Window>] = windows.map { LayoutWindow(id: $0.id(), frame: $0.frame(), isFocused: $0.isFocused()) } return WindowSet<Window>( windows: layoutWindows, isWindowWithIDActive: { [weak self] id -> Bool in guard let window = self?.window(withID: id) else { return false } return self?.isWindowActive(window) ?? false }, isWindowWithIDFloating: { [weak self] windowID -> Bool in guard let window = self?.window(withID: windowID) else { return false } return self?.isWindowFloating(window) ?? false }, windowForID: { [weak self] windowID -> Window? in return self?.window(withID: windowID) } ) } } }
mit
6f831d33bc8a13a03d3c3108c2e66443
31.981707
123
0.549639
4.859838
false
false
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/Tent.swift
1
1032
// // Tent.swift // Pods // // Created by Mohssen Fathi on 6/18/16. // // import UIKit import MetalPerformanceShaders public class Tent: MPS { @objc public var radius: Float = 0.5 { didSet { clamp(&radius, low: 0, high: 1) kernel = MPSImageTent(device : context.device, kernelWidth : Tools.odd(Int(radius * 100.0)), kernelHeight: Tools.odd(Int(radius * 100.0))) (kernel as! MPSImageTent).edgeMode = .clamp needsUpdate = true } } init() { super.init(functionName: nil) commonInit() } override init(functionName: String?) { super.init(functionName: nil) commonInit() } func commonInit() { title = "Tent" properties = [Property(key: "radius" , title: "Radius")] radius = 0.5 } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
6e9af37892d9b4bf2021d1f71eb7edec
20.957447
79
0.515504
4.229508
false
false
false
false
fakerabbit/memoria
Memoria/LearnView.swift
1
6495
// // SplashView.swift // LucasBot // // Created by Mirko Justiniano on 2/8/17. // Copyright © 2017 LB. All rights reserved. // import Foundation import UIKit class LearnView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { typealias LearnViewOnTouch = (Category) -> Void var onCell: LearnViewOnTouch = { category in } typealias LearnViewOnAdd = (LearnView) -> Void var onAdd: LearnViewOnAdd = { view in } lazy var collectionView: UICollectionView! = { let frame = self.frame let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 1.0 let cv: UICollectionView = UICollectionView(frame: frame, collectionViewLayout: layout) cv.backgroundColor = UIColor.clear cv.alwaysBounceVertical = true cv.dataSource = self cv.delegate = self cv.register(LearnCell.classForCoder(), forCellWithReuseIdentifier: "learnCell") return cv }() var categories: [Category?]! { didSet { if categories == nil || categories.count == 0 { debugPrint("WARNING categories is null") return } self.collectionView.reloadData() } } private var lastColors: [CGColor]! private lazy var gradientLayer: CAGradientLayer! = { let view = CAGradientLayer() view.frame = CGRect.zero view.colors = self.lastColors return view }() private lazy var titleLbl: UILabel! = { let lbl = UILabel(frame: CGRect.zero) lbl.font = Utils.logoFont() lbl.textColor = Utils.textColor() lbl.text = "Memoria . . ." lbl.sizeToFit() return lbl }() private lazy var addBtn: CircleBtn! = { let btn = CircleBtn(frame: CGRect.zero) btn.title = "+" btn.addTarget(self, action: #selector(onAdd(_:)), for: .touchUpInside) return btn }() /* * MARK:- Init */ override init(frame: CGRect) { super.init(frame: frame) //self.backgroundColor = Utils.backgroundColor() self.lastColors = self.randomColors() self.layer.addSublayer(gradientLayer) self.addSubview(collectionView) self.addSubview(titleLbl) self.addSubview(addBtn) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Layout override func layoutSubviews() { super.layoutSubviews() let w = self.frame.size.width let h = self.frame.size.height let pad: CGFloat = 100 let btnS: CGFloat = 70 gradientLayer.frame = self.bounds collectionView.frame = CGRect(x: 0, y: pad, width: w, height: h - pad) titleLbl.frame = CGRect(x: 10, y: pad - titleLbl.frame.size.height, width: titleLbl.frame.size.width, height: titleLbl.frame.size.height) addBtn.frame = CGRect(x: w/2 - btnS/2, y: h - (btnS + 10), width: btnS, height: btnS) } /* * MARK:- CollectionView Datasource & Delegate */ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //debugPrint("count: \(categories.count)") return categories.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let category = self.categories[indexPath.row] let cell:LearnCell = collectionView.dequeueReusableCell(withReuseIdentifier: "learnCell", for: indexPath) as! LearnCell cell.text = category?.name cell.cellWidth = category?.width cell.category = category cell.onTouch = { [weak self] category in self?.onCell(category) } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var category:Category? = categories[indexPath.row] let pad: CGFloat = 100 var size = CGSize(width: collectionView.frame.size.width - pad, height: 50) if category != nil { if let text: String = category!.name { let label = RoundTextView(frame: CGRect.zero) label.font = Utils.mainFont() label.text = text label.sizeToFit() size = label.sizeThatFits(CGSize(width: collectionView.frame.size.width/2.5, height: CGFloat.greatestFiniteMagnitude)) if size.width > size.height { size.height = size.width } else { size.width = size.height } category?.width = size.width + 5 categories[indexPath.row] = category! size.width = collectionView.frame.size.width - pad size.height += 5 } } return size } // MARK:- Private func onAdd(_ sender : UIButton) { self.onAdd(self) } // MARK:- Animations func randomColors() -> [CGColor] { let colors = [Utils.darkColor().cgColor, Utils.backgroundColor().cgColor, Utils.blueShadowColor().cgColor] return colors.shuffled() } func backgroundAnim() { let timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] (timer) in let fromColors = self?.lastColors let colors = self?.randomColors() self?.lastColors = colors self?.gradientLayer.colors = colors let animation : CABasicAnimation = CABasicAnimation(keyPath: "colors") animation.fromValue = fromColors animation.toValue = colors animation.duration = 2.0 animation.isRemovedOnCompletion = true animation.fillMode = kCAFillModeForwards animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) self?.gradientLayer.add(animation, forKey:"animateGradient") } RunLoop.current.add(timer, forMode: .commonModes) } }
mit
2b5951a9f94420c3f2699d2a43a82249
33.727273
160
0.6004
4.942161
false
false
false
false
BrisyIOS/TodayNewsSwift3.0
TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/View/HomeListCommonCell.swift
1
3241
// // HomeListCommonCell.swift // TodayNews-Swift3.0 // // Created by zhangxu on 2016/10/27. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit class HomeListCommonCell: UITableViewCell { /// 新闻标题 lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = Font(size: 17) titleLabel.numberOfLines = 0 titleLabel.textColor = UIColor.black; return titleLabel }() /// 用户名头像 lazy var avatarImageView: UIImageView = { let avatarImageView = UIImageView() return avatarImageView }() /// 用户名 lazy var nameLabel: UILabel = { let nameLabel = UILabel() nameLabel.font = Font(size: 12); nameLabel.textColor = UIColor.lightGray; return nameLabel }() /// 评论 lazy var commentLabel: UILabel = { let comentLabel = UILabel() comentLabel.font = Font(size: 12); comentLabel.textColor = UIColor.lightGray; return comentLabel }() /// 时间 lazy var timeLabel: UILabel = { let timeLabel = UILabel() timeLabel.font = Font(size: 12); timeLabel.textColor = UIColor.lightGray; return timeLabel }() /// 置顶,热,广告,视频 lazy var stickLabel: UIButton = { let stickLabel = UIButton() stickLabel.isHidden = true stickLabel.layer.cornerRadius = 3 stickLabel.sizeToFit() stickLabel.isUserInteractionEnabled = false stickLabel.titleLabel!.font = Font(size: 12); stickLabel.setTitleColor(RGB(red: 241, green: 91, blue: 94), for: .normal); stickLabel.layer.borderColor = RGB(red: 241, green: 91, blue: 94).cgColor; stickLabel.layer.borderWidth = 0.5 return stickLabel }() /// 举报按钮 lazy var closeButton: UIButton = { let closeButton = UIButton() closeButton.setImage(UIImage.imageWithName(name: "add_textpage_17x12_"), for: .normal); closeButton.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside); return closeButton }() /// 举报按钮点击 func closeBtnClick() { } // MARK: - 初始化方法 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); // 新闻标题 contentView.addSubview(titleLabel); // 用户名头像 contentView.addSubview(avatarImageView); // 用户名 contentView.addSubview(nameLabel); // 评论 contentView.addSubview(commentLabel); // 时间 contentView.addSubview(timeLabel); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
555e34765360ec9aff5e73951162c732
25.700855
95
0.596351
4.820988
false
false
false
false
Erik-J-D/SYDE361-AutomotiveIOT-PhoneApp-Sensors
iOS/Pods/Charts/Charts/Classes/Charts/BarLineChartViewBase.swift
1
49730
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIGestureRecognizer /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate { /// the maximum number of entried to which values will be drawn internal var _maxVisibleValueCount = 100 private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = UIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = true /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// the object representing the labels on the y-axis, this object is prepared /// in the pepareYLabels() method internal var _leftAxis: ChartYAxis! internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! private var _tapGestureRecognizer: UITapGestureRecognizer! private var _doubleTapGestureRecognizer: UITapGestureRecognizer! private var _pinchGestureRecognizer: UIPinchGestureRecognizer! private var _panGestureRecognizer: UIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame); } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } deinit { stopDeceleration(); } internal override func initialize() { super.initialize(); _leftAxis = ChartYAxis(position: .Left); _rightAxis = ChartYAxis(position: .Right); _xAxis = ChartXAxis(); _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler); _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler); _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer); _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer); _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer); _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")); _doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")); _doubleTapGestureRecognizer.numberOfTapsRequired = 2; _pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")); _panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")); _pinchGestureRecognizer.delegate = self; _panGestureRecognizer.delegate = self; self.addGestureRecognizer(_tapGestureRecognizer); if (_doubleTapToZoomEnabled) { self.addGestureRecognizer(_doubleTapGestureRecognizer); } updateScaleGestureRecognizers(); self.addGestureRecognizer(_panGestureRecognizer); } public override func drawRect(rect: CGRect) { super.drawRect(rect); if (_dataNotSet) { return; } let context = UIGraphicsGetCurrentContext(); calcModulus(); if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus); } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus); } // execute all drawing commands drawGridBackground(context: context); if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum); } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum); } _xAxisRenderer?.renderAxisLine(context: context); _leftYAxisRenderer?.renderAxisLine(context: context); _rightYAxisRenderer?.renderAxisLine(context: context); // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context); CGContextClipToRect(context, _viewPortHandler.contentRect); if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context); } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context); } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context); } _xAxisRenderer?.renderGridLines(context: context); _leftYAxisRenderer?.renderGridLines(context: context); _rightYAxisRenderer?.renderGridLines(context: context); renderer?.drawData(context: context); if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context); } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context); } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context); } // if highlighting is enabled if (highlightEnabled && highlightIndicatorEnabled && valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHightlight); } // Removes clipping rectangle CGContextRestoreGState(context); renderer!.drawExtras(context: context); _xAxisRenderer.renderAxisLabels(context: context); _leftYAxisRenderer.renderAxisLabels(context: context); _rightYAxisRenderer.renderAxisLabels(context: context); renderer!.drawValues(context: context); _legendRenderer.renderLegend(context: context); // drawLegend(); drawMarkers(context: context); drawDescription(context: context); } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum); _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum); } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted); _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted); } public override func notifyDataSetChanged() { if (_dataNotSet) { return; } calcMinMax(); _leftAxis?._defaultValueFormatter = _defaultValueFormatter; _rightAxis?._defaultValueFormatter = _defaultValueFormatter; _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum); _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum); _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals); _legendRenderer?.computeLegend(_data); calculateOffsets(); setNeedsDisplay(); } internal override func calcMinMax() { var minLeft = _data.getYMin(.Left); var maxLeft = _data.getYMax(.Left); var minRight = _data.getYMin(.Right); var maxRight = _data.getYMax(.Right); var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft)); var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight)); // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0; if (!_leftAxis.isStartAtZeroEnabled) { minLeft = minLeft - 1.0; } } if (rightRange == 0.0) { maxRight = maxRight + 1.0; if (!_rightAxis.isStartAtZeroEnabled) { minRight = minRight - 1.0; } } var topSpaceLeft = leftRange * Float(_leftAxis.spaceTop); var topSpaceRight = rightRange * Float(_rightAxis.spaceTop); var bottomSpaceLeft = leftRange * Float(_leftAxis.spaceBottom); var bottomSpaceRight = rightRange * Float(_rightAxis.spaceBottom); _chartXMax = Float(_data.xVals.count - 1); _deltaX = CGFloat(abs(_chartXMax - _chartXMin)); _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft); _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight); _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft); _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight); // consider starting at zero (0) if (_leftAxis.isStartAtZeroEnabled) { _leftAxis.axisMinimum = 0.0; } if (_rightAxis.isStartAtZeroEnabled) { _rightAxis.axisMinimum = 0.0; } _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum); _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum); } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0); var offsetRight = CGFloat(0.0); var offsetTop = CGFloat(0.0); var offsetBottom = CGFloat(0.0); // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += _legend.textWidthMax + _legend.xOffset * 2.0; } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += _legend.textWidthMax + _legend.xOffset * 2.0; } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { offsetBottom += _legend.textHeightMax * 3.0; } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width; } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width; } var xlabelheight = xAxis.labelHeight * 2.0; if (xAxis.isEnabled) { // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight; } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight; } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight; offsetTop += xlabelheight; } } var min = CGFloat(10.0); _viewPortHandler.restrainViewPort( offsetLeft: max(min, offsetLeft), offsetTop: max(min, offsetTop), offsetRight: max(min, offsetRight), offsetBottom: max(min, offsetBottom)); } prepareOffsetMatrix(); prepareValuePxMatrix(); } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return; } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))); } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1; } } public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint { var xPos = CGFloat(entry.xIndex); if (self.isKindOfClass(BarChartView)) { var bd = _data as! BarChartData; var space = bd.groupSpace; var j = _data.getDataSetByIndex(dataSetIndex)!.entryIndex(entry: entry, isEqual: true); var x = CGFloat(j * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(j) + space / 2.0; xPos += x; } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: CGFloat(entry.value) * _animator.phaseY); getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt); return pt; } /// draws the grid background internal func drawGridBackground(#context: CGContext) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context); } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor); CGContextFillRect(context, _viewPortHandler.contentRect); } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth); CGContextSetStrokeColorWithColor(context, borderColor.CGColor); CGContextStrokeRect(context, _viewPortHandler.contentRect); } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context); } } /// Returns the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer; } else { return _rightAxisTransformer; } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false; private var _isScaling = false; private var _gestureScaleAxis = GestureScaleAxis.Both; private var _closestDataSetToTouch: ChartDataSet!; /// the last highlighted object private var _lastHighlighted: ChartHighlight!; private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return; } if (recognizer.state == UIGestureRecognizerState.Ended) { var h = getHighlightByTouchPoint(recognizer.locationInView(self)); if (h === nil || h!.isEqual(_lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true); _lastHighlighted = nil; } else { _lastHighlighted = h; self.highlightValue(highlight: h, callDelegate: true); } } } @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return; } if (recognizer.state == UIGestureRecognizerState.Ended) { if (!_dataNotSet && _doubleTapToZoomEnabled) { var location = recognizer.locationInView(self); location.x = location.x - _viewPortHandler.offsetLeft; if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop); } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom); } self.zoom(1.4, scaleY: 1.4, x: location.x, y: location.y); } } } @objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration(); if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)) { _isScaling = true; if (_pinchZoomEnabled) { _gestureScaleAxis = .Both; } else { var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x); var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y); if (x > y) { _gestureScaleAxis = .X; } else { _gestureScaleAxis = .Y; } } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false; } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isScaling) { var location = recognizer.locationInView(self); location.x = location.x - _viewPortHandler.offsetLeft; if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop); } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom); } var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0; var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0; var matrix = CGAffineTransformMakeTranslation(location.x, location.y); matrix = CGAffineTransformScale(matrix, scaleX, scaleY); matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y); matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); recognizer.scale = 1.0; } } } @objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration(); if (!_dataNotSet && _dragEnabled && !self.hasNoDragOffset || !self.isFullyZoomedOut) { _isDragging = true; _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self)); _lastPanPoint = recognizer.translationInView(self); } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration(); _decelerationLastTime = CACurrentMediaTime(); _decelerationVelocity = recognizer.velocityInView(self); _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")); _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes); } _isDragging = false; } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isDragging) { var originalTranslation = recognizer.translationInView(self); var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y); performPanChange(translation: translation); _lastPanPoint = originalTranslation; } else if (isHighlightPerDragEnabled) { var h = getHighlightByTouchPoint(recognizer.locationInView(self)); if ((h === nil && _lastHighlighted !== nil) || (h !== nil && _lastHighlighted === nil) || (h !== nil && _lastHighlighted !== nil && !h!.isEqual(_lastHighlighted))) { _lastHighlighted = h; self.highlightValue(highlight: h, callDelegate: true); } } } } private func performPanChange(var #translation: CGPoint) { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x; } else { translation.y = -translation.y; } } var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y); matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes); _decelerationDisplayLink = nil; } } @objc private func decelerationLoop() { var currentTime = CACurrentMediaTime(); _decelerationVelocity.x *= self.dragDecelerationFrictionCoef; _decelerationVelocity.y *= self.dragDecelerationFrictionCoef; var timeInterval = CGFloat(currentTime - _decelerationLastTime); var distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ); performPanChange(translation: distance); _decelerationLastTime = currentTime; if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration(); } } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer))) { return true; } return false; } /// MARK: Viewport modifiers /// Zooms in by 1.4f, into the charts center. center. public func zoomIn() { var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Zooms out by 0.7f, from the charts center. center. public func zoomOut() { var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// :param: scaleX if < 1f --> zoom out, if > 1f --> zoom in /// :param: scaleY if < 1f --> zoom out, if > 1f --> zoom in /// :param: x /// :param: y public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { var matrix = _viewPortHandler.fitScreen(); _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true); } /// Sets the minimum scale value to which can be zoomed out. 1f = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX); _viewPortHandler.setMinimumScaleY(scaleY); } /// Sets the size of the area (range on the x-axis) that should be maximum /// visible at once. If this is e.g. set to 10, no more than 10 values on the /// x-axis can be viewed at once without scrolling. public func setVisibleXRange(xRange: CGFloat) { var xScale = _deltaX / (xRange); _viewPortHandler.setMinimumScaleX(xScale); } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// :param: yRange /// :param: axis - the axis for which this limit should apply public func setVisibleYRange(yRange: CGFloat, axis: ChartYAxis.AxisDependency) { var yScale = getDeltaY(axis) / yRange; _viewPortHandler.setMinimumScaleY(yScale); } /// Moves the left side of the current viewport to the specified x-index. public func moveViewToX(xIndex: Int) { if (_viewPortHandler.hasChartDimens) { var pt = CGPoint(x: CGFloat(xIndex), y: 0.0); getTransformer(.Left).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); }); } } /// Centers the viewport to the specified y-value on the y-axis. /// /// :param: yValue /// :param: axis - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY; var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0); getTransformer(axis).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); }); } } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// /// :param: xIndex /// :param: yValue /// :param: axis - which axis should be used as a reference for the y-axis public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY; var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0); getTransformer(axis).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }); } } /// This will move the center of the current viewport to the specified x-index and y-value. /// /// :param: xIndex /// :param: yValue /// :param: axis - which axis should be used as a reference for the y-axis public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY; var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX; var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0); getTransformer(axis).pointValueToPixel(&pt); _viewPortHandler.centerViewPort(pt: pt, chart: self); } else { _sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }); } } /// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this. public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true; if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom); prepareOffsetMatrix(); prepareValuePxMatrix(); } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom); }); } } /// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false; calculateOffsets(); } // MARK: - Accessors /// Returns the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange); } else { return CGFloat(rightAxis.axisRange); } } /// Returns the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)); getTransformer(axis).pointValueToPixel(&vals); return vals; } /// the number of maximum visible drawn values on the chart /// only active when setDrawValues() is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount; } set { _maxVisibleValueCount = newValue; } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled; } set { if (_dragEnabled != newValue) { _dragEnabled = newValue; } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled; } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled; _scaleYEnabled = enabled; updateScaleGestureRecognizers(); } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue; updateScaleGestureRecognizers(); } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue; updateScaleGestureRecognizers(); } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled; } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue; if (_doubleTapToZoomEnabled) { self.addGestureRecognizer(_doubleTapGestureRecognizer); } else { if (self.gestureRecognizers != nil) { for (var i = 0; i < self.gestureRecognizers!.count; i++) { if (self.gestureRecognizers?[i] === _doubleTapGestureRecognizer) { self.gestureRecognizers!.removeAtIndex(i); break; } } } } } } } /// :returns: true if zooming via double-tap is enabled false if not. /// :default: true public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled; } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// :default: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled; } /// if set to true, the highlight indicator (lines for linechart, dark bar for barchart) will be drawn upon selecting values. public var highlightIndicatorEnabled = true /// If set to true, the highlight indicator (vertical line for LineChart and /// ScatterChart, dark bar overlay for BarChart) that gives visual indication /// that an Entry has been selected will be drawn upon selecting values. This /// does not depend on the MarkerView. /// :default: true public var isHighlightIndicatorEnabled: Bool { return highlightIndicatorEnabled; } /// :returns: true if drawing the grid background is enabled, false if not. /// :default: true public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled; } /// :returns: true if drawing the borders rectangle is enabled, false if not. /// :default: false public var isDrawBordersEnabled: Bool { return drawBordersEnabled; } /// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight! { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set."); return nil; } var valPt = CGPoint(); valPt.x = pt.x; valPt.y = 0.0; // take any transformer to determine the x-axis value _leftAxisTransformer.pixelToValue(&valPt); var xTouchVal = valPt.x; var base = floor(xTouchVal); var touchOffset = _deltaX * 0.025; // touch out of chart if (xTouchVal < -touchOffset || xTouchVal > _deltaX + touchOffset) { return nil; } if (base < 0.0) { base = 0.0; } if (base >= _deltaX) { base = _deltaX - 1.0; } var xIndex = Int(base); // check if we are more than half of a x-value or not if (xTouchVal - base > 0.5) { xIndex = Int(base + 1.0); } var valsAtIndex = getYValsAtIndex(xIndex); var leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Left); var rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Right); if (_data!.getFirstRight() === nil) { rightdist = FLT_MAX; } if (_data!.getFirstLeft() === nil) { leftdist = FLT_MAX; } var axis: ChartYAxis.AxisDependency = leftdist < rightdist ? .Left : .Right; var dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(pt.y), axis: axis); if (dataSetIndex == -1) { return nil; } return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex); } /// Returns an array of SelInfo objects for the given x-index. The SelInfo /// objects give information about the value at the selected index and the /// DataSet it belongs to. public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo] { var vals = [ChartSelInfo](); var pt = CGPoint(); for (var i = 0, count = _data.dataSetCount; i < count; i++) { var dataSet = _data.getDataSetByIndex(i); if (dataSet === nil) { continue; } // extract all y-values from all DataSets at the given x-index var yVal = dataSet!.yValForXIndex(xIndex); pt.y = CGFloat(yVal); getTransformer(dataSet!.axisDependency).pointValueToPixel(&pt); if (!isnan(pt.y)) { vals.append(ChartSelInfo(value: Float(pt.y), dataSetIndex: i, dataSet: dataSet!)); } } return vals; } /// Returns the x and y values in the chart at the given touch point /// (encapsulated in a PointD). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// getPixelsForValues(...). public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt); return pt; } /// Transforms the given chart values into pixels. This is the opposite /// method to getValueByTouchPoint(...). public func getPixelForValue(x: Float, y: Float, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)); getTransformer(axis).pointValueToPixel(&pt); return pt; } /// returns the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y; } /// returns the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { var h = getHighlightByTouchPoint(pt); if (h !== nil) { return _data!.getEntryForHighlight(h!); } return nil; } ///returns the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet! { var h = getHighlightByTouchPoint(pt); if (h !== nil) { return _data.getDataSetByIndex(h.dataSetIndex) as! BarLineScatterCandleChartDataSet!; } return nil; } /// Returns the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom); getTransformer(.Left).pixelToValue(&pt); return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0); } /// Returns the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom); getTransformer(.Left).pixelToValue(&pt); return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x); } /// returns the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0; } return _viewPortHandler.scaleX; } /// returns the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0; } return _viewPortHandler.scaleY; } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// Returns the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis; } /// Returns the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// Returns the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis; } else { return _rightAxis; } } /// Returns the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis; } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled; } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue; updateScaleGestureRecognizers(); } } } private func updateScaleGestureRecognizers() { if (self.gestureRecognizers != nil) { for (var i = 0; i < self.gestureRecognizers!.count; i++) { if (self.gestureRecognizers![i] === _pinchGestureRecognizer) { self.gestureRecognizers!.removeAtIndex(i); break; } } } if (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled) { self.addGestureRecognizer(_pinchGestureRecognizer); } } /// returns true if pinch-zoom is enabled, false if not /// :default: false public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset); } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset); } /// :returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } public var xAxisRenderer: ChartXAxisRenderer { return _xAxisRenderer; } public var leftYAxisRenderer: ChartYAxisRenderer { return _leftYAxisRenderer; } public var rightYAxisRenderer: ChartYAxisRenderer { return _rightYAxisRenderer; } public override var chartYMax: Float { return max(leftAxis.axisMaximum, rightAxis.axisMaximum); } public override var chartYMin: Float { return min(leftAxis.axisMinimum, rightAxis.axisMinimum); } /// Returns true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted; } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { private weak var _chart: BarLineChartViewBase!; internal init(chart: BarLineChartViewBase) { _chart = chart; } internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Float, chartMinY: Float) -> CGFloat { var fillMin = CGFloat(0.0); if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0; } else { if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled) { var max: Float, min: Float; if (data.yMax > 0.0) { max = 0.0; } else { max = chartMaxY; } if (data.yMin < 0.0) { min = 0.0; } else { min = chartMinY; } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max); } else { fillMin = 0.0; } } return fillMin; } }
mit
f39a2d64a88dced1e4b25a4bd7b01628
33.22574
263
0.577297
5.509639
false
false
false
false
306244907/Weibo
JLSina/JLSina/Classes/Tools(工具)/UI框架/JLRefreshControl/JLRefreshView.swift
1
2119
// // JLRefreshView.swift // 刷新控件 // // Created by 盘赢 on 2017/11/21. // Copyright © 2017年 JinLong. All rights reserved. // import UIKit //刷新视图 - 负责刷新相关的 UI 显示和动画 class JLRefreshView: UIView { //刷新状态 /* iOS 系统中 ,UIView 封装的旋转动画 - 默认顺时针旋转 - 就近原则 - 要想实现同方向旋转,需要调整一个 非常小的数字 - 如果想实现 360‘ 旋转,需要核心动画 CABaseAnimation */ var refreshState: JLRefreshState = JLRefreshState.Normal { didSet { switch refreshState { case .Normal: //恢复状态 tipIcon?.isHidden = false indicator?.stopAnimating() tipLabel?.text = "继续使劲拉..." UIView.animate(withDuration: 0.25) { self.tipIcon?.transform = CGAffineTransform.identity } case .Pulling: tipLabel?.text = "放手就刷新..." UIView.animate(withDuration: 0.25) { self.tipIcon?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi + 0.001)) } case.WillRefresh: tipLabel?.text = "正在刷新中..." //隐藏提示图标,显示菊花 tipIcon?.isHidden = true indicator?.startAnimating() } } } //父视图的高度 - 为了刷新控件不需要知道子视图是谁 var parentViewHeight: CGFloat = 0 //提示图片 @IBOutlet weak var tipIcon: UIImageView? //提示标签 @IBOutlet weak var tipLabel: UILabel? //指示器 @IBOutlet weak var indicator: UIActivityIndicatorView? class func refreshView()-> JLRefreshView { let nib = UINib(nibName: "JLMeituanRefreshView", bundle: nil) return nib.instantiate(withOwner: nil, options: nil)[0] as! JLRefreshView } }
mit
74ece42eb092d414f3bca43fb62181df
24.633803
106
0.525275
4.385542
false
false
false
false
Draveness/NightNight
NightNight/Classes/NNMutableAttributedString.swift
1
3407
// // NNMutableAttributedString.swift // Pods // // Created by Draveness on 7/9/16. // // import UIKit public extension NSMutableAttributedString { fileprivate struct AssociatedKeys { static var mixedAttrsKey = "mixedAttrs" } fileprivate var mixedAttrs: [String: [NSRange: MixedColor]] { get { if let dict = objc_getAssociatedObject(self, &AssociatedKeys.mixedAttrsKey) as? [String : [NSRange : MixedColor]] { return dict } self.mixedAttrs = [:] MixedColorAttributeNames.forEach { (mixed) in self.mixedAttrs[mixed] = [:] } return self.mixedAttrs } set { objc_setAssociatedObject(self, &AssociatedKeys.mixedAttrsKey, newValue as AnyObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) addNightObserver(#selector(_updateTitleAttributes)) } } func setMixedAttributes(_ attrs: [String : AnyObject]?, range: NSRange) { if var attrs = attrs { MixedColorAttributeNamesDictionary.forEach({ (mixed, normal) in if attrs.keys.contains(mixed) { mixedAttrs[mixed]?[range] = attrs[mixed] as? MixedColor attrs[mixed] = mixedAttrs[mixed]?[range]?.unfold() } }) setAttributes(attrs.withAttributedStringKeys(), range: range) } else { setAttributes(attrs?.withAttributedStringKeys(), range: range) } } func addMixedAttribute(_ name: String, value: AnyObject, range: NSRange) { if containsAttributeName(name), let normalName = MixedColorAttributeNamesDictionary[name] { mixedAttrs[name]?[range] = value as? MixedColor addAttribute(normalName, value: value, range: range) } else { addAttribute(NSAttributedString.Key(rawValue: name), value: value, range: range) } } func addMixedAttributes(_ attrs: [String : AnyObject], range: NSRange) { if containsAttributeName(attrs) { var attrs = attrs MixedColorAttributeNamesDictionary.forEach({ (mixed, normal) in if attrs.keys.contains(mixed) { mixedAttrs[mixed]?[range] = attrs[mixed] as? MixedColor attrs[mixed] = mixedAttrs[mixed]?[range]?.unfold() } }) addAttributes(attrs.withAttributedStringKeys(), range: range) } else { addAttributes(attrs.withAttributedStringKeys(), range: range) } } func removeMixedAttribute(_ name: String, range: NSRange) { if containsAttributeName(name), let normalName = MixedColorAttributeNamesDictionary[name] { _ = mixedAttrs[name]?.removeValue(forKey: range) removeAttribute(normalName, range: range) } else { removeAttribute(NSAttributedString.Key(rawValue: name), range: range) } } @objc func _updateTitleAttributes() { MixedColorAttributeNamesDictionary.forEach { (mixed, normal) in if let foregroundColorDictionary = mixedAttrs[mixed] { foregroundColorDictionary.forEach({ (range, mixedColor) in self.addAttribute(normal, value: mixedColor.unfold(), range: range) }) } } } }
mit
8ca2b39d815e906055555805c6163789
33.07
132
0.593778
5.131024
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine/dBuffers.swift
1
3225
// // Buffer.swift // DKMetal // // Created by Allison Lindner on 07/04/16. // Copyright © 2016 Allison Lindner. All rights reserved. // import Metal import MetalKit public enum dBufferType { case vertex case fragment } public protocol dBufferable { var buffer: MTLBuffer { get } var index: Int { get set } var offset: Int { get set } var bufferType: dBufferType { get } var count: Int { get } } internal class dBuffer<T>: dBufferable { private var _data: [T] private var _id: Int! private var _index: Int private var _offset: Int private var _staticMode: Bool private var _bufferType: dBufferType private var _bufferChanged: Bool internal var id: Int { get { return self._id } } internal var bufferType: dBufferType { get { return _bufferType } } internal var index: Int { get { return self._index } set (i) { self._index = i } } internal var offset: Int { get { return self._offset } set (o) { self._offset = o } } internal var data: [T] { get { return self._data } } internal var buffer: MTLBuffer { get { if self._bufferChanged { _updateBuffer() } guard let buffer = dCore.instance.bManager.getBuffer(_id) else { fatalError("Buffer nil") } return buffer } } internal var count: Int { get { return self._data.count } } internal init(data: [T], index: Int = -1, preAllocateSize size: Int = 1, bufferType: dBufferType = .vertex, staticMode: Bool = false , offset: Int = 0) { self._index = index self._offset = offset self._staticMode = staticMode self._bufferType = bufferType self._data = data self._bufferChanged = true if size > data.count { self._data.reserveCapacity(size) } _updateBuffer() } internal convenience init(data: T, index: Int = -1, preAllocateSize size: Int = 1, bufferType: dBufferType = .vertex, staticMode: Bool = false , offset: Int = 0) { self.init(data: [data], index: index, preAllocateSize: size, bufferType: bufferType, staticMode: staticMode, offset: offset) } internal func append(_ data: T) -> Int { self._data.append(data) self._bufferChanged = true return self._data.count - 1 } internal func change(_ data: T, atIndex: Int) { self._data[atIndex] = data let pointer = self.buffer.contents() let size = MemoryLayout<T>.size memcpy(pointer + (atIndex * size), [data], size) } internal func change(_ data: [T]) { if self._data.count == data.count { self._data = data let pointer = self.buffer.contents() let size = MemoryLayout<T>.size * data.count memcpy(pointer, data, size) } } internal func extendTo(_ size: Int) { if size > self._data.capacity { self._data.reserveCapacity(size) } self._bufferChanged = true } private func _updateBuffer() { self._id = dCore.instance.bManager.createBuffer( _data, index: self._index, offset: self._offset, id: self._id ) _bufferChanged = false } internal func finishBuffer() { _updateBuffer() } }
gpl-3.0
08ce84cc88b2e4a3f6d77bd55a41fcf3
19.024845
126
0.609801
3.390116
false
false
false
false
hilen/TSWeChat
Pods/XLActionController/Source/DynamicCollectionViewFlowLayout.swift
1
10793
// DynamicCollectionViewFlowLayout.swiftg // DynamicCollectionViewFlowLayout ( https://github.com/xmartlabs/XLActionController ) // // Copyright (c) 2015 Xmartlabs ( whttp://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit open class DynamicCollectionViewFlowLayout: UICollectionViewFlowLayout { // MARK: - Properties definition open var dynamicAnimator: UIDynamicAnimator? open var itemsAligment = UIControl.ContentHorizontalAlignment.center open lazy var collisionBehavior: UICollisionBehavior? = { let collision = UICollisionBehavior(items: []) return collision }() open lazy var dynamicItemBehavior: UIDynamicItemBehavior? = { let dynamic = UIDynamicItemBehavior(items: []) dynamic.allowsRotation = false return dynamic }() open lazy var gravityBehavior: UIGravityBehavior? = { let gravity = UIGravityBehavior(items: []) gravity.gravityDirection = CGVector(dx: 0, dy: -1) gravity.magnitude = 4.0 return gravity }() open var useDynamicAnimator = false { didSet(newValue) { guard useDynamicAnimator != newValue else { return } if useDynamicAnimator { dynamicAnimator = UIDynamicAnimator(collectionViewLayout: self) dynamicAnimator!.addBehavior(collisionBehavior!) dynamicAnimator!.addBehavior(dynamicItemBehavior!) dynamicAnimator!.addBehavior(gravityBehavior!) } } } // MARK: - Intialize override init() { super.init() initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } fileprivate func initialize() { minimumInteritemSpacing = 0 minimumLineSpacing = 0 } // MARK: - UICollectionViewFlowLayout overrides override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let animator = dynamicAnimator else { return super.layoutAttributesForElements(in: rect) } let items = animator.items(in: rect) as NSArray return items.compactMap { $0 as? UICollectionViewLayoutAttributes } } override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let indexPath = indexPath guard let animator = dynamicAnimator else { return super.layoutAttributesForItem(at: indexPath) } return animator.layoutAttributesForCell(at: indexPath) ?? setupAttributesForIndexPath(indexPath) } override open func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { super.prepare(forCollectionViewUpdates: updateItems) updateItems.filter { $0.updateAction == .insert && layoutAttributesForItem(at: $0.indexPathAfterUpdate!) == nil } .forEach { setupAttributesForIndexPath($0.indexPathAfterUpdate) } } // MARK: - Helpers fileprivate func topForItemAt(indexPath: IndexPath) -> CGFloat { guard let unwrappedCollectionView = collectionView else { return CGFloat(0.0) } // Top within item's section var top = CGFloat((indexPath as NSIndexPath).item) * itemSize.height if (indexPath as NSIndexPath).section > 0 { let lastItemOfPrevSection = unwrappedCollectionView.numberOfItems(inSection: (indexPath as NSIndexPath).section - 1) // Add previous sections height recursively. We have to add the sectionInsets and the last section's item height let inset = (unwrappedCollectionView.delegate as? UICollectionViewDelegateFlowLayout)?.collectionView?(unwrappedCollectionView, layout: self, insetForSectionAt: (indexPath as NSIndexPath).section) ?? sectionInset top += topForItemAt(indexPath: IndexPath(item: lastItemOfPrevSection - 1, section: (indexPath as NSIndexPath).section - 1)) + inset.bottom + inset.top + itemSize.height } return top } private func isRTL(for view: UIView) -> Bool { return UIView.userInterfaceLayoutDirection(for: view.semanticContentAttribute) == .rightToLeft } @discardableResult func setupAttributesForIndexPath(_ indexPath: IndexPath?) -> UICollectionViewLayoutAttributes? { guard let indexPath = indexPath, let animator = dynamicAnimator, let collectionView = collectionView else { return nil } let delegate: UICollectionViewDelegateFlowLayout = collectionView.delegate as! UICollectionViewDelegateFlowLayout let collectionItemSize = delegate.collectionView!(collectionView, layout: self, sizeForItemAt: indexPath) // UIDynamic animator will animate this item from initialFrame to finalFrame. // Items will be animated from far bottom to its final position in the collection view layout let originY = collectionView.frame.size.height - collectionView.contentInset.top var frame = CGRect(x: 0, y: topForItemAt(indexPath: indexPath), width: collectionItemSize.width, height: collectionItemSize.height) var initialFrame = CGRect(x: 0, y: originY + frame.origin.y, width: collectionItemSize.width, height: collectionItemSize.height) // Calculate x position depending on alignment value let collectionViewContentWidth = collectionView.bounds.size.width - collectionView.contentInset.left - collectionView.contentInset.right let rightMargin = (collectionViewContentWidth - frame.size.width) let leftMargin = CGFloat(0.0) var translationX: CGFloat switch itemsAligment { case .center: translationX = (collectionViewContentWidth - frame.size.width) * 0.5 case .fill, .left: translationX = leftMargin case .right: translationX = rightMargin case .leading: translationX = isRTL(for: collectionView) ? rightMargin : leftMargin case .trailing: translationX = isRTL(for: collectionView) ? leftMargin : rightMargin @unknown default: translationX = isRTL(for: collectionView) ? rightMargin : leftMargin } frame.origin.x = translationX frame.origin.y -= collectionView.contentInset.bottom initialFrame.origin.x = translationX let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = initialFrame let attachmentBehavior: UIAttachmentBehavior let collisionBehavior = UICollisionBehavior(items: [attributes]) let itemBehavior = UIDynamicItemBehavior(items: [attributes]) itemBehavior.allowsRotation = false if (indexPath as NSIndexPath).item == 0 { let mass = CGFloat(collectionView.numberOfItems(inSection: (indexPath as NSIndexPath).section)) itemBehavior.elasticity = (0.70 / mass) var topMargin = CGFloat(1.5) if (indexPath as NSIndexPath).section > 0 { topMargin -= sectionInset.top + sectionInset.bottom } let fromPoint = CGPoint(x: frame.minX, y: frame.minY + topMargin) let toPoint = CGPoint(x: frame.maxX, y: fromPoint.y) collisionBehavior.addBoundary(withIdentifier: "top" as NSCopying, from: fromPoint, to: toPoint) attachmentBehavior = UIAttachmentBehavior(item: attributes, attachedToAnchor:CGPoint(x: frame.midX, y: frame.midY)) attachmentBehavior.length = 1 attachmentBehavior.damping = 0.30 * sqrt(mass) attachmentBehavior.frequency = 5.0 } else { itemBehavior.elasticity = 0.0 let fromPoint = CGPoint(x: frame.minX, y: frame.minY) let toPoint = CGPoint(x: frame.maxX, y: fromPoint.y) collisionBehavior.addBoundary(withIdentifier: "top" as NSCopying, from: fromPoint, to: toPoint) let prevPath = IndexPath(item: (indexPath as NSIndexPath).item - 1, section: (indexPath as NSIndexPath).section) let prevItemAttributes = layoutAttributesForItem(at: prevPath)! attachmentBehavior = UIAttachmentBehavior(item: attributes, attachedTo: prevItemAttributes) attachmentBehavior.length = itemSize.height attachmentBehavior.damping = 0.0 attachmentBehavior.frequency = 0.0 } animator.addBehavior(attachmentBehavior) animator.addBehavior(collisionBehavior) animator.addBehavior(itemBehavior) return attributes } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { guard let animator = dynamicAnimator else { return super.shouldInvalidateLayout(forBoundsChange: newBounds) } guard let unwrappedCollectionView = collectionView else { return super.shouldInvalidateLayout(forBoundsChange: newBounds) } animator.behaviors .filter { $0 is UIAttachmentBehavior || $0 is UICollisionBehavior || $0 is UIDynamicItemBehavior} .forEach { animator.removeBehavior($0) } for section in 0..<unwrappedCollectionView.numberOfSections { for item in 0..<unwrappedCollectionView.numberOfItems(inSection: section) { let indexPath = IndexPath(item: item, section: section) setupAttributesForIndexPath(indexPath) } } return false } }
mit
f8b69c5fb7540104e3eba7d0aea7c414
41.492126
224
0.675252
5.647828
false
false
false
false
eoger/firefox-ios
Sync/Synchronizers/TabsSynchronizer.swift
3
8819
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger let TabsStorageVersion = 1 open class TabsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "tabs") } override var storageVersion: Int { return TabsStorageVersion } var tabsRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastTabsUpload") } get { return self.prefs.unsignedLongForKey("lastTabsUpload") ?? 0 } } fileprivate func createOwnTabsRecord(_ tabs: [RemoteTab]) -> Record<TabsPayload> { let guid = self.scratchpad.clientGUID let tabsJSON = JSON([ "id": guid, "clientName": self.scratchpad.clientName, "tabs": tabs.compactMap { $0.toDictionary() } ]) if Logger.logPII { log.verbose("Sending tabs JSON \(tabsJSON.stringValue() ?? "nil")") } let payload = TabsPayload(tabsJSON) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } fileprivate func uploadOurTabs(_ localTabs: RemoteClientsAndTabs, toServer tabsClient: Sync15CollectionClient<TabsPayload>) -> Success { // check to see if our tabs have changed or we're in a fresh start let lastUploadTime: Timestamp? = (self.tabsRecordLastUpload == 0) ? nil : self.tabsRecordLastUpload if let lastUploadTime = lastUploadTime, lastUploadTime >= (Date.now() - (OneMinuteInMilliseconds)) { log.debug("Not uploading tabs: already did so at \(lastUploadTime).") return succeed() } return localTabs.getTabsForClientWithGUID(nil) >>== { tabs in if let lastUploadTime = lastUploadTime { // TODO: track this in memory so we don't have to hit the disk to figure out when our tabs have // changed and need to be uploaded. if tabs.every({ $0.lastUsed < lastUploadTime }) { return succeed() } } let tabsRecord = self.createOwnTabsRecord(tabs) log.debug("Uploading our tabs: \(tabs.count).") var uploadStats = SyncUploadStats() uploadStats.sent += 1 // We explicitly don't send If-Unmodified-Since, because we always // want our upload to succeed -- we own the record. return tabsClient.put(tabsRecord, ifUnmodifiedSince: nil) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Tabs record upload succeeded. New timestamp: \(ts).") self.tabsRecordLastUpload = ts } else { uploadStats.sentFailed += 1 } return succeed() } >>== effect({ self.statsSession.recordUpload(stats: uploadStats) }) } } open func synchronizeLocalTabs(_ localTabs: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { func onResponseReceived(_ response: StorageResponse<[Record<TabsPayload>]>) -> Success { func afterWipe() -> Success { var downloadStats = SyncDownloadStats() let doInsert: (Record<TabsPayload>) -> Deferred<Maybe<(Int)>> = { record in let remotes = record.payload.isValid() ? record.payload.remoteTabs : [] let ins = localTabs.insertOrUpdateTabsForClientGUID(record.id, tabs: remotes) // Since tabs are all sent within a single record, we don't count number of tabs applied // but number of records. In this case it's just one. downloadStats.applied += 1 ins.upon() { res in if let inserted = res.successValue { if inserted != remotes.count { log.warning("Only inserted \(inserted) tabs, not \(remotes.count). Malformed or missing client?") } downloadStats.applied += 1 } else { downloadStats.failed += 1 } } return ins } let ourGUID = self.scratchpad.clientGUID let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) tab records.") // We can only insert tabs for clients that we know locally, so // first we fetch the list of IDs and intersect the two. // TODO: there's a much more efficient way of doing this. return localTabs.getClientGUIDs() >>== { clientGUIDs in let filtered = records.filter({ $0.id != ourGUID && clientGUIDs.contains($0.id) }) if filtered.count != records.count { log.debug("Filtered \(records.count) records down to \(filtered.count).") } let allDone = all(filtered.map(doInsert)) return allDone.bind { (results) -> Success in if let failure = results.find({ $0.isFailure }) { return deferMaybe(failure.failureValue!) } self.lastFetched = responseTimestamp! return succeed() } } >>== effect({ self.statsSession.downloadStats }) } // If this is a fresh start, do a wipe. if self.lastFetched == 0 { log.info("Last fetch was 0. Wiping tabs.") return localTabs.wipeRemoteTabs() >>== afterWipe } return afterWipe() } if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(SyncStatus.notStarted(reason)) } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<TabsPayload>(decode: { TabsPayload($0) }, encode: { $0.json }) if let encrypter = keys?.encrypter(self.collection, encoder: encoder) { let tabsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter) statsSession.start() if !self.remoteHasChanges(info) { // upload local tabs if they've changed or we're in a fresh start. return uploadOurTabs(localTabs, toServer: tabsClient) >>> { deferMaybe(self.completedWithStats) } } return tabsClient.getSince(self.lastFetched) >>== onResponseReceived >>> { self.uploadOurTabs(localTabs, toServer: tabsClient) } >>> { deferMaybe(self.completedWithStats) } } log.error("Couldn't make tabs factory.") return deferMaybe(FatalError(message: "Couldn't make tabs factory.")) } /** * This is a dedicated resetting interface that does both tabs and clients at the * same time. */ open static func resetClientsAndTabsWithStorage(_ storage: ResettableSyncStorage, basePrefs: Prefs) -> Success { let clientPrefs = BaseCollectionSynchronizer.prefsForCollection("clients", withBasePrefs: basePrefs) let tabsPrefs = BaseCollectionSynchronizer.prefsForCollection("tabs", withBasePrefs: basePrefs) clientPrefs.removeObjectForKey("lastFetched") tabsPrefs.removeObjectForKey("lastFetched") return storage.resetClient() } } extension RemoteTab { public func toDictionary() -> Dictionary<String, Any>? { let tabHistory = history.compactMap { $0.absoluteString } if tabHistory.isEmpty { return nil } return [ "title": title, "icon": icon?.absoluteString as Any? ?? NSNull(), "urlHistory": tabHistory, "lastUsed": millisecondsToDecimalSeconds(lastUsed) ] } }
mpl-2.0
c91cf09a6d2726b0120002815f98f306
41.81068
155
0.576369
5.536095
false
false
false
false
lyft/SwiftLint
Source/swiftlint/Helpers/Benchmark.swift
1
1622
import Foundation import SourceKittenFramework struct BenchmarkEntry { let id: String let time: Double } struct Benchmark { private let name: String private var entries = [BenchmarkEntry]() init(name: String) { self.name = name } mutating func record(id: String, time: Double) { entries.append(BenchmarkEntry(id: id, time: time)) } mutating func record(file: File, from start: Date) { record(id: file.path ?? "<nopath>", time: -start.timeIntervalSinceNow) } func save() { // Decomposed to improve compile times let entriesDict: [String: Double] = entries.reduce(into: [String: Double]()) { accu, idAndTime in accu[idAndTime.id] = (accu[idAndTime.id] ?? 0) + idAndTime.time } let entriesKeyValues: [(String, Double)] = entriesDict.sorted { $0.1 < $1.1 } let lines: [String] = entriesKeyValues.map { id, time -> String in return "\(numberFormatter.string(from: NSNumber(value: time))!): \(id)" } let string: String = lines.joined(separator: "\n") + "\n" let url = URL(fileURLWithPath: "benchmark_\(name)_\(timestamp).txt") try? string.data(using: .utf8)?.write(to: url, options: [.atomic]) } } private let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 3 return formatter }() private let timestamp: String = { let formatter = DateFormatter() formatter.dateFormat = "yyyy_MM_dd_HH_mm_ss" return formatter.string(from: Date()) }()
mit
47515fe0d206d6f9d0d5c5c9f32167c4
30.803922
105
0.634402
3.995074
false
false
false
false
cemolcay/KeyboardLayoutEngine
Keyboard/KeyboardLayoutEngine/KeyboardRow.swift
1
6974
// // KeyboardRow.swift // KeyboardLayoutEngine // // Created by Cem Olcay on 06/05/16. // Copyright © 2016 Prototapp. All rights reserved. // import UIKit // MARK: - KeyboardRowStyle public struct KeyboardRowStyle { public var leadingPadding: CGFloat public var leadingPaddingLandscape: CGFloat public var trailingPadding: CGFloat public var trailingPaddingLandscape: CGFloat public var topPadding: CGFloat public var topPaddingLandscape: CGFloat public var bottomPadding: CGFloat public var bottomPaddingLandscape: CGFloat public var buttonsPadding: CGFloat public var buttonsPaddingLandscape: CGFloat public init( leadingPadding: CGFloat? = nil, leadingPaddingLandscape: CGFloat? = nil, trailingPadding: CGFloat? = nil, trailingPaddingLandscape: CGFloat? = nil, topPadding: CGFloat? = nil, topPaddingLandscape: CGFloat? = nil, bottomPadding: CGFloat? = nil, bottomPaddingLandscape: CGFloat? = nil, buttonsPadding: CGFloat? = nil, buttonsPaddingLandscape: CGFloat? = nil) { self.leadingPadding = leadingPadding ?? 3 self.leadingPaddingLandscape = leadingPaddingLandscape ?? leadingPadding ?? 3 self.trailingPadding = trailingPadding ?? 3 self.trailingPaddingLandscape = trailingPaddingLandscape ?? trailingPadding ?? 3 self.topPadding = topPadding ?? 6 self.topPaddingLandscape = topPaddingLandscape ?? topPadding ?? 6 self.bottomPadding = bottomPadding ?? 6 self.bottomPaddingLandscape = bottomPaddingLandscape ?? bottomPadding ?? 4 self.buttonsPadding = buttonsPadding ?? 6 self.buttonsPaddingLandscape = buttonsPaddingLandscape ?? buttonsPadding ?? 5 } } // MARK: - KeyboardRow public class KeyboardRow: UIView { public var style: KeyboardRowStyle! /// Characters should be eighter `KeyboardButton` or `KeyboardRow` public var characters: [AnyObject]! /// Managed by KeyboardLayout internal var isPortrait: Bool = true /// Managed by self, returns parent `KeyboardRow` if exists. public private(set) var parentRow: KeyboardRow? public var buttonHitRangeInsets: UIEdgeInsets { return UIEdgeInsets( top: isPortrait ? -style.topPadding : -style.topPaddingLandscape, left: -(style.buttonsPadding / 2.0), bottom: isPortrait ? -style.bottomPadding : -style.bottomPaddingLandscape, right: -(style.buttonsPadding / 2.0)) } // MARK: Init public init(style: KeyboardRowStyle, characters: [AnyObject]) { assert(characters.filter({ !(($0 is KeyboardButton) || ($0 is KeyboardRow)) }).count <= 0) super.init(frame: CGRect.zero) self.style = style self.characters = characters for character in self.characters { if let character = character as? KeyboardButton { addSubview(character) } if let row = character as? KeyboardRow { addSubview(row) } } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: Paddings func getLeadingPadding() -> CGFloat { return isPortrait ? style.leadingPadding : style.leadingPaddingLandscape ?? style.leadingPadding } func getTrailingPadding() -> CGFloat { return isPortrait ? style.trailingPadding : style.trailingPaddingLandscape ?? style.trailingPadding } func getButtonsPadding() -> CGFloat { return isPortrait ? style.buttonsPadding : style.buttonsPaddingLandscape ?? style.buttonsPadding } // MARK: Layout public override func layoutSubviews() { super.layoutSubviews() let optimumButtonWidth = getOptimumButtonWidth() var currentX = getLeadingPadding() for character in characters { if let character = character as? KeyboardButton { character.frame = CGRect( x: currentX, y: 0, width: getWidthForKeyboardButton(character), height: frame.size.height) currentX += character.frame.size.width + getButtonsPadding() // Set hit range character.hitRangeInsets = buttonHitRangeInsets if character == characters.first as? KeyboardButton && parentRow == nil { character.hitRangeInsets.left -= 20 } else if character == characters.last as? KeyboardButton && parentRow == nil { character.hitRangeInsets.right -= 20 } } if let childRow = character as? KeyboardRow { childRow.parentRow = self childRow.isPortrait = isPortrait childRow.frame = CGRect( x: currentX, y: 0, width: childRow.getLeadingPadding() + optimumButtonWidth + childRow.getTrailingPadding(), height: frame.size.height) currentX += childRow.frame.size.width + getButtonsPadding() } } currentX += getTrailingPadding() } private func getRelativeWidthForPercent(percent: CGFloat) -> CGFloat { let buttonsPadding = max(0, CGFloat(characters.count - 1)) * getButtonsPadding() let totalPadding = buttonsPadding + getLeadingPadding() + getTrailingPadding() let cleanWidth = frame.size.width - totalPadding return cleanWidth * percent } private func getWidthForKeyboardButton(button: KeyboardButton) -> CGFloat { switch button.widthInRow { case .Dynamic: return getOptimumButtonWidth() case .Static(let width): return width case .Relative(let percent): return getRelativeWidthForPercent(percent) } } private func getOptimumButtonWidth() -> CGFloat { var charactersWithDynamicWidthCount: Int = 0 var totalStaticWidthButtonsWidth: CGFloat = 0 var totalChildRowPadding: CGFloat = 0 for character in characters { if let button = character as? KeyboardButton { switch button.widthInRow { case .Dynamic: charactersWithDynamicWidthCount += 1 case .Static(let width): totalStaticWidthButtonsWidth += width case .Relative(let percent): totalStaticWidthButtonsWidth += getRelativeWidthForPercent(percent) break } } else if let row = character as? KeyboardRow { totalChildRowPadding += row.getLeadingPadding() + row.getTrailingPadding() charactersWithDynamicWidthCount += 1 } } let width = frame.size.width let totalButtonPadding: CGFloat = max(0, CGFloat(characters.count - 1) * getButtonsPadding()) let totalPadding = totalButtonPadding + totalStaticWidthButtonsWidth + totalChildRowPadding + getLeadingPadding() + getTrailingPadding() let opt = (width - totalPadding) / CGFloat(charactersWithDynamicWidthCount) return opt } // MARK: Hit Test public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if UIEdgeInsetsEqualToEdgeInsets(buttonHitRangeInsets, UIEdgeInsetsZero) { return super.pointInside(point, withEvent: event) } let hitFrame = UIEdgeInsetsInsetRect(bounds, buttonHitRangeInsets) return CGRectContainsPoint(hitFrame, point) } }
mit
0059fde4b7f25be21d1b0c287837bcd2
33.519802
103
0.699125
4.973609
false
false
false
false
kosicki123/eidolon
Kiosk/Bid Fulfillment/Models/BidDetails.swift
1
774
@objc public class BidDetails: NSObject { public dynamic var newUser: NewUser = NewUser() public dynamic var saleArtwork: SaleArtwork? public dynamic var paddleNumber: String? public dynamic var bidderPIN: String? public dynamic var bidAmountCents: NSNumber? public dynamic var bidderID: String? public init(saleArtwork: SaleArtwork?, paddleNumber: String?, bidderPIN: String?, bidAmountCents:Int?) { self.saleArtwork = saleArtwork self.paddleNumber = paddleNumber self.bidderPIN = bidderPIN self.bidAmountCents = bidAmountCents } /// Not for production use public convenience init(string: String) { self.init(saleArtwork: nil, paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil) } }
mit
43ee972bbf1b4e65cbc0951ab25a798b
35.904762
108
0.709302
4.867925
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/User/GroupCreatorsResponseHandler.swift
1
2291
// // GroupCreatorsResponseHandler.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import ObjectMapper class GroupCreatorsResponseHandler: ResponseHandler { fileprivate let completion: UsersClosure? init(completion: UsersClosure?) { self.completion = completion } override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) { if let response = response, let usersMappers = Mapper<UserMapper>().mapArray(JSONObject: response["data"]) { let metadata = MappingUtils.metadataFromResponse(response) let pageInfo = MappingUtils.pagingInfoFromResponse(response) let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata) let users = usersMappers.map({ User(mapper: $0, dataMapper: dataMapper, metadata: metadata) }) executeOnMainQueue { self.completion?(users, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) } } else { executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) } } } }
mit
7464f3d96f34e8079037761aa5e476ed
44.82
128
0.726757
4.753112
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01224-swift-parser-skipsingle.swift
1
983
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func e<l { enum e { func p() { p class A { class func a() -> Self { } } func b<T>(t: AnyObject.Type) -> T! { } func b<d-> d { class d:b class b protocol A { } func f() { } func ^(d: e, Bool) -> Bool {g !(d) } protocol d { f k } } protocol n { } class o: n{ cla) u p).v.c() k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) { func f<o>() -> (o, o -> o) -> o { o m o.j = { o) { return { -> T class func a() -> String { struct c { static let d: String = { b {A { u) { func g<T where T.E == F>(f: B<T>) { func e( class A { class func a() -> String { struct c { static let d
apache-2.0
4181627cb073b03d22bed59d916cb2e9
19.479167
79
0.604273
2.693151
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/02100-swift-printingdiagnosticconsumer-handlediagnostic.swift
1
808
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct c { protocol A { let x { } } func g.i { } protocol a { } protocol a { protocol b : Array) -> { func a("foobar""")""foobar" typealias e : h === 1] let h : e() class A<j : ji.b { var d = e() { let t: d = { class func f<T: NSManagedObject { } func a<T where H) -> { protocol b in c { } func b.e() { func ^( typealias e : Int = { h = [") } } init() -> S { protocol c v: l -> { case C([]).<f : d { enum e(j,
apache-2.0
59401088931ce32c766376efb6f2560e
19.717949
79
0.638614
3.003717
false
false
false
false
Bartlebys/Bartleby
Bartleby.xOS/extensions/XImage+Data.swift
1
2353
// // Asset+ImageSupport.swift // YouDub // // Created by Benoit Pereira da silva on 15/08/2017. // Copyright © 2017 https://pereira-da-silva.com/ All rights reserved. // import Foundation #if os(OSX) import AppKit #elseif os(iOS) import UIKit #elseif os(watchOS) #elseif os(tvOS) #endif enum XImageError:Error { case bitmapRepresentationHasFailed case dataRepresentationHasFailed case dataDecodingHasFailed } public extension XImage{ static let DEFAULT_COMPRESSION_FACTOR:Double = 0.7 //#TODO iOS Support public static func from(_ data:Data) throws ->XImage?{ guard let image = XImage(data:data) else{ throw XImageError.dataDecodingHasFailed } return image } public func JPEGdata(compressionFactor:Double=XImage.DEFAULT_COMPRESSION_FACTOR)throws ->Data{ guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(self.size.width), pixelsHigh: Int(self.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.deviceRGB, bytesPerRow: 0, bitsPerPixel: 0 ) else { throw XImageError.bitmapRepresentationHasFailed } let cf = (compressionFactor <= 1.0 && compressionFactor >= 0 ) ? compressionFactor : XImage.DEFAULT_COMPRESSION_FACTOR NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep) self.draw(at: NSZeroPoint, from: NSZeroRect, operation: .sourceOver, fraction: 1.0) NSGraphicsContext.restoreGraphicsState() guard let data = rep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: cf]) else { throw XImageError.dataRepresentationHasFailed } return data } public var JPEGBase64String:String? { if let data = try? JPEGdata(){ return data.base64EncodedString(options: []) } return nil } public static func fromJPEGBase64String(string:String)->XImage?{ if let data = Data(base64Encoded: string){ return XImage(data: data) } return nil } }
apache-2.0
3d9d3195981cb1adb8e342a257691a77
28.037037
155
0.64966
4.648221
false
false
false
false
khizkhiz/swift
test/Constraints/default_literals.swift
2
891
// RUN: %target-parse-verify-swift func acceptInt(_ : inout Int) {} func acceptDouble(_ : inout Double) {} var i1 = 1 acceptInt(&i1) var i2 = 1 + 2.0 + 1 acceptDouble(&i2) func ternary<T>(cond: Bool, @autoclosure _ ifTrue: () -> T, @autoclosure _ ifFalse: () -> T) -> T {} ternary(false, 1, 2.5) ternary(false, 2.5, 1) // <rdar://problem/18447543> ternary(false, 1, 2 as Int32) ternary(false, 1, 2 as Float) func genericFloatingLiteral<T : FloatLiteralConvertible>(x: T) { var _ : T = 2.5 } var d = 3.5 genericFloatingLiteral(d) extension UInt32 { func asChar() -> UnicodeScalar { return UnicodeScalar(self) } } var ch = UInt32(65).asChar() // <rdar://problem/14634379> extension Int { func call0() {} typealias Signature = (a: String, b: String) func call(x: Signature) {} } 3.call((a: "foo", b: "bar")) var (div, mod) = (9 / 4, 9 % 4)
apache-2.0
2a2f0a34ef7b071516efea82b5bcecc8
19.25
64
0.611672
2.83758
false
false
false
false
touchopia/HackingWithSwift
project9/Project7/ViewController.swift
1
2378
// // ViewController.swift // Project7 // // Created by TwoStraws on 15/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import UIKit class ViewController: UITableViewController { var petitions = [[String: String]]() override func viewDidLoad() { super.viewDidLoad() performSelector(inBackground: #selector(fetchJSON), with: nil) } func fetchJSON() { let urlString: String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } if let url = URL(string: urlString) { if let data = try? Data(contentsOf: url) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { self.parse(json: json) return } } } performSelector(onMainThread: #selector(showError), with: nil, waitUntilDone: false) } func parse(json: JSON) { for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let sigs = result["signatureCount"].stringValue let obj = ["title": title, "body": body, "sigs": sigs] petitions.append(obj) } tableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: false) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return petitions.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let petition = petitions[indexPath.row] cell.textLabel?.text = petition["title"] cell.detailTextLabel?.text = petition["body"] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = DetailViewController() vc.detailItem = petitions[indexPath.row] navigationController?.pushViewController(vc, animated: true) } func showError() { let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } }
unlicense
2fd49e9ce5eebb390b21aa2907edf3ab
27.987805
170
0.714767
3.821543
false
false
false
false
tkremenek/swift
test/IRGen/prespecialized-metadata/class-inmodule-1argument-run.swift
10
2556
// RUN: %target-run-simple-swift(%S/Inputs/main.swift %S/Inputs/consume-logging-metadata-value.swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // Executing on the simulator within __abort_with_payload with "No ABI plugin located for triple x86_64h-apple-ios -- shared libraries will not be registered!" // UNSUPPORTED: CPU=x86_64 && OS=ios // UNSUPPORTED: CPU=x86_64 && OS=tvos // UNSUPPORTED: CPU=x86_64 && OS=watchos // UNSUPPORTED: CPU=i386 && OS=watchos // UNSUPPORTED: use_os_stdlib class MyGenericClazz<T> { let line: UInt init(line: UInt = #line) { self.line = line } } extension MyGenericClazz : CustomStringConvertible { var description: String { "\(type(of: self)) @ \(line)" } } @inline(never) func consume<T>(clazz: MyGenericClazz<T>) { consume(clazz) } @inline(never) func consume<T>(clazzType: MyGenericClazz<T>.Type) { consume(clazzType) } public func doit() { // CHECK: [[FLOAT_METADATA_ADDRESS:[0-9a-f]+]] MyGenericClazz<Float> @ 46 consume(MyGenericClazz<Float>()) // CHECK: [[FLOAT_METADATA_ADDRESS]] MyGenericClazz<Float> @ 48 consume(clazz: MyGenericClazz<Float>()) // CHECK: [[DOUBLE_METADATA_ADDRESS:[0-9a-f]+]] MyGenericClazz<Double> @ 51 consume(MyGenericClazz<Double>()) // CHECK: [[DOUBLE_METADATA_ADDRESS]] MyGenericClazz<Double> @ 53 consume(clazz: MyGenericClazz<Double>()) // CHECK: [[INT_METADATA_ADDRESS:[0-9a-f]+]] MyGenericClazz<Int> @ 56 consume(MyGenericClazz<Int>()) // CHECK: [[INT_METADATA_ADDRESS]] MyGenericClazz<Int> @ 58 consume(clazz: MyGenericClazz<Int>()) // CHECK: [[STRING_METADATA_ADDRESS:[0-9a-f]+]] MyGenericClazz<String> @ 61 consume(MyGenericClazz<String>()) // CHECK: [[STRING_METADATA_ADDRESS]] MyGenericClazz<String> @ 63 consume(clazz: MyGenericClazz<String>()) // CHECK: [[NESTED_METADATA_ADDRESS:[0-9a-f]+]] MyGenericClazz<MyGenericClazz<String>> @ 66 consume(MyGenericClazz<MyGenericClazz<String>>()) // CHECK: [[NESTED_METADATA_ADDRESS:[0-9a-f]+]] MyGenericClazz<MyGenericClazz<String>> @ 68 consume(clazz: MyGenericClazz<MyGenericClazz<String>>()) // CHECK: [[FLOAT_METADATA_METATYPE_ADDRESS:[0-9a-f]+]] MyGenericClazz<Float> consume(MyGenericClazz<Float>.self) // CHECK: [[FLOAT_METADATA_METATYPE_ADDRESS]] MyGenericClazz<Float> consume(clazzType: MyGenericClazz<Float>.self) }
apache-2.0
12402f24b6ea0717ab1ebc050b2e5ebf
33.540541
190
0.706182
3.605078
false
false
false
false
tkremenek/swift
validation-test/compiler_crashers_2_fixed/0207-sr7371.swift
11
1032
// RUN: %target-swift-frontend -emit-ir %s public protocol TypedParserResultTransferType { // Remove type constraint associatedtype Result: ParserResult } public struct AnyTypedParserResultTransferType<P: ParserResult>: TypedParserResultTransferType { public typealias Result = P // Remove property public let result: P } public protocol ParserResult {} public protocol StaticParser: ParserResult {} // Change comformance to ParserResult public protocol TypedStaticParser: StaticParser { // Remove type constraint associatedtype ResultTransferType: TypedParserResultTransferType } // Remove where clause public protocol MutableSelfStaticParser: TypedStaticParser where ResultTransferType == AnyTypedParserResultTransferType<Self> { func parseTypeVar() -> AnyTypedParserResultTransferType<Self> } extension MutableSelfStaticParser { public func anyFunction() -> () { let t = self.parseTypeVar // Remove this and below _ = t() _ = self.parseTypeVar() } }
apache-2.0
29616c54c6e7dd37c4b1f0add2ae1824
27.666667
127
0.747093
5.058824
false
false
false
false
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/UIKit/Extension/UIImageViewExt.swift
1
2472
// // UIImageViewExt.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/9/27. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit import Photos let ImageAssetCache = NSCache<NSString, UIImage>() let AssetIdentifier = UnsafeRawPointer.init(bitPattern: "yj_assetIdentifier".hashValue)! /// UIImageView+PHAsset public extension UIImageView { private var assetIdentifier: NSString { get { return objc_getAssociatedObject(self, AssetIdentifier) as! NSString } set { objc_setAssociatedObject(self, AssetIdentifier, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } /// 清空 PHAsset 图片缓存 static func removeCachingImagesForAllAssets() { ImageAssetCache.removeAllObjects() } /// 设置 PHAsset 图片 func setImage(_ asset: PHAsset, placeholder: UIImage? = nil, progressHandler: PHAssetImageProgressHandler? = nil) { self.contentMode = .scaleAspectFill let scale = UIScreen.main.scale let size = CGSize(width: self.frameWidth * scale, height: self.frameHeight * scale) let key = asset.localIdentifier + "\(size)" as NSString self.assetIdentifier = key if let image = ImageAssetCache.object(forKey: key) { self.setAssetImage(image, identifier: key) return } else { self.image = placeholder } let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true options.progressHandler = progressHandler options.resizeMode = .fast PHImageManagerS.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options) { [weak self] (image, _) in guard let image = image else { return } ImageAssetCache.setObject(image, forKey: key) guard let assetIdentifier = self?.assetIdentifier, assetIdentifier == key else { return } DispatchQueue.asyncMain { [weak self] in self?.setAssetImage(image, identifier: key) } } } private func setAssetImage(_ image: UIImage, identifier: NSString) { guard self.assetIdentifier == identifier else { return } let flexibleHeight = image.size.width <= image.size.height self.autoresizingMask = flexibleHeight ? .flexibleHeight : .flexibleWidth self.image = image } }
mit
1a531ffbe702c3b42ca0aa7b6dc1466c
36.430769
138
0.661323
4.74269
false
false
false
false
joncardasis/ChromaColorPicker
Tests/ChromaControlStylableTests.swift
1
1682
// // ChromaControlStylableTests.swift // ChromaColorPickerTests // // Created by Jon Cardasis on 5/2/19. // Copyright © 2019 Jonathan Cardasis. All rights reserved. // import XCTest @testable import ChromaColorPicker class ChromaControlStyableTests: XCTestCase { func testUIViewShadowPropertiesShouldReturnBlackColor() { // Given let view = TestView() // When let shadowProps = view.shadowProperties(forHeight: 120) // Then XCTAssertEqual(shadowProps.color, UIColor.black.cgColor) } func testUIViewShadowPropertiesOpacity() { // Given let view = TestView() // When let shadowProps = view.shadowProperties(forHeight: 120) // Then XCTAssertEqual(shadowProps.opacity, 0.35) } func testUIViewShadowPropertiesRadius() { // Given let view = TestView() // When let shadowProps = view.shadowProperties(forHeight: 120) // Then XCTAssertEqual(shadowProps.radius, 4) } func testUIViewShadowPropertiesOffsetHeightShouldBeOnePercentOfProvidedHeight() { // Given let view = TestView() // When let shadowProps = view.shadowProperties(forHeight: 1200) // Then XCTAssertEqual(shadowProps.offset.width, 0) XCTAssertEqual(shadowProps.offset.height, 12) } } private class TestView: UIView, ChromaControlStylable { var borderWidth: CGFloat = 2.0 var borderColor: UIColor = UIColor.green var showsShadow: Bool = true func updateShadowIfNeeded() {} }
mit
b7c042188bd6d814cc730a3301d82eeb
24.469697
85
0.622844
4.944118
false
true
false
false
ReactiveX/RxSwift
RxCocoa/Foundation/NSObject+Rx.swift
2
19274
// // NSObject+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !os(Linux) import Foundation import RxSwift #if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) import RxCocoaRuntime #endif #if !DISABLE_SWIZZLING && !os(Linux) private var deallocatingSubjectTriggerContext: UInt8 = 0 private var deallocatingSubjectContext: UInt8 = 0 #endif private var deallocatedSubjectTriggerContext: UInt8 = 0 private var deallocatedSubjectContext: UInt8 = 0 #if !os(Linux) /** KVO is a tricky mechanism. When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior. When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior. KVO with weak references is especially tricky. For it to work, some kind of swizzling is required. That can be done by * replacing object class dynamically (like KVO does) * by swizzling `dealloc` method on all instances for a class. * some third method ... Both approaches can fail in certain scenarios: * problems arise when swizzlers return original object class (like KVO does when nobody is observing) * Problems can arise because replacing dealloc method isn't atomic operation (get implementation, set implementation). Second approach is chosen. It can fail in case there are multiple libraries dynamically trying to replace dealloc method. In case that isn't the case, it should be ok. */ extension Reactive where Base: NSObject { /** Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set. `observe` is just a simple and performant wrapper around KVO mechanism. * it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`) * it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`) * the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc. If support for weak properties is needed or observing arbitrary or unknown relationships in the ownership tree, `observeWeakly` is the preferred option. - parameter type: Optional type hint of the observed sequence elements. - parameter keyPath: Key path of property names to observe. - parameter options: KVO mechanism notification options. - parameter retainSelf: Retains self during observation if set `true`. - returns: Observable sequence of objects on `keyPath`. */ public func observe<Element>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<Element?> { KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable() } /** Observes values at the provided key path using the provided options. - parameter keyPath: A key path between the object and one of its properties. - parameter options: Key-value observation options, defaults to `.new` and `.initial`. - note: When the object is deallocated, a completion event is emitted. - returns: An observable emitting value changes at the provided key path. */ public func observe<Element>(_ keyPath: KeyPath<Base, Element>, options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<Element> { Observable<Element>.create { [weak base] observer in let observation = base?.observe(keyPath, options: options) { obj, _ in observer.on(.next(obj[keyPath: keyPath])) } return Disposables.create { observation?.invalidate() } } .take(until: base.rx.deallocated) } } #endif #if !DISABLE_SWIZZLING && !os(Linux) // KVO extension Reactive where Base: NSObject { /** Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`. It can be used in all cases where `observe` can be used and additionally * because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown * it can be used to observe `weak` properties **Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.** - parameter type: Optional type hint of the observed sequence elements. - parameter keyPath: Key path of property names to observe. - parameter options: KVO mechanism notification options. - returns: Observable sequence of objects on `keyPath`. */ public func observeWeakly<Element>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable<Element?> { return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options) .map { n in return n as? Element } } } #endif // Dealloc extension Reactive where Base: AnyObject { /** Observable sequence of object deallocated events. After object is deallocated one `()` element will be produced and sequence will immediately complete. - returns: Observable sequence of object deallocated events. */ public var deallocated: Observable<Void> { return self.synchronized { if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable { return deallocObservable.subject } let deallocObservable = DeallocObservable() objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return deallocObservable.subject } } #if !DISABLE_SWIZZLING && !os(Linux) /** Observable sequence of message arguments that completes when object is deallocated. Each element is produced before message is invoked on target object. `methodInvoked` exists in case observing of invoked messages is needed. In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. In case some argument is `nil`, instance of `NSNull()` will be sent. - returns: Observable sequence of arguments passed to `selector` method. */ public func sentMessage(_ selector: Selector) -> Observable<[Any]> { return self.synchronized { // in case of dealloc selector replay subject behavior needs to be used if selector == deallocSelector { return self.deallocating.map { _ in [] } } do { let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) return proxy.messageSent.asObservable() } catch let e { return Observable.error(e) } } } /** Observable sequence of message arguments that completes when object is deallocated. Each element is produced after message is invoked on target object. `sentMessage` exists in case interception of sent messages before they were invoked is needed. In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. In case some argument is `nil`, instance of `NSNull()` will be sent. - returns: Observable sequence of arguments passed to `selector` method. */ public func methodInvoked(_ selector: Selector) -> Observable<[Any]> { return self.synchronized { // in case of dealloc selector replay subject behavior needs to be used if selector == deallocSelector { return self.deallocated.map { _ in [] } } do { let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) return proxy.methodInvoked.asObservable() } catch let e { return Observable.error(e) } } } /** Observable sequence of object deallocating events. When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence will immediately complete. In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. - returns: Observable sequence of object deallocating events. */ public var deallocating: Observable<()> { return self.synchronized { do { let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector) return proxy.messageSent.asObservable() } catch let e { return Observable.error(e) } } } private func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T { let rxSelector = RX_selector(selector) let selectorReference = RX_reference_from_selector(rxSelector) let subject: T if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T { subject = existingSubject } else { subject = T() objc_setAssociatedObject( self.base, selectorReference, subject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } if subject.isActive { return subject } var error: NSError? let targetImplementation = RX_ensure_observing(self.base, selector, &error) if targetImplementation == nil { throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown } subject.targetImplementation = targetImplementation! return subject } #endif } // MARK: Message interceptors #if !DISABLE_SWIZZLING && !os(Linux) private protocol MessageInterceptorSubject: AnyObject { init() var isActive: Bool { get } var targetImplementation: IMP { get set } } private final class DeallocatingProxy : MessageInterceptorSubject , RXDeallocatingObserver { typealias Element = () let messageSent = ReplaySubject<()>.create(bufferSize: 1) @objc var targetImplementation: IMP = RX_default_target_implementation() var isActive: Bool { return self.targetImplementation != RX_default_target_implementation() } init() { } @objc func deallocating() { self.messageSent.on(.next(())) } deinit { self.messageSent.on(.completed) } } private final class MessageSentProxy : MessageInterceptorSubject , RXMessageSentObserver { typealias Element = [AnyObject] let messageSent = PublishSubject<[Any]>() let methodInvoked = PublishSubject<[Any]>() @objc var targetImplementation: IMP = RX_default_target_implementation() var isActive: Bool { return self.targetImplementation != RX_default_target_implementation() } init() { } @objc func messageSent(withArguments arguments: [Any]) { self.messageSent.on(.next(arguments)) } @objc func methodInvoked(withArguments arguments: [Any]) { self.methodInvoked.on(.next(arguments)) } deinit { self.messageSent.on(.completed) self.methodInvoked.on(.completed) } } #endif private final class DeallocObservable { let subject = ReplaySubject<Void>.create(bufferSize:1) init() { } deinit { self.subject.on(.next(())) self.subject.on(.completed) } } // MARK: KVO #if !os(Linux) private protocol KVOObservableProtocol { var target: AnyObject { get } var keyPath: String { get } var retainTarget: Bool { get } var options: KeyValueObservingOptions { get } } private final class KVOObserver : _RXKVOObserver , Disposable { typealias Callback = (Any?) -> Void var retainSelf: KVOObserver? init(parent: KVOObservableProtocol, callback: @escaping Callback) { #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback) self.retainSelf = self } override func dispose() { super.dispose() self.retainSelf = nil } deinit { #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } private final class KVOObservable<Element> : ObservableType , KVOObservableProtocol { typealias Element = Element? unowned var target: AnyObject var strongTarget: AnyObject? var keyPath: String var options: KeyValueObservingOptions var retainTarget: Bool init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) { self.target = object self.keyPath = keyPath self.options = options self.retainTarget = retainTarget if retainTarget { self.strongTarget = object } } func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element? { let observer = KVOObserver(parent: self) { value in if value as? NSNull != nil { observer.on(.next(nil)) return } observer.on(.next(value as? Element)) } return Disposables.create(with: observer.dispose) } } private extension KeyValueObservingOptions { var nsOptions: NSKeyValueObservingOptions { var result: UInt = 0 if self.contains(.new) { result |= NSKeyValueObservingOptions.new.rawValue } if self.contains(.initial) { result |= NSKeyValueObservingOptions.initial.rawValue } return NSKeyValueObservingOptions(rawValue: result) } } #endif #if !DISABLE_SWIZZLING && !os(Linux) private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable<AnyObject?> { let components = keyPath.components(separatedBy: ".").filter { $0 != "self" } let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options) .finishWithNilWhenDealloc(target) if !options.isDisjoint(with: .initial) { return observable } else { return observable .skip(1) } } // This should work correctly // Identifiers can't contain `,`, so the only place where `,` can appear // is as a delimiter. // This means there is `W` as element in an array of property attributes. private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool { properyRuntimeInfo.range(of: ",W,") != nil } private extension ObservableType where Element == AnyObject? { func finishWithNilWhenDealloc(_ target: NSObject) -> Observable<AnyObject?> { let deallocating = target.rx.deallocating return deallocating .map { _ in return Observable.just(nil) } .startWith(self.asObservable()) .switchLatest() } } private func observeWeaklyKeyPathFor( _ target: NSObject, keyPathSections: [String], options: KeyValueObservingOptions ) -> Observable<AnyObject?> { weak var weakTarget: AnyObject? = target let propertyName = keyPathSections[0] let remainingPaths = Array(keyPathSections[1..<keyPathSections.count]) let property = class_getProperty(object_getClass(target), propertyName) if property == nil { return Observable.error(RxCocoaError.invalidPropertyName(object: target, propertyName: propertyName)) } let propertyAttributes = property_getAttributes(property!) // should dealloc hook be in place if week property, or just create strong reference because it doesn't matter let isWeak = isWeakProperty(propertyAttributes.map(String.init) ?? "") let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.initial), retainTarget: false) as KVOObservable<AnyObject> // KVO recursion for value changes return propertyObservable .flatMapLatest { (nextTarget: AnyObject?) -> Observable<AnyObject?> in if nextTarget == nil { return Observable.just(nil) } let nextObject = nextTarget! as? NSObject let strongTarget: AnyObject? = weakTarget if nextObject == nil { return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName)) } // if target is alive, then send change // if it's deallocated, don't send anything if strongTarget == nil { return Observable.empty() } let nextElementsObservable = keyPathSections.count == 1 ? Observable.just(nextTarget) : observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options) if isWeak { return nextElementsObservable .finishWithNilWhenDealloc(nextObject!) } else { return nextElementsObservable } } } #endif // MARK: Constants private let deallocSelector = NSSelectorFromString("dealloc") // MARK: AnyObject + Reactive extension Reactive where Base: AnyObject { func synchronized<T>( _ action: () -> T) -> T { objc_sync_enter(self.base) let result = action() objc_sync_exit(self.base) return result } } extension Reactive where Base: AnyObject { /** Helper to make sure that `Observable` returned from `createCachedObservable` is only created once. This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`. */ func lazyInstanceObservable<T: AnyObject>(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T { if let value = objc_getAssociatedObject(self.base, key) { return value as! T } let observable = createCachedObservable() objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return observable } } #endif
mit
108120b246983a1ddd967c62363ec0a0
32.871705
169
0.637109
5.175349
false
false
false
false
Maciej-Matuszewski/GRCalendar
GRCalendar/Classes/macOS/GRCalendarItem.swift
1
2582
// // GRCalendarItem.swift // // Created by Maciej Matuszewski on 26.08.2017. // Copyright © 2017 Maciej Matuszewski. All rights reserved. // import Cocoa class GRCalendarItem: NSCollectionViewItem { fileprivate let dateLabel = NSTextField.init() override func loadView() { self.view = NSView.init() self.configureLayout() } override func viewDidLoad() { super.viewDidLoad() } fileprivate func configureLayout() { self.view.wantsLayer = true self.view.layer?.cornerRadius = 20 self.view.layer?.masksToBounds = true self.dateLabel.translatesAutoresizingMaskIntoConstraints = false self.dateLabel.stringValue = "30" self.dateLabel.font = NSFont.systemFont(ofSize: 18) self.dateLabel.textColor = NSColor.textColor self.dateLabel.alignment = .center self.dateLabel.isBezeled = false self.dateLabel.drawsBackground = false self.dateLabel.isEditable = false self.dateLabel.isSelectable = false self.view.addSubview(self.dateLabel) self.dateLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.dateLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true self.dateLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true } func configure(_ state: GRCalendarItemState, dayOfMonth: Int?) { if let day = dayOfMonth{ self.dateLabel.stringValue = day.description } else { self.dateLabel.stringValue = "" } configure(state) } func configure(_ state: GRCalendarItemState) { switch state { case .outsideMonth: self.dateLabel.textColor = NSColor.lightGray self.view.layer?.backgroundColor = NSColor.clear.cgColor return case .today: self.dateLabel.textColor = NSColor.white self.view.layer?.backgroundColor = NSColor.red.cgColor case .selected: self.dateLabel.textColor = NSColor.white self.view.layer?.backgroundColor = NSColor.black.cgColor case .weekend: self.dateLabel.textColor = NSColor.red self.view.layer?.backgroundColor = NSColor.clear.cgColor case .weekday: self.dateLabel.textColor = NSColor.textColor self.view.layer?.backgroundColor = NSColor.clear.cgColor return } } }
mit
dc68433f979ecadb73fee155713f2e2d
31.670886
97
0.631538
5.041016
false
true
false
false
mlgoogle/viossvc
viossvc/AppAPI/SocketAPI/SocketConst.swift
1
4254
// // SockOpcode.swift // viossvc // // Created by yaowang on 2016/11/22. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation class SocketConst: NSObject { enum OPCode:UInt16 { // 心跳包 case Heart = 1000 // 请求登录 case Login = 1001 //请求手机短信 case SMSVerify = 1019 //验证手机验证码 case VerifyCode = 1101 case CheckInviteCode = 1113 //注册 case Register = 1021 //重置密码 case NodifyPasswrod = 1011 //修改用户信息 case NodifyUserInfo = 1023 //获取图片token case GetImageToken = 1047 //获取用户余额 case UserCash = 1067 //认证用户头像 case AuthUserHeader = 1091 //获取用户的银行卡信息 case UserBankCards = 1097 //校验提现密码 case CheckDrawCashPassword = 1087 //提现 case DrawCash = 1103 //提现详情 case DrawCashDetail = 0004 //提现记录 case DrawCashRecord = 1105 //设置默认银行卡 case DefaultBankCard = 1099 //添加新的银行卡 case NewBankCard = 1095 //获取所有技能标签 case AllSkills = 1041 //获取身份认证进度 case AuthStatus = 1057 //上传身份认证信息 case AuthUser = 1055 //设置/修改支付密码 case DrawCashPassword = 1089 //V领队服务 case ServiceList = 1501 //更新V领队服务 case UpdateServiceList = 1503 //技能分享列表 case SkillShareList = 1071 //技能分享详情 case SkillShareDetail = 1073 //技能分享评论列表 case SkillShareComment = 1075 //技能分享预约 case SkillShareEnroll = 1077 /** 订单列表 */ case OrderList = 1505 //订单详情 case OrderDetail = 1507 /** 操作技能标签 */ case HandleSkills = 1509 //商务分享类别 case TourShareType = 1059 //商务分享列表 case TourShareList = 1061 //商务分享详情 case TourShareDetail = 1065 //上传照片到照片墙 case UploadPhoto2Wall = 1107 //获取照片墙 case PhotoWall = 1109 /** 修改订单状态 */ case ModfyOrderStatus = 2011 case UploadContact = 1111 case LoginRet = 1002 case UserInfo = 1013 //发送chat消息 case ChatSendMessage = 2003 //收到chat消息 case ChatReceiveMessage = 2004 //获取chat离线消息 case ChatOfflineRequestMessage = 2025 case ChatOfflineReceiveMessage = 2006 case UpdateDeviceToken = 1031 case VersionInfo = 1115 case IDVerifyRequest = 1121 case PriceList = 1123 case FollowCount = 1129 case PriceSetting = 1131 case ContactAndPrice = 1133 // 发布动态 case SendDynamic = 1135 // 动态列表 case DynamicList = 1139 // 动态点赞 case ThumbUp = 1137 // 订单列表 case ClientOrderList = 1141 //请求活动列表 case getActivityList = 1143 // 个人简介 case persionalIntroduct = 1145 } enum type:UInt8 { case Error = 0 case User = 1 case Chat = 2 } class Key { static let last_id = "last_id_" static let count = "count_" static let share_id = "share_id_" static let page_type = "page_type_" static let uid = "uid_" static let from_uid = "from_uid_" static let to_uid = "to_uid_" static let order_id = "order_id_" static let order_status = "order_status_" static let change_type = "change_type_" static let skills = "skills_" static let phoneNum = "phoneNum_" static let invitationCode = "invitationCode_" } }
apache-2.0
e2ea849759735ea019eb086e89555177
23.396104
59
0.524088
4.216611
false
false
false
false
sopinetchat/SopinetChat-iOS
Pod/Classes/SChatKeyboardController.swift
1
13139
// // SChatKeyboardController.swift // Pods // // Created by David Moreno Lora on 3/5/16. // // import Foundation import UIKit let kSChatKeyboardControllerKeyValueObservingContext = UnsafeMutablePointer<()>() public class SChatKeyboardController : NSObject { // MARK: Properties var delegate: SChatKeyboardControllerDelegate? let textView: UITextView let contextView: UIView let panGestureRecognizer: UIPanGestureRecognizer var keyboardTriggerPoint: CGPoint? = nil var isObserving: Bool var keyboardView: UIView? let SChatKeyboardControllerNotificationKeyboardDidChangeFrame = "SChatKeyboardControllerNotificationKeyboardDidChangeFrame" let SChatKeyboardControllerUserInfoKeyKeyboardDidChangeFrame = "SChatKeyboardControllerUserInfoKeyKeyboardDidChangeFrame" // MARK: Initializers init(textView: UITextView, contextView: UIView, panGestureRecognizer: UIPanGestureRecognizer, delegate: SChatKeyboardControllerDelegate) { self.textView = textView self.contextView = contextView self.panGestureRecognizer = panGestureRecognizer self.delegate = delegate self.isObserving = false } // MARK: Setters func setKeyboardControllerView(keyboardView: UIView) { if self.keyboardView != nil { self.sChatRemoveKeyboardFrameObserver() } self.keyboardView = keyboardView if self.keyboardView != nil && !self.isObserving { self.keyboardView?.addObserver(self, forKeyPath: NSStringFromSelector(Selector("frame")), options: [NSKeyValueObservingOptions.Old, NSKeyValueObservingOptions.New], context: kSChatKeyboardControllerKeyValueObservingContext) self.isObserving = true } } // MARK: Getters func keyboardIsVisible() -> Bool { return self.keyboardView != nil } func currentKeyboardFrame() -> CGRect { if !self.keyboardIsVisible() { return CGRectNull } return self.keyboardView!.frame } // MARK: Keyboard Controller func beginListeningForKeyboard() { if self.textView.inputAccessoryView == nil { self.textView.inputAccessoryView = UIView() } self.sChatRegisterForNotifications() } func endListeningForKeyboard() { self.sChatUnregisterForNotifications() self.sChatSetKeyboardViewHidden(false) self.keyboardView = nil } // MARK: Notifications func sChatRegisterForNotifications() { self.sChatUnregisterForNotifications() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sChatDidReceiveKeyboardDidShowNotification(_:)), name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sChatDidReceiveKeyboardWillChangeFrameNotification(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sChatDidReceiveKeyboardDidChangeFrameNotification(_:)), name: UIKeyboardDidChangeFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sChatDidReceiveKeyboardDidHideNotification(_:)), name: UIKeyboardDidHideNotification, object: nil) } func sChatUnregisterForNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } func sChatDidReceiveKeyboardDidShowNotification(notification: NSNotification) { self.keyboardView = self.textView.inputAccessoryView?.superview self.sChatSetKeyboardViewHidden(false) self.sChatHandleKeyboardNotification(notification, completion: { finished in self.panGestureRecognizer.addTarget(self, action: #selector(self.sChatHandlePanGestureRecognizer(_:))) }) } func sChatDidReceiveKeyboardWillChangeFrameNotification(notification: NSNotification) { self.sChatHandleKeyboardNotification(notification, completion: nil) } func sChatDidReceiveKeyboardDidChangeFrameNotification(notification: NSNotification) { self.sChatSetKeyboardViewHidden(false) self.sChatHandleKeyboardNotification(notification, completion: nil) } func sChatDidReceiveKeyboardDidHideNotification(notification: NSNotification) { self.keyboardView = nil self.sChatHandleKeyboardNotification(notification, completion: { finished in self.panGestureRecognizer.removeTarget(self, action: nil) }) } func sChatHandleKeyboardNotification(notification: NSNotification, completion: ((finished: Bool) -> ())?) { let userInfo = notification.userInfo let keyboardEndFrame: CGRect = userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue() if CGRectIsNull(keyboardEndFrame) { return } let animationCurve = userInfo![UIKeyboardAnimationCurveUserInfoKey]?.integerValue let animationCurveOption = UInt(animationCurve! << 16) let animationDuration = userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue let keyboardEndFrameConverted = self.contextView.convertRect(keyboardEndFrame, fromView: nil) UIView.animateWithDuration(NSTimeInterval(animationDuration!), delay: NSTimeInterval(0.0), options: UIViewAnimationOptions(rawValue:animationCurveOption), animations: { self.sChatNotifyKeyboardFrameNotificationForFrame(keyboardEndFrameConverted) }, completion: { finished in if finished { completion?(finished: finished) } }) } // MARK: Utilities func sChatSetKeyboardViewHidden(hidden: Bool) { self.keyboardView?.hidden = hidden self.keyboardView?.userInteractionEnabled = !hidden } func sChatNotifyKeyboardFrameNotificationForFrame(frame: CGRect) { self.delegate?.keyboardDidChangeFrame(frame) NSNotificationCenter.defaultCenter().postNotificationName(SChatKeyboardControllerNotificationKeyboardDidChangeFrame, object: self, userInfo: [SChatKeyboardControllerUserInfoKeyKeyboardDidChangeFrame: NSValue(CGRect: frame)]) } func sChatResetKeyboardAndTextView() { self.sChatSetKeyboardViewHidden(true) self.sChatRemoveKeyboardFrameObserver() self.textView.resignFirstResponder() } // MARK: Key-value observing override public func observeValueForKeyPath(keyPath: String!, ofObject: AnyObject!, change: [String: AnyObject]!, context: UnsafeMutablePointer<Void>) { if context == kSChatKeyboardControllerKeyValueObservingContext { // TODO: Si algo falla, mirar lo de @selector(frame) if ofObject.isEqual(self.keyboardView!) && keyPath == NSStringFromSelector(Selector("frame")) { let oldKeyboardFrame = change[NSKeyValueChangeOldKey]?.CGRectValue() let newKeyboardFrame = change[NSKeyValueChangeNewKey]?.CGRectValue() if oldKeyboardFrame != nil && newKeyboardFrame != nil { if CGRectEqualToRect(newKeyboardFrame!, oldKeyboardFrame!) || CGRectIsNull(newKeyboardFrame!) { return } } else { return } let keyboardEndFrameConverted = self.contextView.convertRect(newKeyboardFrame!, toView: self.keyboardView!.superview) self.sChatNotifyKeyboardFrameNotificationForFrame(keyboardEndFrameConverted) } } else { //observeValueForKeyPath(keyPath, ofObject: ofObject, change: change, context: context) } } func sChatRemoveKeyboardFrameObserver() { if !isObserving { return } do { try keyboardView?.removeObserver(self, forKeyPath: NSStringFromSelector(Selector("frame")), context:kSChatKeyboardControllerKeyValueObservingContext) } catch { } isObserving = false } // MARK: Pan Gesture Recognizer func sChatHandlePanGestureRecognizer(pan: UIPanGestureRecognizer) { let touch = pan.locationInView(self.contextView.window) let contextViewWindowHeight = CGRectGetHeight((self.contextView.window?.frame)!) let keyboardViewHeight = CGRectGetHeight((self.keyboardView?.frame)!) let dragThresholdY = contextViewWindowHeight - keyboardViewHeight - (self.keyboardTriggerPoint?.y)! var newKeyboardViewFrame = self.keyboardView?.frame let userIsDraggingNearThresholdForDismissing = touch.y > dragThresholdY self.keyboardView?.userInteractionEnabled = !userIsDraggingNearThresholdForDismissing switch (pan.state) { case .Changed: newKeyboardViewFrame!.origin.y = touch.y + self.keyboardTriggerPoint!.y; // bound frame between bottom of view and height of keyboard newKeyboardViewFrame!.origin.y = min(newKeyboardViewFrame!.origin.y, contextViewWindowHeight) newKeyboardViewFrame!.origin.y = max(newKeyboardViewFrame!.origin.y, contextViewWindowHeight - keyboardViewHeight) if (CGRectGetMinY(newKeyboardViewFrame!) == CGRectGetMinY(self.keyboardView!.frame)) { return; } UIView.animateWithDuration(NSTimeInterval(0.0), delay: NSTimeInterval(0.0), options: [UIViewAnimationOptions.BeginFromCurrentState, UIViewAnimationOptions.TransitionNone], animations: { self.keyboardView?.frame = newKeyboardViewFrame! }, completion: nil) case .Ended, .Cancelled, .Failed: let keyboardViewIsHidden = (CGRectGetMinY(self.keyboardView!.frame) >= contextViewWindowHeight); if (keyboardViewIsHidden) { self.sChatResetKeyboardAndTextView() return } let velocity = pan.velocityInView(self.contextView) let userIsScrollingDown = (velocity.y > 0.0) let shouldHide = (userIsScrollingDown && userIsDraggingNearThresholdForDismissing) newKeyboardViewFrame?.origin.y = shouldHide ? contextViewWindowHeight : (contextViewWindowHeight - keyboardViewHeight); UIView.animateWithDuration(NSTimeInterval(0.25), delay: NSTimeInterval(0.0), options: [UIViewAnimationOptions.BeginFromCurrentState, UIViewAnimationOptions.CurveEaseOut], animations: { self.keyboardView?.frame = newKeyboardViewFrame! }, completion: { finished in self.keyboardView?.userInteractionEnabled = !shouldHide if shouldHide { self.sChatResetKeyboardAndTextView() } }) default: break; } } }
gpl-3.0
d129fd4bda9e1200e1dc8d4a1e65e23d
36.867435
173
0.575843
7.215266
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_subclass_arg.swift
1
16195
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK-DAG: @"$s4main9Ancestor1[[UNIQUE_ID_1:[0-9a-zA-Z_]+]]CySiGMf" = // CHECK-DAG: @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMf" = // CHECK: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" = linkonce_odr hidden // CHECK-unknown-SAME: constant // CHECK-apple-SAME: global // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: )*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %TSi*, // CHECK-SAME: %swift.type* // CHECK-SAME: )*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME: }> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CySSGMM // CHECK-unknown-SAME: [[INT]] 0, // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* // : )*, // : i8**, // : [[INT]], // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : void ( // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* // : )*, // : %swift.type*, // : [[INT]], // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* ( // : %swift.opaque*, // : %swift.type* // : )*, // : %swift.type*, // : [[INT]] // : }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMf" to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ), // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_2:[0-9A-Za-z_]+]]5Value to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(48|28)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(160|92)}}, // CHECK-unknown-SAME: i32 136, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : %swift.method_override_descriptor // : }>* @"$s4main5Value[[UNIQUE_ID_1]]CMn" to %swift.type_descriptor* // : ), // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfE // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %TSi*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGSi_tcfCAA9Ancestor2ACLLCAeHyxGx_tcfCTV // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: [[INT]] {{(24|12)}}, // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: [[INT]] {{(32|16)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGx_tcfC // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] fileprivate class Ancestor2<First> { let first_Ancestor2: First init(first: First) { self.first_Ancestor2 = first } } fileprivate class Ancestor1<First> : Ancestor2<First> { let first_Ancestor1: First override init(first: First) { self.first_Ancestor1 = first super.init(first: first) } } fileprivate class Value<First> : Ancestor1<Int> { let first_Value: First init(first: First) { self.first_Value = first super.init(first: 13) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] 0) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( Value(first: "13") ) } doit() // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]] // CHECK: [[TYPE_COMPARISON_LABEL]]: // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast ( // CHECK-SAME: @"$sSiN" // CHECK-SAME: ), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_3:[0-9A-Z_]+]]CySiGMb"([[INT]] [[METADATA_REQUEST]]) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0 // CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1 // CHECK: ret %swift.metadata_response [[RESULT_METADATA]] // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] [[METADATA_REQUEST]], // CHECK-SAME: i8* [[ERASED_TYPE]], // CHECK-SAME: i8* undef, // CHECK-SAME: i8* undef, // : %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>* // CHECK-SAME: $s4main9Ancestor2[[UNIQUE_ID_1]]CMn // : to %swift.type_descriptor* // : ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]] // CHECK: [[TYPE_COMPARISON_LABEL]]: // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast ( // CHECK-SAME: @"$sSiN" // CHECK-SAME: ), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_3:[0-9A-Z_]+]]CySiGMb"([[INT]] [[METADATA_REQUEST]]) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0 // CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1 // CHECK: ret %swift.metadata_response [[RESULT_METADATA]] // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] [[METADATA_REQUEST]], // CHECK-SAME: i8* [[ERASED_TYPE]], // CHECK-SAME: i8* undef, // CHECK-SAME: i8* undef, // : %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor, i32, %swift.method_override_descriptor }>* // CHECK-SAME: $s4main9Ancestor1[[UNIQUE_ID_1]]CMn // : to %swift.type_descriptor* // : ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]] // CHECK: [[TYPE_COMPARISON_LABEL]]: // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast ( // CHECK-SAME: @"$sSSN" // CHECK-SAME: ), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_3:[0-9A-Z_]+]]CySSGMb"([[INT]] [[METADATA_REQUEST]]) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0 // CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1 // CHECK: ret %swift.metadata_response [[RESULT_METADATA]] // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] [[METADATA_REQUEST]], // CHECK-SAME: i8* [[ERASED_TYPE]], // CHECK-SAME: i8* undef, // CHECK-SAME: i8* undef, // : %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, %swift.method_override_descriptor }>* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CMn // : to %swift.type_descriptor* // : ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} { // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) // CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) // CHECK-unknown: ret // CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self( // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" // CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type* // CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0 // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] {{%[0-9]+}}) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] {{%[0-9]+}})
apache-2.0
7720dde5bc53aebb6f8c47f42e52dceb
47.488024
214
0.495215
3.15569
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Interface/UITableView/SectionHeaderView.swift
1
3143
// // SectionHeaderView.swift // ScoreReporter // // Created by Bradley Smith on 9/24/16. // Copyright © 2016 Brad Smith. All rights reserved. // import UIKit import Anchorage @objc public protocol SectionHeaderViewDelegate: class { @objc optional func didSelectActionButton(in headerView: SectionHeaderView) } public class SectionHeaderView: UITableViewHeaderFooterView { fileprivate let titleLabel = UILabel(frame: .zero) fileprivate let actionButton = UIButton(type: .system) fileprivate var actionButtonWidth: NSLayoutConstraint? public class var height: CGFloat { let fontHeight = UIFont.systemFont(ofSize: 28.0, weight: UIFontWeightBlack).lineHeight return fontHeight + 16.0 } public weak var delegate: SectionHeaderViewDelegate? public override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = UIColor.white backgroundView = UIView(frame: .zero) configureViews() configureLayout() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Public public extension SectionHeaderView { func configure(with title: String?, actionButtonTitle: String? = nil) { titleLabel.text = title actionButton.setTitle(actionButtonTitle, for: .normal) actionButtonWidth?.isActive = actionButtonTitle == nil } } // MARK: - Private private extension SectionHeaderView { func configureViews() { titleLabel.font = UIFont.systemFont(ofSize: 28.0, weight: UIFontWeightBlack) titleLabel.adjustsFontSizeToFitWidth = true titleLabel.minimumScaleFactor = 0.5 titleLabel.textColor = UIColor.black contentView.addSubview(titleLabel) actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0, weight: UIFontWeightBlack) actionButton.setTitleColor(UIColor.scRed, for: .normal) actionButton.titleEdgeInsets.top = 23.0 actionButton.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 16.0, bottom: 0.0, right: 16.0) actionButton.addTarget(self, action: #selector(actionButtonTapped), for: .touchUpInside) actionButton.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) actionButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) contentView.addSubview(actionButton) } func configureLayout() { titleLabel.topAnchor == contentView.topAnchor + 16.0 titleLabel.bottomAnchor == contentView.bottomAnchor titleLabel.leadingAnchor == contentView.leadingAnchor + 16.0 actionButton.topAnchor == contentView.topAnchor actionButton.leadingAnchor == titleLabel.trailingAnchor + 16.0 actionButton.trailingAnchor == contentView.trailingAnchor actionButton.bottomAnchor == contentView.bottomAnchor actionButtonWidth = actionButton.widthAnchor == 0.0 } @objc func actionButtonTapped() { delegate?.didSelectActionButton?(in: self) } }
mit
7261676e80530e9cccf70d94dd018b09
33.911111
104
0.714831
5.236667
false
true
false
false
scottsievert/swix
swix/swix/swix/vector/initing.swift
2
3073
// // initing.swift // swix // // Created by Scott Sievert on 7/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate import Swift // SLOW PARTS: array(doubles), read_csv, write_csv. not a huge deal -- hopefully not used in final code func zeros(_ N: Int) -> vector{ // N zeros return vector(n: N) } func zeros_like(_ x: vector) -> vector{ // make an array like the other array return zeros(x.n) } func ones_like(_ x: vector) -> vector{ // make an array like the other array return zeros_like(x) + 1 } func ones(_ N: Int) -> vector{ // N ones return vector(n: N)+1 } func arange(_ max: Double, x exclusive:Bool = true) -> vector{ // 0..<max return arange(0, max: max, x:exclusive) } func arange(_ max: Int, x exclusive:Bool = true) -> vector{ // 0..<max return arange(0, max: max.double, x:exclusive) } func range(_ min:Double, max:Double, step:Double) -> vector{ // min, min+step, min+2*step..., max-step, max return linspace(min, max: max, num:1+((max-min)/step).int) } func arange(_ min: Double, max: Double, x exclusive: Bool = true) -> vector{ // min...max var pad = 0 if !exclusive {pad = 1} let N = max.int - min.int + pad let x = zeros(N) var o = CDouble(min) var l = CDouble(1) vDSP_vrampD(&o, &l, !x, 1.stride, N.length) return x } func linspace(_ min: Double, max: Double, num: Int=50) -> vector{ // 0...1 let x = zeros(num+0) var min = CDouble(min) var step = CDouble((max-min).double/(num-1).double) vDSP_vrampD(&min, &step, !x, 1.stride, x.n.length) return x } func array(_ numbers: Double...) -> vector{ // array(1, 2, 3, 4) -> arange(4)+1 // okay to leave unoptimized, only used for testing var x = zeros(numbers.count) var i = 0 for number in numbers{ x[i] = number i += 1 } return x } func asarray(_ x: [Double]) -> vector{ // convert a grid of double's to an array var y = zeros(x.count) y.grid = x return y } func asarray(_ seq: Range<Int>) -> vector { // make a range a grid of arrays // improve with [1] // [1]:https://gist.github.com/nubbel/d5a3639bea96ad568cf2 let start:Double = seq.lowerBound.double * 1.0 let end:Double = seq.upperBound.double * 1.0 return arange(start, max: end, x:true) } func copy(_ x: vector) -> vector{ // copy the value return x.copy() } func seed(_ n:Int){ SWIX_SEED = __CLPK_integer(n) } func rand(_ N: Int, distro:String="uniform") -> vector{ let x = zeros(N) var i:__CLPK_integer = 1 if distro=="normal" {i = __CLPK_integer(3)} var seed:Array<__CLPK_integer> = [SWIX_SEED, 2, 3, 5] var nn:__CLPK_integer = __CLPK_integer(N) dlarnv_(&i, &seed, &nn, !x) SWIX_SEED = seed[0] return x } func randn(_ N: Int, mean: Double=0, sigma: Double=1) -> vector{ return (rand(N, distro:"normal") * sigma) + mean; } func randperm(_ N:Int)->vector{ let x = arange(N) let y = shuffle(x) return y }
mit
b6dcb22bbe1b9b884e8a37981da40cfd
21.762963
103
0.592255
2.9893
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/UserDataManager.swift
1
9422
// // UserDataManager.swift // QiitaCollection // // Created by ANZ on 2015/02/21. // Copyright (c) 2015年 anz. All rights reserved. // import Foundation class UserDataManager { // シングルトンパターン class var sharedInstance : UserDataManager { struct Static { static let instance : UserDataManager = UserDataManager() } return Static.instance } // MARK: プロパティ let ud : NSUserDefaults = NSUserDefaults.standardUserDefaults() enum UDKeys: String { case MuteUsers = "ud-key-mute-users", Queries = "ud-key-queries", Pins = "ud-key-pins", EntryFiles = "ud-key-entry-files", DisplayedGuides = "ud-key-displayed-guide", QiitaAccessToken = "ud-key-qiita-access-token", QiitaAuthenticatedUserID = "ud-key-qiita-authenticated-user-id", GridCoverImage = "ud-key-grid-cover-image", ViewCoverImage = "ud-key-view-cover-image" } // ミュートユーザーのID var muteUsers: [String] = [String]() // 保存した検索クエリ var queries: [[String: String]] = [[String: String]]() // クリップしたもの var pins: [[String: String]] = [[String: String]]() // 保存したもの var entryFiles: [[String: String]] = [[String: String]]() // 表示したガイド var displayedGuides: [Int] = [Int]() // Qiita AccessToken var qiitaAccessToken: String = "" { didSet { if self.qiitaAccessToken.isEmpty { return } self.saveAuth() // 即時保存させる } } // Qiita AuthenticatedUser ID var qiitaAuthenticatedUserID: String = "" { didSet { if self.qiitaAuthenticatedUserID.isEmpty { return } self.saveAuth() // 即時保存させる } } var imageDataForGridCover: NSData? = nil var imageDataForViewCover: NSData? = nil // MARK: ライフサイクル init() { var defaults = [ UDKeys.MuteUsers.rawValue : self.muteUsers, UDKeys.Queries.rawValue : self.queries, UDKeys.Pins.rawValue : self.pins, UDKeys.EntryFiles.rawValue : self.entryFiles, UDKeys.DisplayedGuides.rawValue : self.displayedGuides, UDKeys.QiitaAccessToken.rawValue : self.qiitaAccessToken, UDKeys.QiitaAuthenticatedUserID.rawValue: self.qiitaAuthenticatedUserID ] self.ud.registerDefaults(defaults as [NSObject : AnyObject]) self.muteUsers = self.ud.arrayForKey(UDKeys.MuteUsers.rawValue) as! [String] self.queries = self.ud.arrayForKey(UDKeys.Queries.rawValue) as! [[String: String]] self.pins = self.ud.arrayForKey(UDKeys.Pins.rawValue) as! [[String: String]] self.entryFiles = self.ud.arrayForKey(UDKeys.EntryFiles.rawValue) as! [[String: String]] self.displayedGuides = self.ud.arrayForKey(UDKeys.DisplayedGuides.rawValue) as! [Int] self.qiitaAccessToken = self.ud.stringForKey(UDKeys.QiitaAccessToken.rawValue)! self.qiitaAuthenticatedUserID = self.ud.stringForKey(UDKeys.QiitaAuthenticatedUserID.rawValue)! self.imageDataForGridCover = self.ud.dataForKey(UDKeys.GridCoverImage.rawValue) self.imageDataForViewCover = self.ud.dataForKey(UDKeys.ViewCoverImage.rawValue) } // MARK: メソッド func saveAuth() { self.ud.setObject(self.qiitaAccessToken, forKey: UDKeys.QiitaAccessToken.rawValue) self.ud.setObject(self.qiitaAuthenticatedUserID, forKey: UDKeys.QiitaAuthenticatedUserID.rawValue) self.ud.synchronize() } func saveAll() { // プロパティで保持していたのをudへ書き込む self.ud.setObject(self.muteUsers, forKey: UDKeys.MuteUsers.rawValue) self.ud.setObject(self.queries, forKey: UDKeys.Queries.rawValue) self.ud.setObject(self.pins, forKey: UDKeys.Pins.rawValue) self.ud.setObject(self.entryFiles, forKey: UDKeys.EntryFiles.rawValue) self.ud.setObject(self.displayedGuides, forKey: UDKeys.DisplayedGuides.rawValue) self.ud.setObject(self.qiitaAccessToken, forKey: UDKeys.QiitaAccessToken.rawValue) self.ud.setObject(self.qiitaAuthenticatedUserID, forKey: UDKeys.QiitaAuthenticatedUserID.rawValue) self.ud.setObject(self.imageDataForGridCover, forKey: UDKeys.GridCoverImage.rawValue) self.ud.setObject(self.imageDataForViewCover, forKey: UDKeys.ViewCoverImage.rawValue) self.ud.synchronize() } func appendMuteUserId(userId: String) -> Bool { if self.isMutedUser(userId) { return false } self.muteUsers.append(userId) return true } func isMutedUser(userId: String) -> Bool { return contains(self.muteUsers, userId) } func clearMutedUser(userId: String) -> [String] { if !isMutedUser(userId) { return self.muteUsers } self.muteUsers.removeObject(userId) return self.muteUsers } func appendQuery(query: String, label: String) { let index = self.indexItem(self.queries, target: query, id: "query") if index != NSNotFound { return } self.queries.append([ "query": query, "title": label ]) } func clearQuery(query: String) { let index = self.indexItem(self.queries, target: query, id: "query") if index == NSNotFound { return } self.queries.removeAtIndex(index) } func clearQuery(index: Int) { if index >= self.queries.count { return } self.queries.removeAtIndex(index) } func appendPinEntry(entryId: String, entryTitle: String) { if self.pins.count >= 10 { self.pins.removeAtIndex(0) } else if self.hasPinEntry(entryId) != NSNotFound { // 重複ID return } self.pins.append([ "id" : entryId, "title": entryTitle ]) } func hasPinEntry(entryId: String) -> Int { return self.indexItem(self.pins, target: entryId) } func clearPinEntry(index: Int) -> [[String: String]] { self.pins.removeAtIndex(index) return self.pins } func clearPinEntry(entryId: String) -> [[String: String]] { let index: Int = self.hasPinEntry(entryId) if index == NSNotFound { return self.pins } self.pins.removeAtIndex(index) return self.pins } func titleSavedEntry(entryId: String) -> String { let index: Int = self.indexItem(self.entryFiles, target: entryId) if index == NSNotFound { return "" } let item: [String: String] = self.entryFiles[index] return item["title"]! } func hasSavedEntry(entryId: String) -> Bool { return self.indexItem(self.entryFiles, target: entryId) != NSNotFound } func appendSavedEntry(entryId: String, title:String) { if self.hasSavedEntry(entryId) { return } self.entryFiles.append([ "id" : entryId, "title" : title ]) } func removeEntry(entryId: String) { let index = self.indexItem(self.entryFiles, target: entryId) self.entryFiles.removeAtIndex(index) } func isDisplayedGuide(guide: Int) -> Bool { return contains(self.displayedGuides, guide) } func appendDisplayedGuide(guide: Int) { if self.isDisplayedGuide(guide) { return } self.displayedGuides.append(guide) } func indexItem(items: [[String: String]], target:String, id: String = "id") -> Int { for var i = 0; i < items.count; i++ { let item = items[i] if item[id] == target { return i } } return NSNotFound } func setQiitaAccessToken(token: String) { self.qiitaAccessToken = token } func clearQiitaAccessToken() { self.qiitaAccessToken = "" } func isAuthorizedQiita() -> Bool { return !self.qiitaAccessToken.isEmpty } func setImageForGridCover(image: UIImage) { self.imageDataForGridCover = UIImagePNGRepresentation(image) self.imageDataForViewCover = nil } func setImageForViewCover(image: UIImage) { self.imageDataForViewCover = UIImagePNGRepresentation(image) self.imageDataForGridCover = nil } func clearImageCover() { self.imageDataForViewCover = nil self.imageDataForGridCover = nil } func hasImageForGridCover() -> Bool { return self.imageDataForGridCover != nil } func hasImageForViewCover() -> Bool { return self.imageDataForViewCover != nil } func imageForGridCover() -> UIImage? { return UIImage(data: self.imageDataForGridCover!) } func imageForViewCover() -> UIImage? { return UIImage(data: self.imageDataForViewCover!) } }
mit
e294c5aa0ced927d6e59e2229f3a0e5d
31.350877
106
0.599024
4.528487
false
false
false
false
solszl/Shrimp500px
Shrimp500px/Extension/UIColor+500px.swift
1
1086
// // UIColor+500px.swift // Shrimp500px // // Created by 振亮 孙 on 16/2/18. // Copyright © 2016年 papa.studio. All rights reserved. // import Foundation import UIKit extension UIColor { class func colorWithHex(hex :UInt, alpha: CGFloat = 1.0) -> UIColor { let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let g = CGFloat((hex & 0x00FF00) >> 8) / 255.0 let b = CGFloat((hex * 0x0000FF) >> 0) / 255.0 return UIColor(red: r, green: g, blue: b, alpha: alpha) } class func fromRGBAInteger(red red: Int, green: Int, blue: Int, alpha: Int = 100) -> UIColor { let r = CGFloat(red) / 255.0 let g = CGFloat(green) / 255.0 let b = CGFloat(blue) / 255.0 let a = CGFloat(alpha) / 100.0 return UIColor(red: r, green: g, blue: b, alpha: a) } class func randomColor() -> UIColor { let r = Int(arc4random() % 255) let g = Int(arc4random() % 255) let b = Int(arc4random() % 255) return UIColor.fromRGBAInteger(red: r, green: g, blue: b) } }
mit
0b62fa94d74dc25a8e228fff580f6c71
28.944444
98
0.563603
3.176991
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Internal/Features/DeepLink.swift
1
3833
import UIKit class DeepLink: NSObject { private let sharedDefaults = UserDefaults.standardDefaults.child(namespace: "webtrekk") static let savedDeepLinkMediaCode = "mediaCodeForDeepLink" // add wt_application to delegation class in runtime and switch implementation with application func @nonobjc func deepLinkInit() { let replacedSel = #selector(wt_application(_:continue:restorationHandler:)) let originalSel = #selector(UIApplicationDelegate.application(_:continue:restorationHandler:)) // get class of delegate instance guard let delegate = UIApplication.shared.delegate, let delegateClass = object_getClass(delegate) else { return } if !replaceImplementationFromAnotherClass(toClass: delegateClass, methodChanged: originalSel, fromClass: DeepLink.self, methodAdded: replacedSel) { logError("Deep link functionality initialization error.") } } // method that replaces application in delegate @objc dynamic func wt_application( _ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool { // test if this is deep link if userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL, let components = URLComponents(url: url, resolvingAgainstBaseURL: true), let queryItems = components.queryItems { WebtrekkTracking.defaultLogger.logDebug("Deep link is received") // as this implementation is added to another class with swizzle we can't use local parameters let track = WebtrekkTracking.instance() //loop for all parameters for queryItem in queryItems { //if parameter is everID set it if queryItem.name == "wt_everID" { if let value = queryItem.value { // check if ever id has correct format 19 digits. if let isMatched = value.isMatchForRegularExpression("\\d{19}"), isMatched { track.everId = value WebtrekkTracking.defaultLogger.logDebug("Ever id from Deep link is set") } else { WebtrekkTracking.defaultLogger.logError("Incorrect everid: \(queryItem.value.simpleDescription)") } } else { WebtrekkTracking.defaultLogger.logError("Everid is empty in request") } } //if parameter is media code set it if queryItem.name == "wt_mediaCode", let value = queryItem.value { track.mediaCode = value WebtrekkTracking.defaultLogger.logDebug("Media code from Deep link is set") } } } if class_respondsToSelector(object_getClass(self), #selector(wt_application(_:continue:restorationHandler:))) { return self.wt_application(application, continue: userActivity, restorationHandler: restorationHandler) } else { return true } } // returns media code and delete it from settings func getAndDeletSavedDeepLinkMediaCode() -> String? { let mediaCode = self.sharedDefaults.stringForKey(DeepLink.savedDeepLinkMediaCode) if let _ = mediaCode { self.sharedDefaults.remove(key: DeepLink.savedDeepLinkMediaCode) } return mediaCode } //save media code to settings func setMediaCode(_ mediaCode: String) { self.sharedDefaults.set(key: DeepLink.savedDeepLinkMediaCode, to: mediaCode) } }
mit
96d3084f19c113ebe75c7c2841b9c06e
42.067416
155
0.615706
5.755255
false
false
false
false
HwwDaDa/WeiBo_swift
WeiBo/WeiBo/Classes/View/Main/HWBBaseViewController.swift
1
4162
// // HWBBaseViewController.swift // WeiBo // // Created by Admin on 2017/6/15. // Copyright © 2017年 Admin. All rights reserved. // import UIKit //OC重支持多继承码,不支持,答案是使用协议替代 //swift的这种方法类似于多继承,这就是不同于OC的地方 class HWBBaseViewController: UIViewController { var visitorInfoDictionary: [String: String]? // MARK: 用户登录标记 var userLogon = false // 表格视图,因此不能用懒加载 var tableView: UITableView? // 可选的刷新空间 var refreshControl: UIRefreshControl? // 上拉刷新标记 var isPullup = false lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64)) lazy var navItem = UINavigationItem() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } override var title: String?{ didSet{ navItem.title = title } } // 加载数据,具体的实现子类实现就可以了 func loadData() { refreshControl?.endRefreshing() } } // MARK: - 设置UI的东西 extension HWBBaseViewController{ func setupUI(){ view.backgroundColor = UIColor.white // 取消自动缩进 - 如果隐藏了导航栏会缩进20个点 automaticallyAdjustsScrollViewInsets = false setupNavigationBar() // 用户是否登录判断 userLogon ? setupTableView() : setupVisitorView() } // MARK: 设置访客视图 private func setupVisitorView(){ let visitorView = WBVisitorView(frame: view.bounds) view.insertSubview(visitorView, belowSubview: navigationBar) visitorView.visitorInfo = visitorInfoDictionary } // 设置表格视图 private func setupTableView(){ tableView = UITableView(frame: view.bounds, style: .plain) // view.addSubview(tableView!) view.insertSubview(tableView!, belowSubview: navigationBar) // 设置数据源和代码方法 ->让自类直接实现数据源方法 tableView?.delegate = self tableView?.dataSource = self tableView?.contentInset = UIEdgeInsetsMake(navigationBar.bounds.height, 0, tabBarController?.tabBar.bounds.height ?? 49, 0) // 设置刷新空间 // ->实例化空间 refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) // 添加到视图 tableView?.addSubview(refreshControl!) } private func setupNavigationBar(){ //添加导航条 view.addSubview(navigationBar) navigationBar.items = [navItem] navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6) navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray] navigationBar.isTranslucent = false; } } //遵守协议 extension HWBBaseViewController:UITableViewDelegate,UITableViewDataSource{ //基类准备方法,子类不需要继承,重写方法就可以了 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // 在现实最后的一行的时候做上啦刷新,先判断是否是最后一行 let row = indexPath.row let section = tableView.numberOfSections - 1 // 判断 if row < 0 || section < 0 { return } let count = tableView.numberOfRows(inSection: section) if row == count - 1 && !isPullup { print("上拉刷新") isPullup = true // 开始刷新 loadData() } } }
mit
67c8120f069e285d9d2a9111764da7aa
25.049645
131
0.617751
4.649367
false
false
false
false
larryhou/swift
LocationTraker/LocationTraker/ChinaGPS.swift
1
4222
// // ChinaGPS.swift // LocationTraker // // Created by larryhou on 28/7/2015. // Copyright © 2015 larryhou. All rights reserved. // import Foundation import CoreLocation class ChinaGPS { struct GPSLocation { var lon, lat: Double } static private let pi = 3.14159265358979324 static private let x_pi = pi * 3000.0 / 180.0 // // Krasovsky 1940 // // a = 6378245.0, 1/f = 298.3 // b = a * (1 - f) // ee = (a^2 - b^2) / a^2; static private let a = 6378245.0 static private let ee = 0.00669342162296594323 private class func encrypt_lat(x: Double, y: Double) -> Double { var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y ret += 0.2 * sqrt(abs(x)) ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0 ret += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0 ret += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0 return ret } private class func encrypt_lon(x: Double, y: Double) -> Double { var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y ret += 0.1 * sqrt(abs(x)) ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0 ret += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0 ret += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0 return ret } private class func outOfChina(lat: Double, lon: Double) -> Bool { if lon < 72.004 || lon > 137.8347 { return true } if lat < 0.8293 || lat > 55.8271 { return true } return false } /// /// WGS-84 到 GCJ-02 的转换 /// class func encrypt_WGS_2_GCJ(loc: GPSLocation) -> GPSLocation { if outOfChina(loc.lat, lon: loc.lon) { return loc } var lat = encrypt_lat(loc.lon - 105.0, y: loc.lat - 35.0) var lon = encrypt_lon(loc.lon - 105.0, y: loc.lat - 35.0) let radian = loc.lat / 180.0 * pi let magic = 1 - ee * sin(radian) * sin(radian) let magic_2 = sqrt(magic) lat = (lat * 180.0) / ((a * (1 - ee)) / (magic * magic_2) * pi) lon = (lon * 180.0) / (a / magic_2 * cos(radian) * pi) return GPSLocation(lon: loc.lon + lon, lat: loc.lat + lat) } class func encrypt_WGS_2_GCJ(latitude latitude: Double, longitude: Double) -> CLLocation { let loc = GPSLocation(lon: longitude, lat: latitude) let ret = encrypt_WGS_2_GCJ(loc) return CLLocation(latitude: ret.lat, longitude: ret.lon) } class func encrypt_WGS_2_GCJ(latitude latitude: Double, longitude: Double) -> CLLocationCoordinate2D { let loc = GPSLocation(lon: longitude, lat: latitude) let ret = encrypt_WGS_2_GCJ(loc) return CLLocationCoordinate2D(latitude: ret.lat, longitude: ret.lon) } /// /// GCJ-02 坐标转换成 BD-09 坐标 /// class func baidu_encrypt(loc: GPSLocation) -> GPSLocation { let x = loc.lon, y = loc.lat let z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi) let theta = atan2(y, x) + 0.000003 * cos(x * x_pi) return GPSLocation(lon: z * cos(theta) + 0.0065, lat: z * sin(theta) + 0.006) } class func baidu_encrypt(latitude latitude: Double, longitude: Double) -> CLLocation { let loc = GPSLocation(lon: longitude, lat: latitude) let ret = baidu_encrypt(loc) return CLLocation(latitude: ret.lat, longitude: ret.lon) } /// /// BD-09 坐标转换成 GCJ-02坐标 /// class func baidu_decrypt(loc: GPSLocation) -> GPSLocation { let x = loc.lon - 0.0065, y = loc.lat - 0.006 let z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi) let theta = atan2(y, x) - 0.000003 * cos(x * x_pi) return GPSLocation(lon: z * cos(theta), lat: z * sin(theta)) } class func baidu_decrypt(latitude latitude: Double, longitude: Double) -> CLLocation { let loc = GPSLocation(lon: longitude, lat: latitude) let ret = baidu_decrypt(loc) return CLLocation(latitude: ret.lat, longitude: ret.lon) } }
mit
943fd40e984a901ca3ab91b14b19c228
31.695313
106
0.53644
3.052516
false
false
false
false
Qmerce/ios-sdk
Sources/Helpers/MessagesDispatcher.swift
1
1787
// // MessageDispatcher.swift // ApesterKit // // Created by Hasan Sa on 10/07/2019. // Copyright © 2019 Apester. All rights reserved. // import Foundation import WebKit // MARK:- MessageDispatcher class MessageDispatcher { private var messages: [Int: String] = [:] private func dispatch(message: String, to webView: WKWebView, completion: ((Any?) -> Void)? = nil) { webView.evaluateJavaScript(message) { (response, error) in completion?(response) } } func contains(message: String, for webView: WKWebView) -> Bool { return self.messages[webView.hash] == message } func dispatch(apesterEvent message: String, to webView: WKWebView, completion: ((Any?) -> Void)? = nil) { self.messages[webView.hash] = message self.dispatch(message: Constants.WebView.sendApesterEvent(with: message), to: webView, completion: completion) } func dispatchAsync(_ message: String, to webView: WKWebView, completion: ((Any?) -> Void)? = nil) { self.messages[webView.hash] = message self.dispatch(message: message, to: webView, completion: completion) } func dispatchSync(message: String, to webView: WKWebView, completion: ((Any?) -> Void)? = nil) { let script = SynchronizedScript() script.lock() self.dispatch(message: message, to: webView) { response in completion?(response) script.unlock() } script.wait() } func sendNativeAdEvent(to webView: WKWebView, _ event: String) { self.dispatch(apesterEvent: """ { type: \"native_ad_report\", nativeAdEvent: \"\(event)\" } """, to: webView); } }
mit
f805af73f197a060c759ae8914c1ec2c
29.271186
118
0.598544
4.324455
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Procedure.swift
2
27092
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // // swiftlint:disable file_length // swiftlint:disable type_body_length import Foundation internal struct ProcedureKit { fileprivate enum FinishingFrom { case main, cancel, finish } fileprivate enum State: Int, Comparable { static func < (lhs: State, rhs: State) -> Bool { return lhs.rawValue < rhs.rawValue } case initialized case pending case executing case finishing case finished func canTransition(to other: State, whenCancelled isCancelled: Bool) -> Bool { switch (self, other) { case (.initialized, .pending), (.pending, .executing), (.executing, .finishing), (.finishing, .finished): return true case (.initialized, .finishing) where isCancelled: // When an operation is cancelled before it is added to a queue it can go from pending direct to finishing. return true case (.pending, .finishing) where isCancelled: // When an operation is cancelled it can go from pending direct to finishing. return true default: return false } } } private init() { } } /** Type to express the intent of the user in regards to executing an Operation instance - see: https://developer.apple.com/library/ios/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html#//apple_ref/doc/uid/TP40015243-CH39 */ @objc public enum UserIntent: Int { case none = 0, sideEffect, initiated internal var qualityOfService: QualityOfService { switch self { case .initiated, .sideEffect: return .userInitiated default: return .default } } } open class Procedure: Operation, ProcedureProtocol { private var _isTransitioningToExecuting = false private var _isFinishingFrom: ProcedureKit.FinishingFrom? = nil private var _isHandlingCancel = false private var _isCancelled = false // should always be set by .cancel() private var _isHandlingFinish: Bool { return _isFinishingFrom != nil } fileprivate let isAutomaticFinishingDisabled: Bool private weak var queue: ProcedureQueue? /** Expresses the user intent in regards to the execution of this Procedure. Setting this property will set the appropriate quality of service parameter on the parent Operation. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. */ public var userIntent: UserIntent = .none { didSet { setQualityOfService(fromUserIntent: userIntent) } } internal let identifier = UUID() // MARK: State private var _state = ProcedureKit.State.initialized private let _stateLock = NSRecursiveLock() fileprivate var state: ProcedureKit.State { get { return _stateLock.withCriticalScope { _state } } set(newState) { _stateLock.withCriticalScope { log.verbose(message: "\(_state) -> \(newState)") assert(_state.canTransition(to: newState, whenCancelled: isCancelled), "Attempting to perform illegal cyclic state transition, \(_state) -> \(newState) for operation: \(identity). Ensure that Procedure instances are added to a ProcedureQueue not an OperationQueue.") _state = newState } } } /// Boolean indicator for whether the Procedure has been enqueue final public var isEnqueued: Bool { return state >= .pending } /// Boolean indicator for whether the Procedure is pending final public var isPending: Bool { return state == .pending } /// Boolean indicator for whether the Procedure is currently executing or not final public override var isExecuting: Bool { return state == .executing } /// Boolean indicator for whether the Procedure has finished or not final public override var isFinished: Bool { return state == .finished } /// Boolean indicator for whether the Operation has cancelled or not final public override var isCancelled: Bool { return _stateLock.withCriticalScope { _isCancelled } } // MARK: Protected Internal Properties fileprivate struct ProtectedProperties { var log: LoggerProtocol = Logger() var errors = [Error]() var observers = [AnyObserver<Procedure>]() var directDependencies = Set<Operation>() var conditions = Set<Condition>() } fileprivate let protectedProperties = Protector(ProtectedProperties()) // MARK: Errors public var errors: [Error] { return protectedProperties.read { $0.errors } } // MARK: Log /** Access the logger for this Operation The `log` property can be used as the interface to access the logger. e.g. to output a message with `LogSeverity.Info` from inside the `Procedure`, do this: ```swift log.info("This is my message") ``` To adjust the instance severity of the LoggerType for the `Procedure`, access it via this property too: ```swift log.severity = .Verbose ``` The logger is a very simple type, and all it does beyond manage the enabled status and severity is send the String to a block on a dedicated serial queue. Therefore to provide custom logging, set the `logger` property: ```swift log.logger = { message in sendMessageToAnalytics(message) } ``` By default, the Logger's logger block is the same as the global LogManager. Therefore to use a custom logger for all Operations: ```swift LogManager.logger = { message in sendMessageToAnalytics(message) } ``` */ public var log: LoggerProtocol { get { let operationName = self.operationName return protectedProperties.read { LoggerContext(parent: $0.log, operationName: operationName) } } set { protectedProperties.write { $0.log = newValue } } } // MARK: Observers var observers: [AnyObserver<Procedure>] { get { return protectedProperties.read { $0.observers } } } // MARK: Dependencies & Conditions internal var directDependencies: Set<Operation> { get { return protectedProperties.read { $0.directDependencies } } } internal fileprivate(set) var evaluateConditionsProcedure: EvaluateConditions? = nil internal var indirectDependencies: Set<Operation> { return Set(conditions .flatMap { $0.directDependencies } .filter { !directDependencies.contains($0) } ) } /// - returns conditions: the Set of Condition instances attached to the operation public var conditions: Set<Condition> { get { return protectedProperties.read { $0.conditions } } } // MARK: - Initialization public override init() { isAutomaticFinishingDisabled = false super.init() name = String(describing: type(of: self)) } // MARK: - Disable Automatic Finishing /** Ability to override Operation's built-in finishing behavior, if a subclass requires full control over when finish() is called. Used for GroupOperation to implement proper .Finished state-handling (only finishing after all child operations have finished). The default behavior of Operation is to automatically call finish() when: (a) it's cancelled, whether that occurs: - prior to the Operation starting (in which case, Operation will skip calling execute()) - on another thread at the same time that the operation is executing (b) when willExecuteObservers log errors To ensure that an Operation subclass does not finish until the subclass calls finish(): call `super.init(disableAutomaticFinishing: true)` in the init. IMPORTANT: If disableAutomaticFinishing == TRUE, the subclass is responsible for calling finish() in *ALL* cases, including when the operation is cancelled. You can react to cancellation using WillCancelObserver/DidCancelObserver and/or checking periodically during execute with something like: ```swift guard !cancelled else { // do any necessary clean-up finish() // always call finish if automatic finishing is disabled return } ``` */ public init(disableAutomaticFinishing: Bool) { isAutomaticFinishingDisabled = disableAutomaticFinishing super.init() name = String(describing: type(of: self)) } // MARK: - Execution private var shouldEnqueue: Bool { return _stateLock.withCriticalScope { // Do not cancel if already finished or finishing, or cancelled guard state < .pending && !_isCancelled else { return false } return true } } public func willEnqueue(on queue: ProcedureQueue) { state = .pending self.queue = queue } /// Starts the operation, correctly managing the cancelled state. Cannot be over-ridden public final override func start() { // Don't call super.start // Replicate NSOperation.start() autorelease behavior // (Push an autoreleasepool before calling main(), pop after main() returns) autoreleasepool { guard !isCancelled || isAutomaticFinishingDisabled else { finish() return } main() } } /// Triggers execution of the operation's task, correctly managing errors and the cancelled state. Cannot be over-ridden public final override func main() { // Prevent concurrent execution func getNextState() -> ProcedureKit.State? { return _stateLock.withCriticalScope { // Check to see if the procedure is already attempting to execute assert(!isExecuting, "Procedure is attempting to execute, but is already executing.") guard !_isTransitioningToExecuting else { assertionFailure("Procedure is attempting to execute twice, concurrently.") return nil } // Check to see if the procedure has now been finished // by an observer (or anything else) guard state <= .pending else { return nil } // Check to see if the procedure has now been cancelled // by an observer guard (errors.isEmpty && !isCancelled) || isAutomaticFinishingDisabled else { _isFinishingFrom = .main return .finishing } // Transition to the .isExecuting state, and explicitly send the required KVO change notifications _isTransitioningToExecuting = true return .executing } } // Check the state again, as it could have changed in another queue via finish func getNextStateAgain() -> ProcedureKit.State? { return _stateLock.withCriticalScope { guard state <= .pending else { return nil } state = .executing _isTransitioningToExecuting = false if isCancelled && !isAutomaticFinishingDisabled && !_isHandlingFinish { // Procedure was cancelled, automatic finishing is enabled, // but cancel is not (yet/ever?) handling the finish. // Because cancel could have already passed the check for executing, // handle calling finish here. _isFinishingFrom = .main return .finishing } return .executing } } observers.forEach { $0.will(execute: self) } let nextState = getNextState() guard nextState != .finishing else { _finish(withErrors: [], from: .main) return } guard nextState == .executing else { return } willChangeValue(forKey: .executing) let nextState2 = getNextStateAgain() didChangeValue(forKey: .executing) guard nextState2 != .finishing else { _finish(withErrors: [], from: .main) return } guard nextState2 == .executing else { return } log.notice(message: "Will Execute") execute() observers.forEach { $0.did(execute: self) } log.notice(message: "Did Execute") } open func execute() { print("\(self) must override `execute()`.") finish() } public final func produce(operation: Operation) throws { precondition(state > .initialized, "Cannot add operation which is not being scheduled on a queue") guard let queue = queue else { throw ProcedureKitError.noQueue() } queue.delegate?.procedureQueue(queue, willProduceOperation: operation) log.notice(message: "Will add \(operation.operationName)") observers.forEach { $0.procedure(self, willAdd: operation) } queue.add(operation: operation) observers.forEach { $0.procedure(self, didAdd: operation) } } internal func queue(_ queue: ProcedureQueue, didAddOperation operation: Operation) { log.notice(message: "Did add \(operation.operationName)") observers.forEach { $0.procedure(self, didAdd: operation) } } // MARK: - Cancellation open func procedureWillCancel(withErrors: [Error]) { } open func procedureDidCancel(withErrors: [Error]) { } public func cancel(withErrors errors: [Error]) { _cancel(withAdditionalErrors: errors) } public final override func cancel() { _cancel(withAdditionalErrors: []) } private var shouldCancel: Bool { return _stateLock.withCriticalScope { // Do not cancel if already finished or finishing, or cancelled guard state <= .executing && !_isCancelled else { return false } // Only a single call to cancel should continue guard !_isHandlingCancel else { return false } _isHandlingCancel = true return true } } private var shouldFinishFromCancel: Bool { return _stateLock.withCriticalScope { let shouldFinish = isExecuting && !isAutomaticFinishingDisabled && !_isHandlingFinish if shouldFinish { _isFinishingFrom = .cancel } return shouldFinish } } private final func _cancel(withAdditionalErrors additionalErrors: [Error]) { guard shouldCancel else { return } let resultingErrors = errors + additionalErrors procedureWillCancel(withErrors: resultingErrors) willChangeValue(forKey: .cancelled) observers.forEach { $0.will(cancel: self, withErrors: resultingErrors) } _stateLock.withCriticalScope { if !additionalErrors.isEmpty { protectedProperties.write { $0.errors.append(contentsOf: additionalErrors) } } _isCancelled = true } procedureDidCancel(withErrors: resultingErrors) observers.forEach { $0.did(cancel: self, withErrors: resultingErrors) } let messageSuffix = !additionalErrors.isEmpty ? "errors: \(additionalErrors)" : "no errors" log.notice(message: "Will cancel with \(messageSuffix).") didChangeValue(forKey: .cancelled) // Call super to trigger .isReady state change on cancel // as well as isReady KVO notification super.cancel() guard shouldFinishFromCancel else { return } _finish(withErrors: [], from: .cancel) } // MARK: - Finishing open func procedureWillFinish(withErrors: [Error]) { } open func procedureDidFinish(withErrors: [Error]) { } /** Finish method which must be called eventually after an operation has begun executing, unless it is cancelled. - parameter errors: an array of `Error`, which defaults to empty. */ public final func finish(withErrors errors: [Error] = []) { _finish(withErrors: errors, from: .finish) } private func shouldFinish(from source: ProcedureKit.FinishingFrom) -> Bool { return _stateLock.withCriticalScope { // Do not finish is already finishing or finished guard state <= .finishing else { return false } // Only a single call to _finish should continue guard !_isHandlingFinish // cancel() and main() ensure one-time execution // thus, cancel() and main() set _isFinishingFrom prior to calling _finish() // but finish() does not; _isFinishingFrom is set below when finish() calls _finish() // this could be simplified to a check for (_isFinishFrom == source) if finish() // ensured that it could only call _finish() once // (although that would require another aquisition of the lock) || (_isFinishingFrom == source && (source == .cancel || source == .main)) else { return false } _isFinishingFrom = source return true } } private final func _finish(withErrors receivedErrors: [Error], from source: ProcedureKit.FinishingFrom) { guard shouldFinish(from: source) else { return } // NOTE: // - The stateLock should only be held when necessary, and should not // be held when notifying observers (whether via KVO or Operation's // observers) or deadlock can result. let changedExecutingState = isExecuting if changedExecutingState { willChangeValue(forKey: .executing) } _stateLock.withCriticalScope { state = .finishing } if changedExecutingState { didChangeValue(forKey: .executing) } let resultingErrors: [Error] = protectedProperties.write { if !receivedErrors.isEmpty { $0.errors.append(contentsOf: receivedErrors) } return $0.errors } let messageSuffix = !resultingErrors.isEmpty ? "errors: \(resultingErrors)" : "no errors" log.notice(message: "Will finish with \(messageSuffix).") procedureWillFinish(withErrors: resultingErrors) willChangeValue(forKey: .finished) observers.forEach { $0.will(finish: self, withErrors: resultingErrors) } _stateLock.withCriticalScope { state = .finished } procedureDidFinish(withErrors: resultingErrors) observers.forEach { $0.did(finish: self, withErrors: resultingErrors) } log.notice(message: "Did finish with \(messageSuffix).") didChangeValue(forKey: .finished) } // MARK: - Observers /** Add an observer to the procedure. - parameter observer: type conforming to protocol `ProcedureObserver`. */ open func add<Observer: ProcedureObserver>(observer: Observer) where Observer.Procedure == Procedure { protectedProperties.write { $0.observers.append(AnyObserver(base: observer)) } observer.didAttach(to: self) } } // MARK: Dependencies public extension Procedure { public func add<Dependency: ProcedureProtocol>(dependency: Dependency) { guard let op = dependency as? Operation else { assertionFailure("Adding dependencies which do not subclass Foundation.Operation is not supported.") return } add(dependency: op) } } // MARK: Conditions extension Procedure { class EvaluateConditions: GroupProcedure, InputProcedure, OutputProcedure { var input: Pending<[Condition]> = .pending var output: Pending<ConditionResult> = .pending init(conditions: Set<Condition>) { let ops = Array(conditions) input = .ready(ops) super.init(operations: ops) } override func procedureWillFinish(withErrors errors: [Error]) { output = .ready(process(withErrors: errors)) } override func procedureWillCancel(withErrors errors: [Error]) { output = .ready(process(withErrors: errors)) } private func process(withErrors errors: [Error]) -> ConditionResult { guard errors.isEmpty else { return .failure(ProcedureKitError.FailedConditions(errors: errors)) } guard let conditions = input.value else { fatalError("Conditions must be set before the evaluation is performed.") } return conditions.reduce(.success(false)) { lhs, condition in // Unwrap the condition's output guard let rhs = condition.output.value else { return lhs } log.verbose(message: "evaluating \(lhs) with \(rhs)") switch (lhs, rhs) { // both results are failures case let (.failure(error), .failure(anotherError)): if let error = error as? ProcedureKitError.FailedConditions { return .failure(error.append(error: anotherError)) } else if let anotherError = anotherError as? ProcedureKitError.FailedConditions { return .failure(anotherError.append(error: error)) } else { return .failure(ProcedureKitError.FailedConditions(errors: [error, anotherError])) } // new condition failed - so return it case (_, .failure(_)): return rhs // first condition is ignored - so return the new one case (.success(false), _): return rhs default: return lhs } } } } func evaluateConditions() -> Procedure { func createEvaluateConditionsProcedure() -> EvaluateConditions { // Set the procedure on each condition conditions.forEach { $0.procedure = self $0.log.enabled = self.log.enabled $0.log.severity = self.log.severity } let evaluator = EvaluateConditions(conditions: conditions) evaluator.name = "\(operationName) Evaluate Conditions" super.addDependency(evaluator) return evaluator } assert(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") let evaluator = createEvaluateConditionsProcedure() // Add the direct dependencies of the procedure as direct dependencies of the evaluator directDependencies.forEach { evaluator.add(dependency: $0) } // Add an observer to the evaluator to see if any of the conditions failed. evaluator.addWillFinishBlockObserver { [weak self] evaluator, _ in guard let result = evaluator.output.value else { return } switch result { case .success(true): break case .success(false): self?.cancel() case let .failure(error): if let failedConditions = error as? ProcedureKitError.FailedConditions { self?.cancel(withErrors: failedConditions.errors) } else { self?.cancel(withError: error) } } } return evaluator } func add(dependencyOnPreviousMutuallyExclusiveProcedure procedure: Procedure) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") super.addDependency(procedure) } func add(directDependency: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") protectedProperties.write { $0.directDependencies.insert(directDependency) } super.addDependency(directDependency) } func remove(directDependency: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") protectedProperties.write { $0.directDependencies.remove(directDependency) } super.removeDependency(directDependency) } public final override var dependencies: [Operation] { return Array(directDependencies.union(indirectDependencies)) } /** Add another `Operation` as a dependency. It is a programmatic error to call this method after the receiver has already started executing. Therefore, best practice is to add dependencies before adding them to operation queues. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - parameter operation: a `Operation` instance. */ public final override func addDependency(_ operation: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") add(directDependency: operation) } /** Remove another `Operation` as a dependency. It is a programmatic error to call this method after the receiver has already started executing. Therefore, best practice is to manage dependencies before adding them to operation queues. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - parameter operation: a `Operation` instance. */ public final override func removeDependency(_ operation: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") remove(directDependency: operation) } /** Add a condition to the procedure. - parameter condition: a `Condition` which must be satisfied for the procedure to be executed. */ public func add(condition: Condition) { assert(state < .executing, "Cannot modify conditions after operation has begun executing, current state: \(state).") protectedProperties.write { $0.conditions.insert(condition) } } } // swiftlint:enable type_body_length // swiftlint:enable file_length
mit
dca88eb5734f5d699ad48aecfe40a4c0
32.991217
282
0.620058
5.336025
false
false
false
false
blg-andreasbraun/ProcedureKit
Tests/Cloud/CKDiscoverUserIdentitiesOperationTests.swift
2
7872
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import XCTest import CloudKit import ProcedureKit import TestingProcedureKit @testable import ProcedureKitCloud class TestCKDiscoverUserIdentitiesOperation: TestCKOperation, CKDiscoverUserIdentitiesOperationProtocol, AssociatedErrorProtocol { typealias AssociatedError = PKCKError var error: Error? var userIdentityLookupInfos: [UserIdentityLookupInfo] = [] var userIdentityDiscoveredBlock: ((UserIdentity, UserIdentityLookupInfo) -> Void)? = nil var discoverUserIdentitiesCompletionBlock: ((Error?) -> Void)? = nil init(error: Error? = nil) { self.error = error super.init() } override func main() { discoverUserIdentitiesCompletionBlock?(error) } } class CKDiscoverUserIdentitiesOperationTests: CKProcedureTestCase { var target: TestCKDiscoverUserIdentitiesOperation! var operation: CKProcedure<TestCKDiscoverUserIdentitiesOperation>! override func setUp() { super.setUp() target = TestCKDiscoverUserIdentitiesOperation() operation = CKProcedure(operation: target) } func test__set_get__userIdentityLookupInfos() { let userIdentityLookupInfos = [ "[email protected]" ] operation.userIdentityLookupInfos = userIdentityLookupInfos XCTAssertEqual(operation.userIdentityLookupInfos, userIdentityLookupInfos) XCTAssertEqual(target.userIdentityLookupInfos, userIdentityLookupInfos) } func test__set_get__userIdentityDiscoveredBlock() { var setByCompletionBlock = false let block: (String, String) -> Void = { identity, lookupInfo in setByCompletionBlock = true } operation.userIdentityDiscoveredBlock = block XCTAssertNotNil(operation.userIdentityDiscoveredBlock) target.userIdentityDiscoveredBlock?("Example", "[email protected]") XCTAssertTrue(setByCompletionBlock) } func test__success_without_completion_block() { wait(for: operation) XCTAssertProcedureFinishedWithoutErrors(operation) } func test__success_with_completion_block() { var didExecuteBlock = false operation.setDiscoverUserIdentitiesCompletionBlock { didExecuteBlock = true } wait(for: operation) XCTAssertProcedureFinishedWithoutErrors(operation) XCTAssertTrue(didExecuteBlock) } func test__error_without_completion_block() { target.error = TestError() wait(for: operation) XCTAssertProcedureFinishedWithoutErrors(operation) } func test__error_with_completion_block() { var didExecuteBlock = false operation.setDiscoverUserIdentitiesCompletionBlock { didExecuteBlock = true } target.error = TestError() wait(for: operation) XCTAssertProcedureFinishedWithErrors(operation, count: 1) XCTAssertFalse(didExecuteBlock) } } class CloudKitProcedureDiscoverUserIdentitiesOperationTests: CKProcedureTestCase { var setByUserIdentityDiscoveredBlock = false var cloudkit: CloudKitProcedure<TestCKDiscoverUserIdentitiesOperation>! override func setUp() { super.setUp() cloudkit = CloudKitProcedure(strategy: .immediate) { TestCKDiscoverUserIdentitiesOperation() } cloudkit.container = container cloudkit.userIdentityLookupInfos = [ "user lookup info" ] cloudkit.userIdentityDiscoveredBlock = { [weak self] _, _ in self?.setByUserIdentityDiscoveredBlock = true } } func test__set_get__errorHandlers() { cloudkit.set(errorHandlers: [.internalError: cloudkit.passthroughSuggestedErrorHandler]) XCTAssertEqual(cloudkit.errorHandlers.count, 1) XCTAssertNotNil(cloudkit.errorHandlers[.internalError]) } func test__set_get_container() { cloudkit.container = "I'm a different container!" XCTAssertEqual(cloudkit.container, "I'm a different container!") } func test__set_get_userIdentityLookupInfos() { cloudkit.userIdentityLookupInfos = [ "user lookup info" ] XCTAssertEqual(cloudkit.userIdentityLookupInfos, [ "user lookup info" ]) } func test__set_get_userIdentityDiscoveredBlock() { XCTAssertNotNil(cloudkit.userIdentityDiscoveredBlock) cloudkit.userIdentityDiscoveredBlock?("user identity", "user lookup info") XCTAssertTrue(setByUserIdentityDiscoveredBlock) } func test__cancellation() { cloudkit.cancel() wait(for: cloudkit) XCTAssertProcedureCancelledWithoutErrors(cloudkit) } func test__success_without_completion_block_set() { wait(for: cloudkit) XCTAssertProcedureFinishedWithoutErrors(cloudkit) } func test__success_with_completion_block_set() { var didExecuteBlock = false cloudkit.setDiscoverUserIdentitiesCompletionBlock { didExecuteBlock = true } wait(for: cloudkit) XCTAssertProcedureFinishedWithoutErrors(cloudkit) XCTAssertTrue(didExecuteBlock) } func test__error_without_completion_block_set() { cloudkit = CloudKitProcedure(strategy: .immediate) { let operation = TestCKDiscoverUserIdentitiesOperation() operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil) return operation } wait(for: cloudkit) XCTAssertProcedureFinishedWithoutErrors(cloudkit) } func test__error_with_completion_block_set() { cloudkit = CloudKitProcedure(strategy: .immediate) { let operation = TestCKDiscoverUserIdentitiesOperation() operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil) return operation } var didExecuteBlock = false cloudkit.setDiscoverUserIdentitiesCompletionBlock { didExecuteBlock = true } wait(for: cloudkit) XCTAssertProcedureFinishedWithErrors(cloudkit, count: 1) XCTAssertFalse(didExecuteBlock) } func test__error_which_retries_using_retry_after_key() { var shouldError = true cloudkit = CloudKitProcedure(strategy: .immediate) { let op = TestCKDiscoverUserIdentitiesOperation() if shouldError { let userInfo = [CKErrorRetryAfterKey: NSNumber(value: 0.001)] op.error = NSError(domain: CKErrorDomain, code: CKError.Code.serviceUnavailable.rawValue, userInfo: userInfo) shouldError = false } return op } var didExecuteBlock = false cloudkit.setDiscoverUserIdentitiesCompletionBlock { didExecuteBlock = true } wait(for: cloudkit) XCTAssertProcedureFinishedWithoutErrors(cloudkit) XCTAssertTrue(didExecuteBlock) } func test__error_which_retries_using_custom_handler() { var shouldError = true cloudkit = CloudKitProcedure(strategy: .immediate) { let op = TestCKDiscoverUserIdentitiesOperation() if shouldError { op.error = NSError(domain: CKErrorDomain, code: CKError.Code.limitExceeded.rawValue, userInfo: nil) shouldError = false } return op } var didRunCustomHandler = false cloudkit.set(errorHandlerForCode: .limitExceeded) { _, _, _, suggestion in didRunCustomHandler = true return suggestion } var didExecuteBlock = false cloudkit.setDiscoverUserIdentitiesCompletionBlock { didExecuteBlock = true } wait(for: cloudkit) XCTAssertProcedureFinishedWithoutErrors(cloudkit) XCTAssertTrue(didExecuteBlock) XCTAssertTrue(didRunCustomHandler) } }
mit
5a18b3ed69079ea1aab634afd1a6dee6
35.439815
130
0.688223
5.891467
false
true
false
false
cstad/SwiftColorPicker
SwiftColorPicker/lib/SwiftColorPicker/ColorGradientView.swift
1
1752
// // ColorGradientView.swift // SwiftColorPicker // // Created by cstad on 12/10/14. // import UIKit class ColorGradientView: UIView { var colorLayer: ColorLayer! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } init(frame: CGRect, color: UIColor!) { super.init(frame: frame) setColor(color) } func setColor(_color: UIColor!) { // Set member color to the new UIColor coming in colorLayer = ColorLayer(color: _color) // Set colorView sublayers to nil to remove any existing sublayers layer.sublayers = nil; // Use the size and position of this views frame to create a new frame for the color.colorLayer colorLayer.layer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.width) // Insert the color.colorLayer into this views layer as a sublayer layer.insertSublayer(colorLayer.layer, atIndex: 0) // Init new CAGradientLayer to be used as the grayScale overlay var grayScaleLayer = CAGradientLayer() // Set the grayScaleLayer colors to black and clear grayScaleLayer.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor] // Display gradient left to right grayScaleLayer.startPoint = CGPointMake(0.0, 0.5) grayScaleLayer.endPoint = CGPointMake(1.0, 0.5) // Use the size and position of this views frame to create a new frame for the grayScaleLayer grayScaleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.width) // Insert the grayScaleLayer into this views layer as a sublayer self.layer.insertSublayer(grayScaleLayer, atIndex: 1) } }
mit
452fc41ff184a966e048626028e933f6
38.818182
110
0.671804
4.413098
false
false
false
false
someoneAnyone/PageCollectionViewLayout
Example/Tests/Tests.swift
1
1283
// https://github.com/Quick/Quick //import Quick //import Nimble import PageCollectionViewLayout //class TableOfContentsSpec: QuickSpec { // override func spec() { // describe("these will fail") { // // it("can do maths") { // expect(1) == 2 // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } // // context("these will pass") { // // it("can do maths") { // expect(23) == 23 // } // // it("can read") { // expect("🐮") == "🐮" // } // // it("will eventually pass") { // var time = "passing" // // dispatch_async(dispatch_get_main_queue()) { // time = "done" // } // // waitUntil { done in // NSThread.sleepForTimeInterval(0.5) // expect(time) == "done" // // done() // } // } // } // } // } //}
mit
00179ba6b27570e7d4f2f3f537f416ab
24.54
65
0.344558
4.228477
false
false
false
false
sbutler2901/IPCanary
IPCanaryTests/IPCanaryTests.swift
1
6337
// // IPCanaryTests.swift // IPCanaryTests // // Created by Seth Butler on 12/15/16. // Copyright © 2016 SBSoftware. All rights reserved. // import XCTest @testable import IPCanary @testable import IPCanaryKit class IPCanaryTests: XCTestCase { //var vc : MainViewController! var networkManager: IPCanaryKitNetworkManager! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. networkManager = IPCanaryKitNetworkManager(withAutoRefresh: false) /*let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) vc = storyboard.instantiateInitialViewController() as! MainViewController*/ } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // TODO: - Ensure tests cover all public interfaces // MARK: - MainViewModel Tests // FIXME: - Dup tests to handle when mock data has same IP & when IP changes? // Ensures instance of mainview model's ip variables matches that of network manager's func testMainViewModelIP() { let mainViewModel = MainViewModel(networkManager: networkManager) XCTAssertEqual(mainViewModel.currentIP, networkManager.getCurrentIPAddress().getIPAddress()) XCTAssertEqual(mainViewModel.city, networkManager.getCurrentIPAddress().getCity()) XCTAssertEqual(mainViewModel.country, networkManager.getCurrentIPAddress().getCountry()) XCTAssertEqual(mainViewModel.hostname, networkManager.getCurrentIPAddress().getHostname()) XCTAssertEqual(mainViewModel.ipLastUpdate, networkManager.getCurrentIPAddress().getLastUpdateDate().description) XCTAssertEqual(mainViewModel.ipLastChanged, networkManager.getCurrentIPAddress().getLastChangeDate().description) } // Tests if main view model IP is updated without the view model being established as delegate func testMainViewModelIPUpdated() { let mainViewModel = MainViewModel(networkManager: networkManager) networkManager.delegate = nil XCTAssertNil(networkManager.delegate) let ipAddress = networkManager.getCurrentIPAddress().getIPAddress() let city = networkManager.getCurrentIPAddress().getCity() let country = networkManager.getCurrentIPAddress().getCountry() let hostname = networkManager.getCurrentIPAddress().getHostname() var newUpdateDate = Date() newUpdateDate.addTimeInterval(TimeInterval(10)) networkManager.getCurrentIPAddress().setAddress(address: ipAddress, city: city, country: country, hostname: hostname, date: newUpdateDate) networkManager.delegate?.ipUpdated() XCTAssertNotEqual(mainViewModel.ipLastUpdate, networkManager.getCurrentIPAddress().getLastUpdateDate().description) } // Tests if main view model IP is updated with view model established as delegate func testMainViewModelRefreshIP() { let mainViewModel = MainViewModel(networkManager: networkManager) networkManager.delegate = mainViewModel XCTAssertNotNil(networkManager.delegate) let ipAddress = networkManager.getCurrentIPAddress().getIPAddress() let city = networkManager.getCurrentIPAddress().getCity() let country = networkManager.getCurrentIPAddress().getCountry() let hostname = networkManager.getCurrentIPAddress().getHostname() var newUpdateDate = Date() newUpdateDate.addTimeInterval(TimeInterval(10)) networkManager.getCurrentIPAddress().setAddress(address: ipAddress, city: city, country: country, hostname: hostname, date: newUpdateDate) networkManager.delegate?.ipUpdated() XCTAssertEqual(mainViewModel.currentIP, networkManager.getCurrentIPAddress().getIPAddress()) XCTAssertEqual(mainViewModel.ipLastUpdate, networkManager.getCurrentIPAddress().getLastUpdateDate().description) XCTAssertEqual(mainViewModel.ipLastChanged, networkManager.getCurrentIPAddress().getLastChangeDate().description) } // TODO: - After timer refresh has been implemented. Use Mock Data? // Mock data code: // let mockDataString: String = "{\"ip\":\"209.222.19.251\",\"ip_decimal\":3520992251,\"country\":\"United States\",\"city\":\"Matawan\",\"hostname\":\"209.222.19.251.adsl.inet-telecom.org\"}" // self.parseRequestedData(data: mockDataString.data(using: .utf8)!) // self.delegate?.ipUpdated() // completionHandler?("SUCCESS") // End Mock data // func testMainViewModelExternallyRefreshedIP() { // let mainViewModel = MainViewModel(networkManager: networkManager) // networkManager.delegate = mainViewModel // //// let expectation: XCTestExpectation = self.expectation(description: "Network Request") //// //// networkManager.refreshIP() { statusCode in //// // Must unwrap the optional string before testing //// if let statusCodeUnwrapped = statusCode { //// //print("Test: \(stringUnwrapped)") //// XCTAssertEqual(statusCodeUnwrapped, "SUCCESS") //// //XCTAssertNotNil(statusCodeUnwrapped, "Expected non-nil string") //// expectation.fulfill() //// } else { //// XCTFail() //// } //// } //// //// waitForExpectations(timeout: 10.0, handler: nil) // // //XCTAssertNotNil(networkManager.delegate) // XCTAssertEqual(mainViewModel.currentIP, networkManager.currentIPAddress.getIPAddress()) // XCTAssertEqual(mainViewModel.ipLastUpdate, networkManager.currentIPAddress.getLastUpdateDate().description) // XCTAssertEqual(mainViewModel.ipLastChanged, networkManager.currentIPAddress.getLastChangeDate().description) // } // MARK: - Performance tests func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
apache-2.0
0a5ab90857a5ee0022bc3fbb04374e9a
44.257143
199
0.682134
5.577465
false
true
false
false
remlostime/one
one/one/ViewControllers/SignInViewController.swift
1
2131
// // SignInViewController.swift // one // // Created by Kai Chen on 12/20/16. // Copyright © 2016 Kai Chen. All rights reserved. // import UIKit import Parse class SignInViewController: UIViewController { @IBOutlet var userNameTextField: UITextField! @IBOutlet var passwordTextField: UITextField! @IBOutlet var forgotPasswordButton: UIButton! @IBOutlet var signInButton: UIButton! @IBOutlet var signUpButton: UIButton! override func viewDidLoad() { signInButton.layer.borderColor = UIColor.lightGray.cgColor signUpButton.layer.borderColor = UIColor.lightGray.cgColor userNameTextField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0); passwordTextField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0); } @IBAction func signInButtonTapped(_ sender: UIButton) { let username = userNameTextField.text let password = passwordTextField.text if let username = username, let password = password { PFUser.logInWithUsername(inBackground: username, password: password, block: { [weak self](user: PFUser?, error: Error?) in guard let strongSelf = self else { return } guard let user = user else { strongSelf.showLoginErrorAlert(error?.localizedDescription) return } let appDelegate = UIApplication.shared.delegate as? AppDelegate appDelegate?.login(withUserName: user.username) }) } } func showLoginErrorAlert(_ message: String?) { let alertVC = UIAlertController(title: "Error", message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertVC.addAction(okAction) self.present(alertVC, animated: true, completion: nil) } }
gpl-3.0
d82a97a612e72bfb1ecc53a4c6aa444a
35.101695
134
0.595775
5.664894
false
false
false
false
cocoascientist/Passengr
Passengr/Pass.swift
1
2503
// // Pass.swift // Passengr // // Created by Andrew Shepard on 11/30/15. // Copyright © 2015 Andrew Shepard. All rights reserved. // import Foundation final class Pass: NSObject { let name: String let url: String var conditions: String = "" var eastbound: String = "" var westbound: String = "" var order: Int var isEnabled: Bool var lastModified: Date = Date() init(name: String, url: String, order: Int, enabled: Bool) { self.name = name self.url = url self.order = order self.isEnabled = enabled super.init() } } extension Pass: NSCoding { convenience init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String, let url = aDecoder.decodeObject(forKey: "url") as? String else { return nil } let enabled = aDecoder.decodeBool(forKey: "isEnabled") let order = aDecoder.decodeInteger(forKey: "order") self.init(name: name, url: url, order: order, enabled: enabled) let conditions = aDecoder.decodeObject(forKey: "conditions") as? String ?? "" let westbound = aDecoder.decodeObject(forKey: "westbound") as? String ?? "" let eastbound = aDecoder.decodeObject(forKey: "eastbound") as? String ?? "" let lastModified = aDecoder.decodeObject(forKey: "lastModified") as? Date ?? Date() self.eastbound = eastbound self.westbound = westbound self.conditions = conditions self.lastModified = lastModified } func encode(with coder: NSCoder) { coder.encode(name, forKey: "name") coder.encode(url, forKey: "url") coder.encode(isEnabled, forKey: "isEnabled") coder.encode(order, forKey: "order") coder.encode(conditions, forKey: "conditions") coder.encode(westbound, forKey: "westbound") coder.encode(eastbound, forKey: "eastbound") coder.encode(lastModified, forKey: "lastModified") } } extension Pass: PassInfoType { var passInfo: PassInfo { return [ PassInfoKeys.Title: self.name, PassInfoKeys.ReferenceURL: self.url ] } func update(using info: [String: String]) { self.conditions = info[PassInfoKeys.Conditions] ?? "" self.westbound = info[PassInfoKeys.Westbound] ?? "" self.eastbound = info[PassInfoKeys.Eastbound] ?? "" } }
mit
d9a179809958044e5fc56895f5a144a0
29.888889
91
0.607114
4.226351
false
false
false
false
tsalvo/nes-chr-editor
NES CHR Editor/NES CHR Editor/Extensions/UInt8+ByteUtils.swift
1
2775
// // UInt8+ByteUtils.swift // NES CHR Editor // // Created by Tom Salvo on 5/24/20. // Copyright © 2020 Tom Salvo. All rights reserved. // import Foundation extension UInt8 { /// Returns an assembler-friendly representation of the hex value of this byte (e.g. 0 = $00, 255 = $FF) var asmHexString: String { return String(format: "$%02X", self) } /// Returns a C-style hex representation of the hex value of this byte (e.g. 0 = 0x00, 255 = 0xFF) var cHexString: String { return String(format: "0x%02X", self) } /// Returns a UInt8 value from an array of 8 boolean values in big endian order (more significant, or "higher", bits first) init(fromBigEndianBitArray aBigEndianBitArray: [Bool]) { var retValue: UInt8 = 0 if aBigEndianBitArray.count == 8 { retValue += aBigEndianBitArray[7] ? 1 : 0 retValue += aBigEndianBitArray[6] ? 2 : 0 retValue += aBigEndianBitArray[5] ? 4 : 0 retValue += aBigEndianBitArray[4] ? 8 : 0 retValue += aBigEndianBitArray[3] ? 16 : 0 retValue += aBigEndianBitArray[2] ? 32 : 0 retValue += aBigEndianBitArray[1] ? 64 : 0 retValue += aBigEndianBitArray[0] ? 128 : 0 } self.init(retValue) } /// Returns an array of 8 boolean values in little-endian order (less significant, or "lower", bits first) var littleEndianBitArray: [Bool] { let lE = self.littleEndian var retValue: [Bool] = [Bool].init(repeating: false, count: 8) retValue[0] = lE >> 0 & 1 == 1 retValue[1] = lE >> 1 & 1 == 1 retValue[2] = lE >> 2 & 1 == 1 retValue[3] = lE >> 3 & 1 == 1 retValue[4] = lE >> 4 & 1 == 1 retValue[5] = lE >> 5 & 1 == 1 retValue[6] = lE >> 6 & 1 == 1 retValue[7] = lE >> 7 & 1 == 1 return retValue } /// Returns a UInt8 value from an array of 8 boolean values in little endian order (less significant, or "lower", bits first) init(fromLittleEndianBitArray aLittleEndianBitArray: [Bool]) { var retValue: UInt8 = 0 if aLittleEndianBitArray.count == 8 { retValue += aLittleEndianBitArray[0] ? 1 : 0 retValue += aLittleEndianBitArray[1] ? 2 : 0 retValue += aLittleEndianBitArray[2] ? 4 : 0 retValue += aLittleEndianBitArray[3] ? 8 : 0 retValue += aLittleEndianBitArray[4] ? 16 : 0 retValue += aLittleEndianBitArray[5] ? 32 : 0 retValue += aLittleEndianBitArray[6] ? 64 : 0 retValue += aLittleEndianBitArray[7] ? 128 : 0 } self.init(retValue) } }
apache-2.0
45ee36db9726b856e27ccd07057477e1
33.675
129
0.562365
4.177711
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Export/Coordinators/BackupCoordinator.swift
1
4883
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import Result import TrustCore import TrustKeystore protocol BackupCoordinatorDelegate: class { func didCancel(coordinator: BackupCoordinator) func didFinish(wallet: Wallet, in coordinator: BackupCoordinator) } final class BackupCoordinator: Coordinator { let navigationController: NavigationController weak var delegate: BackupCoordinatorDelegate? let keystore: Keystore let account: Account var coordinators: [Coordinator] = [] init( navigationController: NavigationController, keystore: Keystore, account: Account ) { self.navigationController = navigationController self.navigationController.modalPresentationStyle = .formSheet self.keystore = keystore self.account = account } func start() { export(for: account) } func finish(result: Result<Bool, AnyError>) { switch result { case .success: delegate?.didFinish(wallet: account.wallet!, in: self) case .failure: delegate?.didCancel(coordinator: self) } } func presentActivityViewController(for account: Account, password: String, newPassword: String, completion: @escaping (Result<Bool, AnyError>) -> Void) { navigationController.topViewController?.displayLoading( text: NSLocalizedString("export.presentBackupOptions.label.title", value: "Preparing backup options...", comment: "") ) keystore.export(account: account, password: password, newPassword: newPassword) { [weak self] result in guard let `self` = self else { return } self.handleExport(result: result, completion: completion) } } private func handleExport(result: (Result<String, KeystoreError>), completion: @escaping (Result<Bool, AnyError>) -> Void) { switch result { case .success(let value): let url = URL(fileURLWithPath: NSTemporaryDirectory().appending("trust_backup_\(account.address.description).json")) do { try value.data(using: .utf8)!.write(to: url) } catch { return completion(.failure(AnyError(error))) } let activityViewController = UIActivityViewController.make(items: [url]) activityViewController.completionWithItemsHandler = { _, result, _, error in do { try FileManager.default.removeItem(at: url) } catch { } guard let error = error else { return completion(.success(result)) } completion(.failure(AnyError(error))) } let presenterViewController = navigationController.topViewController activityViewController.popoverPresentationController?.sourceView = presenterViewController?.view activityViewController.popoverPresentationController?.sourceRect = presenterViewController?.view.centerRect ?? .zero presenterViewController?.present(activityViewController, animated: true) { [weak presenterViewController] in presenterViewController?.hideLoading() } case .failure(let error): navigationController.topViewController?.hideLoading() navigationController.topViewController?.displayError(error: error) } } func presentShareActivity(for account: Account, password: String, newPassword: String) { self.presentActivityViewController(for: account, password: password, newPassword: newPassword) { result in self.finish(result: result) } } func export(for account: Account) { let coordinator = EnterPasswordCoordinator(account: account) coordinator.delegate = self coordinator.start() navigationController.present(coordinator.navigationController, animated: true, completion: nil) addCoordinator(coordinator) } } extension BackupCoordinator: EnterPasswordCoordinatorDelegate { func didCancel(in coordinator: EnterPasswordCoordinator) { coordinator.navigationController.dismiss(animated: true, completion: nil) removeCoordinator(coordinator) } func didEnterPassword(password: String, account: Account, in coordinator: EnterPasswordCoordinator) { coordinator.navigationController.dismiss(animated: true) { [unowned self] in if let currentPassword = self.keystore.getPassword(for: account.wallet!) { self.presentShareActivity(for: account, password: currentPassword, newPassword: password) } else { self.presentShareActivity(for: account, password: password, newPassword: password) } } removeCoordinator(coordinator) } }
gpl-3.0
ee470153a0cd4a9b9dbd1e749b342f80
39.691667
157
0.668646
5.586957
false
false
false
false
gpancio/iOS-Prototypes
EdmundsAPI/EdmundsAPI/Classes/GetMakes.swift
1
1260
// // GetMakes.swift // EdmundsAPI // // Created by Graham Pancio on 2016-04-27. // Copyright © 2016 Graham Pancio. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper public protocol GetMakesDelegate: class { func onSuccess(makes: [String]) func onFail() } /** Retrieves vehicle makes using the Edmunds Vehicle API. */ public class GetMakes { public weak var delegate: GetMakesDelegate? var apiKey: String public init(apiKey: String) { self.apiKey = apiKey } public func makeRequest(year: String) { Alamofire.request(Method.GET, formatUrl(year)).validate().responseObject { (response: Response<VehicleMakeSet, NSError>) in let makeSet = response.result.value if makeSet != nil && makeSet?.makes != nil && makeSet?.makes?.count > 0 { self.delegate?.onSuccess(makeSet?.makesArray ?? []) } else { self.delegate?.onFail() } } } private func formatUrl(year: String) -> String { let urlString = String(format: "https://api.edmunds.com/api/vehicle/v2/makes?fmt=json&year=%@&api_key=%@", year, apiKey) return urlString } }
mit
018059891716cd63bdaeb081fa35e084
25.25
131
0.618745
4.224832
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Extensions/Sources/SwiftExtensions/CodeLocation.swift
1
785
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct CodeLocation: Codable, Hashable, CustomDebugStringConvertible, CustomStringConvertible { var function: String var file: String var line: Int public init( _ function: String = #function, _ file: String = #filePath, _ line: Int = #line ) { self.function = function self.file = file self.line = line } public var debugDescription: String { "← \(file):\(line) @ \(function)" } public var description: String { var __ = file if let i = __.lastIndex(of: "/") { __ = __.suffix(from: __.index(after: i)).description } return "← \(__):\(line)" } }
lgpl-3.0
3b546e659cb224ecc1c85b51ca623353
23.375
102
0.561538
4.357542
false
false
false
false
huonw/swift
stdlib/public/core/NewtypeWrapper.swift
1
3526
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// An implementation detail used to implement support importing /// (Objective-)C entities marked with the swift_newtype Clang /// attribute. public protocol _SwiftNewtypeWrapper : RawRepresentable { } extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue : Hashable { /// The hash value. @inlinable public var hashValue: Int { return rawValue.hashValue } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } } #if _runtime(_ObjC) extension _SwiftNewtypeWrapper where Self.RawValue : _ObjectiveCBridgeable { // Note: This is the only default typealias for _ObjectiveCType, because // constrained extensions aren't allowed to define types in different ways. // Fortunately the others don't need it. public typealias _ObjectiveCType = Self.RawValue._ObjectiveCType @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> Self.RawValue._ObjectiveCType { return rawValue._bridgeToObjectiveC() } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType, result: inout Self? ) { var innerResult: Self.RawValue? Self.RawValue._forceBridgeFromObjectiveC(source, result: &innerResult) result = innerResult.flatMap { Self(rawValue: $0) } } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType, result: inout Self? ) -> Bool { var innerResult: Self.RawValue? let success = Self.RawValue._conditionallyBridgeFromObjectiveC( source, result: &innerResult) result = innerResult.flatMap { Self(rawValue: $0) } return success } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType? ) -> Self { return Self( rawValue: Self.RawValue._unconditionallyBridgeFromObjectiveC(source))! } } extension _SwiftNewtypeWrapper where Self.RawValue: AnyObject { @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> Self.RawValue { return rawValue } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: Self.RawValue, result: inout Self? ) { result = Self(rawValue: source) } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: Self.RawValue, result: inout Self? ) -> Bool { result = Self(rawValue: source) return result != nil } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: Self.RawValue? ) -> Self { return Self(rawValue: source!)! } } #endif
apache-2.0
6b08ee1d76e149032dab2dee657d310f
31.054545
80
0.684628
4.720214
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Swift/Extensions/ProcessInfo+Extensions.swift
1
5476
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import Foundation extension ProcessInfo { /// Returns the process information agent for the process. /// /// An `ProcessInfo` object is created the first time this method is invoked, /// and that same object is returned on each subsequent invocation. /// /// - Returns: Shared process information agent for the process. public static var shared: ProcessInfo { processInfo } public func contains(key: String) -> Bool { environment[key] != nil || inMemoryEnvironmentStorage[key] != nil } } // MARK: - In-memory extension ProcessInfo { private enum AssociatedKey { static var inMemoryEnvironmentStorage = "inMemoryEnvironmentStorage" } private var inMemoryEnvironmentStorage: [String: String] { get { associatedObject(&AssociatedKey.inMemoryEnvironmentStorage, default: [:]) } set { setAssociatedObject(&AssociatedKey.inMemoryEnvironmentStorage, value: newValue) } } } // MARK: - Argument extension ProcessInfo { public struct Argument: RawRepresentable, ExpressibleByStringLiteral, CustomStringConvertible, Hashable { /// The variable name in the environment from which the process was launched. public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public init(stringLiteral value: String) { self.rawValue = value } public var description: String { rawValue } /// A boolean property to indicate whether the variable exists in the /// environment from which the process was launched. public var exists: Bool { ProcessInfo.shared.contains(key: rawValue) || ProcessInfo.shared.inMemoryEnvironmentStorage.keys.contains(rawValue) } /// The variable value in the environment from which the process was launched. private var currentValue: String? { var storedValue = ProcessInfo.shared.inMemoryEnvironmentStorage[rawValue] if storedValue == nil { storedValue = ProcessInfo.shared.environment[rawValue] } guard let value = storedValue, !value.isBlank else { return nil } return value } /// Returns the value of the argument. public func get<T>() -> T? { guard let value = currentValue else { switch T.self { case is Bool.Type, is Optional<Bool>.Type: if exists { return true as? T } default: break } return nil } return StringConverter(value).get() } /// Set given value in memory. public func set<T>(_ value: T?) { var valueToSave: String? if let newValue = value { valueToSave = String(describing: newValue) } ProcessInfo.shared.inMemoryEnvironmentStorage[rawValue] = valueToSave } } } // MARK: - Argument Convenience extension ProcessInfo.Argument { /// Returns the value of the argument. public func get() -> Bool { get() ?? false } /// Returns the value of the argument. /// /// - Parameter defaultValue: The value returned if the value doesn't exists. public func get<T>(default defaultValue: @autoclosure () -> T) -> T { get() ?? defaultValue() } /// Returns the value of the key from registered list of feature flag providers. /// /// - Parameter defaultValue: The value returned if the providers list doesn't /// contain value. /// - Returns: The value for the key. public func get<T>(default defaultValue: @autoclosure () -> T) -> T where T: RawRepresentable, T.RawValue == String { if let rawValue: String = get(), let value = T(rawValue: rawValue) { return value } return defaultValue() } } // MARK: - Arguments Namespace extension ProcessInfo { public enum Arguments { public static func argument(_ flag: String) -> Argument { Argument(rawValue: flag) } } } // MARK: - Built-in Arguments extension ProcessInfo.Arguments { /// A boolean value to determine whether the app is running tests. public static var isTesting: Bool { argument("XCTestConfigurationFilePath").exists } /// A boolean value to determine whether the app is running in previews. public static var isRunningInPreviews: Bool { argument("XCODE_RUNNING_FOR_PREVIEWS").exists } public static var isDebug: Bool { argument("DEBUG").exists } public static var isAnalyticsDebugEnabled: (enabled: Bool, contains: String?) { guard AppInfo.isDebuggerAttached else { return (false, nil) } let flag = argument("XCAnalyticsDebugEnabled") return (flag.exists, flag.get()) } public static var isAllInterstitialsEnabled: Bool { get { #if DEBUG return argument("XCAllInterstitialsEnabled").exists #else return false #endif } set { argument("XCAllInterstitialsEnabled").set(newValue) } } }
mit
60eab0ddf639644c9783c7162d0815f8
28.594595
121
0.602009
5.214286
false
false
false
false
fiveagency/ios-five-ui-components
FiveUIComponents/Classes/Views/PageViewController.swift
1
9879
// // PageViewController.swift // FiveUIComponents // // Created by Mario Radonic on 17/02/17. // Copyright © 2017 Five Agency. All rights reserved. // import UIKit /** Datasource */ @objc public protocol PageViewControllerDatasource: class { func viewControllers(for pageViewController: PageViewController) -> [UIViewController] } /** Provides information about current relative index so that delegate can update page control. */ @objc public protocol PageControlDelegate: class { func updatePageControlsRelativeIndex(_ relativeIndex: CGFloat) func updatePageControlsIndex(from relativeIndex: CGFloat) } /** Page View Controller. It contains horizontal scroll view as root view. Children view controllers' views are subviews of scroll view. */ public class PageViewController: UIViewController { @IBOutlet public weak var datasource: PageViewControllerDatasource? @IBOutlet public weak var pageControlDelegate: PageControlDelegate? private let contentScrollView = UIScrollView() private(set) var numberOfPages = 0 private(set) var viewControllers = [UIViewController]() private(set) var scrollingTransitioningToIndex: Int? private(set) var automaticTransitioningToIndex: Int? fileprivate var currentIndex: Int = 0 fileprivate var currentRelativeIndex: CGFloat { guard view.bounds.width != 0 else { return 0 } return contentScrollView.contentOffset.x / view.bounds.width } public override func viewDidLoad() { super.viewDidLoad() insertAndLayoutContentView() setupContentView() reloadPages() } public override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } private var didInitialLayout = false private var setIndexWhenLayout = 0 public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() didInitialLayout = true if setIndexWhenLayout != 0 { setCurrentPage(at: setIndexWhenLayout) } } private func insertAndLayoutContentView() { view.addSubview(contentScrollView) contentScrollView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|[contentScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["contentScrollView": contentScrollView]) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[contentScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["contentScrollView": contentScrollView]) NSLayoutConstraint.activate(horizontalConstraints) NSLayoutConstraint.activate(verticalConstraints) } private func setupContentView() { contentScrollView.showsHorizontalScrollIndicator = false contentScrollView.showsVerticalScrollIndicator = false contentScrollView.isPagingEnabled = true contentScrollView.scrollsToTop = false contentScrollView.delegate = self } public func reloadPages() { removeChildren() updateNumberOfPagesFromDatasource() updateViewControllersFromDatasource() insertAndLayoutViewControllers() } public func setCurrentPage(at index: Int) { guard viewControllers.count > index else { return } if !didInitialLayout { setIndexWhenLayout = index return } self.automaticTransitioningToIndex = index didHandleAutomaticTransition = false let xOffset = view.bounds.width * CGFloat(index) contentScrollView.setContentOffset(CGPoint(x: xOffset, y: 0), animated: true) } private func removeChildren() { for vc in viewControllers { vc.removeFromParentViewController() vc.view.removeFromSuperview() } } private func updateNumberOfPagesFromDatasource() { if let viewControllers = datasource?.viewControllers(for: self) { numberOfPages = viewControllers.count } numberOfPages = 0 } private func updateViewControllersFromDatasource() { viewControllers = datasource?.viewControllers(for: self) ?? [UIViewController]() } private func insertAndLayoutViewControllers() { var previousView: UIView? viewControllers.first?.beginAppearanceTransition(true, animated: false) for vc in viewControllers { insertChildViewController(vc) layoutChildView(vc.view, with: previousView) previousView = vc.view } viewControllers.first?.endAppearanceTransition() currentIndex = 0 if let lastView = previousView { lastView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: lastView, attribute: .trailing, relatedBy: .equal, toItem: lastView.superview, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true } } private func insertChildViewController(_ childController: UIViewController) { self.addChildViewController(childController) contentScrollView.addSubview(childController.view) childController.didMove(toParentViewController: self) } private func layoutChildView(_ childView: UIView, with previousView: UIView?) { let leftViewToPinTo = previousView ?? contentScrollView let leftEdgeToPinTo: NSLayoutAttribute = (previousView == nil) ? .leading : .trailing childView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: childView, attribute: .leading, relatedBy: .equal, toItem: leftViewToPinTo, attribute: leftEdgeToPinTo, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: childView, attribute: .top, relatedBy: .equal, toItem: childView.superview, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: childView, attribute: .bottom, relatedBy: .equal, toItem: childView.superview, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: childView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true NSLayoutConstraint(item: childView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: 0.0).isActive = true } private var didHandleAutomaticTransition = false fileprivate func updateChildrenAppearanceTransitions() { if let index = automaticTransitioningToIndex { guard !didHandleAutomaticTransition else { return } didHandleAutomaticTransition = true guard let transitioningToVC = viewControllers[safe: index], let currentViewController = viewControllers[safe: currentIndex] else { return } transitioningToVC.beginAppearanceTransition(true, animated: true) currentViewController.beginAppearanceTransition(false, animated: true) return } let relativeIndex = currentRelativeIndex guard relativeIndex >= 0 && relativeIndex < CGFloat(viewControllers.count-1) else { return } let scrollingForward = relativeIndex > CGFloat(currentIndex) let scrollingBackward = relativeIndex < CGFloat(currentIndex) let transitioningToIndex: Int if scrollingForward { transitioningToIndex = currentIndex + 1 } else if scrollingBackward { transitioningToIndex = currentIndex - 1 } else { return } if self.scrollingTransitioningToIndex != transitioningToIndex && transitioningToIndex != currentIndex { self.scrollingTransitioningToIndex = transitioningToIndex guard let transitioningToVC = viewControllers[safe: transitioningToIndex], let currentViewController = viewControllers[safe: currentIndex] else { return } transitioningToVC.beginAppearanceTransition(true, animated: true) currentViewController.beginAppearanceTransition(false, animated: true) } } fileprivate func updateChildrenEndingTransitions() { guard contentScrollView.frame.width != 0 else { return } guard viewControllers.count > 0 else { return } let currentIndex = Int(round(contentScrollView.contentOffset.x / contentScrollView.frame.width)) if currentIndex != self.currentIndex { viewControllers[self.currentIndex].endAppearanceTransition() self.currentIndex = currentIndex viewControllers[self.currentIndex].endAppearanceTransition() } scrollingTransitioningToIndex = nil automaticTransitioningToIndex = nil } deinit { contentScrollView.delegate = nil } } extension PageViewController: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControlDelegate?.updatePageControlsRelativeIndex(currentRelativeIndex) updateChildrenAppearanceTransitions() } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { pageControlDelegate?.updatePageControlsIndex(from: currentRelativeIndex) updateChildrenEndingTransitions() } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { pageControlDelegate?.updatePageControlsIndex(from: currentRelativeIndex) updateChildrenEndingTransitions() } }
mit
a89cf6219e5d3ef72aaed6c55f7e1fa7
38.991903
217
0.689512
6.067568
false
false
false
false
amrap-labs/TeamupKit
Sources/TeamupKit/Controllers/Business/Instructors/InstructorsApiController.swift
1
2471
// // InstructorsApiController.swift // TeamupKit // // Created by Merrick Sapsford on 21/06/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import Foundation import Alamofire class InstructorsApiController: AuthenticatedApiController, InstructorsController { } // MARK: - Methods extension InstructorsApiController { func loadAll(success: ((ResultsPage<Instructor>) -> Void)?, failure: Controller.MethodFailure?) { let parameters: Alamofire.Parameters = [ "business" : config.business.businessId ] let request = requestBuilder.build(for: .instructors, method: .get, parameters: parameters, authentication: .userToken) requestExecutor.execute(request: request, success: { (request, response, data) in guard let data = data else { failure?(TeamupError.unknown, nil) return } do { let instructors = try self.decoder.decode(ResultsPage<Instructor>.self, from: data) success?(instructors) } catch { failure?(error, nil) } }) { (request, response, error) in failure?(error, response?.errorDetail) } } func load(withId id: Int, success: ((Instructor) -> Void)?, failure: Controller.MethodFailure?) { let request = requestBuilder.build(for: .instructor(id: id), method: .get, authentication: .userToken) requestExecutor.execute(request: request, success: { (request, response, data) in guard let data = data else { failure?(TeamupError.unknown, nil) return } do { let instructor = try self.decoder.decode(Instructor.self, from: data) success?(instructor) } catch { failure?(error, nil) } }) { (request, response, error) in failure?(error, response?.errorDetail) } } }
mit
6d8c5fa628d2c66d84ef1a7961b152a9
33.305556
103
0.482186
5.525727
false
false
false
false
walokra/Haikara
Haikara/Controllers/MasterViewController+UIViewControllerPreview.swift
1
3028
// // MasterViewController+UIViewControllerPreview.swift // highkara // // The MIT License (MIT) // // Copyright (c) 2017 Marko Wallin <[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 extension MasterViewController: UIViewControllerPreviewingDelegate { // MARK: UIViewControllerPreviewingDelegate /// Create a previewing view controller to be shown at "Peek". func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { // Obtain the index path and the cell that was pressed. guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil } // Create a detail view controller and set its properties. guard let detailViewController = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else { return nil } let selectedCategory = self.categories[indexPath.row] detailViewController.navigationItemTitle = selectedCategory.title detailViewController.highFiSection = selectedCategory.htmlFilename /* Set the height of the preview by setting the preferred content size of the detail view controller. Width should be zero, because it's not used in portrait. */ detailViewController.preferredContentSize = CGSize(width: 0.0, height: 0.0) // Set the source rect to the cell frame, so surrounding elements are blurred. previewingContext.sourceRect = cell.frame return detailViewController } /// Present the view controller for the "Pop" action. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { // Reuse the "Peek" view controller for presentation. show(viewControllerToCommit, sender: self) } }
mit
0167f11f517c5e4f83ec5dc0ef53938d
47.063492
163
0.736129
5.106239
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/ViewControllers/ShotViewReactor.swift
1
2809
// // ShotViewReactor.swift // Drrrible // // Created by Suyeol Jeon on 12/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import ReactorKit import RxCocoa import RxSwift final class ShotViewReactor: Reactor { enum Action { case refresh } enum Mutation { case setRefreshing(Bool) case setShot(Shot) case setComments([Comment]) } struct State { let shotID: Int var isRefreshing: Bool = false var shotSectionReactor: ShotSectionReactor var commentSectionItems: [ShotViewSectionItem] = [.activityIndicator] var sections: [ShotViewSection] { let sections: [ShotViewSection] = [ .shot(shotSectionReactor.currentState.sectionItems.map(ShotViewSectionItem.shot)), .comment(self.commentSectionItems), ] return sections.filter { !$0.items.isEmpty } } init(shotID: Int, shotSectionReactor: ShotSectionReactor) { self.shotID = shotID self.shotSectionReactor = shotSectionReactor } } let initialState: State fileprivate var shotID: Int { return self.currentState.shotID } fileprivate let shotService: ShotServiceType init( shotID: Int, shot initialShot: Shot? = nil, shotService: ShotServiceType, shotSectionReactorFactory: (Int, Shot?) -> ShotSectionReactor ) { self.initialState = State( shotID: shotID, shotSectionReactor: shotSectionReactorFactory(shotID, initialShot) ) self.shotService = shotService _ = self.state } func mutate(action: Action) -> Observable<Mutation> { switch action { case .refresh: guard !self.currentState.isRefreshing else { return .empty() } return Observable.concat([ Observable.just(.setRefreshing(true)), self.shotService.shot(id: self.shotID).asObservable().map(Mutation.setShot), Observable.just(.setRefreshing(false)), Observable.concat([ self.shotService.isLiked(shotID: self.shotID).asObservable().flatMap { _ in Observable.empty() }, self.shotService.comments(shotID: self.shotID).asObservable().map { Mutation.setComments($0.items) }, ]), ]) } } func reduce(state: State, mutation: Mutation) -> State { var state = state switch mutation { case let .setRefreshing(isRefreshing): state.isRefreshing = isRefreshing return state case let .setShot(shot): state.shotSectionReactor.action.onNext(.updateShot(shot)) return state case let .setComments(comments): state.commentSectionItems = comments .map(ShotViewCommentCellReactor.init) .map(ShotViewSectionItem.comment) return state } } func transform(state: Observable<State>) -> Observable<State> { return state.with(section: \.shotSectionReactor) } }
mit
7b4169ce5cce5eba1d77e86193e52af8
26.80198
111
0.680556
4.422047
false
false
false
false
warnerbros/cpe-manifest-ios-data
Source/TimedEvent.swift
1
10633
// // TimedEvent.swift // import Foundation import SWXMLHash /** Supported `TimedEvent` types - any: Event has any kind of item associated with it - appGroup: Event has an `AppGroup` associated with it - gallery: Event has a `Gallery` associated with it - video: Event has a `Presentation` associated with it - clipShare: Event is a `video` type with subtype `Shareable Clip` - location: Event has a `Location` associated with it - product: Event has a `ProductItem` associated with it - person: Event has a `Person` associated with it - textItem: Event has a `TextObject` associated with it */ public enum TimedEventType { case any case appGroup case gallery case video case clipShare case location case product case person case textItem } /** Checks the equality of two `TimedEvent` objects - Parameters - lhs: The first `TimedEvent` object to compare - rhs: The second `TimedEvent` object to compare - Returns: `true` if the `TimedEvent` objects have the same ID and start time */ public func == (lhs: TimedEvent, rhs: TimedEvent) -> Bool { return (lhs.id == rhs.id && lhs.startTime == rhs.startTime) } /// An event tied to a playback timecode open class TimedEvent: Equatable, Trackable { /// Supported XML attribute keys private struct Attributes { static let Index = "index" } /// Supported XML element tags private struct Elements { static let StartTimecode = "StartTimecode" static let EndTimecode = "EndTimecode" static let PresentationID = "PresentationID" static let PictureID = "PictureID" static let GalleryID = "GalleryID" static let AppGroupID = "AppGroupID" static let TextGroupID = "TextGroupID" static let ProductID = "ProductID" static let OtherID = "OtherID" static let Initialization = "Initialization" } /// Unique identifier public var id: String /// Start time of this event (in seconds) public var startTime: Double /// End time of this event (in seconds) public var endTime: Double /// ID for associated `Presentation` public var presentationID: String? /// ID for associated `Picture` public var pictureID: String? /// ID for associated `Gallery` public var galleryID: String? /// ID for associated `AppGroup` public var appGroupID: String? public var textGroupMappings: [(textGroupID: String, index: Int)]? /// ID for associated `ProductItem` public var productID: ContentIdentifier? /// ID for other associated content (e.g. Person) public var otherID: ContentIdentifier? /// ID for parent `Experience` public var experienceID: String? /// Tracking identifier open lazy var analyticsID: String = { [unowned self] in if let id = self.presentationID { return id } if let id = self.pictureID { return id } if let id = self.galleryID { return id } if let id = self.appGroupID { return id } if let id = self.productID?.identifier { return id } if let id = self.otherID?.identifier { return id } return self.id }() /// Parent `Experience` open var experience: Experience? { return CPEXMLSuite.current?.manifest.experienceWithID(experienceID) } /// Associated `ExperienceAudioVisual` (used for video clips) open lazy var audioVisual: ExperienceAudioVisual? = { [unowned self] in if let id = self.presentationID { return CPEXMLSuite.current?.manifest.presentationToAudioVisualMapping?[id] } return nil }() /// Associated `Picture` (used for single/supplemental image) open var picture: Picture? { return CPEXMLSuite.current?.manifest.pictureWithID(pictureID) } /// Associated `Gallery` (used for gallery of images) open var gallery: Gallery? { return CPEXMLSuite.current?.manifest.galleryWithID(galleryID) } /// Associated `AppGroup` (used for HTML5 apps) open var appGroup: AppGroup? { return CPEXMLSuite.current?.manifest.appGroupWithID(appGroupID) } /// Associated `Person` (used for talent details) open var person: Person? { if let otherID = otherID, otherID.namespace == Namespaces.PeopleID { return CPEXMLSuite.current?.manifest.personWithID(otherID.identifier) } return nil } /// Associated `AppDataItemLocation` (used for scene loations) open var location: AppDataItemLocation? { if let otherID = otherID, otherID.namespace == Namespaces.AppDataID { return CPEXMLSuite.current?.appData?.locationWithID(otherID.identifier) } return nil } /// Associated `AppDataItemProduct` (used for scene products) open var product: AppDataItemProduct? { if let otherID = otherID, otherID.namespace == Namespaces.AppDataID { return CPEXMLSuite.current?.appData?.productWithID(otherID.identifier) } return nil } /// Associated text item (used for trivia) open lazy var textItem: String? = { [unowned self] in if let textGroupMapping = self.textGroupMappings?.first { return CPEXMLSuite.current?.manifest.textGroupWithID(textGroupMapping.textGroupID)?.textObject?.textItem(textGroupMapping.index) } return nil }() /// Primary text of associated object open var description: String? { if isType(.textItem) { return textItem } return (gallery?.title ?? location?.title ?? audioVisual?.title) } /// Image URL of associated object open var imageURL: URL? { if isType(.clipShare) { return audioVisual?.metadata?.largeImageURL } return picture?.imageURL } /// Thumbnail image URL of associated object private var _thumbnailImageURL: URL? open var thumbnailImageURL: URL? { if _thumbnailImageURL == nil { if let url = gallery?.thumbnailImageURL { _thumbnailImageURL = url } else if let url = picture?.thumbnailImageURL { _thumbnailImageURL = url } else if let url = audioVisual?.thumbnailImageURL { _thumbnailImageURL = url } else if let url = location?.thumbnailImageURL { _thumbnailImageURL = url } else if let url = appGroup?.thumbnailImageURL { _thumbnailImageURL = url } } return (_thumbnailImageURL ?? imageURL) } /** Initializes a new event at the provided timecodes - Parameters - startTime: The start time, in seconds, of the event - endTime: The end time, in seconds, of the event */ init(startTime: Double, endTime: Double) { id = UUID().uuidString self.startTime = startTime self.endTime = endTime } /** Initializes a new event with the provided XML indexer - Parameter indexer: The root XML node - Throws: - `ManifestError.missingRequiredChildElement` if an expected XML element is not present */ init(indexer: XMLIndexer) throws { // Custom ID id = UUID().uuidString // StartTimecode guard let startTime: Double = try indexer[Elements.StartTimecode].value() else { throw ManifestError.missingRequiredChildElement(name: Elements.StartTimecode, element: indexer.element) } self.startTime = startTime // EndTimecode guard let endTime: Double = try indexer[Elements.EndTimecode].value() else { throw ManifestError.missingRequiredChildElement(name: Elements.EndTimecode, element: indexer.element) } self.endTime = endTime // PresentationID / PictureID / GalleryID / AppGroupID / TextGroupID / OtherID if indexer.hasElement(Elements.PresentationID) { presentationID = try indexer[Elements.PresentationID].value() } else if indexer.hasElement(Elements.PictureID) { pictureID = try indexer[Elements.PictureID].value() } else if indexer.hasElement(Elements.GalleryID) { galleryID = try indexer[Elements.GalleryID].value() } else if indexer.hasElement(Elements.AppGroupID) { appGroupID = try indexer[Elements.AppGroupID].value() } else if indexer.hasElement(Elements.TextGroupID) { var textGroupMappings = [(String, Int)]() for indexer in indexer[Elements.TextGroupID].all { if let textGroupID: String = try indexer.value(), let index: Int = indexer.value(ofAttribute: Attributes.Index) { textGroupMappings.append((textGroupID, index)) } } self.textGroupMappings = textGroupMappings } else if indexer.hasElement(Elements.ProductID) { productID = try indexer[Elements.ProductID].value() } else if indexer.hasElement(Elements.OtherID) { otherID = try indexer[Elements.OtherID].value() } // Initialization if pictureID == nil { // Making assumption that supplemental PictureID is in the Initialization property pictureID = try indexer[Elements.Initialization].value() } } /** Check if TimedEvent is of the specified type - Parameter type: Type of TimedEvent - Returns: `true` if the TimedEvent is of the specified type */ open func isType(_ type: TimedEventType) -> Bool { switch type { case .appGroup: return (appGroup != nil) case .video: return (audioVisual != nil) case .clipShare: return (experience?.isClipShareExperience ?? false) case .gallery: return (gallery != nil) case .location: return (location != nil) case .product: if let productAPIUtil = CPEXMLSuite.Settings.productAPIUtil, let productNamespace = productID?.namespace { return (productNamespace == Swift.type(of: productAPIUtil).APINamespace) } return (product != nil) case .person: return (person != nil) case .textItem: return (textItem != nil) case .any: return true } } }
apache-2.0
4f469d499d2ff28465c2950cc195c68c
30.181818
140
0.623248
4.884244
false
false
false
false
miracl/amcl
version3/swift/fp12.swift
1
22937
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // fp12.swift // // Created by Michael Scott on 07/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // /* AMCL Fp^12 functions */ /* FP12 elements are of the form a+i.b+i^2.c */ public struct FP12 { static public let ZERO:Int=0 static public let ONE:Int=1 static public let SPARSER:Int=2 static public let SPARSE:Int=3 static public let DENSE:Int=4 private var a:FP4 private var b:FP4 private var c:FP4 private var stype:Int /* reduce all components of this mod Modulus */ mutating func reduce() { a.reduce() b.reduce() c.reduce() } /* normalise all components of this */ mutating func norm() { a.norm() b.norm() c.norm() } mutating func settype(_ t:Int) { stype=t } mutating func gettype() -> Int { return stype } /* Constructors */ public init(_ d:FP4) { a=FP4(d) b=FP4() c=FP4() stype=FP12.SPARSER } public init() { a=FP4() b=FP4() c=FP4() stype=FP12.ZERO } public init(_ d:Int) { a=FP4(d) b=FP4() c=FP4() if (d==1) {stype=FP12.ONE} else {stype=FP12.SPARSER} } public init(_ d:FP4,_ e:FP4,_ f:FP4) { a=FP4(d) b=FP4(e) c=FP4(f) stype=FP12.DENSE } public init(_ x:FP12) { a=FP4(x.a) b=FP4(x.b) c=FP4(x.c) stype=x.stype } /* test x==0 ? */ public func iszilch() -> Bool { return a.iszilch() && b.iszilch() && c.iszilch() } mutating func cmove(_ g:FP12,_ d:Int) { a.cmove(g.a,d) b.cmove(g.b,d) c.cmove(g.c,d) let u = ~(d-1) stype^=(stype^g.stype)&u } /* return 1 if b==c, no branching */ private static func teq(_ b:Int32,_ c:Int32) -> Int { var x=b^c x-=1 // if x=0, x now -1 return Int((x>>31)&1) } /* Constant time select from pre-computed table */ mutating func select(_ g:[FP12],_ b:Int32) { let m=b>>31 var babs=(b^m)-m babs=(babs-1)/2 cmove(g[0],FP12.teq(babs,0)) // conditional move cmove(g[1],FP12.teq(babs,1)) cmove(g[2],FP12.teq(babs,2)) cmove(g[3],FP12.teq(babs,3)) cmove(g[4],FP12.teq(babs,4)) cmove(g[5],FP12.teq(babs,5)) cmove(g[6],FP12.teq(babs,6)) cmove(g[7],FP12.teq(babs,7)) var invf=FP12(self) invf.conj() cmove(invf,Int(m&1)) } /* test x==1 ? */ public func isunity() -> Bool { let one=FP4(1) return a.equals(one) && b.iszilch() && c.iszilch() } /* return 1 if x==y, else 0 */ public func equals(_ x:FP12) -> Bool { return a.equals(x.a) && b.equals(x.b) && c.equals(x.c) } /* extract a from self */ func geta() -> FP4 { return a } /* extract b */ func getb() -> FP4 { return b } /* extract c */ func getc() -> FP4 { return c } /* copy self=x */ public mutating func copy(_ x:FP12) { a.copy(x.a) b.copy(x.b) c.copy(x.c) stype=x.stype } /* set self=1 */ mutating public func one() { a.one() b.zero() c.zero() stype=FP12.ONE } /* set self=0 */ mutating public func zero() { a.zero() b.zero() c.zero() stype=FP12.ZERO } /* self=conj(self) */ mutating public func conj() { a.conj() b.nconj() c.conj() } /* Granger-Scott Unitary Squaring */ mutating public func usqr() { var A=FP4(a) var B=FP4(c) var C=FP4(b) var D=FP4() a.sqr() D.copy(a); D.add(a) a.add(D) a.norm() A.nconj() A.add(A) a.add(A) B.sqr() B.times_i() D.copy(B); D.add(B) B.add(D) B.norm() C.sqr() D.copy(C); D.add(C) C.add(D) C.norm() b.conj() b.add(b) c.nconj() c.add(c) b.add(B) c.add(C) stype=FP12.DENSE reduce() } /* Chung-Hasan SQR2 method from http://cacr.uwaterloo.ca/techreports/2006/cacr2006-24.pdf */ mutating public func sqr() { if (stype==FP12.ONE) {return} var A=FP4(a) var B=FP4(b) var C=FP4(c) var D=FP4(a) A.sqr() B.mul(c) B.add(B); B.norm() C.sqr() D.mul(b) D.add(D) c.add(a) c.add(b); c.norm() c.sqr() a.copy(A) A.add(B) A.norm() A.add(C) A.add(D) A.norm() A.neg() B.times_i() C.times_i() a.add(B) b.copy(C); b.add(D) c.add(A) if (stype==FP12.SPARSER) { stype=FP12.SPARSE } else { stype=FP12.DENSE } norm() } /* FP12 full multiplication this=this*y */ mutating public func mul(_ y:FP12) { var z0=FP4(a) var z1=FP4() var z2=FP4(b) var z3=FP4() var t0=FP4(a) var t1=FP4(y.a) z0.mul(y.a) z2.mul(y.b) t0.add(b) t1.add(y.b) t0.norm(); t1.norm() z1.copy(t0); z1.mul(t1) t0.copy(b); t0.add(c) t1.copy(y.b); t1.add(y.c) t0.norm(); t1.norm() z3.copy(t0); z3.mul(t1) t0.copy(z0); t0.neg() t1.copy(z2); t1.neg() z1.add(t0) b.copy(z1); b.add(t1) z3.add(t1) z2.add(t0) t0.copy(a); t0.add(c) t1.copy(y.a); t1.add(y.c) t0.norm(); t1.norm() t0.mul(t1) z2.add(t0) t0.copy(c); t0.mul(y.c) t1.copy(t0); t1.neg() c.copy(z2); c.add(t1) z3.add(t1) t0.times_i() b.add(t0) z3.norm() z3.times_i() a.copy(z0); a.add(z3) stype=FP12.DENSE norm() } /* FP12 full multiplication w=w*y */ /* Supports sparse multiplicands */ /* Usually w is denser than y */ mutating func ssmul(_ y:FP12) { if stype==FP12.ONE { copy(y) return } if y.stype==FP12.ONE { return } if y.stype>=FP12.SPARSE { var z0=FP4(a) var z1=FP4() var z2=FP4() var z3=FP4() z0.mul(y.a) if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.M_TYPE { if y.stype==FP12.SPARSE || stype==FP12.SPARSE { var ga=FP2() var gb=FP2() gb.copy(b.getb()) gb.mul(y.b.getb()) ga.zero() if y.stype != FP12.SPARSE { ga.copy(b.getb()) ga.mul(y.b.geta()) } if stype != FP12.SPARSE { ga.copy(b.geta()) ga.mul(y.b.getb()) } z2.set_fp2s(ga,gb) z2.times_i() } else { z2.copy(b) z2.mul(y.b) } } else { z2.copy(b) z2.mul(y.b) } var t0=FP4(a) var t1=FP4(y.a) t0.add(b); t0.norm() t1.add(y.b); t1.norm() z1.copy(t0); z1.mul(t1) t0.copy(b); t0.add(c); t0.norm() t1.copy(y.b); t1.add(y.c); t1.norm() z3.copy(t0); z3.mul(t1) t0.copy(z0); t0.neg() t1.copy(z2); t1.neg() z1.add(t0) b.copy(z1); b.add(t1) z3.add(t1) z2.add(t0) t0.copy(a); t0.add(c); t0.norm() t1.copy(y.a); t1.add(y.c); t1.norm() t0.mul(t1) z2.add(t0) if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.D_TYPE { if y.stype==FP12.SPARSE || stype==FP12.SPARSE { var ga=FP2() var gb=FP2() ga.copy(c.geta()) ga.mul(y.c.geta()) gb.zero() if y.stype != FP12.SPARSE { gb.copy(c.geta()) gb.mul(y.c.getb()) } if stype != FP12.SPARSE { gb.copy(c.getb()) gb.mul(y.c.geta()) } t0.set_fp2s(ga,gb) } else { t0.copy(c) t0.mul(y.c) } } else { t0.copy(c) t0.mul(y.c) } t1.copy(t0); t1.neg() c.copy(z2); c.add(t1) z3.add(t1) t0.times_i() b.add(t0) z3.norm() z3.times_i() a.copy(z0); a.add(z3); } else { if stype==FP12.SPARSER { smul(y) return } if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.D_TYPE { // dense by sparser - 13m var z0=FP4(a) var z2=FP4(b) var z3=FP4(b) var t0=FP4() var t1=FP4(y.a) z0.mul(y.a) z2.pmul(y.b.real()) b.add(a) t1.adds(y.b.real()) t1.norm() b.norm() b.mul(t1) z3.add(c) z3.norm() z3.pmul(y.b.real()) t0.copy(z0); t0.neg() t1.copy(z2); t1.neg() b.add(t0) b.add(t1) z3.add(t1) z2.add(t0) t0.copy(a); t0.add(c); t0.norm() z3.norm() t0.mul(y.a) c.copy(z2); c.add(t0) z3.times_i() a.copy(z0); a.add(z3) } if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.M_TYPE { var z0=FP4(a) var z1=FP4() var z2=FP4() var z3=FP4() var t0=FP4(a) var t1=FP4() z0.mul(y.a) t0.add(b); t0.norm() z1.copy(t0); z1.mul(y.a) t0.copy(b); t0.add(c) t0.norm() z3.copy(t0) z3.pmul(y.c.getb()) z3.times_i() t0.copy(z0); t0.neg() z1.add(t0) b.copy(z1) z2.copy(t0) t0.copy(a); t0.add(c); t0.norm() t1.copy(y.a); t1.add(y.c); t1.norm() t0.mul(t1) z2.add(t0) t0.copy(c) t0.pmul(y.c.getb()) t0.times_i() t1.copy(t0); t1.neg() c.copy(z2); c.add(t1) z3.add(t1) t0.times_i() b.add(t0) z3.norm() z3.times_i() a.copy(z0); a.add(z3) } } stype=FP12.DENSE norm() } /* Special case of multiplication arises from special form of ATE pairing line function */ mutating func smul(_ y:FP12) { if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.D_TYPE { var w1=FP2(a.geta()) var w2=FP2(a.getb()) var w3=FP2(b.geta()) w1.mul(y.a.geta()) w2.mul(y.a.getb()) w3.mul(y.b.geta()) var ta=FP2(a.geta()) var tb=FP2(y.a.geta()) ta.add(a.getb()); ta.norm() tb.add(y.a.getb()); tb.norm() var tc=FP2(ta) tc.mul(tb) var t=FP2(w1) t.add(w2) t.neg() tc.add(t) ta.copy(a.geta()); ta.add(b.geta()); ta.norm() tb.copy(y.a.geta()); tb.add(y.b.geta()); tb.norm() var td=FP2(ta) td.mul(tb) t.copy(w1) t.add(w3) t.neg() td.add(t) ta.copy(a.getb()); ta.add(b.geta()); ta.norm() tb.copy(y.a.getb()); tb.add(y.b.geta()); tb.norm() var te=FP2(ta) te.mul(tb) t.copy(w2) t.add(w3) t.neg() te.add(t) w2.mul_ip() w1.add(w2) a.set_fp2s(w1,tc) b.set_fp2s(td,te) c.set_fp2(w3) a.norm() b.norm() } else { var w1=FP2(a.geta()) var w2=FP2(a.getb()) var w3=FP2(c.getb()) w1.mul(y.a.geta()) w2.mul(y.a.getb()) w3.mul(y.c.getb()) var ta=FP2(a.geta()) var tb=FP2(y.a.geta()) ta.add(a.getb()); ta.norm() tb.add(y.a.getb()); tb.norm() var tc=FP2(ta) tc.mul(tb) var t=FP2(w1) t.add(w2) t.neg() tc.add(t) ta.copy(a.geta()); ta.add(c.getb()); ta.norm() tb.copy(y.a.geta()); tb.add(y.c.getb()); tb.norm() var td=FP2(ta) td.mul(tb) t.copy(w1) t.add(w3) t.neg() td.add(t) ta.copy(a.getb()); ta.add(c.getb()); ta.norm() tb.copy(y.a.getb()); tb.add(y.c.getb()); tb.norm() var te=FP2(ta) te.mul(tb) t.copy(w2) t.add(w3) t.neg() te.add(t) w2.mul_ip() w1.add(w2) a.set_fp2s(w1,tc); w3.mul_ip() w3.norm() b.set_fp2h(w3); te.norm() te.mul_ip() c.set_fp2s(te,td) a.norm() c.norm() } stype=FP12.SPARSE } /* self=1/self */ mutating public func inverse() { var f0=FP4(a) var f1=FP4(b) var f2=FP4(a) var f3=FP4() norm() f0.sqr() f1.mul(c) f1.times_i() f0.sub(f1); f0.norm() f1.copy(c); f1.sqr() f1.times_i() f2.mul(b) f1.sub(f2); f1.norm() f2.copy(b); f2.sqr() f3.copy(a); f3.mul(c) f2.sub(f3); f2.norm() f3.copy(b); f3.mul(f2) f3.times_i() a.mul(f0) f3.add(a) c.mul(f1) c.times_i() f3.add(c); f3.norm() f3.inverse() a.copy(f0); a.mul(f3) b.copy(f1); b.mul(f3) c.copy(f2); c.mul(f3) stype=FP12.DENSE } /* self=self^p using Frobenius */ mutating func frob(_ f:FP2) { var f2=FP2(f) var f3=FP2(f) f2.sqr() f3.mul(f2) a.frob(f3) b.frob(f3) c.frob(f3) b.pmul(f) c.pmul(f2) stype=FP12.DENSE } /* trace function */ func trace() -> FP4 { var t=FP4() t.copy(a) t.imul(3) t.reduce() return t } /* convert from byte array to FP12 */ public static func fromBytes(_ w:[UInt8]) -> FP12 { let RM=Int(CONFIG_BIG.MODBYTES) var t=[UInt8](repeating: 0,count: RM) for i in 0 ..< RM {t[i]=w[i]} var a=BIG.fromBytes(t) for i in 0 ..< RM {t[i]=w[i+RM]} var b=BIG.fromBytes(t) var c=FP2(a,b) for i in 0 ..< RM {t[i]=w[i+2*RM]} a=BIG.fromBytes(t) for i in 0 ..< RM {t[i]=w[i+3*RM]} b=BIG.fromBytes(t) var d=FP2(a,b) let e=FP4(c,d) for i in 0 ..< RM {t[i]=w[i+4*RM]} a=BIG.fromBytes(t) for i in 0 ..< RM {t[i]=w[i+5*RM]} b=BIG.fromBytes(t) c=FP2(a,b) for i in 0 ..< RM {t[i]=w[i+6*RM]} a=BIG.fromBytes(t) for i in 0 ..< RM {t[i]=w[i+7*RM]} b=BIG.fromBytes(t) d=FP2(a,b) let f=FP4(c,d) for i in 0 ..< RM {t[i]=w[i+8*RM]} a=BIG.fromBytes(t) for i in 0 ..< RM {t[i]=w[i+9*RM]} b=BIG.fromBytes(t) c=FP2(a,b) for i in 0 ..< RM {t[i]=w[i+10*RM]} a=BIG.fromBytes(t) for i in 0 ..< RM {t[i]=w[i+11*RM]} b=BIG.fromBytes(t); d=FP2(a,b) let g=FP4(c,d) return FP12(e,f,g) } /* convert this to byte array */ public func toBytes(_ w:inout [UInt8]) { let RM=Int(CONFIG_BIG.MODBYTES) var t=[UInt8](repeating: 0,count: RM) a.geta().getA().toBytes(&t) for i in 0 ..< RM {w[i]=t[i]} a.geta().getB().toBytes(&t) for i in 0 ..< RM {w[i+RM]=t[i]} a.getb().getA().toBytes(&t) for i in 0 ..< RM {w[i+2*RM]=t[i]} a.getb().getB().toBytes(&t) for i in 0 ..< RM {w[i+3*RM]=t[i]} b.geta().getA().toBytes(&t) for i in 0 ..< RM {w[i+4*RM]=t[i]} b.geta().getB().toBytes(&t); for i in 0 ..< RM {w[i+5*RM]=t[i]} b.getb().getA().toBytes(&t) for i in 0 ..< RM {w[i+6*RM]=t[i]} b.getb().getB().toBytes(&t) for i in 0 ..< RM {w[i+7*RM]=t[i]} c.geta().getA().toBytes(&t) for i in 0 ..< RM {w[i+8*RM]=t[i]} c.geta().getB().toBytes(&t) for i in 0 ..< RM {w[i+9*RM]=t[i]} c.getb().getA().toBytes(&t) for i in 0 ..< RM {w[i+10*RM]=t[i]} c.getb().getB().toBytes(&t) for i in 0 ..< RM {w[i+11*RM]=t[i]} } /* convert to hex string */ public func toString() -> String { return ("["+a.toString()+","+b.toString()+","+c.toString()+"]") } /* self=self^e */ /* Note this is simple square and multiply, so not side-channel safe */ public func pow(_ e:BIG) -> FP12 { var sf = FP12(self) sf.norm() //e.norm() var e1=BIG(e) e1.norm() var e3=BIG(e1) e3.pmul(3) e3.norm(); var w=FP12(sf) let nb=e3.nbits() for i in (1...nb-2).reversed() { w.usqr() let bt=e3.bit(UInt(i))-e1.bit(UInt(i)) if bt == 1 { w.mul(sf) } if bt == -1 { sf.conj(); w.mul(sf); sf.conj() } } w.reduce() return w } /* constant time powering by small integer of max length bts */ mutating public func pinpow(_ e:Int32,_ bts:Int32) { var R=[FP12]() R.append(FP12(1)) R.append(FP12(self)) for i in (0...bts-1).reversed() { let b=Int((e>>i)&1) R[1-b].mul(R[b]) R[b].usqr() } copy(R[0]) } public func compow(_ e :BIG,_ r :BIG) -> FP4 { let f=FP2(BIG(ROM.Fra),BIG(ROM.Frb)) let q=BIG(ROM.Modulus) var g1=FP12(self) var g2=FP12(self) var m=BIG(q) m.mod(r) var a=BIG(e) a.mod(m) var b=BIG(e) b.div(m); var c=g1.trace() if b.iszilch() { c=c.xtr_pow(e) return c } g2.frob(f) let cp=g2.trace() g1.conj() g2.mul(g1) let cpm1=g2.trace() g2.mul(g1) let cpm2=g2.trace() c=c.xtr_pow2(cp,cpm1,cpm2,a,b) return c } /* P=u0.Q0+u1*Q1+u2*Q2+u3*Q3 */ // Bos & Costello https://eprint.iacr.org/2013/458.pdf // Faz-Hernandez & Longa & Sanchez https://eprint.iacr.org/2013/158.pdf // Side channel attack secure static public func pow4(_ q:[FP12],_ u:[BIG]) -> FP12 { var g=[FP12](); for _ in 0 ..< 8 {g.append(FP12())} var r=FP12() var p=FP12() var t=[BIG]() for i in 0 ..< 4 { t.append(BIG(u[i])) t[i].norm() } var mt=BIG(0); var w=[Int8](repeating: 0,count: CONFIG_BIG.NLEN*Int(CONFIG_BIG.BASEBITS)+1) var s=[Int8](repeating: 0,count: CONFIG_BIG.NLEN*Int(CONFIG_BIG.BASEBITS)+1) // precompute table g[0].copy(q[0]) // q[0] g[1].copy(g[0]); g[1].mul(q[1]) // q[0].q[1] g[2].copy(g[0]); g[2].mul(q[2]) // q[0].q[2] g[3].copy(g[1]); g[3].mul(q[2]) // q[0].q[1].q[2] g[4].copy(g[0]); g[4].mul(q[3]) // q[0].q[3] g[5].copy(g[1]); g[5].mul(q[3]) // q[0].q[1].q[3] g[6].copy(g[2]); g[6].mul(q[3]) // q[0].q[2].q[3] g[7].copy(g[3]); g[7].mul(q[3]) // q[0].q[1].q[2].q[3] // Make it odd let pb=1-t[0].parity() t[0].inc(pb) t[0].norm() // Number of bits mt.zero(); for i in 0 ..< 4 { mt.or(t[i]); } let nb=1+mt.nbits() // Sign pivot s[nb-1]=1 for i in 0 ..< nb-1 { t[0].fshr(1) s[i]=2*Int8(t[0].parity())-1 } // Recoded exponent for i in 0 ..< nb { w[i]=0 var k=1 for j in 1 ..< 4 { let bt=s[i]*Int8(t[j].parity()) t[j].fshr(1) t[j].dec(Int(bt>>1)) t[j].norm() w[i]+=bt*Int8(k) k=2*k } } // Main loop p.select(g,Int32(2*w[nb-1]+1)) for i in (0 ..< nb-1).reversed() { p.usqr() r.select(g,Int32(2*w[i]+s[i])) p.mul(r) } // apply correction r.copy(q[0]); r.conj() r.mul(p) p.cmove(r,pb) p.reduce() return p } }
apache-2.0
06101f36e6e620821c88488c4b8e00fb
22.381244
96
0.403976
2.969191
false
false
false
false
smbarne/AndroidForiOS
iOS-Swift/AndroidForiOS/Cells/SubwayTripTableViewCell.swift
1
770
// // SubwayTripTableViewCell.swift // AndroidForiOS // // Created by Stephen Barnes on 7/27/15. // Copyright © 2015 Stephen Barnes. All rights reserved. // import UIKit class SubwayTripTableViewCell : UITableViewCell { @IBOutlet weak var destinationLabel: UILabel! @IBOutlet weak var trainNameLabel: UILabel! @IBOutlet weak var timestampLabel: UILabel! func updateCell(trip:Trip) { self.destinationLabel.text = trip.destination self.trainNameLabel.text = trip.trainName if let positionTimeStamp = trip.positionTimeStamp { self.timestampLabel.text = DataManager.dataDateFormatter.stringFromDate(positionTimeStamp) } else { self.timestampLabel.text = nil } } }
mit
e2f59018cbe63e8ce8dc600d39659ee8
27.481481
102
0.684005
4.497076
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/templates/UserTemplates.swift
1
1112
// swiftlint:disable line_length import Prelude extension User { internal static let template = User( avatar: .template, facebookConnected: nil, id: 1, isFriend: nil, liveAuthToken: "deadbeef", location: nil, name: "Blob", newsletters: .template, notifications: .template, social: nil, stats: .template ) internal static let brando = .template |> User.lens.avatar.large .~ "https://ksr-ugc.imgix.net/assets/006/258/518/b9033f46095b83119188cf9a66d19356_original.jpg?w=160&h=160&fit=crop&v=1461376829&auto=format&q=92&s=8d7666f01ab6765c3cf09149751ff077" |> User.lens.avatar.medium .~ "https://ksr-ugc.imgix.net/assets/006/258/518/b9033f46095b83119188cf9a66d19356_original.jpg?w=40&h=40&fit=crop&v=1461376829&auto=format&q=92&s=0fcedf8888ca6990408ccde81888899b" |> User.lens.avatar.small .~ "https://ksr-ugc.imgix.net/assets/006/258/518/b9033f46095b83119188cf9a66d19356_original.jpg?w=40&h=40&fit=crop&v=1461376829&auto=format&q=92&s=0fcedf8888ca6990408ccde81888899b" |> User.lens.id .~ "brando".hash |> User.lens.name .~ "Brandon Williams" }
apache-2.0
b1c01c864ef8f8040d30260cbae7698d
43.48
211
0.728417
2.732187
false
false
false
false
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/Extensions/UITextFieldExtension.swift
1
2496
// // UITextFieldExtension.swift // Pods // // Created by MacMini-2 on 04/09/17. // // import Foundation #if os(macOS) import Cocoa #else import UIKit #endif public extension UITextField { /// UITextField text type. /// /// - emailAddress: UITextField is used to enter email addresses. /// - password: UITextField is used to enter passwords. /// - generic: UITextField is used to enter generic text. enum TextType { case emailAddress case password case generic } /// Set textField for common text types. var textType: TextType { get { if keyboardType == .emailAddress { return .emailAddress } else if isSecureTextEntry { return .password } return .generic } set { switch newValue { case .emailAddress: keyboardType = .emailAddress autocorrectionType = .no autocapitalizationType = .none isSecureTextEntry = false case .password: keyboardType = .asciiCapable autocorrectionType = .no autocapitalizationType = .none isSecureTextEntry = true case .generic: isSecureTextEntry = false } } } var fontSize: CGFloat { get { return self.font?.pointSize ?? 17 } set { self.font = UIFont.systemFont(ofSize: newValue) } } /// Add left padding to the text in textfield func addLeftTextPadding(_ blankSize: CGFloat) { let leftView = UIView() leftView.frame = CGRect(x: 0, y: 0, width: blankSize, height: frame.height) self.leftView = leftView self.leftViewMode = UITextField.ViewMode.always } /// Add a image icon on the left side of the textfield func addLeftIcon(_ image: UIImage?, frame: CGRect, imageSize: CGSize) { let leftView = UIView(frame: frame) let imgView = UIImageView() imgView.frame = CGRect(x: frame.width - 8 - imageSize.width, y: (frame.height - imageSize.height) / 2, width: imageSize.width, height: imageSize.height) imgView.image = image leftView.addSubview(imgView) self.leftView = leftView self.leftViewMode = UITextField.ViewMode.always } }
mit
ccb78c270fa53994e75e61f887782742
27.689655
160
0.558093
5.221757
false
false
false
false
mikelikespie/swiftled
src/main/swift/Swiftlights/RootViewController.swift
1
1243
// // ViewController.swift // SwiftledMobile // // Created by Michael Lewis on 12/29/15. // Copyright © 2015 Lolrus Industries. All rights reserved. // import UIKit import RxSwift //import RxCocoa import Foundation import Fixtures import Cleanse import yoga_YogaKit import Views import RxSwift class RootViewController: UIViewController { let disposeBag = DisposeBag() private var typedView: ContentView { return scrollView.container } let rootView: Provider<RootView> init(rootView: Provider<RootView>) { self.rootView = rootView super.init(nibName: nil, bundle: nil) self.title = "Swiftlights" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var scrollView: YogaScrollView = self.rootView.get() override func loadView() { self.view = scrollView } override func viewDidLoad() { super.viewDidLoad() typedView.frame = CGRect(x: 0, y: 0, width: 100, height: 100) scrollView.addSubview(typedView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } }
mit
bc2e256769296ff6850b4a665c61b638
22
69
0.648953
4.483755
false
false
false
false
siutsin/fish
RingMDFish/ViewController.swift
1
4553
// // ViewController.swift // RingMDFish // // Created by simon on 18/11/2015. // Copyright © 2015 Simon Li. All rights reserved. // import UIKit import Dollar class ViewController: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var lake: UIView! @IBOutlet weak var controlPanel: UIView! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var feedButton: UIButton! var scene = Scene() private var autoFeeder: AutoFeeder? private var time: Int = 0 private var notifierRecord = Dictionary<String, FishView>() deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() self.view.setNeedsLayout() self.view.layoutIfNeeded() self.populateFishes() self.startWorld() NSNotificationCenter.defaultCenter().addObserver(self, selector:"oneSecondPassed", name: Event.OneSecondPassed.rawValue, object: nil) self.autoFeeder = AutoFeeder(viewController: self) if !self.autoFeeder!.isAutoFeederEnabled() { self.autoFeeder!.enableAutoFeeder() } } // MARK: Public @IBAction func onClickedFeed(sender: AnyObject) { self.feedButton.enabled = false NSNotificationCenter.defaultCenter().postNotificationName(Event.Feed.rawValue, object: self, userInfo: nil) self.scene.startFeedTimer { [unowned self] (foodLeft, feedCount) -> () in // After farmer drops the pakage of food into the lake, he can not drop it again immediately, need a N in seconds for the food M to be full again. if self.scene.isOkToFeed() || (feedCount <= 1) { self.feedButton.enabled = true } } } // Could drop another fish of existing kind in to the lake. // Could drop another kind of fish kind in to the lake. @IBAction func onClickedAlewife(sender: AnyObject) { self.addFish(FishType.Alewife.rawValue) } @IBAction func onClickedBetta(sender: AnyObject) { self.addFish(FishType.Betta.rawValue) } @IBAction func onClickedCodlet(sender: AnyObject) { self.addFish(FishType.Codlet.rawValue) } @IBAction func onClickedDory(sender: AnyObject) { self.addFish(FishType.Dory.rawValue) } @IBAction func onClickedEagleRay(sender: AnyObject) { self.addFish(FishType.EagleRay.rawValue) } @IBAction func onClickedFirefish(sender: AnyObject) { self.addFish(FishType.Firefish.rawValue) } // MARK: Private @objc private func oneSecondPassed() { self.updateStatus() } private func addFish(fishType: String) { var isNotifier = false if notifierRecord[fishType] == nil { // There is only one randomize fish of each Kind should know. isNotifier = true } let fishView = FishView(lakeFrame: self.lake!.bounds, fishType: fishType, isNotifier: isNotifier, biteCallback: { [unowned self] (amount: Float) -> Bool in let biteResult = self.scene.consumeFood(amount) return biteResult }, notifierDiedCallback: { [unowned self] (fishType: String) -> () in self.notifierRecord.removeValueForKey(fishType) print("notifierRecord: \($.keys(self.notifierRecord))") }) self.lake!.addSubview(fishView) if isNotifier { notifierRecord[(fishView.fish?.getClassName())!] = fishView } } private func populateFishes() { // Randomize the initialization number of each kind of fish 5 < number_of_fishes_in_kind < 10. for var i = 0; i < FishType.allValues.count; i++ { let type = FishType.allValues[i].rawValue let randomInitNumberOfFish = scene.getInitRandomNumberForPopulatingFishes() for var j = 0; j < randomInitNumberOfFish; j++ { self.addFish(type) } } } private func startWorld() { self.scene.startWorldTimer { [unowned self] () -> () in NSNotificationCenter.defaultCenter().postNotificationName(Event.OneSecondPassed.rawValue, object: self, userInfo: nil) self.time++ self.timeLabel.text = String(self.time) } } private func updateStatus() { self.statusLabel.text = "M: \(Int(self.scene.getCurrentFood()))" } }
mit
d832edcb21cf39a2705dfd5427ca0dfc
33.484848
158
0.627636
4.471513
false
false
false
false
nkirby/Humber
_lib/HMGithub/_src/API/GithubAPI.swift
1
4869
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import Janus import Alamofire import ReactiveCocoa import HMCore // ======================================================= public enum GithubAPIError: ErrorType { case NotLoggedIn case RequestError case InvalidResponse case Unknown } public class GithubAPI: NSObject { private let manager = Alamofire.Manager() private let userID: String private let token: GithubOAuthToken public init?(context: ServiceContext) { let query = GithubKeychainStoreQuery() guard context.userIdentifier != "anon", let dict = KeychainStore().keychainItem(query: query), let token = GithubOAuthToken(keychainItem: dict) else { return nil } self.userID = context.userIdentifier self.token = token super.init() self.setupManager() } private func setupManager() { } // ======================================================= // MARK: - Generation private func request(method method: Alamofire.Method, endpoint: String, parameters: [String: AnyObject]?) -> SignalProducer<Alamofire.Request, GithubAPIError> { return SignalProducer { observer, disposable in if Config.routerLogging { print("\(method): \(endpoint)") } let headers = [ "Accept": "application/vnd.github.v3+json", "Authorization": "token \(self.token.accessToken)" ] let url = "https://api.github.com" + endpoint let request = Alamofire.Manager.sharedInstance.request(method, url, parameters: parameters, encoding: ParameterEncoding.URL, headers: headers) observer.sendNext(request) observer.sendCompleted() } } private func enqueue(request request: Alamofire.Request) -> SignalProducer<AnyObject, GithubAPIError> { return SignalProducer { observer, disposable in request.responseJSON { response in switch response.result { case .Success(let value): observer.sendNext(value) observer.sendCompleted() return default: break } observer.sendFailed(.RequestError) } disposable.addDisposable { request.cancel() } } } private func parse<T: JSONDecodable>(response response: AnyObject, toType type: T.Type) -> SignalProducer<T, GithubAPIError> { return SignalProducer { observer, disposable in if let dict = response as? JSONDictionary, let obj = JSONParser.model(type).from(dict) { observer.sendNext(obj) observer.sendCompleted() } else { observer.sendFailed(.InvalidResponse) } } } private func parseFeed<T: JSONDecodable>(response response: AnyObject, toType type: T.Type) -> SignalProducer<[T], GithubAPIError> { return SignalProducer { observer, disposable in if let arr = response as? JSONArray, let feed = JSONParser.models(type).from(arr) { observer.sendNext(feed) observer.sendCompleted() } else { observer.sendFailed(.InvalidResponse) } } } // ======================================================= // MARK: - Request Performing public func enqueueOnly(request request: GithubRequest) -> SignalProducer<AnyObject, GithubAPIError> { return self.request(method: request.method, endpoint: request.endpoint, parameters: request.parameters) .flatMap(.Latest) { self.enqueue(request: $0) } } public func enqueueAndParse<T: JSONDecodable>(request request: GithubRequest, toType type: T.Type) -> SignalProducer<T, GithubAPIError> { return self.request(method: request.method, endpoint: request.endpoint, parameters: request.parameters) .flatMap(.Latest) { self.enqueue(request: $0) } .flatMap(.Latest) { self.parse(response: $0, toType: type) } } public func enqueueAndParseFeed<T: JSONDecodable>(request request: GithubRequest, toType type: T.Type) -> SignalProducer<[T], GithubAPIError> { return self.request(method: request.method, endpoint: request.endpoint, parameters: request.parameters) .flatMap(.Latest) { self.enqueue(request: $0) } .flatMap(.Latest) { self.parseFeed(response: $0, toType: type) } } }
mit
6b14ca63ed5573a99d6eca1a8458cc6a
35.886364
164
0.561101
5.470787
false
false
false
false
caoimghgin/HexKit
Pod/Classes/Transit.swift
1
5161
// // Transit.swift // https://github.com/caoimghgin/HexKit // // Copyright © 2015 Kevin Muldoon. // // This code is distributed under the terms and conditions of the MIT license. // // 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. // class Transit { enum Direction : Int { case N case NE case SE case S case SW case NW case Unknown } enum State : Int { case Allowed case InsufficiantMovementPoints case MaximumMovementReached case Unexpected } var unit = Unit() var departing = Tile() var itinerary = [Tile]() var moves = 0 var path = CGPathCreateMutable() var line = CAShapeLayer.init() internal init() {} internal init(tile:Tile) { self.unit = tile.units.first! self.unit.superview!.bringSubviewToFront(self.unit) self.moves = self.unit.movementRemaining line.fillColor = UIColor.clearColor().CGColor line.strokeColor = UIColor.redColor().CGColor line.opacity = 0.8 line.lineWidth = 18 line.lineJoin = kCALineJoinRound line.lineCap = kCALineCapRound self.departing = tile self.transit(tile) } internal func departure(departing:Tile) { self.departing = departing } internal func transit(tile:Tile) -> State { if (!itinerary.contains(tile)) && (moves > 0) { print(arrivingDirection(departing:self.departing, arriving:tile)) self.itinerary.append(tile) CGPathMoveToPoint(path, nil, CGFloat(departing.center.x), CGFloat(departing.center.y)) for foo in itinerary { CGPathAddLineToPoint(path, nil, CGFloat(foo.center.x), CGFloat(foo.center.y)) line.path = path } if (tile !== self.departing) {self.moves--} return State.Allowed } else if (itinerary.contains(tile)) { if (itinerary.last !== tile) { itinerary.removeLast() self.moves++ path = CGPathCreateMutable() var index = 0 for destination in itinerary { if (index == 0) { path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, CGFloat(destination.center.x), CGFloat(destination.center.y)) } else { CGPathAddLineToPoint(path, nil, CGFloat(destination.center.x), CGFloat(destination.center.y)) } line.path = path index++ } return State.Allowed } return State.Unexpected } else if (tile === self.departing) { print("CONTAINS DEPARTING HEX") return State.Unexpected } else if !(moves > 0) { print("Count move error HEX") return State.Unexpected } else { return State.Unexpected } } internal func arrival(arriving:Tile) { self.itinerary.append(arriving) } func end() { path = CGPathCreateMutable() line.path = path } func arrivingDirection(departing departing:Tile, arriving:Tile) -> Direction { let cubeDelta = Cube( x:departing.cube.x - arriving.cube.x, y:departing.cube.y - arriving.cube.y, z:departing.cube.z - arriving.cube.z ) for i in 0..<HexKit.sharedInstance.directions.count { if (HexKit.sharedInstance.directions[i] == cubeDelta) { return Direction(rawValue: i)!} } return Direction.Unknown } }
mit
d7660093e5d4201f2d4443bb8bf6747e
29.898204
117
0.554264
5.048924
false
false
false
false
Erin-Mounts/BridgeAppSDK
BridgeAppSDK/SBAConsentSection.swift
1
4872
// // SBAConsentSection.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit public protocol SBAConsentSection: class { var sectionType: ORKConsentSectionType { get } var sectionTitle: String? { get } var sectionFormalTitle: String? { get } var sectionSummary: String? { get } var sectionContent: String? { get } var sectionHtmlContent: String? { get } var sectionLearnMoreButtonTitle: String? { get } var sectionCustomImage: UIImage? { get } var sectionCustomAnimationURL: NSURL? { get } } extension SBAConsentSection { func createConsentSection() -> ORKConsentSection { let section = ORKConsentSection(type: self.sectionType) section.title = self.sectionTitle section.formalTitle = self.sectionFormalTitle section.summary = self.sectionSummary section.content = self.sectionContent section.htmlContent = self.sectionHtmlContent section.customImage = self.sectionCustomImage section.customAnimationURL = self.sectionCustomAnimationURL section.customLearnMoreButtonTitle = self.sectionLearnMoreButtonTitle return section } } extension NSDictionary: SBAConsentSection { public var sectionType: ORKConsentSectionType { guard let sectionType = self["sectionType"] as? String else { return .Custom } switch (sectionType) { case "overview" : return .Overview case "privacy" : return .Privacy case "dataGathering" : return .DataGathering case "dataUse" : return .DataUse case "timeCommitment" : return .TimeCommitment case "studySurvey" : return .StudySurvey case "studyTasks" : return .StudyTasks case "withdrawing" : return .Withdrawing case "onlyInDocument" : return .OnlyInDocument default : return .Custom } } public var sectionTitle: String? { return self["sectionTitle"] as? String } public var sectionFormalTitle: String? { return self["sectionFormalTitle"] as? String } public var sectionSummary: String? { return self["sectionSummary"] as? String } public var sectionContent: String? { return self["sectionContent"] as? String } public var sectionLearnMoreButtonTitle: String? { return self["sectionLearnMoreButtonTitle"] as? String } public var sectionHtmlContent: String? { guard let htmlContent = self["sectionHtmlContent"] as? String else { return nil } return SBAResourceFinder().htmlNamed(htmlContent) } public var sectionCustomImage: UIImage? { guard let imageNamed = self["sectionImage"] as? String else { return nil } return SBAResourceFinder().imageNamed(imageNamed) } public var sectionCustomAnimationURL: NSURL? { guard let resource = self["sectionAnimationUrl"] as? String else { return nil } let scaleFactor = UIScreen.mainScreen().scale >= 3 ? "@3x" : "@2x" return SBAResourceFinder().urlNamed("\(resource)\(scaleFactor)", withExtension: "m4v") } }
bsd-3-clause
33170072382d24c1bde26b46a061d73e
40.288136
94
0.697393
4.965341
false
false
false
false
LPinguo/Showlive
Showlive/Showlive/Classes/Tools/Extention/UIBarButtonItem+Extention.swift
1
1326
// // UIBarButtonItem+Extention.swift // Showlive // // Created by LPGuo on 2016/12/16. // Copyright © 2016年 apple. All rights reserved. // import UIKit extension UIBarButtonItem { // 类方法 不建议使用 // class func createItem(imageName: String, hightImageName: String, size: CGSize) -> UIBarButtonItem { // // let btn = UIButton() // // btn.setImage(UIImage(named:imageName ), for: UIControlState.init(rawValue: 0)) // btn.setImage(UIImage(named:hightImageName ), for: .highlighted) // btn.frame.size = size // // return UIBarButtonItem.init(customView: btn) // } // 建议使用 构造函数 使用最多遍历构造 // convenience init(imageName: String, hightImageName: String = "", size: CGSize = CGSize.zero) { // 创建 btn let btn = UIButton() btn.setImage(UIImage(named:imageName ), for: UIControlState.init(rawValue: 0)) if hightImageName != "" { btn.setImage(UIImage(named:hightImageName ), for: .highlighted) } if size == CGSize.zero { btn.sizeToFit() } else { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView:btn) } }
mit
d04a96c13c09c76dd388baa3d1d66f6f
25.479167
105
0.571204
4.073718
false
false
false
false
quaertym/Shark
Shark.swift
1
7465
#!/usr/bin/env xcrun -sdk macosx swift import Foundation struct EnumBuilder { private enum Resource { case File(String) case Directory((String, [Resource])) } private static let forbiddenCharacterSet: NSCharacterSet = { let validSet = NSMutableCharacterSet(charactersInString: "_") validSet.formUnionWithCharacterSet(NSCharacterSet.letterCharacterSet()) return validSet.invertedSet }() static func enumStringForPath(path: String, topLevelName: String = "Shark") throws -> String { let resources = try imageResourcesAtPath(path) if resources.isEmpty { return "" } let topLevelResource = Resource.Directory(topLevelName, resources) return createEnumDeclarationForResources([topLevelResource], indentLevel: 0) } private static func imageResourcesAtPath(path: String) throws -> [Resource] { var results = [Resource]() let URL = NSURL.fileURLWithPath(path) let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(URL, includingPropertiesForKeys: [NSURLNameKey, NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles) for fileURL in contents { var directoryKey: AnyObject? try fileURL.getResourceValue(&directoryKey, forKey: NSURLIsDirectoryKey) guard let isDirectory = directoryKey as? NSNumber else { continue } if isDirectory.integerValue == 1 { if fileURL.absoluteString.hasSuffix(".imageset/") { let name = fileURL.lastPathComponent!.componentsSeparatedByString(".imageset")[0] results.append(.File(name)) } else if !fileURL.absoluteString.hasSuffix(".appiconset/") { let folderName = fileURL.lastPathComponent! let subResources = try imageResourcesAtPath(fileURL.relativePath!) results.append(.Directory((folderName, subResources))) } } } return results } private static func correctedNameForString(string: String) -> String? { //First try replacing -'s with _'s only, then remove illegal characters if let _ = string.rangeOfString("-") { let replacedString = string.stringByReplacingOccurrencesOfString("-", withString: "_") if replacedString.rangeOfCharacterFromSet(forbiddenCharacterSet) == nil { return replacedString } } if let _ = string.rangeOfCharacterFromSet(forbiddenCharacterSet) { return "".join(string.componentsSeparatedByCharactersInSet(forbiddenCharacterSet)) } return nil } //An enum should extend String and conform to SharkImageConvertible if and only if it has at least on image asset in it. //We return empty string when we get a Directory of directories. private static func conformanceStringForResource(resource: Resource) -> String { switch resource { case .Directory(_, let subResources): let index = subResources.indexOf({ if case .File = $0 { return true } else { return false } }) if let _ = index { return ": String, SharkImageConvertible" } else { return "" } case _: return "" } } private static func createEnumDeclarationForResources(resources: [Resource], indentLevel: Int) -> String { let sortedResources = resources.sort { first, _ in if case .Directory = first { return true } return false } var resultString = "" for singleResource in sortedResources { switch singleResource { case .File(let name): print("Creating Case: \(name)") let indentationString = String(count: 4 * (indentLevel + 1), repeatedValue: Character(" ")) if let correctedName = correctedNameForString(name) { resultString += indentationString + "case \(correctedName) = \"\(name)\"\n" } else { resultString += indentationString + "case \(name)\n" } case .Directory(let (name, subResources)): let correctedName = name.stringByReplacingOccurrencesOfString(" ", withString: "") print("Creating Enum: \(correctedName)") let indentationString = String(count: 4 * (indentLevel), repeatedValue: Character(" ")) resultString += "\n" + indentationString + "public enum \(correctedName)" + conformanceStringForResource(singleResource) + " {" + "\n" resultString += createEnumDeclarationForResources(subResources, indentLevel: indentLevel + 1) resultString += indentationString + "}\n\n" } } return resultString } } struct FileBuilder { static func fileStringWithEnumString(enumString: String) -> String { return acknowledgementsString() + "\n\n" + importString() + "\n\n" + imageExtensionString() + "\n" + enumString } private static func importString() -> String { return "import UIKit" } private static func acknowledgementsString() -> String { return "//SharkImageNames.swift\n//Generated by Shark" } private static func imageExtensionString() -> String { return "public protocol SharkImageConvertible {}\n\npublic extension SharkImageConvertible where Self: RawRepresentable, Self.RawValue == String {\n public var image: UIImage? {\n return UIImage(named: self.rawValue)\n }\n}\n\npublic extension UIImage {\n convenience init?<T: RawRepresentable where T.RawValue == String>(shark: T) {\n self.init(named: shark.rawValue)\n }\n}\n" } } //-----------------------------------------------------------// //-----------------------------------------------------------// //Process arguments and run the script let arguments = Process.arguments if arguments.count != 3 { print("You must supply the path to the .xcassets folder, and the output path for the Shark file") print("\n\nExample Usage:\nswift Shark.swift /Users/john/Code/GameProject/GameProject/Images.xcassets/ /Users/john/Code/GameProject/GameProject/") exit(1) } let path = arguments[1] if !(path.hasSuffix(".xcassets") || path.hasSuffix(".xcassets/")) { print("The path should point to a .xcassets folder") exit(1) } let outputPath = arguments[2] var isDirectory: ObjCBool = false if NSFileManager.defaultManager().fileExistsAtPath(outputPath, isDirectory: &isDirectory) == false { print("The output path does not exist") exit(1) } if !isDirectory{ print("The output path is not a valid directory") exit(1) } //Create the file string let enumString = try EnumBuilder.enumStringForPath(path) let fileString = FileBuilder.fileStringWithEnumString(enumString) //Save the file string let outputURL = NSURL.fileURLWithPath(outputPath).URLByAppendingPathComponent("SharkImages.swift") try fileString.writeToURL(outputURL, atomically: true, encoding: NSUTF8StringEncoding)
mit
20f7745ab2e2260c2b7adabd27518b1a
39.797814
412
0.615137
5.332143
false
false
false
false
cdtschange/SwiftMKit
SwiftMKit/Data/Image/ImageScout/ImageScout.swift
1
2758
import QuartzCore public enum ScoutedImageType: String { case GIF = "gif" case PNG = "png" case JPEG = "jpeg" case Unsupported = "unsupported" } public typealias ScoutCompletionBlock = (NSError?, CGSize, ScoutedImageType) -> () let unsupportedFormatErrorMessage = "Unsupported image format. ImageScout only supports PNG, GIF, and JPEG." let unableToParseErrorMessage = "Scouting operation failed. The remote image is likely malformated or corrupt." let invalidURIErrorMessage = "Invalid URI parameter." let errorDomain = "ImageScoutErrorDomain" open class ImageScout { fileprivate var session: URLSession fileprivate var sessionDelegate = SessionDelegate() fileprivate var queue = OperationQueue() fileprivate var operations = [String : ScoutOperation]() public init() { let sessionConfig = URLSessionConfiguration.ephemeral session = URLSession(configuration: sessionConfig, delegate: sessionDelegate, delegateQueue: nil) sessionDelegate.scout = self } /// Takes a URL string and a completion block and returns void. /// The completion block takes an optional error, a size, and an image type, /// and returns void. open func scoutImageWithURI(_ URI: String, completion: @escaping ScoutCompletionBlock) { guard let URL = URL(string: URI) else { let URLError = ImageScout.error(invalidURIErrorMessage, code: 100) return completion(URLError, CGSize.zero, ScoutedImageType.Unsupported) } let operation = ScoutOperation(task: session.dataTask(with: URL)) operation.completionBlock = { [unowned self] in completion(operation.error, operation.size, operation.type) self.operations[URI] = nil } addOperation(operation, withURI: URI) } // MARK: Delegate Methods func didReceiveData(_ data: Data, task: URLSessionDataTask) { guard let requestURL = task.currentRequest?.url?.absoluteString else { return } guard let operation = operations[requestURL] else { return } operation.appendData(data) } func didCompleteWithError(_ error: NSError?, task: URLSessionDataTask) { guard let requestURL = task.currentRequest?.url?.absoluteString else { return } guard let operation = operations[requestURL] else { return } let completionError = error ?? ImageScout.error(unableToParseErrorMessage, code: 101) operation.terminateWithError(completionError) } // MARK: Private Methods fileprivate func addOperation(_ operation: ScoutOperation, withURI URI: String) { operations[URI] = operation queue.addOperation(operation) } // MARK: Class Methods class func error(_ message: String, code: Int) -> NSError { return NSError(domain: errorDomain, code:code, userInfo:[NSLocalizedDescriptionKey: message]) } }
mit
46aac54cd3c63c989de344ca4afee0f4
34.358974
111
0.738579
4.730703
false
true
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01694-void.swift
1
712
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck enum S<e<T -> : d { func a(f: C = B, length: (A.Iterator.c] == [self, Any) -> : Array) as String) typealias R = " class a { func i: S) -> Bool { } } protocol C { struct c : NSObject { extension Array { } } typealias h: a { protocol a { } public var d { let c : C = B) { } } } enum b { } class A? { } func b(c<T.in
apache-2.0
6bc567a0bf1a9b81fea42b34a6a4e721
20.575758
79
0.664326
3.029787
false
false
false
false
KyoheiG3/RxSwift
RxExample/RxExample/Services/ActivityIndicator.swift
9
2221
// // ActivityIndicator.swift // RxExample // // Created by Krunoslav Zaher on 10/18/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif private struct ActivityToken<E> : ObservableConvertibleType, Disposable { private let _source: Observable<E> private let _dispose: Cancelable init(source: Observable<E>, disposeAction: @escaping () -> ()) { _source = source _dispose = Disposables.create(with: disposeAction) } func dispose() { _dispose.dispose() } func asObservable() -> Observable<E> { return _source } } /** Enables monitoring of sequence computation. If there is at least one sequence computation in progress, `true` will be sent. When all activities complete `false` will be sent. */ public class ActivityIndicator : SharedSequenceConvertibleType { public typealias E = Bool public typealias SharingStrategy = DriverSharingStrategy private let _lock = NSRecursiveLock() private let _variable = Variable(0) private let _loading: SharedSequence<SharingStrategy, Bool> public init() { _loading = _variable.asDriver() .map { $0 > 0 } .distinctUntilChanged() } fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> { return Observable.using({ () -> ActivityToken<O.E> in self.increment() return ActivityToken(source: source.asObservable(), disposeAction: self.decrement) }) { t in return t.asObservable() } } private func increment() { _lock.lock() _variable.value = _variable.value + 1 _lock.unlock() } private func decrement() { _lock.lock() _variable.value = _variable.value - 1 _lock.unlock() } public func asSharedSequence() -> SharedSequence<SharingStrategy, E> { return _loading } } extension ObservableConvertibleType { public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> { return activityIndicator.trackActivityOfObservable(self) } }
mit
507cc9fd7c58419b69f899313cf544a6
25.746988
110
0.654054
4.663866
false
false
false
false
mlatham/AFToolkit
Sources/AFToolkit/Views/EmptyCell.swift
1
1280
import Foundation import UIKit public struct EmptyCellViewModel { public let text: String public let image: UIImage? public init(text: String, image: UIImage?) { self.text = text self.image = image } } public class EmptyCell: BaseCell { public typealias Item = EmptyCellViewModel // MARK: - Properties public static var EstimatedHeight: CGFloat { // TODO: Phone size? return 200 } private let _stackView = UIStackView() private let _imageView = UIImageView() private let _label = UILabel() // MARK: - Inits override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(_stackView) _stackView.addArrangedSubview(_imageView) _stackView.addArrangedSubview(_label) _stackView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(x(1)) } _stackView.axis = .vertical _stackView.spacing = x(1) selectionStyle = .none } required init(coder aDecoder: NSCoder) { fatalError(NotImplementedError) } // MARK: - Functions public func configure(with item: EmptyCellViewModel) { _imageView.image = item.image _label.text = item.text } public func selected() { } public func deselected() { } }
mit
aea480f4f04d38332d8f3047048a1d03
18.393939
76
0.7125
3.731778
false
false
false
false
WorldDownTown/ZoomTransitioning
ZoomTransitioning/ZoomTransitioning.swift
1
5522
// // ZoomTransitioning.swift // ZoomTransitioning // // Created by WorldDownTown on 07/08/2016. // Copyright © 2016 WorldDownTown. All rights reserved. // import UIKit public final class ZoomTransitioning: NSObject { static let transitionDuration: TimeInterval = 0.3 private let source: ZoomTransitionSourceDelegate private let destination: ZoomTransitionDestinationDelegate private let forward: Bool required public init(source: ZoomTransitionSourceDelegate, destination: ZoomTransitionDestinationDelegate, forward: Bool) { self.source = source self.destination = destination self.forward = forward super.init() } } // MARK: - UIViewControllerAnimatedTransitioning { extension ZoomTransitioning: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return source.animationDuration } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if forward { animateTransitionForPush(transitionContext) } else { animateTransitionForPop(transitionContext) } } private func animateTransitionForPush(_ transitionContext: UIViewControllerContextTransitioning) { guard let sourceView = transitionContext.view(forKey: UITransitionContextViewKey.from), let destinationView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) return } let containerView: UIView = transitionContext.containerView let transitioningImageView: UIImageView = transitioningPushImageView() containerView.backgroundColor = sourceView.backgroundColor sourceView.alpha = 1 destinationView.alpha = 0 containerView.insertSubview(destinationView, belowSubview: sourceView) containerView.addSubview(transitioningImageView) source.transitionSourceWillBegin() destination.transitionDestinationWillBegin() source.zoomAnimation( animations: { sourceView.alpha = 0 destinationView.alpha = 1 transitioningImageView.frame = self.destination.transitionDestinationImageViewFrame(forward: self.forward) }, completion: { _ in sourceView.alpha = 1 transitioningImageView.alpha = 0 transitioningImageView.removeFromSuperview() self.source.transitionSourceDidEnd() self.destination.transitionDestinationDidEnd(transitioningImageView: transitioningImageView) let completed: Bool = !transitionContext.transitionWasCancelled transitionContext.completeTransition(completed) }) } private func animateTransitionForPop(_ transitionContext: UIViewControllerContextTransitioning) { guard let sourceView = transitionContext.view(forKey: UITransitionContextViewKey.to), let destinationView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) return } let containerView: UIView = transitionContext.containerView let transitioningImageView: UIImageView = transitioningPopImageView() containerView.backgroundColor = destinationView.backgroundColor destinationView.alpha = 1 sourceView.alpha = 0 containerView.insertSubview(sourceView, belowSubview: destinationView) containerView.addSubview(transitioningImageView) source.transitionSourceWillBegin() destination.transitionDestinationWillBegin() if transitioningImageView.frame.maxY < 0 { transitioningImageView.frame.origin.y = -transitioningImageView.frame.height } source.zoomAnimation( animations: { destinationView.alpha = 0 sourceView.alpha = 1 transitioningImageView.frame = self.source.transitionSourceImageViewFrame(forward: self.forward) }, completion: { _ in destinationView.alpha = 1 transitioningImageView.removeFromSuperview() self.source.transitionSourceDidEnd() self.destination.transitionDestinationDidEnd(transitioningImageView: transitioningImageView) let completed: Bool if #available(iOS 10.0, *) { completed = true } else { completed = !transitionContext.transitionWasCancelled } transitionContext.completeTransition(completed) }) } private func transitioningPushImageView() -> UIImageView { let imageView: UIImageView = source.transitionSourceImageView() let frame: CGRect = source.transitionSourceImageViewFrame(forward: forward) return UIImageView(baseImageView: imageView, frame: frame) } private func transitioningPopImageView() -> UIImageView { let imageView: UIImageView = source.transitionSourceImageView() let frame: CGRect = destination.transitionDestinationImageViewFrame(forward: forward) return UIImageView(baseImageView: imageView, frame: frame) } }
mit
3121c2dbd166e92d05c267b70fdb4538
39.007246
127
0.692447
6.659831
false
false
false
false
avaidyam/Parrot
MochaUI/NSLayoutConstraint+Extensions.swift
1
41529
// Anchorage // Copyright 2016 Raizlabs (Rob Visentin) and other contributors (http://raizlabs.com/) #if os(macOS) import Cocoa internal typealias View = NSView internal typealias ViewController = NSViewController internal typealias LayoutGuide = NSLayoutGuide #if swift(>=4.0) public typealias LayoutPriority = NSLayoutConstraint.Priority public typealias EdgeInsets = NSEdgeInsets public typealias ConstraintAttribute = NSLayoutConstraint.Attribute internal let LayoutPriorityRequired = NSLayoutConstraint.Priority.required internal let LayoutPriorityHigh = NSLayoutConstraint.Priority.defaultHigh internal let LayoutPriorityLow = NSLayoutConstraint.Priority.defaultLow internal let LayoutPriorityFittingSize = NSLayoutConstraint.Priority.fittingSizeCompression #else public typealias LayoutPriority = NSLayoutPriority public typealias ConstraintAttribute = NSLayoutAttribute internal let LayoutPriorityRequired = NSLayoutPriorityRequired internal let LayoutPriorityHigh = NSLayoutPriorityDefaultHigh internal let LayoutPriorityLow = NSLayoutPriorityDefaultLow internal let LayoutPriorityFittingSize = NSLayoutPriorityFittingSizeCompression #endif #else import UIKit internal typealias View = UIView internal typealias ViewController = UIViewController internal typealias LayoutGuide = UILayoutGuide public typealias LayoutPriority = UILayoutPriority public typealias EdgeInsets = UIEdgeInsets public typealias ConstraintAttribute = NSLayoutAttribute #if swift(>=4.0) internal let LayoutPriorityRequired = UILayoutPriority.required internal let LayoutPriorityHigh = UILayoutPriority.defaultHigh internal let LayoutPriorityLow = UILayoutPriority.defaultLow internal let LayoutPriorityFittingSize = UILayoutPriority.fittingSizeLevel #else internal let LayoutPriorityRequired = UILayoutPriorityRequired internal let LayoutPriorityHigh = UILayoutPriorityDefaultHigh internal let LayoutPriorityLow = UILayoutPriorityDefaultLow internal let LayoutPriorityFittingSize = UILayoutPriorityFittingSizeLevel #endif #endif #if swift(>=4.0) #else extension LayoutPriority { var rawValue: Float { return self } init(rawValue: Float) { self.init(rawValue) } } #endif public protocol LayoutConstantType {} extension CGFloat: LayoutConstantType {} extension CGSize: LayoutConstantType {} extension EdgeInsets: LayoutConstantType {} public protocol LayoutAnchorType {} extension NSLayoutAnchor: LayoutAnchorType {} extension CGFloat { init<T: BinaryFloatingPoint>(_ value: T) { switch value { case is Double: self.init(value as! Double) case is Float: self.init(value as! Float) case is CGFloat: self.init(value as! CGFloat) default: fatalError("Unable to initialize CGFloat with value \(value) of type \(type(of: value))") } } } extension Float { init<T: BinaryFloatingPoint>(_ value: T) { switch value { case is Double: self.init(value as! Double) case is Float: self.init(value as! Float) case is CGFloat: self.init(value as! CGFloat) default: fatalError("Unable to initialize CGFloat with value \(value) of type \(type(of: value))") } } } public struct LayoutExpression<T: LayoutAnchorType, U: LayoutConstantType> { public var anchor: T? public var constant: U public var multiplier: CGFloat public var priority: Priority internal init(anchor: T? = nil, constant: U, multiplier: CGFloat = 1.0, priority: Priority = .required) { self.anchor = anchor self.constant = constant self.multiplier = multiplier self.priority = priority } } public struct AnchorPair<T: LayoutAnchorType, U: LayoutAnchorType>: LayoutAnchorType { public var first: T public var second: U internal init(first: T, second: U) { self.first = first self.second = second } } internal extension AnchorPair { func finalize(constraintsEqualToConstant size: CGSize, priority: Priority = .required) -> ConstraintPair { return constraints(forConstant: size, priority: priority, builder: ConstraintBuilder.equality); } func finalize(constraintsLessThanOrEqualToConstant size: CGSize, priority: Priority = .required) -> ConstraintPair { return constraints(forConstant: size, priority: priority, builder: ConstraintBuilder.lessThanOrEqual); } func finalize(constraintsGreaterThanOrEqualToConstant size: CGSize, priority: Priority = .required) -> ConstraintPair { return constraints(forConstant: size, priority: priority, builder: ConstraintBuilder.greaterThanOrEqual); } func finalize(constraintsEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: Priority = .required) -> ConstraintPair { return constraints(forAnchors: anchor, constant: c, priority: priority, builder: ConstraintBuilder.equality) } func finalize(constraintsLessThanOrEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: Priority = .required) -> ConstraintPair { return constraints(forAnchors: anchor, constant: c, priority: priority, builder: ConstraintBuilder.lessThanOrEqual) } func finalize(constraintsGreaterThanOrEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: Priority = .required) -> ConstraintPair { return constraints(forAnchors: anchor, constant: c, priority: priority, builder: ConstraintBuilder.greaterThanOrEqual) } func constraints(forConstant size: CGSize, priority: Priority, builder: ConstraintBuilder) -> ConstraintPair { var constraints: ConstraintPair! performInBatch { switch (first, second) { case let (first as NSLayoutDimension, second as NSLayoutDimension): constraints = ConstraintPair( first: builder.dimensionBuilder(first, size.width ~ priority), second: builder.dimensionBuilder(second, size.height ~ priority) ) default: preconditionFailure("Only AnchorPair<NSLayoutDimension, NSLayoutDimension> can be constrained to a constant size.") } } return constraints; } func constraints(forAnchors anchors: AnchorPair<T, U>?, constant c: CGFloat, priority: Priority, builder: ConstraintBuilder) -> ConstraintPair { return constraints(forAnchors: anchors, firstConstant: c, secondConstant: c, priority: priority, builder: builder) } func constraints(forAnchors anchors: AnchorPair<T, U>?, firstConstant c1: CGFloat, secondConstant c2: CGFloat, priority: Priority, builder: ConstraintBuilder) -> ConstraintPair { guard let anchors = anchors else { preconditionFailure("Encountered nil edge anchors, indicating internal inconsistency of this API.") } var constraints: ConstraintPair! performInBatch { switch (first, anchors.first, second, anchors.second) { // Leading, Trailing case let (firstX as NSLayoutXAxisAnchor, otherFirstX as NSLayoutXAxisAnchor, secondX as NSLayoutXAxisAnchor, otherSecondX as NSLayoutXAxisAnchor): constraints = ConstraintPair( first: builder.leadingBuilder(firstX, otherFirstX + c1 ~ priority), second: builder.trailingBuilder(secondX, otherSecondX - c2 ~ priority) ) // Top, Bottom case let (firstY as NSLayoutYAxisAnchor, otherFirstY as NSLayoutYAxisAnchor, secondY as NSLayoutYAxisAnchor, otherSecondY as NSLayoutYAxisAnchor): constraints = ConstraintPair( first: builder.topBuilder(firstY, otherFirstY + c1 ~ priority), second: builder.bottomBuilder(secondY, otherSecondY - c2 ~ priority) ) // CenterX, CenterY case let (firstX as NSLayoutXAxisAnchor, otherFirstX as NSLayoutXAxisAnchor, firstY as NSLayoutYAxisAnchor, otherFirstY as NSLayoutYAxisAnchor): constraints = ConstraintPair( first: builder.centerXBuilder(firstX, otherFirstX + c1 ~ priority), second: builder.centerYBuilder(firstY, otherFirstY + c2 ~ priority) ) // Width, Height case let (first as NSLayoutDimension, otherFirst as NSLayoutDimension, second as NSLayoutDimension, otherSecond as NSLayoutDimension): constraints = ConstraintPair( first: builder.dimensionBuilder(first, otherFirst + c1 ~ priority), second: builder.dimensionBuilder(second, otherSecond + c2 ~ priority) ) default: preconditionFailure("Constrained anchors must match in either axis or type.") } } return constraints } } internal extension EdgeInsets { init(constant: CGFloat) { self.init(top: constant, left: constant, bottom: constant, right: constant) } } internal prefix func - (rhs: EdgeInsets) -> EdgeInsets { return EdgeInsets(top: -rhs.top, left: -rhs.left, bottom: -rhs.bottom, right: -rhs.right) } internal extension EdgeAnchors { init(horizontal: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor>, vertical: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor>) { self.horizontalAnchors = horizontal self.verticalAnchors = vertical } func finalize(constraintsEqualToEdges anchor: EdgeAnchors?, insets: EdgeInsets, priority: Priority = .required) -> ConstraintGroup { return constraints(forAnchors: anchor, insets: insets, priority: priority, builder: ConstraintBuilder.equality) } func finalize(constraintsLessThanOrEqualToEdges anchor: EdgeAnchors?, insets: EdgeInsets, priority: Priority = .required) -> ConstraintGroup { return constraints(forAnchors: anchor, insets: insets, priority: priority, builder: ConstraintBuilder.lessThanOrEqual) } func finalize(constraintsGreaterThanOrEqualToEdges anchor: EdgeAnchors?, insets: EdgeInsets, priority: Priority = .required) -> ConstraintGroup { return constraints(forAnchors: anchor, insets: insets, priority: priority, builder: ConstraintBuilder.greaterThanOrEqual) } func finalize(constraintsEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: Priority = .required) -> ConstraintGroup { return constraints(forAnchors: anchor, insets: EdgeInsets(constant: c), priority: priority, builder: ConstraintBuilder.equality) } func finalize(constraintsLessThanOrEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: Priority = .required) -> ConstraintGroup { return constraints(forAnchors: anchor, insets: EdgeInsets(constant: c), priority: priority, builder: ConstraintBuilder.lessThanOrEqual) } func finalize(constraintsGreaterThanOrEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: Priority = .required) -> ConstraintGroup { return constraints(forAnchors: anchor, insets: EdgeInsets(constant: c), priority: priority, builder: ConstraintBuilder.greaterThanOrEqual) } func constraints(forAnchors anchors: EdgeAnchors?, insets: EdgeInsets, priority: Priority, builder: ConstraintBuilder) -> ConstraintGroup { guard let anchors = anchors else { preconditionFailure("Encountered nil edge anchors, indicating internal inconsistency of this API.") } var constraints: ConstraintGroup! performInBatch { let horizontalConstraints = horizontalAnchors.constraints(forAnchors: anchors.horizontalAnchors, firstConstant: insets.left, secondConstant: insets.right, priority: priority, builder: builder) let verticalConstraints = verticalAnchors.constraints(forAnchors: anchors.verticalAnchors, firstConstant: insets.top, secondConstant: insets.bottom, priority: priority, builder: builder) constraints = ConstraintGroup( top: verticalConstraints.first, leading: horizontalConstraints.first, bottom: verticalConstraints.second, trailing: horizontalConstraints.second ) } return constraints } } internal struct ConstraintBuilder { typealias Horizontal = (NSLayoutXAxisAnchor, LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint typealias Vertical = (NSLayoutYAxisAnchor, LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint typealias Dimension = (NSLayoutDimension, LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint static let equality = ConstraintBuilder(horizontal: ==, vertical: ==, dimension: ==) static let lessThanOrEqual = ConstraintBuilder(leading: <=, top: <=, trailing: >=, bottom: >=, centerX: <=, centerY: <=, dimension: <=) static let greaterThanOrEqual = ConstraintBuilder(leading: >=, top: >=, trailing: <=, bottom: <=, centerX: >=, centerY: >=, dimension: >=) var topBuilder: Vertical var leadingBuilder: Horizontal var bottomBuilder: Vertical var trailingBuilder: Horizontal var centerYBuilder: Vertical var centerXBuilder: Horizontal var dimensionBuilder: Dimension init(horizontal: @escaping Horizontal, vertical: @escaping Vertical, dimension: @escaping Dimension) { topBuilder = vertical leadingBuilder = horizontal bottomBuilder = vertical trailingBuilder = horizontal centerYBuilder = vertical centerXBuilder = horizontal dimensionBuilder = dimension } init(leading: @escaping Horizontal, top: @escaping Vertical, trailing: @escaping Horizontal, bottom: @escaping Vertical, centerX: @escaping Horizontal, centerY: @escaping Vertical, dimension: @escaping Dimension) { leadingBuilder = leading topBuilder = top trailingBuilder = trailing bottomBuilder = bottom centerYBuilder = centerY centerXBuilder = centerX dimensionBuilder = dimension } } internal var batches: [ConstraintBatch] = [] internal class ConstraintBatch { var constraints = [NSLayoutConstraint]() func add(constraint: NSLayoutConstraint) { constraints.append(constraint) } func activate() { NSLayoutConstraint.activate(constraints) } } /// Perform a closure immediately if a batch is already active, /// otherwise executes the closure in a new batch. /// /// - Parameter closure: The work to perform inside of a batch internal func performInBatch(closure: () -> Void) { if batches.isEmpty { batch(closure) } else { closure() } } internal func finalize(constraint: NSLayoutConstraint, withPriority priority: Priority = .required) -> NSLayoutConstraint { // Only disable autoresizing constraints on the LHS item, which is the one definitely intended to be governed by Auto Layout if let first = constraint.firstItem as? View { first.translatesAutoresizingMaskIntoConstraints = false } constraint.priority = priority.value if let lastBatch = batches.last { lastBatch.add(constraint: constraint) } else { constraint.isActive = true } return constraint } public enum Priority: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, Equatable { case required case high case low case fittingSize case custom(LayoutPriority) public var value: LayoutPriority { switch self { case .required: return LayoutPriorityRequired case .high: return LayoutPriorityHigh case .low: return LayoutPriorityLow case .fittingSize: return LayoutPriorityFittingSize case .custom(let priority): return priority } } public init(floatLiteral value: Float) { self = .custom(LayoutPriority(value)) } public init(integerLiteral value: Int) { self.init(value) } public init(_ value: Int) { self = .custom(LayoutPriority(Float(value))) } public init<T: BinaryFloatingPoint>(_ value: T) { self = .custom(LayoutPriority(Float(value))) } } /// Any Anchorage constraints created inside the passed closure are returned in the array. /// /// - Parameter closure: A closure that runs some Anchorage expressions. /// - Returns: An array of new, active `NSLayoutConstraint`s. @discardableResult public func batch(_ closure: () -> Void) -> [NSLayoutConstraint] { return batch(active: true, closure: closure) } /// Any Anchorage constraints created inside the passed closure are returned in the array. /// /// - Parameter active: Whether the created constraints should be active when they are returned. /// - Parameter closure: A closure that runs some Anchorage expressions. /// - Returns: An array of new `NSLayoutConstraint`s. public func batch(active: Bool, closure: () -> Void) -> [NSLayoutConstraint] { let batch = ConstraintBatch() batches.append(batch) defer { batches.removeLast() } closure() if active { batch.activate() } return batch.constraints } public protocol AnchorGroupProvider { var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { get } var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { get } var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { get } var sizeAnchors: AnchorPair<NSLayoutDimension, NSLayoutDimension> { get } } extension AnchorGroupProvider { public var edgeAnchors: EdgeAnchors { return EdgeAnchors(horizontal: horizontalAnchors, vertical: verticalAnchors) } } extension View: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: leadingAnchor, second: trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topAnchor, second: bottomAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: centerXAnchor, second: centerYAnchor) } public var sizeAnchors: AnchorPair<NSLayoutDimension, NSLayoutDimension> { return AnchorPair(first: widthAnchor, second: heightAnchor) } } extension ViewController: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return view.horizontalAnchors } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { #if os(macOS) return view.verticalAnchors #else return AnchorPair(first: topLayoutGuide.bottomAnchor, second: bottomLayoutGuide.topAnchor) #endif } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return view.centerAnchors } public var sizeAnchors: AnchorPair<NSLayoutDimension, NSLayoutDimension> { return view.sizeAnchors } } extension LayoutGuide: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: leadingAnchor, second: trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topAnchor, second: bottomAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: centerXAnchor, second: centerYAnchor) } public var sizeAnchors: AnchorPair<NSLayoutDimension, NSLayoutDimension> { return AnchorPair(first: widthAnchor, second: heightAnchor) } } public struct EdgeAnchors: LayoutAnchorType { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> } public struct ConstraintPair { public var first: NSLayoutConstraint public var second: NSLayoutConstraint } public struct ConstraintGroup { public var top: NSLayoutConstraint public var leading: NSLayoutConstraint public var bottom: NSLayoutConstraint public var trailing: NSLayoutConstraint public var horizontal: [NSLayoutConstraint] { return [leading, trailing] } public var vertical: [NSLayoutConstraint] { return [top, bottom] } public var all: [NSLayoutConstraint] { return [top, leading, bottom, trailing] } } extension NSLayoutXAxisAnchor { func constraint(equalTo anchor: NSLayoutXAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(equalTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(greaterThanOrEqualTo anchor: NSLayoutXAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(greaterThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(lessThanOrEqualTo anchor: NSLayoutXAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(lessThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } } extension NSLayoutYAxisAnchor { func constraint(equalTo anchor: NSLayoutYAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(equalTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(greaterThanOrEqualTo anchor: NSLayoutYAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(greaterThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(lessThanOrEqualTo anchor: NSLayoutYAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(lessThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } } private extension NSLayoutConstraint { func with(multiplier: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint(item: firstItem!, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) } } precedencegroup PriorityPrecedence { associativity: none higherThan: ComparisonPrecedence lowerThan: AdditionPrecedence } infix operator ~: PriorityPrecedence public func == (lhs: Priority, rhs: Priority) -> Bool { return lhs.value == rhs.value } public func + <T: BinaryFloatingPoint>(lhs: Priority, rhs: T) -> Priority { return .custom(LayoutPriority(rawValue: lhs.value.rawValue + Float(rhs))) } public func + <T: BinaryFloatingPoint>(lhs: T, rhs: Priority) -> Priority { return .custom(LayoutPriority(rawValue: Float(lhs) + rhs.value.rawValue)) } public func - <T: BinaryFloatingPoint>(lhs: Priority, rhs: T) -> Priority { return .custom(LayoutPriority(rawValue: lhs.value.rawValue - Float(rhs))) } public func - <T: BinaryFloatingPoint>(lhs: T, rhs: Priority) -> Priority { return .custom(LayoutPriority(rawValue: Float(lhs) - rhs.value.rawValue)) } @discardableResult public func == <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(equalToConstant: CGFloat(rhs))) } @discardableResult public func == (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutXAxisAnchor, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(equalTo: rhs.anchor!, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == (lhs: NSLayoutYAxisAnchor, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(equalTo: rhs.anchor!, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return finalize(constraint: lhs.constraint(equalTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return finalize(constraint: lhs.constraint(equalToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func == (lhs: EdgeAnchors, rhs: EdgeAnchors) -> ConstraintGroup { return lhs.finalize(constraintsEqualToEdges: rhs) } @discardableResult public func == (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, CGFloat>) -> ConstraintGroup { return lhs.finalize(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func == (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, EdgeInsets>) -> ConstraintGroup { return lhs.finalize(constraintsEqualToEdges: rhs.anchor, insets: rhs.constant, priority: rhs.priority) } @discardableResult public func == <T, U>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> ConstraintPair { return lhs.finalize(constraintsEqualToEdges: rhs) } @discardableResult public func == <T, U>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>, CGFloat>) -> ConstraintPair { return lhs.finalize(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func == (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: CGSize) -> ConstraintPair { return lhs.finalize(constraintsEqualToConstant: rhs) } @discardableResult public func == (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize>) -> ConstraintPair { return lhs.finalize(constraintsEqualToConstant: rhs.constant, priority: rhs.priority) } @discardableResult public func <= <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(lessThanOrEqualToConstant: CGFloat(rhs))) } @discardableResult public func <= (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= (lhs: NSLayoutXAxisAnchor, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= (lhs: NSLayoutYAxisAnchor, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return finalize(constraint: lhs.constraint(lessThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return finalize(constraint: lhs.constraint(lessThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func <= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> ConstraintGroup { return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs) } @discardableResult public func <= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, CGFloat>) -> ConstraintGroup { return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func <= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, EdgeInsets>) -> ConstraintGroup { return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs.anchor, insets: rhs.constant, priority: rhs.priority) } @discardableResult public func <= <T, U>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> ConstraintPair { return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs) } @discardableResult public func <= <T, U>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>, CGFloat>) -> ConstraintPair { return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func <= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: CGSize) -> ConstraintPair { return lhs.finalize(constraintsLessThanOrEqualToConstant: rhs) } @discardableResult public func <= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize>) -> ConstraintPair { return lhs.finalize(constraintsLessThanOrEqualToConstant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(greaterThanOrEqualToConstant: CGFloat(rhs))) } @discardableResult public func >= (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >= (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >= (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >= (lhs: NSLayoutXAxisAnchor, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= (lhs: NSLayoutYAxisAnchor, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint { return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return finalize(constraint: lhs.constraint(greaterThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func >= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> ConstraintGroup { return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs) } @discardableResult public func >= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, CGFloat>) -> ConstraintGroup { return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, EdgeInsets>) -> ConstraintGroup { return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs.anchor, insets: rhs.constant, priority: rhs.priority) } @discardableResult public func >= <T, U>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> ConstraintPair { return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs) } @discardableResult public func >= <T, U>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>, CGFloat>) -> ConstraintPair { return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: CGSize) -> ConstraintPair { return lhs.finalize(constraintsGreaterThanOrEqualToConstant: rhs) } @discardableResult public func >= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize>) -> ConstraintPair { return lhs.finalize(constraintsGreaterThanOrEqualToConstant: rhs.constant, priority: rhs.priority) } @discardableResult public func ~ <T: BinaryFloatingPoint>(lhs: T, rhs: Priority) -> LayoutExpression<NSLayoutDimension, CGFloat> { return LayoutExpression(constant: CGFloat(lhs), priority: rhs) } @discardableResult public func ~ (lhs: CGSize, rhs: Priority) -> LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize> { return LayoutExpression(constant: lhs, priority: rhs) } @discardableResult public func ~ <T>(lhs: T, rhs: Priority) -> LayoutExpression<T, CGFloat> { return LayoutExpression(anchor: lhs, constant: 0.0, priority: rhs) } @discardableResult public func ~ <T, U>(lhs: LayoutExpression<T, U>, rhs: Priority) -> LayoutExpression<T, U> { var expr = lhs expr.priority = rhs return expr } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> { return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: CGFloat(rhs)) } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: NSLayoutDimension) -> LayoutExpression<NSLayoutDimension, CGFloat> { return LayoutExpression(anchor: rhs, constant: 0.0, multiplier: CGFloat(lhs)) } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutDimension, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> { var expr = lhs expr.multiplier *= CGFloat(rhs) return expr } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> LayoutExpression<NSLayoutDimension, CGFloat> { var expr = rhs expr.multiplier *= CGFloat(lhs) return expr } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: NSLayoutXAxisAnchor, rhs: T) -> LayoutExpression<NSLayoutXAxisAnchor, CGFloat> { return LayoutExpression(anchor: Optional<NSLayoutXAxisAnchor>.some(lhs), constant: 0.0, multiplier: CGFloat(rhs)) } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: NSLayoutXAxisAnchor) -> LayoutExpression<NSLayoutXAxisAnchor, CGFloat> { return LayoutExpression(anchor: rhs, constant: 0.0, multiplier: CGFloat(lhs)) } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutXAxisAnchor, CGFloat> { var expr = lhs expr.multiplier *= CGFloat(rhs) return expr } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> LayoutExpression<NSLayoutXAxisAnchor, CGFloat> { var expr = rhs expr.multiplier *= CGFloat(lhs) return expr } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: NSLayoutYAxisAnchor, rhs: T) -> LayoutExpression<NSLayoutYAxisAnchor, CGFloat> { return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: CGFloat(rhs)) } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: NSLayoutYAxisAnchor) -> LayoutExpression<NSLayoutYAxisAnchor, CGFloat> { return LayoutExpression(anchor: rhs, constant: 0.0, multiplier: CGFloat(lhs)) } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutYAxisAnchor, CGFloat> { var expr = lhs expr.multiplier *= CGFloat(rhs) return expr } @discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> LayoutExpression<NSLayoutYAxisAnchor, CGFloat> { var expr = rhs expr.multiplier *= CGFloat(lhs) return expr } @discardableResult public func / <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> { return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: 1.0 / CGFloat(rhs)) } @discardableResult public func / <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutDimension, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> { var expr = lhs expr.multiplier /= CGFloat(rhs) return expr } @discardableResult public func / <T: BinaryFloatingPoint>(lhs: NSLayoutXAxisAnchor, rhs: T) -> LayoutExpression<NSLayoutXAxisAnchor, CGFloat> { return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: 1.0 / CGFloat(rhs)) } @discardableResult public func / <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutXAxisAnchor, CGFloat> { var expr = lhs expr.multiplier /= CGFloat(rhs) return expr } @discardableResult public func / <T: BinaryFloatingPoint>(lhs: NSLayoutYAxisAnchor, rhs: T) -> LayoutExpression<NSLayoutYAxisAnchor, CGFloat> { return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: 1.0 / CGFloat(rhs)) } @discardableResult public func / <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutYAxisAnchor, CGFloat> { var expr = lhs expr.multiplier /= CGFloat(rhs) return expr } @discardableResult public func + <T, U: BinaryFloatingPoint>(lhs: T, rhs: U) -> LayoutExpression<T, CGFloat> { return LayoutExpression(anchor: lhs, constant: CGFloat(rhs)) } @discardableResult public func + <T: BinaryFloatingPoint, U>(lhs: T, rhs: U) -> LayoutExpression<U, CGFloat> { return LayoutExpression(anchor: rhs, constant: CGFloat(lhs)) } @discardableResult public func + <T, U: BinaryFloatingPoint>(lhs: LayoutExpression<T, CGFloat>, rhs: U) -> LayoutExpression<T, CGFloat> { var expr = lhs expr.constant += CGFloat(rhs) return expr } @discardableResult public func + <T: BinaryFloatingPoint, U>(lhs: T, rhs: LayoutExpression<U, CGFloat>) -> LayoutExpression<U, CGFloat> { var expr = rhs expr.constant += CGFloat(lhs) return expr } @discardableResult public func + (lhs: EdgeAnchors, rhs: EdgeInsets) -> LayoutExpression<EdgeAnchors, EdgeInsets> { return LayoutExpression(anchor: lhs, constant: rhs) } @discardableResult public func - <T, U: BinaryFloatingPoint>(lhs: T, rhs: U) -> LayoutExpression<T, CGFloat> { return LayoutExpression(anchor: lhs, constant: -CGFloat(rhs)) } @discardableResult public func - <T: BinaryFloatingPoint, U>(lhs: T, rhs: U) -> LayoutExpression<U, CGFloat> { return LayoutExpression(anchor: rhs, constant: -CGFloat(lhs)) } @discardableResult public func - <T, U: BinaryFloatingPoint>(lhs: LayoutExpression<T, CGFloat>, rhs: U) -> LayoutExpression<T, CGFloat> { var expr = lhs expr.constant -= CGFloat(rhs) return expr } @discardableResult public func - <T: BinaryFloatingPoint, U>(lhs: T, rhs: LayoutExpression<U, CGFloat>) -> LayoutExpression<U, CGFloat> { var expr = rhs expr.constant -= CGFloat(lhs) return expr } @discardableResult public func - (lhs: EdgeAnchors, rhs: EdgeInsets) -> LayoutExpression<EdgeAnchors, EdgeInsets> { return LayoutExpression(anchor: lhs, constant: -rhs) }
mpl-2.0
4101cbed872b69132bc431fe49b96e2d
39.996051
204
0.719594
5.160805
false
false
false
false
xxxAIRINxxx/ViewPagerController
Sources/PagerTabMenuView.swift
1
18502
// // PagerTabMenuView.swift // ViewPagerController // // Created by xxxAIRINxxx on 2016/01/05. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit public final class PagerTabMenuView: UIView { // MARK: - Public Handler Properties public var selectedIndexHandler : ((Int) -> Void)? public var updateSelectedViewHandler : ((UIView) -> Void)? public var willBeginScrollingHandler : ((UIView) -> Void)? public var didEndTabMenuScrollingHandler : ((UIView) -> Void)? // MARK: - Custom Settings Properties // Title Layout public fileprivate(set) var titleMargin : CGFloat = 0.0 public fileprivate(set) var titleMinWidth : CGFloat = 0.0 // Title Color public fileprivate(set) var defaultTitleColor : UIColor = UIColor.gray public fileprivate(set) var highlightedTitleColor : UIColor = UIColor.white public fileprivate(set) var selectedTitleColor : UIColor = UIColor.white // Title Font public fileprivate(set) var defaultTitleFont : UIFont = UIFont.systemFont(ofSize: 14) public fileprivate(set) var highlightedTitleFont : UIFont = UIFont.systemFont(ofSize: 14) public fileprivate(set) var selectedTitleFont : UIFont = UIFont.boldSystemFont(ofSize: 14) // Selected View public fileprivate(set) var selectedViewBackgroundColor : UIColor = UIColor.clear public fileprivate(set) var selectedViewInsets : UIEdgeInsets = UIEdgeInsets.zero // MARK: - Private Properties // Views fileprivate var selectedView : UIView = UIView(frame: CGRect.zero) fileprivate var backgroundView : UIView = UIView(frame: CGRect.zero) fileprivate lazy var scrollView : InfiniteScrollView = { var scrollView = InfiniteScrollView(frame: self.bounds) scrollView.infiniteDataSource = self scrollView.infiniteDelegate = self scrollView.scrollsToTop = false scrollView.backgroundColor = UIColor.clear return scrollView }() // Contents fileprivate var contents : [String] = [] // Selected View Layout fileprivate var selectedViewTopConstraint : NSLayoutConstraint! fileprivate var selectedViewBottomConstraint : NSLayoutConstraint! fileprivate var selectedViewWidthConstraint : NSLayoutConstraint! // Sync ContainerView Scrolling fileprivate var isSyncContainerViewScrolling : Bool = false fileprivate var syncStartIndex : Int = Int.min fileprivate var syncNextIndex : Int = Int.min fileprivate var syncStartContentOffsetX : CGFloat = CGFloat.leastNormalMagnitude fileprivate var syncContentOffsetXDistance : CGFloat = CGFloat.leastNormalMagnitude fileprivate var scrollingTowards : Bool = false fileprivate var percentComplete: CGFloat = CGFloat.leastNormalMagnitude // TODO : Workaround : min item infinite scroll fileprivate var useTitles : [String] = [] fileprivate var contentsRepeatCount : Int { get { let minWidth = self.bounds.size.width * 2 let totalItemCount = self.totalItemCount() var totalItemWitdh: CGFloat = 0.0 for index in 0..<totalItemCount { totalItemWitdh += self.thicknessForIndex(index) } if totalItemWitdh == 0 { return 0 } else if minWidth < totalItemWitdh { return 0 } else { return Int(ceil(minWidth.truncatingRemainder(dividingBy: totalItemWitdh))) + 1 } } set {} } fileprivate func updateUseContens() { let contentsRepeatCount = self.contentsRepeatCount if contentsRepeatCount == 0 { self.useTitles = self.contents } else { var tmpTitles: [String] = [] var tmpIdentifiers: [String] = [] for _ in 0..<contentsRepeatCount { self.contents.forEach(){ tmpIdentifiers.append($0) } self.contents.forEach(){ tmpTitles.append($0) } } self.useTitles = tmpTitles } } // MARK: - Constructor public override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } fileprivate func commonInit() { self.addSubview(self.backgroundView) self.addSubview(self.selectedView) self.addSubview(self.scrollView) self.setupConstraint() } // MARK: - Override override public func layoutSubviews() { super.layoutSubviews() self.scrollView.frame = self.bounds } // MARK: - Public Functions public func getSelectedView() -> UIView { return self.selectedView } public func updateAppearance(_ appearance: TabMenuAppearance) { self.backgroundColor = appearance.backgroundColor // Title Layout self.titleMargin = appearance.titleMargin self.titleMinWidth = appearance.titleMinWidth // Title Color self.defaultTitleColor = appearance.defaultTitleColor self.highlightedTitleColor = appearance.highlightedTitleColor self.selectedTitleColor = appearance.selectedTitleColor // Title Font self.defaultTitleFont = appearance.defaultTitleFont self.highlightedTitleFont = appearance.highlightedTitleFont self.selectedTitleFont = appearance.selectedTitleFont // Selected View self.selectedViewBackgroundColor = appearance.selectedViewBackgroundColor self.selectedView.backgroundColor = self.selectedViewBackgroundColor self.selectedViewInsets = appearance.selectedViewInsets self.backgroundView.subviews.forEach() { $0.removeFromSuperview() } if let _contentsView = appearance.backgroundContentsView { self.backgroundView.addSubview(_contentsView) self.backgroundView.allPin(_contentsView) } self.updateSelectedViewLayout(false) self.updateButtonAttribute() self.scrollView.reloadViews() } public func addTitle(_ title: String) { self.contents.append(title) self.reload() } public func removeContentAtIndex(_ index: Int) { self.contents.remove(at: index) self.reload() } public func scrollToCenter(_ index: Int, animated: Bool, animation: (() -> Void)?, completion: (() -> Void)?) { self.scrollView.scrollToCenter(index, animated: animated, animation: animation!, completion: completion!) } public func stopScrolling(_ index: Int) { self.scrollView.isScrollEnabled = false self.scrollView.setContentOffset(self.scrollView.contentOffset, animated: false) self.scrollView.isScrollEnabled = true self.scrollView.resetWithIndex(index) self.updateSelectedButton(index) } public func reload() { self.updateUseContens() self.scrollView.resetWithIndex(0) self.updateSelectedButton(0) self.updateSelectedViewLayout(false) } } // MARK: - Sync ContainerView Scrolling extension PagerTabMenuView { internal func syncContainerViewScrollTo(_ currentIndex: Int, percentComplete: CGFloat, scrollingTowards: Bool) { if self.isSyncContainerViewScrolling { self.scrollingTowards = scrollingTowards self.syncOffset(percentComplete) self.syncSelectedViewWidth(percentComplete) self.syncButtons(percentComplete) } else { self.scrollView.scrollToCenter(currentIndex, animated: false, animation: nil, completion: nil) if let _currentItem = self.scrollView.itemAtCenterPosition() { let nextItem = self.scrollView.itemAtIndex(_currentItem.index + (scrollingTowards ? -1 : 1)) if let _nextItem = nextItem { self.scrollView.isUserInteractionEnabled = false self.isSyncContainerViewScrolling = true self.syncStartIndex = _currentItem.index self.syncNextIndex = _nextItem.index self.syncStartContentOffsetX = self.scrollView.contentOffset.x let startOffsetX = _currentItem.view.frame.midX let endOffsetX = _nextItem.view.frame.midX self.scrollingTowards = scrollingTowards self.syncContentOffsetXDistance = scrollingTowards ? startOffsetX - endOffsetX : endOffsetX - startOffsetX } } } } internal func finishSyncContainerViewScroll(_ index: Int) { self.scrollView.isUserInteractionEnabled = true self.isSyncContainerViewScrolling = false self.percentComplete = CGFloat.leastNormalMagnitude self.updateButtonAttribute() if let _centerItem = self.scrollView.itemAtIndex(index) { self.updateCenterItem(_centerItem, animated: false) } } internal func syncOffset(_ percentComplete: CGFloat) { if self.percentComplete >= 1.0 { return } self.percentComplete = percentComplete let diff = self.syncContentOffsetXDistance * percentComplete let offset = self.scrollingTowards ? self.syncStartContentOffsetX - diff : self.syncStartContentOffsetX + diff self.scrollView.contentOffset = CGPoint(x: offset, y: 0) } internal func syncSelectedViewWidth(_ percentComplete: CGFloat) { guard let _currentItem = self.scrollView.itemAtIndex(self.syncStartIndex), let _nextItem = self.scrollView.itemAtIndex(self.syncNextIndex) else { return } let inset = self.selectedViewInsets.left + self.selectedViewInsets.right let currentWidth = _currentItem.thickness - inset let nextWidth = _nextItem.thickness - inset let diff = nextWidth - currentWidth self.selectedViewWidthConstraint.constant = currentWidth + diff * percentComplete } internal func syncButtons(_ percentComplete: CGFloat) { guard let _currentItem = self.scrollView.itemAtIndex(self.syncStartIndex), let _nextItem = self.scrollView.itemAtIndex(self.syncNextIndex) else { return } let normal = self.defaultTitleColor.getRGBAStruct() let selected = self.selectedTitleColor.getRGBAStruct() let absRatio = fabs(percentComplete) let prevColor = UIColor( red: normal.red * absRatio + selected.red * (1.0 - absRatio), green: normal.green * absRatio + selected.green * (1.0 - absRatio), blue: normal.blue * absRatio + selected.blue * (1.0 - absRatio), alpha: normal.alpha * absRatio + selected.alpha * (1.0 - absRatio) ) let nextColor = UIColor( red: normal.red * (1.0 - absRatio) + selected.red * absRatio, green: normal.green * (1.0 - absRatio) + selected.green * absRatio, blue: normal.blue * (1.0 - absRatio) + selected.blue * absRatio, alpha: normal.alpha * (1.0 - absRatio) + selected.alpha * absRatio ) let currentButton = _currentItem.view as! UIButton let nextButton = _nextItem.view as! UIButton currentButton.setTitleColor(prevColor, for: UIControlState()) nextButton.setTitleColor(nextColor, for: UIControlState()) self.syncButtonTitleColor(currentButton, color: prevColor) self.syncButtonTitleColor(nextButton, color: nextColor) } internal func syncButtonTitleColor(_ button: UIButton, color: UIColor) { button.setButtonTitleAttribute(self.defaultTitleFont, textColor: color, state: UIControlState()) button.setButtonTitleAttribute(self.highlightedTitleFont, textColor: color, state: .highlighted) button.setButtonTitleAttribute(self.selectedTitleFont, textColor: color, state: .selected) } } // MARK: - Button Customize extension PagerTabMenuView { fileprivate func createTitleButton(_ title: String) -> UIButton { let button = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: self.titleMinWidth, height: self.frame.height)) button.isExclusiveTouch = true button.setTitle(title, for: UIControlState()) self.updateButtonTitleAttribute(button) button.addTarget(self, action: #selector(PagerTabMenuView.tabMenuButtonTapped(_:)), for: .touchUpInside) return button } @objc public func tabMenuButtonTapped(_ sender: UIButton) { if let _item = self.scrollView.itemAtView(sender) { self.updateCenterItem(_item, animated: true) self.selectedIndexHandler?(_item.index) } } fileprivate func updateButtonAttribute() { self.scrollView.subviews.forEach() { let button = $0 as! UIButton self.updateButtonTitleAttribute(button) } } fileprivate func updateButtonTitleAttribute(_ button: UIButton) { button.setButtonTitleAttribute(self.defaultTitleFont, textColor: self.defaultTitleColor, state: UIControlState()) button.setButtonTitleAttribute(self.highlightedTitleFont, textColor: self.highlightedTitleColor, state: .highlighted) button.setButtonTitleAttribute(self.selectedTitleFont, textColor: self.selectedTitleColor, state: .selected) } } extension UIButton { public func setButtonTitleAttribute(_ font: UIFont, textColor: UIColor, state: UIControlState) { guard let _title = self.title(for: UIControlState()) else { return } self.setAttributedTitle(NSAttributedString(string: _title, attributes: [ NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor, ] ), for: state) } } // MARK: - Layout extension PagerTabMenuView { fileprivate func setupConstraint() { self.allPin(self.backgroundView) self.allPin(self.scrollView) self.selectedViewTopConstraint = self.addPin(self.selectedView, attribute: .top, toView: self, constant: self.selectedViewInsets.top) self.selectedViewBottomConstraint = self.addPin(self.selectedView, attribute: .bottom, toView: self, constant: -self.selectedViewInsets.bottom) self.selectedViewWidthConstraint = addConstraint( self.selectedView, relation: .equal, withItem: self.selectedView, withAttribute: .width, toItem: nil, toAttribute: .width, constant: self.titleMinWidth ) _ = addConstraint( self, relation: .equal, withItem: self, withAttribute: .centerX, toItem: self.selectedView, toAttribute: .centerX, constant: 0 ) } internal func updateSelectedViewLayout(_ animated: Bool) { self.updateSelectedViewWidth() self.selectedViewTopConstraint.constant = self.selectedViewInsets.top self.selectedViewBottomConstraint.constant = -self.selectedViewInsets.bottom self.updateSelectedViewHandler?(self.selectedView) UIView.animate(withDuration: animated ? 0.25 : 0, animations: { self.selectedView.layoutIfNeeded() }) } fileprivate func updateSelectedViewWidth() { guard let _centerItem = self.scrollView.itemAtCenterPosition() else { return } let inset = self.selectedViewInsets.left + self.selectedViewInsets.right self.selectedViewWidthConstraint.constant = _centerItem.thickness - inset } fileprivate func updateCenterItem(_ item: InfiniteItem, animated: Bool) { self.scrollView.scrollToCenter(item.index, animated: animated, animation: nil, completion: nil) self.updateSelectedButton(item.index) self.updateSelectedViewLayout(animated) } fileprivate func updateSelectedButton(_ index: Int) { self.scrollView.updateItems() { let itemButton = $0.view as! UIButton itemButton.isSelected = $0.index == index ? true : false return $0 } } } // MARK: - InfiniteScrollViewDataSource extension PagerTabMenuView: InfiniteScrollViewDataSource { public func totalItemCount() -> Int { return self.useTitles.count } public func viewForIndex(_ index: Int) -> UIView { let title = self.useTitles[index] let button = self.createTitleButton(title) return button } public func thicknessForIndex(_ index: Int) -> CGFloat { let title = self.useTitles[index] let fontAttr: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font : self.selectedTitleFont] var width = NSString(string: title).size(withAttributes: fontAttr).width if width < self.titleMinWidth { width = self.titleMinWidth } return width + self.titleMargin * 2 } } // MARK: - InfiniteScrollViewDelegate extension PagerTabMenuView: InfiniteScrollViewDelegate { public func updateContentOffset(_ delta: CGFloat) { self.syncStartContentOffsetX += delta } public func infiniteScrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { } public func infiniteScrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard !self.isSyncContainerViewScrolling else { return } self.willBeginScrollingHandler?(self.selectedView) } public func infinitScrollViewDidScroll(_ scrollView: UIScrollView) { } public func infiniteScrollViewDidEndCenterScrolling(_ item: InfiniteItem) { guard !self.isSyncContainerViewScrolling else { return } self.updateCenterItem(item, animated: false) self.didEndTabMenuScrollingHandler?(self.selectedView) self.selectedIndexHandler?(item.index) } public func infiniteScrollViewDidShowCenterItem(_ item: InfiniteItem) { guard !self.isSyncContainerViewScrolling else { return } self.updateCenterItem(item, animated: false) } }
mit
74e8d68d9e77b24a842981077a81228f
37.463617
151
0.655802
5.337853
false
false
false
false
CharlesVu/Smart-iPad
Persistance/Persistance/RealmModels/RealmWeatherCity.swift
1
867
// // WeatherCity.swift // Persistance // // Created by Charles Vu on 05/06/2019. // Copyright © 2019 Charles Vu. All rights reserved. // import Foundation import RealmSwift @objcMembers public class RealmWeatherCity: Object { public dynamic var name: String! = "" public dynamic var longitude: Double! = 0 public dynamic var latitude: Double! = 0 override public static func primaryKey() -> String? { return "name" } convenience init(name: String, longitude: Double, latitude: Double) { self.init() self.name = name self.longitude = longitude self.latitude = latitude } convenience init(city: WeatherCity) { self.init() self.name = city.name self.longitude = city.longitude self.latitude = city.latitude } }
mit
5ca1e8373edc4a34984ecc5bcf59db36
23.055556
57
0.610855
4.373737
false
false
false
false
zisko/swift
test/IRGen/associated_types.swift
1
4398
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=i386 || CPU=x86_64 protocol Runcer { associatedtype Runcee } protocol Runcible { associatedtype RuncerType : Runcer associatedtype AltRuncerType : Runcer } struct Mince {} struct Quince : Runcer { typealias Runcee = Mince } struct Spoon : Runcible { typealias RuncerType = Quince typealias AltRuncerType = Quince } struct Owl<T : Runcible, U> { // CHECK: define hidden swiftcc void @"$S16associated_types3OwlV3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque* func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { } } class Pussycat<T : Runcible, U> { init() {} // CHECK: define hidden swiftcc void @"$S16associated_types8PussycatC3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %T16associated_types8PussycatC* swiftself) func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { } } func owl() -> Owl<Spoon, Int> { return Owl() } func owl2() { Owl<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon()) } func pussycat() -> Pussycat<Spoon, Int> { return Pussycat() } func pussycat2() { Pussycat<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon()) } protocol Speedy { static func accelerate() } protocol FastRuncer { associatedtype Runcee : Speedy } protocol FastRuncible { associatedtype RuncerType : FastRuncer } // This is a complex example demonstrating the need to pull conformance // information for archetypes from all paths to that archetype, not just // its parent relationships. func testFastRuncible<T: Runcible, U: FastRuncible>(_ t: T, u: U) where T.RuncerType == U.RuncerType { U.RuncerType.Runcee.accelerate() } // CHECK: define hidden swiftcc void @"$S16associated_types16testFastRuncible_1uyx_q_tAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) #0 { // 1. Get the type metadata for U.RuncerType.Runcee. // 1a. Get the type metadata for U.RuncerType. // Note that we actually look things up in T, which is going to prove unfortunate. // CHECK: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.Runcible, i32 1 // CHECK: [[T0:%.*]] = load i8*, i8** [[T0_GEP]] // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to %swift.type* (%swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType = call %swift.type* [[T1]](%swift.type* %T, i8** %T.Runcible) // 2. Get the witness table for U.RuncerType.Runcee : Speedy // 2a. Get the protocol witness table for U.RuncerType : FastRuncer. // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** %U.FastRuncible, i32 2 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], // CHECK-NEXT: [[T2:%.*]] = bitcast i8* [[T1]] to i8** (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType.FastRuncer = call i8** [[T2]](%swift.type* %T.RuncerType, %swift.type* %U, i8** %U.FastRuncible) // 1c. Get the type metadata for U.RuncerType.Runcee. // CHECK-NEXT: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.FastRuncer, i32 1 // CHECK-NEXT: [[T0:%.*]] = load i8*, i8** [[T0_GEP]] // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to %swift.type* (%swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType.Runcee = call %swift.type* [[T1]](%swift.type* %T.RuncerType, i8** %T.RuncerType.FastRuncer) // 2b. Get the witness table for U.RuncerType.Runcee : Speedy. // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.FastRuncer, i32 2 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], // CHECK-NEXT: [[T2:%.*]] = bitcast i8* [[T1]] to i8** (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType.Runcee.Speedy = call i8** [[T2]](%swift.type* %T.RuncerType.Runcee, %swift.type* %T.RuncerType, i8** %T.RuncerType.FastRuncer) // 3. Perform the actual call. // CHECK-NEXT: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.Runcee.Speedy, i32 1 // CHECK-NEXT: [[T0:%.*]] = load i8*, i8** [[T0_GEP]] // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to void (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: call swiftcc void [[T1]](%swift.type* swiftself %T.RuncerType.Runcee, %swift.type* %T.RuncerType.Runcee, i8** %T.RuncerType.Runcee.Speedy)
apache-2.0
d1665c084716749b328f6fa2e6621fb8
41.699029
274
0.659845
3.134711
false
false
false
false
yujinjcho/movie_recommendations
ios_ui/Pods/Nimble/Sources/Nimble/Matchers/BeVoid.swift
97
510
import Foundation /// A Nimble matcher that succeeds when the actual value is Void. public func beVoid() -> Predicate<()> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "be void" let actualValue: ()? = try actualExpression.evaluate() return actualValue != nil } } public func == (lhs: Expectation<()>, rhs: ()) { lhs.to(beVoid()) } public func != (lhs: Expectation<()>, rhs: ()) { lhs.toNot(beVoid()) }
mit
b92f5ab01ecd7b24fe558723d750f2c7
27.333333
80
0.652941
4.513274
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_10000000_asyncsequenceproducer.swift
1
1707
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) fileprivate typealias SequenceProducer = NIOAsyncSequenceProducer<Int, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate> @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) fileprivate final class Delegate: NIOAsyncSequenceProducerDelegate, @unchecked Sendable { private let elements = Array(repeating: 1, count: 1000) var source: SequenceProducer.Source! func produceMore() { _ = self.source.yield(contentsOf: self.elements) } func didTerminate() {} } func run(identifier: String) { guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) else { return } measure(identifier: identifier) { let delegate = Delegate() let producer = SequenceProducer.makeSequence(backPressureStrategy: .init(lowWatermark: 100, highWatermark: 500), delegate: delegate) let sequence = producer.sequence delegate.source = producer.source var counter = 0 for await i in sequence { counter += i if counter == 10000000 { return counter } } return counter } }
apache-2.0
ec76b682c72e3380e3dd42da509c02c0
30.611111
145
0.615114
4.768156
false
false
false
false
lbkchen/cvicu-app
complicationsapp/Pods/Eureka/Source/Rows/SegmentedRow.swift
1
5762
// // SegmentedRow.swift // Eureka // // Created by Martin Barreto on 2/23/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation //MARK: SegmentedCell public class SegmentedCell<T: Equatable> : Cell<T>, CellType { public var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, forAxis: .Horizontal) return textLabel } lazy public var segmentedControl : UISegmentedControl = { let result = UISegmentedControl() result.translatesAutoresizingMaskIntoConstraints = false result.setContentHuggingPriority(500, forAxis: .Horizontal) return result }() private var dynamicConstraints = [NSLayoutConstraint]() required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } deinit { segmentedControl.removeTarget(self, action: nil, forControlEvents: .AllEvents) titleLabel?.removeObserver(self, forKeyPath: "text") imageView?.removeObserver(self, forKeyPath: "image") } public override func setup() { super.setup() selectionStyle = .None contentView.addSubview(titleLabel!) contentView.addSubview(segmentedControl) titleLabel?.addObserver(self, forKeyPath: "text", options: [.Old, .New], context: nil) imageView?.addObserver(self, forKeyPath: "image", options: [.Old, .New], context: nil) segmentedControl.addTarget(self, action: #selector(SegmentedCell.valueChanged), forControlEvents: .ValueChanged) contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0)) } public override func update() { super.update() detailTextLabel?.text = nil updateSegmentedControl() segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControlNoSegment segmentedControl.enabled = !row.isDisabled } func valueChanged() { row.value = (row as! SegmentedRow<T>).options[segmentedControl.selectedSegmentIndex] } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let obj = object, let changeType = change, let _ = keyPath where ((obj === titleLabel && keyPath == "text") || (obj === imageView && keyPath == "image")) && changeType[NSKeyValueChangeKindKey]?.unsignedLongValue == NSKeyValueChange.Setting.rawValue{ setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } func updateSegmentedControl() { segmentedControl.removeAllSegments() items().enumerate().forEach { segmentedControl.insertSegmentWithTitle($0.element, atIndex: $0.index, animated: false) } } public override func updateConstraints() { contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["segmentedControl": segmentedControl] var hasImageView = false var hasTitleLabel = false if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView hasImageView = true } if let titleLabel = titleLabel, text = titleLabel.text where !text.isEmpty { views["titleLabel"] = titleLabel hasTitleLabel = true dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0)) } dynamicConstraints.append(NSLayoutConstraint(item: segmentedControl, attribute: .Width, relatedBy: .GreaterThanOrEqual, toItem: contentView, attribute: .Width, multiplier: 0.3, constant: 0.0)) if hasImageView && hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]-[titleLabel]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if hasImageView && !hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if !hasImageView && hasTitleLabel { dynamicConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[titleLabel]-[segmentedControl]-|", options: .AlignAllCenterY, metrics: nil, views: views) } else { dynamicConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segmentedControl]-|", options: .AlignAllCenterY, metrics: nil, views: views) } contentView.addConstraints(dynamicConstraints) super.updateConstraints() } func items() -> [String] {// or create protocol for options var result = [String]() for object in (row as! SegmentedRow<T>).options { result.append(row.displayValueFor?(object) ?? "") } return result } func selectedIndex() -> Int? { guard let value = row.value else { return nil } return (row as! SegmentedRow<T>).options.indexOf(value) } } //MARK: SegmentedRow /// An options row where the user can select an option from an UISegmentedControl public final class SegmentedRow<T: Equatable>: OptionsRow<T, SegmentedCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
81c071b7de4f7e2eeddca59d3f1f7176
41.992537
260
0.667592
5.40939
false
false
false
false
babarqb/HackingWithSwift
project33/Project33/AddCommentsViewController.swift
24
1588
// // AddCommentsViewController.swift // Project33 // // Created by Hudzilla on 19/09/2015. // Copyright © 2015 Paul Hudson. All rights reserved. // import UIKit class AddCommentsViewController: UIViewController, UITextViewDelegate { var genre: String! var comments: UITextView! let placeholder = "If you have any additional comments that might help identify your tune, enter them here." override func loadView() { super.loadView() comments = UITextView() comments.translatesAutoresizingMaskIntoConstraints = false comments.delegate = self comments.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) view.addSubview(comments) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[comments]|", options: .AlignAllCenterX, metrics: nil, views: ["comments": comments])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[comments]|", options: .AlignAllCenterX, metrics: nil, views: ["comments": comments])) } override func viewDidLoad() { super.viewDidLoad() title = "Comments" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Submit", style: .Plain, target: self, action: "submitTapped") comments.text = placeholder } func submitTapped() { let vc = SubmitViewController() vc.genre = genre if comments.text == placeholder { vc.comments = "" } else { vc.comments = comments.text } navigationController?.pushViewController(vc, animated: true) } func textViewDidBeginEditing(textView: UITextView) { if textView.text == placeholder { textView.text = "" } } }
unlicense
047731daccbd8828313a8da8c50b1d04
27.339286
159
0.743541
4.266129
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Foundation/BloomFilter/SipHash/SipHasher.swift
4
6443
// // SipHasher.swift // SipHash // // Created by Károly Lőrentey on 2016-03-08. // Copyright © 2016 Károly Lőrentey. @inline(__always) private func rotateLeft(_ value: UInt64, by amount: UInt64) -> UInt64 { return (value << amount) | (value >> (64 - amount)) } /// An implementation of the [SipHash-2-4](https://131002.net/siphash) hashing algorithm, /// suitable for use in projects outside the Swift standard library. /// (The Swift stdlib already includes SipHash; unfortunately its API is not public.) /// /// SipHash was invented by Jean-Philippe Aumasson and Daniel J. Bernstein. public struct SipHasher { /// The number of compression rounds. private static let c = 2 /// The number of finalization rounds. private static let d = 4 /// The default key, used by the default initializer. /// Each process has a unique key, chosen randomly when the first instance of `SipHasher` is initialized. static let key: (UInt64, UInt64) = (randomUInt64(), randomUInt64()) /// Word 0 of the internal state, initialized to ASCII encoding of "somepseu". var v0: UInt64 = 0x736f6d6570736575 /// Word 1 of the internal state, initialized to ASCII encoding of "dorandom". var v1: UInt64 = 0x646f72616e646f6d /// Word 2 of the internal state, initialized to ASCII encoding of "lygenera". var v2: UInt64 = 0x6c7967656e657261 /// Word 3 of the internal state, initialized to ASCII encoding of "tedbytes". var v3: UInt64 = 0x7465646279746573 /// The current partial word, not yet mixed in with the internal state. var pendingBytes: UInt64 = 0 /// The number of bytes that are currently pending in `tailBytes`. Guaranteed to be between 0 and 7. var pendingByteCount = 0 /// The number of bytes collected so far, or -1 if the hash value has already been finalized. var byteCount = 0 //MARK: Initializers /// Initialize a new instance with the default key, generated randomly the first time this initializer is called. public init() { self.init(k0: SipHasher.key.0, k1: SipHasher.key.1) } /// Initialize a new instance with the specified key. /// /// - Parameter k0: The low 64 bits of the secret key. /// - Parameter k1: The high 64 bits of the secret key. public init(k0: UInt64, k1: UInt64) { v0 ^= k0 v1 ^= k1 v2 ^= k0 v3 ^= k1 } @inline(__always) private mutating func sipRound() { v0 = v0 &+ v1 v1 = rotateLeft(v1, by: 13) v1 ^= v0 v0 = rotateLeft(v0, by: 32) v2 = v2 &+ v3 v3 = rotateLeft(v3, by: 16) v3 ^= v2 v0 = v0 &+ v3 v3 = rotateLeft(v3, by: 21) v3 ^= v0 v2 = v2 &+ v1 v1 = rotateLeft(v1, by: 17) v1 ^= v2 v2 = rotateLeft(v2, by: 32) } mutating func compressWord(_ m: UInt64) { v3 ^= m for _ in 0 ..< SipHasher.c { sipRound() } v0 ^= m } mutating func _finalize() -> UInt64 { precondition(byteCount >= 0) pendingBytes |= UInt64(byteCount) << 56 byteCount = -1 compressWord(pendingBytes) v2 ^= 0xff for _ in 0 ..< SipHasher.d { sipRound() } return v0 ^ v1 ^ v2 ^ v3 } //MARK: Appending data /// Add all bytes in `buffer` to this hash. /// /// - Requires: `finalize()` hasn't been called on this instance yet. public mutating func append(_ buffer: UnsafeRawBufferPointer) { precondition(byteCount >= 0) // Use the first couple of bytes to complete the pending word. var i = 0 if pendingByteCount > 0 { let readCount = min(buffer.count, 8 - pendingByteCount) var m: UInt64 = 0 switch readCount { case 7: m |= UInt64(buffer[6]) << 48 fallthrough case 6: m |= UInt64(buffer[5]) << 40 fallthrough case 5: m |= UInt64(buffer[4]) << 32 fallthrough case 4: m |= UInt64(buffer[3]) << 24 fallthrough case 3: m |= UInt64(buffer[2]) << 16 fallthrough case 2: m |= UInt64(buffer[1]) << 8 fallthrough case 1: m |= UInt64(buffer[0]) default: precondition(readCount == 0) } pendingBytes |= m << UInt64(pendingByteCount << 3) pendingByteCount += readCount i += readCount if pendingByteCount == 8 { compressWord(pendingBytes) pendingBytes = 0 pendingByteCount = 0 } } let left = (buffer.count - i) & 7 let end = (buffer.count - i) - left while i < end { let m = UInt64(buffer[i]) | (UInt64(buffer[i + 1]) << 8) | (UInt64(buffer[i + 2]) << 16) | (UInt64(buffer[i + 3]) << 24) | (UInt64(buffer[i + 4]) << 32) | (UInt64(buffer[i + 5]) << 40) | (UInt64(buffer[i + 6]) << 48) | (UInt64(buffer[i + 7]) << 56) compressWord(m) i += 8 } switch left { case 7: pendingBytes |= UInt64(buffer[i + 6]) << 48 fallthrough case 6: pendingBytes |= UInt64(buffer[i + 5]) << 40 fallthrough case 5: pendingBytes |= UInt64(buffer[i + 4]) << 32 fallthrough case 4: pendingBytes |= UInt64(buffer[i + 3]) << 24 fallthrough case 3: pendingBytes |= UInt64(buffer[i + 2]) << 16 fallthrough case 2: pendingBytes |= UInt64(buffer[i + 1]) << 8 fallthrough case 1: pendingBytes |= UInt64(buffer[i]) default: precondition(left == 0) } pendingByteCount = left byteCount += buffer.count } //MARK: Finalization /// Finalize this hash and return the hash value. /// /// - Requires: `finalize()` hasn't been called on this instance yet. public mutating func finalize() -> Int { return Int(truncatingBitPattern: _finalize()) } }
mpl-2.0
374b882e3434e6301b6b9256f19c4b5f
30.714286
117
0.53557
4.105867
false
false
false
false