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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
googlearchive/science-journal-ios
|
ScienceJournal/Sensors/AltimeterSensor.swift
|
1
|
3523
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import CoreMotion
import Foundation
/// A sensor that reads data from the device's altimeter sensor.
class AltimeterSensor: Sensor {
// MARK: - Properties
private static let altimeter = CMAltimeter()
private var currentAltitudeData: CMAltitudeData?
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - sensorId: The sensor ID.
/// - name: The name of the sensor.
/// - textDescription: The text description of the accelerometer sensor.
/// - iconName: The icon name for the sensor.
/// - animatingIconName: The animating icon name for the sensor.
/// - unitDescription: Units the sensor's values are measured in.
/// - learnMore: The contents of the learn more view for a sensor.
/// - sensorTimer: The sensor timer to use for this sensor.
init(sensorId: String,
name: String,
textDescription: String,
iconName: String,
animatingIconName: String,
unitDescription: String?,
learnMore: LearnMore,
sensorTimer: SensorTimer) {
let animatingIconView = RelativeScaleAnimationView(iconName: animatingIconName)
super.init(sensorId: sensorId,
name: name,
textDescription: textDescription,
iconName: iconName,
animatingIconView: animatingIconView,
unitDescription: unitDescription,
learnMore: learnMore,
sensorTimer: sensorTimer)
isSupported = CMAltimeter.isRelativeAltitudeAvailable()
}
override func start() {
guard state != .ready else { return }
state = .ready
AltimeterSensor.altimeter.startRelativeAltitudeUpdates(to: .main) {
[weak self] (altitudeData, _) in
if let altitudeData = altitudeData {
self?.currentAltitudeData = altitudeData
}
}
}
override func pause() {
guard state != .paused else { return }
state = .paused
AltimeterSensor.altimeter.stopRelativeAltitudeUpdates()
}
override func callListenerBlocksWithData(atMilliseconds milliseconds: Int64) {
// TODO: Make sensors pending until a value is available. http://b/64477130
guard let altitudeData = currentAltitudeData else { return }
callListenerBlocksWithAltitudeData(altitudeData, atMilliseconds: milliseconds)
}
/// Calls all listener blocks with altitude data. Must be overriden by subclasses to call with
/// the data value it is associated with (pressure or relative altitude).
///
/// - Parameters:
/// - altitudeData: The CMAltitudeData received from the altimeter.
/// - milliseconds: The date in milliseconds when the timer fired.
func callListenerBlocksWithAltitudeData(_ altitudeData: CMAltitudeData,
atMilliseconds milliseconds: Int64) {
fatalError("`callListenerBlocksWithAltitudeData` must be overridden by the subclass.")
}
}
|
apache-2.0
|
175b32a8df39b85fabddd66819526665
| 35.319588 | 96 | 0.68805 | 4.581274 | false | false | false | false |
martinomamic/CarBooking
|
CarBooking/Controllers/CreateBooking/CreateBookingPresenter.swift
|
1
|
1158
|
//
// CreateBookingPresenter.swift
// CarBooking
//
// Created by Martino Mamic on 29/07/2017.
// Copyright © 2017 Martino Mamic. All rights reserved.
//
import UIKit
import Foundation
typealias DisplayedBooking = CreateBookingUseCases.CreateBooking.ViewModel.DisplayedBooking
protocol CreateBookingPresentationDelegate {
func presentCreatedBooking(response: CreateBookingUseCases.CreateBooking.Response)
}
class CreateBookingPresenter: CreateBookingPresentationDelegate {
weak var viewController: CreateBookingDisplayDelegate?
func presentCreatedBooking(response: CreateBookingUseCases.CreateBooking.Response) {
let booking = response.booking
let car = booking.car
let displayedBooking = DisplayedBooking(startDate: booking.startDate,
endDate: booking.endDate.bookingDate(), carInfo: car.info,
carName: car.name, carImage: car.image)
let viewModel = CreateBookingUseCases.CreateBooking.ViewModel(displayedBooking: displayedBooking)
viewController?.displayCreatedBooking(viewModel: viewModel)
}
}
|
mit
|
d220f3251b59af10b9696d0a3bd77c66
| 38.896552 | 106 | 0.724287 | 5.119469 | false | false | false | false |
ReticentJohn/Amaroq
|
DireFloof/MSPushNotificationStore.swift
|
1
|
4043
|
//
// MSPushNotificationStore.swift
// DireFloof
//
// Created by John Gabelmann on 2/24/19.
// Copyright © 2019 Keyboard Floofs. All rights reserved.
//
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class MSPushNotificationStore: NSObject {
static let singleton = MSPushNotificationStore()
@objc class func sharedStore() -> MSPushNotificationStore {
return MSPushNotificationStore.singleton
}
private var state: PushNotificationState? = UserDefaults(suiteName: "group.keyboardfloofs.amarok")?.retrieve(object: PushNotificationState.self, fromKey: MS_CLIENT_NOTIFICATION_STATE_KEY) {
didSet {
guard let state = state else {
return
}
UserDefaults(suiteName: "group.keyboardfloofs.amarok")?.save(customObject: state, inKey: MS_CLIENT_NOTIFICATION_STATE_KEY)
}
}
@objc func subscribePushNotifications(_ deviceToken: NSData, completion: ((Bool, NSError?) -> Void)?) {
let token = (deviceToken as Data).map { String(format: "%02.2hhx", $0) }.joined()
let requestToken = PushNotificationDeviceToken(deviceToken: deviceToken as Data)
// TODO: Think of a better way to only update the notification state on token change, this will have notification decryption problems on network failure
let alerts = PushNotificationAlerts(favourite: DWSettingStore.shared()?.favoriteNotifications ?? false, follow: DWSettingStore.shared()?.newFollowerNotifications ?? false, mention: DWSettingStore.shared()?.mentionNotifications ?? false, reblog: DWSettingStore.shared()?.boostNotifications ?? false)
let subscription = PushNotificationSubscription(endpoint: URL(string:"https://amaroq-apns.herokuapp.com/relay-to/production/\(token)")!, alerts: alerts)
let receiver = try! PushNotificationReceiver()
state = PushNotificationState(receiver: receiver, subscription: subscription, deviceToken: requestToken)
let params = PushNotificationSubscriptionRequest(endpoint: "https://amaroq-apns.herokuapp.com/relay-to/production/\(token)", receiver: receiver, alerts: alerts)
guard let baseAPI = MSAppStore.shared()?.base_api_url_string else {
if let completion = completion {
completion(false, nil)
}
return
}
MSAPIClient.sharedClient(withBaseAPI: baseAPI)?.post("push/subscription", parameters: params.dictionary, constructingBodyWith: nil, progress: nil, success: { (task, responseObject) in
if let completion = completion {
completion(true, nil)
}
}, failure: { (task, error) in
if let completion = completion {
completion(false, error as NSError)
}
})
}
}
extension UserDefaults {
func save<T:Encodable>(customObject object: T, inKey key: String) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(object) {
self.set(encoded, forKey: key)
}
}
func retrieve<T:Decodable>(object type:T.Type, fromKey key: String) -> T? {
if let data = self.data(forKey: key) {
let decoder = JSONDecoder()
if let object = try? decoder.decode(type, from: data) {
return object
}else {
print("Couldnt decode object")
return nil
}
}else {
print("Couldnt find key")
return nil
}
}
}
extension Encodable {
var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
|
mpl-2.0
|
08876a2d89474ea30b244246ebb99f18
| 40.670103 | 306 | 0.634834 | 4.593182 | false | false | false | false |
andrewgrant/Playgrounds
|
FilteringTypes.playground/Contents.swift
|
1
|
1119
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class Base {
var name : String
init(name newName: String) {
name = newName
}
func des
}
class Foo : Base {
}
class Bar : Base {
}
let numbers = [ 10000, 10303, 30913, 50000, 100000, 101039, 1000000 ]
let formattedNumbers = numbers.map { $0 + 1}
let mixedArray = [Foo(name: "Frank"), Bar(name: "Bob"), Foo(name: "Gary")]
func filterTest(filter : (item : Base) -> Bool) -> [Base] {
return mixedArray.filter(filter)
}
let items = filterTest { item in return true }
func filterTypes<T>(filter : ((item : T) -> Bool)) -> [T] {
var items = [T]()
let arr = mixedArray.filter {
if $0 is T {
items.append($0 as! T)
return true
}
return false
}
return items
}
let bars = filterTypes{ (item : Foo) -> Bool in
return true
}
let frank = filterTypes { (item : Foo) -> Bool in
return item.name == "Frank"
}
let bobs = filterTypes() { (item : Bar) -> Bool in
return true
}
|
mit
|
949665988c8b4ce3b2731e66ffa5f3a5
| 15.701493 | 74 | 0.561215 | 3.475155 | false | false | false | false |
uias/Tabman
|
Sources/Tabman/Bar/BarLayout/Types/TMHorizontalBarLayout+Separator.swift
|
1
|
3340
|
//
// TMHorizontalBarLayout+Separator.swift
// Tabman
//
// Created by Merrick Sapsford on 28/04/2019.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
extension TMHorizontalBarLayout {
internal class SeparatorView: UIView {
// swiftlint:disable nesting
private struct Defaults {
static let width: CGFloat = 1.0
static let contentInset = UIEdgeInsets(top: 4.0, left: 0.0, bottom: 4.0, right: 0.0)
}
// MARK: Properties
private let content = UIView()
@available (*, unavailable)
override var backgroundColor: UIColor? {
didSet {}
}
override var tintColor: UIColor! {
didSet {
content.backgroundColor = tintColor
}
}
private var contentWidth: NSLayoutConstraint?
private var _width: CGFloat?
var width: CGFloat! {
get {
return _width ?? Defaults.width
}
set {
_width = newValue
contentWidth?.constant = width
}
}
private var contentLeading: NSLayoutConstraint?
private var contentTop: NSLayoutConstraint?
private var contentTrailing: NSLayoutConstraint?
private var contentBottom: NSLayoutConstraint?
private var _contentInset: UIEdgeInsets?
var contentInset: UIEdgeInsets! {
get {
return _contentInset ?? Defaults.contentInset
}
set {
_contentInset = newValue
contentLeading?.constant = contentInset.left
contentTop?.constant = contentInset.top
contentTrailing?.constant = contentInset.right
contentBottom?.constant = contentInset.bottom
}
}
// MARK: Init
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
content.translatesAutoresizingMaskIntoConstraints = false
addSubview(content)
let leading = content.leadingAnchor.constraint(equalTo: leadingAnchor, constant: contentInset.left)
let top = content.topAnchor.constraint(equalTo: topAnchor, constant: contentInset.top)
let trailing = trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: contentInset.right)
let bottom = bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: contentInset.bottom)
NSLayoutConstraint.activate([
leading,
top,
trailing,
bottom
])
contentLeading = leading
contentTop = top
contentTrailing = trailing
contentBottom = bottom
contentWidth = content.widthAnchor.constraint(equalToConstant: width)
contentWidth?.isActive = true
content.backgroundColor = tintColor
}
}
}
|
mit
|
73f3904a006d0b51b13ffc86372115c6
| 30.8 | 115 | 0.550165 | 6.016216 | false | false | false | false |
duanhjlt/TextFieldEffects
|
TextFieldEffects/TextFieldEffects/MadokaTextField.swift
|
3
|
5417
|
//
// MadokaTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 05/02/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class MadokaTextField: TextFieldEffects {
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
@IBInspectable public var borderColor: UIColor? {
didSet {
updateBorder()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: CGFloat = 1
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CAShapeLayer()
private var backgroundLayerColor: UIColor?
// MARK: - TextFieldsEffectsProtocol
override func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
private func updateBorder() {
let rect = rectForBorder(bounds)
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.height - borderThickness))
path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.height - borderThickness))
path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.origin.y + borderThickness))
path.addLineToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.origin.y + borderThickness))
path.closePath()
borderLayer.path = path.CGPath
borderLayer.lineCap = kCALineCapSquare
borderLayer.lineWidth = borderThickness
borderLayer.fillColor = nil
borderLayer.strokeColor = borderColor?.CGColor
borderLayer.strokeEnd = percentageForBottomBorder()
}
private func percentageForBottomBorder() -> CGFloat {
let borderRect = rectForBorder(bounds)
let sumOfSides = (borderRect.width * 2) + (borderRect.height * 2)
return (borderRect.width * 100 / sumOfSides) / 100
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() || text!.isNotEmpty {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65)
return smallerFont
}
private func rectForBorder(bounds: CGRect) -> CGRect {
let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newRect
}
private func layoutPlaceholderInTextRect() {
if text!.isNotEmpty {
return
}
placeholderLabel.transform = CGAffineTransformIdentity
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: textRect.height - placeholderLabel.bounds.height - placeholderInsets.y,
width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height)
}
override func animateViewsForTextEntry() {
borderLayer.strokeEnd = 1
UIView.animateWithDuration(0.3, animations: {
let translate = CGAffineTransformMakeTranslation(-self.placeholderInsets.x, self.placeholderLabel.bounds.height + (self.placeholderInsets.y * 2))
let scale = CGAffineTransformMakeScale(0.9, 0.9)
self.placeholderLabel.transform = CGAffineTransformConcat(translate, scale)
})
}
override func animateViewsForTextDisplay() {
if text!.isEmpty {
borderLayer.strokeEnd = percentageForBottomBorder()
UIView.animateWithDuration(0.3, animations: {
self.placeholderLabel.transform = CGAffineTransformIdentity
})
}
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
}
|
mit
|
5b3d5c41d1462fbd37e2f7271025588d
| 32.85 | 157 | 0.632939 | 5.399801 | false | false | false | false |
MoralAlberto/SlackWebAPIKit
|
SlackWebAPIKit/Classes/Data/APIClient/APIClients/APIClient.swift
|
1
|
1401
|
import Foundation
import Alamofire
import ObjectMapper
import RxSwift
public protocol APIClientProtocol: class {
func execute(withURL url: URL?) -> Observable<[String: Any]>
}
public class APIClient: APIClientProtocol {
fileprivate let sessionManager = SessionManager()
public init() {
self.sessionManager.adapter = AccessTokenAdapter(accessToken: API.sharedInstance.getToken()!)
}
public func execute(withURL url: URL?) -> Observable<[String: Any]> {
return Observable.create { [weak self] observable in
guard let strongSelf = self else {
return Disposables.create()
}
strongSelf.sessionManager.request(url!).responseJSON(queue: .global()) { (json) in
guard let json = json.result.value as? [String : AnyObject] else {
observable.onError(APIClientError.unhandled(localizedDescription: "invalidJSON"))
return
}
guard let status = json["ok"] as? Bool, status == true else {
let error = APIClientError(type: json["error"] as! String)
observable.onError(error)
return
}
observable.onNext(json)
observable.onCompleted()
}
return Disposables.create()
}
}
}
|
mit
|
31c6f1321c5b63de5960118f2bb4a1e4
| 34.923077 | 101 | 0.579586 | 5.472656 | false | false | false | false |
VernonVan/SmartClass
|
SmartClass/Paper/Paper Result/View/ExamResultViewController.swift
|
1
|
3289
|
//
// ExamResultViewController.swift
// SmartClass
//
// Created by FSQ on 16/5/2.
// Copyright © 2016年 Vernon. All rights reserved.
//
import UIKit
import RealmSwift
import DZNEmptyDataSet
struct ResultItem
{
var studentName: String
var score: Int?
}
class ExamResultViewController: UIViewController
{
var paper: Paper?
@IBOutlet weak var tableView: UITableView!
var items = [ResultItem]()
var students: Results<Student>!
let realm = try! Realm()
// MARK: - Lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
students = realm.objects(Student.self).sorted(byProperty: "number")
tableView.dataSource = self
tableView.emptyDataSetSource = self
tableView.separatorStyle = .none
tableView.tableFooterView = UIView()
configureResultItems()
}
func configureResultItems()
{
let results = paper!.results.sorted(byProperty: "score", ascending: false)
for result in results {
let item = ResultItem(studentName: result.name!, score: result.score)
items.append(item)
}
for student in students {
if results.filter("name == '\(student.name)'").first == nil {
let item = ResultItem(studentName: student.name, score: nil)
items.append(item)
}
}
}
}
// MARK: - Table view
extension ExamResultViewController: UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath) as! ResultCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(_ cell: ResultCell, atIndexPath indexPath: IndexPath)
{
let item = items[indexPath.row]
if indexPath.row < 3 && item.score != nil {
cell.starImageView.isHidden = false
cell.orderLabel.isHidden = true
} else {
cell.starImageView.isHidden = true
cell.orderLabel.text = "\(indexPath.row + 1)"
}
cell.nameLabel.text = item.studentName
cell.scoreLabel.text = (item.score != nil ? "\(item.score!)" : NSLocalizedString("缺考", comment: ""))
cell.scoreLabel.textColor = item.score != nil ? (item.score! > 60 ? UIColor.red : ThemeBlueColor) : UIColor.lightGray
cell.backgroundColor = (indexPath.row % 2 == 0) ? UIColor.white : UIColor(netHex: 0xf5f5f5)
}
}
// MARK: - DZNEmptyDataSetSource
extension ExamResultViewController: DZNEmptyDataSetSource
{
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString!
{
let text = NSLocalizedString("请先添加学生", comment: "")
let attributes = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 22.0) ,
NSForegroundColorAttributeName : UIColor.darkGray]
return NSAttributedString(string: text , attributes: attributes)
}
}
|
mit
|
39aa44595dcd4d9f7553e062f5e53f68
| 27.938053 | 125 | 0.624771 | 4.780702 | false | false | false | false |
kaojohnny/CoreStore
|
CoreStoreTests/SelectTests.swift
|
1
|
18266
|
//
// SelectTests.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import XCTest
@testable
import CoreStore
//MARK: - SelectTests
final class SelectTests: XCTestCase {
@objc
dynamic func test_ThatAttributeSelectTerms_ConfigureCorrectly() {
do {
let term: SelectTerm = "attribute"
XCTAssertEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Attribute(let key):
XCTAssertEqual(key, "attribute")
default:
XCTFail()
}
}
do {
let term = SelectTerm.Attribute("attribute")
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Attribute(let key):
XCTAssertEqual(key, "attribute")
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatAverageSelectTerms_ConfigureCorrectly() {
do {
let term = SelectTerm.Average("attribute")
XCTAssertEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "average:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "average(attribute)")
XCTAssertTrue(nativeType == .DecimalAttributeType)
default:
XCTFail()
}
}
do {
let term = SelectTerm.Average("attribute", As: "alias")
XCTAssertEqual(term, SelectTerm.Average("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute", As: "alias2"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "average:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "alias")
XCTAssertTrue(nativeType == .DecimalAttributeType)
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatCountSelectTerms_ConfigureCorrectly() {
do {
let term = SelectTerm.Count("attribute")
XCTAssertEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "count:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "count(attribute)")
XCTAssertTrue(nativeType == .Integer64AttributeType)
default:
XCTFail()
}
}
do {
let term = SelectTerm.Count("attribute", As: "alias")
XCTAssertEqual(term, SelectTerm.Count("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute", As: "alias2"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "count:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "alias")
XCTAssertTrue(nativeType == .Integer64AttributeType)
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatMaximumSelectTerms_ConfigureCorrectly() {
do {
let term = SelectTerm.Maximum("attribute")
XCTAssertEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "max:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "max(attribute)")
XCTAssertTrue(nativeType == .UndefinedAttributeType)
default:
XCTFail()
}
}
do {
let term = SelectTerm.Maximum("attribute", As: "alias")
XCTAssertEqual(term, SelectTerm.Maximum("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute", As: "alias2"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "max:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "alias")
XCTAssertTrue(nativeType == .UndefinedAttributeType)
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatMinimumSelectTerms_ConfigureCorrectly() {
do {
let term = SelectTerm.Minimum("attribute")
XCTAssertEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "min:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "min(attribute)")
XCTAssertTrue(nativeType == .UndefinedAttributeType)
default:
XCTFail()
}
}
do {
let term = SelectTerm.Minimum("attribute", As: "alias")
XCTAssertEqual(term, SelectTerm.Minimum("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute", As: "alias2"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "min:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "alias")
XCTAssertTrue(nativeType == .UndefinedAttributeType)
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatSumSelectTerms_ConfigureCorrectly() {
do {
let term = SelectTerm.Sum("attribute")
XCTAssertEqual(term, SelectTerm.Sum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "sum:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "sum(attribute)")
XCTAssertTrue(nativeType == .DecimalAttributeType)
default:
XCTFail()
}
}
do {
let term = SelectTerm.Sum("attribute", As: "alias")
XCTAssertEqual(term, SelectTerm.Sum("attribute", As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute", As: "alias2"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute2"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
switch term {
case ._Aggregate(let function, let keyPath, let alias, let nativeType):
XCTAssertEqual(function, "sum:")
XCTAssertEqual(keyPath, "attribute")
XCTAssertEqual(alias, "alias")
XCTAssertTrue(nativeType == .DecimalAttributeType)
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatObjectIDSelectTerms_ConfigureCorrectly() {
do {
let term = SelectTerm.ObjectID()
XCTAssertEqual(term, SelectTerm.ObjectID())
XCTAssertNotEqual(term, SelectTerm.ObjectID(As: "alias"))
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
switch term {
case ._Identity(let alias, let nativeType):
XCTAssertEqual(alias, "objectID")
XCTAssertTrue(nativeType == .ObjectIDAttributeType)
default:
XCTFail()
}
}
do {
let term = SelectTerm.ObjectID(As: "alias")
XCTAssertEqual(term, SelectTerm.ObjectID(As: "alias"))
XCTAssertNotEqual(term, SelectTerm.ObjectID(As: "alias2"))
XCTAssertNotEqual(term, SelectTerm.ObjectID())
XCTAssertNotEqual(term, SelectTerm.Attribute("attribute"))
XCTAssertNotEqual(term, SelectTerm.Average("attribute"))
XCTAssertNotEqual(term, SelectTerm.Count("attribute"))
XCTAssertNotEqual(term, SelectTerm.Maximum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Minimum("attribute"))
XCTAssertNotEqual(term, SelectTerm.Sum("attribute"))
switch term {
case ._Identity(let alias, let nativeType):
XCTAssertEqual(alias, "alias")
XCTAssertTrue(nativeType == .ObjectIDAttributeType)
default:
XCTFail()
}
}
}
@objc
dynamic func test_ThatSelectClauses_ConfigureCorrectly() {
let term1 = SelectTerm.Attribute("attribute1")
let term2 = SelectTerm.Attribute("attribute2")
let term3 = SelectTerm.Attribute("attribute3")
do {
let select = Select<Int>(term1, term2, term3)
XCTAssertEqual(select.selectTerms, [term1, term2, term3])
XCTAssertNotEqual(select.selectTerms, [term1, term3, term2])
XCTAssertNotEqual(select.selectTerms, [term2, term1, term3])
XCTAssertNotEqual(select.selectTerms, [term2, term3, term1])
XCTAssertNotEqual(select.selectTerms, [term3, term1, term2])
XCTAssertNotEqual(select.selectTerms, [term3, term2, term1])
}
do {
let select = Select<Int>([term1, term2, term3])
XCTAssertEqual(select.selectTerms, [term1, term2, term3])
XCTAssertNotEqual(select.selectTerms, [term1, term3, term2])
XCTAssertNotEqual(select.selectTerms, [term2, term1, term3])
XCTAssertNotEqual(select.selectTerms, [term2, term3, term1])
XCTAssertNotEqual(select.selectTerms, [term3, term1, term2])
XCTAssertNotEqual(select.selectTerms, [term3, term2, term1])
}
}
}
|
mit
|
3087756dd02acaa0a8d05d29a59ce600
| 42.488095 | 83 | 0.5902 | 5.539885 | false | false | false | false |
binarious/bemindful
|
BeMindful/AppDelegate.swift
|
1
|
4523
|
//
// AppDelegate.swift
// BeMindful
//
// Created by Martin Bieder on 26.01.15.
// Copyright (c) 2015 Martin Bieder. All rights reserved.
//
import Cocoa
import CoreGraphics
import Foundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var statusBar = NSStatusBar.systemStatusBar()
var statusBarItem : NSStatusItem = NSStatusItem()
var active : Int = 0
var idleTime : Double = 0.0
var lastHour :Double = 0.0
var menu: NSMenu = NSMenu()
var loginHandler: LoginHandler = LoginHandler()
var menuItemStartup : NSMenuItem = NSMenuItem()
func quitApp(sender: AnyObject) {
NSApplication.sharedApplication().terminate(self)
}
func resetActive() {
active = 0
lastHour = 0.0
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
initMenu();
// check idle time every minute
var idleTimer = NSTimer.scheduledTimerWithTimeInterval(
60,
target: self,
selector: Selector("updateIdle"),
userInfo: nil,
repeats: true
)
// count every minute
var activeTimer = NSTimer.scheduledTimerWithTimeInterval(
60.2,
target: self,
selector: Selector("updateActive"),
userInfo: nil,
repeats: true
)
}
func setItemStartupText() {
var startOnLogin = loginHandler.applicationIsInStartUpItems()
menuItemStartup.title = startOnLogin ? "Don't start on login" : "Start on login"
}
func toggleLogin() {
loginHandler.toggleLaunchAtStartup()
setItemStartupText()
}
func initMenu() {
// initially set status bar text
statusBarItem = statusBar.statusItemWithLength(-1)
statusBarItem.title = "0m"
statusBarItem.menu = menu
var menuItemReset : NSMenuItem = NSMenuItem()
// Add quit item
menuItemReset.title = "Reset"
menuItemReset.action = Selector("resetActive")
menuItemReset.keyEquivalent = ""
menu.addItem(menuItemReset)
// Add startup item
menuItemStartup.action = Selector("toggleLogin")
setItemStartupText()
menuItemStartup.keyEquivalent = ""
menu.addItem(menuItemStartup)
var menuItemQuit : NSMenuItem = NSMenuItem()
// Add quit item
menuItemQuit.title = "Quit"
menuItemQuit.action = Selector("quitApp:")
menuItemQuit.keyEquivalent = ""
menu.addItem(menuItemQuit)
}
/**
* Determine active time and display it in the status bar
*/
func updateActive () {
// only active when not idle for a minute
if idleTime < 60.0 {
active = active + 1
}
var activeMin = active % 60
var activeHour = floor(Double(active) / 60)
var activeStr = ""
if activeHour > 0 {
activeStr = NSString(format: "%.0f", activeHour) + "h "
}
activeStr += String(activeMin) + "m"
statusBarItem.title = activeStr
// check change in hours
if (activeHour != lastHour) {
lastHour = activeHour
// show notification every active hour
var notification:NSUserNotification = NSUserNotification()
notification.title = "Be mindful!"
notification.subtitle = "You've been active for an hour."
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
notificationcenter.scheduleNotification(notification)
}
}
/**
* If idle time > 5 minutes then reset the active time
*/
func updateIdle () {
// collect mouse and keyboard events
let idleTimeMouse = CGEventSourceSecondsSinceLastEventType(0, kCGEventMouseMoved)
let idleTimeKeyboard = CGEventSourceSecondsSinceLastEventType(0, kCGEventKeyDown)
if idleTimeKeyboard > idleTimeMouse {
idleTime = idleTimeMouse
} else {
idleTime = idleTimeKeyboard
}
if idleTime >= 5.0 * 60.0 {
resetActive()
}
}
func applicationWillTerminate(aNotification: NSNotification) {
}
}
|
mit
|
6a7ff9a20b04041a44bce7897d7076c9
| 27.808917 | 118 | 0.591201 | 5.21684 | false | false | false | false |
twtstudio/WePeiYang-iOS
|
WePeiYang/LostFound/View/LostFoundTableViewCell.swift
|
1
|
2745
|
//
// LostFoundTableViewCell.swift
// WePeiYang
//
// Created by Qin Yubo on 16/3/31.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
class LostFoundTableViewCell: UITableViewCell {
@IBOutlet weak var picImageView: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var placeLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
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
}
func setLostFoundItem(obj: LostFoundItem, type: Int) {
nameLabel.text = obj.name
titleLabel.text = obj.title
placeLabel.text = obj.place
timeLabel.text = obj.time
phoneLabel.text = obj.phone
if type == 0 {
// lost
/*
'lost_type' => [
'0' => '其它,用户自定义',
'1' => '银行卡',
'2' => '饭卡&身份证',
'3' => '钥匙',
'4' => '书包',
'5' => '电脑包',
'6' => '手表&饰品',
'7' => 'U盘&硬盘',
'8' => '水杯',
'9' => '书',
'10' => '手机'
],
*/
switch obj.lostType {
case 0:
picImageView.image = UIImage(named: "lf_item_lostDefault")
case 1:
picImageView.image = UIImage(named: "lf_item_card")
case 2:
picImageView.image = UIImage(named: "lf_item_idcard")
case 3:
picImageView.image = UIImage(named: "lf_item_key")
case 4:
picImageView.image = UIImage(named: "lf_item_schoolbag")
case 5:
picImageView.image = UIImage(named: "lf_item_pcbag")
case 6:
picImageView.image = UIImage(named: "lf_item_watch")
case 7:
picImageView.image = UIImage(named: "lf_item_udisk")
case 8:
picImageView.image = UIImage(named: "lf_item_cup")
case 9:
picImageView.image = UIImage(named: "lf_item_book")
case 10:
picImageView.image = UIImage(named: "lf_item_phone")
default:
break
}
} else {
picImageView.setImageWithURL(NSURL(string: obj.foundPic)!, placeholderImage: UIImage(named: "lf_item_foundDefault"))
}
}
}
|
mit
|
16f1662919f45d474e34875ca848b38a
| 30.435294 | 128 | 0.513099 | 4.104455 | false | false | false | false |
mrdepth/EVEUniverse
|
Legacy/Neocom/Neocom/API+Constants.swift
|
2
|
19457
|
//
// API+Constants.swift
// Neocom
//
// Created by Artem Shimanski on 11/6/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import Dgmpp
extension ESI.Incursions.Incursion.State {
var title: String {
switch self {
case .established:
return NSLocalizedString("Established", comment: "")
case .mobilizing:
return NSLocalizedString("Mobilizing", comment: "")
case .withdrawing:
return NSLocalizedString("Withdrawing", comment: "")
}
}
}
extension ESI.Industry.Job {
var currentStatus: ESI.Industry.JobStatus {
switch status {
case .active:
return endDate < Date() ? .ready : status
default:
return status
}
}
}
extension ESI.Contracts.Contract.ContractType {
var title: String {
switch self {
case .auction:
return NSLocalizedString("Auction", comment: "")
case .courier:
return NSLocalizedString("Courier", comment: "")
case .itemExchange:
return NSLocalizedString("Item Exchange", comment: "")
case .loan:
return NSLocalizedString("Loan", comment: "")
case .unknown:
return NSLocalizedString("Unknown", comment: "")
}
}
}
extension ESI.Contracts.Contract.Availability {
var title: String {
switch self {
case .alliance:
return NSLocalizedString("Alliance", comment: "")
case .corporation:
return NSLocalizedString("Corporation", comment: "")
case .personal:
return NSLocalizedString("Personal", comment: "")
case .public:
return NSLocalizedString("Public", comment: "")
}
}
}
extension ESI.Contracts.Contract.Status {
var title: String {
switch self {
case .outstanding:
return NSLocalizedString("Outstanding", comment: "")
case .inProgress:
return NSLocalizedString("In Progress", comment: "")
case .cancelled:
return NSLocalizedString("Cancelled", comment: "")
case .deleted:
return NSLocalizedString("Deleted", comment: "")
case .failed:
return NSLocalizedString("Failed", comment: "")
case .finished, .finishedContractor, .finishedIssuer:
return NSLocalizedString("Finished", comment: "")
case .rejected:
return NSLocalizedString("Rejected", comment: "")
case .reversed:
return NSLocalizedString("Reversed", comment: "")
}
}
}
extension ESI.Contracts.Contract {
var currentStatus: ESI.Contracts.Contract.Status {
switch status {
case .outstanding, .inProgress:
return dateExpired < Date() ? .finished : status
default:
return status
}
}
var isOpen: Bool {
return dateExpired > Date() && (status == .outstanding || status == .inProgress)
}
}
extension ESI.Wallet.RefType {
var title: String {
return rawValue.replacingOccurrences(of: "_", with: " ").capitalized
}
}
public enum AssetSlot: Int, Hashable {
case hi
case med
case low
case rig
case subsystem
case drone
case cargo
case implant
var title: String {
switch self {
case .hi:
return NSLocalizedString("Hi Slot", comment: "")
case .med:
return NSLocalizedString("Med Slot", comment: "")
case .low:
return NSLocalizedString("Low Slot", comment: "")
case .rig:
return NSLocalizedString("Rig Slot", comment: "")
case .subsystem:
return NSLocalizedString("Subsystem Slot", comment: "")
case .drone:
return NSLocalizedString("Drones", comment: "")
case .cargo:
return NSLocalizedString("Cargo", comment: "")
case .implant:
return NSLocalizedString("Implant", comment: "")
}
}
var image: UIImage {
switch self {
case .hi:
return #imageLiteral(resourceName: "slotHigh")
case .med:
return #imageLiteral(resourceName: "slotMed")
case .low:
return #imageLiteral(resourceName: "slotLow")
case .rig:
return #imageLiteral(resourceName: "slotRig")
case .subsystem:
return #imageLiteral(resourceName: "slotSubsystem")
case .drone:
return #imageLiteral(resourceName: "drone")
case .cargo:
return #imageLiteral(resourceName: "cargoBay")
case .implant:
return #imageLiteral(resourceName: "implant.pdf")
}
}
}
extension ESI.Assets.Asset.Flag {
var slot: AssetSlot? {
switch self {
case .hiSlot0, .hiSlot1, .hiSlot2, .hiSlot3, .hiSlot4, .hiSlot5, .hiSlot6, .hiSlot7:
return .hi
case .medSlot0, .medSlot1, .medSlot2, .medSlot3, .medSlot4, .medSlot5, .medSlot6, .medSlot7:
return .med
case .loSlot0, .loSlot1, .loSlot2, .loSlot3, .loSlot4, .loSlot5, .loSlot6, .loSlot7:
return .low
case .rigSlot0, .rigSlot1, .rigSlot2, .rigSlot3, .rigSlot4, .rigSlot5, .rigSlot6, .rigSlot7:
return .rig
case .subSystemSlot0, .subSystemSlot1, .subSystemSlot2, .subSystemSlot3, .subSystemSlot4, .subSystemSlot5, .subSystemSlot6, .subSystemSlot7:
return .subsystem
case .droneBay, .fighterBay, .fighterTube0, .fighterTube1, .fighterTube2, .fighterTube3, .fighterTube4:
return .drone
case .cargo:
return .cargo
case .implant:
return .implant
default:
return nil
}
}
}
extension ESI.Assets.Asset.Flag {
init?(rawValue: Int) {
let result: ESI.Assets.Asset.Flag?
switch rawValue {
case 0:
result = ESI.Assets.Asset.Flag(rawValue: "None")
case 1:
result = ESI.Assets.Asset.Flag(rawValue: "Wallet")
case 2:
result = ESI.Assets.Asset.Flag(rawValue: "Factory")
case 3:
result = ESI.Assets.Asset.Flag(rawValue: "Wardrobe")
case 4:
result = ESI.Assets.Asset.Flag(rawValue: "Hangar")
case 5:
result = ESI.Assets.Asset.Flag(rawValue: "Cargo")
case 6:
result = ESI.Assets.Asset.Flag(rawValue: "Briefcase")
case 7:
result = ESI.Assets.Asset.Flag(rawValue: "Skill")
case 8:
result = ESI.Assets.Asset.Flag(rawValue: "Reward")
case 9:
result = ESI.Assets.Asset.Flag(rawValue: "Connected")
case 10:
result = ESI.Assets.Asset.Flag(rawValue: "Disconnected")
case 11:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot0")
case 12:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot1")
case 13:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot2")
case 14:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot3")
case 15:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot4")
case 16:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot5")
case 17:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot6")
case 18:
result = ESI.Assets.Asset.Flag(rawValue: "LoSlot7")
case 19:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot0")
case 20:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot1")
case 21:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot2")
case 22:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot3")
case 23:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot4")
case 24:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot5")
case 25:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot6")
case 26:
result = ESI.Assets.Asset.Flag(rawValue: "MedSlot7")
case 27:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot0")
case 28:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot1")
case 29:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot2")
case 30:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot3")
case 31:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot4")
case 32:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot5")
case 33:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot6")
case 34:
result = ESI.Assets.Asset.Flag(rawValue: "HiSlot7")
case 35:
result = ESI.Assets.Asset.Flag(rawValue: "Fixed Slot")
case 36:
result = ESI.Assets.Asset.Flag(rawValue: "AssetSafety")
case 40:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot1")
case 41:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot2")
case 42:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot3")
case 43:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot4")
case 44:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot5")
case 45:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot6")
case 46:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot7")
case 47:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot8")
case 48:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot9")
case 49:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot10")
case 50:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot11")
case 51:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot12")
case 52:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot13")
case 53:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot14")
case 54:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot15")
case 55:
result = ESI.Assets.Asset.Flag(rawValue: "PromenadeSlot16")
case 56:
result = ESI.Assets.Asset.Flag(rawValue: "Capsule")
case 57:
result = ESI.Assets.Asset.Flag(rawValue: "Pilot")
case 58:
result = ESI.Assets.Asset.Flag(rawValue: "Passenger")
case 59:
result = ESI.Assets.Asset.Flag(rawValue: "Boarding Gate")
case 60:
result = ESI.Assets.Asset.Flag(rawValue: "Crew")
case 61:
result = ESI.Assets.Asset.Flag(rawValue: "Skill In Training")
case 62:
result = ESI.Assets.Asset.Flag(rawValue: "CorpMarket")
case 63:
result = ESI.Assets.Asset.Flag(rawValue: "Locked")
case 64:
result = ESI.Assets.Asset.Flag(rawValue: "Unlocked")
case 70:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 1")
case 71:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 2")
case 72:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 3")
case 73:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 4")
case 74:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 5")
case 75:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 6")
case 76:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 7")
case 77:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 8")
case 78:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 9")
case 79:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 10")
case 80:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 11")
case 81:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 12")
case 82:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 13")
case 83:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 14")
case 84:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 15")
case 85:
result = ESI.Assets.Asset.Flag(rawValue: "Office Slot 16")
case 86:
result = ESI.Assets.Asset.Flag(rawValue: "Bonus")
case 87:
result = ESI.Assets.Asset.Flag(rawValue: "DroneBay")
case 88:
result = ESI.Assets.Asset.Flag(rawValue: "Booster")
case 89:
result = ESI.Assets.Asset.Flag(rawValue: "Implant")
case 90:
result = ESI.Assets.Asset.Flag(rawValue: "ShipHangar")
case 91:
result = ESI.Assets.Asset.Flag(rawValue: "ShipOffline")
case 92:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot0")
case 93:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot1")
case 94:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot2")
case 95:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot3")
case 96:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot4")
case 97:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot5")
case 98:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot6")
case 99:
result = ESI.Assets.Asset.Flag(rawValue: "RigSlot7")
case 100:
result = ESI.Assets.Asset.Flag(rawValue: "Factory Operation")
case 115:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG1")
case 116:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG2")
case 117:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG3")
case 118:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG4")
case 119:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG5")
case 120:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG6")
case 121:
result = ESI.Assets.Asset.Flag(rawValue: "CorpSAG7")
case 122:
result = ESI.Assets.Asset.Flag(rawValue: "SecondaryStorage")
case 123:
result = ESI.Assets.Asset.Flag(rawValue: "CaptainsQuarters")
case 124:
result = ESI.Assets.Asset.Flag(rawValue: "Wis Promenade")
case 125:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem0")
case 126:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem1")
case 127:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem2")
case 128:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem3")
case 129:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem4")
case 130:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem5")
case 131:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem6")
case 132:
result = ESI.Assets.Asset.Flag(rawValue: "SubSystem7")
case 133:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedFuelBay")
case 134:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedOreHold")
case 135:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedGasHold")
case 136:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedMineralHold")
case 137:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedSalvageHold")
case 138:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedShipHold")
case 139:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedSmallShipHold")
case 140:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedMediumShipHold")
case 141:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedLargeShipHold")
case 142:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedIndustrialShipHold")
case 143:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedAmmoHold")
case 144:
result = ESI.Assets.Asset.Flag(rawValue: "StructureActive")
case 145:
result = ESI.Assets.Asset.Flag(rawValue: "StructureInactive")
case 146:
result = ESI.Assets.Asset.Flag(rawValue: "JunkyardReprocessed")
case 147:
result = ESI.Assets.Asset.Flag(rawValue: "JunkyardTrashed")
case 148:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedCommandCenterHold")
case 149:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedPlanetaryCommoditiesHold")
case 150:
result = ESI.Assets.Asset.Flag(rawValue: "PlanetSurface")
case 151:
result = ESI.Assets.Asset.Flag(rawValue: "SpecializedMaterialBay")
case 152:
result = ESI.Assets.Asset.Flag(rawValue: "DustCharacterDatabank")
case 153:
result = ESI.Assets.Asset.Flag(rawValue: "DustCharacterBattle")
case 154:
result = ESI.Assets.Asset.Flag(rawValue: "QuafeBay")
case 155:
result = ESI.Assets.Asset.Flag(rawValue: "FleetHangar")
case 156:
result = ESI.Assets.Asset.Flag(rawValue: "HiddenModifiers")
case 157:
result = ESI.Assets.Asset.Flag(rawValue: "StructureOffline")
case 158:
result = ESI.Assets.Asset.Flag(rawValue: "FighterBay")
case 159:
result = ESI.Assets.Asset.Flag(rawValue: "FighterTube0")
case 160:
result = ESI.Assets.Asset.Flag(rawValue: "FighterTube1")
case 161:
result = ESI.Assets.Asset.Flag(rawValue: "FighterTube2")
case 162:
result = ESI.Assets.Asset.Flag(rawValue: "FighterTube3")
case 163:
result = ESI.Assets.Asset.Flag(rawValue: "FighterTube4")
case 164:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot0")
case 165:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot1")
case 166:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot2")
case 167:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot3")
case 168:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot4")
case 169:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot5")
case 170:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot6")
case 171:
result = ESI.Assets.Asset.Flag(rawValue: "StructureServiceSlot7")
case 172:
result = ESI.Assets.Asset.Flag(rawValue: "StructureFuel")
case 173:
result = ESI.Assets.Asset.Flag(rawValue: "Deliveries")
default:
result = nil
}
if let res = result {
self = res
}
else {
return nil
}
}
var intValue: Int {
switch self {
case .wardrobe:
return 3
case .hangar:
return 4
case .cargo:
return 5
case .loSlot0:
return 11
case .loSlot1:
return 12
case .loSlot2:
return 13
case .loSlot3:
return 14
case .loSlot4:
return 15
case .loSlot5:
return 16
case .loSlot6:
return 17
case .loSlot7:
return 18
case .medSlot0:
return 19
case .medSlot1:
return 20
case .medSlot2:
return 21
case .medSlot3:
return 22
case .medSlot4:
return 23
case .medSlot5:
return 24
case .medSlot6:
return 25
case .medSlot7:
return 26
case .hiSlot0:
return 27
case .hiSlot1:
return 28
case .hiSlot2:
return 29
case .hiSlot3:
return 30
case .hiSlot4:
return 31
case .hiSlot5:
return 32
case .hiSlot6:
return 33
case .hiSlot7:
return 34
case .assetSafety:
return 36
case .locked:
return 63
case .unlocked:
return 64
case .droneBay:
return 87
case .implant:
return 89
case .shipHangar:
return 90
case .rigSlot0:
return 92
case .rigSlot1:
return 93
case .rigSlot2:
return 94
case .rigSlot3:
return 95
case .rigSlot4:
return 96
case .rigSlot5:
return 97
case .rigSlot6:
return 98
case .rigSlot7:
return 99
case .subSystemSlot0:
return 125
case .subSystemSlot1:
return 126
case .subSystemSlot2:
return 127
case .subSystemSlot3:
return 128
case .subSystemSlot4:
return 129
case .subSystemSlot5:
return 130
case .subSystemSlot6:
return 131
case .subSystemSlot7:
return 132
case .specializedFuelBay:
return 133
case .specializedOreHold:
return 134
case .specializedGasHold:
return 135
case .specializedMineralHold:
return 136
case .specializedSalvageHold:
return 137
case .specializedShipHold:
return 138
case .specializedSmallShipHold:
return 139
case .specializedMediumShipHold:
return 140
case .specializedLargeShipHold:
return 141
case .specializedIndustrialShipHold:
return 142
case .specializedAmmoHold:
return 143
case .specializedCommandCenterHold:
return 148
case .specializedPlanetaryCommoditiesHold:
return 149
case .specializedMaterialBay:
return 151
case .quafeBay:
return 154
case .fleetHangar:
return 155
case .hiddenModifiers:
return 156
case .fighterBay:
return 158
case .fighterTube0:
return 159
case .fighterTube1:
return 160
case .fighterTube2:
return 161
case .fighterTube3:
return 162
case .fighterTube4:
return 163
case .structureServiceSlot0:
return 164
case .structureServiceSlot1:
return 165
case .structureServiceSlot2:
return 166
case .structureServiceSlot3:
return 167
case .structureServiceSlot4:
return 168
case .structureServiceSlot5:
return 169
case .structureServiceSlot6:
return 169
case .structureServiceSlot7:
return 171
case .structureFuel:
return 172
case .deliveries:
return 173
case .autoFit, .corpseBay, .hangarAll, .subSystemBay, .skill, .boosterBay:
return 0
}
}
}
extension ESI.Mail.RecipientType {
var title: String {
switch self {
case .alliance:
return NSLocalizedString("Alliance", comment: "")
case .character:
return NSLocalizedString("Character", comment: "")
case .corporation:
return NSLocalizedString("Corporation", comment: "")
case .mailingList:
return NSLocalizedString("Mailing List", comment: "")
}
}
}
|
lgpl-2.1
|
8b853b1f5779630d28a6a43fefe2f92a
| 26.834049 | 142 | 0.698859 | 3.036679 | false | false | false | false |
cpk1/fastlane
|
fastlane/swift/LaneFileProtocol.swift
|
1
|
6343
|
// LaneFileProtocol.swift
// Copyright (c) 2021 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
public protocol LaneFileProtocol: class {
var fastlaneVersion: String { get }
static func runLane(from fastfile: LaneFile?, named lane: String, with parameters: [String: String]) -> Bool
func recordLaneDescriptions()
func beforeAll(with lane: String)
func afterAll(with lane: String)
func onError(currentLane: String, errorInfo: String)
}
public extension LaneFileProtocol {
var fastlaneVersion: String { return "" } // Defaults to "" because that means any is fine
func beforeAll(with _: String) {} // No-op by default
func afterAll(with _: String) {} // No-op by default
func onError(currentLane _: String, errorInfo _: String) {} // No-op by default
func recordLaneDescriptions() {} // No-op by default
}
@objcMembers
open class LaneFile: NSObject, LaneFileProtocol {
private(set) static var fastfileInstance: LaneFile?
private static func trimLaneFromName(laneName: String) -> String {
return String(laneName.prefix(laneName.count - 4))
}
private static func trimLaneWithOptionsFromName(laneName: String) -> String {
return String(laneName.prefix(laneName.count - 12))
}
private static var laneFunctionNames: [String] {
var lanes: [String] = []
var methodCount: UInt32 = 0
#if !SWIFT_PACKAGE
let methodList = class_copyMethodList(self, &methodCount)
#else
// In SPM we're calling this functions out of the scope of the normal binary that it's
// being built, so *self* in this scope would be the SPM executable instead of the Fastfile
// that we'd normally expect.
let methodList = class_copyMethodList(type(of: fastfileInstance!), &methodCount)
#endif
for i in 0 ..< Int(methodCount) {
let selName = sel_getName(method_getName(methodList![i]))
let name = String(cString: selName)
let lowercasedName = name.lowercased()
if lowercasedName.hasSuffix("lane") || lowercasedName.hasSuffix("lanewithoptions:") {
lanes.append(name)
}
}
return lanes
}
public static var lanes: [String: String] {
var laneToMethodName: [String: String] = [:]
laneFunctionNames.forEach { name in
let lowercasedName = name.lowercased()
if lowercasedName.hasSuffix("lane") {
laneToMethodName[lowercasedName] = name
let lowercasedNameNoLane = trimLaneFromName(laneName: lowercasedName)
laneToMethodName[lowercasedNameNoLane] = name
} else if lowercasedName.hasSuffix("lanewithoptions:") {
let lowercasedNameNoOptions = trimLaneWithOptionsFromName(laneName: lowercasedName)
laneToMethodName[lowercasedNameNoOptions] = name
let lowercasedNameNoLane = trimLaneFromName(laneName: lowercasedNameNoOptions)
laneToMethodName[lowercasedNameNoLane] = name
}
}
return laneToMethodName
}
public static func loadFastfile() {
if fastfileInstance == nil {
let fastfileType: AnyObject.Type = NSClassFromString(className())!
let fastfileAsNSObjectType: NSObject.Type = fastfileType as! NSObject.Type
let currentFastfileInstance: Fastfile? = fastfileAsNSObjectType.init() as? Fastfile
fastfileInstance = currentFastfileInstance
}
}
public static func runLane(from fastfile: LaneFile?, named lane: String, with parameters: [String: String]) -> Bool {
log(message: "Running lane: \(lane)")
#if !SWIFT_PACKAGE
// When not in SPM environment, we load the Fastfile from its `className()`.
loadFastfile()
guard let fastfileInstance = self.fastfileInstance as? Fastfile else {
let message = "Unable to instantiate class named: \(className())"
log(message: message)
fatalError(message)
}
#else
// When in SPM environment, we can't load the Fastfile from its `className()` because the executable is in
// another scope, so `className()` won't be the expected Fastfile. Instead, we load the Fastfile as a Lanefile
// in a static way, by parameter.
guard let fastfileInstance = fastfile else {
log(message: "Found nil instance of fastfile")
preconditionFailure()
}
self.fastfileInstance = fastfileInstance
#endif
let currentLanes = lanes
let lowerCasedLaneRequested = lane.lowercased()
guard let laneMethod = currentLanes[lowerCasedLaneRequested] else {
let laneNames = laneFunctionNames.map { laneFuctionName in
if laneFuctionName.hasSuffix("lanewithoptions:") {
return trimLaneWithOptionsFromName(laneName: laneFuctionName)
} else {
return trimLaneFromName(laneName: laneFuctionName)
}
}.joined(separator: ", ")
let message = "[!] Could not find lane '\(lane)'. Available lanes: \(laneNames)"
log(message: message)
let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .clientError), message: message)
_ = runner.executeCommand(shutdownCommand)
return false
}
// Call all methods that need to be called before we start calling lanes.
fastfileInstance.beforeAll(with: lane)
// We need to catch all possible errors here and display a nice message.
_ = fastfileInstance.perform(NSSelectorFromString(laneMethod), with: parameters)
// Call only on success.
fastfileInstance.afterAll(with: lane)
log(message: "Done running lane: \(lane) 🚀")
return true
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
|
mit
|
b58c214b598e042cfec24f990de65fee
| 41.550336 | 122 | 0.641483 | 4.620991 | false | false | false | false |
wfleming/pico-block
|
pblock/Services/RuleUpdater.swift
|
1
|
6968
|
//
// RuleUpdater.swift
// pblock
//
// Created by Will Fleming on 8/30/15.
// Copyright © 2015 PBlock. All rights reserved.
//
import Foundation
import Alamofire
import ReactiveCocoa
import CoreData
class RuleUpdater {
private let etagHeader = "ETag"
let updateWaitInterval = (60 * 60 * 6) as Double // 6 hours
private var sources: Array<RuleSource>
private var coreDataCtx: NSManagedObjectContext
class func forAllEnabledSources() -> RuleUpdater {
let mgr = CoreDataManager.sharedInstance
let fetchRequest = mgr.managedObjectModel!.fetchRequestTemplateForName("ThirdPartyRuleSources")
do {
let ctx = mgr.childManagedObjectContext()!
let sources = try ctx.executeFetchRequest(fetchRequest!)
let enabledSources = (sources as! Array<RuleSource>).filter {
if let b = $0.enabled?.boolValue {
return b
} else {
// NOTE: I don't think this is happening anymore (using a child context fixed it):
// going to leave this logging for a while in case it reoccurs.
// consider record with enabled => nil to be disabled: this shouldn't happen, though?
dlog("source \($0.name) had unexpected nil enabled \($0)")
return false
}
}
dlog("\(enabledSources.count) sources")
return self.init(ctx: ctx, sources: enabledSources)
} catch {
dlog("failed fetching: \(error)")
abort()
}
}
required init(ctx: NSManagedObjectContext, sources: Array<RuleSource>) {
self.coreDataCtx = ctx
self.sources = sources
}
// constructs a signal that encapsulates all update logic: this signal will emit an integer
// which is the number of rule soures that actually fetched & parsed new rules.
func doUpdate() -> RACSignal {
return RACSignal.zip(self.sources.map { updateSource($0) })
.map({ (val: AnyObject!) -> AnyObject! in
if let nextTuple = val as? RACTuple {
return nextTuple.allObjects().reduce(0,
combine: { (sum: Int, updated: AnyObject) -> Int in
if let updatedBool = updated as? Bool where updatedBool {
return sum + 1
} else {
return sum
}
})
} else {
return 0
}
})
}
// construct a signal for a source that emits whether the rule needs updating
func sourceNeedsUpdate(source: RuleSource) -> RACSignal {
assert(!source.fault, "PROBLEM: fault is not firing \(source)")
return RACSignal.createSignal({ (sub: RACSubscriber!) -> RACDisposable! in
var urlFetch: Request?
if let d = source.lastUpdatedAt {
let isOld = (0 - d.timeIntervalSinceNow) > self.updateWaitInterval
if isOld {
if let etag = source.etag where etag.characters.count > 0 {
// fetch the HEAD of the url, compare etag
urlFetch = Alamofire.request(.HEAD, source.url!)
.response(queue: dispatch_get_global_queue(QOS_CLASS_UTILITY, 0),
responseSerializer: Request.stringResponseSerializer(),
completionHandler: { (_, response, _) in
var cacheExpired = true
if let respEtag = response?.allHeaderFields[self.etagHeader] as! String? {
if respEtag.characters.count > 0 {
cacheExpired = respEtag != etag
}
}
sub.sendNext(cacheExpired)
sub.sendCompleted()
})
} else {
// we haven't updated in a while, and don't have a cache header to check, so return true
sub.sendNext(true)
sub.sendCompleted()
}
} else {
// we've been updated fairly recently, don't bother checking etag
sub.sendNext(false)
sub.sendCompleted()
}
} else {
// no lastUpdatedAt means it's never been loaded
sub.sendNext(true)
sub.sendCompleted()
}
return RACDisposable {
urlFetch?.cancel()
}
})
}
func updateSource(source: RuleSource) -> RACSignal {
var urlFetch: Request?
return RACSignal.createSignal({ (sub: RACSubscriber!) -> RACDisposable! in
self.sourceNeedsUpdate(source).subscribeNext({ (needsUpdateObj: AnyObject!) -> Void in
if let needsUpdate = needsUpdateObj as? Bool where needsUpdate {
if let url = source.url where nil == url.rangeOfString("localhost") {
urlFetch = self.reqSourceContents(source, sub)
} else {
sub.sendNext(false)
sub.sendCompleted()
}
} else {
sub.sendNext(false)
sub.sendCompleted()
}
})
return RACDisposable {
urlFetch?.cancel()
}
})
}
func reqSourceContents(source: RuleSource, _ subscriber: RACSubscriber) -> Request {
return Alamofire.request(.GET, source.url!)
.response(queue: dispatch_get_global_queue(QOS_CLASS_UTILITY, 0),
responseSerializer: Request.stringResponseSerializer(),
completionHandler: { _, response, result in
dlog("got response for contents of \(source.name)")
if !result.isSuccess {
dlog("the response for \(source.name) does not indicate success: \(response)")
subscriber.sendNext(false)
subscriber.sendCompleted()
return
}
// store caching info on rule source
source.lastUpdatedAt = NSDate()
source.etag = response?.allHeaderFields[self.etagHeader] as! String?
CoreDataManager.sharedInstance.saveContext(self.coreDataCtx)
// parse returned rules
if let contents = result.value {
self.parseNewRules(source.objectID, contents, subscriber)
}
})
}
func parseNewRules(sourceId: NSManagedObjectID, _ contents: String, _ subscriber: RACSubscriber) {
defer {
subscriber.sendNext(true)
subscriber.sendCompleted()
}
// because this runs in yet another thread, it needs its own
let childCtx = CoreDataManager.sharedInstance.childManagedObjectContext()!
let source = childCtx.objectWithID(sourceId) as! RuleSource
let parserClass = source.parserClass()!
let parser = parserClass.init(fileSource: contents)
// destroy the old rules on this source
if let oldRules = source.rules {
oldRules.forEach { childCtx.deleteObject($0 as! NSManagedObject) }
}
// parse the rules & save everything
source.rules = NSOrderedSet(array: parser.parsedRules().map { (parsedRule) -> Rule in
let rule = Rule(inContext: childCtx, parsedRule: parsedRule)
rule.source = source
return rule
})
source.lastUpdatedAt = NSDate()
dlog("rule source \(source.name) now has \(source.rules?.count) parsed rules")
CoreDataManager.sharedInstance.saveContext(childCtx)
}
}
|
mit
|
feaaf8b3e69388c6c359b3e4f867ffc7
| 36.462366 | 100 | 0.618344 | 4.678979 | false | false | false | false |
carabina/MaterialKit-1
|
Source/MaterialTheme.swift
|
1
|
28996
|
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public struct MaterialTheme {
// clear
public struct clear {
public static let color: UIColor = white.color.colorWithAlphaComponent(0)
}
// white
public struct white {
public static let color: UIColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
}
// black
public struct black {
public static let color: UIColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1)
}
// red
public struct red {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 235/255, blue: 238/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 225/255, green: 205/255, blue: 210/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 239/255, green: 154/255, blue: 254/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 229/255, green: 115/255, blue: 115/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 229/255, green: 83/255, blue: 80/255, alpha: 1)
public static let color: UIColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 229/255, green: 57/255, blue: 53/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 211/255, green: 47/255, blue: 47/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 198/255, green: 40/255, blue: 40/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 183/255, green: 28/255, blue: 28/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 138/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 82/255, blue: 82/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 23/255, blue: 68/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 213/255, green: 0/255, blue: 0/255, alpha: 1)
}
// pink
public struct pink {
public static let lighten5: UIColor = UIColor(red: 252/255, green: 228/255, blue: 236/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 248/255, green: 107/255, blue: 208/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 244/255, green: 143/255, blue: 177/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 240/255, green: 98/255, blue: 146/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 236/255, green: 64/255, blue: 122/255, alpha: 1)
public static let color: UIColor = UIColor(red: 233/255, green: 30/255, blue: 99/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 216/255, green: 27/255, blue: 96/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 194/255, green: 24/255, blue: 191/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 173/255, green: 20/255, blue: 87/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 136/255, green: 14/255, blue: 79/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 128/255, blue: 171/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 245/255, green: 0/255, blue: 87/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 197/255, green: 17/255, blue: 98/255, alpha: 1)
}
// purple
public struct purple {
public static let lighten5: UIColor = UIColor(red: 243/255, green: 229/255, blue: 245/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 225/255, green: 190/255, blue: 231/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 206/255, green: 147/255, blue: 216/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 186/255, green: 104/255, blue: 200/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 171/255, green: 71/255, blue: 188/255, alpha: 1)
public static let color: UIColor = UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 142/255, green: 36/255, blue: 170/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 106/255, green: 27/255, blue: 154/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 74/255, green: 20/255, blue: 140/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 234/255, green: 128/255, blue: 252/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 224/255, green: 64/255, blue: 251/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 213/255, green: 0/255, blue: 249/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 170/255, green: 0/255, blue: 255/255, alpha: 1)
}
// deepPurple
public struct deepPurple {
public static let lighten5: UIColor = UIColor(red: 237/255, green: 231/255, blue: 246/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 209/255, green: 196/255, blue: 233/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 179/255, green: 157/255, blue: 219/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 149/255, green: 117/255, blue: 205/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 126/255, green: 87/255, blue: 194/255, alpha: 1)
public static let color: UIColor = UIColor(red: 103/255, green: 58/255, blue: 183/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 94/255, green: 53/255, blue: 177/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 81/255, green: 45/255, blue: 168/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 69/255, green: 39/255, blue: 160/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 49/255, green: 27/255, blue: 146/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 179/255, green: 136/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 124/255, green: 77/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 101/255, green: 31/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 98/255, green: 0/255, blue: 234/255, alpha: 1)
}
// indigo
public struct indigo {
public static let lighten5: UIColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 197/255, green: 202/255, blue: 233/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 159/255, green: 168/255, blue: 218/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 121/255, green: 134/255, blue: 203/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 92/255, green: 107/255, blue: 192/255, alpha: 1)
public static let color: UIColor = UIColor(red: 63/255, green: 81/255, blue: 181/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 57/255, green: 73/255, blue: 171/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 48/255, green: 63/255, blue: 159/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 40/255, green: 53/255, blue: 147/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 26/255, green: 35/255, blue: 126/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 140/255, green: 158/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 83/255, green: 109/255, blue: 254/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 61/255, green: 90/255, blue: 254/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 48/255, green: 79/255, blue: 254/255, alpha: 1)
}
// blue
public struct blue {
public static let lighten5: UIColor = UIColor(red: 227/255, green: 242/255, blue: 253/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 187/255, green: 222/255, blue: 251/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 144/255, green: 202/255, blue: 249/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 100/255, green: 181/255, blue: 246/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 66/255, green: 165/255, blue: 245/255, alpha: 1)
public static let color: UIColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 30/255, green: 136/255, blue: 229/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 25/255, green: 118/255, blue: 210/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 21/255, green: 101/255, blue: 192/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 13/255, green: 71/255, blue: 161/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 130/255, green: 177/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 68/255, green: 138/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 41/255, green: 121/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 41/255, green: 98/255, blue: 255/255, alpha: 1)
}
// light blue
public struct lightBlue {
public static let lighten5: UIColor = UIColor(red: 225/255, green: 245/255, blue: 254/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 179/255, green: 229/255, blue: 252/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 129/255, green: 212/255, blue: 250/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 79/255, green: 195/255, blue: 247/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 41/255, green: 182/255, blue: 246/255, alpha: 1)
public static let color: UIColor = UIColor(red: 3/255, green: 169/255, blue: 244/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 3/255, green: 155/255, blue: 229/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 2/255, green: 136/255, blue: 209/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 2/255, green: 119/255, blue: 189/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 1/255, green: 87/255, blue: 155/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 128/255, green: 216/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 64/255, green: 196/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 176/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 145/255, blue: 234/255, alpha: 1)
}
// cyan
public struct cyab {
public static let lighten5: UIColor = UIColor(red: 224/255, green: 247/255, blue: 250/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 1178/255, green: 235/255, blue: 242/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 128/255, green: 222/255, blue: 2343/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 77/255, green: 208/255, blue: 225/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 38/255, green: 198/255, blue: 218/255, alpha: 1)
public static let color: UIColor = UIColor(red: 0/255, green: 188/255, blue: 212/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 0/255, green: 172/255, blue: 193/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 0/255, green: 151/255, blue: 167/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 0/255, green: 131/255, blue: 143/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 0/255, green: 96/255, blue: 100/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 132/255, green: 255/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 24/255, green: 255/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 229/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 184/255, blue: 212/255, alpha: 1)
}
// teal
public struct teal {
public static let lighten5: UIColor = UIColor(red: 224/255, green: 242/255, blue: 241/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 178/255, green: 223/255, blue: 219/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 128/255, green: 203/255, blue: 196/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 77/255, green: 182/255, blue: 172/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 38/255, green: 166/255, blue: 154/255, alpha: 1)
public static let color: UIColor = UIColor(red: 0/255, green: 150/255, blue: 136/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 0/255, green: 137/255, blue: 123/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 0/255, green: 121/255, blue: 107/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 0/255, green: 105/255, blue: 92/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 0/255, green: 77/255, blue: 64/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 167/255, green: 255/255, blue: 235/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 100/255, green: 255/255, blue: 218/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 29/255, green: 133/255, blue: 182/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1)
}
// green
public struct green {
public static let lighten5: UIColor = UIColor(red: 232/255, green: 245/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 200/255, green: 230/255, blue: 201/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 165/255, green: 214/255, blue: 167/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 129/255, green: 199/255, blue: 132/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 102/255, green: 187/255, blue: 106/255, alpha: 1)
public static let color: UIColor = UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 67/255, green: 160/255, blue: 71/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 56/255, green: 142/255, blue: 60/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 46/255, green: 125/255, blue: 50/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 27/255, green: 94/255, blue: 32/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 185/255, green: 246/255, blue: 202/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 105/255, green: 240/255, blue: 174/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 230/255, blue: 118/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 200/255, blue: 83/255, alpha: 1)
}
// light green
public struct lightGreen {
public static let lighten5: UIColor = UIColor(red: 241/255, green: 248/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 220/255, green: 237/255, blue: 200/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 197/255, green: 225/255, blue: 165/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 174/255, green: 213/255, blue: 129/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 156/255, green: 204/255, blue: 101/255, alpha: 1)
public static let color: UIColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 124/255, green: 179/255, blue: 66/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 104/255, green: 159/255, blue: 56/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 85/255, green: 139/255, blue: 47/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 51/255, green: 105/255, blue: 30/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 204/255, green: 255/255, blue: 144/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 178/255, green: 255/255, blue: 89/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 118/255, green: 255/255, blue: 3/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 100/255, green: 221/255, blue: 23/255, alpha: 1)
}
// lime
public struct lime {
public static let lighten5: UIColor = UIColor(red: 249/255, green: 251/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 240/255, green: 244/255, blue: 195/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 230/255, green: 238/255, blue: 156/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 220/255, green: 231/255, blue: 117/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 212/255, green: 225/255, blue: 87/255, alpha: 1)
public static let color: UIColor = UIColor(red: 205/255, green: 220/255, blue: 57/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 192/255, green: 202/255, blue: 51/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 175/255, green: 180/255, blue: 43/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 158/255, green: 157/255, blue: 36/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 130/255, green: 119/255, blue: 23/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 244/255, green: 255/255, blue: 129/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 238/255, green: 255/255, blue: 65/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 198/255, green: 255/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 174/255, green: 234/255, blue: 0/255, alpha: 1)
}
// yellow
public struct yellow {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 253/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 249/255, blue: 196/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 245/255, blue: 157/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 241/255, blue: 118/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 238/255, blue: 88/255, alpha: 1)
public static let color: UIColor = UIColor(red: 255/255, green: 235/255, blue: 59/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 253/255, green: 216/255, blue: 53/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 251/255, green: 192/255, blue: 45/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 249/255, green: 168/255, blue: 37/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 245/255, green: 127/255, blue: 23/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 255/255, blue: 141/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 234/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 214/255, blue: 0/255, alpha: 1)
}
// amber
public struct amber {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 248/255, blue: 225/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 236/255, blue: 179/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 224/255, blue: 130/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 213/255, blue: 79/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 202/255, blue: 40/255, alpha: 1)
public static let color: UIColor = UIColor(red: 255/255, green: 193/255, blue: 7/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 255/255, green: 179/255, blue: 0/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 255/255, green: 160/255, blue: 0/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 255/255, green: 143/255, blue: 0/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 255/255, green: 111/255, blue: 0/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 229/255, blue: 127/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 215/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 196/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 171/255, blue: 0/255, alpha: 1)
}
// orange
public struct orange {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 243/255, blue: 224/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 224/255, blue: 178/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 204/255, blue: 128/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 183/255, blue: 77/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 167/255, blue: 38/255, alpha: 1)
public static let color: UIColor = UIColor(red: 255/255, green: 152/255, blue: 0/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 251/255, green: 140/255, blue: 0/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 245/255, green: 124/255, blue: 0/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 239/255, green: 108/255, blue: 0/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 230/255, green: 81/255, blue: 0/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 209/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 171/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 145/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 109/255, blue: 0/255, alpha: 1)
}
// deep orange
public struct deepOrange {
public static let lighten5: UIColor = UIColor(red: 251/255, green: 233/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 204/255, blue: 188/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 171/255, blue: 145/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 138/255, blue: 101/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 112/255, blue: 67/255, alpha: 1)
public static let color: UIColor = UIColor(red: 255/255, green: 87/255, blue: 34/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 244/255, green: 81/255, blue: 30/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 230/255, green: 74/255, blue: 25/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 216/255, green: 67/255, blue: 21/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 191/255, green: 54/255, blue: 12/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 158/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 110/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 61/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 221/255, green: 44/255, blue: 0/255, alpha: 1)
}
// brown
public struct brown {
public static let lighten5: UIColor = UIColor(red: 239/255, green: 235/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 215/255, green: 204/255, blue: 200/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 188/255, green: 170/255, blue: 164/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 161/255, green: 136/255, blue: 127/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 141/255, green: 110/255, blue: 99/255, alpha: 1)
public static let color: UIColor = UIColor(red: 121/255, green: 85/255, blue: 72/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 109/255, green: 76/255, blue: 65/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 93/255, green: 64/255, blue: 55/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 78/255, green: 52/255, blue: 46/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 62/255, green: 39/255, blue: 35/255, alpha: 1)
}
// grey
public struct grey {
public static let lighten5: UIColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 189/255, green: 189/255, blue: 189/255, alpha: 1)
public static let color: UIColor = UIColor(red: 158/255, green: 158/255, blue: 158/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 117/255, green: 117/255, blue: 117/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 97/255, green: 97/255, blue: 97/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 66/255, green: 66/255, blue: 66/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 33/255, green: 33/255, blue: 33/255, alpha: 1)
}
// blue grey
public struct blueGrey {
public static let lighten5: UIColor = UIColor(red: 236/255, green: 239/255, blue: 241/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 207/255, green: 216/255, blue: 220/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 176/255, green: 190/255, blue: 197/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 144/255, green: 164/255, blue: 174/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 120/255, green: 144/255, blue: 156/255, alpha: 1)
public static let color: UIColor = UIColor(red: 96/255, green: 125/255, blue: 139/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 84/255, green: 110/255, blue: 122/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 69/255, green: 90/255, blue: 100/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 55/255, green: 71/255, blue: 79/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 38/255, green: 50/255, blue: 56/255, alpha: 1)
}
}
|
agpl-3.0
|
3b5bdf20e055faa44a30a9879053b258
| 77.793478 | 109 | 0.670575 | 3.230752 | false | false | false | false |
narner/AudioKit
|
Playgrounds/AudioKitPlaygrounds/Playgrounds/Playback.playground/Pages/Sequencer.xcplaygroundpage/Contents.swift
|
1
|
2146
|
//: ## Sequencer
//:
import AudioKitPlaygrounds
import AudioKit
//: Create some samplers, load different sounds, and connect it to a mixer and the output
var piano = AKMIDISampler()
try piano.loadWav("Samples/FM Piano")
var bell = AKMIDISampler()
try bell.loadWav("Samples/Bell")
var mixer = AKMixer(piano, bell)
let reverb = AKCostelloReverb(mixer)
let dryWetMixer = AKDryWetMixer(mixer, reverb, balance: 0.2)
AudioKit.output = dryWetMixer
//: Create the sequencer after AudioKit's output has been set
//: Load in a midi file, and set the sequencer to the main audiokit engine
var sequencer = AKSequencer(filename: "4tracks")
//: Do some basic setup to make the sequence loop correctly
sequencer.setLength(AKDuration(beats: 4))
sequencer.enableLooping()
sequencer.setGlobalMIDIOutput(piano.midiIn)
AudioKit.start()
sequencer.play()
//: Set up a basic UI for setting outputs of tracks
import AudioKitUI
class LiveView: AKLiveViewController {
enum State {
case bell, piano
}
var buttons: [AKButton] = []
var states: [State] = [.piano, .piano, .piano, .piano]
override func viewDidLoad() {
addTitle("Sequencer")
for i in 0 ..< 4 {
let button = AKButton(title: "Track \(i + 1): FM Piano") { _ in
self.states[i] = self.states[i] == .bell ? .piano : .bell
self.update()
}
addView(button)
button.color = .green
buttons.append(button)
}
}
func update() {
sequencer.stop()
for i in 0 ..< 4 {
if states[i] == .bell {
sequencer.tracks[i + 1].setMIDIOutput(bell.midiIn)
buttons[i].title = "Track \(i + 1): Bell"
buttons[i].color = .red
} else {
sequencer.tracks[i + 1].setMIDIOutput(piano.midiIn)
buttons[i].title = "Track \(i + 1): FM Piano"
buttons[i].color = .green
}
}
sequencer.play()
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
|
mit
|
86d50226af172ff9fb4add3acf7fdbe9
| 26.164557 | 89 | 0.616496 | 3.832143 | false | false | false | false |
LYM-mg/MGDYZB
|
MGDYZB/MGDYZB/Class/Home/ViewModel/BaseViewModel.swift
|
1
|
1499
|
//
// BaseViewModel.swift
// MGDYZB
//
// Created by ming on 16/10/26.
// Copyright © 2016年 ming. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel {
func loadAnchorData(isGroup isGroupData : Bool, urlString : String, parameters : [String : Any]? = nil, finishedCallback: @escaping () -> ()) {
NetWorkTools.requestData1(.get, urlString: urlString, parameters: parameters) { (result) in
// 1.对界面进行处理
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
// 2.判断是否分组数据
if isGroupData {
// 2.1.遍历数组中的字典
for dict in dataArray {
self.anchorGroups.append(AnchorGroup(dict: dict))
}
}
else {
// 2.1.创建组
let group = AnchorGroup()
// 2.2.遍历dataArray的所有的字典
for dict in dataArray {
group.anchors.append(AnchorModel(dict: dict))
}
// 2.3.将group,添加到anchorGroups
self.anchorGroups.append(group)
}
// 3.完成回调
finishedCallback()
}
}
}
|
mit
|
46920b3a5c2781dcb3f6fad4b554d426
| 29.695652 | 147 | 0.506374 | 4.706667 | false | false | false | false |
HeartRateLearning/HRLApp
|
HRLAppTests/Modules/AddWorkout/Configurator/AddWorkoutConfiguratorTests.swift
|
1
|
1276
|
//
// AddWorkoutAddWorkoutConfiguratorTests.swift
// HRLApp
//
// Created by Enrique de la Torre on 18/01/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import XCTest
@testable import HRLApp
// MARK: - Main body
final class AddWorkoutModuleConfiguratorTests: XCTestCase {
// MARK: - Properties
let store = WorkoutStoreTestDouble()
let viewController = AddWorkoutViewController()
let sut = AddWorkoutModuleConfigurator()
// MARK: - Tests
func test_configureDependenciesForViewController_setAllDependencies() {
// when
sut.configureDependencies(for: viewController, with: store)
// then
XCTAssertNotNil(viewController.output)
let presenter = viewController.output as! AddWorkoutPresenter
XCTAssertNotNil(presenter.view)
XCTAssertNotNil(presenter.router)
XCTAssertNotNil(presenter.getAllWorkouts)
XCTAssertNotNil(presenter.storeWorkout)
let getAllWorkouts = presenter.getAllWorkouts as! GetAllWorkoutsInteractor
XCTAssertNotNil(getAllWorkouts.output)
let storeWorkout = presenter.storeWorkout as! StoreWorkoutInteractor
XCTAssertNotNil(storeWorkout.store)
XCTAssertNotNil(storeWorkout.output)
}
}
|
mit
|
87aa586dbd907d835a75af927970cc2c
| 26.717391 | 82 | 0.723137 | 4.94186 | false | true | false | false |
gp09/Beefit
|
BeefitMsc/BeefitMsc/BeeMapVIewController.swift
|
1
|
3986
|
//
// BeeMapVIewController.swift
// BeefitMsc
//
// Created by Priyank on 31/07/2017.
// Copyright © 2017 priyank. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
let client_id = "DZI4XQWAVOVUHXHTZ2BUQJH1O2YJ25V4KRNPX3PQVUYG01MW" // visit developer.foursqure.com for API key
let client_secret = "PYKWMVPW4432QSTKDQVWUWQU4QVACNSCAGLKRMF3DSKVEIUH" // visit developer.foursqure.com for API key
class BeeMapVIewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate
// Try to ad import MapKit - MK Annotation
{
let locationManager = CLLocationManager()
var currentLocation:CLLocationCoordinate2D!
var searchResults = [JSON]()
override func viewDidLoad() {
super.viewDidLoad()
// set up location manager
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
// Do any additional setup after loading the view.
// check if access is granted
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
// MARK: - Foursquare API
func checkPlacesAtCurrentLocation() {
let url = "https://api.foursquare.com/v2/venues/search?ll=\(currentLocation.latitude),\(currentLocation.longitude)&v=20160607&intent=checkin&limit=1&radius=4000&client_id=\(client_id)&client_secret=\(client_secret)"
let request = NSMutableURLRequest(url: URL(string: url)!)
let session = URLSession.shared
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, err -> Void in
var currentVenueName:String?
let json = JSON(data: data!)
currentVenueName = json["response"]["venues"][0]["name"].string
// set label name and visible
// DispatchQueue.main.async {
// if let v = currentVenueName {
// self.currentLocationLabel.text = "You're at \(v). Here's some ☕️ nearby."
// }
// self.currentLocationLabel.isHidden = false
// }
})
task.resume()
}
// MARK: - search/recommendations endpoint
// https://developer.foursquare.com/docs/search/recommendations
func searchForhopitalCall() {
let url = "https://api.foursquare.com/v2/search/recommendations?ll=\(currentLocation.latitude),\(currentLocation.longitude)&v=20160607&intent=coffee&limit=15&client_id=\(client_id)&client_secret=\(client_secret)"
let request = NSMutableURLRequest(url: URL(string: url)!)
let session = URLSession.shared
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, err -> Void in
let json = JSON(data: data!)
self.searchResults = json["response"]["group"]["results"].arrayValue
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
b32c96020a24cdc06294a54860a3fe83
| 35.861111 | 223 | 0.648078 | 4.62907 | false | false | false | false |
fousa/trackkit
|
Example/Tests/Tests/GPX/1.1/GPXParserSpecs.swift
|
1
|
1674
|
//
// TrackKit
//
// Created by Jelle Vandebeeck on 30/12/2016.
//
import Quick
import Nimble
import TrackKit
class GPXParserSpec: QuickSpec {
override func spec() {
describe("parser") {
it("should be successful") {
expect { try TrackParser(data: Data(), type: .gpx) }.notTo(throwError())
}
it("should throw an data error") {
expect { try TrackParser(data: nil, type: .gpx) }.to(throwError(TrackParseError.invalidData))
}
it("should throw an parse error") {
expect { try TrackParser(data: Data(), type: .gpx).parse() }.to(throwError(TrackParseError.invalidFormat))
}
it("should throw an invalid version error") {
let content = "<gpx version='0.0'></gpx>"
let data = content.data(using: .utf8)
expect { try TrackParser(data: data, type: .gpx).parse() }.to(throwError(TrackParseError.invalidVersion))
}
it("should not throw an invalid version error for 1.0") {
let content = "<gpx version='1.0'></gpx>"
let data = content.data(using: .utf8)
expect { try TrackParser(data: data, type: .gpx).parse() }.toNot(throwError(TrackParseError.invalidVersion))
}
it("should not throw an invalid version error for 1.1") {
let content = "<gpx version='1.1'></gpx>"
let data = content.data(using: .utf8)
expect { try TrackParser(data: data, type: .gpx).parse() }.toNot(throwError(TrackParseError.invalidVersion))
}
}
}
}
|
mit
|
e47352934313ab674a1eb0ca9c51dd23
| 36.2 | 124 | 0.555556 | 4.359375 | false | false | false | false |
ja-mes/experiments
|
iOS/rainyshinycloudy/Pods/Alamofire/Source/Error.swift
|
3
|
2707
|
//
// Error.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The domain used for creating all Alamofire errors.
public let ErrorDomain = "org.alamofire.error"
/// The custom error codes generated by Alamofire.
public enum ErrorCode: Int {
case inputStreamReadFailed = -6000
case outputStreamWriteFailed = -6001
case contentTypeValidationFailed = -6002
case statusCodeValidationFailed = -6003
case dataSerializationFailed = -6004
case stringSerializationFailed = -6005
case jsonSerializationFailed = -6006
case propertyListSerializationFailed = -6007
}
// MARK: -
/// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
public struct ErrorUserInfoKeys {
/// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
public static let ContentType = "ContentType"
/// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
public static let StatusCode = "StatusCode"
}
// MARK: -
extension NSError {
convenience init(domain: String = ErrorDomain, code: ErrorCode, failureReason: String) {
self.init(domain: domain, code: code.rawValue, failureReason: failureReason)
}
convenience init(domain: String = ErrorDomain, code: Int, failureReason: String) {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
self.init(domain: domain, code: code, userInfo: userInfo)
}
}
|
mit
|
b0d4bb6d2900f650c4fae7df6f4e8a31
| 41.296875 | 109 | 0.729221 | 4.580372 | false | false | false | false |
astralbodies/CoreDataConcurrencyDemo
|
CoreDataConcurrencyDemoTests/TestCoreDataStack.swift
|
1
|
1667
|
import CoreDataConcurrencyDemo
import Foundation
import CoreData
class TestCoreDataStack: CoreDataStack {
override lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
NSLog("Providing in-memory persistent store coordinator")
var options = [NSInferMappingModelAutomaticallyOption: true, NSMigratePersistentStoresAutomaticallyOption: true]
var psc: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
var error: NSError? = nil
var ps = psc!.addPersistentStoreWithType(NSInMemoryStoreType, configuration:nil, URL: nil, options: options, error: &error)
if (ps == nil) {
abort()
}
return psc
}()
override func saveDerivedContext(context: NSManagedObjectContext) {
context.performBlock() {
var error: NSError? = nil
if !(context.obtainPermanentIDsForObjects(context.insertedObjects.allObjects, error: &error)) {
NSLog("Error obtaining permanent IDs for \(context.insertedObjects.allObjects), \(error)")
}
if !(context.save(&error)) {
NSLog("Unresolved core data error: \(error)")
abort()
}
// While this is needed because we don't observe change notifications for the derived context, it
// breaks concurrency rules for Core Data. Provide a mechanism to destroy a derived context that
// unregisters it from the save notification instead and rely upon that for merging.
self.saveContext(self.mainContext!)
}
}
}
|
gpl-2.0
|
30c4381804ab174650bcb61f2f5866ae
| 40.675 | 131 | 0.664067 | 5.808362 | false | false | false | false |
Davidde94/StemCode_iOS
|
StemCode/StemProjectKitTests/ProjectionCreationTests.swift
|
1
|
2182
|
//
// ProjectionCreationTests.swift
// StemProjectKitTests
//
// Created by David Evans on 14/09/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import XCTest
import StemKit
@testable import StemProjectKit
class ProjectionCreationTests: XCTestCase {
var testDirectory: String {
return FileManager.default.documentsDirectory + "/test"
}
override func setUp() {
super.setUp()
try? FileManager.default.removeItem(atPath: testDirectory)
try? FileManager.default.createDirectory(atPath: testDirectory, withIntermediateDirectories: true, attributes: nil)
}
func testCreateProject() {
let steps = [
ProjectTemplateStep.CreateFile("Test File", nil),
ProjectTemplateStep.CreateFolder("Test Folder")
]
let template = ProjectTemplate(name: "Template", iconName: "None", languages: ["C"], steps: steps)
let userInfo = UserInfo(name: "David")
let language = LanguageOption(name: "C", extension: "c", headerExtension: "h", templateName: "")
let config = ProjectCreationConfig(userInfo: userInfo, template: template, language: language)
do {
let count = try FileManager.default.contentsOfDirectory(atPath: testDirectory).count
XCTAssertEqual(0, count)
} catch {
XCTFail(error.localizedDescription)
return
}
let project = ProjectCreator.shared.createProject(name: "Test Project", image: nil, config: config, in: testDirectory)
XCTAssertEqual(project.name, "Test Project")
do {
let count = try FileManager.default.contentsOfDirectory(atPath: testDirectory).count
XCTAssertEqual(1, count)
} catch {
XCTFail(error.localizedDescription)
return
}
var isFolder: ObjCBool = false
var exists = FileManager.default.fileExists(atPath: testDirectory, isDirectory: &isFolder)
XCTAssertTrue(exists)
XCTAssertTrue(isFolder.boolValue)
exists = FileManager.default.fileExists(atPath: project.projectFolder + "/Test Project.stem", isDirectory: &isFolder)
XCTAssertTrue(exists)
XCTAssertFalse(isFolder.boolValue)
exists = FileManager.default.fileExists(atPath: project.projectFolder + "/Test Project", isDirectory: &isFolder)
XCTAssertTrue(exists)
XCTAssertTrue(isFolder.boolValue)
}
}
|
mit
|
ec2619a3ec84600becc9ae956fc48f00
| 29.71831 | 120 | 0.752866 | 4.038889 | false | true | false | false |
DuckDeck/StarReview
|
StarReview/StarReview.swift
|
1
|
9921
|
//
// StarReview.swift
// StarReviewDemo
//
// Created by Tyrant on 12/4/15.
// Copyright © 2015 Qfq. All rights reserved.
//
import UIKit
public final class StarReview: UIControl {
public var starCount:Int = 5{ //可以用来打分的星星的数量
didSet{
maxmunValue = Float(starCount) //再设最大值
setNeedsDisplay()
}
}
public var starFillColor:UIColor = UIColor.blue{ //星星的填充颜色
didSet{
setNeedsDisplay()
}
}
public var starBackgroundColor:UIColor = UIColor.gray{
didSet{
setNeedsDisplay()
}
}
public var allowEdit:Bool = true
public var allowAccruteStars:Bool = false{
didSet{
setNeedsDisplay()
}
}
public var starMarginScale:Float = 0.3{
didSet{
if starMarginScale > 0.9
{
starMarginScale = 0.9
}
if starMarginScale < 0.1{
starMarginScale = 0.1
}
setNeedsDisplay()
}
}
public var value:Float {
get{
if allowAccruteStars{
let index = getStarIndex()
if index.0 != -1{ //如果是在星上
let a = Float((1 + starMarginScale) * Float(starRadius) * (Float(index.0) - 1)) //按下的那颗星开始的坐标点
return (Float(starPixelValue * (1 + starMarginScale) * starRadius) - a) / Float(starRadius) + Float(index.0) - 1
}
else{ //如果不在星上
return Float(index.1 + 1)
}
}
else{
return starPixelValue
}
}
set{
if newValue > Float(starCount){
starPixelValue = Float(starCount)
}
else if newValue < 0{
starPixelValue = 0
}
else{
if allowAccruteStars{
//starValue = CGFloat(newValue - 0.08) //这样不精确 需要将值进行转化,虽然这两者很相近,想并不相等
//先取出整数部分
let intPart = Int(newValue)
//取出小数部分
let floatPart = newValue - Float(intPart)
//转化成坐标点
let x = (1 + starMarginScale) * starRadius * Float(intPart) + starRadius * Float(floatPart)
//坐标转化成 starValue
starPixelValue = x / starRadius / (1 + starMarginScale)
}
else{
starPixelValue = Float(lroundf(newValue))
}
}
}
}
public var maxmunValue:Float = 5{
didSet{
setNeedsDisplay()
}
}
public var minimunValue:Float = 0{
didSet{
setNeedsDisplay()
}
}
fileprivate var starRadius:Float = 0.0; //表示Star的大小,其实也就是半径
fileprivate weak var target:AnyObject?
fileprivate var selector:Selector?
fileprivate var event:UIControl.Event?
fileprivate var offsetX:Float{
get{
// return ratio > startReviewWidthScale ? Float(self.frame.width) / 2 - startReviewWidthScale / 2 * Float(self.frame.height) + Float(layer.borderWidth) : Float(layer.borderWidth) //左边的空白处
return ratio > startReviewWidthScale ? Float(self.frame.width) / 2 - startReviewWidthScale / 2 * Float(self.frame.height) : 0.0 //左边的空白处
}
}
fileprivate var offsetY:Float{
get{
return ratio < startReviewWidthScale ? (Float(self.frame.height) - starRadius) / 2 : 0.0 //上面的空白处
}
}
fileprivate var ratio:Float{ //长宽比
get{
return Float(self.frame.width) / Float(self.frame.height)
}
}
fileprivate var startReviewWidthScale:Float{ //这个是5个星星们的长宽比.
get {
return Float(starCount) + Float((starCount - 1)) * starMarginScale
}
}
fileprivate var starPixelValue:Float = 0.0{
didSet{
if starPixelValue > Float(starCount){
starPixelValue = Float(starCount)
}
if starPixelValue < 0{
starPixelValue = 0
}
setNeedsDisplay()
if target != nil && event != nil{
if event == UIControl.Event.valueChanged{
self.sendAction(selector!, to: target, for: nil)
}
}
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(){
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
self.backgroundColor = UIColor.clear
self.isUserInteractionEnabled = true
starRadius = Float(self.frame.size.height) - Float(layer.borderWidth * 2)
if ratio < startReviewWidthScale{
starRadius = Float(self.frame.width) / startReviewWidthScale - Float(layer.borderWidth * 2)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.isUserInteractionEnabled = true
starRadius = Float(self.frame.size.height) - Float(layer.borderWidth * 2)
if ratio < startReviewWidthScale{
starRadius = Float(self.frame.width) / startReviewWidthScale - Float(layer.borderWidth * 2)
}
}
override public func draw(_ rect: CGRect) {
//对于View的尺寸是有要求的,如果过长,那么5颗星排起来也排不满整个长度,如果太高的话,那么又占不了整个高度,如果一个星是正文形,长宽都是1的话,那么总长宽比可以是
//所以可以计算一下应该取多少
clipsToBounds = false
starRadius = Float(self.frame.size.height) - Float(layer.borderWidth * 2)
if ratio < startReviewWidthScale{
starRadius = Float(self.frame.width) / startReviewWidthScale - Float(layer.borderWidth * 2)
}
// print("startReviewWidthScale\(startReviewWidthScale)")
// print("offsetX:\(offsetX)")
// print("offsetY:\(offsetY)")
let ctx = UIGraphicsGetCurrentContext()
for s in 0...(starCount-1){
let x = starMarginScale * Float(s) * starRadius + starRadius * (0.5 + Float(s))
var starCenter = CGPoint(x: CGFloat(x), y: (self.frame.height) / 2) //第个星的中心
if ratio > startReviewWidthScale{
starCenter = CGPoint(x: CGFloat(x)+CGFloat(offsetX), y: self.frame.height / 2)
}
//print("第\(s)个星的中心x:\(starCenter.x) y:\(starCenter.y)")
let radius = starRadius / 2 //半径
//print("星圆的半径:\(radius)")
let p1 = CGPoint(x: starCenter.x, y: starCenter.y - CGFloat(radius)) //
ctx?.setFillColor(starBackgroundColor.cgColor)
ctx?.setStrokeColor(starBackgroundColor.cgColor)
ctx?.setLineCap(CGLineCap.butt)
ctx?.move(to: CGPoint(x: p1.x, y: p1.y))
let angle = Float(4 * Double.pi / 5)
for i in 1...5{
let x = Float(starCenter.x) - sinf(angle * Float(i)) * Float(radius)
let y = Float(starCenter.y) - cosf(angle * Float(i)) * Float(radius)
ctx?.addLine(to: CGPoint(x: CGFloat(x), y: CGFloat(y)))
}
ctx?.drawPath(using: CGPathDrawingMode.fillStroke)
}
ctx?.setFillColor(starFillColor.cgColor)
ctx?.setBlendMode(CGBlendMode.sourceIn)
// print(offsetX)
// print(level)
// print(starValue)
// print(starValue * starLength * ( 1 + gapStarLengthScale))
// print(starLength)
// print(gapStarLengthScale * starLength)
let temp = starRadius * ( 1 + starMarginScale) * starPixelValue
ctx?.fill(CGRect(x: CGFloat(offsetX), y: CGFloat(offsetY), width: CGFloat(temp), height: CGFloat(starRadius)))
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch:UITouch = touches.first{
let point = touch.location(in: self)
let temp = (Float(point.x) - offsetX) / (starRadius * ( 1 + starMarginScale))
if allowAccruteStars{
starPixelValue = temp
}
else{
starPixelValue = Float(Int(temp) + 1)
}
// print("starPicelValue:\(starPixelValue)")
}
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if !allowEdit
{
return
}
if let touch:UITouch = touches.first{
let point = touch.location(in: self)
let temp = (Float(point.x) - offsetX) / (starRadius * ( 1 + starMarginScale))
if allowAccruteStars{
starPixelValue = temp
}
else{
starPixelValue = Float(Int(temp) + 1)
}
// print("starPicelValue:\(starPixelValue)")
}
}
override public func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event) {
self.target = target as AnyObject?
self.selector = action
self.event = controlEvents
}
fileprivate func getStarIndex()->(Int,Int){ //判断坐标在第几个星上,如果不在星上,返回在第几个间隙上
let i = Int(starPixelValue)
if starPixelValue - Float(i) <= 1 / (1 + starMarginScale)
{
return (i + 1,-1)
}
else{
return (-1, i)
}
}
}
|
mit
|
7fa19a1d9f3d587eb9643d7a8e005071
| 32.877256 | 199 | 0.541027 | 4.044828 | false | false | false | false |
tectijuana/patrones
|
Bloque1SwiftArchivado/PracticasSwift/Cinthyajuarez/Ejercicio3.swift
|
1
|
810
|
/*
Instituto Nacional de México
Instituto Tecnológico de Tijuana
Patrones de diseño
Profesor Rene Solis
Ejercicio 3
Fecha: 3/2/2017
Juarez Medina Yesifer Cinthya - 13211442
@CinthyaJuarez
Descripción del problema:
Imprimir si las gráficas de las dos ecuaciones siguientes representan la misra recta,
rectas paralelas o rectas que se intersectan en un punto.
5x+y=12 10x+2y=24
*/
var Ecuacion1:[Int] = [5,1,12]
var Ecuacion2:[Int] = [10,2,24]
var x=0, y=0, z=0
x = Ecuacion1[0] / Ecuacion2[0]
y = Ecuacion1[1] / Ecuacion2[1]
z = Ecuacion1[2] / Ecuacion2[2]
print ("Las ecuaciones 5x+y=12 y 10x+2y=24 son: ")
if x==y && y==z{
print ("Ecuaciones con la misma recta")
}
if x != y {
print ("Ecuaciones no perpendiculares")
}
if x==y && y != z{
print("Ecuaciones con diferente recta")
}
|
gpl-3.0
|
9f54ca9b8f71652735e9be1c4c0ba891
| 19.125 | 85 | 0.699379 | 2.236111 | false | false | false | false |
dxdp/Stage
|
Stage/PropertyBindings/UIActivityIndicatorViewBindings.swift
|
1
|
3269
|
//
// UIActivityIndicatorViewBindings.swift
// Stage
//
// Copyright © 2016 David Parton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
public extension StageRegister {
public class func ActivityIndicatorView(_ registration: StagePropertyRegistration) {
tap(registration) {
$0.register("activityIndicatorViewStyle") { scanner in try UIActivityIndicatorViewStyle.create(using: scanner) }
.apply { (view: UIActivityIndicatorView, value) in view.activityIndicatorViewStyle = value }
$0.registerColor("color")
.apply { (view: UIActivityIndicatorView, value) in view.color = value }
$0.registerBool("hidesWhenStopped")
.apply { (view: UIActivityIndicatorView, value) in view.hidesWhenStopped = value }
$0.registerBool("startsWhenShown")
.apply { (view: UIActivityIndicatorView, value) in
view.stageState.startsWhenShown = value
if !view.isHidden && !view.isAnimating { view.startAnimating() }
}
}
}
}
public extension UIActivityIndicatorView {
@objc class UIActivityIndicatorViewStageState: NSObject {
static var AssociationKey = 0
weak var owner: UIActivityIndicatorView?
var startsWhenShown: Bool = false
init(owner: UIActivityIndicatorView) {
super.init()
self.owner = owner
StageSafeKVO.observer(self, watchKey: "hidden", in: owner) { [weak self] _, _, _ in
guard let this = self, let owner = this.owner else { return }
if !owner.isHidden && !owner.isAnimating && this.startsWhenShown {
owner.startAnimating()
}
}
}
}
var stageState : UIActivityIndicatorViewStageState {
if let state = associatedObject(key: &UIActivityIndicatorViewStageState.AssociationKey) as? UIActivityIndicatorViewStageState { return state }
let state = UIActivityIndicatorViewStageState(owner: self)
associateObject(state, key: &UIActivityIndicatorViewStageState.AssociationKey, policy: .RetainNonatomic)
return state
}
}
|
mit
|
dcaec6900561f6d642099e4bd94e9550
| 48.515152 | 150 | 0.679009 | 5.04321 | false | false | false | false |
spark/photon-tinker-ios
|
Photon-Tinker/Mesh/Gen3SetupConnectingToInternetViewControllers.swift
|
1
|
4019
|
//
// Created by Raimundas Sakalauskas on 9/20/18.
// Copyright (c) 2018 Particle. All rights reserved.
//
import UIKit
class Gen3SetupConnectingToInternetEthernetViewController: Gen3SetupProgressViewController, Storyboardable {
static var nibName: String {
return "Gen3SetupProgressView"
}
override func setContent() {
successTitleLabel.text = Gen3SetupStrings.ConnectingToInternetEthernet.SuccessTitle
successTextLabel.text = Gen3SetupStrings.ConnectingToInternetEthernet.SuccessText
progressTitleLabel.text = Gen3SetupStrings.ConnectingToInternetEthernet.Title
self.progressTextLabelValues = [
Gen3SetupStrings.ConnectingToInternetEthernet.Text1,
Gen3SetupStrings.ConnectingToInternetEthernet.Text2
]
setProgressLabelValues()
}
override func setState(_ state: Gen3SetupFlowState) {
DispatchQueue.main.async {
switch state {
case .TargetDeviceConnectingToInternetStarted:
self.setStep(0)
case .TargetDeviceConnectingToInternetStep1Done:
self.setStep(1)
case .TargetDeviceConnectingToInternetCompleted:
self.setStep(2)
default:
fatalError("this should never happen")
}
}
}
}
class Gen3SetupConnectingToInternetWifiViewController: Gen3SetupProgressViewController, Storyboardable {
static var nibName: String {
return "Gen3SetupProgressView"
}
override func setContent() {
successTitleLabel.text = Gen3SetupStrings.ConnectingToInternetWifi.SuccessTitle
successTextLabel.text = Gen3SetupStrings.ConnectingToInternetWifi.SuccessText
progressTitleLabel.text = Gen3SetupStrings.ConnectingToInternetWifi.Title
self.progressTextLabelValues = [
Gen3SetupStrings.ConnectingToInternetWifi.Text1,
Gen3SetupStrings.ConnectingToInternetWifi.Text2
]
setProgressLabelValues()
}
override func setState(_ state: Gen3SetupFlowState) {
DispatchQueue.main.async {
switch state {
case .TargetDeviceConnectingToInternetStarted:
self.setStep(0)
case .TargetDeviceConnectingToInternetStep1Done:
self.setStep(1)
case .TargetDeviceConnectingToInternetCompleted:
self.setStep(2)
default:
fatalError("this should never happen")
}
}
}
}
class Gen3SetupConnectingToInternetCellularViewController: Gen3SetupProgressViewController, Storyboardable {
static var nibName: String {
return "Gen3SetupProgressView"
}
override func setContent() {
successTitleLabel.text = Gen3SetupStrings.ConnectingToInternetCellular.SuccessTitle
successTextLabel.text = Gen3SetupStrings.ConnectingToInternetCellular.SuccessText
progressTitleLabel.text = Gen3SetupStrings.ConnectingToInternetCellular.Title
self.progressTextLabelValues = [
Gen3SetupStrings.ConnectingToInternetCellular.Text1,
Gen3SetupStrings.ConnectingToInternetCellular.Text2,
Gen3SetupStrings.ConnectingToInternetCellular.Text3
]
setProgressLabelValues()
}
override func setState(_ state: Gen3SetupFlowState) {
DispatchQueue.main.async {
switch state {
case .TargetDeviceConnectingToInternetStarted:
self.setStep(0)
case .TargetDeviceConnectingToInternetStep0Done:
self.setStep(1)
case .TargetDeviceConnectingToInternetStep1Done:
self.setStep(2)
case .TargetDeviceConnectingToInternetCompleted:
self.setStep(3)
default:
fatalError("this should never happen")
}
}
}
}
|
apache-2.0
|
5b3baeb03f217b19e416573cbb750944
| 32.491667 | 108 | 0.657626 | 5.431081 | false | false | false | false |
cocoaheadsru/server
|
Sources/App/Controllers/User/GiveSpeechController.swift
|
1
|
893
|
import Vapor
import FluentProvider
import Foundation
import Multipart
final class GiveSpeechController {
func storeRequest(_ request: Request) throws -> ResponseRepresentable {
guard
let json = request.json,
let title = json[GiveSpeech.Keys.title]?.string,
let desciption = json[GiveSpeech.Keys.description]?.string
else {
throw Abort(.badRequest, reason: "Request's body no have `title` or `desciption` fields to give speech")
}
let user = try request.user()
let giveSpeech = GiveSpeech(
title: title,
description: desciption,
userId: user.id!)
try giveSpeech.save()
return giveSpeech
}
}
extension GiveSpeechController: ResourceRepresentable {
func makeResource() -> Resource<GiveSpeech> {
return Resource(
store: storeRequest
)
}
}
extension GiveSpeechController: EmptyInitializable { }
|
mit
|
d45fe13c4c858f1db68e5c3fa3175d04
| 21.897436 | 112 | 0.696529 | 4.442786 | false | false | false | false |
benlangmuir/swift
|
validation-test/Reflection/reflect_NSSet.swift
|
22
|
1431
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_NSSet
// RUN: %target-codesign %t/reflect_NSSet
// RUN: %target-run %target-swift-reflection-test %t/reflect_NSSet | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
import Foundation
class TestClass {
var t: NSSet
init(t: NSSet) {
self.t = t
}
}
var obj = TestClass(t: [1, 2, 3, 3, 2, 1])
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_NSSet.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=t offset=16
// CHECK-64: (reference kind=strong refcounting=unknown)))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_NSSet.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=t offset=8
// CHECK-32: (reference kind=strong refcounting=unknown)))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
|
apache-2.0
|
3f2ddae10e6fd6f486f84bd29ed6ecc8
| 28.204082 | 119 | 0.693222 | 3.124454 | false | true | false | false |
WestlakeAPC/game-off-2016
|
external/Fiber2D/Fiber2D/ActionSequence.swift
|
1
|
4002
|
//
// ActionSequenceContainer.swift
// Fiber2D
//
// Created by Andrey Volodin on 04.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
public struct ActionSequenceContainer: ActionContainer, Continous {
@inline(__always)
mutating public func update(state: Float) {
let t = state
var found = 0
var new_t: Float = 0.0
if t < split {
// action[0]
found = 0
if split != 0 {
new_t = t / split
}
else {
new_t = 1
}
}
else {
// action[1]
found = 1
if split == 1 {
new_t = 1
}
else {
new_t = (t - split) / (1 - split)
}
}
if found == 1 {
if last == -1 {
// action[0] was skipped, execute it.
actions[0].start(with: target)
actions[0].update(state: 1.0)
actions[0].stop()
}
else if last == 0 {
// switching to action 1. stop action 0.
actions[0].update(state: 1.0)
actions[0].stop()
}
}
else if found == 0 && last == 1 {
// Reverse mode ?
// XXX: Bug. this case doesn't contemplate when _last==-1, found=0 and in "reverse mode"
// since it will require a hack to know if an action is on reverse mode or not.
// "step" should be overriden, and the "reverseMode" value propagated to inner Sequences.
actions[1].update(state: 0)
actions[1].stop()
}
// Last action found and it is done.
if found == last && actions[found].isDone {
return
}
// New action. Start it.
if found != last {
actions[found].start(with: target)
}
actions[found].update(state: new_t)
self.last = found
}
public mutating func start(with target: AnyObject?) {
elapsed = 0
self.target = target
self.split = actions[0].duration / max(duration, Float.ulpOfOne)
self.last = -1
}
public mutating func stop() {
// Issue #1305
if last != -1 {
actions[last].stop()
}
target = nil
}
public mutating func step(dt: Time) {
elapsed += dt
self.update(state: max(0, // needed for rewind. elapsed could be negative
min(1, elapsed / max(duration, Float.ulpOfOne)) // division by 0
)
)
}
weak var target: AnyObject? = nil
public var tag: Int = 0
private(set) public var duration: Time = 0.0
private(set) public var elapsed: Time = 0.0
public var isDone: Bool {
return elapsed > duration
}
private(set) var actions: [ActionContainerFiniteTime] = []
private var split: Float = 0.0
private var last = -1
init(first: ActionContainerFiniteTime, second: ActionContainerFiniteTime) {
actions = [first, second]
// Force unwrap because it won't work otherwise anyways
duration = first.duration + second.duration
}
}
/*extension ActionSequenceContainer {
init(actions: ActionContainer...) {
guard actions.count > 2 else {
assertionFailure("ERROR: Sequence must contain at least 2 actions")
return
}
let first = actions.first!
var second: ActionContainer = actions[1]
for i in 2..<actions.count {
second = ActionSequenceContainer(first: second, second: actions[i])
}
self.init(first: first, second: second)
}
}*/
extension ActionContainer where Self: FiniteTime {
public func then(_ next: ActionContainerFiniteTime) -> ActionSequenceContainer {
return ActionSequenceContainer(first: self, second: next)
}
}
|
apache-2.0
|
1483d86eda24f5a4118a15ecd9657b4c
| 28.20438 | 101 | 0.51962 | 4.344191 | false | false | false | false |
francisceioseph/Swift-Files-App
|
Swift-Files/SFPlainTextTableViewController.swift
|
1
|
2633
|
//
// SFPlainTextTableViewController.swift
// Swift-Files
//
// Created by Francisco José A. C. Souza on 26/12/15.
// Copyright © 2015 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
class SFPlainTextTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Delegate Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch (indexPath.row) {
case 0:
FileHelper.sharedInstance.createPlainTextFileWithName("plain_text")
self.makeSimpleAlert("Success", message: "File plain_text.txt created succfully!")
case 1...2:
var fileContent: String?
do {
fileContent = try FileHelper.sharedInstance.readPlainTextWithName("plain_text")
let options = ["mode": indexPath.row, "file_content": fileContent!] as [String : AnyObject]
performSegueWithIdentifier("toPlainTextDetail", sender: options)
}
catch {
self.makeSimpleAlert("Error", message: "File Not Found!!!")
}
case 3:
do {
try FileHelper.sharedInstance.deletePlainTextFileWithName("plain_text")
self.makeSimpleAlert("Success", message: "File plain_text.txt deleted succfully!")
}
catch {
self.makeSimpleAlert("Error", message: "An error was detected when deleting plain_text.txt.")
}
default:
break
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toPlainTextDetail" {
let destinationViewController = segue.destinationViewController as! SFPlainTextDetailViewController
if let options = sender as? [String : AnyObject],
let fileContent = options["file_content"] as? String{
destinationViewController.bodyText = fileContent
if let mode = options["mode"] as? Int where mode == 2 {
destinationViewController.editMode = true
}
}
}
}
}
|
mit
|
86c4a3986fc4dd16f6d5a98f0941482c
| 33.155844 | 111 | 0.565779 | 5.754923 | false | false | false | false |
beeth0ven/LTMorphingLabel
|
LTMorphingLabel/LTMorphingLabel+Pixelate.swift
|
6
|
3504
|
//
// LTMorphingLabel+Pixelate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2015 Lex Tang, http://lexrus.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
extension LTMorphingLabel {
func PixelateLoad() {
effectClosures["Pixelate\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
effectClosures["Pixelate\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self.newRects[index],
alpha: CGFloat(progress),
size: self.font.pointSize,
drawingProgress: CGFloat(1.0 - progress)
)
}
drawingClosures["Pixelate\(LTMorphingPhaseDraw)"] = {
(charLimbo: LTCharacterLimbo) in
if charLimbo.drawingProgress > 0.0 {
let charImage = self.pixelateImageForCharLimbo(charLimbo, withBlurRadius: charLimbo.drawingProgress * 6.0)
charImage.drawInRect(charLimbo.rect)
return true
}
return false
}
}
private func pixelateImageForCharLimbo(charLimbo: LTCharacterLimbo, withBlurRadius blurRadius: CGFloat) -> UIImage {
let scale = min(UIScreen.mainScreen().scale, 1.0 / blurRadius)
UIGraphicsBeginImageContextWithOptions(charLimbo.rect.size, false, scale)
let fadeOutAlpha = min(1.0, max(0.0, charLimbo.drawingProgress * -2.0 + 2.0 + 0.01))
let rect = CGRectMake(0, 0, charLimbo.rect.size.width, charLimbo.rect.size.height)
String(charLimbo.char).drawInRect(rect, withAttributes: [
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: self.textColor.colorWithAlphaComponent(fadeOutAlpha)
])
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage
}
}
|
mit
|
13d1734420b1de44f114cf408b0889f2
| 39.195402 | 122 | 0.634153 | 4.987161 | false | false | false | false |
sebastiangoetz/slr-toolkit
|
ios-client/SLR Toolkit/Views/Add Project/AddProjectViewInteractor.swift
|
1
|
2588
|
import SwiftUI
protocol AddProjectViewInteractor {
/// Clones a project from a remote git repository.
func cloneProject(username: String, token: String, rememberCredentials: Bool, repositoryURL: String, isLoading: Binding<Bool>, progress: Binding<Float?>, completion: @escaping (Result<URL, Error>) -> Void)
}
struct AddProjectViewInteractorImplementation: AddProjectViewInteractor {
func cloneProject(username: String, token: String, rememberCredentials: Bool, repositoryURL: String, isLoading: Binding<Bool>, progress: Binding<Float?>, completion: @escaping (Result<URL, Error>) -> Void) {
isLoading.wrappedValue = true
if rememberCredentials {
// TODO store securely in keychain, e.g. using https://github.com/kishikawakatsumi/KeychainAccess
UserDefaults.standard.set(username, forKey: .username)
}
guard let url = URL(string: repositoryURL) else { return }
GitManager.default.cloneRepository(at: url, credentials: (username, token)) { prgrss in
progress.wrappedValue = prgrss
} completion: { result in
switch result {
case .success(let repositoryDirectory):
isLoading.wrappedValue = false
if rememberCredentials {
UserDefaults.standard.set(token, forKey: .token)
}
completion(.success(repositoryDirectory))
case .failure(let error):
completion(.failure(error))
}
}
}
}
struct AddProjectViewInteractorMock: AddProjectViewInteractor {
func cloneProject(username: String, token: String, rememberCredentials: Bool, repositoryURL: String, isLoading: Binding<Bool>, progress: Binding<Float?>, completion: @escaping (Result<URL, Error>) -> Void) {
guard let url = URL(string: repositoryURL) else { return }
GitManager(gitClient: MockGitClient()).cloneRepository(at: url, credentials: (username, token)) { result in
switch result {
case .success(let url):
completion(.success(url))
case .failure(let error):
completion(.failure(error))
}
}
}
}
struct AddProjectViewInteractorKey: EnvironmentKey {
static let defaultValue: AddProjectViewInteractor = AddProjectViewInteractorImplementation()
}
extension EnvironmentValues {
var addProjectViewInteractor: AddProjectViewInteractor {
get { self[AddProjectViewInteractorKey.self] }
set { self[AddProjectViewInteractorKey.self] = newValue }
}
}
|
epl-1.0
|
77fac2be2ccf816ab44b495bd05d5ade
| 42.864407 | 211 | 0.667311 | 4.801484 | false | false | false | false |
kstaring/swift
|
test/DebugInfo/generic_arg.swift
|
7
|
1068
|
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
import StdlibUnittest
func foo<T>(_ x: T) -> () {
// CHECK: define {{.*}} @_TF11generic_arg3foourFxT_
// CHECK: %[[T:.*]] = alloca %swift.type*
// CHECK: %[[X:.*]] = alloca %swift.opaque*
// CHECK: store %swift.type* %T, %swift.type** %[[T]],
// CHECK: call void @llvm.dbg.declare(metadata %swift.type** %[[T]],
// CHECK-SAME: metadata ![[T1:.*]], metadata ![[EMPTY:.*]])
// CHECK: store %swift.opaque* %0, %swift.opaque** %[[X]],
// CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %[[X]],
// CHECK-SAME: metadata ![[X1:.*]], metadata ![[EMPTY]])
// CHECK: ![[T1]] = !DILocalVariable(name: "$swift.type.T",
// CHECK-SAME: flags: DIFlagArtificial)
// CHECK: ![[EMPTY]] = !DIExpression()
// CHECK: ![[X1]] = !DILocalVariable(name: "x", arg: 1,
// CHECK-SAME: line: 3, type: ![[TY:.*]])
// CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_TtQq_F11generic_arg3foourFxT_")
_blackHole(x)
}
foo(42)
|
apache-2.0
|
05682d531824beb10ce4d1ba89a2b397
| 47.545455 | 90 | 0.544007 | 3.266055 | false | false | false | false |
cxpyear/cc
|
spdbapp/spdbapp/Models.swift
|
1
|
1239
|
//
// Models.swift
// spdbapp
//
// Created by tommy on 15/5/11.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import Foundation
protocol GBModelBaseAciton {
func Add()
func Update()
func Del()
func Find()
}
//meeting type
enum GBMeetingType {
case HANGBAN, DANGBAN, DANGWEI, DONGSHI, ALL
}
class GBBase: NSObject {
var basename = ""
}
class GBBox: GBBase {
var macId : String = "11-22-33-44-55-66"
var type : GBMeetingType?
//add new name
var name: String = ""
override init(){
super.init()
//Defualt type = HANGBAN
type = GBMeetingType.ALL
macId = GBNetwork.getMacId()
//add new name
name = ""
}
}
class GBMeeting: GBBase {
var name: String = ""
var type : GBMeetingType = .ALL
var startTime: NSDate = NSDate()
var status: Bool?
var files:[GBDoc] = []
var id: String = ""
}
class GBDoc: GBBase {
var id: String = ""
var index: Int = 0
var count: Int = 0
var type: GBMeetingType = .ALL
var status: Bool?
var pdfPath: String = ""
var size: Int = 0
var createAt: String = ""
var path: String = ""
var name: String = ""
}
|
bsd-3-clause
|
635388b8b4c00a94b9dd883aeeaef51b
| 16.422535 | 52 | 0.56346 | 3.316354 | false | false | false | false |
Mai-Tai-D/maitaid001
|
Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsLayer.swift
|
1
|
7840
|
//
// ChartPointsLayer.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public struct ChartPointLayerModel<T: ChartPoint>: CustomDebugStringConvertible {
public let chartPoint: T
public let index: Int
public var screenLoc: CGPoint
init(chartPoint: T, index: Int, screenLoc: CGPoint) {
self.chartPoint = chartPoint
self.index = index
self.screenLoc = screenLoc
}
func copy(_ chartPoint: T? = nil, index: Int? = nil, screenLoc: CGPoint? = nil) -> ChartPointLayerModel<T> {
return ChartPointLayerModel(
chartPoint: chartPoint ?? self.chartPoint,
index: index ?? self.index,
screenLoc: screenLoc ?? self.screenLoc
)
}
public var debugDescription: String {
return "chartPoint: \(chartPoint), index: \(index), screenLoc: \(screenLoc)"
}
}
public struct TappedChartPointLayerModel<T: ChartPoint> {
public let model: ChartPointLayerModel<T>
public let distance: CGFloat
init(model: ChartPointLayerModel<T>, distance: CGFloat) {
self.model = model
self.distance = distance
}
}
public struct TappedChartPointLayerModels<T: ChartPoint> {
public let models: [TappedChartPointLayerModel<T>]
public let layer: ChartPointsLayer<T>
init(models: [TappedChartPointLayerModel<T>], layer: ChartPointsLayer<T>) {
self.models = models
self.layer = layer
}
}
public struct ChartPointsTapSettings<T: ChartPoint> {
public let radius: CGFloat
let handler: ((TappedChartPointLayerModels<T>) -> Void)?
public init(radius: CGFloat = 30, handler: ((TappedChartPointLayerModels<T>) -> Void)? = nil) {
self.radius = radius
self.handler = handler
}
}
open class ChartPointsLayer<T: ChartPoint>: ChartCoordsSpaceLayer {
open internal(set) var chartPointsModels: [ChartPointLayerModel<T>] = []
open let displayDelay: Float
open var chartPointScreenLocs: [CGPoint] {
return chartPointsModels.map{$0.screenLoc}
}
fileprivate let chartPoints: [T]
fileprivate let tapSettings: ChartPointsTapSettings<T>?
public init(xAxis: ChartAxis, yAxis: ChartAxis, chartPoints: [T], displayDelay: Float = 0, tapSettings: ChartPointsTapSettings<T>? = nil) {
self.chartPoints = chartPoints
self.displayDelay = displayDelay
self.tapSettings = tapSettings
super.init(xAxis: xAxis, yAxis: yAxis)
}
open override func handleGlobalTap(_ location: CGPoint) -> Any? {
guard let tapSettings = tapSettings, let localCenter = toLocalCoordinates(location) else {return nil}
var models: [TappedChartPointLayerModel<T>] = []
for chartPointModel in chartPointsModels {
let transformedScreenLoc = modelLocToScreenLoc(x: chartPointModel.chartPoint.x.scalar, y: chartPointModel.chartPoint.y.scalar)
let distance = transformedScreenLoc.distance(localCenter)
if distance < tapSettings.radius {
models.append(TappedChartPointLayerModel(model: chartPointModel.copy(screenLoc: contentToGlobalScreenLoc(chartPointModel.chartPoint)), distance: distance))
}
}
let tappedModels = TappedChartPointLayerModels(models: models, layer: self)
tapSettings.handler?(tappedModels)
return tappedModels
}
func toLocalCoordinates(_ globalPoint: CGPoint) -> CGPoint? {
return globalPoint
}
override open func chartInitialized(chart: Chart) {
super.chartInitialized(chart: chart)
initChartPointModels()
if displayDelay == 0 {
display(chart: chart)
} else {
DispatchQueue.main.asyncAfter(deadline: ChartTimeUtils.toDispatchTime(displayDelay)) {
self.display(chart: chart)
}
}
}
func initChartPointModels() {
chartPointsModels = generateChartPointModels(chartPoints)
}
func generateChartPointModels(_ chartPoints: [T]) -> [ChartPointLayerModel<T>] {
return chartPoints.enumerated().map {index, chartPoint in
ChartPointLayerModel(chartPoint: chartPoint, index: index, screenLoc: modelLocToScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar))
}
}
open func display(chart: Chart) {}
open override func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) {
super.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh)
chartPointsModels = chartPoints.enumerated().map {index, chartPoint in
return ChartPointLayerModel(chartPoint: chartPoint, index: index, screenLoc: modelLocToScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar))
}
}
open func chartPointScreenLoc(_ chartPoint: ChartPoint) -> CGPoint {
return modelLocToScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar)
}
open func chartPointsForScreenLoc(_ screenLoc: CGPoint) -> [T] {
return filterChartPoints { $0 == screenLoc }
}
open func chartPointsForScreenLocX(_ x: CGFloat) -> [T] {
return filterChartPoints { $0.x =~ x }
}
open func chartPointsForScreenLocY(_ y: CGFloat) -> [T] {
return filterChartPoints { $0.y =~ y }
}
// smallest screen space between chartpoints on x axis
open lazy private(set) var minXScreenSpace: CGFloat = {
return self.minAxisScreenSpace{$0.x}
}()
// smallest screen space between chartpoints on y axis
open lazy private(set) var minYScreenSpace: CGFloat = {
return self.minAxisScreenSpace{$0.y}
}()
fileprivate func minAxisScreenSpace(dimPicker: (CGPoint) -> CGFloat) -> CGFloat {
return chartPointsModels.reduce((CGFloat.greatestFiniteMagnitude, -CGFloat.greatestFiniteMagnitude)) {tuple, viewWithChartPoint in
let minSpace = tuple.0
let previousScreenLoc = tuple.1
return (min(minSpace, abs(dimPicker(viewWithChartPoint.screenLoc) - previousScreenLoc)), dimPicker(viewWithChartPoint.screenLoc))
}.0
}
fileprivate func filterChartPoints(_ includePoint: (CGPoint) -> Bool) -> [T] {
return chartPointsModels.reduce(Array<T>()) {includedPoints, chartPointModel in
let chartPoint = chartPointModel.chartPoint
if includePoint(chartPointScreenLoc(chartPoint)) {
return includedPoints + [chartPoint]
} else {
return includedPoints
}
}
}
func updateChartPointsScreenLocations() {
chartPointsModels = updateChartPointsScreenLocations(chartPointsModels)
}
open func contentScreenCoords(_ chartPoint: T) -> CGPoint {
return modelLocToScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar)
}
open func containerScreenCoords(_ chartPoint: T) -> CGPoint {
return modelLocToContainerScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar)
}
func updateChartPointsScreenLocations(_ chartPointsModels: [ChartPointLayerModel<T>]) -> [ChartPointLayerModel<T>] {
var chartPointsModelsVar = chartPointsModels
for i in 0..<chartPointsModelsVar.count {
let chartPointModel = chartPointsModelsVar[i]
chartPointsModelsVar[i].screenLoc = CGPoint(x: xAxis.screenLocForScalar(chartPointModel.chartPoint.x.scalar), y: yAxis.screenLocForScalar(chartPointModel.chartPoint.y.scalar))
}
return chartPointsModelsVar
}
}
|
mit
|
ce5e3cf3bbbbde7593f8204d73eb55ab
| 36.333333 | 203 | 0.667474 | 4.728589 | false | false | false | false |
cdtschange/SwiftMKit
|
SwiftMKitDemo/SwiftMKitDemoTests/NumberKeyboardTests.swift
|
1
|
12272
|
//
// NumberKeyboardTests.swift
// SwiftMKitDemo
//
// Created by Mao on 6/16/16.
// Copyright © 2016 cdts. All rights reserved.
//
import XCTest
@testable import SwiftMKitDemo
class NumberKeyboardTests: XCTestCase {
var numberKeyboard: NumberKeyboardProtocol = NumberKeyboard()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testInputDotNormalType() {
numberKeyboard.type = .normal
var old = "12.3"
var new = "1.2.3"
var (final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "12.3")
old = "123"
new = "12.3"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "12.3")
old = "123"
new = ".123"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.123")
old = "123"
new = "123."
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "123.")
old = "10"
new = "1.0"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "1.0")
old = "0"
new = ".0"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.0")
old = ""
new = "."
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.")
}
func testInputDotMoneyType() {
numberKeyboard.type = .money
var old = "12.3"
var new = "1.2.3"
var (final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "12.3")
old = "123"
new = "12.3"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "12.3")
old = "123"
new = ".123"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.12")
old = "123"
new = "123."
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "123.")
old = "10"
new = "1.0"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "1.0")
old = "100"
new = ".100"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.10")
old = "0"
new = ".0"
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.0")
old = ""
new = "."
(final, _) = numberKeyboard.matchInputDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.")
}
func testInputNumberNormalType() {
numberKeyboard.type = .normal
var old = "0"
var new = "01"
var (final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "01")
old = "0"
new = "00"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "00")
old = "0.1"
new = "00.1"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "00.1")
old = "0.1"
new = "0.01"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.01")
old = "0.1"
new = "0.10"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.10")
old = "0.1"
new = "10.1"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.1")
old = "0.1"
new = "02.1"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "02.1")
old = "10.10"
new = "10.105"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.105")
old = "10.10"
new = "10.100"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.100")
old = "123.21"
new = "123.321"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "123.321")
}
func testInputNumberMoneyType() {
numberKeyboard.type = .money
var old = "0"
var new = "01"
var (final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "01")
old = "0"
new = "00"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "00")
old = "0.1"
new = "00.1"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "00.1")
old = "0.1"
new = "0.01"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.01")
old = "0.1"
new = "0.10"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.10")
old = "0.1"
new = "10.1"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.1")
old = "0.1"
new = "02.1"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "02.1")
old = "10.10"
new = "10.105"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.10")
old = "10.10"
new = "10.100"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.10")
old = "10.10"
new = "10.120"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "10.10")
}
func testInputNoDotType() {
numberKeyboard.type = .noDot
var old = "0"
var new = "01"
var (final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "01")
old = "0"
new = "00"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "00")
old = "1"
new = "01"
(final, _) = numberKeyboard.matchInputNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "01")
}
func testDeleteNumberNormalType() {
numberKeyboard.type = .normal
var old = "01"
var new = "0"
var (final, _) = numberKeyboard.matchDeleteNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0")
old = "01"
new = "1"
(final, _) = numberKeyboard.matchDeleteNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "1")
old = "0.1"
new = ".1"
(final, _) = numberKeyboard.matchDeleteNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, ".1")
old = "0.1"
new = "0."
(final, _) = numberKeyboard.matchDeleteNumber(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "0.")
}
func testDeleteDotNormalType() {
numberKeyboard.type = .normal
var old = "0.1"
var new = "01"
var (final, _) = numberKeyboard.matchDeleteDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "1")
old = "00.1"
new = "001"
(final, _) = numberKeyboard.matchDeleteDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "1")
old = "01.1"
new = "011"
(final, _) = numberKeyboard.matchDeleteDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "11")
old = "1.23"
new = "123"
(final, _) = numberKeyboard.matchDeleteDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "123")
old = "12."
new = "12"
(final, _) = numberKeyboard.matchDeleteDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "12")
old = ".23"
new = "23"
(final, _) = numberKeyboard.matchDeleteDot(old, new: new)
XCTAssertNotNil(final)
XCTAssertEqual(final, "23")
}
func testmatchConfirmNormalType() {
numberKeyboard.type = .normal
var input = "1"
var (output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "1")
input = "0.1"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "0.1")
input = "01"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "1")
input = "00001"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "1")
input = ".1"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "0.1")
input = "00.1"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "0.1")
input = "01.5"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "1.5")
input = "1.50"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "1.5")
input = "1.00"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "1")
input = "0.0"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "0")
input = "0.00000005"
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "0.00000005")
input = ""
(output) = numberKeyboard.matchConfirm(input)
XCTAssertNotNil(output)
XCTAssertEqual(output, "")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
995a5e1f48b6d135cb46b19fc9344ca1
| 29.224138 | 111 | 0.542499 | 4.068634 | false | false | false | false |
winslowdibona/TabDrawer
|
TabDrawer/Classes/UIView+Easy.swift
|
1
|
5191
|
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
infix operator <- {}
/**
Operator which applies the attribute given to the view located
in the left hand side of it
- parameter lhs: `UIView` the attributes will apply to
- parameter rhs: Attribute applied to the `UIView`
- returns: The array of attributes applied
*/
public func <- (lhs: UIView, rhs: Attribute) -> [Attribute] {
return lhs <- [rhs]
}
/**
Opeator which applies the attributes given to the view located
in the left hand side of it
- parameter lhs: UIView the attributes will apply to
- parameter rhs: Attributes applied to the UIView
- returns: The array of attributes applied
*/
public func <- (lhs: UIView, rhs: [Attribute]) -> [Attribute] {
// Disable autoresizing to constraints translation
lhs.translatesAutoresizingMaskIntoConstraints = false
// Create constraints to install and gather regular attribtues
var constraintsToInstall: [NSLayoutConstraint] = []
var regularAttributes: [Attribute] = []
for attribute in rhs {
// Create the constraint
let newConstraints = attribute.createConstraintForView(lhs)
constraintsToInstall.appendContentsOf(newConstraints)
// Gather regular attributes only as we don't want to store
// `CompoundAttribute` objects
var attributesToStore: [Attribute] = []
if let compountAttribute = attribute as? CompoundAttribute {
attributesToStore.appendContentsOf(compountAttribute.attributes)
}
else {
attributesToStore.append(attribute)
}
// Append to the list of attributes that will be returned
regularAttributes.appendContentsOf(attributesToStore)
// Store the attribute applied in the superview
if attribute.ownedBySuperview() {
lhs.superview?.easy_attributes.appendContentsOf(attributesToStore)
}
else { // Store the attributes applied in self
lhs.easy_attributes.appendContentsOf(attributesToStore)
}
}
// Install these constraints
NSLayoutConstraint.activateConstraints(constraintsToInstall)
// Return just regular `Attributes`, not `CompoundAttributes`
return regularAttributes
}
/**
Convenience methods applicable to `UIView` and subclasses
*/
public extension UIView {
/**
This method will trigger the recreation of the constraints
created using *EasyPeasy* for the current view. `Condition`
closures will be evaluated again
*/
public func easy_reload() {
var storedAttributes: [Attribute] = []
// Reload attributes owned by the superview
if let attributes = (self.superview?.easy_attributes.filter { $0.createView === self }) {
storedAttributes.appendContentsOf(attributes)
}
// Reload attributes owned by the current view
let attributes = self.easy_attributes.filter { $0.createView === self }
storedAttributes.appendContentsOf(attributes)
// Apply
self <- storedAttributes
}
/**
Clears all the constraints applied with EasyPeasy to the
current `UIView`
*/
public func easy_clear() {
// Remove from the stored Attribute objects of the superview
// those which createView is the current UIView
if let superview = self.superview {
superview.easy_attributes = superview.easy_attributes.filter { $0.createView !== self }
}
// Remove from the stored Attribute objects of the current view
// those which createView is the current UIView
self.easy_attributes = self.easy_attributes.filter { $0.createView !== self }
// Now uninstall those constraints
var constraintsToUninstall: [NSLayoutConstraint] = []
// Gather NSLayoutConstraints in the superview with self as createView
for constraint in (self.superview?.constraints ?? []) {
if let attribute = constraint.easy_attribute where attribute.createView === self {
constraintsToUninstall.append(constraint)
}
}
// Gather NSLayoutConstraints in self with self as createView
for constraint in self.constraints {
if let attribute = constraint.easy_attribute where attribute.createView === self {
constraintsToUninstall.append(constraint)
}
}
// Deactive the constraints
NSLayoutConstraint.deactivateConstraints(constraintsToUninstall)
}
}
|
mit
|
7e4910f95e3f6efb00cde97ac37c4c56
| 37.169118 | 99 | 0.663649 | 5.296939 | false | false | false | false |
lemberg/connfa-ios
|
Connfa/Stores/Firebase/InterestedFirebase.swift
|
1
|
4519
|
//
// InterestedFirebase.swift
// Connfa
//
// Created by Marian Fedyk on 1/2/18.
// Copyright © 2018 Lemberg Solution. All rights reserved.
//
import Foundation
import Firebase
import EventKit
class InterestedFirebase {
static let shared = InterestedFirebase()
private let eventStorage = EventStorage()
private init() {
fetchSnapshot {}
if let _ = UserFirebase.shared.ownPinId {
setupObservers()
} else {
NotificationCenter.default.addObserver(self, selector: #selector(self.setupObservers), name: .signedIn , object: nil)
}
}
typealias ErrorBlock = (_ error : FirebaseError?) -> ()
typealias CompletionBlock = () -> ()
typealias InterestedBlock = (_ isInterested: Bool, _ eventId: String) -> ()
private let ref = Database.database().reference().child(Keys.startDate)
private var interestedSnapshot: DataSnapshot?
private var interestedReference: DatabaseReference {
return ref.child(Keys.interested)
}
private var ownEventsSnapshot: DataSnapshot? {
if let pin = UserFirebase.shared.ownPin?.pinId {
return interestedSnapshot?.childSnapshot(forPath: pin)
} else {
return nil
}
}
@objc private func setupObservers() {
interestedReference.child(UserFirebase.shared.ownPinId!).observe(.childAdded) { (snapshot) in
let dict = [Keys.Event.eventId: snapshot.key]
self.fetchSnapshot {
NotificationCenter.default.post(name: .interestedAdded, object: nil, userInfo: dict)
NotificationCenter.default.post(name: .interestedChanged, object: nil, userInfo: dict)
}
}
interestedReference.child(UserFirebase.shared.ownPinId!).observe(.childRemoved) { (snapshot) in
let dict = [Keys.Event.eventId: snapshot.key]
self.fetchSnapshot {
NotificationCenter.default.post(name: .interestedRemoved, object: nil, userInfo: dict)
NotificationCenter.default.post(name: .interestedChanged, object: nil, userInfo: dict)
}
}
}
func requestInterested(eventId: String, _ block: @escaping InterestedBlock) {
DispatchQueue.global(qos: .userInitiated).async {
var isInterested = false
if let snapshot = self.ownEventsSnapshot {
isInterested = snapshot.hasChild(eventId)
}
DispatchQueue.main.async {
block(isInterested,eventId)
}
}
}
func contains(pinId: String, eventId: String) -> Bool {
return interestedSnapshot?.childSnapshot(forPath: pinId).hasChild(eventId) ?? false
}
func update(_ block: @escaping CompletionBlock) {
self.fetchSnapshot(block)
}
func isValid(_ id: String) -> Bool {
return id.count == 4 && id.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
func checkFriendIntersted(eventId: String, _ block: @escaping InterestedBlock) {
DispatchQueue.global(qos: .userInitiated).async {
var isInterested = false
if let pinsSnap = self.interestedSnapshot {
for pin in UserFirebase.shared.pins {
if pinsSnap.childSnapshot(forPath: pin.pinId).hasChild(eventId) && pin != UserFirebase.shared.ownPin {
isInterested = true
break
}
}
}
DispatchQueue.main.async {
block(isInterested,eventId)
}
}
}
func friendsInterestedInEvent(eventId: String) -> [String] {
if let pinsSnap = interestedSnapshot {
return UserFirebase.shared.pins
.filter{ pinsSnap.childSnapshot(forPath: $0.pinId).hasChild(eventId) && $0 != UserFirebase.shared.ownPin }
.map{ $0.actionTitle }
} else {
return []
}
}
func updateInterested(for eventId: String,_ block: @escaping ErrorBlock) {
guard let pin = UserFirebase.shared.ownPin?.pinId else {
block(.noPin)
return
}
let eventRef = interestedReference.child(pin).child(eventId)
requestInterested(eventId: eventId) { (isInterested, id) in
if id == eventId {
if isInterested {
eventRef.removeValue()
self.eventStorage.removeFromCalendarEvents(ids: [eventId])
} else {
eventRef.setValue(true)
self.eventStorage.addToCalendarEvents(ids: [eventId])
}
}
}
block(nil)
}
private func fetchSnapshot(_ block: @escaping CompletionBlock) {
interestedReference.observeSingleEvent(of: .value) { (snapshot) in
self.interestedSnapshot = snapshot
DispatchQueue.main.async {
block()
}
}
}
}
|
apache-2.0
|
ebd8954f739e393a0134dc4cc200da67
| 30.375 | 123 | 0.661797 | 4.250235 | false | false | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps
|
TheMovieManager-v1/TheMovieManager/FavoritesViewController.swift
|
1
|
2373
|
//
// FavoritesTableViewController.swift
// TheMovieManager
//
// Created by Jarrod Parkes on 2/26/15.
// Copyright (c) 2015 Jarrod Parkes. All rights reserved.
//
import UIKit
// MARK: - FavoritesViewController: UIViewController
class FavoritesViewController: UIViewController {
// MARK: Properties
var movies: [TMDBMovie] = [TMDBMovie]()
// MARK: Outlets
@IBOutlet weak var moviesTableView: UITableView!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// create and set the logout button
parentViewController!.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Reply, target: self, action: #selector(logout))
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
// MARK: Logout
func logout() {
dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: - FavoritesViewController: UITableViewDelegate, UITableViewDataSource
extension FavoritesViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/* Get cell type */
let cellReuseIdentifier = "FavoriteTableViewCell"
let movie = movies[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
/* Set cell defaults */
cell.textLabel!.text = movie.title
cell.imageView!.image = UIImage(named: "Film")
cell.imageView!.contentMode = UIViewContentMode.ScaleAspectFit
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let controller = storyboard!.instantiateViewControllerWithIdentifier("MovieDetailViewController") as! MovieDetailViewController
controller.movie = movies[indexPath.row]
navigationController!.pushViewController(controller, animated: true)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
}
|
mit
|
0636f170db1313fe771fa2db92a17aa4
| 30.653333 | 150 | 0.688158 | 5.787805 | false | false | false | false |
jegumhon/URWeatherView
|
Example/URExampleWeatherView/PageViewController.swift
|
1
|
2068
|
//
// PageViewController.swift
// URExampleWeatherView
//
// Created by DongSoo Lee on 2017. 5. 8..
// Copyright © 2017년 zigbang. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.dataSource = self
self.view.backgroundColor = #colorLiteral(red: 1, green: 0.5502320528, blue: 0, alpha: 1)
let initialVC = self.viewControllers(at: 0)
self.setViewControllers([initialVC], direction: UIPageViewController.NavigationDirection.forward, animated: true, completion: nil)
}
var backgroundColors: [UIColor] = [.red, .blue, .green, .yellow, .orange]
func viewControllers(at index: Int) -> UIViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "pageContent") as! PageContentViewController
vc.index = index
vc.view.backgroundColor = self.backgroundColors[index]
return vc
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return 5
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).index
if index == 0 {
return nil
}
index -= 1
return self.viewControllers(at: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).index
index += 1
if index == 5 {
return nil
}
return self.viewControllers(at: index)
}
}
|
mit
|
245cca66539775cd31106c72dcda00c6
| 29.820896 | 149 | 0.683777 | 5.1625 | false | false | false | false |
iOSDevLog/iOSDevLog
|
201. UI Test/Swift/ListerKit/ListDocument.swift
|
1
|
4762
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListDocument` class is a `UIDocument` subclass that represents a list. `ListDocument` manages the serialization / deserialization of the list object in addition to a list presenter.
*/
import UIKit
import WatchConnectivity
/// Protocol that allows a list document to notify other objects of it being deleted.
@objc public protocol ListDocumentDelegate {
func listDocumentWasDeleted(listDocument: ListDocument)
}
public class ListDocument: UIDocument {
// MARK: Properties
public weak var delegate: ListDocumentDelegate?
// Use a default, empty list.
public var listPresenter: ListPresenterType?
// MARK: Initializers
public init(fileURL URL: NSURL, listPresenter: ListPresenterType? = nil) {
self.listPresenter = listPresenter
super.init(fileURL: URL)
}
// MARK: Serialization / Deserialization
override public func loadFromContents(contents: AnyObject, ofType typeName: String?) throws {
if let unarchivedList = NSKeyedUnarchiver.unarchiveObjectWithData(contents as! NSData) as? List {
/*
This method is called on the queue that the `openWithCompletionHandler(_:)` method was called
on (typically, the main queue). List presenter operations are main queue only, so explicitly
call on the main queue.
*/
dispatch_async(dispatch_get_main_queue()) {
self.listPresenter?.setList(unarchivedList)
return
}
return
}
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: [
NSLocalizedDescriptionKey: NSLocalizedString("Could not read file", comment: "Read error description"),
NSLocalizedFailureReasonErrorKey: NSLocalizedString("File was in an invalid format", comment: "Read failure reason")
])
}
override public func contentsForType(typeName: String) throws -> AnyObject {
if let archiveableList = listPresenter?.archiveableList {
return NSKeyedArchiver.archivedDataWithRootObject(archiveableList)
}
throw NSError(domain: "ListDocumentDomain", code: -1, userInfo: [
NSLocalizedDescriptionKey: NSLocalizedString("Could not archive list", comment: "Archive error description"),
NSLocalizedFailureReasonErrorKey: NSLocalizedString("No list presenter was available for the document", comment: "Archive failure reason")
])
}
// MARK: Saving
override public func saveToURL(url: NSURL, forSaveOperation saveOperation: UIDocumentSaveOperation, completionHandler: ((Bool) -> Void)?) {
super.saveToURL(url, forSaveOperation: saveOperation) { success in
// On a successful save, transfer the file to the paired watch if appropriate.
if WCSession.isSupported() && WCSession.defaultSession().watchAppInstalled && success {
let fileCoordinator = NSFileCoordinator()
let readingIntent = NSFileAccessIntent.readingIntentWithURL(url, options: [])
fileCoordinator.coordinateAccessWithIntents([readingIntent], queue: NSOperationQueue()) { accessError in
if accessError != nil {
return
}
let session = WCSession.defaultSession()
for transfer in session.outstandingFileTransfers {
if transfer.file.fileURL == readingIntent.URL {
transfer.cancel()
break
}
}
session.transferFile(readingIntent.URL, metadata: nil)
}
}
completionHandler?(success)
}
}
// MARK: Deletion
override public func accommodatePresentedItemDeletionWithCompletionHandler(completionHandler: NSError? -> Void) {
super.accommodatePresentedItemDeletionWithCompletionHandler(completionHandler)
delegate?.listDocumentWasDeleted(self)
}
// MARK: Handoff
override public func updateUserActivityState(userActivity: NSUserActivity) {
super.updateUserActivityState(userActivity)
if let rawColorValue = listPresenter?.color.rawValue {
userActivity.addUserInfoEntriesFromDictionary([
AppConfiguration.UserActivity.listColorUserInfoKey: rawColorValue
])
}
}
}
|
mit
|
67634fbefbfd9a49bca790dcc48229f5
| 39.683761 | 190 | 0.637815 | 6.017699 | false | false | false | false |
achimk/Cars
|
CarsApp/Infrastructure/Cars/RestService/Tasks/ListCarsTask.swift
|
1
|
1154
|
//
// ListCarsTask.swift
// CarsApp
//
// Created by Joachim Kret on 01/08/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
import RxSwift
import ObjectMapper
final class ListCarsTask: BaseCarsTask<Void, Array<CarModelResponse>> {
typealias ContentResponse = Array<Dictionary<String, Any>>
override func perform(_ input: ()) -> Observable<Array<CarModelResponse>> {
let dispatcher = self.dispatcher
let recognizer: ((Any) throws -> ContentResponse) = { response in
if let content = response as? ContentResponse {
return content
}
throw RestCarsServiceError.invalidResponse
}
let mapper: ((ContentResponse) -> Array<CarModelResponse>) = { content in
return Mapper<CarModelResponse>().mapArray(JSONArray: content)
}
return createRequest(endpoint: .cars)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default))
.flatMap { dispatcher.execute($0) }
.map(recognizer)
.map(mapper)
.observeOn(MainScheduler.asyncInstance)
}
}
|
mit
|
47fafddfadec20fdf62dc48196804325
| 28.564103 | 81 | 0.641804 | 4.744856 | false | false | false | false |
yaslab/ZeroFormatter.swift
|
Sources/BinaryUtility.swift
|
1
|
15667
|
//
// BinaryUtility.swift
// ZeroFormatter
//
// Created by Yasuhiro Hatta on 2016/12/14.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
internal enum BinaryUtility {
// -------------------------------------------------------------------------
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Bool) -> Int {
return serialize(bytes, Int8(value ? 1 : 0))
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Int8) -> Int {
let byteSize = 1
var value = value
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int16) -> Int {
let byteSize = 2
var value = value.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int32) -> Int {
let byteSize = 4
var value = value.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int64) -> Int {
let byteSize = 8
var value = value.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: UInt8) -> Int {
let byteSize = 1
var value = value
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: UInt16) -> Int {
let byteSize = 2
var value = value.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: UInt32) -> Int {
let byteSize = 4
var value = value.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: UInt64) -> Int {
let byteSize = 8
var value = value.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Float) -> Int {
let byteSize = 4
var value = value.bitPattern.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Double) -> Int {
let byteSize = 8
var value = value.bitPattern.littleEndian
withUnsafePointer(to: &value) { bytes.append($0, length: byteSize) }
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Bool?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Int8?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int16?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int32?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int64?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: UInt8?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: UInt16?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: UInt32?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: UInt64?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Float?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
internal static func serialize(_ bytes: NSMutableData, _ value: Double?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
// MARK: -
internal static func serialize(_ bytes: NSMutableData, _ value: Int) -> Int {
return serialize(bytes, Int32(value))
}
internal static func serialize(_ bytes: NSMutableData, _ value: Int?) -> Int {
var byteSize = 0
if let value = value {
byteSize += serialize(bytes, true)
byteSize += serialize(bytes, value)
} else {
byteSize += serialize(bytes, false)
}
return byteSize
}
// MARK: - Int (offset)
internal static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Int) -> Int {
assert(bytes.length >= (offset + 4))
let byteSize = 4
let value = Int32(value).littleEndian
(bytes.mutableBytes + offset).assumingMemoryBound(to: Int32.self)[0] = value
return byteSize
}
// -------------------------------------------------------------------------
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Bool {
let value: Int8 = deserialize(bytes, offset, &byteSize)
return (value != 0)
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int8 {
byteSize += 1
return (bytes.bytes + offset).assumingMemoryBound(to: Int8.self)[0]
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int16 {
byteSize += 2
return (bytes.bytes + offset).assumingMemoryBound(to: Int16.self)[0].littleEndian
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int32 {
byteSize += 4
return (bytes.bytes + offset).assumingMemoryBound(to: Int32.self)[0].littleEndian
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int64 {
byteSize += 8
return (bytes.bytes + offset).assumingMemoryBound(to: Int64.self)[0].littleEndian
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt8 {
byteSize += 1
return (bytes.bytes + offset).assumingMemoryBound(to: UInt8.self)[0]
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt16 {
byteSize += 2
return (bytes.bytes + offset).assumingMemoryBound(to: UInt16.self)[0].littleEndian
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt32 {
byteSize += 4
return (bytes.bytes + offset).assumingMemoryBound(to: UInt32.self)[0].littleEndian
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt64 {
byteSize += 8
return (bytes.bytes + offset).assumingMemoryBound(to: UInt64.self)[0].littleEndian
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Float {
let value: UInt32 = deserialize(bytes, offset, &byteSize)
return Float(bitPattern: value.littleEndian)
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Double {
let value: UInt64 = deserialize(bytes, offset, &byteSize)
return Double(bitPattern: value.littleEndian)
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Bool? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int8? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Int8 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int16? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Int16 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int32? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Int32 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int64? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Int64 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt8? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: UInt8 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt16? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: UInt16 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt32? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: UInt32 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> UInt64? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: UInt64 = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Float? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Float = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Double? {
let start = byteSize
let hasValue: Bool = deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: Double = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
// MARK: -
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int {
let value: Int32 = deserialize(bytes, offset, &byteSize)
return Int(value)
}
internal static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Int? {
let value: Int32? = deserialize(bytes, offset, &byteSize)
if let value = value {
return Int(value)
} else {
return nil
}
}
}
|
mit
|
6c1be421426505ec1cb2b2b065c17875
| 32.909091 | 104 | 0.562045 | 4.670841 | false | false | false | false |
tombuildsstuff/swiftcity
|
SwiftCity/Entities/VCSRevisions.swift
|
1
|
835
|
public struct VCSRevisions {
public let count: Int
public let revisions: [VCSRevision]?
init?(dictionary: [String: AnyObject]) {
guard let count = dictionary["count"] as? Int else {
return nil
}
self.count = count
if let revisionsDictionary = dictionary["revision"] as? [[String: AnyObject]] {
self.revisions = revisionsDictionary.map({ (dictionary: [String : AnyObject]) -> VCSRevision? in
return VCSRevision(dictionary: dictionary)
}).filter({ (revision:VCSRevision?) -> Bool in
return revision != nil
}).map({ (revision: VCSRevision?) -> VCSRevision in
return revision!
})
}
else {
self.revisions = nil
}
}
}
|
mit
|
babcb36bf47e2496d600be88ce3a9f52
| 31.153846 | 108 | 0.532934 | 4.970238 | false | false | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/WelcomeAnimationViewController.swift
|
4
|
1063
|
import UIKit
final class WelcomeAnimationViewController: UIViewController {
private var completedAnimation = false
let animationView: WelcomeAnimationView
private let waitsForAnimationTrigger: Bool
init(animationView: WelcomeAnimationView, waitsForAnimationTrigger: Bool = true) {
self.animationView = animationView
self.waitsForAnimationTrigger = waitsForAnimationTrigger
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.wmf_addSubviewWithConstraintsToEdges(animationView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard !waitsForAnimationTrigger else {
return
}
animate()
}
func animate() {
guard !completedAnimation else {
return
}
animationView.animate()
completedAnimation = true
}
}
|
mit
|
1ee0df1ef8931a97e5fb4d906421d6d2
| 26.973684 | 86 | 0.668862 | 5.507772 | false | false | false | false |
kubusma/JMWeatherApp
|
JMWeatherApp/DataSources/ForecastDataSource.swift
|
1
|
3004
|
//
// ForecastDataSource.swift
// JMWeatherApp
//
// Created by Jakub Matuła on 05/10/2017.
// Copyright © 2017 Jakub Matuła. All rights reserved.
//
import Foundation
import UIKit
class ForecastDataSourceAndDelegate: NSObject {
private var forecast: [Weather]?
var weather: Weather
private let weatherService: WeatherService!
weak private var tableView: UITableView!
init(tableView: UITableView, weather: Weather, weatherService: WeatherService) {
self.tableView = tableView
self.weather = weather
self.weatherService = weatherService
super.init()
weatherService.fetch12HourForecast(forLocation: weather.location) { [weak self] forecast in
self?.forecast = forecast
DispatchQueue.main.async {
guard let strongSelf = self else { return }
if let forecast = forecast, forecast.isEmpty {
let noItemsLabel = strongSelf.noItemsLabel(text: "Fetching forecast unsuccesful")
noItemsLabel.center = strongSelf.tableView.center
self?.tableView.backgroundView = noItemsLabel
}
self?.tableView.reloadData()
}
}
}
private func noItemsLabel(text: String) -> UILabel {
let noItemsLabel = UILabel(frame: .zero)
noItemsLabel.text = text
noItemsLabel.font = UIFont(name: noItemsLabel.font.fontName, size: 25)
noItemsLabel.numberOfLines = 0
noItemsLabel.sizeToFit()
noItemsLabel.textAlignment = .center
return noItemsLabel
}
}
//MARK:- UITableViewDataSource
extension ForecastDataSourceAndDelegate: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forecast?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cells.forecast.identifier, for: indexPath) as! HourlyForecastTableViewCell
let cellViewModel = SimpleWeatherViewModel(weather: forecast![indexPath.row],
tempratureColorProvider: BasicTemperatureColorProvider(),
dateFormatter: DateFormatter.shortDateFormatter)
cell.viewModel = cellViewModel
return cell
}
}
//MARK:- UITableViewDelegate
extension ForecastDataSourceAndDelegate: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? HourlyForecastTableViewCell
else { return }
weatherService.fetchWeatherIcon(weather: forecast?[indexPath.row]) { [weak cell] iconImage in
DispatchQueue.main.async {
cell?.icon = iconImage
}
}
}
}
|
mit
|
e45c68ce211a085f65865e9cba5165bf
| 36.5125 | 139 | 0.645452 | 5.320922 | false | false | false | false |
MukeshKumarS/Swift
|
test/SILGen/sil_locations.swift
|
1
|
12454
|
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | FileCheck %s
// FIXME: Not sure if this an ideal source info for the branch -
// it points to if, not the last instruction in the block.
func ifexpr() -> Int {
var x : Int = 0;
if true {
x++;
}
return x;
// CHECK-LABEL: sil hidden @_TF13sil_locations6ifexprFT_Si
// CHECK: apply {{.*}} line:[[@LINE-5]]:6
// CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]] // {{.*}} line:[[@LINE-6]]:6
// CHECK: br [[FALSE_BB]] // {{.*}} line:[[@LINE-5]]:3
// CHECK: return {{.*}} // {{.*}} line:[[@LINE-5]]:3:return
}
func ifelseexpr() -> Int {
var x : Int = 0;
if true {
x++;
} else {
x--;
}
return x;
// CHECK-LABEL: sil hidden @_TF13sil_locations10ifelseexprFT_Si
// CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]] // {{.*}} line:[[@LINE-7]]:6
// CHECK: [[TRUE_BB]]:
// CHECK: br bb{{[0-9]+}} // {{.*}} line:[[@LINE-7]]:3
// CHECK: [[FALSE_BB]]:
// CHECK: br bb{{[0-9]+}} // {{.*}} line:[[@LINE-7]]:3
// CHECK: return {{.*}} // {{.*}} line:[[@LINE-7]]:3:return
}
// The source locations are handled differently here - since
// the return is unified, we keep the location of the return(not the if)
// in the branch.
func ifexpr_return() -> Int {
if true {
return 5;
}
return 6;
// CHECK-LABEL: sil hidden @_TF13sil_locations13ifexpr_returnFT_Si
// CHECK: apply {{.*}} line:[[@LINE-5]]:6
// CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]] // {{.*}} line:[[@LINE-6]]:6
// CHECK: [[TRUE_BB]]:
// CHECK: br bb{{[0-9]+}}({{%.*}}) // {{.*}} line:[[@LINE-7]]:5:return
// CHECK: [[FALSE_BB]]:
// CHECK: br bb{{[0-9]+}}({{%.*}}) // {{.*}} line:[[@LINE-7]]:3:return
// CHECK: return {{.*}} // {{.*}} line:[[@LINE+1]]:1:cleanup
}
func ifexpr_rval() -> Int {
var x = true ? 5 : 6;
return x;
// CHECK-LABEL: sil hidden @_TF13sil_locations11ifexpr_rvalFT_Si
// CHECK: apply {{.*}} line:[[@LINE-3]]:11
// CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]] // {{.*}} line:[[@LINE-4]]:11
// CHECK: [[TRUE_BB]]:
// CHECK: br bb{{[0-9]+}}({{%.*}}) // {{.*}} line:[[@LINE-6]]:18
// CHECK: [[FALSE_BB]]:
// CHECK: br bb{{[0-9]+}}({{%.*}}) // {{.*}} line:[[@LINE-8]]:22
}
// TODO: missing info on the first branch.
func forstmt_empty_cond(i: Int) -> Int {
for var i=0;;++i {}
// CHECK-LABEL: sil hidden @{{.*}}forstmt_empty_cond{{.*}}
// CHECK: apply {{.*}} line:[[@LINE-2]]:13
// CHECK: br [[TRUE_BB:bb[0-9]+]]
// CHECK: [[TRUE_BB:bb[0-9]+]]:
// CHECK: br [[TRUE_BB:bb[0-9]+]] // {{.*}} line:[[@LINE-5]]:21
}
// --- Test function calls.
func simpleDirectCallTest(i: Int) -> Int {
return simpleDirectCallTest(i)
// CHECK-LABEL: sil hidden @_TF13sil_locations20simpleDirectCallTest
// CHECK: function_ref @_TF13sil_locations20simpleDirectCallTest{{.*}} line:[[@LINE-2]]:10
// CHECK: {{%.*}} apply {{%.*}} line:[[@LINE-3]]:10
}
func templateTest<T>(value: T) -> T {
return value
}
func useTemplateTest() -> Int {
return templateTest(5);
// CHECK-LABEL: sil hidden @_TF13sil_locations15useTemplateTestFT_Si
// CHECK: function_ref @_TFSiC{{.*}} line:87
}
func foo(x: Int) -> Int {
func bar(y: Int) -> Int {
return x + y
}
return bar(1)
// CHECK-LABEL: sil hidden @_TF13sil_locations3foo
// CHECK: [[CLOSURE:%[0-9]+]] = function_ref {{.*}} line:[[@LINE-2]]:10
// CHECK: apply [[CLOSURE:%[0-9]+]]
}
class LocationClass {
func mem() {}
}
func testMethodCall() {
var l: LocationClass;
l.mem();
// CHECK-LABEL: sil hidden @_TF13sil_locations14testMethodCallFT_T_
// CHECK: class_method {{.[0-9]+}} : $LocationClass, #LocationClass.mem!1 {{.*}} line:[[@LINE-3]]:5
}
func multipleReturnsImplicitAndExplicit() {
var x = 5+3;
if x > 10 {
return;
}
x++;
// CHECK-LABEL: sil hidden @_TF13sil_locations34multipleReturnsImplicitAndExplicitFT_T_
// CHECK: cond_br
// CHECK: br bb{{[0-9]+}} // {{.*}} line:[[@LINE-5]]:5:return
// CHECK: br bb{{[0-9]+}} // {{.*}} line:[[@LINE+2]]:1:imp_return
// CHECK: return {{.*}} // {{.*}} line:[[@LINE+1]]:1:cleanup
}
func simplifiedImplicitReturn() -> () {
var y = 0
// CHECK-LABEL: sil hidden @_TF13sil_locations24simplifiedImplicitReturnFT_T_
// CHECK: return {{.*}} // {{.*}} line:[[@LINE+1]]:1:imp_return
}
func switchfoo() -> Int { return 0 }
func switchbar() -> Int { return 0 }
// CHECK-LABEL: sil hidden @_TF13sil_locations10testSwitchFT_T_
func testSwitch() {
var x:Int
x = 0
switch (switchfoo(), switchbar()) {
// CHECK: store {{.*}} // {{.*}} line:[[@LINE+1]]
case (1,2):
// CHECK: integer_literal $Builtin.Int2048, 2 // {{.*}} line:[[@LINE-1]]:11
// FIXME: Location info is missing.
// CHECK: cond_br
//
var z: Int = 200
// CHECK: [[VAR_Z:%[0-9]+]] = alloc_box $Int, var, name "z"{{.*}}line:[[@LINE-1]]:9
// CHECK: integer_literal $Builtin.Int2048, 200 // {{.*}} line:[[@LINE-2]]:18
x = z
// CHECK: strong_release [[VAR_Z]]{{.*}} // {{.*}} line:[[@LINE-1]]:9:cleanup
case (3, let y):
x += 1
}
}
func testIf() {
if true {
var y:Int;
} else {
var x:Int;
}
// CHECK-LABEL: sil hidden @_TF13sil_locations6testIfFT_T_
//
// FIXME: Missing location info here.
// CHECK: function_ref
// CHECK: apply
//
//
//
// CHECK: br {{.*}} // {{.*}} line:[[@LINE-13]]:6
}
func testFor() {
for (var i:Int = 0; i<10; i++) {
var y: Int = 300;
y++;
if true {
break;
}
y--;
continue;
}
// CHECK-LABEL: sil hidden @_TF13sil_locations7testForFT_T_
// CHECK: [[VAR_Y_IN_FOR:%[0-9]+]] = alloc_box $Int, var, name "y" // {{.*}} line:[[@LINE-10]]:9
// CHECK: integer_literal $Builtin.Int2048, 300 // {{.*}} line:[[@LINE-11]]:18
// CHECK: strong_release [[VAR_Y_IN_FOR]]#0 : $@box Int
// CHECK: br bb{{.*}} // {{.*}} line:[[@LINE-10]]:7
// CHECK: strong_release [[VAR_Y_IN_FOR]]#0 : $@box Int
// CHECK: br bb{{.*}} // {{.*}} line:[[@LINE-9]]:5
}
func testTuples() {
var t = (2,3)
var tt = (2, (4,5))
var d = "foo"
// CHECK-LABEL: sil hidden @_TF13sil_locations10testTuplesFT_T_
// CHECK: tuple_element_addr {{.*}} line:[[@LINE-6]]:11
// CHECK: integer_literal $Builtin.Int2048, 2 {{.*}} line:[[@LINE-7]]:12
// CHECK: integer_literal $Builtin.Int2048, 3 {{.*}} line:[[@LINE-8]]:14
// CHECK: tuple_element_addr {{.*}} line:[[@LINE-8]]:12
// CHECK: tuple_element_addr {{.*}} line:[[@LINE-9]]:16
}
// Test tuple imploding/exploding.
protocol Ordinable {
func ord() -> Int
}
func b<T : Ordinable>(seq: T) -> (Int) -> Int {
return {i in i + seq.ord() }
}
func captures_tuple<T, U>(x: (T, U)) -> () -> (T, U) {
return {x}
// CHECK-LABEL: sil hidden @_TF13sil_locations14captures_tuple
// CHECK: tuple_element_addr {{.*}} line:[[@LINE-5]]:27
// CHECK: copy_addr [take] {{.*}} line:[[@LINE-6]]:27
// CHECK: function_ref {{.*}} line:[[@LINE-6]]:10
// CHECK-LABEL: sil shared @_TFF13sil_locations14captures_tuple
// CHECK: copy_addr {{.*}} line:[[@LINE-10]]:11
}
func interpolated_string(x: Int, y: String) -> String {
return "The \(x) Million Dollar \(y)"
// CHECK-LABEL: sil hidden @_TF13sil_locations19interpolated_string
// CHECK: retain_value{{.*}} {{.*}} line:[[@LINE-5]]:37
}
func int(x: Int) {}
func tuple() -> (Int, Float) { return (1, 1.0) }
func tuple_element(x: (Int, Float)) {
int(tuple().0)
// CHECK-LABEL: sil hidden @_TF13sil_locations13tuple_element
// CHECK: apply {{.*}} line:[[@LINE-3]]:7
// CHECK: tuple_extract{{.*}}, 0 {{.*}} line:[[@LINE-4]]:7
// CHECK: tuple_extract{{.*}}, 1 {{.*}} line:[[@LINE-5]]:7
// CHECK: apply {{.*}} line:[[@LINE-6]]:3
}
func containers() -> ([Int], Dictionary<String, Int>) {
return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3])
// CHECK-LABEL: sil hidden @_TF13sil_locations10containers
// CHECK: apply {{%.*}}<(String, Int)>({{%.*}}) {{.*}} line:[[@LINE-2]]:22
// CHECK: string_literal utf8 "Ankeny" {{.*}} line:[[@LINE-4]]:23
// CHECK: integer_literal $Builtin.Int2048, 1 {{.*}} line:[[@LINE-6]]:33
// CHECK: integer_literal $Builtin.Int2048, 2 {{.*}} line:[[@LINE-7]]:48
}
func a() {}
func b() -> Int { return 0 }
protocol P { func p() }
struct X : P { func p() {} }
func test_isa_2(p: P) {
switch (p, b()) {
case (is X, b()):
a()
case _:
a()
}
// CHECK-LABEL: sil hidden @_TF13sil_locations10test_isa_2
// CHECK: alloc_stack $(P, Int) {{.*}} line:[[@LINE-10]]:10
// CHECK: tuple_element_addr{{.*}} $*(P, Int), 0 {{.*}} line:[[@LINE-11]]:10
// CHECK: tuple_element_addr{{.*}} $*(P, Int), 1 {{.*}} line:[[@LINE-12]]:10
// CHECK: load {{.*}} line:[[@LINE-12]]:8
//
// CHECK: checked_cast_addr_br {{.*}} line:[[@LINE-14]]:9
// CHECK: load {{.*}} line:[[@LINE-15]]:9
}
func runcibleWhy() {}
protocol Runcible {
func runce()
}
enum SinglePayloadAddressOnly {
case x(Runcible)
case y
}
func printSinglePayloadAddressOnly(v:SinglePayloadAddressOnly) {
switch v {
case .x(let runcible):
runcible.runce()
case .y:
runcibleWhy()
}
// CHECK_LABEL: sil hidden @_TF13sil_locations29printSinglePayloadAddressOnly
// CHECK: bb0
// CHECK: switch_enum_addr {{.*}} [[FALSE_BB:bb[0-9]+]] // {{.*}} line:[[@LINE-10]]:3
// CHECK: [[FALSE_BB]]:
}
func testStringForEachStmt() {
var i = 0;
for index in 1..<20 {
i += 1
if i == 15 {
break
}
}
// CHECK-LABEL: sil hidden @_TF13sil_locations21testStringForEachStmtFT_T_
// CHECK: br {{.*}} line:[[@LINE-8]]:3
// CHECK: cond_br {{.*}} line:[[@LINE-9]]:3
// CHECK: cond_br {{.*}} line:[[@LINE-8]]:8
// Break branch:
// CHECK: br {{.*}} line:[[@LINE-9]]:7
// Looping back branch:
// CHECK: br {{.*}} line:[[@LINE-9]]:3
// Condition is false branch:
// CHECK: br {{.*}} line:[[@LINE-16]]:3
}
func testForStmt() {
var i = 0;
var m = 0;
for (i = 0; i < 10; ++i) {
m += 1
if m == 15 {
break
} else {
continue
}
}
// CHECK-LABEL: sil hidden @_TF13sil_locations11testForStmtFT_T_
// CHECK: br {{.*}} line:[[@LINE-12]]:3
// CHECK: cond_br {{.*}} line:[[@LINE-13]]:15
// CHECK: cond_br {{.*}} line:[[@LINE-12]]:8
// Break branch:
// CHECK: br {{.*}} line:[[@LINE-13]]:7
// Continue branch:
// CHECK: br {{.*}} line:[[@LINE-13]]:7
// Looping back branch:
// CHECK: br {{.*}} line:[[@LINE-12]]:3
// Condition is false branch:
// CHECK: br {{.*}} line:[[@LINE-22]]:3
}
func testRepeatWhile() {
var m = 0;
repeat {
m += 1
} while (m < 200)
// CHECK-LABEL: sil hidden @_TF13sil_locations15testRepeatWhileFT_T_
// CHECK: br {{.*}} line:[[@LINE-6]]:3
// CHECK: cond_br {{.*}} line:[[@LINE-5]]:11
// Loop back branch:
// CHECK: br {{.*}} line:[[@LINE-7]]:11
}
func testWhile() {
var m = 0;
while m < 100 {
m += 1
if m > 5 {
break
}
m += 1
}
// CHECK-LABEL: sil hidden @_TF13sil_locations9testWhileFT_T_
// CHECK: br {{.*}} line:[[@LINE-9]]:3
// While loop conditional branch:
// CHECK: cond_br {{.*}} line:[[@LINE-11]]:9
// If stmt condition branch:
// CHECK: cond_br {{.*}} line:[[@LINE-11]]:8
// Break branch:
// CHECK: br {{.*}} line:[[@LINE-12]]:7
// Looping back branch:
// CHECK: br {{.*}} line:[[@LINE-11]]:3
}
|
apache-2.0
|
5c5906264390cafbecfd0bf6375f489a
| 28.581948 | 103 | 0.492051 | 3.371413 | false | true | false | false |
mpclarkson/vapor
|
Sources/Vapor/View/View.swift
|
1
|
1885
|
/**
Loads and renders a file from the `Resources` folder
in the Application's work directory.
*/
public class View {
///Currently applied RenderDrivers
public static var renderers: [String: RenderDriver] = [:]
var data: Data
enum Error: ErrorProtocol {
case InvalidPath
}
/**
Attempt to load and render a file
from the supplied path using the contextual
information supplied.
- context Passed to RenderDrivers
*/
public init(application: Application, path: String, context: [String: Any] = [:]) throws {
let filesPath = application.workDir + "Resources/Views/" + path
guard let fileBody = try? FileManager.readBytesFromFile(filesPath) else {
self.data = Data()
Log.error("No view found in path: \(filesPath)")
throw Error.InvalidPath
}
self.data = Data(fileBody)
for (suffix, renderer) in View.renderers {
if path.hasSuffix(suffix) {
let template = try String(data: data)
let rendered = try renderer.render(template: template, context: context)
self.data = rendered.data
}
}
}
}
///Allows Views to be returned in Vapor closures
extension View: ResponseRepresentable {
public func makeResponse() -> Response {
return Response(status: .ok, headers: [
"Content-Type": "text/html"
], body: data)
}
}
///Adds convenience method to Application to create a view
extension Application {
/**
Views directory relative to Application.resourcesDir
*/
public var viewsDir: String {
return resourcesDir + "Views/"
}
public func view(path: String, context: [String: Any] = [:]) throws -> View {
return try View(application: self, path: path, context: context)
}
}
|
mit
|
b9681364abed543ee5dbdd864bdf1b13
| 27.560606 | 94 | 0.611671 | 4.542169 | false | false | false | false |
mshhmzh/firefox-ios
|
Client/Frontend/Browser/URLBarView.swift
|
1
|
36054
|
/* 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 UIKit
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
struct URLBarViewUX {
static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
static let URLBarCurveOffsetLeft: CGFloat = -10
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let ProgressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.borderColor = UIConstants.PrivateModeLocationBorderColor
theme.activeBorderColor = UIConstants.PrivateModePurple
theme.tintColor = UIConstants.PrivateModePurple
theme.textColor = UIColor.whiteColor()
theme.buttonTintColor = UIConstants.PrivateModeActionButtonTintColor
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.borderColor = TextFieldBorderColor
theme.activeBorderColor = TextFieldActiveBorderColor
theme.tintColor = ProgressTintColor
theme.textColor = UIColor.blackColor()
theme.buttonTintColor = UIColor.darkGrayColor()
themes[Theme.NormalMode] = theme
return themes
}()
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidEnterOverlayMode(urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
func urlBarDisplayTextForURL(url: NSURL?) -> String?
}
class URLBarView: UIView {
// Additional UIAppearance-configurable properties
dynamic var locationBorderColor: UIColor = URLBarViewUX.TextFieldBorderColor {
didSet {
if !inOverlayMode {
locationContainer.layer.borderColor = locationBorderColor.CGColor
}
}
}
dynamic var locationActiveBorderColor: UIColor = URLBarViewUX.TextFieldActiveBorderColor {
didSet {
if inOverlayMode {
locationContainer.layer.borderColor = locationActiveBorderColor.CGColor
}
}
}
weak var delegate: URLBarDelegate?
weak var tabToolbarDelegate: TabToolbarDelegate?
var helper: TabToolbarHelper?
var isTransitioning: Bool = false {
didSet {
if isTransitioning {
// Cancel any pending/in-progress animations related to the progress bar
self.progressBar.setProgress(1, animated: false)
self.progressBar.alpha = 0.0
}
}
}
private var currentTheme: String = Theme.NormalMode
var toolbarIsShowing = false
var topTabsIsShowing = false {
didSet {
curveShape.hidden = topTabsIsShowing
}
}
private var locationTextField: ToolbarTextField?
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
lazy var locationView: TabLocationView = {
let locationView = TabLocationView()
locationView.translatesAutoresizingMaskIntoConstraints = false
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
return locationView
}()
private lazy var locationContainer: UIView = {
let locationContainer = UIView()
locationContainer.translatesAutoresizingMaskIntoConstraints = false
// Enable clipping to apply the rounded edges to subviews.
locationContainer.clipsToBounds = true
locationContainer.layer.borderColor = self.locationBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
return locationContainer
}()
private lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.addTarget(self, action: #selector(URLBarView.SELdidClickAddTab), forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityIdentifier = "URLBarView.tabsButton"
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.progressTintColor = URLBarViewUX.ProgressTintColor
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Label for Cancel button")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultChromeFont
cancelButton.addTarget(self, action: #selector(URLBarView.SELdidClickCancel), forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.alpha = 0
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(URLBarView.SELtappedScrollToTopArea), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var menuButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var homePageButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return AppConstants.MOZ_MENU ? [self.shareButton, self.menuButton, self.forwardButton, self.backButton, self.stopReloadButton, self.homePageButton] : [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape)
addSubview(scrollToTopButton)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
if AppConstants.MOZ_MENU {
addSubview(menuButton)
addSubview(homePageButton)
} else {
addSubview(bookmarkButton)
}
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
locationContainer.addSubview(locationView)
addSubview(locationContainer)
helper = TabToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
backButton.snp_makeConstraints { make in
make.left.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.snp_makeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
stopReloadButton.snp_makeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
if AppConstants.MOZ_MENU {
shareButton.snp_makeConstraints { make in
make.right.equalTo(self.menuButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
homePageButton.snp_makeConstraints { make in
make.center.equalTo(shareButton)
make.size.equalTo(shareButton)
}
menuButton.snp_makeConstraints { make in
make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
} else {
shareButton.snp_makeConstraints { make in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
bookmarkButton.snp_makeConstraints { make in
make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
}
}
override func updateConstraints() {
super.updateConstraints()
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
if (topTabsIsShowing) {
tabsButton.snp_remakeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.leading.equalTo(self.snp_trailing)
make.size.equalTo(UIConstants.ToolbarHeight)
}
}
else {
tabsButton.snp_remakeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
}
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.leading.equalTo(self.stopReloadButton.snp_trailing)
make.trailing.equalTo(self.shareButton.snp_leading)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
func createLocationTextField() {
guard locationTextField == nil else { return }
locationTextField = ToolbarTextField()
guard let locationTextField = locationTextField else { return }
locationTextField.translatesAutoresizingMaskIntoConstraints = false
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = UIKeyboardType.WebSearch
locationTextField.autocorrectionType = UITextAutocorrectionType.No
locationTextField.autocapitalizationType = UITextAutocapitalizationType.None
locationTextField.returnKeyType = UIReturnKeyType.Go
locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
locationTextField.font = UIConstants.DefaultChromeFont
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
locationContainer.addSubview(locationTextField)
locationTextField.snp_makeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
locationTextField.applyTheme(currentTheme)
}
func removeLocationTextField() {
locationTextField?.removeFromSuperview()
locationTextField = nil
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
// when we transition from portrait to landscape, calling this here causes
// the constraints to be calculated too early and there are constraint errors
if !toolbarIsShowing {
updateConstraintsIfNeeded()
}
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
self.actionButtons.forEach { $0.alpha = alpha }
}
func updateTabCount(count: Int, animated: Bool = true) {
self.tabsButton.updateTabCount(count, animated: animated)
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: !isTransitioning)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { finished in
if finished {
self.progressBar.setProgress(0.0, animated: false)
}
})
} else {
if self.progressBar.alpha < 1.0 {
self.progressBar.alpha = 1.0
}
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress) && !isTransitioning)
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationTextField?.setAutocompleteSuggestion(suggestion)
}
func enterOverlayMode(locationText: String?, pasted: Bool) {
createLocationTextField()
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(overlayMode: true)
delegate?.urlBarDidEnterOverlayMode(self)
// Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens
// won't take the initial frame of the label into consideration, which makes the label
// look squished at the start of the animation and expand to be correct. As a workaround,
// we becomeFirstResponder as the next event on UI thread, so the animation starts before we
// set a first responder.
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
self.locationTextField?.text = ""
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField?.becomeFirstResponder()
self.locationTextField?.text = locationText
}
} else {
// Copy the current URL to the editable text field, then activate it.
self.locationTextField?.text = locationText
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField?.becomeFirstResponder()
}
}
}
func leaveOverlayMode(didCancel cancel: Bool = false) {
locationTextField?.resignFirstResponder()
animateToOverlayState(overlayMode: false, didCancel: cancel)
delegate?.urlBarDidLeaveOverlayMode(self)
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.bringSubviewToFront(self.locationContainer)
self.cancelButton.hidden = false
self.progressBar.hidden = false
if AppConstants.MOZ_MENU {
self.menuButton.hidden = !self.toolbarIsShowing
} else {
self.bookmarkButton.hidden = !self.toolbarIsShowing
}
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
}
func transitionToOverlay(didCancel: Bool = false) {
self.cancelButton.alpha = inOverlayMode ? 1 : 0
self.progressBar.alpha = inOverlayMode || didCancel ? 0 : 1
self.shareButton.alpha = inOverlayMode ? 0 : 1
if AppConstants.MOZ_MENU {
self.menuButton.alpha = inOverlayMode ? 0 : 1
} else {
self.bookmarkButton.alpha = inOverlayMode ? 0 : 1
}
self.forwardButton.alpha = inOverlayMode ? 0 : 1
self.backButton.alpha = inOverlayMode ? 0 : 1
self.stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? locationActiveBorderColor : locationBorderColor
locationContainer.layer.borderColor = borderColor.CGColor
if inOverlayMode {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
self.locationTextField?.snp_remakeConstraints { make in
make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset)
make.top.bottom.trailing.equalTo(self.locationContainer)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
// Shrink the editable text field back to the size of the location view before hiding it.
self.locationTextField?.snp_remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
self.cancelButton.hidden = !inOverlayMode
self.progressBar.hidden = inOverlayMode
if AppConstants.MOZ_MENU {
self.menuButton.hidden = !self.toolbarIsShowing || inOverlayMode
} else {
self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode
}
self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.tabsButton.hidden = self.topTabsIsShowing
}
func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
if !overlay {
removeLocationTextField()
}
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { _ in
self.transitionToOverlay(cancel)
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
leaveOverlayMode(didCancel: true)
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: TabToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
helper?.updateReloadStatus(isLoading)
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(isWebPage isWebPage: Bool) {
if !AppConstants.MOZ_MENU {
bookmarkButton.enabled = isWebPage
}
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]? {
get {
if inOverlayMode {
guard let locationTextField = locationTextField else { return nil }
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return AppConstants.MOZ_MENU ? [backButton, forwardButton, stopReloadButton, locationView, shareButton, menuButton, tabsButton, progressBar] : [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: TabLocationViewDelegate {
func tabLocationViewDidLongPressReaderMode(tabLocationView: TabLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func tabLocationViewDidTapLocation(tabLocationView: TabLocationView) {
let locationText = delegate?.urlBarDisplayTextForURL(locationView.url)
enterOverlayMode(locationText, pasted: false)
}
func tabLocationViewDidLongPressLocation(tabLocationView: TabLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func tabLocationViewDidTapReload(tabLocationView: TabLocationView) {
delegate?.urlBarDidPressReload(self)
}
func tabLocationViewDidTapStop(tabLocationView: TabLocationView) {
delegate?.urlBarDidPressStop(self)
}
func tabLocationViewDidTapReaderMode(tabLocationView: TabLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func tabLocationViewLocationAccessibilityActions(tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
guard let text = locationTextField?.text else { return true }
delegate?.urlBar(self, didSubmitText: text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
// MARK: UIAppearance
extension URLBarView {
dynamic var progressBarTint: UIColor? {
get { return progressBar.progressTintColor }
set { progressBar.progressTintColor = newValue }
}
dynamic var cancelTextColor: UIColor? {
get { return cancelButton.titleColorForState(UIControlState.Normal) }
set { return cancelButton.setTitleColor(newValue, forState: UIControlState.Normal) }
}
dynamic var actionButtonTintColor: UIColor? {
get { return helper?.buttonTintColor }
set {
guard let value = newValue else { return }
helper?.buttonTintColor = value
}
}
}
extension URLBarView: Themeable {
func applyTheme(themeName: String) {
locationView.applyTheme(themeName)
locationTextField?.applyTheme(themeName)
guard let theme = URLBarViewUX.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
currentTheme = themeName
locationBorderColor = theme.borderColor!
locationActiveBorderColor = theme.activeBorderColor!
progressBarTint = theme.tintColor
cancelTextColor = theme.textColor
actionButtonTintColor = theme.buttonTintColor
tabsButton.applyTheme(themeName)
}
}
extension URLBarView: AppStateDelegate {
func appDidUpdateState(appState: AppState) {
if toolbarIsShowing {
let showShareButton = HomePageAccessors.isButtonInMenu(appState)
homePageButton.hidden = showShareButton
shareButton.hidden = !showShareButton
homePageButton.enabled = HomePageAccessors.isButtonEnabled(appState)
} else {
homePageButton.hidden = true
shareButton.hidden = true
}
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
let from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextRestoreGState(context)
}
}
class ToolbarTextField: AutocompleteTextField {
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.backgroundColor = UIConstants.PrivateModeLocationBackgroundColor
theme.textColor = UIColor.whiteColor()
theme.buttonTintColor = UIColor.whiteColor()
theme.highlightColor = UIConstants.PrivateModeTextHighlightColor
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.backgroundColor = UIColor.whiteColor()
theme.textColor = UIColor.blackColor()
theme.highlightColor = AutocompleteTextFieldUX.HighlightColor
themes[Theme.NormalMode] = theme
return themes
}()
dynamic var clearButtonTintColor: UIColor? {
didSet {
// Clear previous tinted image that's cache and ask for a relayout
tintedClearImage = nil
setNeedsLayout()
}
}
private var tintedClearImage: UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// Since we're unable to change the tint color of the clear image, we need to iterate through the
// subviews, find the clear button, and tint it ourselves. Thanks to Mikael Hellman for the tip:
// http://stackoverflow.com/questions/27944781/how-to-change-the-tint-color-of-the-clear-button-on-a-uitextfield
for view in subviews as [UIView] {
if let button = view as? UIButton {
if let image = button.imageForState(.Normal) {
if tintedClearImage == nil {
tintedClearImage = tintImage(image, color: clearButtonTintColor)
}
if button.imageView?.image != tintedClearImage {
button.setImage(tintedClearImage, forState: .Normal)
}
}
}
}
}
private func tintImage(image: UIImage, color: UIColor?) -> UIImage {
guard let color = color else { return image }
let size = image.size
UIGraphicsBeginImageContextWithOptions(size, false, 2)
let context = UIGraphicsGetCurrentContext()
image.drawAtPoint(CGPointZero, blendMode: CGBlendMode.Normal, alpha: 1.0)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextSetBlendMode(context, CGBlendMode.SourceIn)
CGContextSetAlpha(context, 1.0)
let rect = CGRectMake(
CGPointZero.x,
CGPointZero.y,
image.size.width,
image.size.height)
CGContextFillRect(UIGraphicsGetCurrentContext(), rect)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}
extension ToolbarTextField: Themeable {
func applyTheme(themeName: String) {
guard let theme = ToolbarTextField.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
backgroundColor = theme.backgroundColor
textColor = theme.textColor
clearButtonTintColor = theme.buttonTintColor
highlightColor = theme.highlightColor!
}
}
|
mpl-2.0
|
6ee7d0262c4fc40f6864c04cb49b76be
| 37.4371 | 276 | 0.665086 | 5.487671 | false | false | false | false |
darren90/Gankoo_Swift
|
Gankoo/Gankoo/Classes/Main/Base/BaseNavigationController.swift
|
1
|
1437
|
//
// BaseNavigationController.swift
// iTVshows
//
// Created by Fengtf on 2016/11/21.
// Copyright © 2016年 tengfei. All rights reserved.
//
import UIKit
class BaseNavigationController: UINavigationController,UINavigationControllerDelegate,UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
/// 隐藏导航栏
// isNavigationBarHidden = true
interactivePopGestureRecognizer?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
return (topViewController?.supportedInterfaceOrientations)!
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return (topViewController?.preferredInterfaceOrientationForPresentation)!
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if interactivePopGestureRecognizer != nil {
self.interactivePopGestureRecognizer?.isEnabled = false
}
if viewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
}
|
apache-2.0
|
b857907b5138c487112fc36ddaad7a6e
| 28.061224 | 115 | 0.711376 | 6.472727 | false | false | false | false |
perlguy99/GAS3_XLActionControllerAdditions
|
Example/Pods/XLActionController/Source/ActionCell.swift
|
1
|
2007
|
// ActionCell.swift
// XLActionController ( https://github.com/xmartlabs/ActionCell )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public protocol SeparatorCellType: NSObjectProtocol {
func showSeparator()
func hideSeparator()
}
public class ActionCell: UICollectionViewCell, SeparatorCellType {
@IBOutlet public weak var actionTitleLabel: UILabel?
@IBOutlet public weak var actionImageView: UIImageView?
@IBOutlet public weak var actionDetailLabel: UILabel?
@IBOutlet public weak var separatorView: UIView?
public func setup(title: String?, detail: String?, image: UIImage?) {
actionTitleLabel?.text = title
actionDetailLabel?.text = detail
actionImageView?.image = image
}
public func showSeparator() {
separatorView?.alpha = 1.0
}
public func hideSeparator() {
separatorView?.alpha = 0.0
}
}
|
mit
|
d54e3749229769b981e772bec15b2f07
| 37.596154 | 80 | 0.732436 | 4.678322 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK
|
BridgeAppSDK/SBANotificationsManager.swift
|
1
|
4533
|
//
// SBANotificationsManager.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 UIKit
enum SBAScheduledNotificationType: String {
case scheduledActivity
}
open class SBANotificationsManager: NSObject, SBASharedInfoController {
static let notificationType = "notificationType"
static let identifier = "identifier"
@objc(sharedManager)
open static let shared = SBANotificationsManager()
lazy open var sharedAppDelegate: SBAAppInfoDelegate = {
return UIApplication.shared.delegate as! SBAAppInfoDelegate
}()
lazy open var sharedApplication: UIApplication = {
return UIApplication.shared
}()
lazy open var permissionsManager: SBAPermissionsManager = {
return SBAPermissionsManager.shared
}()
@objc(setupNotificationsForScheduledActivities:)
open func setupNotifications(for scheduledActivities: [SBBScheduledActivity]) {
permissionsManager.requestPermissions(.localNotifications, alertPresenter: nil) { [weak self] (granted) in
if granted {
self?.scheduleNotifications(scheduledActivities: scheduledActivities)
}
}
}
fileprivate func scheduleNotifications(scheduledActivities activities: [SBBScheduledActivity]) {
// Cancel previous notifications
cancelNotifications(notificationType: .scheduledActivity)
// Add a notification for the scheduled activities that should include one
let app = sharedApplication
for sa in activities {
if let taskRef = self.sharedBridgeInfo.taskReferenceForSchedule(sa)
, taskRef.scheduleNotification {
let notif = UILocalNotification()
notif.fireDate = sa.scheduledOn
notif.soundName = UILocalNotificationDefaultSoundName
notif.alertBody = Localization.localizedStringWithFormatKey("SBA_TIME_FOR_%@", sa.activity.label)
notif.userInfo = [ SBANotificationsManager.notificationType: SBAScheduledNotificationType.scheduledActivity.rawValue,
SBANotificationsManager.identifier: sa.scheduleIdentifier ]
app.scheduleLocalNotification(notif)
}
}
}
fileprivate func cancelNotifications(notificationType: SBAScheduledNotificationType) {
let app = sharedApplication
if let scheduledNotifications = app.scheduledLocalNotifications {
for notif in scheduledNotifications {
if let type = notif.userInfo?[SBANotificationsManager.notificationType] as? String,
let notifType = SBAScheduledNotificationType(rawValue: type) , notifType == notificationType {
app.cancelLocalNotification(notif)
}
}
}
}
}
|
bsd-3-clause
|
a4a805083243bcf631f0adb5be640b31
| 43.871287 | 133 | 0.710503 | 5.520097 | false | false | false | false |
kevin0571/Ditto
|
Sources/ConvertibleTypes.swift
|
1
|
2920
|
//
// ConvertibleTypes.swift
// Ditto
//
// Created by Kevin Lin on 7/9/16.
// Copyright © 2016 Kevin. All rights reserved.
//
import Foundation
// MARK: DefaultConvertible
/**
DefaultConvertible simply return the current object.
*/
public protocol DefaultConvertible: Convertible {}
extension DefaultConvertible {
public func convert() -> JSONValue? {
return self as? JSONValue
}
}
extension String: DefaultConvertible {}
extension Int: DefaultConvertible {}
extension UInt: DefaultConvertible {}
extension Int8: DefaultConvertible {}
extension Int16: DefaultConvertible {}
extension Int32: DefaultConvertible {}
extension Int64: DefaultConvertible {}
extension UInt8: DefaultConvertible {}
extension UInt16: DefaultConvertible {}
extension UInt32: DefaultConvertible {}
extension UInt64: DefaultConvertible {}
extension Float: DefaultConvertible {}
extension Double: DefaultConvertible {}
extension Bool: DefaultConvertible {}
extension NSString: DefaultConvertible {}
extension NSNumber: DefaultConvertible {}
// MARK: Frequently used convertible types
extension URL: Convertible {
public func convert() -> JSONValue? {
return self.absoluteString
}
}
extension NSURL: Convertible {
public func convert() -> JSONValue? {
return self.absoluteString
}
}
extension NSNull: Convertible {
public func convert() -> JSONValue? {
return nil
}
}
extension Array: Convertible {
public func convert() -> JSONValue? {
return convertSequence(sequence: self)
}
}
extension NSArray: Convertible {
public func convert() -> JSONValue? {
return convertSequence(sequence: self)
}
}
extension Dictionary: Convertible {
public func convert() -> JSONValue? {
var jsonObject = JSONObject()
for (key, value) in self {
guard let key = key as? String else {
continue
}
jsonObject[key] = convertAny(any: value)
}
return jsonObject
}
}
extension Optional: Convertible {
public func convert() -> JSONValue? {
switch self {
case let .some(value):
if let value = convertAny(any: value) {
return value
} else {
return nil
}
default:
return nil
}
}
}
// MARK: Helpers
private func convertAny(any: Any) -> JSONValue? {
if let convertible = any as? Convertible {
return convertible.convert()
} else if let serializable = any as? Serializable {
return serializable.serialize() as JSONObject
} else {
return nil
}
}
private func convertSequence<T: Sequence>(sequence: T) -> [Any] {
var convertedArray = [Any]()
for element in sequence {
if let element = convertAny(any: element) {
convertedArray.append(element)
}
}
return convertedArray
}
|
mit
|
d6eaed0e30c58c891c8b6060af5c8544
| 23.123967 | 65 | 0.650908 | 4.769608 | false | false | false | false |
muukii/NextGrowingTextView
|
NextGrowingTextView-Demo/UIControl+Closure.swift
|
1
|
1421
|
import UIKit
private final class Proxy {
static var key: Void?
private weak var base: UIControl?
init(
_ base: UIControl
) {
self.base = base
}
var onTouchUpInside: (() -> Void)? {
didSet {
base?.addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
}
}
@objc private func touchUpInside(sender: AnyObject) {
onTouchUpInside?()
}
}
extension UIControl {
func onTap(_ closure: @escaping () -> Swift.Void) {
tapable.onTouchUpInside = closure
}
private var tapable: Proxy {
get {
if let handler = objc_getAssociatedObject(self, &Proxy.key) as? Proxy {
return handler
} else {
self.tapable = Proxy(self)
return self.tapable
}
}
set {
objc_setAssociatedObject(self, &Proxy.key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
extension UIButton {
static func make(
title: String,
color: UIColor? = nil,
onTap: @escaping () -> Void
) -> UIButton {
let button = UIButton(type: .system)
button.setAttributedTitle(
NSAttributedString(
string: title,
attributes: ([
.font: UIFont.preferredFont(forTextStyle: .headline),
.foregroundColor : color
] as [NSAttributedString.Key : AnyHashable?])
.compactMapValues { $0 }
),
for: .normal
)
button.onTap(onTap)
return button
}
}
|
mit
|
845024650aac12ffb286c9205bd06862
| 20.208955 | 94 | 0.607319 | 4.130814 | false | false | false | false |
eaplatanios/jelly-bean-world
|
api/swift/Sources/JellyBeanWorldExperiments/Utilities.swift
|
1
|
2729
|
// Copyright 2019, The Jelly Bean World Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import TensorFlow
extension Array where Element == Float {
internal var sum: Float { reduce(0, +) }
internal var mean: Float { sum / Float(count) }
internal var median: Float {
let sortedArray = sorted()
if count % 2 != 0 {
return Float(sortedArray[count / 2])
} else {
return Float(sortedArray[count / 2] + sortedArray[count / 2 - 1]) / 2.0
}
}
internal var standardDeviation: Element {
let mean = self.mean
let variance = map { ($0 - mean) * ($0 - mean) }
return TensorFlow.sqrt(variance.mean)
}
internal func scan<T>(_ initial: T, _ f: (T, Element) -> T) -> [T] {
reduce([initial], { (listSoFar: [T], next: Element) -> [T] in
listSoFar + [f(listSoFar.last!, next)]
})
}
}
extension Sequence where Element: Collection, Element.Index == Int {
public func transposed(prefixWithMaxLength max: Int = .max) -> [[Element.Element]] {
var transposed: [[Element.Element]] = []
let n = Swift.min(max, self.min { $0.count < $1.count }?.count ?? 0)
transposed.reserveCapacity(n)
for i in 0..<n { transposed.append(map{ $0[i] }) }
return transposed
}
}
@usableFromInline
internal struct Deque<Scalar: FloatingPoint> {
@usableFromInline internal let size: Int
@usableFromInline internal var buffer: [Scalar]
@usableFromInline internal var index: Int
@usableFromInline internal var full: Bool
@inlinable
init(size: Int) {
self.size = size
self.buffer = [Scalar](repeating: 0, count: size)
self.index = 0
self.full = false
}
@inlinable
mutating func push(_ value: Scalar) {
buffer[index] = value
index += 1
full = full || index == buffer.count
index = index % buffer.count
}
@inlinable
mutating func reset() {
index = 0
full = false
}
@inlinable
func sum() -> Scalar {
return full ? buffer.reduce(0, +) : buffer[0..<index].reduce(0, +)
}
@inlinable
func mean() -> Scalar {
let sum = full ? buffer.reduce(0, +) : buffer[0..<index].reduce(0, +)
let count = full ? buffer.count : index
return sum / Scalar(count)
}
}
|
apache-2.0
|
6a6b008efc1465483c05b1a626e3c698
| 28.031915 | 86 | 0.650421 | 3.77455 | false | false | false | false |
mamouneyya/TheSkillsProof
|
Pods/p2.OAuth2/Sources/Base/OAuth2CodeGrant.swift
|
2
|
5325
|
//
// OAuth2CodeGrant.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/16/14.
// Copyright 2014 Pascal Pfiffner
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
A class to handle authorization for confidential clients via the authorization code grant method.
This auth flow is designed for clients that are capable of protecting their client secret but can be used from installed apps. During
code exchange and token refresh flows, **if** the client has a secret, a "Basic key:secret" Authorization header will be used. If not
the client key will be embedded into the request body.
*/
public class OAuth2CodeGrant: OAuth2 {
public override class var grantType: String {
return "authorization_code"
}
override public class var responseType: String? {
return "code"
}
// MARK: - Token Request
/**
Generate the URL to be used for the token request from known instance variables and supplied parameters.
This will set "grant_type" to "authorization_code", add the "code" provided and forward to `authorizeURLWithBase()` to fill the
remaining parameters. The "client_id" is only added if there is no secret (public client) or if the request body is used for id and
secret.
- parameter code: The code you want to exchange for an access token
- parameter params: Optional additional params to add as URL parameters
- returns: The URL you can use to exchange the code for an access token
*/
func tokenURLWithCode(code: String, params: OAuth2StringDict? = nil) throws -> NSURL {
guard let redirect = context.redirectURL else {
throw OAuth2Error.NoRedirectURL
}
var urlParams = params ?? OAuth2StringDict()
urlParams["code"] = code
urlParams["grant_type"] = self.dynamicType.grantType
urlParams["redirect_uri"] = redirect
if let secret = clientConfig.clientSecret {
if authConfig.secretInBody {
urlParams["client_secret"] = secret
urlParams["client_id"] = clientConfig.clientId
}
}
else {
urlParams["client_id"] = clientConfig.clientId
}
return try authorizeURLWithParams(urlParams, asTokenURL: true)
}
/**
Create a request for token exchange.
*/
func tokenRequestWithCode(code: String) throws -> NSMutableURLRequest {
let url = try tokenURLWithCode(code)
return try tokenRequestWithURL(url)
}
/**
Extracts the code from the redirect URL and exchanges it for a token.
*/
override public func handleRedirectURL(redirect: NSURL) {
logIfVerbose("Handling redirect URL \(redirect.description)")
do {
let code = try validateRedirectURL(redirect)
exchangeCodeForToken(code)
}
catch let error {
didFail(error)
}
}
/**
Takes the received code and exchanges it for a token.
*/
public func exchangeCodeForToken(code: String) {
do {
guard !code.isEmpty else {
throw OAuth2Error.PrerequisiteFailed("I don't have a code to exchange, let the user authorize first")
}
let post = try tokenRequestWithCode(code)
logIfVerbose("Exchanging code \(code) for access token at \(post.URL!)")
performRequest(post) { data, status, error in
do {
guard let data = data else {
throw error ?? OAuth2Error.NoDataInResponse
}
let params = try self.parseAccessTokenResponse(data)
if status < 400 {
self.logIfVerbose("Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens")
self.didAuthorize(params)
}
else {
throw OAuth2Error.Generic("\(status)")
}
}
catch let error {
self.didFail(error)
}
}
}
catch let error {
didFail(error)
}
}
// MARK: - Utilities
/**
Validates the redirect URI: returns a tuple with the code and nil on success, nil and an error on failure.
*/
func validateRedirectURL(redirect: NSURL) throws -> String {
guard let expectRedirect = context.redirectURL else {
throw OAuth2Error.NoRedirectURL
}
let comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true)
if !redirect.absoluteString.hasPrefix(expectRedirect) && (!redirect.absoluteString.hasPrefix("urn:ietf:wg:oauth:2.0:oob") && "localhost" != comp?.host) {
throw OAuth2Error.InvalidRedirectURL("Expecting «\(expectRedirect)» but received «\(redirect)»")
}
if let compQuery = comp?.query where compQuery.characters.count > 0 {
let query = OAuth2CodeGrant.paramsFromQuery(comp!.percentEncodedQuery!)
try assureNoErrorInResponse(query)
if let cd = query["code"] {
// we got a code, use it if state is correct (and reset state)
try assureMatchesState(query)
return cd
}
throw OAuth2Error.ResponseError("No “code” received")
}
throw OAuth2Error.PrerequisiteFailed("The redirect URL contains no query fragment")
}
}
|
mit
|
56a924a1b4a942da18348bbfbd85fcb6
| 31.820988 | 159 | 0.715629 | 3.875364 | false | false | false | false |
OscarSwanros/swift
|
test/Constraints/closures_swift4.swift
|
9
|
773
|
// RUN: %target-typecheck-verify-swift -swift-version 4
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-error {{'+' is unavailable}}
}
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 }
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
r32432145 { _ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
print("answer is 42")
}
|
apache-2.0
|
184a2aece2396f5af3d1e0387ea71da7
| 37.65 | 124 | 0.639069 | 3.420354 | false | false | false | false |
cyrilchandelier/TodoSwift
|
Code/TodoSwiftKit/TaskService.swift
|
1
|
3818
|
//
// TaskService.swift
// TodoSwift
//
// Created by Cyril Chandelier on 01/11/15.
// Copyright © 2015 Cyril Chandelier. All rights reserved.
//
import Foundation
import CoreData
public class TaskService
{
public class func createTask(content: String) -> Task?
{
let managedObjectContext = CoreDataController.sharedInstance.managedObjectContext
// Trim content
let trimmedContent = trimmedContentFrom(content)
if trimmedContent == "" {
return nil
}
// Create task
let task = NSEntityDescription.insertNewObjectForEntityForName(TaskEntityName, inManagedObjectContext: managedObjectContext) as! Task
task.createdAt = NSDate()
task.completed = false
task.label = trimmedContent
// Save managed object context
saveContext(managedObjectContext)
return task
}
public class func updateTask(task: Task, content: String)
{
let managedObjectContext = CoreDataController.sharedInstance.managedObjectContext
// Trim content
let trimmedContent = trimmedContentFrom(content)
// Delete task if content is empty, update it otherwise
if trimmedContent.characters.count == 0
{
managedObjectContext.deleteObject(task)
saveContext(managedObjectContext)
}
else
{
task.label = trimmedContent
saveContext(task.managedObjectContext)
}
}
public class func deleteTask(task: Task)
{
let managedObjectContext = CoreDataController.sharedInstance.managedObjectContext
// Delete task from main managed object context
managedObjectContext.deleteObject(task)
// Save
saveContext(managedObjectContext)
}
public class func toggleTask(task: Task)
{
task.completed = !task.completed.boolValue
saveContext(task.managedObjectContext)
}
public class func taskList(predicate: NSPredicate?) -> [AnyObject]
{
let managedObjectContext = CoreDataController.sharedInstance.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: TaskEntityName)
fetchRequest.predicate = predicate
do {
return try managedObjectContext.executeFetchRequest(fetchRequest)
} catch let error as NSError {
print(error.localizedDescription)
}
return []
}
public class func clearCompletedTasks()
{
clearTasks(Task.completedPredicate())
}
private class func clearTasks(predicate: NSPredicate?)
{
let managedObjectContext = CoreDataController.sharedInstance.managedObjectContext
// Build a fetch request to retrieve completed task
let fetchRequest = NSFetchRequest(entityName: TaskEntityName)
fetchRequest.predicate = predicate
// Perform query
do {
let tasks = try managedObjectContext.executeFetchRequest(fetchRequest)
for task in tasks {
managedObjectContext.deleteObject(task as! NSManagedObject)
}
saveContext(managedObjectContext)
} catch let error as NSError {
print(error.localizedDescription)
}
}
private class func trimmedContentFrom(string: String) -> String
{
return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
private class func saveContext(context: NSManagedObjectContext?)
{
do {
try context?.save()
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
|
mit
|
4120a6760833493434f97bf01062dc75
| 28.828125 | 141 | 0.634792 | 6.020505 | false | false | false | false |
lynnx4869/LYAutoPhotoPickers
|
LYAutoPhotoPickers/Pods/JXPhotoBrowser/Sources/JXPhotoBrowser/JXPhotoBrowserZoomAnimator.swift
|
1
|
5520
|
//
// JXPhotoBrowserZoomAnimator.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2019/11/26.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
/// Zoom动画
open class JXPhotoBrowserZoomAnimator: NSObject, JXPhotoBrowserAnimatedTransitioning {
open var showDuration: TimeInterval = 0.25
open var dismissDuration: TimeInterval = 0.25
open var isNavigationAnimation = false
public typealias PreviousViewAtIndexClosure = (_ index: Int) -> UIView?
/// 转场动画的前向视图
open var previousViewProvider: PreviousViewAtIndexClosure = { _ in return nil }
/// 替补的动画方案
open lazy var substituteAnimator: JXPhotoBrowserAnimatedTransitioning = JXPhotoBrowserFadeAnimator()
public init(previousView: @escaping PreviousViewAtIndexClosure) {
previousViewProvider = previousView
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return isForShow ? showDuration : dismissDuration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isForShow {
playShowAnimation(context: transitionContext)
} else {
playDismissAnimation(context: transitionContext)
}
}
private func playShowAnimation(context: UIViewControllerContextTransitioning) {
guard let browser = photoBrowser, let toView = context.view(forKey: .to) else {
return
}
if isNavigationAnimation, let fromView = context.view(forKey: .from), let fromViewSnapshot = snapshot(with: fromView) {
toView.insertSubview(fromViewSnapshot, at: 0)
}
context.containerView.addSubview(toView)
guard let (snap1, snap2, thumbnailFrame, destinationFrame) = snapshotsAndFrames(browser: browser) else {
// 转为执行替补动画
substituteAnimator.isForShow = isForShow
substituteAnimator.photoBrowser = photoBrowser
substituteAnimator.animateTransition(using: context)
return
}
snap1.frame = thumbnailFrame
snap2.frame = thumbnailFrame
snap2.alpha = 0
browser.maskView.alpha = 0
browser.browserView.isHidden = true
context.containerView.addSubview(snap1)
context.containerView.addSubview(snap2)
UIView.animate(withDuration: showDuration, animations: {
browser.maskView.alpha = 1.0
snap1.frame = destinationFrame
snap1.alpha = 0
snap2.frame = destinationFrame
snap2.alpha = 1.0
}) { _ in
browser.browserView.isHidden = false
toView.insertSubview(browser.maskView, belowSubview: browser.browserView)
snap1.removeFromSuperview()
snap2.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
private func playDismissAnimation(context: UIViewControllerContextTransitioning) {
guard let browser = photoBrowser else {
return
}
guard let (snap1, snap2, thumbnailFrame, destinationFrame) = snapshotsAndFrames(browser: browser) else {
// 转为执行替补动画
substituteAnimator.isForShow = isForShow
substituteAnimator.photoBrowser = photoBrowser
substituteAnimator.animateTransition(using: context)
return
}
snap1.frame = destinationFrame
snap1.alpha = 0
snap2.frame = destinationFrame
context.containerView.addSubview(snap1)
context.containerView.addSubview(snap2)
browser.browserView.isHidden = true
UIView.animate(withDuration: showDuration, animations: {
browser.maskView.alpha = 0
snap1.frame = thumbnailFrame
snap1.alpha = 0
snap2.frame = thumbnailFrame
snap2.alpha = 1.0
}) { _ in
if let toView = context.view(forKey: .to) {
context.containerView.addSubview(toView)
}
snap1.removeFromSuperview()
snap2.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
private func snapshotsAndFrames(browser: JXPhotoBrowser) -> (UIView, UIView, CGRect, CGRect)? {
let browserView = browser.browserView
let view = browser.view
let closure = previousViewProvider
guard let previousView = closure(browserView.pageIndex) else {
return nil
}
guard let cell = browserView.visibleCells[browserView.pageIndex] as? JXPhotoBrowserZoomSupportedCell else {
return nil
}
let thumbnailFrame = previousView.convert(previousView.bounds, to: view)
let showContentView = cell.showContentView
// 两Rect求交集,得出显示中的区域
let destinationFrame = cell.convert(cell.bounds.intersection(showContentView.frame), to: view)
guard let snap1 = fastSnapshot(with: previousView) else {
JXPhotoBrowserLog.high("取不到前截图!")
return nil
}
guard let snap2 = snapshot(with: cell.showContentView) else {
JXPhotoBrowserLog.high("取不到后截图!")
return nil
}
return (snap1, snap2, thumbnailFrame, destinationFrame)
}
}
|
mit
|
d61e9fe8277842fabe77e2a571e252d5
| 37.827338 | 127 | 0.652585 | 5.135109 | false | false | false | false |
buyiyang/iosstar
|
iOSStar/General/Extension/UIButton+Extension.swift
|
3
|
3097
|
//
// UIButton+Extension.swift
// iOSStar
//
// Created by mu on 2017/6/26.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
extension UIButton{
// private struct controlKeys{
// static var acceptEventInterval = "controlInterval"
// static var acceptEventTime = "controlTime"
//
// }
// var controlInterval: TimeInterval{
// get{
// if let interval = objc_getAssociatedObject(self, &controlKeys.acceptEventInterval) as? TimeInterval{
// return interval
// }
// return 1.0
// }
// set{
// objc_setAssociatedObject(self, &controlKeys.acceptEventInterval, newValue as TimeInterval, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// }
// }
// var controlTime: TimeInterval{
// get{
// if let time = objc_getAssociatedObject(self, &controlKeys.acceptEventTime) as? TimeInterval{
// return time
// }
// return 3.0
// }
// set{
// objc_setAssociatedObject(self, &controlKeys.acceptEventTime, newValue as TimeInterval, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// }
// }
//
// override open class func initialize(){
//
// if self == UIButton.self {
// if ShareDataModel.share().buttonExtOnceSwitch {
// let sysSel = #selector(UIButton.sendAction(_:to:for:))
// let sysMethod: Method = class_getInstanceMethod(self, sysSel)
// let newSel = #selector(UIButton.y_sendAction(_:to:for:))
// let newMethod: Method = class_getInstanceMethod(self, newSel)
// let didAddMethod = class_addMethod(self, sysSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))
// if didAddMethod{
// class_replaceMethod(self, newSel, method_getImplementation(sysMethod), method_getTypeEncoding(sysMethod))
// }else{
// method_exchangeImplementations(sysMethod, newMethod)
// }
// ShareDataModel.share().buttonExtOnceSwitch = false
// }
// }
// }
//
// func y_sendAction(_ action: Selector, to target: AnyObject?, for event: UIEvent?) {
// if self.classForCoder != UIButton.self || ShareDataModel.share().voiceSwitch{
// self.y_sendAction(action, to: target, for: event)
// return
// }
//
// if ShareDataModel.share().controlSwitch == false{
// NotificationCenter.default.post(name: Notification.Name.init(rawValue: AppConst.NoticeKey.frozeUser.rawValue), object: nil, userInfo: nil)
// return
// }
//
//
//
// if NSDate().timeIntervalSince1970 - self.controlTime < self.controlInterval {
// print("onc")
// return
// }
//
// self.controlTime = NSDate().timeIntervalSince1970
//
// y_sendAction(action, to: target, for:event)
// }
}
|
gpl-3.0
|
1a3df84c441a02f9245fcdc0daff0536
| 36.731707 | 162 | 0.579186 | 4.169811 | false | false | false | false |
ale84/ABLE
|
ABLE/Mocks/CBPeripheralMock.swift
|
1
|
5383
|
//
// Created by Alessio Orlando on 07/06/18.
// Copyright © 2019 Alessio Orlando. All rights reserved.
//
import Foundation
import CoreBluetooth
public class CBPeripheralMock: CBPeripheralType {
public var discoverServicesBehaviour: DiscoverServicesBehaviour = .success(with: [], after: 0)
public var discoverCharacteristicsBehaviour: DiscoverCharacteristicsBehaviour = .failure
public var readValueBehaviour: ReadValueBehaviour = .success
public var writeValueBehaviour: WriteValueBehaviour = .success
public var notifyBehaviour: NotifyBehaviour = .success
public var readRSSIBehaviour: ReadRSSIBehaviour = .success
public var cbDelegate: CBPeripheralDelegateType?
public var name: String?
public var state: CBPeripheralState = .connected
public var canSendWriteWithoutResponse: Bool = false
public var identifier: UUID = UUID()
public var cbServices: [CBServiceType]? = []
public var ancsAuthorized: Bool = false
public func discoverServices(_ serviceUUIDs: [CBUUID]?) {
switch discoverServicesBehaviour {
case .success(let services, let interval):
delay(interval) {
self.cbServices = services
self.cbDelegate?.peripheral(self, didDiscoverServices: nil)
}
case .failure:
cbDelegate?.peripheral(self, didDiscoverServices: DiscoverServicesError.discoveryFailed)
}
}
public func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: CBServiceType) { }
public func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: CBServiceType) {
switch discoverCharacteristicsBehaviour {
case .success(let service, let interval):
delay(interval) {
self.cbDelegate?.peripheral(self, didDiscoverCharacteristicsFor: service, error: nil)
}
case .failure:
cbDelegate?.peripheral(self, didDiscoverCharacteristicsFor: service, error: DiscoverCharacteristicError.discoveryFailed)
}
}
public func discoverDescriptors(for characteristic: CBCharacteristicType) { }
public func readValue(for characteristic: CBCharacteristicType) {
switch readValueBehaviour {
case .success:
cbDelegate?.peripheral(self, didUpdateValueFor: characteristic, error: nil)
case .failure:
cbDelegate?.peripheral(self, didUpdateValueFor: characteristic, error: ReadValueError.readFailed)
}
}
public func writeValue(_ data: Data, for characteristic: CBCharacteristicType, type: CBCharacteristicWriteType) {
switch writeValueBehaviour {
case .success:
cbDelegate?.peripheral(self, didWriteValueFor: characteristic, error: nil)
case .failure:
cbDelegate?.peripheral(self, didWriteValueFor: characteristic, error: WriteValueError.writeFailed)
}
}
public func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristicType) {
switch notifyBehaviour {
case .success:
cbDelegate?.peripheral(self, didUpdateNotificationStateFor: characteristic, error: nil)
if enabled {
cbDelegate?.peripheral(self, didUpdateValueFor: characteristic, error: nil)
}
case .failure:
cbDelegate?.peripheral(self, didUpdateNotificationStateFor: characteristic, error: NotifyError.updateStateFailure)
}
}
public func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int {
return 100
}
public func readRSSI() {
switch readRSSIBehaviour {
case .success:
cbDelegate?.peripheral(self, didReadRSSI: NSNumber(value: -30), error: nil)
case .failure:
cbDelegate?.peripheral(self, didReadRSSI: NSNumber(value: 0), error: ReadRSSIError.readFailed)
}
}
public func readValue(for descriptor: CBDescriptor) { }
public func writeValue(_ data: Data, for descriptor: CBDescriptor) { }
public func openL2CAPChannel(_ PSM: CBL2CAPPSM) { }
}
// MARK: Behaviours.
extension CBPeripheralMock {
public enum DiscoverServicesBehaviour {
case success(with: [CBServiceType], after: TimeInterval)
case failure
}
public enum DiscoverCharacteristicsBehaviour {
case success(with: CBServiceType, after: TimeInterval)
case failure
}
public enum ReadValueBehaviour {
case success
case failure
}
public enum WriteValueBehaviour {
case success
case failure
}
public enum NotifyBehaviour {
case success
case failure
}
public enum ReadRSSIBehaviour {
case success
case failure
}
}
// MARK: Errors.
extension CBPeripheralMock {
public enum DiscoverServicesError: Error {
case discoveryFailed
}
public enum DiscoverCharacteristicError: Error {
case discoveryFailed
}
public enum ReadValueError: Error {
case readFailed
}
public enum WriteValueError: Error {
case writeFailed
}
public enum NotifyError: Error {
case updateStateFailure
}
public enum ReadRSSIError: Error {
case readFailed
}
}
|
mit
|
8eb7b87373b5ad83401b524a06bbd863
| 32.428571 | 132 | 0.668896 | 5.355224 | false | false | false | false |
hfutrell/BezierKit
|
BezierKit/Library/BernsteinPolynomialN.swift
|
1
|
4588
|
//
// BezierCurve.swift
// GraphicsPathNearest
//
// Created by Holmes Futrell on 2/19/21.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
struct BernsteinPolynomialN: BernsteinPolynomial {
let coefficients: [CGFloat]
func difference(a1: CGFloat, a2: CGFloat) -> BernsteinPolynomialN {
fatalError("unimplemented.")
}
var order: Int { return coefficients.count - 1 }
init(coefficients: [CGFloat]) {
precondition(coefficients.isEmpty == false, "Bezier curves require at least one point")
self.coefficients = coefficients
}
static func * (left: CGFloat, right: BernsteinPolynomialN) -> BernsteinPolynomialN {
return BernsteinPolynomialN(coefficients: right.coefficients.map { left * $0 })
}
static func == (left: BernsteinPolynomialN, right: BernsteinPolynomialN) -> Bool {
return left.coefficients == right.coefficients
}
func reversed() -> BernsteinPolynomialN {
return BernsteinPolynomialN(coefficients: coefficients.reversed())
}
var derivative: BernsteinPolynomialN {
guard order > 0 else { return BernsteinPolynomialN(coefficients: [CGFloat.zero]) }
return CGFloat(order) * hodograph
}
func value(at t: CGFloat) -> CGFloat {
return self.split(at: t).left.coefficients.last!
}
private var hodograph: BernsteinPolynomialN {
precondition(order > 0)
let differences = (0..<order).map { coefficients[$0 + 1] - coefficients[$0] }
return BernsteinPolynomialN(coefficients: differences)
}
func split(at t: CGFloat) -> (left: BernsteinPolynomialN, right: BernsteinPolynomialN) {
guard order > 0 else {
// splitting a point results in getting a point back
return (left: self, right: self)
}
// apply de Casteljau Algorithm
var leftPoints = [CGFloat](repeating: .zero, count: coefficients.count)
var rightPoints = [CGFloat](repeating: .zero, count: coefficients.count)
let n = order
var scratchPad: [CGFloat] = coefficients
leftPoints[0] = scratchPad[0]
rightPoints[n] = scratchPad[n]
for j in 1...n {
for i in 0...n - j {
scratchPad[i] = Utils.linearInterpolate(scratchPad[i], scratchPad[i + 1], t)
}
leftPoints[j] = scratchPad[0]
rightPoints[n - j] = scratchPad[n - j]
}
return (left: BernsteinPolynomialN(coefficients: leftPoints),
right: BernsteinPolynomialN(coefficients: rightPoints))
}
func split(from t1: CGFloat, to t2: CGFloat) -> BernsteinPolynomialN {
guard (t1 > t2) == false else {
// simplifying to t1 <= t2 would infinite loop on NaN because NaN comparisons are always false
return split(from: t2, to: t1).reversed()
}
guard t1 != 0 else { return split(at: t2).left }
let right = split(at: t1).right
guard t2 != 1 else { return right }
let t2MappedToRight = (t2 - t1) / (1 - t1)
return right.split(at: t2MappedToRight).left
}
}
extension BernsteinPolynomialN {
static func + (left: BernsteinPolynomialN, right: BernsteinPolynomialN) -> BernsteinPolynomialN {
precondition(left.order == right.order, "curves must have equal degree (unless we support upgrading degrees, which we don't here)")
return BernsteinPolynomialN(coefficients: zip(left.coefficients, right.coefficients).map(+))
}
static func * (left: BernsteinPolynomialN, right: BernsteinPolynomialN) -> BernsteinPolynomialN {
// the polynomials are multiplied in Bernstein form, which is a little different
// from normal polynomial multiplication. For a discussion of how this works see
// "Computer Aided Geometric Design" by T.W. Sederberg,
// 9.3 Multiplication of Polynomials in Bernstein Form
let m = left.order
let n = right.order
let points = (0...m + n).map { k -> CGFloat in
let start = max(k - n, 0)
let end = min(m, k)
let sum = (start...end).reduce(CGFloat.zero) { totalSoFar, i in
let j = k - i
return totalSoFar + CGFloat(Utils.binomialCoefficient(m, choose: i) * Utils.binomialCoefficient(n, choose: j)) * left.coefficients[i] * right.coefficients[j]
}
let divisor = CGFloat(Utils.binomialCoefficient(m + n, choose: k))
return sum / divisor
}
return BernsteinPolynomialN(coefficients: points)
}
}
|
mit
|
689453920ad8d2d8095bc8f8ad94d291
| 42.695238 | 173 | 0.63884 | 4.070985 | false | false | false | false |
WeHUD/app
|
weHub-ios/Gzone_App/Gzone_App/NetworkReachability.swift
|
1
|
2249
|
//
// NetworkReachability.swift
// Gzone_App
//
// Created by Tracy Sablon on 08/07/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import UIKit
import ReachabilitySwift
class NetworkReachability: NSObject {
static let shared = NetworkReachability()
// Boolean to track network reachability
var isNetworkAvailable : Bool {
return reachabilityStatus != .notReachable
}
// Tracks current NetworkStatus (notReachable, reachableViaWiFi, reachableViaWWAN)
var reachabilityStatus: Reachability.NetworkStatus = .notReachable
// 5. Reachability instance for Network status monitoring
let reachability = Reachability()!
/// Called whenever there is a change in NetworkReachibility Status
///
/// — parameter notification: Notification with the Reachability instance
func reachabilityChanged(notification: Notification) {
let reachability = notification.object as! Reachability
switch reachability.currentReachabilityStatus {
case .notReachable:
print("Network became unreachable : \(isNetworkAvailable)")
case .reachableViaWiFi:
print("Network reachable through WiFi")
case .reachableViaWWAN:
debugPrint("Network reachable through Cellular Data")
}
}
/// Starts monitoring the network availability status
func startMonitoring() {
NotificationCenter.default.addObserver(self,
selector: #selector(self.reachabilityChanged),
name: ReachabilityChangedNotification,
object: reachability)
do{
try reachability.startNotifier()
} catch {
debugPrint("Could not start reachability notifier")
}
}
/// Stops monitoring the network availability status
func stopMonitoring(){
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self,
name: ReachabilityChangedNotification,
object: reachability)
}
}
|
bsd-3-clause
|
7a454639b518224ea68e7bebb37ab49b
| 34.650794 | 93 | 0.616652 | 6.548105 | false | false | false | false |
BenEmdon/swift-algorithm-club
|
Binary Search Tree/Solution 2/BinarySearchTree.playground/Sources/BinarySearchTree.swift
|
1
|
2940
|
/*
Binary search tree using value types
The tree is immutable. Any insertions or deletions will create a new tree.
*/
public enum BinarySearchTree<T: Comparable> {
case Empty
case Leaf(T)
indirect case Node(BinarySearchTree, T, BinarySearchTree)
/* How many nodes are in this subtree. Performance: O(n). */
public var count: Int {
switch self {
case .Empty: return 0
case .Leaf: return 1
case let .Node(left, _, right): return left.count + 1 + right.count
}
}
/* Distance of this node to its lowest leaf. Performance: O(n). */
public var height: Int {
switch self {
case .Empty: return 0
case .Leaf: return 1
case let .Node(left, _, right): return 1 + max(left.height, right.height)
}
}
/*
Inserts a new element into the tree.
Performance: runs in O(h) time, where h is the height of the tree.
*/
public func insert(newValue: T) -> BinarySearchTree {
switch self {
case .Empty:
return .Leaf(newValue)
case .Leaf(let value):
if newValue < value {
return .Node(.Leaf(newValue), value, .Empty)
} else {
return .Node(.Empty, value, .Leaf(newValue))
}
case .Node(let left, let value, let right):
if newValue < value {
return .Node(left.insert(newValue: newValue), value, right)
} else {
return .Node(left, value, right.insert(newValue: newValue))
}
}
}
/*
Finds the "highest" node with the specified value.
Performance: runs in O(h) time, where h is the height of the tree.
*/
public func search(x: T) -> BinarySearchTree? {
switch self {
case .Empty:
return nil
case .Leaf(let y):
return (x == y) ? self : nil
case let .Node(left, y, right):
if x < y {
return left.search(x: x)
} else if y < x {
return right.search(x: x)
} else {
return self
}
}
}
public func contains(x: T) -> Bool {
return search(x: x) != nil
}
/*
Returns the leftmost descendent. O(h) time.
*/
public func minimum() -> BinarySearchTree {
var node = self
var prev = node
while case let .Node(next, _, _) = node {
prev = node
node = next
}
if case .Leaf = node {
return node
}
return prev
}
/*
Returns the rightmost descendent. O(h) time.
*/
public func maximum() -> BinarySearchTree {
var node = self
var prev = node
while case let .Node(_, _, next) = node {
prev = node
node = next
}
if case .Leaf = node {
return node
}
return prev
}
}
extension BinarySearchTree: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .Empty: return "."
case .Leaf(let value): return "\(value)"
case .Node(let left, let value, let right):
return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))"
}
}
}
|
mit
|
2c20a0c78e8642e8363eb670caf61253
| 23.297521 | 82 | 0.592517 | 3.873518 | false | false | false | false |
krad/buffie
|
Sources/Buffie/Video/VideoSampleHelpers.swift
|
1
|
3895
|
import Foundation
import AVFoundation
internal func createSample(from buffer: [UInt8], format: CMFormatDescription) -> CMSampleBuffer? {
var timingInfo = timingInfoFrom(buffer, ptsAppended: false)
if let blockBuffer = blockBuffer(from: buffer) {
if let sample = sample(from: blockBuffer, timingInfo: &timingInfo, format: format) {
return sample
}
}
return nil
}
/// Build a timing info struct from a stream of bytes
///
/// - Parameters:
/// - bytes: stream of bytes that MIGHT have timing info appended
/// - ptsAppended: If the last 8 bytes of the bytes have a timestamp
/// - Returns: CMSampleTimingInfoStruct
internal func timingInfoFrom(_ bytes: [UInt8], ptsAppended: Bool) -> CMSampleTimingInfo {
let duration = kCMTimeInvalid
var presentation = kCMTimeInvalid
let decode = kCMTimeInvalid
if ptsAppended {
let ptsBytes = Array(bytes[bytes.endIndex-8..<bytes.endIndex])
let ptsValue = Int64(bytes: ptsBytes)!
presentation = CMTime(value: ptsValue, timescale: 600, flags: CMTimeFlags.valid, epoch: 0)
}
return CMSampleTimingInfo(duration: duration,
presentationTimeStamp: presentation,
decodeTimeStamp: decode)
}
/// Returns a block buffer constructed from an array of bytes
///
/// - Parameter bytes: Bytes you want to bind to a block buffer
/// - Returns: CMBlockBuffer
internal func blockBuffer(from bytes: [UInt8]) -> CMBlockBuffer? {
// let naluWithLength = prependLengthToBytes(bytes)
let naluData = data(from: bytes)
var status = noErr
var blockBuffer: CMBlockBuffer?
status = CMBlockBufferCreateEmpty(nil, 1, 0, &blockBuffer)
if status != noErr {
return nil
}
if let blockBufferRef = blockBuffer {
let dataPtr = UnsafeMutablePointer<UInt8>(mutating: (naluData as NSData).bytes.bindMemory(to: UInt8.self, capacity: naluData.count))
status = CMBlockBufferAppendMemoryBlock(blockBufferRef, dataPtr, naluData.count, kCFAllocatorNull, nil, 0, naluData.count, 0)
if status != noErr {
return nil
}
return blockBufferRef
}
return nil
}
internal func data(from bytes: [UInt8]) -> Data {
return Data(bytes)
}
internal func sample(from blockBuffer: CMBlockBuffer, timingInfo: inout CMSampleTimingInfo, format: CMFormatDescription) -> CMSampleBuffer? {
var status = noErr
var sample: CMSampleBuffer? = nil
var sampleSizeArray: [size_t] = [CMBlockBufferGetDataLength(blockBuffer)]
status = CMSampleBufferCreate(kCFAllocatorDefault,
blockBuffer,
true,
nil,
nil,
format,
1,
1,
&timingInfo,
1,
&sampleSizeArray,
&sample)
if status != noErr { return nil }
return sample
}
/// Adds an attachment to a CMSampleBuffer
///
/// - Parameters:
/// - key: Key name of the attachment
/// - value: Value of the attachment
/// - sample: Sample to attach to
internal func addAttachment(key: CFString, value: CFBoolean, to sample: inout CMSampleBuffer) {
if let attachments: CFArray = CMSampleBufferGetSampleAttachmentsArray(sample, true) {
let attachment: CFMutableDictionary = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self)
CFDictionarySetValue(attachment, Unmanaged.passUnretained(key).toOpaque(), Unmanaged.passUnretained(value).toOpaque())
}
}
|
mit
|
64bb059f401f70bb9e77ed14db3d0eac
| 34.409091 | 141 | 0.607959 | 4.75 | false | false | false | false |
dreamsxin/swift
|
test/Inputs/ObjCBridging/Appliances.swift
|
2
|
1928
|
@_exported import Appliances
public struct Refrigerator {
public var temperature: Double
}
extension Refrigerator : _ObjectiveCBridgeable {
public typealias _ObjectiveCType = APPRefrigerator
public static func _isBridgedToObjectiveC() -> Bool { return true }
public func _bridgeToObjectiveC() -> _ObjectiveCType {
return APPRefrigerator(temperature: temperature)
}
public static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Refrigerator?
) {
result = Refrigerator(temperature: source.temperature)
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Refrigerator?
) -> Bool {
result = Refrigerator(temperature: source.temperature)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Refrigerator {
return Refrigerator(temperature: source!.temperature)
}
}
public struct ManufacturerInfo<DataType: AnyObject> {
private var impl: APPManufacturerInfo<DataType>
public var value: DataType {
return impl.value
}
}
extension ManufacturerInfo : _ObjectiveCBridgeable {
public typealias _ObjectiveCType = APPManufacturerInfo<DataType>
public static func _isBridgedToObjectiveC() -> Bool { return true }
public func _bridgeToObjectiveC() -> _ObjectiveCType {
return impl
}
public static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout ManufacturerInfo?
) {
result = ManufacturerInfo(impl: source)
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout ManufacturerInfo?
) -> Bool {
result = ManufacturerInfo(impl: source)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType?
) -> ManufacturerInfo {
return ManufacturerInfo(impl: source!)
}
}
|
apache-2.0
|
dd45ac64776061e47b559e698533b215
| 25.410959 | 85 | 0.733402 | 5.34072 | false | false | false | false |
kfarst/alarm
|
alarm/AlarmSoundHelper.swift
|
1
|
5301
|
//
// AlarmSoundHelper.swift
// alarm
//
// Created by Michael Lewis on 3/15/15.
// Copyright (c) 2015 Kevin Farst. All rights reserved.
//
import AVFoundation
import Foundation
// Stash a singleton global instance
private let _alarmSoundHelper = AlarmSoundHelper()
class AlarmSoundHelper: NSObject {
let VOLUME_INITIAL: Float = 0.20 // start at 20%
let VOLUME_RAMP_UP_STEP: Float = 0.01 // 1% at a time
let VOLUME_RAMP_UP_TIME: Float = 60.0 // seconds
let VOLUME_RAMP_DOWN_STEP: Float = 0.05 // 5% at a time
let VOLUME_RAMP_DOWN_TIME: Float = 3.0 // seconds
let FIRST_VIBRATION_AT: Float = 60.0 // seconds
let VIBRATION_URGENCY: Float = 1.0 / 1.25 // Next vibe arrives 25% faster
let alertSound = NSURL(
fileURLWithPath: NSBundle.mainBundle().pathForResource("alarm", ofType: "m4a")!
)
let player: AVAudioPlayer
// The volumeTimer is responsible for ramping the volume up and down
var volumeTimer: NSTimer?
var vibrationTimer: NSTimer?
// How long we're waiting until the next vibration
var currentVibrationWait: Float = 0.0
override init() {
var error: NSError?
player = AVAudioPlayer(
contentsOfURL: alertSound,
error: &error
)
if let e = error {
NSLog("AlarmSoundHelper error: \(e.description)")
}
super.init()
}
// Create and hold onto a singleton instance of this class
class var singleton: AlarmSoundHelper {
return _alarmSoundHelper
}
/* Public interface */
class func startPlaying() {
singleton.startPlaying()
}
class func stopPlaying() {
singleton.stopPlaying()
}
/* Instance functions */
// Start playing the sound, and ramp up the volume
func startPlaying() {
player.volume = VOLUME_INITIAL
player.currentTime = 0
player.numberOfLoops = 100
player.prepareToPlay()
player.play()
rampUpVolume()
activateVibrationRampup()
}
// Ramp the volume down to zero.
// When it reaches zero, stop the player.
func stopPlaying() {
rampDownVolumeToStop()
invalidateVibrationTimer()
}
/* Private functions */
// If there's an old volume timer, invalidate it
private func invalidateVolumeTimer() {
if let timer = volumeTimer {
timer.invalidate()
volumeTimer = nil
}
}
// If there's an old vibration timer, invalidate it
private func invalidateVibrationTimer() {
if let timer = vibrationTimer {
timer.invalidate()
vibrationTimer = nil
}
}
private func rampUpVolume() {
invalidateVolumeTimer()
// Set up a repeating timer that ramps up the player volume
volumeTimer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(VOLUME_RAMP_UP_TIME * VOLUME_RAMP_UP_STEP), // seconds
target: self,
selector: "increaseVolumeOneNotch",
userInfo: nil,
repeats: true
)
}
private func rampDownVolumeToStop() {
invalidateVolumeTimer()
// Set up a repeating timer that ramps up the player volume
volumeTimer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(VOLUME_RAMP_DOWN_TIME * VOLUME_RAMP_DOWN_STEP), // seconds
target: self,
selector: "decreaseVolumeOneNotchToStop",
userInfo: nil,
repeats: true
)
}
// Vibration is not introduced until a ways into the alarm
// It starts out slow and ramps up exponentially
// Unhandled, it will get really annoying
private func activateVibrationRampup() {
// Invalidate the existing timer
invalidateVibrationTimer()
// Reset our vibration wait
currentVibrationWait = FIRST_VIBRATION_AT
// Set up the timer for the first one. It's recursive for the rest.
vibrationTimer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(currentVibrationWait), // seconds
target: self,
selector: "triggerVibration",
userInfo: nil,
repeats: false
)
}
/* Event handlers */
// Called by the volumeTimer to slowly increase volume
func increaseVolumeOneNotch() {
player.volume += VOLUME_RAMP_UP_STEP
// If we've reached full volume, stop the timer
if player.volume >= 1.0 {
NSLog("Volume at 100%")
invalidateVolumeTimer()
// For sanity, make sure volume is not above 1.0
player.volume = 1.0
}
}
// Called by the volumeTimer to slowly decrease volume
func decreaseVolumeOneNotchToStop() {
player.volume -= VOLUME_RAMP_DOWN_STEP
// If we've reached zero volume, stop the player and the timer
if player.volume <= 0.0 {
NSLog("Volume at 0%")
invalidateVolumeTimer()
// For sanity, make sure volume is not below 0.0
player.volume = 0.0
// Stop the player
player.stop()
}
}
// Trigger a vibration and schedule the next one
func triggerVibration() {
NSLog("vibe")
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
invalidateVibrationTimer()
currentVibrationWait *= VIBRATION_URGENCY
// Cap it at one vibration per 5 seconds
if currentVibrationWait < 5.0 {
currentVibrationWait = 5.0
}
vibrationTimer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(currentVibrationWait), // seconds
target: self,
selector: "triggerVibration",
userInfo: nil,
repeats: false
)
}
}
|
mit
|
232e51b67210ecd48b161aa70b84b77f
| 24.985294 | 83 | 0.676665 | 4.040396 | false | false | false | false |
nickswalker/BubblesView
|
Sources/Classes/BubbleView.swift
|
2
|
3011
|
//
// Copyright (c) 2016 Nick Walker.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
/// A circle with a centered label and/or a background image.
open class BubbleView: UIView {
open var label = UILabel()
open var imageView = UIImageView()
/// The index that this bubble represents in its parent BubblesView
internal var index: Int?
override public init(frame: CGRect) {
super.init(frame: frame)
addSubview(label)
addSubview(imageView)
translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = .clear
/*
let leading = imageView.leadingAnchor.constraintEqualToAnchor(leadingAnchor)
let trailing = imageView.trailingAnchor.constraintEqualToAnchor(trailingAnchor)
let top = imageView.topAnchor.constraintEqualToAnchor(topAnchor)
let bottom = imageView.bottomAnchor.constraintEqualToAnchor(bottomAnchor)
//addConstraints([leading, trailing, top, bottom])
*/
label.textColor = .white
label.font = UIFont.boldSystemFont(ofSize: 21.0)
label.textAlignment = .center
/*
let centerX = label.centerXAnchor.constraintEqualToAnchor(centerXAnchor)
let centerY = label.centerYAnchor.constraintEqualToAnchor(centerYAnchor)
//addConstraints([centerX, centerY])
*/
}
override open func layoutSubviews() {
super.layoutSubviews()
label.frame = CGRect(origin: CGPoint.zero, size: label.intrinsicContentSize)
label.frame = CGRect(x: 10, y: frame.height / 2.0 - label.frame.height / 2.0, width: frame.width - 20.0, height: 30)
layer.cornerRadius = frame.width / 2.0
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override var collisionBoundsType: UIDynamicItemCollisionBoundsType {
return .ellipse
}
}
|
mit
|
a34c0919f3e95040057716da57ddf5f7
| 39.689189 | 124 | 0.708403 | 4.779365 | false | false | false | false |
emilstahl/swift
|
test/SILGen/partial_apply_init.swift
|
13
|
2273
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
class C {
init(x: Int) {}
required init(required: Double) {}
}
class D {
required init(required: Double) {}
}
protocol P {
init(proto: String)
}
extension P {
init(protoExt: Float) {
self.init(proto: "")
}
}
// CHECK-LABEL: sil hidden @_TF18partial_apply_init24class_init_partial_apply
func class_init_partial_apply(c: C.Type) {
// Partial applications at the static metatype use the direct (_TTd) thunk.
// CHECK: function_ref @_TTdFC18partial_apply_init1CC
let xC: Int -> C = C.init
// CHECK: function_ref @_TTdFC18partial_apply_init1CC
let requiredC: Double -> C = C.init
// Partial applications to a dynamic metatype must be dynamically dispatched and use
// the normal thunk.
// CHECK: function_ref @_TFC18partial_apply_init1CC
let requiredM: Double -> C = c.init
}
// CHECK-LABEL: sil shared @_TTdFC18partial_apply_init1CC
// CHECK: function_ref @_TFC18partial_apply_init1CC
// CHECK-LABEL: sil shared @_TTdFC18partial_apply_init1CC
// CHECK: function_ref @_TFC18partial_apply_init1CC
// CHECK-LABEL: sil shared @_TFC18partial_apply_init1CC
// CHECK: class_method %0 : $@thick C.Type, #C.init!allocator.1
// CHECK-LABEL: sil hidden @_TF18partial_apply_init28archetype_init_partial_apply
func archetype_init_partial_apply<T: C where T: P>(t: T.Type) {
// Archetype initializations are always dynamic, whether applied to the type or a metatype.
// CHECK: function_ref @_TFC18partial_apply_init1CC
let requiredT: Double -> T = T.init
// CHECK: function_ref @_TFP18partial_apply_init1PC
let protoT: String -> T = T.init
// CHECK: function_ref @_TFE18partial_apply_initPS_1PC
let protoExtT: Float -> T = T.init
// CHECK: function_ref @_TFC18partial_apply_init1CC
let requiredM: Double -> T = t.init
// CHECK: function_ref @_TFP18partial_apply_init1PC
let protoM: String -> T = t.init
// CHECK: function_ref @_TFE18partial_apply_initPS_1PC
let protoExtM: Float -> T = t.init
}
// CHECK-LABEL: sil shared @_TFP18partial_apply_init1PC
// CHECK: witness_method $Self, #P.init!allocator.1
// CHECK-LABEL: sil shared @_TFE18partial_apply_initPS_1PC
// CHECK: function_ref @_TFE18partial_apply_initPS_1PC
|
apache-2.0
|
64157ed1b61a8d2eb87d0c3ffd92245f
| 33.439394 | 93 | 0.697756 | 3.143845 | false | false | false | false |
senojsitruc/libSwerve
|
libSwerve/libSwerve/Extern/Pulse/DeviceId.swift
|
1
|
1531
|
import Foundation
public class DeviceId: Equatable, CustomStringConvertible {
let hash: NSData
private init!(hash: NSData) {
self.hash = hash
if (hash.length != 256 / 8) {
return nil
}
}
public convenience init!(hash: [UInt8]) {
self.init(hash: NSData(bytes: hash, length: hash.count))
}
public convenience init!(cert: SecCertificate) {
self.init(hash: cert.data.SHA256Digest())
}
public var description: String {
//return "-".join(base32Groups)
return ""
}
// public var sha256 : [UInt8] {
// return hash.bytes
// }
// private var base32Groups: [String] {
// var result: [String] = []
// base32PlusChecks.processChunksOfSize(7) {
// result.append($0)
// }
// return result
// }
// private var base32PlusChecks: String {
// var result = ""
// base32.processChunksOfSize(13) {
// result = result + $0 + String(LuhnBase32Wrong.calculateCheckDigit($0))
// }
// return result
// }
// private var base32: String {
// let result = hash.base32String()
// return result.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "="))
// }
}
public func == (lhs: DeviceId, rhs: DeviceId) -> Bool {
return lhs.hash == rhs.hash
}
extension String {
func processChunksOfSize(chunkSize: Int, _ closure: (String)->()) {
let amountOfChunks = self.characters.count / chunkSize
var begin = self.startIndex
for _ in 0..<amountOfChunks {
let end = begin.advancedBy(chunkSize)
let chunk = self[begin..<end]
closure(chunk)
begin = end
}
}
}
|
mit
|
005e1e5070a128dd1e9d7cc11eaa2e6e
| 19.689189 | 90 | 0.657087 | 3.09919 | false | false | false | false |
mcudich/TemplateKit
|
Source/Utilities/URL.swift
|
1
|
706
|
//
// URL.swift
// TemplateKit
//
// Created by Matias Cudich on 9/30/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
extension URL: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public typealias UnicodeScalarLiteralType = String
public typealias ExtendedGraphemeClusterLiteralType = String
public init(stringLiteral value: URL.StringLiteralType) {
self = URL(string: value)!
}
public init(extendedGraphemeClusterLiteral value: URL.ExtendedGraphemeClusterLiteralType) {
self = URL(string: value)!
}
public init(unicodeScalarLiteral value: URL.UnicodeScalarLiteralType) {
self = URL(string: value)!
}
}
|
mit
|
2ecf271099a3a9fe11813aff3ac2e229
| 27.2 | 93 | 0.747518 | 4.93007 | false | false | false | false |
devpunk/punknote
|
punknote/View/Create/VCreateCellCard.swift
|
1
|
2525
|
import UIKit
class VCreateCellCard:VCreateCell
{
private weak var viewText:VCreateCellCardText!
private weak var viewGradient:UIView?
private let kBorderHeight:CGFloat = 1
private let kAnimationDuration:TimeInterval = 0.4
override init(frame:CGRect)
{
super.init(frame:frame)
let borderTop:VBorder = VBorder(color:UIColor.black)
let borderBottom:VBorder = VBorder(color:UIColor.black)
let viewText:VCreateCellCardText = VCreateCellCardText()
let viewBar:VCreateCellCardBar = VCreateCellCardBar(
viewText:viewText)
viewText.inputAccessoryView = viewBar
self.viewText = viewText
addSubview(borderTop)
addSubview(borderBottom)
addSubview(viewText)
NSLayoutConstraint.topToTop(
view:borderTop,
toView:self)
NSLayoutConstraint.height(
view:borderTop,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:borderTop,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:borderBottom,
toView:self)
NSLayoutConstraint.height(
view:borderBottom,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:borderBottom,
toView:self)
NSLayoutConstraint.equals(
view:viewText,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func config(controller:CCreate)
{
super.config(controller:controller)
viewText.config(model:controller.model)
addGradient()
}
//MARK: private
private func addGradient()
{
self.viewGradient?.removeFromSuperview()
guard
let backgroundModel:MCreateBackgroundProtocol = controller?.model.selectedBackgroundModel()
else
{
return
}
let viewGradient:UIView = backgroundModel.view()
viewGradient.alpha = 0
self.viewGradient = viewGradient
insertSubview(viewGradient, at:0)
NSLayoutConstraint.equals(
view:viewGradient,
toView:self)
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.viewGradient?.alpha = 1
}
}
}
|
mit
|
2820aec92c6b942876662722db263c72
| 25.030928 | 103 | 0.585347 | 5.24948 | false | false | false | false |
AlexIzh/Griddle
|
Griddle/Classes/Map.swift
|
1
|
2791
|
//
// Map.swift
// CollectionPresenter
//
// Created by Alex on 21/02/16.
// Copyright © 2016 Moqod. All rights reserved.
//
import Foundation
import UIKit
public struct RegistrationItem {
public enum ItemType {
case header, footer, row
}
public enum ViewType {
case nib(UINib)
case viewClass(AnyClass)
}
public var identifier: String
public var itemType: ItemType = .row
public var viewType: ViewType
public init(viewType: ViewType, id: String, itemType: ItemType = .row) {
self.viewType = viewType
self.itemType = itemType
identifier = id
}
public init(viewClass: AnyClass, itemType: ItemType = .row) {
self.init(viewType: .viewClass(viewClass), id: String(describing: viewClass), itemType: itemType)
}
}
public class ViewInfo {
public var identifier: String
public var setModel: (_ view: Any, _ model: Any) -> Void
public var size: (_ model: Any, _ container: UIView) -> CGSize?
public var estimatedSize: (_ model: Any, _ container: UIView) -> CGSize?
public convenience init<T: ReusableView>(viewClass: T.Type) {
self.init(identifier: String(describing: viewClass.self), viewClass: viewClass)
}
public init<T: ReusableView>(identifier: String, viewClass: T.Type) {
self.identifier = identifier
estimatedSize = { aModel, container in
guard let model = aModel as? T.Model
else { fatalError("Trying to calculate estimated size with incorrect model \(aModel) for \(String(describing: T.self))") }
return T.estimatedSize(for: model, container: container)
}
size = { aModel, container in
guard let model = aModel as? T.Model
else { fatalError("Trying to calculate size with incorrect model \(aModel) for \(String(describing: T.self))") }
return T.size(for: model, container: container)
}
setModel = { aView, aModel in
guard let model = aModel as? T.Model
else { fatalError("\(String(describing: T.self)) doesn't support \(aModel).") }
guard var view = aView as? T
else { fatalError("Incorrect view \(aView). \(String(describing: T.self)) is expected...") }
view.model = model
}
}
}
public protocol Map {
func viewInfo(for model: Any, indexPath: IndexPath) -> ViewInfo?
var registrationItems: [RegistrationItem] { get }
}
public struct DefaultMap: Map {
public var registrationItems: [RegistrationItem] = []
public var viewInfoGeneration: (Any, IndexPath) -> ViewInfo = { _ in
fatalError("You should set viewInfoGeneration for DefaultMap object")
}
public func viewInfo(for model: Any, indexPath: IndexPath) -> ViewInfo? {
return viewInfoGeneration(model, indexPath)
}
public init() {}
}
|
mit
|
3fd5b7032052ff328186f36baf482566
| 29.659341 | 131 | 0.659498 | 4.176647 | false | false | false | false |
mzp/OctoEye
|
Tests/Unit/GithubAPI/GithubClientSpec.swift
|
1
|
1949
|
//
// GithubClientSpec.swift
// Tests
//
// Created by mzp on 2017/07/07.
// Copyright © 2017 mzp. All rights reserved.
//
import BrightFutures
import GraphQLicious
import JetToTheFuture
import Nimble
import Quick
import Result
internal class GithubClientSpec: QuickSpec {
internal struct SampleResponse: Codable {
}
private func github(future: Future<Data, AnyError>) -> GithubClient {
return GithubClient(token: "-", httpRequest: MockHttpRequest(future: future))
}
override func spec() {
let query = Query(request: Request(name: "repository"))
describe("error handling") {
it("return http request error") {
let error = Result<SampleResponse, AnyError>.error(nil)
let future = Future<Data, AnyError>(error: AnyError(error))
let r = forcedFuture { _ -> Future<SampleResponse, AnyError> in
self.github(future: future).query(query)
}
expect(r.value).to(beNil())
}
it("return json parsing error") {
// swiftlint:disable:next force_unwrapping
let future = Future<Data, AnyError>(value: "{ \"datum\": {} }".data(using: .utf8)!)
let r = forcedFuture { _ -> Future<SampleResponse, AnyError> in
self.github(future: future).query(query)
}
expect(r.value).to(beNil())
}
}
describe("return value") {
it("return decoded value") {
// swiftlint:disable:next force_unwrapping
let future = Future<Data, AnyError>(value: "{ \"data\": {} }".data(using: .utf8)!)
let r = forcedFuture { _ -> Future<SampleResponse, AnyError> in
self.github(future: future).query(query)
}
expect(r.value).toNot(beNil())
}
}
}
}
|
mit
|
9cd1983f9bb3ec72dad13445bf25ae6b
| 30.934426 | 99 | 0.553388 | 4.616114 | false | false | false | false |
cuappdev/podcast-ios
|
Recast/Utilities/ViewController.swift
|
1
|
3619
|
//
// ViewController.swift
// Recast
//
// Created by Jack Thompson on 11/20/18.
// Copyright © 2018 Cornell AppDev. All rights reserved.
//
import UIKit
enum NavBarType {
case `default`
case custom
case hidden
}
class ViewController: UIViewController, UIScrollViewDelegate {
// MARK: - Variables
var customNavBar: CustomNavigationBar?
var navBarType: NavBarType = .default {
didSet {
setNavBar(navBarType)
}
}
var mainScrollView: UIScrollView? {
didSet {
if navBarType == .custom {
mainScrollView?.delegate = self
mainScrollView?.contentInsetAdjustmentBehavior = .never
mainScrollView?.contentInset = self.additionalSafeAreaInsets
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setNavBar(navBarType)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setNavBar(navBarType)
}
func setNavBar(_ type: NavBarType) {
switch type {
case .default:
setDefaultNavBar()
case .custom:
removeNavBar()
if let navBar = customNavBar {
navBar.isHidden = false
} else {
addCustomNavBar()
}
case .hidden:
removeNavBar()
}
}
func setDefaultNavBar() {
navigationController?.navigationBar.prefersLargeTitles = true
extendedLayoutIncludesOpaqueBars = true
navigationController?.navigationBar.barTintColor = .black
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.isOpaque = true
navigationController?.navigationBar.isTranslucent = false
}
func removeNavBar() {
navigationController?.navigationBar.prefersLargeTitles = false
navigationController?.navigationBar.backgroundColor = .clear
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
extendedLayoutIncludesOpaqueBars = true
}
func addCustomNavBar() {
customNavBar = CustomNavigationBar()
customNavBar?.title = navigationItem.title
navigationItem.title = nil
view.addSubview(customNavBar!)
customNavBar?.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
make.height.equalTo(CustomNavigationBar.height).priority(999)
make.height.greaterThanOrEqualTo(CustomNavigationBar.smallHeight)
}
// `mainScrollView` insets for when using custom navigation bar
var newSafeArea = view.safeAreaInsets
newSafeArea.top = CustomNavigationBar.height
newSafeArea.bottom = AppDelegate.appDelegate.tabBarController.tabBar.frame.height
self.additionalSafeAreaInsets = newSafeArea
viewSafeAreaInsetsDidChange()
}
/// Resizes Custom Navigation Bar upon scrolling, if `navBarType = .custom`.
dynamic func scrollViewDidScroll(_ scrollView: UIScrollView) {
customNavBar?.snp.updateConstraints { update in
update.height.equalTo(-scrollView.contentOffset.y).priority(999)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// keep navigation bar on top
if let navBar = customNavBar {
view.bringSubviewToFront(navBar)
}
}
}
|
mit
|
ac373a397e8c44dacbf81865deaa884d
| 29.661017 | 89 | 0.650636 | 5.661972 | false | false | false | false |
tectijuana/iOS
|
VargasJuan/Demo-MVC/Lib/SQLite.swift/SQLiteTests/TestHelpers.swift
|
23
|
3836
|
import XCTest
import SQLite
class SQLiteTestCase : XCTestCase {
var trace = [String: Int]()
let db = try! Connection()
let users = Table("users")
override func setUp() {
super.setUp()
db.trace { SQL in
print(SQL)
self.trace[SQL] = (self.trace[SQL] ?? 0) + 1
}
}
func CreateUsersTable() {
try! db.execute(
"CREATE TABLE \"users\" (" +
"id INTEGER PRIMARY KEY, " +
"email TEXT NOT NULL UNIQUE, " +
"age INTEGER, " +
"salary REAL, " +
"admin BOOLEAN NOT NULL DEFAULT 0 CHECK (admin IN (0, 1)), " +
"manager_id INTEGER, " +
"FOREIGN KEY(manager_id) REFERENCES users(id)" +
")"
)
}
func InsertUsers(_ names: String...) throws {
try InsertUsers(names)
}
func InsertUsers(_ names: [String]) throws {
for name in names { try InsertUser(name) }
}
@discardableResult func InsertUser(_ name: String, age: Int? = nil, admin: Bool = false) throws -> Statement {
return try db.run(
"INSERT INTO \"users\" (email, age, admin) values (?, ?, ?)",
"\(name)@example.com", age?.datatypeValue, admin.datatypeValue
)
}
func AssertSQL(_ SQL: String, _ executions: Int = 1, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(
executions, trace[SQL] ?? 0,
message ?? SQL,
file: file, line: line
)
}
func AssertSQL(_ SQL: String, _ statement: Statement, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) {
try! statement.run()
AssertSQL(SQL, 1, message, file: file, line: line)
if let count = trace[SQL] { trace[SQL] = count - 1 }
}
// func AssertSQL(SQL: String, _ query: Query, _ message: String? = nil, file: String = __FILE__, line: UInt = __LINE__) {
// for _ in query {}
// AssertSQL(SQL, 1, message, file: file, line: line)
// if let count = trace[SQL] { trace[SQL] = count - 1 }
// }
func async(expect description: String = "async", timeout: Double = 5, block: (@escaping () -> Void) -> Void) {
let expectation = self.expectation(description: description)
block(expectation.fulfill)
waitForExpectations(timeout: timeout, handler: nil)
}
}
let bool = Expression<Bool>("bool")
let boolOptional = Expression<Bool?>("boolOptional")
let data = Expression<Blob>("blob")
let dataOptional = Expression<Blob?>("blobOptional")
let date = Expression<Date>("date")
let dateOptional = Expression<Date?>("dateOptional")
let double = Expression<Double>("double")
let doubleOptional = Expression<Double?>("doubleOptional")
let int = Expression<Int>("int")
let intOptional = Expression<Int?>("intOptional")
let int64 = Expression<Int64>("int64")
let int64Optional = Expression<Int64?>("int64Optional")
let string = Expression<String>("string")
let stringOptional = Expression<String?>("stringOptional")
func AssertSQL(_ expression1: @autoclosure () -> String, _ expression2: @autoclosure () -> Expressible, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(expression1(), expression2().asSQL(), file: file, line: line)
}
func AssertThrows<T>(_ expression: @autoclosure () throws -> T, file: StaticString = #file, line: UInt = #line) {
do {
_ = try expression()
XCTFail("expression expected to throw", file: file, line: line)
} catch {
XCTAssert(true, file: file, line: line)
}
}
let table = Table("table")
let qualifiedTable = Table("table", database: "main")
let virtualTable = VirtualTable("virtual_table")
let _view = View("view") // avoid Mac XCTestCase collision
|
mit
|
4982879198b6fec378cf1d260706fb66
| 32.356522 | 153 | 0.595933 | 3.979253 | false | false | false | false |
openhab/openhab.ios
|
openHABWatch Extension/Views/Utils/ColorSelection.swift
|
1
|
4572
|
// Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import os.log
import SwiftUI
/// Drag State describing the combination of a long press and drag gesture.
/// - seealso:
/// [Reference]: https://developer.apple.com/documentation/swiftui/gestures/composing_swiftui_gestures "Composing SwiftUI Gestures "
enum DragState {
case inactive
case pressing
case dragging(translation: CGSize)
var translation: CGSize {
switch self {
case .inactive, .pressing:
return .zero
case let .dragging(translation):
return translation
}
}
var isActive: Bool {
switch self {
case .inactive:
return false
case .pressing, .dragging:
return true
}
}
var isDragging: Bool {
switch self {
case .inactive, .pressing:
return false
case .dragging:
return true
}
}
}
struct ColorSelection: View {
@GestureState var thumb: DragState = .inactive
@State var hue: Double = 0.5
@State var xpos: Double = 100
@State var ypos: Double = 100
var body: some View {
let spectrum = Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red])
let conic = AngularGradient(gradient: spectrum, center: .center, angle: .degrees(0))
return GeometryReader { (geometry: GeometryProxy) in
Circle()
.size(geometry.size)
.fill(conic)
.overlay(self.generateHandle(geometry: geometry))
}
}
/// Prevent the draggable element from going over its limit
func limitDisplacement(_ value: Double, _ limit: CGFloat, _ state: CGFloat) -> CGFloat {
max(0, min(limit, CGFloat(value) * limit + state))
}
/// Prevent the draggable element from going beyond the circle
func limitCircle(_ point: CGPoint, _ geometry: CGSize, _ state: CGSize) -> (CGPoint) {
let x1 = point.x + state.width - geometry.width / 2
let y1 = point.y + state.height - geometry.height / 2
let theta = atan2(x1, y1)
// Circle limit.width = limit.height
let radius = min(sqrt(x1 * x1 + y1 * y1), geometry.width / 2)
return CGPoint(x: sin(theta) * radius + geometry.width / 2, y: cos(theta) * radius + geometry.width / 2)
}
/// Creates the `Handle` and adds the drag gesture to it.
func generateHandle(geometry: GeometryProxy) -> some View {
/// [Reference]: https://developer.apple.com/documentation/swiftui/gestures/composing_swiftui_gestures "Composing SwiftUI Gestures "
let longPressDrag = LongPressGesture(minimumDuration: 0.05)
.sequenced(before: DragGesture())
.updating($thumb) { value, state, _ in
switch value {
// Long press begins.
case .first(true):
state = .pressing
// Long press confirmed, dragging may begin.
case .second(true, let drag):
state = .dragging(translation: drag?.translation ?? .zero)
// Dragging ended or the long press cancelled.
default:
state = .inactive
}
}
.onEnded { value in
guard case .second(true, let drag?) = value else { return }
os_log("Translation x y = %g, %g", log: .default, type: .info, drag.translation.width, drag.translation.height)
self.xpos += Double(drag.translation.width)
self.ypos += Double(drag.translation.height)
}
// MARK: Customize Handle Here
// Add the gestures and visuals to the handle
return Circle()
.overlay(thumb.isDragging ? Circle().stroke(Color.white, lineWidth: 2) : nil)
.foregroundColor(.white)
.frame(width: 25, height: 25, alignment: .center)
.position(limitCircle(CGPoint(x: xpos, y: ypos), geometry.size, thumb.translation))
.animation(.interactiveSpring())
.gesture(longPressDrag)
}
}
struct ColorSelection_Previews: PreviewProvider {
static var previews: some View {
ColorSelection()
}
}
|
epl-1.0
|
dea9a988306460f692f85e88761e1c03
| 34.44186 | 141 | 0.596457 | 4.354286 | false | false | false | false |
mattjgalloway/emoncms-ios
|
EmonCMSiOS/UI/View Controllers/AddAccountQRViewController.swift
|
1
|
5362
|
//
// AddAccountQRViewController.swift
// EmonCMSiOS
//
// Created by Matt Galloway on 12/09/2016.
// Copyright © 2016 Matt Galloway. All rights reserved.
//
import UIKit
import AVFoundation
protocol AddAccountQRViewControllerDelegate: class {
func addAccountQRViewController(controller: AddAccountQRViewController, didFinishWithAccount account: Account)
func addAccountQRViewControllerDidCancel(controller: AddAccountQRViewController)
}
final class AddAccountQRViewController: UIViewController {
weak var delegate: AddAccountQRViewControllerDelegate?
@IBOutlet var playerLayerView: UIView!
private var captureSession: AVCaptureSession?
private var videoPreviewLayer: AVCaptureVideoPreviewLayer?
fileprivate var foundAccount = false
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Scan Code"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.checkCameraPermissionAndSetupStack()
self.captureSession?.startRunning()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.captureSession?.stopRunning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.videoPreviewLayer?.frame = self.playerLayerView.bounds
}
private dynamic func cancel() {
self.delegate?.addAccountQRViewControllerDidCancel(controller: self)
}
private func checkCameraPermissionAndSetupStack() {
guard self.captureSession == nil else { return }
let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch authStatus {
case .authorized:
self.setupAVStack()
case .notDetermined:
self.askForCameraPermission()
case .denied:
self.presentCameraRequiredDialog()
case .restricted:
self.presentCameraRestrictedDialog()
}
}
private func setupAVStack() {
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
let captureSession = AVCaptureSession()
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureSession.addOutput(captureMetadataOutput)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
if let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer.frame = self.playerLayerView.bounds
self.videoPreviewLayer = videoPreviewLayer
self.playerLayerView.layer.addSublayer(videoPreviewLayer)
}
self.captureSession = captureSession
captureSession.startRunning()
} catch {
AppLog.error("Error setting up AV stack: \(error)")
}
}
private func askForCameraPermission() {
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { (enabled) in
DispatchQueue.main.async {
if enabled {
self.setupAVStack()
} else {
self.presentCameraRequiredDialog()
}
}
}
}
private func presentCameraRequiredDialog() {
let alert = UIAlertController(title: "Camera Required", message: "Camera access is required for QR code scanning to work. Turn on camera permission in Settings.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Go to Settings", style: .default, handler: { _ in
if let url = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
private func presentCameraRestrictedDialog() {
let alert = UIAlertController(title: "Camera Required", message: "Camera access is required for QR code scanning to work. Turn on camera permission in Settings.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
extension AddAccountQRViewController: AVCaptureMetadataOutputObjectsDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
guard self.foundAccount == false else { return }
guard let metadataObjects = metadataObjects,
metadataObjects.count > 0
else {
return
}
guard let qrCode = metadataObjects[0] as? AVMetadataMachineReadableCodeObject,
qrCode.type == AVMetadataObjectTypeQRCode,
let string = qrCode.stringValue
else {
return
}
guard let result = EmonCMSAPI.extractAPIDetailsFromURLString(string) else {
return
}
self.foundAccount = true
DispatchQueue.main.async {
let account = Account(uuid: UUID(), url: result.host, apikey: result.apikey)
self.delegate?.addAccountQRViewController(controller: self, didFinishWithAccount: account)
}
}
}
|
mit
|
cc7f56763f4f8308dab474487f40f48f
| 32.93038 | 190 | 0.736989 | 5.199806 | false | false | false | false |
efremidze/VisualEffectView
|
Sources/UIViewEffectViewiOS14.swift
|
1
|
2275
|
//
// UIViewEffectViewiOS14.swift
// VisualEffectView
//
// Created by Lasha Efremidze on 9/14/20.
//
import UIKit
@available(iOS 14, *)
extension UIVisualEffectView {
var ios14_blurRadius: CGFloat {
get {
return gaussianBlur?.requestedValues?["inputRadius"] as? CGFloat ?? 0
}
set {
prepareForChanges()
gaussianBlur?.requestedValues?["inputRadius"] = newValue
applyChanges()
}
}
var ios14_colorTint: UIColor? {
get {
return sourceOver?.value(forKeyPath: "color") as? UIColor
}
set {
prepareForChanges()
sourceOver?.setValue(newValue, forKeyPath: "color")
sourceOver?.perform(Selector(("applyRequestedEffectToView:")), with: overlayView)
applyChanges()
overlayView?.backgroundColor = newValue
}
}
}
private extension UIVisualEffectView {
var backdropView: UIView? {
return subview(of: NSClassFromString("_UIVisualEffectBackdropView"))
}
var overlayView: UIView? {
return subview(of: NSClassFromString("_UIVisualEffectSubview"))
}
var gaussianBlur: NSObject? {
return backdropView?.value(forKey: "filters", withFilterType: "gaussianBlur")
}
var sourceOver: NSObject? {
return overlayView?.value(forKey: "viewEffects", withFilterType: "sourceOver")
}
func prepareForChanges() {
self.effect = UIBlurEffect(style: .light)
gaussianBlur?.setValue(1.0, forKeyPath: "requestedScaleHint")
}
func applyChanges() {
backdropView?.perform(Selector(("applyRequestedFilterEffects")))
}
}
private extension NSObject {
var requestedValues: [String: Any]? {
get { return value(forKeyPath: "requestedValues") as? [String: Any] }
set { setValue(newValue, forKeyPath: "requestedValues") }
}
func value(forKey key: String, withFilterType filterType: String) -> NSObject? {
return (value(forKeyPath: key) as? [NSObject])?.first { $0.value(forKeyPath: "filterType") as? String == filterType }
}
}
private extension UIView {
func subview(of classType: AnyClass?) -> UIView? {
return subviews.first { type(of: $0) == classType }
}
}
|
mit
|
bd46631117aba155f6aecb99a362b53f
| 30.597222 | 125 | 0.632967 | 4.55 | false | false | false | false |
PrashantMangukiya/SwiftParseDemo
|
SwiftParseDemo/SwiftParseDemo/LoginViewController.swift
|
2
|
4934
|
//
// LoginViewController.swift
// SwiftParseDemo
//
// Created by Prashant on 10/09/15.
// Copyright (c) 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController, UITextFieldDelegate {
// outlet - activity indicator (spinner)
@IBOutlet var spinner: UIActivityIndicatorView!
// outlet and action - username
@IBOutlet var usernameText: UITextField!
@IBAction func usernameEditingChanged(sender: UITextField) {
// validate input while entering text
self.validateInput()
}
// outlet and action - password
@IBOutlet var passwordText: UITextField!
@IBAction func passwordTextEditingChanged(sender: UITextField) {
// validate input while entering text
self.validateInput()
}
// outlet and action - sign in button
@IBOutlet var signInButton: UIButton!
@IBAction func signInButtonAction(sender: UIButton) {
// end editing i.e. close keyboard if open
self.view.endEditing(true)
// do parse login
self.doSignIn()
}
// action - forgot password button
@IBAction func forgotPasswordAction(sender: UIButton) {
self.performSegueWithIdentifier("segueForgotPassword", sender: self)
}
// action - new user signup button
@IBAction func userRegisterAction(sender: UIButton) {
self.performSegueWithIdentifier("segueUserRegister", sender: self)
}
// MARK: - view functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// stop spinner at view load
self.spinner.stopAnimating()
// set text field delegate
self.passwordText.delegate = self
self.usernameText.delegate = self
// disable sign in button
self.signInButton.enabled = false
}
override func viewDidAppear(animated: Bool) {
// if user logged in then close the screen
if PFUser.currentUser() != nil {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - text field delegate function
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: - Utility functions
// perform sign in within parse database
private func doSignIn() -> Void {
// show spinner for task in progress
self.spinner.startAnimating()
// collect username, password value from text field.
let username = self.usernameText.text
let password = self.passwordText.text
// Send asynchronous login request to parse server
PFUser.logInWithUsernameInBackground(username!, password: password!, block: { (user, error) -> Void in
// Stop the spinner
self.spinner.stopAnimating()
// if user object not nil means login success, otherwise show error message.
if ( user != nil ) {
// close login screen
self.dismissViewControllerAnimated(true, completion: nil)
}else{
// show error message
self.showAlertMessage(alertTitle: "Error!", alertMessage: "Invalid username or password.")
}
})
}
// validate input data, disable sign in button if any input not valid.
private func validateInput() -> Void {
var isValidInput : Bool = true
// if any input not valid then set status false
if self.usernameText.text!.characters.count < 4 {
isValidInput = false
}
if self.passwordText.text!.characters.count < 4 {
isValidInput = false
}
// if valid input then enable sign in button
if isValidInput {
self.signInButton.enabled = true
}else{
self.signInButton.enabled = false
}
}
// show alert message with given title and message
private func showAlertMessage(alertTitle alertTitle: String, alertMessage: String) -> Void {
let alertCtrl = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
alertCtrl.addAction(okAction)
self.showViewController(alertCtrl, sender: self)
}
}
|
mit
|
bf0eb4b98d20bfbb902d190902216ace
| 28.722892 | 129 | 0.602351 | 5.550056 | false | false | false | false |
zhxnlai/Algorithms
|
swift/FindOneNumber.playground/Contents.swift
|
2
|
454
|
// Playground - noun: a place where people can play
import UIKit
func findOneNumber(a: [Int]) -> Int {
var c = a[0]
var t = 1
for i in a[1..<a.count] {
if t == 0 {
c = i
t = 1
} else {
if c == i {
t++
} else {
t--
}
}
}
return c
}
findOneNumber([1,2,1,2,1])
findOneNumber([0,1,2,1,1])
findOneNumber([5,5,5,5,1])
|
mit
|
19f867dd4a8393664749cd4ed4035435
| 15.214286 | 51 | 0.398678 | 3.131034 | false | false | false | false |
iMasanari/cmd-eikana
|
cmd-eikana/KeyTextField.swift
|
1
|
3184
|
//
// KeyTextField.swift
// ⌘英かな
//
// MIT License
// Copyright (c) 2016 iMasanari
//
import Cocoa
var activeKeyTextField: KeyTextField?
class KeyTextField: NSComboBox {
/// Custom delegate with other methods than NSTextFieldDelegate.
var shortcut: KeyboardShortcut? = nil
var saveAddress: (row: Int, id: String)? = nil
var isAllowModifierOnly = true
override func becomeFirstResponder() -> Bool {
let became = super.becomeFirstResponder();
if (became) {
activeKeyTextField = self
}
return became;
}
// override func resignFirstResponder() -> Bool {
// let resigned = super.resignFirstResponder();
// if (resigned) {
// }
// return resigned;
// }
override func textDidEndEditing(_ obj: Notification) {
super.textDidEndEditing(obj)
switch self.stringValue {
case "英数":
shortcut = KeyboardShortcut(keyCode: 102)
break
case "かな":
shortcut = KeyboardShortcut(keyCode: 104)
break
case "⇧かな":
shortcut = KeyboardShortcut(keyCode: 104, flags: CGEventFlags.maskShift)
break
case "前の入力ソースを選択", "select the previous input source":
let symbolichotkeys = UserDefaults.init(suiteName: "com.apple.symbolichotkeys.plist")?.object(forKey: "AppleSymbolicHotKeys") as! NSDictionary
let parameters = symbolichotkeys.value(forKeyPath: "60.value.parameters") as! [Int]
shortcut = KeyboardShortcut(keyCode: CGKeyCode(parameters[1]), flags: CGEventFlags(rawValue: UInt64(parameters[2])))
break
case "入力メニューの次のソースを選択", "select next source in input menu":
let symbolichotkeys = UserDefaults.init(suiteName: "com.apple.symbolichotkeys.plist")?.object(forKey: "AppleSymbolicHotKeys") as! NSDictionary
let parameters = symbolichotkeys.value(forKeyPath: "61.value.parameters") as! [Int]
shortcut = KeyboardShortcut(keyCode: CGKeyCode(parameters[1]), flags: CGEventFlags(rawValue: UInt64(parameters[2])))
break
case "Disable":
shortcut = KeyboardShortcut(keyCode: CGKeyCode(999))
break
default:
break
}
if let shortcut = shortcut {
self.stringValue = shortcut.toString()
if let saveAddress = saveAddress {
if saveAddress.id == "input" {
keyMappingList[saveAddress.row].input = shortcut
}
else {
keyMappingList[saveAddress.row].output = shortcut
}
keyMappingListToShortcutList()
}
}
else {
self.stringValue = ""
}
saveKeyMappings()
if activeKeyTextField == self {
activeKeyTextField = nil
}
}
func blur() {
self.window?.makeFirstResponder(nil)
activeKeyTextField = nil
}
}
|
mit
|
dd383236db5e099ce3b34a8fd64cd86b
| 32.826087 | 154 | 0.576799 | 4.75841 | false | false | false | false |
apple/swift-nio
|
Sources/NIOConcurrencyHelpers/NIOAtomic.swift
|
1
|
18318
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 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 CNIOAtomics
/// The protocol that all types that can be made atomic must conform to.
///
/// **Do not add conformance to this protocol for arbitrary types**. Only a small range
/// of types have appropriate atomic operations supported by the CPU, and those types
/// already have conformances implemented.
public protocol NIOAtomicPrimitive {
associatedtype AtomicWrapper
static var nio_atomic_create_with_existing_storage: (UnsafeMutablePointer<AtomicWrapper>, Self) -> Void { get }
static var nio_atomic_compare_and_exchange: (UnsafeMutablePointer<AtomicWrapper>, Self, Self) -> Bool { get }
static var nio_atomic_add: (UnsafeMutablePointer<AtomicWrapper>, Self) -> Self { get }
static var nio_atomic_sub: (UnsafeMutablePointer<AtomicWrapper>, Self) -> Self { get }
static var nio_atomic_exchange: (UnsafeMutablePointer<AtomicWrapper>, Self) -> Self { get }
static var nio_atomic_load: (UnsafeMutablePointer<AtomicWrapper>) -> Self { get }
static var nio_atomic_store: (UnsafeMutablePointer<AtomicWrapper>, Self) -> Void { get }
}
extension Bool: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic__Bool
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic__Bool_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic__Bool_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic__Bool_add
public static let nio_atomic_sub = catmc_nio_atomic__Bool_sub
public static let nio_atomic_exchange = catmc_nio_atomic__Bool_exchange
public static let nio_atomic_load = catmc_nio_atomic__Bool_load
public static let nio_atomic_store = catmc_nio_atomic__Bool_store
}
extension Int8: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_int_least8_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_int_least8_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_int_least8_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_int_least8_t_add
public static let nio_atomic_sub = catmc_nio_atomic_int_least8_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_int_least8_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_int_least8_t_load
public static let nio_atomic_store = catmc_nio_atomic_int_least8_t_store
}
extension UInt8: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_uint_least8_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_uint_least8_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_uint_least8_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_uint_least8_t_add
public static let nio_atomic_sub = catmc_nio_atomic_uint_least8_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_uint_least8_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_uint_least8_t_load
public static let nio_atomic_store = catmc_nio_atomic_uint_least8_t_store
}
extension Int16: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_int_least16_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_int_least16_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_int_least16_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_int_least16_t_add
public static let nio_atomic_sub = catmc_nio_atomic_int_least16_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_int_least16_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_int_least16_t_load
public static let nio_atomic_store = catmc_nio_atomic_int_least16_t_store
}
extension UInt16: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_uint_least16_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_uint_least16_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_uint_least16_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_uint_least16_t_add
public static let nio_atomic_sub = catmc_nio_atomic_uint_least16_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_uint_least16_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_uint_least16_t_load
public static let nio_atomic_store = catmc_nio_atomic_uint_least16_t_store
}
extension Int32: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_int_least32_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_int_least32_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_int_least32_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_int_least32_t_add
public static let nio_atomic_sub = catmc_nio_atomic_int_least32_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_int_least32_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_int_least32_t_load
public static let nio_atomic_store = catmc_nio_atomic_int_least32_t_store
}
extension UInt32: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_uint_least32_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_uint_least32_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_uint_least32_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_uint_least32_t_add
public static let nio_atomic_sub = catmc_nio_atomic_uint_least32_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_uint_least32_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_uint_least32_t_load
public static let nio_atomic_store = catmc_nio_atomic_uint_least32_t_store
}
extension Int64: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_long_long
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_long_long_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_long_long_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_long_long_add
public static let nio_atomic_sub = catmc_nio_atomic_long_long_sub
public static let nio_atomic_exchange = catmc_nio_atomic_long_long_exchange
public static let nio_atomic_load = catmc_nio_atomic_long_long_load
public static let nio_atomic_store = catmc_nio_atomic_long_long_store
}
extension UInt64: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_unsigned_long_long
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_unsigned_long_long_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_unsigned_long_long_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_unsigned_long_long_add
public static let nio_atomic_sub = catmc_nio_atomic_unsigned_long_long_sub
public static let nio_atomic_exchange = catmc_nio_atomic_unsigned_long_long_exchange
public static let nio_atomic_load = catmc_nio_atomic_unsigned_long_long_load
public static let nio_atomic_store = catmc_nio_atomic_unsigned_long_long_store
}
#if os(Windows)
extension Int: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_intptr_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_intptr_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_intptr_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_intptr_t_add
public static let nio_atomic_sub = catmc_nio_atomic_intptr_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_intptr_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_intptr_t_load
public static let nio_atomic_store = catmc_nio_atomic_intptr_t_store
}
extension UInt: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_uintptr_t
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_uintptr_t_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_uintptr_t_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_uintptr_t_add
public static let nio_atomic_sub = catmc_nio_atomic_uintptr_t_sub
public static let nio_atomic_exchange = catmc_nio_atomic_uintptr_t_exchange
public static let nio_atomic_load = catmc_nio_atomic_uintptr_t_load
public static let nio_atomic_store = catmc_nio_atomic_uintptr_t_store
}
#else
extension Int: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_long
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_long_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_long_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_long_add
public static let nio_atomic_sub = catmc_nio_atomic_long_sub
public static let nio_atomic_exchange = catmc_nio_atomic_long_exchange
public static let nio_atomic_load = catmc_nio_atomic_long_load
public static let nio_atomic_store = catmc_nio_atomic_long_store
}
extension UInt: NIOAtomicPrimitive {
public typealias AtomicWrapper = catmc_nio_atomic_unsigned_long
public static let nio_atomic_create_with_existing_storage = catmc_nio_atomic_unsigned_long_create_with_existing_storage
public static let nio_atomic_compare_and_exchange = catmc_nio_atomic_unsigned_long_compare_and_exchange
public static let nio_atomic_add = catmc_nio_atomic_unsigned_long_add
public static let nio_atomic_sub = catmc_nio_atomic_unsigned_long_sub
public static let nio_atomic_exchange = catmc_nio_atomic_unsigned_long_exchange
public static let nio_atomic_load = catmc_nio_atomic_unsigned_long_load
public static let nio_atomic_store = catmc_nio_atomic_unsigned_long_store
}
#endif
/// An encapsulation of an atomic primitive object.
///
/// Atomic objects support a wide range of atomic operations:
///
/// - Compare and swap
/// - Add
/// - Subtract
/// - Exchange
/// - Load current value
/// - Store current value
///
/// Atomic primitives are useful when building constructs that need to
/// communicate or cooperate across multiple threads. In the case of
/// SwiftNIO this usually involves communicating across multiple event loops.
///
/// By necessity, all atomic values are references: after all, it makes no
/// sense to talk about managing an atomic value when each time it's modified
/// the thread that modified it gets a local copy!
@available(*, deprecated, message:"please use ManagedAtomic from https://github.com/apple/swift-atomics instead")
public final class NIOAtomic<T: NIOAtomicPrimitive> {
@usableFromInline
typealias Manager = ManagedBufferPointer<Void, T.AtomicWrapper>
/// Create an atomic object with `value`
@inlinable
public static func makeAtomic(value: T) -> NIOAtomic {
let manager = Manager(bufferClass: self, minimumCapacity: 1) { _, _ in }
manager.withUnsafeMutablePointerToElements {
T.nio_atomic_create_with_existing_storage($0, value)
}
return manager.buffer as! NIOAtomic<T>
}
/// Atomically compares the value against `expected` and, if they are equal,
/// replaces the value with `desired`.
///
/// This implementation conforms to C11's `atomic_compare_exchange_strong`. This
/// means that the compare-and-swap will always succeed if `expected` is equal to
/// value. Additionally, it uses a *sequentially consistent ordering*. For more
/// details on atomic memory models, check the documentation for C11's
/// `stdatomic.h`.
///
/// - Parameter expected: The value that this object must currently hold for the
/// compare-and-swap to succeed.
/// - Parameter desired: The new value that this object will hold if the compare
/// succeeds.
/// - Returns: `True` if the exchange occurred, or `False` if `expected` did not
/// match the current value and so no exchange occurred.
@inlinable
public func compareAndExchange(expected: T, desired: T) -> Bool {
return Manager(unsafeBufferObject: self).withUnsafeMutablePointerToElements {
return T.nio_atomic_compare_and_exchange($0, expected, desired)
}
}
/// Atomically adds `rhs` to this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter rhs: The value to add to this object.
/// - Returns: The previous value of this object, before the addition occurred.
@inlinable
@discardableResult
public func add(_ rhs: T) -> T {
return Manager(unsafeBufferObject: self).withUnsafeMutablePointerToElements {
return T.nio_atomic_add($0, rhs)
}
}
/// Atomically subtracts `rhs` from this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter rhs: The value to subtract from this object.
/// - Returns: The previous value of this object, before the subtraction occurred.
@inlinable
@discardableResult
public func sub(_ rhs: T) -> T {
return Manager(unsafeBufferObject: self).withUnsafeMutablePointerToElements {
return T.nio_atomic_sub($0, rhs)
}
}
/// Atomically exchanges `value` for the current value of this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter value: The new value to set this object to.
/// - Returns: The value previously held by this object.
@inlinable
public func exchange(with value: T) -> T {
return Manager(unsafeBufferObject: self).withUnsafeMutablePointerToElements {
return T.nio_atomic_exchange($0, value)
}
}
/// Atomically loads and returns the value of this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Returns: The value of this object
@inlinable
public func load() -> T {
return Manager(unsafeBufferObject: self).withUnsafeMutablePointerToElements {
return T.nio_atomic_load($0)
}
}
/// Atomically replaces the value of this object with `value`.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter value: The new value to set the object to.
@inlinable
public func store(_ value: T) -> Void {
return Manager(unsafeBufferObject: self).withUnsafeMutablePointerToElements {
return T.nio_atomic_store($0, value)
}
}
deinit {
Manager(unsafeBufferObject: self).withUnsafeMutablePointers { headerPtr, elementsPtr in
elementsPtr.deinitialize(count: 1)
headerPtr.deinitialize(count: 1)
}
}
}
@available(*, deprecated)
extension NIOAtomic: Sendable {}
|
apache-2.0
|
65754f4fca4a7dd43aa9776a19df2004
| 56.785489 | 128 | 0.66219 | 4.25703 | false | false | false | false |
oarrabi/RangeSliderView
|
Pod/Classes/KnobView.swift
|
1
|
1097
|
//
// KnobView.swift
// DublinBusMenu
//
// Created by Omar Abdelhafith on 04/02/2016.
// Copyright © 2016 Omar Abdelhafith. All rights reserved.
//
import Foundation
protocol Knob {
#if os(OSX)
var backgroundNormalColor: NSColor { get }
var backgroundHighligtedColor: NSColor { get }
var borderColor: NSColor { get }
var fillColor: NSColor { get }
#else
var backgroundNormalColor: UIColor { get }
var backgroundHighligtedColor: UIColor { get }
var borderColor: UIColor { get }
var fillColor: UIColor { get }
#endif
var frame: CGRect { get }
}
class KnobViewImpl {
static func drawKnob(forView view: Knob, dirtyRect: CGRect) {
var rect = CGRectMake(dirtyRect.minX, dirtyRect.minY, dirtyRect.width, dirtyRect.height)
rect = CGRectInset(rect, 1, 1)
#if os(OSX)
let ovalPath = NSBezierPath(ovalInRect: rect)
#else
let ovalPath = UIBezierPath(ovalInRect: rect)
#endif
view.fillColor.setFill()
ovalPath.fill()
view.borderColor.setStroke()
ovalPath.lineWidth = 1
ovalPath.stroke()
}
}
|
mit
|
ce2d26121098dfbd00ea7ee8243c4be7
| 20.94 | 92 | 0.673358 | 3.859155 | false | false | false | false |
beltex/dshb
|
dshb/WidgetTemperature.swift
|
1
|
3192
|
//
// WidgetTemperature.swift
// dshb
//
// The MIT License
//
// Copyright (C) 2014-2017 beltex <https://beltex.github.io>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
struct WidgetTemperature: WidgetType {
let name = "Temperature"
let displayOrder = 5
var title: WidgetUITitle
var stats = [WidgetUIStat]()
let maxValue = 128.0
fileprivate let sensors: [TemperatureSensor]
init(window: Window = Window()) {
title = WidgetUITitle(name: name, window: window)
do {
// TODO: Add battery temperature from SystemKit? SMC will usually
// have a key for it too (though not always certain which one)
let allKnownSensors = try SMCKit.allKnownTemperatureSensors().sorted
{ $0.name < $1.name }
let allUnknownSensors: [TemperatureSensor]
if CLIUnknownTemperatureSensorsOption.wasSet {
allUnknownSensors = try SMCKit.allUnknownTemperatureSensors()
} else { allUnknownSensors = [ ] }
sensors = allKnownSensors + allUnknownSensors
} catch {
// TODO: Have some sort of warning message under temperature widget
sensors = [ ]
}
for sensor in sensors {
let name: String
if sensor.name == "Unknown" {
name = sensor.name + " (\(sensor.code.toString()))"
} else { name = sensor.name }
stats.append(WidgetUIStat(name: name, unit: .Celsius,
max: maxValue))
}
}
mutating func draw() {
for index in 0..<stats.count {
// TODO: Fix going past bottom of terminal window
//if stats[i].window.point.y >= LINES - 2 { break }
do {
let value = try SMCKit.temperature(sensors[index].code)
stats[index].draw(String(value), percentage: value / maxValue)
} catch {
stats[index].draw("Error", percentage: 0)
// TODO: stats[i].unit = .None
}
}
}
}
|
mit
|
9afe8631fd4a85290b02477aa585293d
| 37 | 80 | 0.614975 | 4.639535 | false | false | false | false |
shazino/ResearchKit
|
samples/ORKSample/ORKSample/ActivityViewController.swift
|
4
|
5520
|
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(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 UIKit
import ResearchKit
enum Activity: Int {
case Survey, Microphone, Tapping
static var allValues: [Activity] {
var idx = 0
return Array(anyGenerator{ return self.init(rawValue: idx++)})
}
var title: String {
switch self {
case .Survey:
return "Survey"
case .Microphone:
return "Microphone"
case .Tapping:
return "Tapping"
}
}
var subtitle: String {
switch self {
case .Survey:
return "Answer 6 short questions"
case .Microphone:
return "Voice evaluation"
case .Tapping:
return "Test tapping speed"
}
}
}
class ActivityViewController: UITableViewController {
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section == 0 else { return 0 }
return Activity.allValues.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("activityCell", forIndexPath: indexPath)
if let activity = Activity(rawValue: indexPath.row) {
cell.textLabel?.text = activity.title
cell.detailTextLabel?.text = activity.subtitle
}
return cell
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard let activity = Activity(rawValue: indexPath.row) else { return }
let taskViewController: ORKTaskViewController
switch activity {
case .Survey:
taskViewController = ORKTaskViewController(task: StudyTasks.surveyTask, taskRunUUID: NSUUID())
case .Microphone:
taskViewController = ORKTaskViewController(task: StudyTasks.microphoneTask, taskRunUUID: NSUUID())
do {
let defaultFileManager = NSFileManager.defaultManager()
// Identify the documents directory.
let documentsDirectory = try defaultFileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
// Create a directory based on the `taskRunUUID` to store output from the task.
let outputDirectory = documentsDirectory.URLByAppendingPathComponent(taskViewController.taskRunUUID.UUIDString)
try defaultFileManager.createDirectoryAtURL(outputDirectory, withIntermediateDirectories: true, attributes: nil)
taskViewController.outputDirectory = outputDirectory
}
catch let error as NSError {
fatalError("The output directory for the task with UUID: \(taskViewController.taskRunUUID.UUIDString) could not be created. Error: \(error.localizedDescription)")
}
case .Tapping:
taskViewController = ORKTaskViewController(task: StudyTasks.tappingTask, taskRunUUID: NSUUID())
}
taskViewController.delegate = self
navigationController?.presentViewController(taskViewController, animated: true, completion: nil)
}
}
extension ActivityViewController : ORKTaskViewControllerDelegate {
func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?) {
// Handle results using taskViewController.result
taskViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
|
bsd-3-clause
|
1697316fe5d5da81e283d1668d0206c0
| 41.790698 | 182 | 0.681884 | 5.702479 | false | false | false | false |
iosdevelopershq/code-challenges
|
CodeChallenge/Challenges/LetterCombinationsOfPhoneNumber/Entries/BugKrushaLetterCombinationsOfPhoneNumberEntry.swift
|
1
|
1806
|
//
// BugKrusha.swift
// CodeChallenge
//
// Created by Jon-Tait Beason on 11/2/15.
// Copyright © 2015 iosdevelopers. All rights reserved.
//
import Foundation
let bugKrushaLetterCombinationOfPhoneNumberEntry = CodeChallengeEntry<LetterCombinationsOfPhoneNumberChallenge>(name: "bugKrusha") { input in
return getCombinations(digitString: input)
}
private enum Digit: String {
case Two = "abc"
case Three = "def"
case Four = "ghi"
case Five = "jkl"
case Six = "mno"
case Seven = "pqrs"
case Eight = "tuv"
case Nine = "wxyz"
}
private func getCharactersForNumber(number: String) -> Digit? {
switch number {
case "2": return Digit.Two
case "3": return Digit.Three
case "4": return Digit.Four
case "5": return Digit.Five
case "6": return Digit.Six
case "7": return Digit.Seven
case "8": return Digit.Eight
case "9": return Digit.Nine
default: break
}
return nil
}
private func getCombinations(digitString: String) -> [String] {
var arrayOfCharacterSets = [String]()
for (index, character) in digitString.characters.enumerated() {
if let charactersForNumber = getCharactersForNumber(number: "\(character)")?.rawValue {
if index == 0 {
arrayOfCharacterSets = charactersForNumber.characters.map { "\($0)" }
} else {
var tempArray = [String]()
for char in charactersForNumber.characters {
for characterSet in arrayOfCharacterSets {
let newString = characterSet + "\(char)"
tempArray.append(newString)
}
}
arrayOfCharacterSets = tempArray
}
}
}
return arrayOfCharacterSets
}
|
mit
|
bd62aed9df3d928e8c6b8d24ef77e082
| 26.769231 | 141 | 0.607202 | 4.307876 | false | false | false | false |
anzfactory/QiitaCollection
|
QiitaCollection/Array+App.swift
|
1
|
752
|
//
// Array+App.swift
// QiitaCollection
//
// Created by ANZ on 2015/02/22.
// Copyright (c) 2015年 anz. All rights reserved.
//
extension Array {
mutating func removeObject<E: Equatable>(object: E) -> Array {
for var i = 0; i < self.count; i++ {
if self[i] as! E == object {
self.removeAtIndex(i)
break
}
}
return self
}
static func convert(dict: [[String: String]], key: String) -> [T] {
var result: [T] = [T]()
for item in dict {
if let keyValue = item[key] {
if keyValue is T {
result.append(keyValue as! T)
}
}
}
return result
}
}
|
mit
|
67197147abcfe0777f29e0a1c20e2c8c
| 23.193548 | 71 | 0.464 | 3.88601 | false | false | false | false |
Liqiankun/DLSwift
|
Swift/MyPlayground.playground/Contents.swift
|
1
|
151
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let a = 200
let b = 100
let c = a + b
str += ":)"
|
mit
|
830573e1a4938bb4b2477abde6914b60
| 10.692308 | 52 | 0.615894 | 3.081633 | false | false | false | false |
pkc456/Roastbook
|
Roastbook/Roastbook/View Controller/Feed View Controller/FirstViewController.swift
|
1
|
1666
|
//
// FirstViewController.swift
// Roastbook
//
// Created by Pradeep Choudhary on 3/28/17.
// Copyright © 2017 Pardeep chaudhary. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableviewFeed: UITableView!
var arrayMusic : Array<Feed>?
override func viewDidLoad() {
super.viewDidLoad()
tableviewFeed.rowHeight = UITableViewAutomaticDimension
tableviewFeed.estimatedRowHeight = 70.0
fetchFeedData()
}
private func fetchFeedData(){
arrayMusic = FeedBusinessLayer.sharedInstance.getFeedInformationDataArray()
tableviewFeed.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 90.0
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRow = self.arrayMusic?.count ?? 0
return numberOfRow
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCell", for: indexPath) as! FeedTableViewCell
let curentFeed = arrayMusic?[indexPath.row]
cell.configureCellWithData(feedInformationModelObject: curentFeed!)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
|
mit
|
d5ab8dbf3df88ea4ec1f48e865bcdf3f
| 29.272727 | 123 | 0.688288 | 5.219436 | false | false | false | false |
hongqingWang/HQSwiftMVVM
|
HQSwiftMVVM/HQSwiftMVVM/Classes/View/Vistor/HQVistorView.swift
|
1
|
10032
|
//
// HQVistorView.swift
// HQSwiftMVVM
//
// Created by 王红庆 on 2017/7/11.
// Copyright © 2017年 王红庆. All rights reserved.
//
import UIKit
class HQVistorView: UIView {
/// 注册按钮
lazy var registerButton: UIButton = UIButton(hq_title: "注册", color: UIColor.orange, backImageName: "common_button_white_disable")
/// 登录按钮
lazy var loginButton: UIButton = UIButton(hq_title: "登录", color: UIColor.darkGray, backImageName: "common_button_white_disable")
/// 设置访客视图信息字典[imageName / message]
var vistorInfo: [String: String]? {
didSet {
guard let imageName = vistorInfo?["imageName"],
let message = vistorInfo?["message"]
else {
return
}
tipLabel.text = message
if imageName == "" {
startAnimation()
return
}
iconImageView.image = UIImage(named: imageName)
houseImageView.isHidden = true
maskImageView.isHidden = true
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 旋转视图动画
fileprivate func startAnimation() {
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = 2 * Double.pi
anim.repeatCount = MAXFLOAT
anim.duration = 15
// 设置动画一直保持转动,如果`iconImageView`被释放,动画会被一起释放
anim.isRemovedOnCompletion = false
// 将动画添加到图层
iconImageView.layer.add(anim, forKey: nil)
}
// MARK: - 私有控件
/// 图像视图
fileprivate lazy var iconImageView: UIImageView = UIImageView(hq_imageName: "visitordiscover_feed_image_smallicon")
/// 遮罩视图
fileprivate lazy var maskImageView: UIImageView = UIImageView(hq_imageName: "visitordiscover_feed_mask_smallicon")
/// 小房子
fileprivate lazy var houseImageView: UIImageView = UIImageView(hq_imageName: "visitordiscover_feed_image_house")
/// 提示标签
fileprivate lazy var tipLabel: UILabel = UILabel(hq_title: "关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜")
}
// MARK: - 设置访客视图界面
extension HQVistorView {
fileprivate func setupUI() {
backgroundColor = UIColor.hq_color(withHex: 0xEDEDED)
addSubview(iconImageView)
addSubview(maskImageView)
addSubview(houseImageView)
addSubview(tipLabel)
addSubview(registerButton)
addSubview(loginButton)
tipLabel.textAlignment = .center
// 取消 autoresizing
for v in subviews {
v.translatesAutoresizingMaskIntoConstraints = false
}
/*
利用原生自动布局代码进行自动布局
自动布局本质公式:
firstItem.firstAttribute {==,<=,>=} secondItem.secondAttribute * multiplier + constant
*/
let margin: CGFloat = 20.0
/// 图像视图
addConstraint(NSLayoutConstraint(item: iconImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: iconImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1.0,
constant: -60))
/// 小房子
addConstraint(NSLayoutConstraint(item: houseImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: iconImageView,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: houseImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: iconImageView,
attribute: .centerY,
multiplier: 1.0,
constant: 0))
/// 提示标签
addConstraint(NSLayoutConstraint(item: tipLabel,
attribute: .centerX,
relatedBy: .equal,
toItem: iconImageView,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: tipLabel,
attribute: .top,
relatedBy: .equal,
toItem: iconImageView,
attribute: .bottom,
multiplier: 1.0,
constant: margin))
addConstraint(NSLayoutConstraint(item: tipLabel,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 236))
/// 注册按钮
addConstraint(NSLayoutConstraint(item: registerButton,
attribute: .left,
relatedBy: .equal,
toItem: tipLabel,
attribute: .left,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: registerButton,
attribute: .top,
relatedBy: .equal,
toItem: tipLabel,
attribute: .bottom,
multiplier: 1.0,
constant: margin))
addConstraint(NSLayoutConstraint(item: registerButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 100))
/// 登录按钮
addConstraint(NSLayoutConstraint(item: loginButton,
attribute: .right,
relatedBy: .equal,
toItem: tipLabel,
attribute: .right,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: loginButton,
attribute: .top,
relatedBy: .equal,
toItem: registerButton,
attribute: .top,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: loginButton,
attribute: .width,
relatedBy: .equal,
toItem: registerButton,
attribute: .width,
multiplier: 1.0,
constant: 0))
/// 遮罩视图布局,采用 VFL 布局
/*
VFL 可视化语言
多用于连续参照关系,如遇到居中对其,通常多使用参照
- `H`水平方向
- `V`竖直方向
- `|`边界
- `[]`包含控件的名称字符串,对应关系在`views`字典中定义
- `()`定义控件的宽/高,可以在`metrics`中指定
*/
/*
views: 定义 VFL 中控件名称和实际名称的映射关系
metrics: 定义 VFL 中 () 内指定的常数映射关系,防止在代码中出现魔法数字
*/
let viewDict: [String: Any] = ["maskImageView": maskImageView,
"registerButton": registerButton]
let metrics = ["spacing": -35]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[maskImageView]-0-|",
options: [],
metrics: nil,
views: viewDict))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[maskImageView]-(spacing)-[registerButton]",
options: [],
metrics: metrics,
views: viewDict))
}
}
|
mit
|
2cd929c261adcf42294bb8580a89b627
| 40.792035 | 133 | 0.420222 | 6.442701 | false | false | false | false |
MobileOrg/mobileorg
|
Classes/Utilities/String+Attributes.swift
|
1
|
5194
|
//
// String+Attributes.swift
// MobileOrg
//
// Created by Artem Loenko on 13/10/2019.
// Copyright © 2019 Artem Loenko.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
import Foundation
extension String {
func asTitle(done: Bool = false) -> NSAttributedString {
let attributes: [ NSAttributedString.Key: Any ] = [
.font : UIFont.preferredFont(forTextStyle: .body),
.foregroundColor: done ? UIColor.mo_tertiaryText : UIColor.mo_text
]
return NSAttributedString(string: self, attributes: attributes)
}
func asNote(done: Bool = false) -> NSAttributedString {
let attributes: [ NSAttributedString.Key: Any ] = [
.font : UIFont.preferredFont(forTextStyle: .footnote),
.foregroundColor: done ? UIColor.mo_tertiaryText : UIColor.mo_secondaryText
]
return NSAttributedString(string: self, attributes: attributes)
}
func asStatus(done: Bool = false) -> NSAttributedString {
let attributes: [ NSAttributedString.Key: Any ] = [
.font : UIFont.systemFont(ofSize: UIFont.preferredFont(forTextStyle: .caption1).pointSize, weight: .semibold),
.foregroundColor: done ? UIColor.mo_tertiaryText : UIColor.mo_accent
]
return NSAttributedString(string: self, attributes: attributes)
}
func asPriority(done: Bool = false) -> NSAttributedString {
let attributes: [ NSAttributedString.Key: Any ] = [
.font : UIFont.preferredFont(forTextStyle: .caption1),
.foregroundColor: done ? UIColor.mo_tertiaryText : UIColor.mo_secondaryText,
.underlineStyle: NSUnderlineStyle.double.rawValue
]
return NSAttributedString(string: self, attributes: attributes)
}
func asTags(done: Bool = false) -> NSAttributedString {
let attributes: [ NSAttributedString.Key: Any ] = [
.font : UIFont.preferredFont(forTextStyle: .caption1),
.foregroundColor: done ? UIColor.mo_tertiaryText : UIColor.mo_secondaryText
]
return NSAttributedString(string: self, attributes: attributes)
}
func asScheduled(with date: Date, done: Bool = false) -> NSAttributedString {
return self.with(date: date, done: done)
}
func asDeadline(with date: Date, done: Bool = false) -> NSAttributedString {
return self.with(date: date, done: done)
}
func asCreatedAt(with date: Date) -> NSAttributedString {
return self.with(date: date, relative: true)
}
// MARK: Private
private func with(date: Date, done: Bool = false, relative: Bool = false) -> NSAttributedString {
let attributes: [ NSAttributedString.Key: Any ] = [
.font : UIFont.preferredFont(forTextStyle: .caption1),
.foregroundColor: done ? UIColor.mo_tertiaryText : UIColor.mo_secondaryText
]
// FIXME: custom attributes for the date when overdue or coming soon
let _date = self.format(date: date, relative: relative)
return NSAttributedString(string: "\(self)\(_date)", attributes: attributes)
}
private func format(date: Date, relative: Bool = false) -> String {
if relative {
if #available(iOS 13, *) {
return StoredPropertiesHolder._relativeDateFormatter.localizedString(for: date, relativeTo: Date())
}
}
return StoredPropertiesHolder._dateFormatter.string(from: date)
}
private struct StoredPropertiesHolder {
static var _dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .short // FIXME: Remove time if it is midnight
return formatter
}()
@available(iOS 13.0, *)
static var _relativeDateFormatter: RelativeDateTimeFormatter = {
let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .numeric
formatter.unitsStyle = .full
return formatter
}()
}
}
extension NSMutableAttributedString {
@discardableResult
func newLine() -> Self {
self.append(NSAttributedString(string: "\n"))
return self
}
@discardableResult
func space() -> Self {
self.append(NSAttributedString(string: " "))
return self
}
@discardableResult
func tab() -> Self {
self.append(NSAttributedString(string: "\t"))
return self
}
}
|
gpl-2.0
|
b9f0038b9223736941a453df1ebd11d4
| 36.905109 | 122 | 0.650876 | 4.66158 | false | false | false | false |
xiaoyouPrince/DYLive
|
DYLive/DYLive/Classes/Home/Controller/AmuseViewController.swift
|
1
|
1495
|
//
// AmuseViewController.swift
// DYLive
//
// Created by 渠晓友 on 2017/5/3.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseViewController: BaceAnchorViewController {
// MARK: - 懒加载
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.creatMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
}
extension AmuseViewController{
override func buildUI() {
super.buildUI()
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
extension AmuseViewController{
override func loadData() {
// 1.给父类的数据赋值
super.baceVM = amuseVM
// 2.请求数据
self.amuseVM.loadAmuseData {
// 2.1 刷新表格
self.collectionView.reloadData()
// 2.2 刷新上边的menuView
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
// 调用父类的加载完成方法
self.loadDataFinished()
}
}
}
|
mit
|
ab6c9bca0a42f5c08fe5697727f2287d
| 21.83871 | 97 | 0.581215 | 4.783784 | false | false | false | false |
apple/swift-tools-support-core
|
Sources/TSCBasic/RegEx.swift
|
2
|
2236
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
/// A helpful wrapper around NSRegularExpression.
/// - SeeAlso: NSRegularExpression
public struct RegEx {
private let regex: NSRegularExpression
public typealias Options = NSRegularExpression.Options
/// Creates a new Regex using `pattern`.
///
/// - Parameters:
/// - pattern: A valid Regular Expression pattern
/// - options: NSRegularExpression.Options on how the RegEx should be processed.
/// - Note: Deliminators must be double escaped. Once for Swift and once for RegEx.
/// Example, to math a negative integer: `RegEx(pattern: "-\d")` -> `RegEx(pattern: "-\\d")`
/// - SeeAlso: NSRegularExpression
/// - Throws: An Error if `pattern` is an invalid Regular Expression.
public init(pattern: String, options: Options = []) throws {
self.regex = try NSRegularExpression(pattern: pattern, options: options)
}
/// Returns match groups for every match of the Regex.
///
/// For every match in the string, it constructs the collection
/// of groups matched.
///
/// RegEx(pattern: "([a-z]+)([0-9]+)").matchGroups(in: "foo1 bar2 baz3")
///
/// Returns `[["foo", "1"], ["bar", "2"], ["baz", "3"]]`.
///
/// - Parameters:
/// - in: A string to check for matches to the whole Regex.
/// - Returns: A collection where each elements is the collection of matched groups.
public func matchGroups(in string: String) -> [[String]] {
let nsString = NSString(string: string)
return regex.matches(in: string, options: [], range: NSMakeRange(0, nsString.length)).map{ match -> [String] in
return (1 ..< match.numberOfRanges).map { idx -> String in
let range = match.range(at: idx)
return range.location == NSNotFound ? "" : nsString.substring(with: range)
}
}
}
}
|
apache-2.0
|
19aace5692bf446eee0d4aa2ecafebe9
| 40.407407 | 119 | 0.635063 | 4.384314 | false | false | false | false |
xwu/NumericAnnex
|
Tests/NumericAnnexTests/RandomXorshiftTests.swift
|
1
|
11971
|
import XCTest
@testable import NumericAnnex
class RandomXorshiftTests : XCTestCase {
func testEntropy() {
guard let rng = Random() else {
XCTFail()
return
}
XCTAssertTrue(rng.state != (0, 0))
let mock = {
return nil as [UInt64]?
}
XCTAssertNil(Random(_entropy: mock()))
}
func test_1_2() {
let rng = Random(state: (1, 2))
// Values were generated using the reference implementation found at:
// http://xoroshiro.di.unimi.it/xorshift128plus.c
let expected: [UInt64] = [
3,
8388645,
33816707,
70368778527840,
211106267172129,
281552312399723,
352084508939685,
648800200157934532,
2540241598295339419,
2648407162339308712,
2668752799858137237,
2693699070923777171,
4963962142036894822,
11906738374415673757,
9632391838565739090,
2066554175270807792,
2494022894752328945,
1356498747469623086,
11211414770921777427,
10429009827004399351,
2323958476090753392,
3568022355029630745,
66653323867787511,
2202670577644624798,
12857773250674142713,
4201717447333134628,
15638699059651815979,
4364251867564744889,
7660026492187243788,
3800851612386782149,
9605385339319476694,
2406190703679268226,
846469172938628641,
5337113899023465296,
15781852488115071549,
15354462637857246627,
11103786004116532909,
10104343325409002424,
12295544783831320534,
9091324406814034890,
6628842478985115447,
12899089858988772368,
16555193421103270775,
5182223508147526313,
1789523054416386623,
8305247958687497212,
4332901280696262112,
4830599505179982300,
16562699778378001540,
4301002138587088699,
16887648884050224867,
8961088417938801842,
18120357346625319699,
5062957422512203146,
14533691471387576319,
17893283120539033726,
8933729491225170482,
7703252517382402300,
4527677543428710360,
11852647525519638421,
14323485818621793660,
1603981125980772416,
10667357879029765177,
12618821681808242380,
15688459637854892994,
16858336139413885781,
8192223518607711332,
15086078044025798325,
7820396459134496922,
10260666624710253760,
12864353747813168684,
3349112384258896183,
17079950137619159659,
13693940288920244054,
4120914027243693443,
16513947166147576873,
7753202820822651981,
6626804775540638270,
6691531028144752467,
1848899687106318854,
13681393795236538282,
16157808923290844879,
14402137377069136975,
10721861038970349125,
11713871874537672148,
17636397933591539986,
4203420467318374,
14279516174659940213,
5030216290135979793,
12431123221355774434,
3353451983739559286,
1982730773867159337,
4287093158672282079,
10427894759339841969,
10992708284980487886,
9826778016246262346,
598098170064759435,
5132675295537973900,
2977953682469803199,
7095603002820811521,
14473363250705030589,
5815164147694210911,
893364492343289163,
7223131833749622824,
8283693734360236205,
18098811217686597526,
13472185143670172098,
4921989762323275340,
1122032220579367383,
1580787425287478212,
12971777770367737930,
14141602702208488443,
8934944843784058286,
6607626240826326523,
6849503334803588545,
8945087483095516625,
11138928521629212103,
17790276629890369045,
1578334294751373582,
2806185787680672391,
2659421138426664381,
5725303483961243766,
6184936954810297634,
939427805219677289,
7877825174927605138,
17042809939415329651,
7007032053414486723,
708948147059678574,
5807695797323831903,
10654984825451839699,
658076860194383956,
6054460744441943985,
18125771188890900160,
12455829269468258300,
7801377697876303864,
1155650389744014674,
14837203265123196363,
14611150480548774776,
11295561405428659877,
14652736317255425712,
10357309030900164003,
11362376726255131814,
17481625516190528824,
10063769529741033785,
10070196982447573973,
10858208953628516990,
8316996154212129605,
1966992145466461251,
9534492825751960063,
17331020003238783005,
4055301956728939736,
15747646385425363016,
5713890891727580694,
16363438003468365099,
6059680446507887551,
15805989924395708713,
7701919984793556335,
10881930014020511227,
16418946584288169403,
149521899493351325,
12534253806982171802,
11139483896115829864,
308345381091007206,
11578160645028040120,
16035213593244811876,
2483577470144144779,
2382343175518057727,
4467734399270823599,
6604294351011625227,
8344523632028305909,
13176362180825574816,
5057251926377527702,
4615034777510676815,
716527652147291657,
2255853362627944573,
1040521049739732381,
8767117186808380895,
4542310411533510448,
17298777313319151232,
6001563173036790655,
6632155663823324745,
260008012886308771,
8125529425889733497,
8459386663958119024,
478351272518501156,
16245194212119991188,
16067636681512186800,
13291772728582610504,
977325433216839797,
316583137798752960,
16331330055435573991,
13872944562523015302,
14073886698853620462,
10932979021145220513,
9767459346543799817,
3499076079183291818,
16794441505776618298,
2728580826238923060,
9982312178378568539,
10174783523235389589,
]
for (index, value) in zip(0..., rng.prefix(expected.count)) {
XCTAssertEqual(expected[index], value)
}
}
func test_42_42() {
let rng = Random(state: (42, 42))
// Values were generated using the reference implementation found at:
// http://xoroshiro.di.unimi.it/xorshift128plus.c
let expected: [UInt64] = [
84,
352322923,
363332930,
2955487621802017,
5910974877560714,
5984590265422244,
3102369235448484,
8794055518707935431,
11715271280642458577,
11121097408281568494,
11123324466519438486,
11813657815484460077,
15967982470865911351,
16027149834536272202,
14579330570455427858,
17901094324785512346,
7299173581280891606,
9598572314193889241,
6321253227128400616,
12069832686681671119,
8362407854952761049,
4240112657210925663,
8298289508193808350,
5492533585219385488,
3424077862959065976,
16763914594806242130,
1218199477047421836,
7673362999398496465,
5794997430478554395,
7270864472693218401,
6217237324811287380,
5931838762482735489,
2650854048920189469,
15912113305156886344,
12742758016124380936,
4295159997148736665,
377715972074097257,
2850808977988091172,
8491599958789257052,
9324795365995984871,
8211242245495735455,
17422811286952683550,
13418142500587507919,
5930788801560645895,
6741187258797332316,
10118554851581664695,
115595561983548771,
8043906809085936116,
11823913423613696098,
14518129458877160117,
8343257749050278180,
13733556794904034707,
8684565082910747967,
3120612299320189264,
12303575766779633627,
12795815681716387847,
9809457554914526522,
8920375781289094670,
1993124226495641609,
1733459562229749526,
17111289711044275575,
17744781264274534442,
8365870118406280068,
3394993270264399372,
17743599368353179843,
10866568771989044846,
5256627558940251261,
1523012312127918050,
4830133096723200725,
15678901288667906426,
12456461226754166128,
11853493959818320069,
12499595671348820672,
1087309203085082628,
8913015614641765480,
7628423184432057398,
3580904369680909773,
803445358366289622,
11594309456042139689,
4033442513255026894,
1433661196805234850,
12192207108666652295,
14586722686201389331,
6181944170276831130,
764669472652961289,
889048737081245825,
12138836305257926083,
888086957463834642,
2390515631187897836,
2446868417045655461,
11015187241185530986,
10036793306822931734,
12334486703513775025,
5108691882609665754,
9514819673388488194,
2273142206574835406,
14437507437202006078,
3730714957717498326,
2872726062891204564,
3798333342152566218,
16669861045337712380,
13102670696856779254,
10908263394212623530,
10676532138494980932,
15489857964433950539,
7937142546638092754,
13417642705898345692,
13600811864162143445,
9477162617086519863,
10624389419236725677,
7441007177458375221,
16546523980542070736,
17024880117250866739,
18039589907068853828,
17555160936737332920,
7083735549926373853,
4420365159915317578,
16029263747729017986,
9972633967851497325,
7138346049748499288,
13270188884066368590,
9463122843754064712,
11942301208543755374,
2622930306965644834,
17433830334026038459,
8169816655638087827,
12836491954871888680,
14528181774076346116,
15183710998958962615,
4028984353527250283,
11816946909171962632,
4065563158656645039,
15930560328422184085,
10849511457716257195,
12483535526530318894,
11367233570755787020,
17859411692174119294,
1306416274365004041,
3368018692405648683,
2913934462501646291,
5248772458214493708,
1765279421221167687,
3394064100077089893,
3629895405441912055,
12299657979994244302,
16008402201086829007,
5458106375116620038,
16730533680684926710,
505844743719408298,
4843472813567170388,
12363442002524133152,
11170145896500987331,
8329207398927125713,
11036379913765865888,
2618306290991370477,
1741543416193582741,
5146591056299389583,
7865421083469608492,
7071530335411999512,
9836070694521579615,
8260774949340336056,
551175967640246701,
2030281209927081181,
16417504261929240858,
14442013933768465970,
3838236631860248808,
16071916515461671872,
12960610862896350943,
5289632148835048055,
1827674498314689410,
10789868859655831854,
11210908846547680913,
13945725155205586140,
10261895380415373153,
4016205272160740838,
16497458846534660898,
9795538644692598039,
18053416664331168520,
3256852140039313454,
12501759108812025258,
7098503516961967472,
11650064198712856478,
1593512087519278921,
10264399986535021899,
3537643041203047414,
5650861041254369406,
15204856943036229121,
14012199752722101339,
9164702022019181819,
17759817422978365807,
9543001839860678976,
11899169602608869168,
1442073933760388807,
11121798007280630550,
6079263746152188428,
11994280689457877647,
7959160577587456781,
2831973816179963895,
309986269562773395,
6500631040839990712,
]
for (index, value) in zip(0..., rng.prefix(expected.count)) {
XCTAssertEqual(expected[index], value)
}
}
static var allTests = [
("testEntropy", testEntropy),
("test_1_2", test_1_2),
("test_42_42", test_42_42),
]
}
|
mit
|
18dc82e668b366c2646842bd33cbac0e
| 25.780761 | 73 | 0.695681 | 2.864561 | false | false | false | false |
matthew-healy/TableControlling
|
TableControllingTests/TestHelpers/AssertSymmetricallyEqual.swift
|
1
|
2333
|
import XCTest
/**
Asserts that the equality operation on an `Equatable` type `T` is symmetric.
i.e., it asserts that `t_1 == t_2` if and only if `t_2 == t_1`.
This is a dumb function to need, because in reality equality should be an
equivalence relation, and therefore guarantee symmetry, but `XCTAssertEqual`
doesn't check in both directions. This is only really necessary when actually
defining `==` for a type.
- parameter expression1: An `@autoclosure` which evaluates to something of type `T`.
- parameter expression2: An `@autoclosure` which evaluates to something of type `T`.
- parameter message: The message to print in case of failure. Defaults to "AssertSymmetricallyEqual failed."
*/
func AssertSymmetricallyEqual<T: Equatable>(
_ expression1: @autoclosure () throws -> T,
_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "AssertSymmetricallyEqual failed.",
file: StaticString = #file,
line: UInt = #line
) {
XCTAssertEqual(expression1, expression2, message(), file: file, line: line)
XCTAssertEqual(expression2, expression1, message(), file: file, line: line)
}
/**
Asserts that the non-equality operation on an `Equatable` type `T` is symmetric.
i.e., it asserts that `t_1 != t_2` if and only if `t_2 != t_1`.
This is a dumb function to need, because in reality equality should be an
equivalence relation, and therefore guarantee symmetry, but `XCTAssertNotEqual`
doesn't check in both directions. This is only really necessary when actually
defining `==` (and therefore `!=`) for a type.
- parameter expression1: An `@autoclosure` which evaluates to something of type `T`.
- parameter expression2: An `@autoclosure` which evaluates to something of type `T`.
- parameter message: The message to print in case of failure. Defaults to "AssertSymmetricallyNotEqual failed."
*/
func AssertSymmetricallyNotEqual<T: Equatable>(
_ expression1: @autoclosure () throws -> T,
_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "AssertSymmetricallyNotEqual failed.",
file: StaticString = #file,
line: UInt = #line
) {
XCTAssertNotEqual(expression1, expression2, message(), file: file, line: line)
XCTAssertNotEqual(expression2, expression1, message(), file: file, line: line)
}
|
mit
|
fe539d77ac2f7840bdfb3fa85cab0286
| 46.612245 | 112 | 0.718817 | 4.158645 | false | false | false | false |
benbahrenburg/KeyStorage
|
KeyStorage/Classes/KeyStorageKeyChainProvider.swift
|
1
|
17560
|
//
// KeyStorage - Simplifying securely saving key information
// KeyStorageKeyChainProvider.swift
//
// Created by Ben Bahrenburg on 3/23/16.
// Copyright © 2019 bencoding.com. All rights reserved.
//
import Foundation
import Security
/**
Storage Provider that saves/reads keys from the Keychain
*/
public final class KeyStorageKeyChainProvider: KeyStorage {
private let lock = NSLock()
private var accessGroup: String?
private var accessible = KeyChainInfo.accessibleOption.afterFirstUnlock
private var serviceName = Bundle.main.bundleIdentifier ?? "KeyStorageKeyChainProvider"
private var crypter: KeyStorageCrypter?
private var synchronizable: Bool = true
public init(serviceName: String? = nil, accessGroup: String? = nil, accessible: KeyChainInfo.accessibleOption = .afterFirstUnlock, cryptoProvider: KeyStorageCrypter? = nil, synchronizable: Bool = true) {
self.accessGroup = accessGroup
self.accessible = accessible
self.serviceName = serviceName ?? self.serviceName
self.crypter = cryptoProvider
self.synchronizable = synchronizable
}
@discardableResult public func setStruct<T: Codable>(forKey: String, value: T?) -> Bool {
guard let data = try? JSONEncoder().encode(value) else {
return removeKey(forKey: forKey)
}
return saveData(forKey: forKey, value: data)
}
public func getStruct<T>(forKey: String, forType: T.Type) -> T? where T : Decodable {
if let data = load(forKey: forKey) {
return try! JSONDecoder().decode(forType, from: data)
}
return nil
}
@discardableResult public func setStructArray<T: Codable>(forKey: String, value: [T]) -> Bool {
let data = value.compactMap { try? JSONEncoder().encode($0) }
if data.count == 0 {
return removeKey(forKey: forKey)
}
return saveData(forKey: forKey, value: data)
}
public func getStructArray<T>(forKey: String, forType: T.Type) -> [T] where T : Decodable {
if let data = loadArray(forKey: forKey) {
return data.map { try! JSONDecoder().decode(forType, from: $0) }
}
return []
}
@discardableResult public func setURL(forKey: String, value: URL) -> Bool {
if let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false) {
return saveData(forKey: forKey, value: data)
}
return false
}
public func getURL(forKey: String) -> URL? {
guard let data = load(forKey: forKey) else {
return nil
}
if let result = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? URL {
return result
}
return nil
}
public func getURL(forKey: String, defaultValue: URL) -> URL {
guard let data = load(forKey: forKey) else {
return defaultValue
}
if let result = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? URL {
return result
}
return defaultValue
}
@discardableResult public func setObject(forKey: String, value: NSCoding) -> Bool {
// let data = NSKeyedArchiver.archivedData(withRootObject: value)
if let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false) {
return saveData(forKey: forKey, value: data)
}
return false
}
@discardableResult public func setData(forKey: String, value: Data) -> Bool {
return saveData(forKey: forKey, value: value)
}
@discardableResult public func setString(forKey: String, value: String) -> Bool {
if let data = value.data(using: .utf8) {
return saveData(forKey: forKey, value: data)
}
return false
}
@discardableResult public func setInt(forKey: String, value: Int) -> Bool {
return saveObject(forKey: forKey, value: NSNumber(value: value))
}
@discardableResult public func setDouble(forKey: String, value: Double) -> Bool {
return saveObject(forKey: forKey, value: NSNumber(value: value))
}
@discardableResult public func setFloat(forKey: String, value: Float) -> Bool {
return saveObject(forKey: forKey, value: NSNumber(value: value))
}
@discardableResult public func setDate(forKey: String, value: Date) -> Bool {
return saveObject(forKey: forKey, value: NSNumber(value: value.timeIntervalSince1970))
}
@discardableResult public func setBool(forKey: String, value: Bool) -> Bool {
return saveObject(forKey: forKey, value: NSNumber(value: value))
}
/**
Removes the stored value for the provided key.
- Parameter forKey: The key that should have it's stored value removed
- Returns: Bool is returned with the status of the removal operation. True for success, false for error.
*/
@discardableResult public func removeKey(forKey: String) -> Bool {
lock.lock()
defer { lock.unlock() }
let query = buildQuery(forKey)
let status = SecItemDelete(query as CFDictionary)
guard status != errSecItemNotFound else { return true }
if status != errSecSuccess {
let error = KeyChainInfo.errorDetail.unhandledError(status: status).localizedDescription
print("Error Removing key \(forKey) from keychain. Error: \(error) ")
return false
}
return true
}
/**
Returns a Bool indicating if a stored value exists for the provided key.
- Parameter forKey: The key to check if there is a stored value for.
- Returns: Bool is returned true if a stored value exists or false if there is no stored value.
*/
public func exists(forKey: String) -> Bool {
let results = load(forKey: forKey)
return results != nil
}
/**
Returns Data? (optional) for a provided key. Nil is returned if no stored value is found.
- Parameter forKey: The key used to return a stored value
- Returns: The Data? (optional) for the provided key
*/
public func getData(forKey: String) -> Data? {
return load(forKey: forKey)
}
/**
Returns String? (optional) for a provided key. Nil is returned if no stored value is found.
- Parameter forKey: The key used to return a stored value
- Returns: The String? (optional) for the provided key
*/
public func getString(forKey: String) -> String? {
if let data = load(forKey: forKey) {
return String(data: data, encoding: String.Encoding.utf8)
}
return nil
}
/**
Returns String for a provided key. If no stored value is available, defaultValue is returned.
- Parameter forKey: The key used to return a stored value
- Parameter defaultValue: The value to be returned if no stored value is available
- Returns: The String for the provided key
*/
public func getString(forKey: String, defaultValue: String) -> String {
if let data = load(forKey: forKey) {
return String(data: data, encoding: String.Encoding.utf8)!
}
return defaultValue
}
public func getInt(forKey: String) -> Int {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return 0
}
return result.intValue
}
public func getInt(forKey: String, defaultValue: Int) -> Int {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return defaultValue
}
return result.intValue
}
public func getDouble(forKey: String) -> Double {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return 0
}
return result.doubleValue
}
public func getDouble(forKey: String, defaultValue: Double) -> Double {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return defaultValue
}
return result.doubleValue
}
public func getFloat(forKey: String) -> Float {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return 0
}
return result.floatValue
}
public func getFloat(forKey: String, defaultValue: Float) -> Float {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return defaultValue
}
return result.floatValue
}
public func getBool(forKey: String) -> Bool {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return false
}
return result.boolValue
}
public func getBool(forKey: String, defaultValue: Bool) -> Bool {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return defaultValue
}
return result.boolValue
}
public func getDate(forKey: String) -> Date? {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return nil
}
return Date(timeIntervalSince1970: TimeInterval(truncating: result))
}
public func getDate(forKey: String, defaultValue: Date) -> Date {
guard let result = getObject(forKey: forKey) as? NSNumber else {
return defaultValue
}
return Date(timeIntervalSince1970: TimeInterval(truncating: result))
}
/**
Removes all of the keys stored with the provider
- Returns: Bool is returned with the status of the removal operation. True for success, false for error.
*/
@discardableResult public func removeAllKeys() -> Bool {
lock.lock()
defer { lock.unlock() }
var query: [String:Any] = [kSecClass as String: kSecClassGenericPassword]
query[kSecAttrService as String] = serviceName
// Set the keychain access group if defined
if let accessGroup = self.accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup
}
let status: OSStatus = SecItemDelete(query as CFDictionary)
guard status != errSecItemNotFound else { return true }
if status != errSecSuccess {
if let error: String = SecCopyErrorMessageString(status, nil) as String? {
print("Error removeAllKeys in keychain. Error: \(error) ")
}
return false
}
return true
}
public func getArray(forKey: String) -> NSArray? {
guard let data = load(forKey: forKey) else {
return nil
}
if let result = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? NSArray {
result
}
return nil
}
/**
Saves an NSArray to the keychain.
- Parameter forKey: The key to be used when saving the provided value
- Parameter value: The value to be saved
- Returns: True if saved successfully, false if the provider was not able to save successfully
*/
@discardableResult public func setArray(forKey: String, value: NSArray) -> Bool {
if let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false) {
return saveData(forKey: forKey, value: data)
}
return false
}
public func getDictionary(forKey: String) -> NSDictionary? {
guard let data = load(forKey: forKey) else {
return nil
}
if let result = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? NSDictionary {
result
}
return nil
}
/**
Saves a NSDictionary to the keychain.
- Parameter forKey: The key to be used when saving the provided value
- Parameter value: The value to be saved
- Returns: True if saved successfully, false if the provider was not able to save successfully
*/
@discardableResult public func setDictionary(forKey: String, value: NSDictionary) -> Bool {
if let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false) {
return saveData(forKey: forKey, value: data)
}
return false
}
private func getObject(forKey: String) -> NSCoding? {
guard let data = load(forKey: forKey) else {
return nil
}
if let result = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? NSCoding {
result
}
return nil
}
private func saveObject(forKey: String, value: NSCoding) -> Bool {
if let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false) {
return saveData(forKey: forKey, value: data)
}
return false
}
private func handleResultStatus(forKey: String, status: OSStatus) -> Bool {
if status != errSecSuccess {
if let error: String = SecCopyErrorMessageString(status, nil) as String? {
print("Error Saving key \(forKey) to keychain. Error: \(error) ")
}
return false
}
return true
}
private func saveData(forKey: String, value: [Data]) -> Bool {
lock.lock()
defer { lock.unlock() }
let query = buildQuery(forKey)
if let crypto = self.crypter {
query[kSecValueData as String] = crypto.encrypt(data: value, forKey: forKey)
} else {
query[kSecValueData as String] = value
}
if SecItemCopyMatching(query, nil) == noErr {
let status = SecItemUpdate(query, NSDictionary(dictionary: [kSecValueData: value]))
return handleResultStatus(forKey: forKey, status: status)
}
let status = SecItemAdd(query, nil)
return handleResultStatus(forKey: forKey, status: status)
}
private func saveData(forKey: String, value: Data) -> Bool {
lock.lock()
defer { lock.unlock() }
let query = buildQuery(forKey)
if let crypto = self.crypter {
query[kSecValueData as String] = crypto.encrypt(data: value, forKey: forKey)
} else {
query[kSecValueData as String] = value
}
if SecItemCopyMatching(query, nil) == noErr {
let status = SecItemUpdate(query, NSDictionary(dictionary: [kSecValueData: value]))
return handleResultStatus(forKey: forKey, status: status)
}
let status = SecItemAdd(query, nil)
let saveResult: Bool = handleResultStatus(forKey: forKey, status: status)
return saveResult
}
private func load(forKey: String) -> Data? {
let query = buildQuery(forKey)
// Setup parameters needed to return value from query
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnData as String] = kCFBooleanTrue
var dataTypeRef: AnyObject?
let status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
if let data = dataTypeRef as! Data? {
if let crypto = self.crypter {
return crypto.decrypt(data: data, forKey: forKey)
}
return data
}
}
return nil
}
private func loadArray(forKey: String) -> [Data]? {
let query = buildQuery(forKey)
// Setup parameters needed to return value from query
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnData as String] = kCFBooleanTrue
var dataTypeRef: AnyObject?
let status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
if let data = dataTypeRef as! [Data]? {
if let crypto = self.crypter {
return crypto.decrypt(data: data, forKey: forKey)
}
return data
}
}
return nil
}
private func buildQuery(_ forKey: String) -> NSMutableDictionary {
// Setup default access as generic password (rather than a certificate, internet password, etc)
let query = NSMutableDictionary()
query.setValue(kSecClassGenericPassword, forKey: kSecClass as String)
//Add Service Name
query[kSecAttrService as String] = serviceName
//There will always be a value here as we default to afterFirstUnlock
query[kSecAttrAccessible as String] = accessible.rawValue
//Check if access group has been defined
if let accessGroup = self.accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup
}
query[kSecAttrSynchronizable as String] = synchronizable
query[kSecAttrGeneric as String] = forKey.data(using: String.Encoding.utf8)
query[kSecAttrAccount as String] = forKey
return query
}
}
|
mit
|
a9dbe85f99986c10fcfafe5b644316e4
| 34.32998 | 207 | 0.612962 | 5.079259 | false | false | false | false |
bpenda/Transit-Chief
|
Transit Chief/StopPoint.swift
|
1
|
806
|
//
// StopPoint.swift
// Transit Chief
//
// Created by Vasil Pendavinji on 8/3/15.
// Copyright © 2015 Vasil Pendavinji. All rights reserved.
//
import Foundation
class StopPoint {
var code:String
var distance:Double
var stopId:String
var lat:Double
var lon:Double
var name:String
var buses:Array<Bus>
init(code:String, dist:Double, stopId:String, lat:Double, lon:Double, name:String){
self.code = code
self.distance = dist
self.stopId = stopId
self.lat = lat
self.lon = lon
self.name = name
self.buses = []
}
init(){
self.code = ""
self.distance = 0.0
self.stopId = ""
self.lat = 0.0
self.lon = 0.0
self.name = ""
self.buses = []
}
}
|
gpl-3.0
|
ab46277d916cc89ad8d1839d40adb164
| 19.15 | 87 | 0.557764 | 3.425532 | false | false | false | false |
huonw/swift
|
benchmark/single-source/SortStrings.swift
|
9
|
39352
|
//===--- SortStrings.swift ------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import TestsUtils
// Sort an array of strings using an explicit sort predicate.
public let SortStrings = [
BenchmarkInfo(name: "SortSortedStrings", runFunction: run_SortSortedStrings, tags: [.validation, .api, .algorithm, .String]),
BenchmarkInfo(name: "SortStrings", runFunction: run_SortStrings, tags: [.validation, .api, .algorithm, .String]),
BenchmarkInfo(name: "SortStringsUnicode", runFunction: run_SortStringsUnicode, tags: [.validation, .api, .algorithm, .String]),
]
var stringBenchmarkWords: [String] = [
"woodshed",
"lakism",
"gastroperiodynia",
"afetal",
"ramsch",
"Nickieben",
"undutifulness",
"birdglue",
"ungentlemanize",
"menacingly",
"heterophile",
"leoparde",
"Casearia",
"decorticate",
"neognathic",
"mentionable",
"tetraphenol",
"pseudonymal",
"dislegitimate",
"Discoidea",
"intitule",
"ionium",
"Lotuko",
"timbering",
"nonliquidating",
"oarialgia",
"Saccobranchus",
"reconnoiter",
"criminative",
"disintegratory",
"executer",
"Cylindrosporium",
"complimentation",
"Ixiama",
"Araceae",
"silaginoid",
"derencephalus",
"Lamiidae",
"marrowlike",
"ninepin",
"dynastid",
"lampfly",
"feint",
"trihemimer",
"semibarbarous",
"heresy",
"tritanope",
"indifferentist",
"confound",
"hyperbolaeon",
"planirostral",
"philosophunculist",
"existence",
"fretless",
"Leptandra",
"Amiranha",
"handgravure",
"gnash",
"unbelievability",
"orthotropic",
"Susumu",
"teleutospore",
"sleazy",
"shapeliness",
"hepatotomy",
"exclusivism",
"stifler",
"cunning",
"isocyanuric",
"pseudepigraphy",
"carpetbagger",
"respectiveness",
"Jussi",
"vasotomy",
"proctotomy",
"ovatotriangular",
"aesthetic",
"schizogamy",
"disengagement",
"foray",
"haplocaulescent",
"noncoherent",
"astrocyte",
"unreverberated",
"presenile",
"lanson",
"enkraal",
"contemplative",
"Syun",
"sartage",
"unforgot",
"wyde",
"homeotransplant",
"implicational",
"forerunnership",
"calcaneum",
"stomatodeum",
"pharmacopedia",
"preconcessive",
"trypanosomatic",
"intracollegiate",
"rampacious",
"secundipara",
"isomeric",
"treehair",
"pulmonal",
"uvate",
"dugway",
"glucofrangulin",
"unglory",
"Amandus",
"icterogenetic",
"quadrireme",
"Lagostomus",
"brakeroot",
"anthracemia",
"fluted",
"protoelastose",
"thro",
"pined",
"Saxicolinae",
"holidaymaking",
"strigil",
"uncurbed",
"starling",
"redeemeress",
"Liliaceae",
"imparsonee",
"obtusish",
"brushed",
"mesally",
"probosciformed",
"Bourbonesque",
"histological",
"caroba",
"digestion",
"Vindemiatrix",
"triactinal",
"tattling",
"arthrobacterium",
"unended",
"suspectfulness",
"movelessness",
"chartist",
"Corynebacterium",
"tercer",
"oversaturation",
"Congoleum",
"antiskeptical",
"sacral",
"equiradiate",
"whiskerage",
"panidiomorphic",
"unplanned",
"anilopyrine",
"Queres",
"tartronyl",
"Ing",
"notehead",
"finestiller",
"weekender",
"kittenhood",
"competitrix",
"premillenarian",
"convergescence",
"microcoleoptera",
"slirt",
"asteatosis",
"Gruidae",
"metastome",
"ambuscader",
"untugged",
"uneducated",
"redistill",
"rushlight",
"freakish",
"dosology",
"papyrine",
"iconologist",
"Bidpai",
"prophethood",
"pneumotropic",
"chloroformize",
"intemperance",
"spongiform",
"superindignant",
"divider",
"starlit",
"merchantish",
"indexless",
"unidentifiably",
"coumarone",
"nomism",
"diaphanous",
"salve",
"option",
"anallantoic",
"paint",
"thiofurfuran",
"baddeleyite",
"Donne",
"heterogenicity",
"decess",
"eschynite",
"mamma",
"unmonarchical",
"Archiplata",
"widdifow",
"apathic",
"overline",
"chaetophoraceous",
"creaky",
"trichosporange",
"uninterlined",
"cometwise",
"hermeneut",
"unbedraggled",
"tagged",
"Sminthurus",
"somniloquacious",
"aphasiac",
"Inoperculata",
"photoactivity",
"mobship",
"unblightedly",
"lievrite",
"Khoja",
"Falerian",
"milfoil",
"protectingly",
"householder",
"cathedra",
"calmingly",
"tordrillite",
"rearhorse",
"Leonard",
"maracock",
"youngish",
"kammererite",
"metanephric",
"Sageretia",
"diplococcoid",
"accelerative",
"choreal",
"metalogical",
"recombination",
"unimprison",
"invocation",
"syndetic",
"toadback",
"vaned",
"cupholder",
"metropolitanship",
"paramandelic",
"dermolysis",
"Sheriyat",
"rhabdus",
"seducee",
"encrinoid",
"unsuppliable",
"cololite",
"timesaver",
"preambulate",
"sampling",
"roaster",
"springald",
"densher",
"protraditional",
"naturalesque",
"Hydrodamalis",
"cytogenic",
"shortly",
"cryptogrammatical",
"squat",
"genual",
"backspier",
"solubleness",
"macroanalytical",
"overcovetousness",
"Natalie",
"cuprobismutite",
"phratriac",
"Montanize",
"hymnologist",
"karyomiton",
"podger",
"unofficiousness",
"antisplasher",
"supraclavicular",
"calidity",
"disembellish",
"antepredicament",
"recurvirostral",
"pulmonifer",
"coccidial",
"botonee",
"protoglobulose",
"isonym",
"myeloid",
"premiership",
"unmonopolize",
"unsesquipedalian",
"unfelicitously",
"theftbote",
"undauntable",
"lob",
"praenomen",
"underriver",
"gorfly",
"pluckage",
"radiovision",
"tyrantship",
"fraught",
"doppelkummel",
"rowan",
"allosyndetic",
"kinesiology",
"psychopath",
"arrent",
"amusively",
"preincorporation",
"Montargis",
"pentacron",
"neomedievalism",
"sima",
"lichenicolous",
"Ecclesiastes",
"woofed",
"cardinalist",
"sandaracin",
"gymnasial",
"lithoglyptics",
"centimeter",
"quadrupedous",
"phraseology",
"tumuli",
"ankylotomy",
"myrtol",
"cohibitive",
"lepospondylous",
"silvendy",
"inequipotential",
"entangle",
"raveling",
"Zeugobranchiata",
"devastating",
"grainage",
"amphisbaenian",
"blady",
"cirrose",
"proclericalism",
"governmentalist",
"carcinomorphic",
"nurtureship",
"clancular",
"unsteamed",
"discernibly",
"pleurogenic",
"impalpability",
"Azotobacterieae",
"sarcoplasmic",
"alternant",
"fitly",
"acrorrheuma",
"shrapnel",
"pastorize",
"gulflike",
"foreglow",
"unrelated",
"cirriped",
"cerviconasal",
"sexuale",
"pussyfooter",
"gadolinic",
"duplicature",
"codelinquency",
"trypanolysis",
"pathophobia",
"incapsulation",
"nonaerating",
"feldspar",
"diaphonic",
"epiglottic",
"depopulator",
"wisecracker",
"gravitational",
"kuba",
"lactesce",
"Toxotes",
"periomphalic",
"singstress",
"fannier",
"counterformula",
"Acemetae",
"repugnatorial",
"collimator",
"Acinetina",
"unpeace",
"drum",
"tetramorphic",
"descendentalism",
"cementer",
"supraloral",
"intercostal",
"Nipponize",
"negotiator",
"vacationless",
"synthol",
"fissureless",
"resoap",
"pachycarpous",
"reinspiration",
"misappropriation",
"disdiazo",
"unheatable",
"streng",
"Detroiter",
"infandous",
"loganiaceous",
"desugar",
"Matronalia",
"myxocystoma",
"Gandhiism",
"kiddier",
"relodge",
"counterreprisal",
"recentralize",
"foliously",
"reprinter",
"gender",
"edaciousness",
"chondriomite",
"concordant",
"stockrider",
"pedary",
"shikra",
"blameworthiness",
"vaccina",
"Thamnophilinae",
"wrongwise",
"unsuperannuated",
"convalescency",
"intransmutable",
"dropcloth",
"Ceriomyces",
"ponderal",
"unstentorian",
"mem",
"deceleration",
"ethionic",
"untopped",
"wetback",
"bebar",
"undecaying",
"shoreside",
"energize",
"presacral",
"undismay",
"agricolite",
"cowheart",
"hemibathybian",
"postexilian",
"Phacidiaceae",
"offing",
"redesignation",
"skeptically",
"physicianless",
"bronchopathy",
"marabuto",
"proprietory",
"unobtruded",
"funmaker",
"plateresque",
"preadventure",
"beseeching",
"cowpath",
"pachycephalia",
"arthresthesia",
"supari",
"lengthily",
"Nepa",
"liberation",
"nigrify",
"belfry",
"entoolitic",
"bazoo",
"pentachromic",
"distinguishable",
"slideable",
"galvanoscope",
"remanage",
"cetene",
"bocardo",
"consummation",
"boycottism",
"perplexity",
"astay",
"Gaetuli",
"periplastic",
"consolidator",
"sluggarding",
"coracoscapular",
"anangioid",
"oxygenizer",
"Hunanese",
"seminary",
"periplast",
"Corylus",
"unoriginativeness",
"persecutee",
"tweaker",
"silliness",
"Dabitis",
"facetiousness",
"thymy",
"nonimperial",
"mesoblastema",
"turbiniform",
"churchway",
"cooing",
"frithbot",
"concomitantly",
"stalwartize",
"clingfish",
"hardmouthed",
"parallelepipedonal",
"coracoacromial",
"factuality",
"curtilage",
"arachnoidean",
"semiaridity",
"phytobacteriology",
"premastery",
"hyperpurist",
"mobed",
"opportunistic",
"acclimature",
"outdistance",
"sophister",
"condonement",
"oxygenerator",
"acetonic",
"emanatory",
"periphlebitis",
"nonsociety",
"spectroradiometric",
"superaverage",
"cleanness",
"posteroventral",
"unadvised",
"unmistakedly",
"pimgenet",
"auresca",
"overimitate",
"dipnoan",
"chromoxylograph",
"triakistetrahedron",
"Suessiones",
"uncopiable",
"oligomenorrhea",
"fribbling",
"worriable",
"flot",
"ornithotrophy",
"phytoteratology",
"setup",
"lanneret",
"unbraceleted",
"gudemother",
"Spica",
"unconsolatory",
"recorruption",
"premenstrual",
"subretinal",
"millennialist",
"subjectibility",
"rewardproof",
"counterflight",
"pilomotor",
"carpetbaggery",
"macrodiagonal",
"slim",
"indiscernible",
"cuckoo",
"moted",
"controllingly",
"gynecopathy",
"porrectus",
"wanworth",
"lutfisk",
"semiprivate",
"philadelphy",
"abdominothoracic",
"coxcomb",
"dambrod",
"Metanemertini",
"balminess",
"homotypy",
"waremaker",
"absurdity",
"gimcrack",
"asquat",
"suitable",
"perimorphous",
"kitchenwards",
"pielum",
"salloo",
"paleontologic",
"Olson",
"Tellinidae",
"ferryman",
"peptonoid",
"Bopyridae",
"fallacy",
"ictuate",
"aguinaldo",
"rhyodacite",
"Ligydidae",
"galvanometric",
"acquisitor",
"muscology",
"hemikaryon",
"ethnobotanic",
"postganglionic",
"rudimentarily",
"replenish",
"phyllorhine",
"popgunnery",
"summar",
"quodlibetary",
"xanthochromia",
"autosymbolically",
"preloreal",
"extent",
"strawberry",
"immortalness",
"colicwort",
"frisca",
"electiveness",
"heartbroken",
"affrightingly",
"reconfiscation",
"jacchus",
"imponderably",
"semantics",
"beennut",
"paleometeorological",
"becost",
"timberwright",
"resuppose",
"syncategorematical",
"cytolymph",
"steinbok",
"explantation",
"hyperelliptic",
"antescript",
"blowdown",
"antinomical",
"caravanserai",
"unweariedly",
"isonymic",
"keratoplasty",
"vipery",
"parepigastric",
"endolymphatic",
"Londonese",
"necrotomy",
"angelship",
"Schizogregarinida",
"steeplebush",
"sparaxis",
"connectedness",
"tolerance",
"impingent",
"agglutinin",
"reviver",
"hieroglyphical",
"dialogize",
"coestate",
"declamatory",
"ventilation",
"tauromachy",
"cotransubstantiate",
"pome",
"underseas",
"triquadrantal",
"preconfinemnt",
"electroindustrial",
"selachostomous",
"nongolfer",
"mesalike",
"hamartiology",
"ganglioblast",
"unsuccessive",
"yallow",
"bacchanalianly",
"platydactyl",
"Bucephala",
"ultraurgent",
"penalist",
"catamenial",
"lynnhaven",
"unrelevant",
"lunkhead",
"metropolitan",
"hydro",
"outsoar",
"vernant",
"interlanguage",
"catarrhal",
"Ionicize",
"keelless",
"myomantic",
"booker",
"Xanthomonas",
"unimpeded",
"overfeminize",
"speronaro",
"diaconia",
"overholiness",
"liquefacient",
"Spartium",
"haggly",
"albumose",
"nonnecessary",
"sulcalization",
"decapitate",
"cellated",
"unguirostral",
"trichiurid",
"loveproof",
"amakebe",
"screet",
"arsenoferratin",
"unfrizz",
"undiscoverable",
"procollectivistic",
"tractile",
"Winona",
"dermostosis",
"eliminant",
"scomberoid",
"tensile",
"typesetting",
"xylic",
"dermatopathology",
"cycloplegic",
"revocable",
"fissate",
"afterplay",
"screwship",
"microerg",
"bentonite",
"stagecoaching",
"beglerbeglic",
"overcharitably",
"Plotinism",
"Veddoid",
"disequalize",
"cytoproct",
"trophophore",
"antidote",
"allerion",
"famous",
"convey",
"postotic",
"rapillo",
"cilectomy",
"penkeeper",
"patronym",
"bravely",
"ureteropyelitis",
"Hildebrandine",
"missileproof",
"Conularia",
"deadening",
"Conrad",
"pseudochylous",
"typologically",
"strummer",
"luxuriousness",
"resublimation",
"glossiness",
"hydrocauline",
"anaglyph",
"personifiable",
"seniority",
"formulator",
"datiscaceous",
"hydracrylate",
"Tyranni",
"Crawthumper",
"overprove",
"masher",
"dissonance",
"Serpentinian",
"malachite",
"interestless",
"stchi",
"ogum",
"polyspermic",
"archegoniate",
"precogitation",
"Alkaphrah",
"craggily",
"delightfulness",
"bioplast",
"diplocaulescent",
"neverland",
"interspheral",
"chlorhydric",
"forsakenly",
"scandium",
"detubation",
"telega",
"Valeriana",
"centraxonial",
"anabolite",
"neger",
"miscellanea",
"whalebacker",
"stylidiaceous",
"unpropelled",
"Kennedya",
"Jacksonite",
"ghoulish",
"Dendrocalamus",
"paynimhood",
"rappist",
"unluffed",
"falling",
"Lyctus",
"uncrown",
"warmly",
"pneumatism",
"Morisonian",
"notate",
"isoagglutinin",
"Pelidnota",
"previsit",
"contradistinctly",
"utter",
"porometer",
"gie",
"germanization",
"betwixt",
"prenephritic",
"underpier",
"Eleutheria",
"ruthenious",
"convertor",
"antisepsin",
"winterage",
"tetramethylammonium",
"Rockaway",
"Penaea",
"prelatehood",
"brisket",
"unwishful",
"Minahassa",
"Briareus",
"semiaxis",
"disintegrant",
"peastick",
"iatromechanical",
"fastus",
"thymectomy",
"ladyless",
"unpreened",
"overflutter",
"sicker",
"apsidally",
"thiazine",
"guideway",
"pausation",
"tellinoid",
"abrogative",
"foraminulate",
"omphalos",
"Monorhina",
"polymyarian",
"unhelpful",
"newslessness",
"oryctognosy",
"octoradial",
"doxology",
"arrhythmy",
"gugal",
"mesityl",
"hexaplaric",
"Cabirian",
"hordeiform",
"eddyroot",
"internarial",
"deservingness",
"jawbation",
"orographically",
"semiprecious",
"seasick",
"thermically",
"grew",
"tamability",
"egotistically",
"fip",
"preabsorbent",
"leptochroa",
"ethnobotany",
"podolite",
"egoistic",
"semitropical",
"cero",
"spinelessness",
"onshore",
"omlah",
"tintinnabulist",
"machila",
"entomotomy",
"nubile",
"nonscholastic",
"burnt",
"Alea",
"befume",
"doctorless",
"Napoleonic",
"scenting",
"apokreos",
"cresylene",
"paramide",
"rattery",
"disinterested",
"idiopathetic",
"negatory",
"fervid",
"quintato",
"untricked",
"Metrosideros",
"mescaline",
"midverse",
"Musophagidae",
"fictionary",
"branchiostegous",
"yoker",
"residuum",
"culmigenous",
"fleam",
"suffragism",
"Anacreon",
"sarcodous",
"parodistic",
"writmaking",
"conversationism",
"retroposed",
"tornillo",
"presuspect",
"didymous",
"Saumur",
"spicing",
"drawbridge",
"cantor",
"incumbrancer",
"heterospory",
"Turkeydom",
"anteprandial",
"neighborship",
"thatchless",
"drepanoid",
"lusher",
"paling",
"ecthlipsis",
"heredosyphilitic",
"although",
"garetta",
"temporarily",
"Monotropa",
"proglottic",
"calyptro",
"persiflage",
"degradable",
"paraspecific",
"undecorative",
"Pholas",
"myelon",
"resteal",
"quadrantly",
"scrimped",
"airer",
"deviless",
"caliciform",
"Sefekhet",
"shastaite",
"togate",
"macrostructure",
"bipyramid",
"wey",
"didynamy",
"knacker",
"swage",
"supermanism",
"epitheton",
"overpresumptuous"
]
@inline(never)
func benchSortStrings(_ words: [String]) {
// Notice that we _copy_ the array of words before we sort it.
// Pass an explicit '<' predicate to benchmark reabstraction thunks.
var tempwords = words
tempwords.sort(by: <)
}
public func run_SortStrings(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(stringBenchmarkWords)
}
}
public func run_SortSortedStrings(_ N: Int) {
let sortedBenchmarkWords = stringBenchmarkWords.sorted()
for _ in 1...5*N {
benchSortStrings(sortedBenchmarkWords)
}
}
var stringBenchmarkWordsUnicode: [String] = [
"❄️woodshed",
"❄️lakism",
"❄️gastroperiodynia",
"❄️afetal",
"❄️ramsch",
"❄️Nickieben",
"❄️undutifulness",
"❄️birdglue",
"❄️ungentlemanize",
"❄️menacingly",
"❄️heterophile",
"❄️leoparde",
"❄️Casearia",
"❄️decorticate",
"❄️neognathic",
"❄️mentionable",
"❄️tetraphenol",
"❄️pseudonymal",
"❄️dislegitimate",
"❄️Discoidea",
"❄️intitule",
"❄️ionium",
"❄️Lotuko",
"❄️timbering",
"❄️nonliquidating",
"❄️oarialgia",
"❄️Saccobranchus",
"❄️reconnoiter",
"❄️criminative",
"❄️disintegratory",
"❄️executer",
"❄️Cylindrosporium",
"❄️complimentation",
"❄️Ixiama",
"❄️Araceae",
"❄️silaginoid",
"❄️derencephalus",
"❄️Lamiidae",
"❄️marrowlike",
"❄️ninepin",
"❄️dynastid",
"❄️lampfly",
"❄️feint",
"❄️trihemimer",
"❄️semibarbarous",
"❄️heresy",
"❄️tritanope",
"❄️indifferentist",
"❄️confound",
"❄️hyperbolaeon",
"❄️planirostral",
"❄️philosophunculist",
"❄️existence",
"❄️fretless",
"❄️Leptandra",
"❄️Amiranha",
"❄️handgravure",
"❄️gnash",
"❄️unbelievability",
"❄️orthotropic",
"❄️Susumu",
"❄️teleutospore",
"❄️sleazy",
"❄️shapeliness",
"❄️hepatotomy",
"❄️exclusivism",
"❄️stifler",
"❄️cunning",
"❄️isocyanuric",
"❄️pseudepigraphy",
"❄️carpetbagger",
"❄️respectiveness",
"❄️Jussi",
"❄️vasotomy",
"❄️proctotomy",
"❄️ovatotriangular",
"❄️aesthetic",
"❄️schizogamy",
"❄️disengagement",
"❄️foray",
"❄️haplocaulescent",
"❄️noncoherent",
"❄️astrocyte",
"❄️unreverberated",
"❄️presenile",
"❄️lanson",
"❄️enkraal",
"❄️contemplative",
"❄️Syun",
"❄️sartage",
"❄️unforgot",
"❄️wyde",
"❄️homeotransplant",
"❄️implicational",
"❄️forerunnership",
"❄️calcaneum",
"❄️stomatodeum",
"❄️pharmacopedia",
"❄️preconcessive",
"❄️trypanosomatic",
"❄️intracollegiate",
"❄️rampacious",
"❄️secundipara",
"❄️isomeric",
"❄️treehair",
"❄️pulmonal",
"❄️uvate",
"❄️dugway",
"❄️glucofrangulin",
"❄️unglory",
"❄️Amandus",
"❄️icterogenetic",
"❄️quadrireme",
"❄️Lagostomus",
"❄️brakeroot",
"❄️anthracemia",
"❄️fluted",
"❄️protoelastose",
"❄️thro",
"❄️pined",
"❄️Saxicolinae",
"❄️holidaymaking",
"❄️strigil",
"❄️uncurbed",
"❄️starling",
"❄️redeemeress",
"❄️Liliaceae",
"❄️imparsonee",
"❄️obtusish",
"❄️brushed",
"❄️mesally",
"❄️probosciformed",
"❄️Bourbonesque",
"❄️histological",
"❄️caroba",
"❄️digestion",
"❄️Vindemiatrix",
"❄️triactinal",
"❄️tattling",
"❄️arthrobacterium",
"❄️unended",
"❄️suspectfulness",
"❄️movelessness",
"❄️chartist",
"❄️Corynebacterium",
"❄️tercer",
"❄️oversaturation",
"❄️Congoleum",
"❄️antiskeptical",
"❄️sacral",
"❄️equiradiate",
"❄️whiskerage",
"❄️panidiomorphic",
"❄️unplanned",
"❄️anilopyrine",
"❄️Queres",
"❄️tartronyl",
"❄️Ing",
"❄️notehead",
"❄️finestiller",
"❄️weekender",
"❄️kittenhood",
"❄️competitrix",
"❄️premillenarian",
"❄️convergescence",
"❄️microcoleoptera",
"❄️slirt",
"❄️asteatosis",
"❄️Gruidae",
"❄️metastome",
"❄️ambuscader",
"❄️untugged",
"❄️uneducated",
"❄️redistill",
"❄️rushlight",
"❄️freakish",
"❄️dosology",
"❄️papyrine",
"❄️iconologist",
"❄️Bidpai",
"❄️prophethood",
"❄️pneumotropic",
"❄️chloroformize",
"❄️intemperance",
"❄️spongiform",
"❄️superindignant",
"❄️divider",
"❄️starlit",
"❄️merchantish",
"❄️indexless",
"❄️unidentifiably",
"❄️coumarone",
"❄️nomism",
"❄️diaphanous",
"❄️salve",
"❄️option",
"❄️anallantoic",
"❄️paint",
"❄️thiofurfuran",
"❄️baddeleyite",
"❄️Donne",
"❄️heterogenicity",
"❄️decess",
"❄️eschynite",
"❄️mamma",
"❄️unmonarchical",
"❄️Archiplata",
"❄️widdifow",
"❄️apathic",
"❄️overline",
"❄️chaetophoraceous",
"❄️creaky",
"❄️trichosporange",
"❄️uninterlined",
"❄️cometwise",
"❄️hermeneut",
"❄️unbedraggled",
"❄️tagged",
"❄️Sminthurus",
"❄️somniloquacious",
"❄️aphasiac",
"❄️Inoperculata",
"❄️photoactivity",
"❄️mobship",
"❄️unblightedly",
"❄️lievrite",
"❄️Khoja",
"❄️Falerian",
"❄️milfoil",
"❄️protectingly",
"❄️householder",
"❄️cathedra",
"❄️calmingly",
"❄️tordrillite",
"❄️rearhorse",
"❄️Leonard",
"❄️maracock",
"❄️youngish",
"❄️kammererite",
"❄️metanephric",
"❄️Sageretia",
"❄️diplococcoid",
"❄️accelerative",
"❄️choreal",
"❄️metalogical",
"❄️recombination",
"❄️unimprison",
"❄️invocation",
"❄️syndetic",
"❄️toadback",
"❄️vaned",
"❄️cupholder",
"❄️metropolitanship",
"❄️paramandelic",
"❄️dermolysis",
"❄️Sheriyat",
"❄️rhabdus",
"❄️seducee",
"❄️encrinoid",
"❄️unsuppliable",
"❄️cololite",
"❄️timesaver",
"❄️preambulate",
"❄️sampling",
"❄️roaster",
"❄️springald",
"❄️densher",
"❄️protraditional",
"❄️naturalesque",
"❄️Hydrodamalis",
"❄️cytogenic",
"❄️shortly",
"❄️cryptogrammatical",
"❄️squat",
"❄️genual",
"❄️backspier",
"❄️solubleness",
"❄️macroanalytical",
"❄️overcovetousness",
"❄️Natalie",
"❄️cuprobismutite",
"❄️phratriac",
"❄️Montanize",
"❄️hymnologist",
"❄️karyomiton",
"❄️podger",
"❄️unofficiousness",
"❄️antisplasher",
"❄️supraclavicular",
"❄️calidity",
"❄️disembellish",
"❄️antepredicament",
"❄️recurvirostral",
"❄️pulmonifer",
"❄️coccidial",
"❄️botonee",
"❄️protoglobulose",
"❄️isonym",
"❄️myeloid",
"❄️premiership",
"❄️unmonopolize",
"❄️unsesquipedalian",
"❄️unfelicitously",
"❄️theftbote",
"❄️undauntable",
"❄️lob",
"❄️praenomen",
"❄️underriver",
"❄️gorfly",
"❄️pluckage",
"❄️radiovision",
"❄️tyrantship",
"❄️fraught",
"❄️doppelkummel",
"❄️rowan",
"❄️allosyndetic",
"❄️kinesiology",
"❄️psychopath",
"❄️arrent",
"❄️amusively",
"❄️preincorporation",
"❄️Montargis",
"❄️pentacron",
"❄️neomedievalism",
"❄️sima",
"❄️lichenicolous",
"❄️Ecclesiastes",
"❄️woofed",
"❄️cardinalist",
"❄️sandaracin",
"❄️gymnasial",
"❄️lithoglyptics",
"❄️centimeter",
"❄️quadrupedous",
"❄️phraseology",
"❄️tumuli",
"❄️ankylotomy",
"❄️myrtol",
"❄️cohibitive",
"❄️lepospondylous",
"❄️silvendy",
"❄️inequipotential",
"❄️entangle",
"❄️raveling",
"❄️Zeugobranchiata",
"❄️devastating",
"❄️grainage",
"❄️amphisbaenian",
"❄️blady",
"❄️cirrose",
"❄️proclericalism",
"❄️governmentalist",
"❄️carcinomorphic",
"❄️nurtureship",
"❄️clancular",
"❄️unsteamed",
"❄️discernibly",
"❄️pleurogenic",
"❄️impalpability",
"❄️Azotobacterieae",
"❄️sarcoplasmic",
"❄️alternant",
"❄️fitly",
"❄️acrorrheuma",
"❄️shrapnel",
"❄️pastorize",
"❄️gulflike",
"❄️foreglow",
"❄️unrelated",
"❄️cirriped",
"❄️cerviconasal",
"❄️sexuale",
"❄️pussyfooter",
"❄️gadolinic",
"❄️duplicature",
"❄️codelinquency",
"❄️trypanolysis",
"❄️pathophobia",
"❄️incapsulation",
"❄️nonaerating",
"❄️feldspar",
"❄️diaphonic",
"❄️epiglottic",
"❄️depopulator",
"❄️wisecracker",
"❄️gravitational",
"❄️kuba",
"❄️lactesce",
"❄️Toxotes",
"❄️periomphalic",
"❄️singstress",
"❄️fannier",
"❄️counterformula",
"❄️Acemetae",
"❄️repugnatorial",
"❄️collimator",
"❄️Acinetina",
"❄️unpeace",
"❄️drum",
"❄️tetramorphic",
"❄️descendentalism",
"❄️cementer",
"❄️supraloral",
"❄️intercostal",
"❄️Nipponize",
"❄️negotiator",
"❄️vacationless",
"❄️synthol",
"❄️fissureless",
"❄️resoap",
"❄️pachycarpous",
"❄️reinspiration",
"❄️misappropriation",
"❄️disdiazo",
"❄️unheatable",
"❄️streng",
"❄️Detroiter",
"❄️infandous",
"❄️loganiaceous",
"❄️desugar",
"❄️Matronalia",
"❄️myxocystoma",
"❄️Gandhiism",
"❄️kiddier",
"❄️relodge",
"❄️counterreprisal",
"❄️recentralize",
"❄️foliously",
"❄️reprinter",
"❄️gender",
"❄️edaciousness",
"❄️chondriomite",
"❄️concordant",
"❄️stockrider",
"❄️pedary",
"❄️shikra",
"❄️blameworthiness",
"❄️vaccina",
"❄️Thamnophilinae",
"❄️wrongwise",
"❄️unsuperannuated",
"❄️convalescency",
"❄️intransmutable",
"❄️dropcloth",
"❄️Ceriomyces",
"❄️ponderal",
"❄️unstentorian",
"❄️mem",
"❄️deceleration",
"❄️ethionic",
"❄️untopped",
"❄️wetback",
"❄️bebar",
"❄️undecaying",
"❄️shoreside",
"❄️energize",
"❄️presacral",
"❄️undismay",
"❄️agricolite",
"❄️cowheart",
"❄️hemibathybian",
"❄️postexilian",
"❄️Phacidiaceae",
"❄️offing",
"❄️redesignation",
"❄️skeptically",
"❄️physicianless",
"❄️bronchopathy",
"❄️marabuto",
"❄️proprietory",
"❄️unobtruded",
"❄️funmaker",
"❄️plateresque",
"❄️preadventure",
"❄️beseeching",
"❄️cowpath",
"❄️pachycephalia",
"❄️arthresthesia",
"❄️supari",
"❄️lengthily",
"❄️Nepa",
"❄️liberation",
"❄️nigrify",
"❄️belfry",
"❄️entoolitic",
"❄️bazoo",
"❄️pentachromic",
"❄️distinguishable",
"❄️slideable",
"❄️galvanoscope",
"❄️remanage",
"❄️cetene",
"❄️bocardo",
"❄️consummation",
"❄️boycottism",
"❄️perplexity",
"❄️astay",
"❄️Gaetuli",
"❄️periplastic",
"❄️consolidator",
"❄️sluggarding",
"❄️coracoscapular",
"❄️anangioid",
"❄️oxygenizer",
"❄️Hunanese",
"❄️seminary",
"❄️periplast",
"❄️Corylus",
"❄️unoriginativeness",
"❄️persecutee",
"❄️tweaker",
"❄️silliness",
"❄️Dabitis",
"❄️facetiousness",
"❄️thymy",
"❄️nonimperial",
"❄️mesoblastema",
"❄️turbiniform",
"❄️churchway",
"❄️cooing",
"❄️frithbot",
"❄️concomitantly",
"❄️stalwartize",
"❄️clingfish",
"❄️hardmouthed",
"❄️parallelepipedonal",
"❄️coracoacromial",
"❄️factuality",
"❄️curtilage",
"❄️arachnoidean",
"❄️semiaridity",
"❄️phytobacteriology",
"❄️premastery",
"❄️hyperpurist",
"❄️mobed",
"❄️opportunistic",
"❄️acclimature",
"❄️outdistance",
"❄️sophister",
"❄️condonement",
"❄️oxygenerator",
"❄️acetonic",
"❄️emanatory",
"❄️periphlebitis",
"❄️nonsociety",
"❄️spectroradiometric",
"❄️superaverage",
"❄️cleanness",
"❄️posteroventral",
"❄️unadvised",
"❄️unmistakedly",
"❄️pimgenet",
"❄️auresca",
"❄️overimitate",
"❄️dipnoan",
"❄️chromoxylograph",
"❄️triakistetrahedron",
"❄️Suessiones",
"❄️uncopiable",
"❄️oligomenorrhea",
"❄️fribbling",
"❄️worriable",
"❄️flot",
"❄️ornithotrophy",
"❄️phytoteratology",
"❄️setup",
"❄️lanneret",
"❄️unbraceleted",
"❄️gudemother",
"❄️Spica",
"❄️unconsolatory",
"❄️recorruption",
"❄️premenstrual",
"❄️subretinal",
"❄️millennialist",
"❄️subjectibility",
"❄️rewardproof",
"❄️counterflight",
"❄️pilomotor",
"❄️carpetbaggery",
"❄️macrodiagonal",
"❄️slim",
"❄️indiscernible",
"❄️cuckoo",
"❄️moted",
"❄️controllingly",
"❄️gynecopathy",
"❄️porrectus",
"❄️wanworth",
"❄️lutfisk",
"❄️semiprivate",
"❄️philadelphy",
"❄️abdominothoracic",
"❄️coxcomb",
"❄️dambrod",
"❄️Metanemertini",
"❄️balminess",
"❄️homotypy",
"❄️waremaker",
"❄️absurdity",
"❄️gimcrack",
"❄️asquat",
"❄️suitable",
"❄️perimorphous",
"❄️kitchenwards",
"❄️pielum",
"❄️salloo",
"❄️paleontologic",
"❄️Olson",
"❄️Tellinidae",
"❄️ferryman",
"❄️peptonoid",
"❄️Bopyridae",
"❄️fallacy",
"❄️ictuate",
"❄️aguinaldo",
"❄️rhyodacite",
"❄️Ligydidae",
"❄️galvanometric",
"❄️acquisitor",
"❄️muscology",
"❄️hemikaryon",
"❄️ethnobotanic",
"❄️postganglionic",
"❄️rudimentarily",
"❄️replenish",
"❄️phyllorhine",
"❄️popgunnery",
"❄️summar",
"❄️quodlibetary",
"❄️xanthochromia",
"❄️autosymbolically",
"❄️preloreal",
"❄️extent",
"❄️strawberry",
"❄️immortalness",
"❄️colicwort",
"❄️frisca",
"❄️electiveness",
"❄️heartbroken",
"❄️affrightingly",
"❄️reconfiscation",
"❄️jacchus",
"❄️imponderably",
"❄️semantics",
"❄️beennut",
"❄️paleometeorological",
"❄️becost",
"❄️timberwright",
"❄️resuppose",
"❄️syncategorematical",
"❄️cytolymph",
"❄️steinbok",
"❄️explantation",
"❄️hyperelliptic",
"❄️antescript",
"❄️blowdown",
"❄️antinomical",
"❄️caravanserai",
"❄️unweariedly",
"❄️isonymic",
"❄️keratoplasty",
"❄️vipery",
"❄️parepigastric",
"❄️endolymphatic",
"❄️Londonese",
"❄️necrotomy",
"❄️angelship",
"❄️Schizogregarinida",
"❄️steeplebush",
"❄️sparaxis",
"❄️connectedness",
"❄️tolerance",
"❄️impingent",
"❄️agglutinin",
"❄️reviver",
"❄️hieroglyphical",
"❄️dialogize",
"❄️coestate",
"❄️declamatory",
"❄️ventilation",
"❄️tauromachy",
"❄️cotransubstantiate",
"❄️pome",
"❄️underseas",
"❄️triquadrantal",
"❄️preconfinemnt",
"❄️electroindustrial",
"❄️selachostomous",
"❄️nongolfer",
"❄️mesalike",
"❄️hamartiology",
"❄️ganglioblast",
"❄️unsuccessive",
"❄️yallow",
"❄️bacchanalianly",
"❄️platydactyl",
"❄️Bucephala",
"❄️ultraurgent",
"❄️penalist",
"❄️catamenial",
"❄️lynnhaven",
"❄️unrelevant",
"❄️lunkhead",
"❄️metropolitan",
"❄️hydro",
"❄️outsoar",
"❄️vernant",
"❄️interlanguage",
"❄️catarrhal",
"❄️Ionicize",
"❄️keelless",
"❄️myomantic",
"❄️booker",
"❄️Xanthomonas",
"❄️unimpeded",
"❄️overfeminize",
"❄️speronaro",
"❄️diaconia",
"❄️overholiness",
"❄️liquefacient",
"❄️Spartium",
"❄️haggly",
"❄️albumose",
"❄️nonnecessary",
"❄️sulcalization",
"❄️decapitate",
"❄️cellated",
"❄️unguirostral",
"❄️trichiurid",
"❄️loveproof",
"❄️amakebe",
"❄️screet",
"❄️arsenoferratin",
"❄️unfrizz",
"❄️undiscoverable",
"❄️procollectivistic",
"❄️tractile",
"❄️Winona",
"❄️dermostosis",
"❄️eliminant",
"❄️scomberoid",
"❄️tensile",
"❄️typesetting",
"❄️xylic",
"❄️dermatopathology",
"❄️cycloplegic",
"❄️revocable",
"❄️fissate",
"❄️afterplay",
"❄️screwship",
"❄️microerg",
"❄️bentonite",
"❄️stagecoaching",
"❄️beglerbeglic",
"❄️overcharitably",
"❄️Plotinism",
"❄️Veddoid",
"❄️disequalize",
"❄️cytoproct",
"❄️trophophore",
"❄️antidote",
"❄️allerion",
"❄️famous",
"❄️convey",
"❄️postotic",
"❄️rapillo",
"❄️cilectomy",
"❄️penkeeper",
"❄️patronym",
"❄️bravely",
"❄️ureteropyelitis",
"❄️Hildebrandine",
"❄️missileproof",
"❄️Conularia",
"❄️deadening",
"❄️Conrad",
"❄️pseudochylous",
"❄️typologically",
"❄️strummer",
"❄️luxuriousness",
"❄️resublimation",
"❄️glossiness",
"❄️hydrocauline",
"❄️anaglyph",
"❄️personifiable",
"❄️seniority",
"❄️formulator",
"❄️datiscaceous",
"❄️hydracrylate",
"❄️Tyranni",
"❄️Crawthumper",
"❄️overprove",
"❄️masher",
"❄️dissonance",
"❄️Serpentinian",
"❄️malachite",
"❄️interestless",
"❄️stchi",
"❄️ogum",
"❄️polyspermic",
"❄️archegoniate",
"❄️precogitation",
"❄️Alkaphrah",
"❄️craggily",
"❄️delightfulness",
"❄️bioplast",
"❄️diplocaulescent",
"❄️neverland",
"❄️interspheral",
"❄️chlorhydric",
"❄️forsakenly",
"❄️scandium",
"❄️detubation",
"❄️telega",
"❄️Valeriana",
"❄️centraxonial",
"❄️anabolite",
"❄️neger",
"❄️miscellanea",
"❄️whalebacker",
"❄️stylidiaceous",
"❄️unpropelled",
"❄️Kennedya",
"❄️Jacksonite",
"❄️ghoulish",
"❄️Dendrocalamus",
"❄️paynimhood",
"❄️rappist",
"❄️unluffed",
"❄️falling",
"❄️Lyctus",
"❄️uncrown",
"❄️warmly",
"❄️pneumatism",
"❄️Morisonian",
"❄️notate",
"❄️isoagglutinin",
"❄️Pelidnota",
"❄️previsit",
"❄️contradistinctly",
"❄️utter",
"❄️porometer",
"❄️gie",
"❄️germanization",
"❄️betwixt",
"❄️prenephritic",
"❄️underpier",
"❄️Eleutheria",
"❄️ruthenious",
"❄️convertor",
"❄️antisepsin",
"❄️winterage",
"❄️tetramethylammonium",
"❄️Rockaway",
"❄️Penaea",
"❄️prelatehood",
"❄️brisket",
"❄️unwishful",
"❄️Minahassa",
"❄️Briareus",
"❄️semiaxis",
"❄️disintegrant",
"❄️peastick",
"❄️iatromechanical",
"❄️fastus",
"❄️thymectomy",
"❄️ladyless",
"❄️unpreened",
"❄️overflutter",
"❄️sicker",
"❄️apsidally",
"❄️thiazine",
"❄️guideway",
"❄️pausation",
"❄️tellinoid",
"❄️abrogative",
"❄️foraminulate",
"❄️omphalos",
"❄️Monorhina",
"❄️polymyarian",
"❄️unhelpful",
"❄️newslessness",
"❄️oryctognosy",
"❄️octoradial",
"❄️doxology",
"❄️arrhythmy",
"❄️gugal",
"❄️mesityl",
"❄️hexaplaric",
"❄️Cabirian",
"❄️hordeiform",
"❄️eddyroot",
"❄️internarial",
"❄️deservingness",
"❄️jawbation",
"❄️orographically",
"❄️semiprecious",
"❄️seasick",
"❄️thermically",
"❄️grew",
"❄️tamability",
"❄️egotistically",
"❄️fip",
"❄️preabsorbent",
"❄️leptochroa",
"❄️ethnobotany",
"❄️podolite",
"❄️egoistic",
"❄️semitropical",
"❄️cero",
"❄️spinelessness",
"❄️onshore",
"❄️omlah",
"❄️tintinnabulist",
"❄️machila",
"❄️entomotomy",
"❄️nubile",
"❄️nonscholastic",
"❄️burnt",
"❄️Alea",
"❄️befume",
"❄️doctorless",
"❄️Napoleonic",
"❄️scenting",
"❄️apokreos",
"❄️cresylene",
"❄️paramide",
"❄️rattery",
"❄️disinterested",
"❄️idiopathetic",
"❄️negatory",
"❄️fervid",
"❄️quintato",
"❄️untricked",
"❄️Metrosideros",
"❄️mescaline",
"❄️midverse",
"❄️Musophagidae",
"❄️fictionary",
"❄️branchiostegous",
"❄️yoker",
"❄️residuum",
"❄️culmigenous",
"❄️fleam",
"❄️suffragism",
"❄️Anacreon",
"❄️sarcodous",
"❄️parodistic",
"❄️writmaking",
"❄️conversationism",
"❄️retroposed",
"❄️tornillo",
"❄️presuspect",
"❄️didymous",
"❄️Saumur",
"❄️spicing",
"❄️drawbridge",
"❄️cantor",
"❄️incumbrancer",
"❄️heterospory",
"❄️Turkeydom",
"❄️anteprandial",
"❄️neighborship",
"❄️thatchless",
"❄️drepanoid",
"❄️lusher",
"❄️paling",
"❄️ecthlipsis",
"❄️heredosyphilitic",
"❄️although",
"❄️garetta",
"❄️temporarily",
"❄️Monotropa",
"❄️proglottic",
"❄️calyptro",
"❄️persiflage",
"❄️degradable",
"❄️paraspecific",
"❄️undecorative",
"❄️Pholas",
"❄️myelon",
"❄️resteal",
"❄️quadrantly",
"❄️scrimped",
"❄️airer",
"❄️deviless",
"❄️caliciform",
"❄️Sefekhet",
"❄️shastaite",
"❄️togate",
"❄️macrostructure",
"❄️bipyramid",
"❄️wey",
"❄️didynamy",
"❄️knacker",
"❄️swage",
"❄️supermanism",
"❄️epitheton",
"❄️overpresumptuous"
]
public func run_SortStringsUnicode(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(stringBenchmarkWordsUnicode)
}
}
|
apache-2.0
|
6d5ea3669c79b931b4a06cd66e2bd628
| 16.219679 | 129 | 0.587435 | 2.551202 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.