repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tlax/GaussSquad
GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemCosDeg.swift
1
899
import UIKit class MCalculatorFunctionsItemCosDeg:MCalculatorFunctionsItem { init() { let icon:UIImage = #imageLiteral(resourceName: "assetFunctionCos") let title:String = NSLocalizedString("MCalculatorFunctionsItemCosDeg_title", comment:"") super.init( icon:icon, title:title) } override func processFunction( currentValue:Double, currentString:String, modelKeyboard:MKeyboard, view:UITextView) { let cosDegValue:Double = cos(currentValue * M_PI / 180.0) let cosDegString:String = modelKeyboard.numberAsString(scalar:cosDegValue) let descr:String = "deg cos(\(currentString)) = \(cosDegString)" applyUpdate( modelKeyboard:modelKeyboard, view:view, newEditing:cosDegString, descr:descr) } }
mit
6782ecc22c6d3377d37be089537d4665
28
96
0.619577
4.540404
false
false
false
false
imobilize/Molib
Molib/Classes/ViewControllers/MOTableViewCoordinator.swift
1
6888
import UIKit public protocol TableViewCellProvider: class { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell } public protocol DataSourceProviderTableViewAdapterDelegate: class { func tableViewWillUpdateContent(_ tableView: UITableView) func tableViewDidUpdateContent(_ tableView: UITableView) } public protocol TableViewEditingDelegate: class { func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool func tableView(_ tableView: UITableView, didDeleteRowAt indexPath: IndexPath) } public class DataSourceProviderTableViewAdapter<ItemType>: DataSourceProviderDelegate { private unowned let tableView: UITableView public weak var delegate: DataSourceProviderTableViewAdapterDelegate? = nil private var tableViewRowAnimations: UITableViewRowAnimation = .automatic public var tableAnimationsEnabled: Bool { set { if newValue { tableViewRowAnimations = .automatic } else { tableViewRowAnimations = .none } } get { return (tableViewRowAnimations != .none) } } init(tableView: UITableView) { self.tableView = tableView } // conformance to the DataSourceProviderDelegate public func providerWillChangeContent() { self.delegate?.tableViewWillUpdateContent(tableView) self.tableView.beginUpdates() } public func providerDidEndChangeContent(updatesBlock: VoidCompletion) { updatesBlock() self.tableView.endUpdates() self.delegate?.tableViewDidUpdateContent(tableView) } public func providerDidInsertSectionAtIndex(index: Int) { self.tableView.insertSections(IndexSet(integer: index), with: tableViewRowAnimations) } public func providerDidDeleteSectionAtIndex(index: Int) { self.tableView.deleteSections(IndexSet(integer: index), with: tableViewRowAnimations) } public func providerDidInsertItemsAtIndexPaths(items: [ItemType], atIndexPaths indexPaths: [IndexPath]) { self.tableView.insertRows(at: indexPaths, with: tableViewRowAnimations) } public func providerDidDeleteItemsAtIndexPaths(items: [ItemType], atIndexPaths indexPaths: [IndexPath]) { self.tableView.deleteRows(at: indexPaths, with: tableViewRowAnimations) } public func providerDidUpdateItemsAtIndexPaths(items: [ItemType], atIndexPaths indexPaths: [IndexPath]) { self.tableView.reloadRows(at: indexPaths, with: tableViewRowAnimations) } public func providerDidMoveItem(item: ItemType, atIndexPath: IndexPath, toIndexPath: IndexPath) { self.tableView.deleteRows(at: [atIndexPath], with: tableViewRowAnimations) self.tableView.insertRows(at: [toIndexPath], with: tableViewRowAnimations) } public func providerDidDeleteAllItemsInSection(section: Int) { let sectionSet = IndexSet(integer: section) self.tableView.reloadSections(sectionSet, with: tableViewRowAnimations) } } public class TableViewCoordinator<CollectionType, DataSource: DataSourceProvider> : NSObject, UITableViewDataSource where DataSource.ItemType == CollectionType, DataSource.DataSourceDelegate == DataSourceProviderTableViewAdapter<CollectionType> { var dataSource: DataSource private var sectionNames: [String: String] private let dataSourceProviderTableViewAdapter: DataSourceProviderTableViewAdapter<CollectionType> private unowned let tableViewCellProvider: TableViewCellProvider public weak var tableViewEditingDelegate: TableViewEditingDelegate? public var tableViewAnimations: Bool { set { dataSourceProviderTableViewAdapter.tableAnimationsEnabled = false } get { return dataSourceProviderTableViewAdapter.tableAnimationsEnabled } } public init(tableView: UITableView, dataSource: DataSource, cellProvider: TableViewCellProvider) { self.dataSource = dataSource self.tableViewCellProvider = cellProvider self.dataSourceProviderTableViewAdapter = DataSourceProviderTableViewAdapter<CollectionType>(tableView: tableView) self.sectionNames = [String: String]() super.init() tableView.dataSource = self self.dataSource.delegate = self.dataSourceProviderTableViewAdapter } public func setName(_ name: String, forSection section: Int) { sectionNames["\(section)"] = name } // MARK: - Table View public func numberOfSections(in tableView: UITableView) -> Int { return self.dataSource.numberOfSections() } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.numberOfRowsInSection(section: section) } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableViewCellProvider.tableView(tableView: tableView, cellForRowAtIndexPath: indexPath) } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { var canEdit = false if let editable = tableViewEditingDelegate?.tableView(tableView, canEditRowAt: indexPath) { canEdit = editable } return canEdit } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { tableViewEditingDelegate?.tableView(tableView, didDeleteRowAt: indexPath) } } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionNames["\(section)"] } } public class PlaceholderTableViewCoordinator<CollectionType, DataSource: DataSourceProvider>:TableViewCoordinator<CollectionType, DataSource> where DataSource.ItemType == CollectionType, DataSource.DataSourceDelegate == DataSourceProviderTableViewAdapter<CollectionType> { let placeholderCells: Int public init(tableView: UITableView, dataSource: DataSource, placeholderCells: Int, cellProvider: TableViewCellProvider) { self.placeholderCells = placeholderCells super.init(tableView: tableView, dataSource: dataSource, cellProvider: cellProvider) } public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.isEmpty() ? placeholderCells : dataSource.numberOfRowsInSection(section: section) } }
apache-2.0
0ea8d299ea34774ae03f2f8546684ef5
33.44
272
0.704994
5.968804
false
false
false
false
mperovic/my41
MODsView.swift
1
2021
// // MODsView.swift // my41 // // Created by Miroslav Perovic on 30.1.21.. // Copyright © 2021 iPera. All rights reserved. // import SwiftUI struct MODsView: View { var port: HPPort { didSet { filePath = port.getFilePath() } } var filePath: String? @ObservedObject var settingsState: SettingsState var onPress: (HPPort) -> () = {_ in } // @ViewBuilder var body: some View { GeometryReader { geometry in if getModule() == nil { Button(action: { onPress(port) }, label: { Image(systemName: "pencil") .font(.system(size: 32)) }) .frame(width: geometry.size.width, height: geometry.size.height) .clipShape(RoundedRectangle(cornerRadius: 5.0, style: .continuous)) .foregroundColor(.white) } else { VStack { Spacer() MODDetailsView(module: getModule()!, short: true) .padding([.leading, .trailing], 5) Spacer() HStack { Spacer() Button(action: { switch port { case .port1: settingsState.module1 = nil case .port2: settingsState.module2 = nil case .port3: settingsState.module3 = nil case .port4: settingsState.module4 = nil } }, label: { Image(systemName: "trash") .font(.system(size: 26)) .foregroundColor(.white) }) .padding(.trailing, 10) .padding(.bottom, 5) } } .frame(width: geometry.size.width, height: geometry.size.height) } } } func onPress(_ callback: @escaping (HPPort) -> ()) -> some View { MODsView(port: port, settingsState: settingsState, onPress: callback) } func getModule() -> MOD? { switch port { case .port1: return settingsState.module1 case .port2: return settingsState.module2 case .port3: return settingsState.module3 case .port4: return settingsState.module4 } } } struct MODsView_Previews: PreviewProvider { static var previews: some View { MODsView(port: .port1, settingsState: SettingsState()) } }
bsd-3-clause
5f0aed14cc00fedfe89fbf972d71c713
20.956522
71
0.616337
3.333333
false
false
false
false
PGSSoft/AutoMate
AutoMateExample/AutoMateExampleUITests/PermissionsTests.swift
1
15249
// // PermissionsTests.swift // AutoMateExample // // Created by Bartosz Janda on 15.02.2017. // Copyright © 2017 PGS Software. All rights reserved. // import XCTest import AutoMate // swiftlint:disable type_body_length class PermissionsTests: AppUITestCase { // MARK: Arrange Page Objects lazy var mainPage: MainPage = MainPage(in: self.app) lazy var permissionsPage: PermissionsPage = PermissionsPage(in: self.app) lazy var locationPage: LocationPage = LocationPage(in: self.app) lazy var contactsPage: ContactsPage = ContactsPage(in: self.app) lazy var homeKitPage: HomeKitPage = HomeKitPage(in: self.app) lazy var healthKitPage: HealthKitPage = HealthKitPage(in: self.app) lazy var healthPermissionPage: HealthPermissionPage = HealthPermissionPage(in: self.app) lazy var speechRecognitionPage: SpeechRecognitionPage = SpeechRecognitionPage(in: self.app) lazy var siriPage: SiriPage = SiriPage(in: self.app) lazy var remindersPage: RemindersPage = RemindersPage(in: self.app) lazy var photosPage: PhotosPage = PhotosPage(in: self.app) lazy var cameraPage: CameraPage = CameraPage(in: self.app) lazy var mediaLibraryPage: MediaLibraryPage = MediaLibraryPage(in: self.app) lazy var bluetoothPage: BluetoothPage = BluetoothPage(in: self.app) lazy var microphonePage: MicrophonePage = MicrophonePage(in: self.app) lazy var callsPage: CallsPage = CallsPage(in: self.app) lazy var calendarPage: CalendarPage = CalendarPage(in: self.app) lazy var motionPage: MotionPage = MotionPage(in: self.app) // MARK: Set up override func setUp() { super.setUp() TestLauncher.configureWithDefaultOptions(app).launch() wait(forVisibilityOf: mainPage) } // MARK: Tests func locationWhenInUse() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Location") { (alert) -> Bool in guard let locationAlert = LocationWhenInUseAlert(element: alert) else { XCTFail("Cannot create LocationWhenInUseAlert object") return false } XCTAssertTrue(locationAlert.denyElement.exists) XCTAssertTrue(locationAlert.allowElement.exists) locationAlert.allowElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToLocationWhenInUse() wait(forVisibilityOf: locationPage.requestLabel) app.tap() locationPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func locationUpgradeToAlways() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Location") { (alert) -> Bool in guard let locationAlert = LocationUpgradeWhenInUseAlwaysAlert(element: alert) else { XCTFail("Cannot create LocationUpgradeWhenInUseAlwaysAlert object") return false } XCTAssertTrue(locationAlert.cancelElement.exists) XCTAssertTrue(locationAlert.allowElement.exists) locationAlert.cancelElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToLocationAlways() app.tap() locationPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testLocationSystemAlert() { locationWhenInUse() if #available(iOS 11, *) { locationUpgradeToAlways() } } func testContactsSystemAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Contacts") { (alert) -> Bool in guard let contactsAlert = AddressBookAlert(element: alert) else { XCTFail("Cannot create AddressBookAlert object") return false } XCTAssertTrue(contactsAlert.denyElement.exists) XCTAssertTrue(contactsAlert.allowElement.exists) contactsAlert.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToContacts() Thread.sleep(forTimeInterval: 2) contactsPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testHomeKitAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "HomeKit") { (alert) -> Bool in guard let homeKitAlert = WillowAlert(element: alert) else { XCTFail("Cannot create WillowAlert object") return false } XCTAssertTrue(homeKitAlert.denyElement.exists) XCTAssertTrue(homeKitAlert.allowElement.exists) homeKitAlert.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToHomeKit() Thread.sleep(forTimeInterval: 2) app.tap() homeKitPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testHealthKitAlert() { // Skip test on iPad. // HealthKit is not available on iPad. if app.isRunningOnIpad { return } mainPage.goToPermissionsPageMenu() permissionsPage.goToHealthKit() wait(forVisibilityOf: healthPermissionPage) XCTAssertTrue(healthPermissionPage.allowElement.exists) XCTAssertTrue(healthPermissionPage.denyElement.exists) XCTAssertTrue(healthPermissionPage.turnOnAllElement.exists) healthPermissionPage.turnOnAllElement.tap() XCTAssertTrue(healthPermissionPage.turnOffAllElement.exists) healthPermissionPage.denyElement.tap() Thread.sleep(forTimeInterval: 2) guard let healthAlert = HealthAuthorizationDontAllowAlert(element: app.alerts.firstMatch) else { XCTFail("Cannot create HealthAuthorizationDontAllowAlert object") return } XCTAssertTrue(healthAlert.okElement.exists) healthAlert.okElement.tap() healthKitPage.goBack() permissionsPage.goBack() } func testSpeechRecognitionAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "SpeechRecognition") { (alert) -> Bool in guard let alertView = SpeechRecognitionAlert(element: alert) else { XCTFail("Cannot create SpeechRecognitionAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToSpeechRecognition() speechRecognitionPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } // Doesn't work on simulator func testSiriAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Siri") { (alert) -> Bool in guard let alertView = SiriAlert(element: alert) else { XCTFail("Cannot create SiriAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToSiri() siriPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } // Tested through `testIfRemindersAreVisible`. func testRemindersAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Reminders") { (alert) -> Bool in guard let alertView = RemindersAlert(element: alert) else { XCTFail("Cannot create RemindersAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToReminders() remindersPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testPhotosAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Photos") { (alert) -> Bool in guard let alertView = PhotosAlert(element: alert) else { XCTFail("Cannot create PhotosAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToPhotos() photosPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testCameraAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Camera") { (alert) -> Bool in guard let alertView = CameraAlert(element: alert) else { XCTFail("Cannot create CameraAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToCamera() cameraPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testMediaLibraryAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "MediaLibrary") { (alert) -> Bool in guard let alertView = MediaLibraryAlert(element: alert) else { XCTFail("Cannot create MediaLibraryAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToMediaLibrary() mediaLibraryPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } // Doesn't work on simulator func testBluetoothPeripheralAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Bluetooth") { (alert) -> Bool in guard let alertView = BluetoothPeripheralAlert(element: alert) else { XCTFail("Cannot create BluetoothPeripheralAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToBluetooth() bluetoothPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } // Doesn't work on simulator func testMicrophoneAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Microphone") { (alert) -> Bool in guard let alertView = MicrophoneAlert(element: alert) else { XCTFail("Cannot create MicrophoneAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToMicrophone() microphonePage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } // Doesn't work on simulator func testCallsAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Calls") { (alert) -> Bool in guard let alertView = CallsAlert(element: alert) else { XCTFail("Cannot create CallsAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToCalls() callsPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } // Tested through `testIfEventsAreVisible`. func testCalendarAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Calendar") { (alert) -> Bool in guard let alertView = CalendarAlert(element: alert) else { XCTFail("Cannot create CalendarAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToCalendar() calendarPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } func testMotionAlert() { var handled = false let token = addUIInterruptionMonitor(withDescription: "Motion") { (alert) -> Bool in guard let alertView = MotionAlert(element: alert) else { XCTFail("Cannot create MotionAlert object") return false } XCTAssertTrue(alertView.denyElement.exists) XCTAssertTrue(alertView.allowElement.exists) alertView.denyElement.tap() handled = true return true } mainPage.goToPermissionsPageMenu() permissionsPage.goToMotion() motionPage.goBack() permissionsPage.goBack() removeUIInterruptionMonitor(token) XCTAssertTrue(handled) } }
mit
8767a5c0afc4b26c768832a74bcbd24f
31.791398
104
0.633132
5.218344
false
true
false
false
BanyaKrylov/Learn-Swift
SpriteKitBasics/SpriteKitBasics/GameScene.swift
1
2967
// // GameScene.swift // SpriteKitBasics // // Created by Иван Крылов on 28.08.17. // Copyright © 2017 Иван Крылов. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMove(to view: SKView) { sceneSetting() sKSpriteNodeDemo() } func sceneSetting() { self.backgroundColor = #colorLiteral(red: 1, green: 0.7088894842, blue: 0.4229762584, alpha: 1) } func sKSpriteNodeDemo() { //Создаем переменную Texture и ей присваиваем объект типа SKTexture. В качестве параметра передаем имя нашего изображение let Texture = SKTexture(imageNamed: "desert_BG") //Создаем переменную BackgroundSprite и ей присваиваем объект типа SKSpriteNode. // В качестве параметра передаем объект типа SKTexture созданный нами выше. let BackgroundSprite = SKSpriteNode(texture: Texture) BackgroundSprite.size = CGSize(width:640, height:320) //задаем размер. BackgroundSprite.position = CGPoint(x:-200, y:-150) //задаем позицию. BackgroundSprite.anchorPoint = CGPoint(x:0, y:0) //задаем начальную точку. BackgroundSprite.name = "BackgroundSprite" // задаем имя. self.addChild(BackgroundSprite) //добавляем наш объект на нашу сцену. //Создаем переменную SimpleSprite и ей присваиваем объект типа SKSpriteNode. // В качестве параметров передаем цвет и размер. let SimpleSprite = SKSpriteNode(color: UIColor.blue, size: CGSize(width:50, height:50)) SimpleSprite.position = CGPoint(x:200, y:150) //задаем позицию. SimpleSprite.zPosition = 1; // задаем положение нашего объекта относительно оси Z. SimpleSprite.name = "SimpleSprite" // задаем имя. self.addChild(SimpleSprite) //добавляем наш объект на нашу сцену. //Создаем переменную ImageSprite и ей присваиваем объект типа SKSpriteNode. // В качестве параметров передаем имя нашего изображение. let ImageSprite = SKSpriteNode(imageNamed: "DerevoOpora") ImageSprite.position = CGPoint(x:250, y:50) //задаем позицию. ImageSprite.size = CGSize(width:100, height:15) //задаем размер. ImageSprite.name = "ImageSprite" // задаем имя. self.addChild(ImageSprite) //добавляем наш объект на нашу сцену. } }
apache-2.0
ab633dea6ca4d869a8725f6b044879c6
42.666667
129
0.677269
3.195122
false
false
false
false
rebe1one/alertcontroller
Source/RoundButton.swift
1
1347
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit @IBDesignable class RoundButton: UIButton { @IBInspectable var cornerRadius: CGFloat = 3 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var enabledBackgroundColor: UIColor = UIColor.darkMint() { didSet { setNeedsLayout() } } @IBInspectable var disabledBackgroundColor: UIColor = UIColor.pinkishGrey() { didSet { setNeedsLayout() } } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = cornerRadius clipsToBounds = true backgroundColor = isEnabled ? enabledBackgroundColor : disabledBackgroundColor } }
apache-2.0
4fd82896b2b88a5902bbedaa37e2990d
27.659574
86
0.665924
5.026119
false
false
false
false
WzhGoSky/ZHPlayer
ZHPlayer/ZHPlayer/ZHPlayer/String+Extension.swift
1
567
// // String+Extension.swift // CustomPlayer // // Created by Hayder on 2016/12/31. // Copyright © 2016年 Hayder. All rights reserved. // import UIKit extension String{ static func convertTimeWithSecond(second: TimeInterval) -> String{ let date = Date(timeIntervalSince1970: second) let fmt = DateFormatter() if second/3600>=1 { fmt.dateFormat = "HH:mm:ss" }else { fmt.dateFormat = "mm:ss" } return fmt.string(from: date) } }
mit
7e62deddf9fd7ae89c5504eff475e943
19.142857
70
0.546099
4.086957
false
false
false
false
daltoniam/Starscream
Sources/Security/FoundationSecurity.swift
1
3513
////////////////////////////////////////////////////////////////////////////////////////////////// // // FoundationSecurity.swift // Starscream // // Created by Dalton Cherry on 3/16/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CommonCrypto public enum FoundationSecurityError: Error { case invalidRequest } public class FoundationSecurity { var allowSelfSigned = false public init(allowSelfSigned: Bool = false) { self.allowSelfSigned = allowSelfSigned } } extension FoundationSecurity: CertificatePinning { public func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) { if allowSelfSigned { completion(.success) return } SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, domain as NSString?)) handleSecurityTrust(trust: trust, completion: completion) } private func handleSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { if #available(iOS 12.0, OSX 10.14, watchOS 5.0, tvOS 12.0, *) { var error: CFError? if SecTrustEvaluateWithError(trust, &error) { completion(.success) } else { completion(.failed(error)) } } else { handleOldSecurityTrust(trust: trust, completion: completion) } } private func handleOldSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { var result: SecTrustResultType = .unspecified SecTrustEvaluate(trust, &result) if result == .unspecified || result == .proceed { completion(.success) } else { let e = CFErrorCreate(kCFAllocatorDefault, "FoundationSecurityError" as NSString?, Int(result.rawValue), nil) completion(.failed(e)) } } } extension FoundationSecurity: HeaderValidator { public func validate(headers: [String: String], key: String) -> Error? { if let acceptKey = headers[HTTPWSHeader.acceptName] { let sha = "\(key)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() if sha != acceptKey { return WSError(type: .securityError, message: "accept header doesn't match", code: SecurityErrorCode.acceptFailed.rawValue) } } return nil } } private extension String { func sha1Base64() -> String { let data = self.data(using: .utf8)! let pointer = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) CC_SHA1(bytes.baseAddress, CC_LONG(data.count), &digest) return digest } return Data(pointer).base64EncodedString() } }
apache-2.0
b9042e8ce51a1aef5546ed346edce5a0
34.474747
139
0.602506
4.61498
false
false
false
false
FAU-Inf2/kwikshop-ios
SortType.swift
1
837
// // SortType.swift // Kwik Shop // // Created by Adrian Kretschmer on 31.08.15. // Copyright (c) 2015 FAU-Inf2. All rights reserved. // import Foundation enum SortType: Int { case manual = 0, group, alphabetically, manualWithGroups var showGroups : Bool { switch self { case .manual: fallthrough case .alphabetically: return false case .group: fallthrough case .manualWithGroups: return true } } var isManualSorting : Bool { switch self { case .manual: fallthrough case .manualWithGroups: return true default: return false } } } func == (left: SortType, right: SortType) -> Bool { return left.rawValue == right.rawValue }
mit
24392ac4c72f6053dad7d8578940e55a
19.414634
60
0.550777
4.248731
false
false
false
false
mennovf/Swift-MathEagle
MathEagle/Source/Linear Algebra/DiagonalMatrix.swift
1
27513
// // DiagonalMatrix.swift // MathEagle // // Created by Rugen Heidbuchel on 26/05/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Foundation import Accelerate /** A class representing a diagonal matrix. This matrix stores it's elements in an efficient way. The matrix does not have to be square, but it will only have non-zero elements on it's main diagonal. */ public class DiagonalMatrix <T: MatrixCompatible> : Matrix<T> { /** Returns a row major ordered list of all elements in the array. This should be used for high performance applications. */ override public var elementsList: [T] { get { var elementsList = [T]() for row in 0 ..< self.dimensions.rows { for col in 0 ..< self.dimensions.columns { elementsList.append(row == col ? self.elementsStructure[row] : 0) } } return elementsList } set (newElementsList) { if newElementsList.count != self.dimensions.product { NSException(name: "Wrong number of elements", reason: "The number of elements in the given elementsList is not correct. \(self.dimensions.product) elements expected, but got \(newElementsList.count).", userInfo: nil).raise() } for i in 0 ..< self.dimensions.minimum { self.elementsStructure[i] = newElementsList[i * (1 + self.dimensions.columns)] } } } /** Returns or sets a 2 dimensional array containing the elements of the matrix. The array contains array's that represent rows. :performance: This method scales O(n*m) for an nxm matrix, so elementsList should be used for high performance applications. */ override public var elements: [[T]] { get { var elements = [[T]]() for r in 0 ..< self.dimensions.rows { var rowElements = [T]() for c in 0 ..< self.dimensions.columns { rowElements.append(r == c ? self.elementsStructure[r] : 0) } elements.append(rowElements) } if elements.count == 0 { elements.append([]) } return elements } set(newElements) { if newElements.count == 0 || newElements[0].count == 0 { self.innerDimensions = Dimensions() } else { self.innerDimensions = Dimensions(newElements.count, newElements[0].count) } self.elementsStructure = [] for i in 0 ..< self.dimensions.minimum { self.elementsStructure.append(newElements[i][i]) } } } // MARK: Initialisation /** Creates a square diagonal matrix with the given elements on it's main diagonal. */ public init(diagonal: [T]) { super.init() self.elementsStructure = diagonal self.innerDimensions = Dimensions(size: diagonal.count) } /** Creates a diagonal matrix with the given dimensions and the given elements on it's main diagonal. :exception: Throws an exception when the number of given diagonal elements is not equal to the minimum dimension of the given dimensions. */ public init(diagonal: [T], dimensions: Dimensions) { super.init() if diagonal.count != dimensions.minimum { NSException(name: "Wrong number of elements", reason: "The number of given diagonal elements (\(diagonal.count)) is not equal to the minimum dimension of the given dimensions (\(dimensions.minimum)).", userInfo: nil).raise() } self.elementsStructure = diagonal self.innerDimensions = dimensions } /** Creates a diagonal matrix with the given dimensions using the given generator. Note that the row and column values of the indives will be equal. - parameter dimensions: The dimensions the matrix should have. - parameter generator: The generator used to generate the matrix. This function is called for every element passing the index of the element. */ override public init(dimensions: Dimensions, generator: (Index) -> T) { super.init() self.elementsStructure = [] self.innerDimensions = dimensions for i in 0 ..< self.dimensions.minimum { self.elementsStructure.append(generator([i, i])) } } /** Creates a diagonal matrix with the given dimensions with the diagonal filled with the given element. - parameter element: The element to fill the diagonal with. - parameter dimensions: The dimensions the matrix should have. */ override public init(filledWith element: T, dimensions: Dimensions) { super.init() self.elementsStructure = [T](count: dimensions.minimum, repeatedValue: element) self.innerDimensions = dimensions } // MARK: Basic Properties /** Gives the rank of the matrix. This is not the tensor rank. - returns: The rank of the matrix. */ override public var rank: Int { //TODO: Improve this implementation using a general count function or something using diagonalElements var rank = self.dimensions.minimum for element in self.elementsStructure { if element == 0 { rank-- } } return rank } /** Returns the determinant of the matrix. This is the product of the diagonal elements. */ override public var determinant: T { return product(self.diagonalElements) } /** Gets or sets the diagonal elements of the matrix. - returns: An array with the diagonal elements of the matrix. :set: When the number of given elements is bigger than the minimum dimension of the matrix, the dimensions will be padded as few as possible. This means that when a 2x4 matrix is set using 3 elements it will only be padded to a 3x4 matrix. When the number of given elements is less than the minimum dimension of the matrix, the minimum dimensions will shrink even more. Unless the matrix is square. When it is square, both dimensions will shrink. This means that when a 3x4 matrix is set using 2 elements it will shrink to a 2x4 matrix, but when a 4x4 matrix is set using 2 elements it will shrink to a 2x2 matrix. */ override public var diagonalElements: [T] { get { return self.elementsStructure } set(elements) { self.elementsStructure = elements if elements.count >= self.dimensions.minimum { self.innerDimensions = Dimensions(max(elements.count, self.dimensions.rows), max(elements.count, self.dimensions.columns)) } else { if self.isSquare { self.innerDimensions = Dimensions(size: elements.count) } else { if self.dimensions.rows < self.dimensions.columns { self.innerDimensions = Dimensions(elements.count, self.dimensions.columns) } else { self.innerDimensions = Dimensions(self.dimensions.rows, elements.count) } } } } } /** Returns the elements of the diagonal at the given index. 0 represents the main diagonal. -1 means the first subdiagonal, this is the one below the main diagonal. Other negative numbers represent lower subdiagonals. 1 means the first superdiagonal, this is the one above the main diagonal. Other positive numbers represent higher superdiagonals. - parameter n: The diagonal's index. - returns: An array representing the diagonal elements from top left to bottom right in the matrix. :exception: An exception will be raised if the diagonal at the given index does not exist. This means -n > the number of rows or n > the number of columns. */ override public func diagonalElements(n: Int = 0) -> [T] { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: "Index out the bounds.", reason: "The given index is out of bounds.", userInfo: nil).raise() } if n == 0 { return elementsStructure } else { let cnt = min(self.dimensions.minimum, n < 0 ? self.dimensions.rows + n : self.dimensions.columns - n) return [T](count: cnt, repeatedValue: 0) } } /** Returns a copy of the matrix with all elements under the main diagonal set to zero. This also applies to non-square matrices. */ override public var upperTriangle: Matrix<T> { return self } /** Returns the upper triangle part of the matrix. This is the part of above the diagonal with the given index. The diagonal itself is also included. The part below the diagonal contains zero. 0 represents the main diagonal. -1 means the first subdiagonal, this is the one below the main diagonal. Other negative numbers represent lower subdiagonals. 1 means the first superdiagonal, this is the one above the main diagonal. Other positive numbers represent higher superdiagonals. :note: Note that this method also works for non-square matrices, but the returned matrix will thus be not upper triangular because only square matrices are upper triangular. - parameter n: The diagonal's index. - returns: A matrix where all elements under the diagonal with the given index are zero. :exception: An exception will be raised if the diagonal at the given index does not exist. This means -n > the number of rows or n > the number of columns. */ override public func upperTriangle(n: Int = 0) -> Matrix<T> { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: "Index out the bounds.", reason: "The given index is out of bounds.", userInfo: nil).raise() } if n == 0 { return self } else { return Matrix(filledWith: 0, dimensions: self.dimensions) } } /** Returns the lower triangle part of the matrix. This is the part of below the diagonal with the given index. The diagonal itself is also included. The part below the diagonal contains zero. 0 represents the main diagonal. -1 means the first subdiagonal, this is the one below the main diagonal. Other negative numbers represent lower subdiagonals. 1 means the first superdiagonal, this is the one above the main diagonal. Other positive numbers represent higher superdiagonals. :note: Note that this method also works for non-square matrices, but the returned matrix will thus be not lower triangular because only square matrices are lower triangular. - parameter n: The diagonal's index. - returns: A matrix where all elements above the diagonal with the given index are zero. :exception: An exception will be raised if the diagonal at the given index does not exist. This means -n >= the number of rows or n >= the number of columns. */ override public func lowerTriangle(n: Int = 0) -> Matrix<T> { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: "Index out the bounds.", reason: "The given index is out of bounds.", userInfo: nil).raise() } if n == 0 { return self } else { return Matrix(filledWith: 0, dimensions: self.dimensions) } } /** Returns the maximum element in the matrix if the matrix is not empty, otherwise it returns nil. */ override public var maxElement: T? { if self.isEmpty { return nil } else { return max(max(self.elementsStructure), 0) } } /** Returns the minimum element in the matrix if the matrix is not empty, otherwise it returns nil. */ override public var minElement: T? { if self.isEmpty { return nil } else { return min(min(self.elementsStructure), 0) } } /** Returns the transpose of the matrix. */ override public var transpose: Matrix<T> { return DiagonalMatrix(diagonal: self.elementsStructure, dimensions: self.dimensions.transpose) } /** Returns the conjugate of the matrix. */ override public var conjugate: Matrix<T> { return DiagonalMatrix(diagonal: self.elementsStructure.map{ $0.conjugate }, dimensions: self.dimensions) } /** Returns the conjugate transpose of the matrix. This is also called the Hermitian transpose. */ override public var conjugateTranspose: Matrix<T> { return DiagonalMatrix(diagonal: self.elementsStructure.map{ $0.conjugate }, dimensions: self.dimensions.transpose) } /** Returns whether all elements are zero. */ override public var isZero: Bool { for element in self.diagonalElements { if element != 0 { return false } } return true } /** Returns whether the matrix is diagonal. This means all elements that are not on the main diagonal are zero. */ override public var isDiagonal: Bool { return true } /** Returns whether the matrix is symmetrical. This method works O(2n) for symmetrical (square) matrixes of size n. - returns: true if the matrix is symmetrical. */ override public var isSymmetrical: Bool { return self.isSquare } /** Returns whether the matrix is upper triangular according to the given diagonal index. This means all elements below the diagonal at the given index n must be zero. When mustBeSquare is set to true the matrix must be square. - parameter n: The diagonal's index. - parameter mustBeSquare: Whether the matrix must be square to be upper triangular. */ override public func isUpperTriangular(n: Int = 0, mustBeSquare: Bool = true) -> Bool { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: "Index out the bounds.", reason: "The given diagonal index is out of bounds.", userInfo: nil).raise() } return (!mustBeSquare || self.isSquare) && (n <= 0 || self.isZero) } /** Returns whether the matrix is upper Hessenberg. This means all elements below the first subdiagonal are zero. */ override public var isUpperHessenberg: Bool { return self.isSquare } /** Returns whether the matrix is lower triangular according to the given diagonal index. This means all elements above the diagonal at the given index n must be zero. When mustBeSquare is set to true the matrix must be square. - parameter n: The diagonal's index. - parameter mustBeSquare: Whether the matrix must be square to be lower triangular. */ override public func isLowerTriangular(n: Int = 0, mustBeSquare: Bool = true) -> Bool { if -n >= self.dimensions.rows || n >= self.dimensions.columns { NSException(name: "Index out the bounds.", reason: "The given diagonal index is out of bounds.", userInfo: nil).raise() } return (!mustBeSquare || self.isSquare) && (n >= 0 || self.isZero) } /** Returns whether the matrix is a lower Hessenberg matrix. This means all elements above the first superdiagonal are zero. */ override public var isLowerHessenberg: Bool { return isLowerTriangular(1) } // MARK: Element Methods /** Returns the element at the given index (row, column). - parameter row: The row index of the requested element - parameter column: The column index of the requested element - returns: The element at the given index (row, column). */ override public func element(row: Int, _ column: Int) -> T { if row < 0 || row >= self.dimensions.rows { NSException(name: "Row index out of bounds", reason: "The requested element's row index is out of bounds.", userInfo: nil).raise() } if column < 0 || column >= self.dimensions.columns { NSException(name: "Column index out of bounds", reason: "The requested element's column index is out of bounds.", userInfo: nil).raise() } return row == column ? self.elementsStructure[row] : 0 } /** Sets the element at the given indexes. - parameter row: The row index of the element - parameter column: The column index of the element - parameter element: The element to set at the given indexes */ override public func setElement(atRow row: Int, atColumn column: Int, toElement element: T) { if row < 0 || row >= self.dimensions.rows { NSException(name: "Row index out of bounds", reason: "The row index at which the element should be set is out of bounds.", userInfo: nil) } if column < 0 || column >= self.dimensions.columns { NSException(name: "Column index out of bounds", reason: "The column index at which the element should be set is out of bounds.", userInfo: nil) } if row != column { NSException(name: "Unsettable element", reason: "Can't set a non-diagonal element.", userInfo: nil).raise() } self.elementsStructure[row] = element } /** Returns the row at the given index. The first row has index 0. - returns: The row at the given index. */ override public func row(index: Int) -> Vector<T> { if index < 0 || index >= self.dimensions.rows { NSException(name: "Row index out of bounds", reason: "The requested row's index is out of bounds.", userInfo: nil).raise() } var elementsList = [T](count: self.dimensions.columns, repeatedValue: 0) elementsList[index] = self.elementsStructure[index] return Vector(elementsList) } /** Sets the row at the given index to the given row. - parameter index: The index of the row to change. - parameter newRow: The row to set at the given index. */ override public func setRow(atIndex index: Int, toRow newRow: Vector<T>) { // If the index is out of bounds if index < 0 || index >= self.dimensions.rows { NSException(name: "Row index out of bounds", reason: "The index at which the row should be set is out of bounds.", userInfo: nil).raise() } // If the row's length is not correct if newRow.length != self.dimensions.columns { NSException(name: "New row wrong length", reason: "The new row's length is not equal to the matrix's number of columns.", userInfo: nil).raise() } for (i, element) in newRow.enumerate() { if i == index { self.elementsStructure[i] = element } else if element != 0 { NSException(name: "Unsettable element", reason: "All elements at non-diagonal positions must be zero.", userInfo: nil).raise() } } } /** Switches the rows at the given indexes. - parameter i: The index of the first row. - parameter j: The index of the second row. */ override public func switchRows(i: Int, _ j: Int) { NSException(name: "Can't switch rows", reason: "Rows can't be switched in a DiagonalMatrix.", userInfo: nil).raise() } /** Returns the column at the given index. The first column has index 0. - returns: The column at the given index. */ override public func column(index: Int) -> Vector<T> { if index < 0 || index >= self.dimensions.columns { NSException(name: "Column index out of bounds", reason: "The requested column's index is out of bounds.", userInfo: nil).raise() } var elementsList = [T](count: self.dimensions.rows, repeatedValue: 0) elementsList[index] = self.elementsStructure[index] return Vector(elementsList) } /** Sets the column at the given index to the given column. - parameter index: The index of the column to change. - parameter column: The column to set at the given index. */ override public func setColumn(atIndex index: Int, toColumn newColumn: Vector<T>) { // If the index is out of bounds if index < 0 || index >= self.dimensions.columns { NSException(name: "Column index out of bounds", reason: "The index at which the column should be set is out of bounds.", userInfo: nil).raise() } // If the column's length is not correct if newColumn.length != self.dimensions.rows { NSException(name: "New column wrong length", reason: "The new column's length is not equal to the matrix's number of rows.", userInfo: nil).raise() } for (i, element) in newColumn.enumerate() { if i == index { self.elementsStructure[i] = element } else if element != 0 { NSException(name: "Unsettable element", reason: "All elements at non-diagonal positions must be zero.", userInfo: nil).raise() } } } /** Switches the columns at the given indexes. - parameter i: The index of the first column. - parameter j: The index of the second column. */ override public func switchColumns(i: Int, _ j: Int) { NSException(name: "Can't switch columns", reason: "Columns can't be switched in a DiagonalMatrix.", userInfo: nil).raise() } /** Fills the diagonal with the given value. - parameter value: The value to fill the diagonal with. */ override public func fillDiagonal(value: T) { self.elementsStructure = [T](count: self.dimensions.minimum, repeatedValue: value) } } // MARK: DiagonalMatrix Equality /** Returns whether the two given matrices are equal. This means corresponding elements are equal. - parameter left: The left matrix in the equation. - parameter right: The right matrix in the equation. - returns: true if the two matrices are equal. */ public func == <T: MatrixCompatible> (left: DiagonalMatrix<T>, right: DiagonalMatrix<T>) -> Bool { if left.dimensions != right.dimensions { return false } return left.elementsStructure == right.elementsStructure } // MARK: Matrix Addition /** Returns the sum of the two matrices. - parameter left: The left matrix in the sum. - parameter right: The right matrix in the sum. - returns: A matrix of the same dimensions as the two given matrices. :exception: Throws an exception when the dimensions of the two matrices are not equal. */ public func + <T: MatrixCompatible> (left: DiagonalMatrix<T>, right: DiagonalMatrix<T>) -> DiagonalMatrix<T> { if left.dimensions != right.dimensions { NSException(name: "Unequal dimensions", reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } return DiagonalMatrix(diagonal: (Vector(left.elementsStructure) + Vector(right.elementsStructure)).elements, dimensions: left.dimensions) } /** Returns the sum of the two matrices. - parameter left: The left matrix in the sum. - parameter right: The right matrix in the sum. - returns: A matrix of the same dimensions as the two given matrices. :exception: Throws an exception when the dimensions of the two matrices are not equal. */ public func + (left: DiagonalMatrix<Float>, right: DiagonalMatrix<Float>) -> DiagonalMatrix<Float> { if left.dimensions != right.dimensions { NSException(name: "Unequal dimensions", reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } var diagonal = right.elementsStructure cblas_saxpy(Int32(left.dimensions.minimum), 1.0, left.elementsStructure, 1, &diagonal, 1) return DiagonalMatrix(diagonal: diagonal, dimensions: left.dimensions) } /** Returns the sum of the two matrices. - parameter left: The left matrix in the sum. - parameter right: The right matrix in the sum. - returns: A matrix of the same dimensions as the two given matrices. :exception: Throws an exception when the dimensions of the two matrices are not equal. */ public func + (left: DiagonalMatrix<Double>, right: DiagonalMatrix<Double>) -> DiagonalMatrix<Double> { if left.dimensions != right.dimensions { NSException(name: "Unequal dimensions", reason: "The dimensions of the two matrices are not equal.", userInfo: nil).raise() } var diagonal = right.elementsStructure cblas_daxpy(Int32(left.dimensions.minimum), 1.0, left.elementsStructure, 1, &diagonal, 1) return DiagonalMatrix(diagonal: diagonal, dimensions: left.dimensions) }
mit
0b00efa278b1d710d2eefdc412244731
33.608805
240
0.58456
4.943935
false
false
false
false
einsteinx2/iSub
Classes/Singletons/SavedSettings.swift
1
11940
// // SavedSettings.swift // iSub // // Created by Benjamin Baron on 1/23/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class SavedSettings { struct Keys { // MARK: Settings static let currentServerId = "currentServerId" static let currentServer = "currentServer" static let redirectUrlString = "redirectUrlString" static let isScreenSleepEnabled = "isScreenSleepEnabled" static let isDisableUsageOver3G = "isDisableUsageOver3G" static let quickSkipNumberOfSeconds = "quickSkipNumberOfSeconds" static let maxBitRate3G = "maxBitrate3GSetting" static let maxBitRateWifi = "maxBitrateWifiSetting" static let maxVideoBitRate3G = "maxVideoBitrate3G" static let maxVideoBitRateWifi = "maxVideoBitrateWifi" static let isManualCachingOnWWANEnabled = "isManualCachingOnWWANEnabled" static let isAutoSongCachingEnabled = "isSongCachingEnabled" static let isNextSongCacheEnabled = "enableNextSongCacheSetting" static let isBackupCacheEnabled = "isBackupCacheEnabled" static let minFreeSpace = "minFreeSpace" static let maxCacheSize = "maxCacheSize" // MARK: Saved state static let rootArtistSortOrder = "rootArtistSortOrder" static let rootAlbumSortOrder = "rootAlbumSortOrder" static let seekTime = "seekTime" static let isPlayerZoomed = "isPlayerZoomed" static let byteOffset = "byteOffset" static let isEqualizerOn = "isEqualizerOn" static let preampGain = "gainMultiplier" } struct JGUserDefaults { static let disableScreenSleep = JGUserDefault(key: Keys.isScreenSleepEnabled, defaultValue: true) static let disableUsageCell = JGUserDefault(key: Keys.isDisableUsageOver3G, defaultValue: false) static let quickSkipLength = JGUserDefault(key: Keys.quickSkipNumberOfSeconds, defaultValue: 10) static let maxAudioBitrateCell = JGUserDefault(key: Keys.maxBitRate3G, defaultValue: 7) static let maxAudioBitrateWifi = JGUserDefault(key: Keys.maxBitRateWifi, defaultValue: 7) static let maxVideoBitrateCell = JGUserDefault(key: Keys.maxVideoBitRate3G, defaultValue: 3) static let maxVideoBitrateWifi = JGUserDefault(key: Keys.maxVideoBitRateWifi, defaultValue: 3) static let downloadUsingCell = JGUserDefault(key: Keys.isManualCachingOnWWANEnabled, defaultValue: false) static let autoSongCaching = JGUserDefault(key: Keys.isAutoSongCachingEnabled, defaultValue: true) static let preloadNextSong = JGUserDefault(key: Keys.isNextSongCacheEnabled, defaultValue: true) static let backupDownloads = JGUserDefault(key: Keys.isBackupCacheEnabled, defaultValue: false) static let minFreeSpace = JGUserDefault(key: Keys.minFreeSpace, defaultValue: Float(256 * 1024 * 1024)) static let maxCacheSize = JGUserDefault(key: Keys.maxCacheSize, defaultValue: Float(1024 * 1024 * 1024)) } static let si = SavedSettings() fileprivate let storage = UserDefaults.standard fileprivate let lock = SpinLock() func setup() { UIApplication.shared.isIdleTimerDisabled = !isScreenSleepEnabled createInitialSettings() } fileprivate func createInitialSettings() { let defaults: [String: Any] = [Keys.maxBitRateWifi: 7, Keys.maxBitRate3G: 7, Keys.isAutoSongCachingEnabled: true, Keys.isNextSongCacheEnabled: true, Keys.maxCacheSize: 1024 * 1024 * 1024, // 1GB Keys.minFreeSpace: 256 * 1024 * 1024, // 256MB Keys.isScreenSleepEnabled: true, Keys.maxVideoBitRateWifi: 3, Keys.maxVideoBitRate3G: 3, Keys.currentServerId: Server.testServerId, Keys.rootArtistSortOrder: ArtistSortOrder.name.rawValue, Keys.rootAlbumSortOrder: AlbumSortOrder.name.rawValue] storage.register(defaults: defaults) } var currentServerId: Int64 { get { return lock.synchronizedResult { return self.storage.object(forKey: Keys.currentServerId) as? Int64 ?? -1 }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.currentServerId) }} } var isTestServer: Bool { return currentServerId == Server.testServerId } var currentServer: Server { let serverId = currentServerId if serverId == Server.testServerId { return Server.testServer } else { return ServerRepository.si.server(serverId: serverId) ?? Server.testServer } } var redirectUrlString: String? { get { return lock.synchronizedResult { return self.storage.string(forKey: Keys.redirectUrlString) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.redirectUrlString) }} } var isOfflineMode: Bool = false var maxBitRateWifi: Int { get { return lock.synchronizedResult { return self.storage.integer(forKey: Keys.maxBitRateWifi) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.maxBitRateWifi) }} } var maxBitRate3G: Int { get { return lock.synchronizedResult { return self.storage.integer(forKey: Keys.maxBitRate3G) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.maxBitRate3G) }} } var currentMaxBitRate: Int { let maxBitRate = AppDelegate.si.networkStatus.isReachableWifi ? maxBitRateWifi : maxBitRate3G switch maxBitRate { case 0: return 64; case 1: return 96; case 2: return 128; case 3: return 160; case 4: return 192; case 5: return 256; case 6: return 320; default: return 0; } } var maxVideoBitRateWifi: Int { get { return lock.synchronizedResult { return self.storage.integer(forKey: Keys.maxVideoBitRateWifi) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.maxVideoBitRateWifi) }} } var maxVideoBitRate3G: Int { get { return lock.synchronizedResult { return self.storage.integer(forKey: Keys.maxVideoBitRate3G) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.maxVideoBitRate3G) }} } var currentVideoBitRates: [Int] { let maxBitRate = AppDelegate.si.networkStatus.isReachableWifi ? maxVideoBitRateWifi : maxVideoBitRate3G switch maxBitRate { case 0: return [60] case 1: return [256, 60] case 2: return [512, 256, 60] case 3: return [1024, 512, 60] case 4: return [1536, 768, 60] case 5: return [2048, 1024, 60] default: return [] } } var isAutoSongCachingEnabled: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isAutoSongCachingEnabled) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isAutoSongCachingEnabled) }} } var isNextSongCacheEnabled: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isNextSongCacheEnabled) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isNextSongCacheEnabled) }} } var isBackupCacheEnabled: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isBackupCacheEnabled) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isBackupCacheEnabled) } CacheManager.si.backupSongCache = newValue } } var isManualCachingOnWWANEnabled: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isManualCachingOnWWANEnabled) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isManualCachingOnWWANEnabled) } if AppDelegate.si.networkStatus.isReachableWWAN { newValue ? DownloadQueue.si.start() : DownloadQueue.si.stop() } } } var maxCacheSize: Int64 { get { return lock.synchronizedResult { return self.storage.object(forKey: Keys.maxCacheSize) as? Int64 ?? -1 }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.maxCacheSize) }} } var minFreeSpace: Int64 { get { return lock.synchronizedResult { return self.storage.object(forKey: Keys.minFreeSpace) as? Int64 ?? -1 }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.minFreeSpace) }} } var isScreenSleepEnabled: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isScreenSleepEnabled) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isScreenSleepEnabled) }} } var quickSkipNumberOfSeconds: Int { get { return lock.synchronizedResult { return self.storage.integer(forKey: Keys.quickSkipNumberOfSeconds) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.quickSkipNumberOfSeconds) }} } var isDisableUsageOver3G: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isDisableUsageOver3G) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isDisableUsageOver3G) }} } var rootArtistSortOrder: ArtistSortOrder { get { return lock.synchronizedResult { let rawValue = self.storage.integer(forKey: Keys.rootArtistSortOrder) return ArtistSortOrder(rawValue: rawValue) ?? .name } } set { lock.synchronized { self.storage.set(newValue.rawValue, forKey: Keys.rootArtistSortOrder) }} } var rootAlbumSortOrder: AlbumSortOrder { get { return lock.synchronizedResult { let rawValue = self.storage.integer(forKey: Keys.rootAlbumSortOrder) return AlbumSortOrder(rawValue: rawValue) ?? .name } } set { lock.synchronized { self.storage.set(newValue.rawValue, forKey: Keys.rootAlbumSortOrder) }} } // MARK: - State Saving - var seekTime: Double { get { return lock.synchronizedResult { return self.storage.double(forKey: Keys.seekTime) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.seekTime) }} } var byteOffset: Int64 { get { return lock.synchronizedResult { return self.storage.object(forKey: Keys.byteOffset) as? Int64 ?? 0 }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.byteOffset) }} } var isPlayerZoomed: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isPlayerZoomed) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isPlayerZoomed) }} } var isEqualizerOn: Bool { get { return lock.synchronizedResult { return self.storage.bool(forKey: Keys.isEqualizerOn) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.isEqualizerOn) }} } var preampGain: Float { get { return lock.synchronizedResult { return self.storage.float(forKey: Keys.preampGain) }} set { lock.synchronized { self.storage.set(newValue, forKey: Keys.preampGain) }} } }
gpl-3.0
79f5885b6ceb5628a01f3638bf103ba2
44.223485
122
0.642851
4.481607
false
false
false
false
vknabel/Rock
Sources/RockLib/YamlAndStencil.swift
1
3227
import Foundation import PathKit import Stencil import Yaml typealias ContextLiteral = [String: Any] private extension String { func render(_ context: ContextLiteral? = nil) throws -> String { let template = Template(templateString: self) return try template.render(context) } } private func sortDescriptor(by order: [Yaml]) -> Yaml.YamlSortDescriptor { func priority(_ yaml: Yaml) -> Int? { return order.index(of: yaml) } return { (lhs: (Yaml, Yaml), rhs: (Yaml, Yaml)) -> Bool in switch (priority(lhs.0), priority(rhs.0)) { case let (.some(lhs), .some(rhs)): return lhs < rhs case (.some(_), _): return true case (_, .some(_)): return false default: return true } } } private extension Yaml { /// Dict: only strings var rawValue: Any { switch self { case .null: return () case let .bool(value): return value case let .int(value): return value case let .double(value): return value case let .string(value): return value case let .array(value): return value.map { $0.rawValue } case let .dictionary(dict): var rawDict = [String: Any]() for (key, value) in dict { guard let key = key.string else { continue } rawDict[key] = value.rawValue } return rawDict } } func render( _ dictionary: [String: Any], descriptor: Yaml.YamlSortDescriptor ) throws -> (Any, Yaml) { let context = dictionary switch self { case let .string(value): let rendered = try value.render(context) return (rendered, .string(rendered)) case let .array(values): var contextList = [Any]() var vs = [(Any, Yaml)]() for v in values { let result = try v.render(dictionary, descriptor: descriptor) contextList.append(result.0) vs.append(result) } return (vs.map { $0.0 }, .array(vs.map { $0.1 })) case let .dictionary(value): var dict = [Yaml: Yaml]() var dictionary = dictionary var localDictionary: [String: Any] = [:] try value.sorted(by: descriptor).forEach { key, value in let renderedKey = try key.render(dictionary, descriptor: descriptor) let renderedValue = try value.render(dictionary, descriptor: descriptor) dict[renderedKey.1] = renderedValue.1 if let renderedKey = renderedKey.0 as? String { localDictionary[renderedKey] = renderedValue.0 dictionary[renderedKey] = renderedValue.0 } } return (localDictionary, .dictionary(dict)) default: return (self.rawValue, self) } } } public extension Yaml { public typealias YamlSortDescriptor = ((Yaml, Yaml), (Yaml, Yaml)) -> Bool public static func rendering( _ text: String, orderedBy order: [Yaml] = ["const", "constant", "constants", "version", "license", "name", "url"] ) throws -> Yaml { return try rendering(text, sort: sortDescriptor(by: order)) } public static func rendering( _ text: String, sort descriptor: YamlSortDescriptor ) throws -> Yaml { return try Yaml.load(text).render([:], descriptor: descriptor).1 } }
mit
8218b27350ac5c01ab6fdf46f6ebba84
27.307018
101
0.612333
4.028714
false
false
false
false
zSher/BulletThief
BulletThief/BulletThief/ShopItem.swift
1
2873
// // ShopItem.swift // BulletThief // // Created by Zachary on 5/8/15. // Copyright (c) 2015 Zachary. All rights reserved. // import UIKit // class ShopItem: NSObject { var itemName:String = "" var detailText:String = "" var cost:UInt = 0 var baseCost:UInt = 0 var costChange:UInt = 0 var action: (data:PlayerData) -> () //callback for what this item should do when purchased var equippable = false override init() { action = {(data) in } super.init() } //init with properties convenience init(name:String, detail:String, cost:UInt, costChange:UInt, costLevel:UInt, action: (data:PlayerData) -> (), equippable: Bool = false) { self.init() self.itemName = name self.detailText = detail self.baseCost = cost self.costChange = costChange if equippable { calculateEquipmentCost(playerData.purchasedBulletSetFlags[itemName]!) } else { calculateCost(costLevel) } self.action = action self.equippable = equippable } //Recalculate the cost of the item based on the player's current level of this item func calculateCost(costLevel: UInt){ self.cost = baseCost + costChange * (costLevel - 1) } //Recalculate cost of equipment, if it is bought already the cost is 0 func calculateEquipmentCost(costLevel: UInt){ if costLevel == 1 { self.cost = baseCost + costChange * (costLevel - 1) } else { cost = 0 } } //Apply the closure func applyItemEffect(data:PlayerData) { self.action(data: data) //function pointers, cooool } } //Singleton to hold all item effects that are given to a shop item class ItemEffectLibrary { //increase movement speed by 10% func increaseMovementSpeed(data:PlayerData) { data.speedLevel += 1 } //increase bullet fire rate by 10% func increaseFireRate(data:PlayerData) { data.bulletDelayLevel += 1 } //increase bullet damage func increaseBulletDamage(data:PlayerData) { //TODO: Bullet damage println("Bullet Damage Not Completed yet") } //increase number of shots per fire func increaseBulletNumber(data:PlayerData){ data.bulletNumber += 1 } //Equip default set func equipDefaultSet(data:PlayerData){ data.bulletSet = DefaultSet(data: data) } //Equip double cross set func equipDoubleCrossSet(data:PlayerData){ data.bulletSet = DoubleCrossSet(data: data) println(data.bulletSet!.bulletEffects) } //Equip hyper rapid set func equipHyperRapidSet(data:PlayerData){ data.bulletSet = HyperRapidFireSet(data:data) } } var itemEffectLibrary = ItemEffectLibrary() //SINGLETON
mit
6983f06abbb25114e896feab55c1997c
26.902913
154
0.628959
4.069405
false
false
false
false
clappr/clappr-ios
Tests/Clappr_Tests/Classes/Plugin/Playback/AVFoundationPlaybackTests.swift
1
85671
import Quick import Nimble import AVFoundation import OHHTTPStubs @testable import Clappr class AVFoundationPlaybackTests: QuickSpec { override func spec() { describe("AVFoundationPlayback Tests") { var asset: AVURLAssetStub! var item: AVPlayerItemStub! var player: AVPlayerStub! var playback: AVFoundationPlayback! var itemInfo: AVPlayerItemInfo! beforeEach { OHHTTPStubs.removeAllStubs() asset = AVURLAssetStub(url: URL(string: "https://www.google.com")!, options: nil) item = AVPlayerItemStub(asset: asset) player = AVPlayerStub() player.set(currentItem: item) playback = AVFoundationPlayback(options: [:]) playback.player = player playback.render() itemInfo = AVPlayerItemInfo(item: item, delegate: playback) playback.itemInfo = itemInfo stub(condition: isHost("clappr.sample") || isHost("clappr.io")) { result in if result.url?.path == "/master.m3u8" { let stubPath = OHPathForFile("master.m3u8", type(of: self)) return fixture(filePath: stubPath!, headers: [:]) } else if result.url!.path.contains(".ts") { let stubPath = OHPathForFile(result.url!.path.replacingOccurrences(of: "/", with: ""), type(of: self)) return fixture(filePath: stubPath!, headers: [:]) } let stubPath = OHPathForFile("sample.m3u8", type(of: self)) return fixture(filePath: stubPath!, headers: [:]) } } afterEach { playback.stop() itemInfo = nil asset = nil item = nil player = nil playback = nil itemInfo = nil OHHTTPStubs.removeAllStubs() } describe("#init") { context("without current item") { it("it should call update asset if needed when current item is set") { var didCallEventReady = false playback = AVFoundationPlayback(options: [:]) playback.render() expect(playback.itemInfo).to(beNil()) expect(playback.player.currentItem).to(beNil()) playback.on(Event.ready.rawValue) { _ in didCallEventReady = true } playback.player.replaceCurrentItem(with: item) playback.play() expect(playback.itemInfo).toNot(beNil()) expect(playback.player.currentItem).toNot(beNil()) expect(didCallEventReady).toEventually(beTrue(), timeout: 5) } } context("without kLoop option") { it("instantiates player as an instance of AVPlayer") { let options = [kSourceUrl: "http://clappr.io/highline.mp4"] let playback = AVFoundationPlayback(options: options) playback.play() expect(playback.player).to(beAKindOf(AVPlayer.self)) } } context("with kLoop option") { it("instantiates player as an instance of AVQueuePlayer") { let options: Options = [kSourceUrl: "http://clappr.io/highline.mp4", kLoop: true] let playback = AVFoundationPlayback(options: options) playback.play() expect(playback.player).to(beAKindOf(AVQueuePlayer.self)) } context("when video finishes") { it("triggers didLoop event") { let options: Options = [kSourceUrl: "http://clappr.sample/sample.m3u8", kLoop: true] playback = AVFoundationPlayback(options: options) playback.render() var didLoopTriggered = false playback.on(Event.didLoop.rawValue) { _ in didLoopTriggered = true } playback.on(Event.assetReady.rawValue) { _ in playback.seek(playback.duration) } playback.play() expect(didLoopTriggered).toEventually(beTrue(), timeout: 10) } } context("on destroy") { it("stops observing loopCount") { let options: Options = [kSourceUrl: "http://clappr.io/highline.mp4", kLoop: true] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.destroy() expect(playback.loopObserver).to(beNil()) } } } } describe("AVFoundationPlaybackExtension") { describe("#minDvrSize") { context("when minDvrOption has correct type value") { it("return minDvrOption value") { let options = [kMinDvrSize: 15.1] let playback = AVFoundationPlayback(options: options) expect(playback.minDvrSize).to(equal(15.1)) } } context("when minDvrOption has wrong type value") { it("return default value") { let options = [kMinDvrSize: 15] let playback = AVFoundationPlayback(options: options) expect(playback.minDvrSize).to(equal(60)) } } context("when minDvrOption has no value") { it("returns default value") { expect(playback.minDvrSize).to(equal(60)) } } } describe("#didChangeDvrStatus") { context("when video is vod") { it("returns false") { asset.set(duration: CMTime(seconds: 60, preferredTimescale: 1)) expect(playback.isDvrInUse).to(beFalse()) } } context("when video is live") { beforeEach { item._duration = CMTime.indefinite } context("video has dvr") { context("when dvr is being used") { it("triggers didChangeDvrStatus with inUse true") { item.setSeekableTimeRange(with: 60) item.set(currentTime: CMTime(seconds: 54, preferredTimescale: 1)) itemInfo.update(item: item) var usingDVR = false playback.on(Event.didChangeDvrStatus.rawValue) { info in if let enabled = info?["inUse"] as? Bool { usingDVR = enabled } } player.setStatus(to: .readyToPlay) playback.seek(50) expect(usingDVR).toEventually(beTrue()) } } context("when dvr is not being used") { it("triggers didChangeDvrStatus with inUse false") { player.set(currentTime: CMTime(seconds: 60, preferredTimescale: 1)) item.setSeekableTimeRange(with: 60) itemInfo.update(item: item) var usingDVR = false playback.on(Event.didChangeDvrStatus.rawValue) { info in if let enabled = info?["inUse"] as? Bool { usingDVR = enabled } } player.setStatus(to: .readyToPlay) playback.seek(60) expect(usingDVR).toEventually(beFalse()) } } } context("whe video does not have dvr") { it("doesn't trigger didChangeDvrStatus event") { player.set(currentTime: CMTime(seconds: 59, preferredTimescale: 1)) var usingDVR: Bool? playback.on(Event.didChangeDvrStatus.rawValue) { info in if let enabled = info?["inUse"] as? Bool { usingDVR = enabled } } player.setStatus(to: .readyToPlay) playback.seek(60) expect(usingDVR).toEventually(beNil()) } } } } describe("#pause") { beforeEach { item._duration = CMTime.indefinite itemInfo.update(item: item) } context("video has dvr") { it("triggers usinDVR with enabled true") { item.setSeekableTimeRange(with: 60) player.setStatus(to: .readyToPlay) var didChangeDvrStatusTriggered = false playback.on(Event.didChangeDvrStatus.rawValue) { info in didChangeDvrStatusTriggered = true } playback.pause() expect(didChangeDvrStatusTriggered).toEventually(beTrue()) } } context("whe video does not have dvr") { it("doesn't trigger usingDVR event") { var didChangeDvrStatusTriggered = false playback.on(Event.didChangeDvrStatus.rawValue) { info in didChangeDvrStatusTriggered = true } playback.pause() expect(didChangeDvrStatusTriggered).toEventually(beFalse()) } } } describe("#didChangeDvrAvailability") { var playback: AVFoundationPlayback! var playerItem: AVPlayerItemStub? var available: Bool? var didCallChangeDvrAvailability: Bool? let playerAsset = AVURLAssetStub(url: URL(string: "http://clappr.sample/master.m3u8")!) func setupTest(minDvrSize: Double, seekableTimeRange: Double, duration: CMTime = .indefinite) { playback = AVFoundationPlayback(options: [kMinDvrSize: minDvrSize]) playerItem = AVPlayerItemStub(asset: playerAsset) playerItem!._duration = duration playerItem!.setSeekableTimeRange(with: seekableTimeRange) let player = AVPlayerStub() player.set(currentItem: playerItem!) playback.player = player player.setStatus(to: .readyToPlay) itemInfo = AVPlayerItemInfo(item: playerItem!, delegate: playback) playback.itemInfo = itemInfo playback.on(Event.didChangeDvrAvailability.rawValue) { info in didCallChangeDvrAvailability = true if let dvrAvailable = info?["available"] as? Bool { available = dvrAvailable } } } beforeEach { didCallChangeDvrAvailability = false } context("when calls handleDvrAvailabilityChange") { context("and lastDvrAvailability is nil") { context("and seekableTime duration its lower than minDvrSize (dvr not available)") { it("calls didChangeDvrAvailability event with available false") { setupTest(minDvrSize: 60.0, seekableTimeRange: 45.0, duration: .indefinite) playback.lastDvrAvailability = nil playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beTrue()) expect(available).toEventually(beFalse()) } } context("and seekableTime duration its higher(or equal) than minDvrSize (dvr available)") { it("calls didChangeDvrAvailability event with available true") { setupTest(minDvrSize: 60.0, seekableTimeRange: 75.0, duration: .indefinite) playback.lastDvrAvailability = nil playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beTrue()) expect(available).toEventually(beTrue()) } } } context("and lastDvrAvailability is true") { context("and seekableTime duration its lower than minDvrSize (dvr not available)") { it("calls didChangeDvrAvailability event with available false") { setupTest(minDvrSize: 60.0, seekableTimeRange: 45.0, duration: .indefinite) playback.lastDvrAvailability = true playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beTrue()) expect(available).toEventually(beFalse()) } } context("and seekableTime duration its higher(or equal) than minDvrSize (dvr available)") { it("does not call didChangeDvrAvailability") { setupTest(minDvrSize: 60.0, seekableTimeRange: 85.0, duration: .indefinite) playback.lastDvrAvailability = true playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beFalse()) } } } context("and lastDvrAvailability is false") { context("and seekableTime duration its lower than minDvrSize (dvr not available)") { it("does not call didChangeDvrAvailability") { setupTest(minDvrSize: 60.0, seekableTimeRange: 35.0, duration: .indefinite) playback.lastDvrAvailability = false playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beFalse()) } } context("and seekableTime duration its higher(or equal) than minDvrSize (dvr available)") { it("calls didChangeDvrAvailability event with available true") { setupTest(minDvrSize: 60.0, seekableTimeRange: 75.0, duration: .indefinite) playback.lastDvrAvailability = false playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beTrue()) expect(available).toEventually(beTrue()) } } } } context("video is not live") { it("does not call didChangeDvrAvailability") { setupTest(minDvrSize: 60.0, seekableTimeRange: 45.0, duration: CMTime(seconds: 60, preferredTimescale: 1)) playback.lastDvrAvailability = nil playback.handleDvrAvailabilityChange() expect(didCallChangeDvrAvailability).toEventually(beFalse()) } } } describe("#seekableTimeRanges") { context("when video has seekableTimeRanges") { it("returns an array with NSValue") { item.setSeekableTimeRange(with: 60) expect(playback.seekableTimeRanges).toNot(beEmpty()) } } context("when video does not have seekableTimeRanges") { it("is empty") { expect(playback.seekableTimeRanges).to(beEmpty()) } } } describe("#epochDvrWindowStart") { it("returns the epoch time corresponding to the DVR start") { let now = Date() player.setStatus(to: .readyToPlay) item._duration = .indefinite item.setSeekableTimeRange(with: 200) item.setWindow(start: 100, end: 160) item._currentTime = CMTime(seconds: 125, preferredTimescale: 1) itemInfo.update(item: item) item.set(currentDate: now) let dvrStart = now.addingTimeInterval(-25).timeIntervalSince1970 expect(playback.epochDvrWindowStart).to(equal(dvrStart)) } } describe("#loadedTimeRanges") { context("when video has loadedTimeRanges") { it("returns an array with NSValue") { player.setStatus(to: .readyToPlay) itemInfo.update(item: item) item.setLoadedTimeRanges(with: 60) expect(playback.loadedTimeRanges).toNot(beEmpty()) } } context("when video does not have loadedTimeRanges") { it("is empty") { player.setStatus(to: .readyToPlay) itemInfo.update(item: item) expect(playback.loadedTimeRanges).to(beEmpty()) } } } describe("#isDvrAvailable") { context("when video is vod") { it("returns false") { asset.set(duration: CMTime(seconds: 60, preferredTimescale: 1)) expect(playback.isDvrAvailable).to(beFalse()) } } context("when video is live") { it("returns true") { player.setStatus(to: .readyToPlay) itemInfo.update(item: item) item._duration = .indefinite item.setSeekableTimeRange(with: 60) expect(playback.isDvrAvailable).to(beTrue()) } } } describe("#position") { context("when live") { context("and DVR is available") { it("returns the position inside the DVR window") { player.setStatus(to: .readyToPlay) itemInfo.update(item: item) item._duration = .indefinite item.setSeekableTimeRange(with: 200) item.setWindow(start: 100, end: 160) item._currentTime = CMTime(seconds: 125, preferredTimescale: 1) expect(playback.position).to(equal(25)) } } context("and dvr is not available") { it("returns 0") { asset.set(duration: .indefinite) item.setSeekableTimeRange(with: 0) expect(playback.position).to(equal(0)) } } } context("when vod") { it("returns current time") { player.setStatus(to: .readyToPlay) item._duration = CMTime(seconds: 160, preferredTimescale: 1) item._currentTime = CMTime(seconds: 125, preferredTimescale: 1) itemInfo.update(item: item) expect(playback.position).to(equal(125)) } } } describe("#currentDate") { it("returns the currentDate of the video") { let date = Date() item.set(currentDate: date) expect(playback.currentDate).to(equal(date)) } } describe("#currentLiveDate") { context("when a video is not live") { it("returns nil") { let playback = StubbedLiveDatePlayback(options: [:]) playback.player = player playback._playbackType = .vod expect(playback.currentLiveDate).to(beNil()) } } context("when there's a currentDate") { it("returns the currentLiveDate of the video") { let playback = StubbedLiveDatePlayback(options: [:]) playback.player = player let currentDate = Date() item.set(currentDate: currentDate) playback._position = 0 playback._duration = 0 expect(playback.currentLiveDate?.timeIntervalSince1970).to(equal(currentDate.timeIntervalSince1970)) } } context("when the video is not at the live position") { it("returns the currentLiveDate of the video") { let playback = StubbedLiveDatePlayback(options: [:]) playback.player = player let currentDate = Date() item.set(currentDate: currentDate) playback._position = 30 playback._duration = 1000 expect(currentDate.timeIntervalSince1970).to(beLessThan(playback.currentLiveDate?.timeIntervalSince1970)) } } } } describe("#duration") { var asset: AVURLAssetStub! var item: AVPlayerItemStub! var player: AVPlayerStub! var playback: AVFoundationPlayback! beforeEach { asset = AVURLAssetStub(url: URL(string: "https://www.google.com")!, options: nil) item = AVPlayerItemStub(asset: asset) player = AVPlayerStub() player.set(currentItem: item) playback = AVFoundationPlayback(options: [:]) playback.player = player } context("when video is vod") { it("returns different from zero") { player.setStatus(to: .readyToPlay) item._duration = CMTime(seconds: 60, preferredTimescale: 1) itemInfo = AVPlayerItemInfo(item: item, delegate: playback) playback.itemInfo = itemInfo player.set(currentItem: item) expect(playback.duration).to(equal(60)) } } context("when video is live") { context("when has dvr enabled") { it("returns different from zero") { item._duration = .indefinite item.setSeekableTimeRange(with: 60) itemInfo = AVPlayerItemInfo(item: item, delegate: playback) playback.itemInfo = itemInfo player.setStatus(to: .readyToPlay) expect(playback.duration).to(equal(60)) } } context("when doesn't have dvr enabled") { it("returns zero") { item._duration = .indefinite player.setStatus(to: .readyToPlay) expect(playback.duration).to(equal(0)) } } } } context("canPlay media") { it("Should return true for valid url with mp4 path extension") { let options = [kSourceUrl: "http://clappr.io/highline.mp4"] let canPlay = AVFoundationPlayback.canPlay(options) expect(canPlay).to(beTrue()) } it("Should return true for valid url with m3u8 path extension") { let options = [kSourceUrl: "http://clappr.io/highline.m3u8"] let canPlay = AVFoundationPlayback.canPlay(options) expect(canPlay).to(beTrue()) } it("Should return true for valid url without path extension with supported mimetype") { let options = [kSourceUrl: "http://clappr.io/highline", kMimeType: "video/avi"] let canPlay = AVFoundationPlayback.canPlay(options) expect(canPlay).to(beTrue()) } it("Should return false for invalid url") { let options = [kSourceUrl: "123123"] let canPlay = AVFoundationPlayback.canPlay(options) expect(canPlay).to(beFalse()) } it("Should return false for url with invalid path extension") { let options = [kSourceUrl: "http://clappr.io/highline.zip"] let canPlay = AVFoundationPlayback.canPlay(options) expect(canPlay).to(beFalse()) } } context("playback state") { var playback: AVFoundationPlaybackMock! beforeEach { playback = AVFoundationPlaybackMock(options: [:]) } context("idle") { beforeEach { playback = AVFoundationPlaybackMock(options: [:]) playback.set(state: .idle) } it("canPlay") { expect(playback.canPlay).to(beTrue()) } it("canPause") { expect(playback.canPause).to(beTrue()) } } context("paused") { beforeEach { playback.set(state: .paused) } it("canPlay") { expect(playback.canPlay).to(beTrue()) } it("cannot Pause") { expect(playback.canPause).to(beFalse()) } } context("stalling") { beforeEach { playback.set(state: .stalling) } context("and asset is ready to play") { it("canPlay") { let url = URL(string: "http://clappr.sample/master.m3u8")! let playerAsset = AVURLAssetStub(url: url) let playerItem = AVPlayerItemStub(asset: playerAsset) playerItem._status = .readyToPlay let player = AVPlayerStub() player.set(currentItem: playerItem) playback.player = player expect(playback.canPlay).to(beTrue()) } } it("canPause") { expect(playback.canPause).to(beTrue()) } } context("playing") { beforeEach { playback.set(state: .playing) } it("cannot play") { expect(playback.canPlay).to(beFalse()) } it("canPause") { expect(playback.canPause).to(beTrue()) } context("live video with no DVR support") { it("cannot Pause") { playback._playbackType = .live playback.set(isDvrAvailable: false) expect(playback.canPause).to(beFalse()) } } context("live video with DVR support") { it("canSeek") { playback._playbackType = .live playback.set(isDvrAvailable: true) expect(playback.canSeek).to(beTrue()) } } context("video with zero duration") { it("cannot Seek") { playback._playbackType = .vod playback.videoDuration = 0.0 expect(playback.canSeek).to(beFalse()) } } } context("error") { beforeEach { playback.set(state: .error) } it("cannot Seek") { expect(playback.canSeek).to(beFalse()) } } } if #available(iOS 11.0, *) { #if os(iOS) context("when did change bounds") { it("sets preferredMaximumResolution according to playback bounds size") { let playback = AVFoundationPlayback(options: [kSourceUrl: "http://clappr.io/slack.mp4"]) playback.render() playback.play() playback.view.bounds = CGRect(x: 0, y: 0, width: 200, height: 200) let playerSize = playback.view.bounds.size let mainScale = UIScreen.main.scale let screenSize = CGSize(width: playerSize.width * mainScale, height: playerSize.height * mainScale) expect(playback.player?.currentItem?.preferredMaximumResolution).to(equal(screenSize)) } } #endif context("when setups avplayer") { beforeEach { stub(condition: isHost("clappr.io")) { _ in let stubPath = OHPathForFile("video.mp4", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type":"video/mp4"]) } } afterEach { OHHTTPStubs.removeAllStubs() } #if os(iOS) it("sets preferredMaximumResolution according to playback bounds size") { let playback = AVFoundationPlayback(options: [kSourceUrl: "http://clappr.io/slack.mp4"]) playback.render() playback.view.bounds = CGRect(x: 0, y: 0, width: 200, height: 200) let playerSize = playback.view.bounds.size let mainScale = UIScreen.main.scale let screenSize = CGSize(width: playerSize.width * mainScale, height: playerSize.height * mainScale) playback.play() expect(playback.player?.currentItem?.preferredMaximumResolution).toEventually(equal(screenSize)) } #endif it("trigger didUpdateDuration") { let playback = AVFoundationPlayback(options: [kSourceUrl: "http://clappr.sample/master.m3u8"]) var callDidUpdateDuration = false playback.render() playback.on(Event.didUpdateDuration.rawValue) { userInfo in callDidUpdateDuration = true } playback.play() expect(callDidUpdateDuration).toEventually(beTrue(), timeout: 3) } context("with startAt") { it("triggers didSeek") { let playback = AVFoundationPlayback(options: [kSourceUrl: "http://clappr.sample/master.m3u8", kStartAt: 10]) var didSeek = false var startAtValue: Double = 0 playback.render() playback.on(Event.didSeek.rawValue) { userInfo in didSeek = true startAtValue = userInfo!["position"] as! Double } playback.play() expect(didSeek).toEventually(beTrue()) expect(startAtValue).toEventually(beCloseTo(10, within: 0.1)) } } context("with liveStartTime") { func setupLiveDvr(liveStartTime: Double, dvrWindowStart: Double, dvrWindowEnd: Double) { playback = AVFoundationPlayback(options: [kMinDvrSize: 0, kLiveStartTime: liveStartTime]) asset = AVURLAssetStub(url: URL(string:"globo.com")!) item = AVPlayerItemStub(asset: asset) item._duration = .indefinite let dvrWindowSize = dvrWindowEnd - dvrWindowStart item.setWindow(start: 0, end: dvrWindowSize) item.set(currentTime: CMTime(seconds: dvrWindowSize, preferredTimescale: 1)) item.set(currentDate: Date(timeIntervalSince1970: dvrWindowEnd)) player = AVPlayerStub() player.set(currentItem: item) itemInfo = AVPlayerItemInfo(item: item, delegate: playback) playback.itemInfo = itemInfo playback.player = player player.setStatus(to: .readyToPlay) } context("when video is live with dvr") { context("and liveStartTime is between dvrWindow range") { it("triggers didUpdatePosition") { setupLiveDvr(liveStartTime: 2500, dvrWindowStart: 2000, dvrWindowEnd: 3000) let expectedPositionToSeek = 500.0 var didCallUpdatePosition = false var positionToSeek: Double = 0 playback.on(Event.didUpdatePosition.rawValue) { userInfo in didCallUpdatePosition = true positionToSeek = userInfo!["position"] as! Double } playback.didLoadDuration() expect(didCallUpdatePosition).toEventually(beTrue()) expect(positionToSeek).toEventually(equal(expectedPositionToSeek)) } } context("and liveStartTime is before dvrWindow range") { it("should not seek") { setupLiveDvr(liveStartTime: 1500, dvrWindowStart: 2000, dvrWindowEnd: 3000) var didSeek = false playback.on(Event.didSeek.rawValue) { _ in didSeek = true } playback.handleDvrAvailabilityChange() expect(didSeek).toEventually(beFalse()) } } context("and liveStartTime is after dvrWindow range") { it("should not seek") { setupLiveDvr(liveStartTime: 3500, dvrWindowStart: 2000, dvrWindowEnd: 3000) var didSeek = false playback.on(Event.didSeek.rawValue) { _ in didSeek = true } playback.handleDvrAvailabilityChange() expect(didSeek).toEventually(beFalse()) } } } context("when video is live without dvr") { it("should not seek") { let playback = AVFoundationPlayback(options: [kLiveStartTime: 2500.0]) let asset = AVURLAssetStub(url: URL(string:"globo.com")!) asset.set(duration: .indefinite) let item = AVPlayerItemStub(asset: asset) let player = AVPlayerStub() player.set(currentItem: item) playback.player = player player.setStatus(to: .readyToPlay) var didSeek = false playback.on(Event.didSeek.rawValue) { _ in didSeek = true } playback.handleDvrAvailabilityChange() expect(didSeek).toEventually(beFalse()) } } context("when video is VOD") { it("should not seek") { let playback = AVFoundationPlayback(options: [kLiveStartTime: 2500.0]) let playerStub = AVPlayerStub() playback.player = playerStub playerStub.setStatus(to: .readyToPlay) var didSeek = false playback.on(Event.didSeek.rawValue) { _ in didSeek = true } playback.handleDvrAvailabilityChange() expect(didSeek).toEventually(beFalse()) } } } } } describe("#isReadyToPlay") { context("when AVPlayer status is readyToPlay") { it("returns true") { let playback = AVFoundationPlayback(options: [:]) let playerStub = AVPlayerStub() playback.player = playerStub playerStub.setStatus(to: .readyToPlay) expect(playback.isReadyToPlay).to(beTrue()) } } context("when AVPlayer status is unknown") { it("returns false") { let playback = AVFoundationPlayback(options: [:]) let playerStub = AVPlayerStub() playback.player = playerStub playerStub.setStatus(to: .unknown) expect(playback.isReadyToPlay).to(beFalse()) } } context("when AVPlayer status is failed") { it("returns false") { let playback = AVFoundationPlayback(options: [:]) let playerStub = AVPlayerStub() playback.player = playerStub playerStub.setStatus(to: .failed) expect(playback.isReadyToPlay).to(beFalse()) } } } describe("playbackDidEnd") { func generateAssetWith(duration: TimeInterval, currentTime: TimeInterval) -> AVPlayerItemStub { let url = URL(string: "http://clappr.sample/master.m3u8")! let playerAsset = AVURLAssetStub(url: url) let item = AVPlayerItemStub(asset: playerAsset) item._duration = CMTime(seconds: duration, preferredTimescale: 1) item._currentTime = CMTime(seconds: currentTime, preferredTimescale: 1) return item } func generatePlayback(withState state: PlaybackState, itemDuration: TimeInterval, currentTime: TimeInterval) -> AVFoundationPlaybackMock { let playback = AVFoundationPlaybackMock(options: [:]) let playerStub = AVPlayerStub() playback.player = playerStub playerStub.set(currentItem: generateAssetWith(duration: itemDuration, currentTime: currentTime)) playback.set(state: state) return playback } context("when duration and currentTime are the same") { it("calls didComplete") { let playback = generatePlayback(withState: .playing, itemDuration: 100, currentTime: 100) let notification = NSNotification(name: NSNotification.Name(""), object: playback.player?.currentItem) var didCompleteCalled = false playback.on(Event.didComplete.rawValue) { _ in didCompleteCalled = true } playback.playbackDidEnd(notification: notification) expect(didCompleteCalled).to(beTrue()) expect(playback.state).to(equal(.idle)) } } context("when duration and currentTime are at most 2 seconds apart") { it("calls didComplete") { let playback = generatePlayback(withState: .playing, itemDuration: 102, currentTime: 100) let notification = NSNotification(name: NSNotification.Name(""), object: playback.player?.currentItem) var didCompleteCalled = false playback.on(Event.didComplete.rawValue) { _ in didCompleteCalled = true } playback.playbackDidEnd(notification: notification) expect(didCompleteCalled).to(beTrue()) expect(playback.state).to(equal(.idle)) } } context("when duration and currentTime are more than 2 seconds apart") { it("doesn't call didComplete and keep the same playback state") { let playback = generatePlayback(withState: .playing, itemDuration: 103, currentTime: 100) let notification = NSNotification(name: NSNotification.Name(""), object: playback.player?.currentItem) var didCompleteCalled = false playback.on(Event.didComplete.rawValue) { _ in didCompleteCalled = true } playback.playbackDidEnd(notification: notification) expect(didCompleteCalled).to(beFalse()) expect(playback.state).to(equal(.playing)) } } context("when currentItem is not the same as notification object payload") { it("doesn't call didComplete and keep the same playback state") { let playback = generatePlayback(withState: .playing, itemDuration: 103, currentTime: 100) let otherItem = generateAssetWith(duration: 200, currentTime: 200) let notification = NSNotification(name: NSNotification.Name(""), object: otherItem) var didCompleteCalled = false playback.on(Event.didComplete.rawValue) { _ in didCompleteCalled = true } playback.playbackDidEnd(notification: notification) expect(didCompleteCalled).to(beFalse()) expect(playback.state).to(equal(.playing)) } } } context("when onFailedToPlayToEndTime") { it("dispatch error") { let playback = AVFoundationPlayback(options: [:]) let error = NSError(domain: "", code: 0, userInfo: [:]) let notification = NSNotification(name: NSNotification.Name(""), object: playback.player?.currentItem, userInfo: ["AVPlayerItemFailedToPlayToEndTimeErrorKey": error]) var didErrorCalled = false playback.on(Event.error.rawValue) { _ in didErrorCalled = true } playback.onFailedToPlayToEndTime(notification: notification) expect(didErrorCalled).to(beTrue()) } context("user info on notification is nil") { it("triggers default error") { let errorKey = "AVPlayerItemFailedToPlayToEndTimeErrorKey" let playback = AVFoundationPlayback(options: [:]) let notification = NSNotification(name: NSNotification.Name(""), object: playback.player?.currentItem, userInfo: nil) var error: NSError? playback.on(Event.error.rawValue) { userInfo in error = userInfo?["error"] as? NSError } playback.onFailedToPlayToEndTime(notification: notification) let errorDescription = error?.userInfo[errorKey] as? String expect(errorDescription).to(equal("defaultError")) } } } describe("#seek") { var avFoundationPlayback: AVFoundationPlayback! beforeEach { avFoundationPlayback = AVFoundationPlayback(options: [kSourceUrl: "http://clappr.sample/master.m3u8"]) avFoundationPlayback.play() } context("when AVPlayer status is readyToPlay") { it("doesn't store the desired seek time") { let playback = AVFoundationPlayback(options: [:]) let player = AVPlayerStub() player.setStatus(to: .readyToPlay) playback.player = player playback.seek(20) expect(playback.seekToTimeWhenReadyToPlay).to(beNil()) } it("calls seek right away") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() player.setStatus(to: .readyToPlay) playback.player = player playback.seek(20) expect(player._item.didCallSeekWithCompletionHandler).to(beTrue()) } } context("when AVPlayer status is not readyToPlay") { it("stores the desired seek time") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 playback.seek(20) expect(playback.seekToTimeWhenReadyToPlay).to(equal(20)) } it("doesn't calls seek right away") { let playback = AVFoundationPlayback(options: [:]) let player = AVPlayerStub() playback.player = player player.setStatus(to: .unknown) playback.seek(20) expect(player._item.didCallSeekWithCompletionHandler).to(beFalse()) } } context("when DVR is available") { it("seeks to the correct time inside the DVR window") { item._duration = .indefinite item.setSeekableTimeRange(with: 60) item.setWindow(start: 60, end: 120) itemInfo.update(item: item) player.setStatus(to: .readyToPlay) playback.seek(20) expect(item.didCallSeekWithTime?.seconds).to(equal(80)) } } describe("#seekIfNeeded") { context("when seekToTimeWhenReadyToPlay is nil") { it("doesnt perform a seek") { let playback = AVFoundationPlayback(options: [:]) let player = AVPlayerStub() playback.player = player player.setStatus(to: .readyToPlay) playback.seekOnReadyIfNeeded() expect(player._item.didCallSeekWithCompletionHandler).to(beFalse()) expect(playback.seekToTimeWhenReadyToPlay).to(beNil()) } } context("when seekToTimeWhenReadyToPlay is not nil") { it("does perform a seek") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() playback.player = player player.setStatus(to: .unknown) playback.seek(20) player.setStatus(to: .readyToPlay) playback.seekOnReadyIfNeeded() expect(player._item.didCallSeekWithCompletionHandler).to(beTrue()) expect(playback.seekToTimeWhenReadyToPlay).to(beNil()) } } } it("triggers willSeek event and send position") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() playback.player = player player.setStatus(to: .readyToPlay) var didTriggerWillSeek = false var position: Double? let initialSeekPosition = 0.0 playback.on(Event.willSeek.rawValue) { userInfo in didTriggerWillSeek = true } position = playback.position playback.seek(5) expect(position).to(equal(initialSeekPosition)) expect(didTriggerWillSeek).to(beTrue()) } it("triggers didSeek when a seek is completed and send position") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() playback.player = player player.setStatus(to: .readyToPlay) var didTriggerDidSeek = false var position: Double? let expectedSeekPosition = 5.0 playback.on(Event.didSeek.rawValue) { userInfo in position = userInfo?["position"] as? Double didTriggerDidSeek = true } playback.seek(5) expect(position).to(equal(expectedSeekPosition)) expect(didTriggerDidSeek).to(beTrue()) } context("and playback is paused") { it("triggers didPause event") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() playback.player = player player.setStatus(to: .readyToPlay) playback.set(state: .paused) var didTriggerDidPause = false playback.on(Event.didPause.rawValue) { _ in didTriggerDidPause = true } playback.seek(5) expect(didTriggerDidPause).to(beTrue()) } } it("triggers didUpdatePosition for the desired position") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() playback.player = player player.setStatus(to: .readyToPlay) var updatedPosition: Double? = nil let expectedSeekPosition = 5.0 playback.on(Event.didUpdatePosition.rawValue) { (userInfo: EventUserInfo) in updatedPosition = userInfo!["position"] as? Double } playback.seek(5) expect(updatedPosition).to(equal(expectedSeekPosition)) } it("triggers didUpdatePosition before didSeek event") { let playback = AVFoundationPlaybackMock(options: [:]) playback.videoDuration = 100 let player = AVPlayerStub() playback.player = player player.setStatus(to: .readyToPlay) var updatedPosition: Double? = nil var didSeek = false var didTriggerDidSeekBefore = false let expectedSeekPosition = 5.0 playback.on(Event.didSeek.rawValue) { _ in didSeek = true } playback.on(Event.didUpdatePosition.rawValue) { (userInfo: EventUserInfo) in updatedPosition = userInfo!["position"] as? Double if didSeek { didTriggerDidSeekBefore = true } } playback.seek(5) expect(updatedPosition).to(equal(expectedSeekPosition)) expect(didTriggerDidSeekBefore).to(beFalse()) } } describe("#seekToLivePosition") { var playback: AVFoundationPlayback! var playerItem: AVPlayerItemStub! beforeEach { playback = AVFoundationPlayback(options: [:]) let url = URL(string: "http://clappr.sample/master.m3u8")! let playerAsset = AVURLAssetStub(url: url) playerItem = AVPlayerItemStub(asset: playerAsset) playerItem.setSeekableTimeRange(with: 45) let player = AVPlayerStub() player.set(currentItem: playerItem) itemInfo = AVPlayerItemInfo(item: playerItem, delegate: playback) playback.itemInfo = itemInfo playback.player = player player.setStatus(to: .readyToPlay) } it("triggers seek event") { var didTriggerDidSeek = false playback.once(Event.didSeek.rawValue) { _ in didTriggerDidSeek = true } playback.seekToLivePosition() expect(didTriggerDidSeek).toEventually(beTrue()) } it("triggers didUpdatePosition for the desired position") { var updatedPosition: Double? = nil playback.once(Event.didUpdatePosition.rawValue) { userInfo in updatedPosition = userInfo?["position"] as? Double } playback.seekToLivePosition() let endPosition = playback.seekableTimeRanges.last?.timeRangeValue.end.seconds expect(updatedPosition).to(equal(endPosition)) } } describe("#isDvrInUse") { beforeEach { item._duration = .indefinite item.setSeekableTimeRange(with: 160) itemInfo.update(item: item) player.setStatus(to: .readyToPlay) } context("when video is paused") { it("returns true") { playback.pause() expect(playback.isDvrInUse).to(beTrue()) } } context("when currentTime is lower then dvrWindowEnd - liveHeadTolerance") { it("returns true") { item.set(currentTime: CMTime(seconds: 154, preferredTimescale: 1)) player.play() expect(playback.isDvrInUse).toEventually(beTrue()) } } context("when currentTime is higher or equal then dvrWindowEnd - liveHeadTolerance") { it("returns false") { player.set(currentTime: CMTime(seconds: 156, preferredTimescale: 1)) player.play() expect(playback.isDvrInUse).toEventually(beFalse()) } } } describe("#didFindAudio") { context("when video is ready") { context("and has no default audio from options") { it("triggers didFindAudio event with hasDefaultFromOption false") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() var hasDefaultFromOption = true playback.on(Event.didFindAudio.rawValue) { userInfo in guard let audio = userInfo?["audios"] as? AvailableMediaOptions else { return } hasDefaultFromOption = audio.hasDefaultSelected } playback.play() expect(hasDefaultFromOption).toEventually(beFalse(), timeout: 2) } } } } describe("#selectDefaultSubtitleIfNeeded") { context("for online asset") { it("changes subtitle just once") { let options = [kSourceUrl: "http://clappr.sample/sample.m3u8", kDefaultSubtitle: "pt"] let playback = AVFoundationPlayback(options: options) playback.render() var hasDefaultFromOption = false playback.on(Event.didFindSubtitle.rawValue) { userInfo in guard let subtitles = userInfo?["subtitles"] as? AvailableMediaOptions else { return } hasDefaultFromOption = subtitles.hasDefaultSelected } playback.play() expect(hasDefaultFromOption).toEventually(beTrue(), timeout: 5) playback.selectDefaultSubtitleIfNeeded() expect(hasDefaultFromOption).toEventually(beFalse(), timeout: 5) } } context("for local asset") { it("changes subtitle source") { guard let pathSubtitle = Bundle(for: AVFoundationPlaybackTests.self).path(forResource: "sample", ofType: "movpkg") else { fail("Could not load local sample") return } let localURL = URL(fileURLWithPath: pathSubtitle) let options = [kSourceUrl: localURL.absoluteString, kDefaultSubtitle: "pt"] let playback = AVFoundationPlayback(options: options) playback.play() expect(playback.subtitles?.first?.name).toEventually(equal("Portuguese"), timeout: 5) } } } describe("#changeSubtitleStyle") { it("changes the subtitles style") { let options = [kSourceUrl: "http://clappr.sample/sample.m3u8", kDefaultSubtitle: "pt"] let playback = AVFoundationPlayback(options: options) let expectedvalue = [ AVTextStyleRule(textMarkupAttributes: [String((kCMTextMarkupAttribute_BoldStyle)) : true]), AVTextStyleRule(textMarkupAttributes: [String((kCMTextMarkupAttribute_GenericFontFamilyName)) : kCMTextMarkupGenericFontName_Default]), ] playback.play() let didChangeSubtitleStyle = playback.applySubtitleStyle(with: [ .bold, .font(.default) ]) expect(didChangeSubtitleStyle).to(beTrue()) expect(playback.player?.currentItem?.textStyleRules).toEventually(equal(expectedvalue), timeout: 2) } } describe("#selectDefaultAudioIfNeeded") { context("for online asset") { it("changes audio just once") { let options = [kSourceUrl: "http://clappr.sample/sample.m3u8", kDefaultAudioSource: "pt"] let playback = AVFoundationPlayback(options: options) playback.render() var hasDefaultFromOption = false playback.on(Event.didFindAudio.rawValue) { userInfo in guard let audio = userInfo?["audios"] as? AvailableMediaOptions else { return } hasDefaultFromOption = audio.hasDefaultSelected } playback.play() expect(hasDefaultFromOption).toEventually(beTrue(), timeout: 5) playback.selectDefaultAudioIfNeeded() expect(hasDefaultFromOption).toEventually(beFalse(), timeout: 2) } } context("for local asset") { context("when default audio is passed") { it("changes the audio source") { guard let pathAudio = Bundle(for: AVFoundationPlaybackTests.self).path(forResource: "sample", ofType: "movpkg") else { fail("Could not load local sample") return } let localURL = URL(fileURLWithPath: pathAudio) let options = [kSourceUrl: localURL.absoluteString, kDefaultAudioSource: "por"] let playback = AVFoundationPlayback(options: options) playback.play() expect(playback.audioSources?.first?.name).toEventually(equal("Portuguese"), timeout: 5) } } } } describe("#didFindSubtitle") { context("when video is ready and has subtitle available") { context("and has default subtitle from options") { it("triggers didFindSubtitle event with hasDefaultFromOption true") { let options = [kSourceUrl: "http://clappr.sample/sample.m3u8", kDefaultSubtitle: "pt"] let playback = AVFoundationPlayback(options: options) playback.render() var hasDefaultFromOption = false playback.on(Event.didFindSubtitle.rawValue) { userInfo in guard let subtitles = userInfo?["subtitles"] as? AvailableMediaOptions else { return } hasDefaultFromOption = subtitles.hasDefaultSelected } playback.play() expect(hasDefaultFromOption).toEventually(beTrue(), timeout: 5) } } context("and has no default subtitle from options") { it("triggers didFindSubtitle event with hasDefaultFromOption false") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() var hasDefaultFromOption = true playback.on(Event.didFindSubtitle.rawValue) { userInfo in guard let subtitles = userInfo?["subtitles"] as? AvailableMediaOptions else { return } hasDefaultFromOption = subtitles.hasDefaultSelected } playback.play() expect(hasDefaultFromOption).toEventually(beFalse(), timeout: 4) } } } } describe("#didSelectSubtitle") { var avFoundationPlayback: AVFoundationPlayback! beforeEach { stub(condition: isHost("clappr.sample")) { _ in let stubPath = OHPathForFile("sample.m3u8", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type":"application/vnd.apple.mpegURL; charset=utf-8"]) } avFoundationPlayback = AVFoundationPlayback(options: [kSourceUrl: "https://clappr.sample/sample.m3u8"]) avFoundationPlayback.play() } context("when playback does not have subtitles") { it("returns nil for selected subtitle") { expect(playback.selectedSubtitle).to(beNil()) } } context("when playback has subtitles") { it("returns default subtitle for a playback with subtitles") { expect(avFoundationPlayback.selectedSubtitle).toEventuallyNot(beNil(), timeout: 2) } } context("when subtitle is selected") { it("triggers didSelectSubtitle event") { var subtitleOption: MediaOption? avFoundationPlayback.on(Event.didSelectSubtitle.rawValue) { userInfo in subtitleOption = userInfo?["mediaOption"] as? MediaOption } avFoundationPlayback.selectedSubtitle = avFoundationPlayback.subtitles?.first expect(subtitleOption).toEventuallyNot(beNil()) expect(subtitleOption).toEventually(beAKindOf(MediaOption.self)) } } } describe("#selectedAudioSource") { it("returns nil for a playback without audio sources") { expect(playback.selectedAudioSource).to(beNil()) } context("when audio is selected") { it("triggers didSelectAudio event") { var audioSelected: MediaOption? playback.on(Event.didSelectAudio.rawValue) { userInfo in audioSelected = userInfo?["mediaOption"] as? MediaOption } playback.selectedAudioSource = MediaOption(name: "English", type: MediaOptionType.audioSource, language: "eng", raw: AVMediaSelectionOption()) expect(audioSelected).toEventuallyNot(beNil()) expect(audioSelected).to(beAKindOf(MediaOption.self)) } } } describe("#AVFoundationPlayback states") { describe("#idle") { context("when ready to play") { it("current state must be idle") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) expect(playback.state).toEventually(equal(.idle)) } } context("when play is called") { it("changes isPlaying to true") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() expect(playback.state).toEventually(equal(.playing), timeout: 10) } } context("when pause is called") { it("changes current state to paused") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.pause() expect(playback.state).toEventually(equal(.paused), timeout: 3) } } context("when stop is called") { it("does not trigger didStop event") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) var didStopWasTriggered = false playback.on(Event.didStop.rawValue) { _ in didStopWasTriggered = true } playback.stop() expect(didStopWasTriggered).to(beFalse()) } } } describe("#playing") { context("when paused is called") { it("changes current state to paused") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.play() playback.pause() expect(playback.state).toEventually(equal(.paused)) } } context("when seek is called") { it("keeps playing") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.seek(10) expect(playback.state).toEventually(equal(.playing), timeout: 3) } } context("when stop is called") { it("changes state to idle") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.play() playback.stop() expect(playback.state).toEventually(equal(.idle), timeout: 3) } } context("when video is over") { it("changes state to idle") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.play() playback.seek(playback.duration) expect(playback.state).toEventually(equal(.idle), timeout: 10) } } context("when is not likely to keep up") { it("changes state to stalling") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() expect(playback.state).to(equal(.stalling)) } } } describe("#paused") { context("when playing is called") { it("changes isPlaying to true") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.pause() playback.play() expect(playback.state).toEventually(equal(.playing), timeout: 3) } } context("when seek is called") { it("keeps state in paused") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.play() playback.pause() playback.seek(10) expect(playback.state).to(equal(.paused)) } } context("when stop is called") { it("changes state to idle") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.play() playback.pause() playback.stop() expect(playback.state).to(equal(.idle)) } } context("when is not likely to keep up") { it("changes state to stalling") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.pause() playback.play() expect(playback.state).toEventually(equal(.stalling), timeout: 3) } } } describe("#stalling") { context("when seek is called") { it("keeps stalling state") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.seek(10) expect(playback.state).to(equal(.stalling)) } } context("when paused is called") { it("changes state to paused") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.pause() expect(playback.state).to(equal(.paused)) } } context("when stop is called") { it("changes state to idle") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() playback.play() playback.stop() expect(playback.state).to(equal(.idle)) } } } } describe("#setupPlayer") { context("when asset is available") { it("triggers event assetAvailable") { let options = [kSourceUrl: "http://clappr.sample/master.m3u8"] let playback = AVFoundationPlayback(options: options) playback.render() var didTriggerAssetReady = false playback.on(Event.assetReady.rawValue) { _ in didTriggerAssetReady = true } playback.play() expect(didTriggerAssetReady).toEventually(beTrue()) } } } describe("#mute") { context("when mute is enabled") { it("sets volume to zero") { playback.mute(true) expect(player.volume).to(equal(0)) } } context("when mute is disabled") { it("sets volume to maximum") { player.volume = 0 playback.mute(false) expect(player.volume).to(equal(1)) } } } } } } private class StubbedLiveDatePlayback: AVFoundationPlayback { var _position: Double = .zero override var position: Double { _position } var _duration: Double = .zero override var duration: Double { _duration } var _playbackType: PlaybackType = .live override var playbackType: PlaybackType { _playbackType } }
bsd-3-clause
e4d0cf71160967f807577bed23708185
44.232841
186
0.434826
6.507976
false
false
false
false
fancymax/12306ForMac
12306ForMac/Model/LeftTicketParam.swift
1
607
// // LeftTicketDTO.swift // Train12306 // // Created by fancymax on 15/10/24. // Copyright © 2015年 fancy. All rights reserved. // import Foundation struct LeftTicketParam{ //2015-09-23 var train_date = "2015-09-23" //SZQ -> 深圳 var from_stationCode = "SZQ" //SHH -> 上海 var to_stationCode = "SHH" //ADULT var purpose_codes = "ADULT" func ToGetParams()->String{ return "leftTicketDTO.train_date=\(train_date)&leftTicketDTO.from_station=\(from_stationCode)&leftTicketDTO.to_station=\(to_stationCode)&purpose_codes=\(purpose_codes)" } }
mit
71b31377cb1e5d2f8bbf9e5ca9e64aa5
23.833333
176
0.645973
3.088083
false
false
false
false
terietor/GTForms
Source/Forms/Selection/BaseSelectionFormItem.swift
1
1614
// Copyright (c) 2016 Giorgos Tsiapaliokas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class BaseSelectionFormItem { public let text: String public let detailText: String? /** The cell reuse identifier */ public var cellReuseIdentifier = "SelectionItemCell" weak var selectionForm: BaseSelectionForm? public var selected: Bool = false public init( text: String, detailText: String? = nil ) { self.text = text self.detailText = text } }
mit
ff74e321d6982f0ad7bb682017f9f835
35.681818
80
0.727385
4.50838
false
false
false
false
artursDerkintis/YouTube
Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorShape.swift
1
5327
// // NVActivityIndicatorShape.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/22/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit enum NVActivityIndicatorShape { case Circle case CircleSemi case Ring case RingTwoHalfVertical case RingTwoHalfHorizontal case RingThirdFour case Rectangle case Triangle case Line case Pacman func createLayerWith(size size: CGSize, color: UIColor) -> CALayer { let layer: CAShapeLayer = CAShapeLayer() var path: UIBezierPath = UIBezierPath() let lineWidth: CGFloat = 2 switch self { case .Circle: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: false); layer.strokeColor = UIColor.lightGrayColor().CGColor layer.lineWidth = 0.5 layer.fillColor = color.CGColor case .CircleSemi: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: CGFloat(-M_PI / 6), endAngle: CGFloat(-5 * M_PI / 6), clockwise: false) path.closePath() layer.fillColor = color.CGColor case .Ring: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: false); layer.fillColor = nil layer.strokeColor = color.CGColor layer.lineWidth = lineWidth case .RingTwoHalfVertical: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(-3 * M_PI_4), endAngle:CGFloat(-M_PI_4), clockwise:true) path.moveToPoint( CGPoint(x: size.width / 2 - size.width / 2 * CGFloat(cos(M_PI_4)), y: size.height / 2 + size.height / 2 * CGFloat(sin(M_PI_4))) ) path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(-5 * M_PI_4), endAngle:CGFloat(-7 * M_PI_4), clockwise:false) layer.fillColor = nil layer.strokeColor = color.CGColor layer.lineWidth = lineWidth case .RingTwoHalfHorizontal: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(3 * M_PI_4), endAngle:CGFloat(5 * M_PI_4), clockwise:true) path.moveToPoint( CGPoint(x: size.width / 2 + size.width / 2 * CGFloat(cos(M_PI_4)), y: size.height / 2 - size.height / 2 * CGFloat(sin(M_PI_4))) ) path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(-M_PI_4), endAngle:CGFloat(M_PI_4), clockwise:true) layer.fillColor = nil layer.strokeColor = color.CGColor layer.lineWidth = lineWidth case .RingThirdFour: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: CGFloat(-3 * M_PI_4), endAngle: CGFloat(-M_PI_4), clockwise: false) layer.fillColor = nil layer.strokeColor = color.CGColor layer.lineWidth = 2 case .Rectangle: path.moveToPoint(CGPoint(x: 0, y: 0)) path.addLineToPoint(CGPoint(x: size.width, y: 0)) path.addLineToPoint(CGPoint(x: size.width, y: size.height)) path.addLineToPoint(CGPoint(x: 0, y: size.height)) layer.fillColor = color.CGColor case .Triangle: let offsetY = size.height / 4 path.moveToPoint(CGPoint(x: 0, y: size.height - offsetY)) path.addLineToPoint(CGPoint(x: size.width / 2, y: size.height / 2 - offsetY)) path.addLineToPoint(CGPoint(x: size.width, y: size.height - offsetY)) path.closePath() layer.fillColor = color.CGColor case .Line: path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height), cornerRadius: size.width / 2) layer.fillColor = color.CGColor case .Pacman: path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 4, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true); layer.fillColor = nil layer.strokeColor = color.CGColor layer.lineWidth = size.width / 2 } layer.backgroundColor = nil layer.path = path.CGPath return layer } }
mit
f8f4e2f8295884f3183c404d09b259f7
38.466667
104
0.53257
4.345024
false
false
false
false
phuongvnc/CPMenuView
CPMenuView/CPMenuAnimator.swift
1
2860
// // CPMenuAnimator.swift // CPMenuView // // Created by framgia on 2/24/17. // Copyright © 2017 framgia. All rights reserved. // import UIKit public protocol CPMenuAnimationProtocol { func animationHomeButton(homeButton: HomeMenuButton, state: CPMenuViewState, completion: (() -> Void)?) func animationShowSubMenuButton(subButtons: [SubMenuButton], completion: (() -> Void)?) func animationHideSubMenuButton(subButtons: [SubMenuButton], completion: (() -> Void)?) } public struct CPMenuAnimator { public var commonDuration: TimeInterval! public var commonSpringWithDamping: CGFloat! public var commonSpringVelocity:CGFloat! public init(commonDuration:TimeInterval = 0.5,commonSpringWithDamping:CGFloat = 0.5 ,commonSpringVelocity:CGFloat = 0){ self.commonDuration = commonDuration self.commonSpringWithDamping = commonSpringWithDamping self.commonSpringVelocity = commonSpringVelocity } public func animation(delay: TimeInterval,animation: @escaping () -> Void, completion: @escaping (Bool) -> Void) { UIView.animate(withDuration: commonDuration!, delay: delay, usingSpringWithDamping: commonSpringWithDamping, initialSpringVelocity: commonSpringVelocity, options: UIViewAnimationOptions.curveEaseInOut, animations: animation, completion: completion) } } extension CPMenuAnimator: CPMenuAnimationProtocol { public func animationShowSubMenuButton(subButtons: [SubMenuButton], completion: (() -> Void)?) { var delay: TimeInterval = 0 for button in subButtons { let completionBlock = button.isEqual(subButtons.last) ? completion : nil animation(delay:delay, animation: { button.center = button.endPosition! button.alpha = 1 }, completion: { (finish) in completionBlock?() }) delay += 0.2 } } public func animationHideSubMenuButton(subButtons: [SubMenuButton], completion: (() -> Void)?) { var delay: TimeInterval = 0 for button in subButtons.reversed() { let completionBlock = button.isEqual(subButtons.last) ? completion : nil animation(delay:delay, animation: { button.center = button.startPosition! button.alpha = 0 }, completion: { (finish) in completionBlock?() }) delay += 0.2 } } public func animationHomeButton(homeButton: HomeMenuButton, state: CPMenuViewState, completion: (() -> Void)?) { let scale: CGFloat = state == .expand ? 1.0 : 0.9 let transform = CGAffineTransform(scaleX: scale, y: scale) animation(delay: 0, animation: { homeButton.transform = transform }, completion: { finish in completion?() }) } }
mit
9dc190f4b279e48de5328dd50e0aea60
39.267606
256
0.655824
4.862245
false
false
false
false
cgoldsby/TvOSMoreButton
Source/Private/Helpers/UIView+Autolayout.swift
1
1922
// // UIView+Autolayout.swift // // Copyright (c) 2016-2019 Chris Goldsby // // 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 UIView { func pinToSuperview(insets: UIEdgeInsets = .zero) { guard let superview = superview else { return } translatesAutoresizingMaskIntoConstraints = false let topConstraint = topAnchor.constraint(equalTo: superview.topAnchor, constant: insets.top) let bottomConstraint = bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -insets.bottom) let leadingConstraint = leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: insets.left) let trailingConstraint = trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: -insets.right) superview.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint]) } }
mit
471c24c3c3aec67e4644a0d833a98360
48.282051
118
0.760666
4.915601
false
false
false
false
google-fabric/FABOperation
Examples/SwiftExample/SwiftExample/AppDelegate.swift
2
3699
// // AppDelegate.swift // SwiftExample // // Created by Cory Dolphin on 3/17/16. // Copyright © 2016 Twitter. All rights reserved. // import UIKit import FABOperation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let operation = RandomDelayedOperation() operation.asyncCompletion = { error -> Void in print(error) } operation.start() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } class RandomDelayedOperation: FABAsyncOperation { override func main() { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in var error: NSError? if random() % 1 == 0 { error = NSError(domain: "Dummy", code: 0, userInfo: nil) } self.finish(error) } } private func finish(asyncError: NSError?) { // set this operation as done // NSOperation's completionBlock will execute immediately if one was provided // this could also be done after calling asyncCompletion, it's up to you self.markDone() // check for some possible failure modes var errorInfo = [String: AnyObject]() if self.cancelled { errorInfo[NSLocalizedDescriptionKey] = "Operation cancelled" } if let asyncErrorValue = asyncError { errorInfo[NSLocalizedDescriptionKey] = "Async work failed" errorInfo[NSUnderlyingErrorKey] = asyncErrorValue } // package up the error, if there was one var error: NSError? if errorInfo.count > 0 { error = NSError(domain: "my.error.domain", code: 0, userInfo: errorInfo) } // call asyncCompletion if one was provided if let asyncCompletion = self.asyncCompletion { asyncCompletion(error) } } }
mit
b0be60e13cd44718a7b99e519dc6f0e3
41.022727
285
0.687669
5.24539
false
false
false
false
mzyy94/TesSoMe
TesSoMe/ColorPickerViewController.swift
1
4298
// // ColorPickerViewController.swift // TesSoMe // // Created by Yuki Mizuno on 2014/10/09. // Copyright (c) 2014年 Yuki Mizuno. All rights reserved. // import UIKit class ColorPickerViewController: UICollectionViewController { var size: CGFloat = 5.0 var color: UIColor = UIColor.blackColor() var colors: [UIColor] = [] var sizeSlider: UISlider! = nil func generateColors() { for white in 0..<32 { let color = UIColor(white: (32.0 - CGFloat(white)) / 32.0, alpha: 1.0) self.colors.append(color) } for r in 0..<6 { for g in 0..<6 { for b in 0..<6 { let color = UIColor(red: CGFloat(r) / 5.0, green: CGFloat(g) / 5.0, blue: CGFloat(b) / 5.0, alpha: 1.0) self.colors.append(color) } } } self.colors.removeLast() } override func viewDidLoad() { super.viewDidLoad() generateColors() self.collectionView?.reloadData() for i in 0..<colors.count { if colors[i] == color { self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forRow: i, inSection: 0), atScrollPosition: .Top, animated: false) break } } sizeSlider = UISlider() sizeSlider.minimumValue = 1.0 sizeSlider.maximumValue = 30.0 sizeSlider.value = Float(size) sizeSlider.tintColor = color sizeSlider.addTarget(self, action: Selector("changeSize:"), forControlEvents: .ValueChanged) self.navigationItem.titleView = UIView(frame: self.navigationController!.navigationBar.frame) sizeSlider.setTranslatesAutoresizingMaskIntoConstraints(false) self.navigationItem.titleView?.addSubview(sizeSlider) let attributes: [NSLayoutAttribute] = [.Top, .Left, .Right, .Bottom] for attribute in attributes { let constraint = NSLayoutConstraint(item: sizeSlider, attribute: attribute, relatedBy: .Equal, toItem: self.navigationItem.titleView, attribute: attribute, multiplier: 1.0, constant: 0.0) self.navigationItem.titleView?.addConstraint(constraint) } let colorPreviewView = UIImageView(frame: CGRect(x: 0, y: 0, width: 64, height: 64)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: colorPreviewView) drawPreviewImage() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func changeSize(sender: UISlider) { size = CGFloat(sender.value) drawPreviewImage() } func drawPreviewImage() { let imageView = self.navigationItem.rightBarButtonItem?.customView as UIImageView UIGraphicsBeginImageContext(imageView.bounds.size) let context = UIGraphicsGetCurrentContext() let circle = CGRect(x: (imageView.bounds.size.width - size) / 2, y: (imageView.bounds.size.height - size) / 2, width: size, height: size) CGContextSetLineWidth(context, 1.0) CGContextSetStrokeColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextSetFillColorWithColor(context, color.CGColor) CGContextStrokeEllipseInRect(context, circle) CGContextFillEllipseInRect(context, circle) imageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colors.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let colorCell = collectionView.dequeueReusableCellWithReuseIdentifier("ColorCell", forIndexPath: indexPath) as UICollectionViewCell colorCell.backgroundColor = self.colors[indexPath.row] return colorCell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { color = colors[indexPath.row] sizeSlider.tintColor = color drawPreviewImage() return } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) let postDrawingViewController = self.parentViewController?.childViewControllers.first as PostDrawingViewController postDrawingViewController.color = self.color postDrawingViewController.size = self.size } }
gpl-3.0
e617e6d28f165c77b1252e9119f123e9
29.906475
190
0.75
4.091429
false
false
false
false
VanHack/binners-project-ios
ios-binners-project/CloseViewController.swift
1
1408
// // CloseModalViewController.swift // ios-binners-project // // Created by Matheus Ruschel on 03/12/16. // Copyright © 2016 Rodrigo de Souza Reis. All rights reserved. // import Foundation class CloseButtonViewController: UIViewController { var hideCloseButton : Bool = false { didSet { setCloseButtonHidden(hideCloseButton) } } override func viewDidLoad() { super.viewDidLoad() hideCloseButton = false } func setCloseButtonHidden(_ hidden: Bool) { if self.navigationController == nil { if !hidden { let closeButton = UIButton(frame: CGRect(x:0, y:0, width: 50, height: 50)) closeButton.setImage(UIImage(named: "delete_sign"), for: .normal) closeButton.addTarget(self, action: #selector(CloseButtonViewController.dismissVC), for: .touchUpInside) self.view.addSubview(closeButton) } } else { if hidden { self.navigationItem.leftBarButtonItem = nil } else { self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(CloseButtonViewController.dismissVC)) } } } func dismissVC() { self.dismiss(animated: true, completion: nil) } }
mit
a08e825ed44a2d33a450b994e43d7ecc
28.3125
169
0.595593
4.936842
false
false
false
false
darofar/lswc
p5-pokedex/Pokedex/PokedexModel.swift
1
1974
// // PokedexModel.swift // Pokedex // // Created by Santiago Pavón on 26/11/14. // Copyright (c) 2014 UPM. All rights reserved. // import Foundation /** * Modelo de datos de los pokemons. * Tiene informacion sobre las razas y los tipos de pokemons. */ class PokedexModel { // Array de objetos Race. var races: [Race] // Array de objetos Type. var types: [Type] init() { // Cargar los datos desde pokemons.plist // y rellenar las propiedades races y types. let path = NSBundle.mainBundle().pathForResource("pokemons", ofType: "plist")! let plist = NSDictionary(contentsOfFile: path)! let allNames = plist["nombres"]! as! [String:String] let allIcons = plist["iconos"]! as! [String:String] let allTypes = plist["tipos"]! as! [String:[Int]] // Calcular valor de la propiedad self.races. races = [] for (code,name) in allNames { races.append(Race(code: code, name: name, icon: allIcons[code]!)) } races.sort({ (race1:Race, race2:Race) -> Bool in return race1.name < race2.name }) // Calcular valor de la propiedad self.types. types = [] for (name,raceCodes) in allTypes { var racesOfThisType: [Race] = raceCodes.map({ (code) -> Race in for race in self.races { if race.code == "\(code)" { return race } } return Race(code: "\(code)", name: "????", icon: "") }) racesOfThisType.sort({ (race1:Race, race2:Race) -> Bool in return race1.name < race2.name }) types.append(Type(name: name, races: racesOfThisType)) } types.sort({ (type1, type2) -> Bool in return type1.name < type2.name }) } }
apache-2.0
3a985ee00780a572a64ca3c5f557a21f
26.788732
86
0.521541
3.953908
false
false
false
false
GorCat/TSImagePicker
ImagePicker/ImagePicker/ImagePicker/UI/toolbar/AlbumCollectionToolbar.swift
1
1773
// // AlbumCollectionToolbar.swift // ImagePicker // // Created by GorCat on 2017/7/3. // Copyright © 2017年 GorCat. All rights reserved. // // collection 的工具栏 import UIKit class AlbumCollectionToolbar: UIView { /// 预览按钮 var buttonForPreview = UIButton(type: .custom) /// 完成按钮 var buttonForFinish = UIButton(type: .custom) // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) setUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUI() } // MARK: - Custom user interface func setUI() { backgroundColor = UIColor.white // 1.完成按钮 buttonForFinish.backgroundColor = UIColor.black buttonForFinish.setTitleColor(UIColor.white, for: .normal) buttonForFinish.titleLabel?.font = UIFont.systemFont(ofSize: 14) buttonForFinish.layer.cornerRadius = 5 buttonForFinish.clipsToBounds = true buttonForFinish.frame = CGRect(x: frame.width - 70 - 9, y: (frame.height - 30) / 2, width: 70, height: 30) // 2.预览按钮 buttonForPreview.frame = CGRect(x: 0, y: 0, width: 50, height: frame.height) buttonForPreview.setTitle("预览", for: .normal) buttonForPreview.titleLabel?.font = UIFont.systemFont(ofSize: 15) buttonForPreview.setTitleColor(UIColor.black, for: .normal) // 3.分割线 let separator = UIView(frame: CGRect(origin: .zero, size: CGSize(width: frame.width, height: 1))) separator.backgroundColor = UIColor.gray addSubview(separator) addSubview(buttonForFinish) addSubview(buttonForPreview) } }
mit
6a9a126b75747c49b3bb8af4b682c052
29.175439
114
0.626744
4.095238
false
false
false
false
KrishMunot/swift
test/DebugInfo/closure.swift
2
807
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(_ t: T) {} func foldl1<T>(_ list: [T], _ function: (a: T, b: T) -> T) -> T { assert(list.count > 1) var accumulator = list[0] for var i = 1; i < list.count; i += 1 { accumulator = function(a: accumulator, b: list[i]) } return accumulator } var a = [Int64](repeating: 0, count: 10) for i in 0..<10 { a[i] = Int64(i) } // A closure is not an artificial function (the last i32 0). // CHECK: !DISubprogram({{.*}}linkageName: "_TF7closureU_FTVs5Int64S0__S0_",{{.*}} line: 20,{{.*}} scopeLine: 20, // CHECK: !DILocalVariable(name: "$0", arg: 1{{.*}} line: [[@LINE+2]], // CHECK: !DILocalVariable(name: "$1", arg: 2{{.*}} line: [[@LINE+1]], var sum:Int64 = foldl1(a, { $0 + $1 }) markUsed(sum)
apache-2.0
12d14ad5997e35b9b1a1f6371c285a33
37.428571
113
0.568773
2.861702
false
false
false
false
RLovelett/VHS
VHS/Types/VCRSequence.swift
1
2425
// // VCRSequence.swift // VHS // // Created by Ryan Lovelett on 7/16/16. // Copyright © 2016 Ryan Lovelett. All rights reserved. // import Foundation internal protocol VCRSequence { init(sequenceOf: [Track], inOrder: VCR.PlaybackSequence) mutating func next(for request: Request) -> Track? } private func byMatching(_ track: Request, with request: Request) -> (Bool, VCR.PlaybackSequence.MatchType) -> Bool { return { (previous: Bool, type: VCR.PlaybackSequence.MatchType) -> Bool in return previous && type.match(track, with: request) } } internal struct LoopingSequence: VCRSequence { let tracks: [Track] let orderBy: VCR.PlaybackSequence var currentIndex: Array<Track>.Index init(sequenceOf: [Track], inOrder: VCR.PlaybackSequence) { self.tracks = sequenceOf self.orderBy = inOrder self.currentIndex = sequenceOf.startIndex } mutating func next(for request: Request) -> Track? { switch self.orderBy { case .cassetteOrder: let track = self.tracks[self.currentIndex] self.currentIndex = self.currentIndex.advanced(by: 1) if self.currentIndex >= self.tracks.endIndex { self.currentIndex = self.tracks.startIndex } return track case .properties(matching: let matchers): for track in self.tracks { guard matchers.reduce(true, byMatching(track.request, with: request)) else { continue } return track } return .none } } } internal struct EphemeralSequence: VCRSequence { var tracks: [Track] let matchers: [VCR.PlaybackSequence.MatchType] init(sequenceOf: [Track], inOrder: VCR.PlaybackSequence) { self.tracks = sequenceOf switch inOrder { case .cassetteOrder: self.matchers = [] case .properties(matching: let matchers): self.matchers = matchers } } mutating func next(for request: Request) -> Track? { for (offset, track) in self.tracks.enumerated() { guard matchers.reduce(true, byMatching(track.request, with: request)) else { continue } let index = self.tracks.index(self.tracks.startIndex, offsetBy: offset) self.tracks.remove(at: index) return track } return .none } }
mit
1ae7f306dada183f5d3635bc364f165a
28.204819
116
0.619224
4.252632
false
false
false
false
joerocca/GitHawk
Classes/PullReqeustReviews/PullRequestReviewCommentsViewController.swift
1
2985
// // PullRequestReviewCommentsViewController.swift // Freetime // // Created by Ryan Nystrom on 11/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit final class PullRequestReviewCommentsViewController: BaseListViewController<NSNumber>, BaseListViewControllerDataSource { private let model: IssueDetailsModel private let client: GithubClient private var models = [ListDiffable]() init(model: IssueDetailsModel, client: GithubClient) { self.model = model self.client = client super.init( emptyErrorMessage: NSLocalizedString("Error loading review comments.", comment: ""), dataSource: self ) title = NSLocalizedString("Review Comments", comment: "") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Overrides override func fetch(page: NSNumber?) { client.fetchPRComments( owner: model.owner, repo: model.repo, number: model.number, width: view.bounds.width ) { [weak self] (result) in switch result { case .error: ToastManager.showGenericError() case .success(let models, let page): self?.models = models self?.update(page: page as NSNumber?, animated: trueUnlessReduceMotionEnabled) } } } // MARK: BaseListViewControllerDataSource func headModels(listAdapter: ListAdapter) -> [ListDiffable] { return [] } func models(listAdapter: ListAdapter) -> [ListDiffable] { return models } func sectionController(model: Any, listAdapter: ListAdapter) -> ListSectionController { switch model { case is NSAttributedStringSizing: return IssueTitleSectionController() case is IssueCommentModel: return IssueCommentSectionController(model: self.model, client: client) case is IssueDiffHunkModel: return IssueDiffHunkSectionController() default: fatalError("Unhandled object: \(model)") } } func emptySectionController(listAdapter: ListAdapter) -> ListSectionController { return ListSingleSectionController(cellClass: LabelCell.self, configureBlock: { (_, cell: UICollectionViewCell) in guard let cell = cell as? LabelCell else { return } cell.label.text = NSLocalizedString("No review comments found.", comment: "") }, sizeBlock: { [weak self] (_, context: ListCollectionContext?) -> CGSize in guard let context = context, let strongSelf = self else { return .zero } return CGSize( width: context.containerSize.width, height: context.containerSize.height - strongSelf.topLayoutGuide.length - strongSelf.bottomLayoutGuide.length ) }) } // MARK: IssueCommentSectionControllerDelegate }
mit
64cba61d371971fc75f7cbf97921d783
33.298851
125
0.650469
5.244288
false
false
false
false
sffernando/SwiftLearning
FoodTracker/FoodTracker/MealViewController.swift
1
3428
// // MealViewController.swift // FoodTracker // // Created by koudai on 2016/11/26. // Copyright © 2016年 fernando. All rights reserved. // import UIKit class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var ratingControl: RatingControl! @IBOutlet weak var saveButton: UIBarButtonItem! var meal: Meal? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Handle the text field’s user input through delegate callbacks. nameTextField.delegate = self if let meal = meal { navigationItem.title = meal.name nameTextField.text = meal.name ratingControl.rating = meal.rating photoImageView.image = meal.image } checkValidMealName() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { checkValidMealName() navigationItem.title = textField.text } func textFieldDidBeginEditing(_ textField: UITextField) { saveButton.isEnabled = false } func checkValidMealName() { let text = nameTextField.text ?? "" saveButton.isEnabled = !text.isEmpty } // MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let selectImage = info[UIImagePickerControllerOriginalImage] as! UIImage photoImageView.image = selectImage dismiss(animated: true, completion: nil) } //MARK: navigation @IBAction func cancel(_ sender: UIBarButtonItem) { let isPresentingInAddMealMode = presentingViewController is UINavigationController if isPresentingInAddMealMode { dismiss(animated: true, completion: nil) } else { navigationController!.popViewController(animated: true) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if saveButton === sender as AnyObject? { let name = nameTextField.text ?? "" let photo = photoImageView.image let rating = ratingControl.rating meal = Meal.init(name: name, photo: photo, rating: rating) } } // MARK: Actions @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) { // hide the keyboard nameTextField.resignFirstResponder() let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .photoLibrary imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } }
mit
928630d188e723f1f0ed37bb8160d008
32.558824
130
0.66579
5.782095
false
false
false
false
ngohongthai/BaseViperComponent
BasePrj/BasePrj/Modules/ExampleViewController/ExampleWireFrame.swift
1
921
// // ExampleWireFrame.swift // Test // // Created by Ngo Thai on 5/8/17. // Copyright © 2017 BeeSnippeter. All rights reserved. // import UIKit protocol ExampleWireFrameInterface: BaseWireFrameInterface { } class ExampleWireFrame: BaseWireFrame { class func createExampleModule() -> UIViewController { let view = ExampleViewController() let presenter = ExamplePresenter() let interactor = ExampleInteractor() let wireFrame = ExampleWireFrame() //Connecting view.basePresenter = presenter presenter.baseView = view presenter.baseWireFrame = wireFrame presenter.interactor = interactor interactor.output = presenter return view } static var storyBoard: UIStoryboard { return UIStoryboard(name: "Example", bundle: Bundle.main) } } extension ExampleWireFrame: ExampleWireFrameInterface { }
mit
4d6fb862347a9e0fc6cd60eade8df64c
18.574468
65
0.679348
4.693878
false
false
false
false
gewill/GWMarkSlider
Demo/GWMarkSlider/ViewController.swift
1
3119
// // ViewController.swift // GWMarkSlider // // Created by Will on 6/28/16. // Copyright © 2016 gewill.org. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var markSlider1: GWMarkSlider! var markSlider2: GWMarkSlider! var slider: UISlider! var markInfo1 = GWMarkInfo() var markInfo2 = GWMarkInfo() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // markSlider1.minTintColor = UIColor.clearColor() // markSlider1.maxTintColor = UIColor.clearColor() markInfo1.value = 0.3 markInfo1.image = UIImage(named: "bg") markInfo2.value = 0.5 markInfo2.image = UIImage(named: "bg2") markSlider1.markInfos = [markInfo1, markInfo2] markSlider1.addTarget(self, action: #selector(self.markSliderMarkTouchDown(_:)), for: .editingChanged) markSlider1.addTarget(self, action: #selector(self.markSliderValueChanged(_:)), for: .valueChanged) markSlider1.addTarget(self, action: #selector(self.markSliderTouchDown(_:)), for: .touchDown) markSlider1.addTarget(self, action: #selector(self.markSliderTouchUpInside(_:)), for: .touchUpInside) markSlider2 = GWMarkSlider() let y = UIApplication.shared.statusBarFrame.height + 44 + 20 markSlider2.frame = CGRect(x: 20, y: y, width: 200, height: 25) markSlider2.trackHeight = 5 markSlider2.minTintColor = UIColor.purple markSlider2.maxTintColor = UIColor.lightGray markSlider2.thumbTintColor = UIColor.red markSlider2.markInfos = [markInfo1, markInfo2, markInfo2] self.view.addSubview(markSlider2) } // MARK: - response methods @objc func markSliderMarkTouchDown(_ markSlider: GWMarkSlider) { print("\(#function): \(markSlider.selectedMarkIndex)") } @objc func markSliderValueChanged(_ markSlider: GWMarkSlider) { print("\(#function) : \(markSlider.currentValue)") } @objc func markSliderTouchDown(_ markSlider: GWMarkSlider) { print("\(#function) : ↓\(markSlider.currentValue)") } @objc func markSliderTouchUpInside(_ markSlider: GWMarkSlider) { print("\(#function) : ↑\(markSlider.currentValue)") } @IBAction func changeMarkPostionsButtonClick(_ sender: AnyObject) { markSlider1.markInfos = [markInfo1, markInfo2, markInfo1, markInfo2] } // UISlider response methods @IBAction func sliderTouchDown(_ sender: UISlider) { print("\(#function) : ↓\(sender.value)") } @IBAction func sliderTouchUpInside(_ sender: UISlider) { print("\(#function) : ↑\(sender.value)") } @IBAction func sliderValueChanged(_ sender: UISlider) { print("\(#function): \(sender.value)") } @IBAction func pushObjectiveCVC(_ sender: UIButton) { let vc = GWObjectiveCViewController(nibName: "GWObjectiveCViewController", bundle: nil) self.navigationController?.pushViewController(vc, animated: true) } }
mit
42df6adef6034e253cd9aa9835168c4f
31.395833
110
0.667203
4.146667
false
false
false
false
delba/Log
Source/Theme.swift
1
2858
// // Theme.swift // // Copyright (c) 2015-2019 Damien (http://delba.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. // import Foundation open class Themes {} open class Theme: Themes { /// The theme colors. var colors: [Level: String] /// The theme textual representation. var description: String { return colors.keys.sorted().map { $0.description.withColor(colors[$0]) }.joined(separator: " ") } /** Creates and returns a theme with the specified colors. - parameter trace: The color for the trace level. - parameter debug: The color for the debug level. - parameter info: The color for the info level. - parameter warning: The color for the warning level. - parameter error: The color for the error level. - returns: A theme with the specified colors. */ public init(trace: String, debug: String, info: String, warning: String, error: String) { colors = [ .trace: Theme.formatHex(trace), .debug: Theme.formatHex(debug), .info: Theme.formatHex(info), .warning: Theme.formatHex(warning), .error: Theme.formatHex(error) ] } /** Returns a string representation of the hex color. - parameter hex: The hex color. - returns: A string representation of the hex color. */ private static func formatHex(_ hex: String) -> String { let scanner = Scanner(string: hex) var hex: UInt32 = 0 scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#") scanner.scanHexInt32(&hex) let r = (hex & 0xFF0000) >> 16 let g = (hex & 0xFF00) >> 8 let b = (hex & 0xFF) return [r, g, b].map({ String($0) }).joined(separator: ",") } }
mit
84068fae28d1b6245c98bf00a7b4547a
34.283951
93
0.655703
4.330303
false
false
false
false
ddaguro/clintonconcord
OIMApp/Identity.swift
1
1336
// // Identity.swift // OIMApp // // Created by Linh NGUYEN on 5/6/15. // Copyright (c) 2015 Persistent Systems. All rights reserved. // import Foundation class Identity { //var Title : String! //var Location : String! //var Url : String! var Email : String! var UserLogin : String! var FirstName : String! var LastName : String! var FullName : String! var Title : String! var Role : String! var UsrCreate : String! init(data : NSDictionary){ //self.Title = Utils.getStringFromJSON(data, key: "title") //self.Location = Utils.getStringFromJSON(data, key: "location") //self.Url = Utils.getStringFromJSON(data, key: "siteurl") self.Email = Utils.getStringFromJSON(data, key: "Email") self.UserLogin = Utils.getStringFromJSON(data, key: "User Login") self.FirstName = Utils.getStringFromJSON(data, key: "First Name") self.LastName = Utils.getStringFromJSON(data, key: "Last Name") self.FullName = Utils.getStringFromJSON(data, key: "Full Name") self.Title = Utils.getStringFromJSON(data, key: "Title") self.Role = Utils.getStringFromJSON(data, key: "Role") self.UsrCreate = Utils.getStringFromJSON(data, key: "usr_create") } }
mit
60725af4bfe58a78889e712915715581
28.711111
73
0.618263
3.929412
false
false
false
false
jpush/aurora-imui
iOS/IMUIInputView/Controllers/IMUIInputView.swift
1
15494
// // IMUIInputView2.swift // sample // // Created by oshumini on 2018/4/12. // Copyright © 2018年 HXHG. All rights reserved. // import UIKit import Photos enum IMUIInputStatus { case text case microphone case photo case camera case emoji case none } public enum IMUIFeatureType { case voice case gallery case camera case location case emoji case empty case none } public protocol IMUIFeatureViewDelegate: NSObjectProtocol { func didSelectPhoto(with images: [UIImage]) func startRecordVoice() func didRecordVoice(with voicePath: String, durationTime: Double) func didShotPicture(with image: Data) func startRecordVideo() func didRecordVideo(with videoPath: String, durationTime: Double) func didSeletedEmoji(with emoji: IMUIEmojiModel) func didChangeSelectedGallery(with gallerys: [PHAsset]) func cameraFullScreen() func cameraRecoverScreen() } public extension IMUIFeatureViewDelegate { func didSelectPhoto(with images: [UIImage]) {} func startRecordVoice() {} func didRecordVoice(with voicePath: String, durationTime: Double) {} func didShotPicture(with image: Data) {} func startRecordVideo() {} func didRecordVideo(with videoPath: String, durationTime: Double) {} func didSeletedEmoji(with emoji: IMUIEmojiModel) {} func didChangeSelectedGallery() {} func cameraFullScreen() {} func cameraRecoverScreen() {} } open class IMUIInputView: IMUICustomInputView { struct IMUIInputViewData { var left: [IMUIFeatureIconModel] var right: [IMUIFeatureIconModel] var bottom: [IMUIFeatureIconModel] var allObjects: [String: [IMUIFeatureIconModel]] { return [ "left": left, "right": right, "bottom": bottom ] } func dataWithPositon(position: IMUIInputViewItemPosition) -> [IMUIFeatureIconModel] { switch position { case .left: return left case .right: return right case .bottom: return bottom } } } var inputBarItemData = IMUIInputViewData(left: [IMUIFeatureIconModel](), right: [IMUIFeatureIconModel](), bottom: [IMUIFeatureIconModel]()) var currentType:IMUIFeatureType = .voice @objc public weak var delegate: IMUIInputViewDelegate? override public init(frame: CGRect) { super.init(frame: frame) } open override func awakeFromNib() { super.awakeFromNib() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupInputViewData() self.inputViewDelegate = self self.dataSource = self } func setupInputViewData() { inputBarItemData.bottom.append(IMUIFeatureIconModel(featureType: .voice, UIImage.imuiImage(with: "input_item_mic"), UIImage.imuiImage(with:"input_item_mic"))) inputBarItemData.bottom.append(IMUIFeatureIconModel(featureType: .gallery, UIImage.imuiImage(with: "input_item_photo"), UIImage.imuiImage(with:"input_item_photo"))) inputBarItemData.bottom.append(IMUIFeatureIconModel(featureType: .camera, UIImage.imuiImage(with: "input_item_camera"), UIImage.imuiImage(with:"input_item_camera"))) inputBarItemData.bottom.append(IMUIFeatureIconModel(featureType: .emoji, UIImage.imuiImage(with: "input_item_emoji"), UIImage.imuiImage(with:"input_item_emoji"))) inputBarItemData.bottom.append(IMUIFeatureIconModel(featureType: .none, UIImage.imuiImage(with: "input_item_send"), UIImage.imuiImage(with:"input_item_send_message_selected"), 0, false)) self.registerCellForInputView() } // for react native dynamic, config inputViewBar with json @objc public func setupDataWithDic(dic:[String:[String]]) { var newData = IMUIInputViewData(left: [IMUIFeatureIconModel](), right: [IMUIFeatureIconModel](), bottom: [IMUIFeatureIconModel]()) for (positionStr, itemArr) in dic { let position = self.convertStringToPosition(str: positionStr) for itemStr in itemArr { switch position { case .left: if let item = self.convertStringToIconModel(itemStr: itemStr) { newData.left.append(item) } break case .right: if let item = self.convertStringToIconModel(itemStr: itemStr) { newData.right.append(item) } break case .bottom: if let item = self.convertStringToIconModel(itemStr: itemStr) { newData.bottom.append(item) } break } } } self.inputBarItemData = newData self.layoutInputBar() self.reloadData() } @objc public func isNeedShowBottomView() -> Bool{ return !inputBarItemData.bottom.isEmpty } fileprivate func convertStringToIconModel(itemStr: String) ->IMUIFeatureIconModel? { if itemStr == "voice" { return IMUIFeatureIconModel(featureType: .voice, UIImage.imuiImage(with: "input_item_mic"), UIImage.imuiImage(with:"input_item_mic")) } if itemStr == "gallery" { return IMUIFeatureIconModel(featureType: .gallery, UIImage.imuiImage(with: "input_item_photo"), UIImage.imuiImage(with:"input_item_photo")) } if itemStr == "camera" { return IMUIFeatureIconModel(featureType: .camera, UIImage.imuiImage(with: "input_item_camera"), UIImage.imuiImage(with:"input_item_camera")) } if itemStr == "emoji" { return IMUIFeatureIconModel(featureType: .emoji, UIImage.imuiImage(with: "input_item_emoji"), UIImage.imuiImage(with:"input_item_emoji")) } if itemStr == "send" { return IMUIFeatureIconModel(featureType: .none, UIImage.imuiImage(with: "input_item_send"), UIImage.imuiImage(with:"input_item_send_message_selected"), 0, false) } return nil } fileprivate func registerCellForInputView() { let bundle = Bundle.imuiInputViewBundle() self.register(UINib(nibName: "IMUIFeatureListIconCell", bundle: bundle), in: .bottom, forCellWithReuseIdentifier: "IMUIFeatureListIconCell") self.register(UINib(nibName: "IMUIFeatureListIconCell", bundle: bundle), in: .right, forCellWithReuseIdentifier: "IMUIFeatureListIconCell") self.register(UINib(nibName: "IMUIFeatureListIconCell", bundle: bundle), in: .left, forCellWithReuseIdentifier: "IMUIFeatureListIconCell") self.registerForFeatureView(UINib(nibName: "IMUIRecordVoiceCell", bundle: bundle), forCellWithReuseIdentifier: "IMUIRecordVoiceCell") self.registerForFeatureView(UINib(nibName: "IMUIGalleryContainerCell", bundle: bundle), forCellWithReuseIdentifier: "IMUIGalleryContainerCell") self.registerForFeatureView(UINib(nibName: "IMUICameraCell", bundle: bundle), forCellWithReuseIdentifier: "IMUICameraCell") self.registerForFeatureView(UINib(nibName: "IMUIEmojiCell", bundle: bundle), forCellWithReuseIdentifier: "IMUIEmojiCell") self.registerForFeatureView(IMUIEmptyContainerCell.self, forCellWithReuseIdentifier: "IMUIEmptyContainerCell") } // need dynamic get send model for react-native custom layout fileprivate var sendModel: IMUIFeatureIconModel { let position = self.findSendPosition() let model = inputBarItemData.dataWithPositon(position: position.position)[position.index] return model } fileprivate func findSendPosition() -> (position:IMUIInputViewItemPosition, index:Int) { for (key, arr) in inputBarItemData.allObjects { for model in arr { if model.featureType == .none { let position = self.convertStringToPosition(str: key) let index = arr.index(of: model) return (position, index!) } } } return (.bottom,1) } fileprivate func convertStringToPosition(str: String) -> IMUIInputViewItemPosition { if str == "left" { return .left } if str == "right" { return .right } return .bottom } fileprivate func switchToFeature(type: IMUIFeatureType, button: UIButton) { self.featureView.layoutFeature(with: type) switch type { case .voice: self.delegate?.switchToMicrophoneMode?(recordVoiceBtn: button) break case .camera: self.delegate?.switchToCameraMode?(cameraBtn: button) break case .gallery: self.delegate?.switchToGalleryMode?(photoBtn: button) break case .emoji: self.delegate?.switchToEmojiMode?(cameraBtn: button) break default: break } } } extension IMUIInputView: IMUICustomInputViewDataSource { public func imuiInputView(_ inputBarItemListView: UICollectionView, numberForItemAt position: IMUIInputViewItemPosition) -> Int { switch position { case .right: return self.inputBarItemData.right.count case .left: return self.inputBarItemData.left.count case .bottom: return self.inputBarItemData.bottom.count } } public func imuiInputView(_ inputBarItemListView: UICollectionView, _ position: IMUIInputViewItemPosition, sizeForIndex indexPath: IndexPath) -> CGSize { return CGSize(width: 30, height: 30) } public func imuiInputView(_ inputBarItemListView: UICollectionView, _ position: IMUIInputViewItemPosition, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var dataArr:[IMUIFeatureIconModel] switch position { case .bottom: dataArr = self.inputBarItemData.bottom case .right: dataArr = self.inputBarItemData.right default: dataArr = self.inputBarItemData.left } let cellIdentifier = "IMUIFeatureListIconCell" let cell = inputBarItemListView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! IMUIFeatureListIconCell cell.layout(with: dataArr[indexPath.item],onClickCallback: { cell in if cell.featureData!.featureType != .none { self.currentType = cell.featureData!.featureType self.switchToFeature(type: self.currentType, button: cell.featureIconBtn) self.showFeatureView() self.reloadFeaturnView() } switch cell.featureData!.featureType { case .none: self.clickSendBtn(cell: cell) break default: break } }) return cell } // featureView dataSource public func imuiInputView(_ featureView: UICollectionView, cellForItem indexPath: IndexPath) -> UICollectionViewCell { var CellIdentifier = "" switch currentType { case .voice: CellIdentifier = "IMUIRecordVoiceCell" case .camera: CellIdentifier = "IMUICameraCell" break case .emoji: CellIdentifier = "IMUIEmojiCell" break case .location: // TODO: break case .gallery: CellIdentifier = "IMUIGalleryContainerCell" break case .empty: CellIdentifier = "IMUIEmptyContainerCell" default: break } var cell = featureView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! IMUIFeatureCellProtocol cell.activateMedia() cell.featureDelegate = self return cell as! UICollectionViewCell } } extension IMUIInputView: IMUIFeatureListDelegate { func clickSendBtn(cell: IMUIFeatureListIconCell) { if IMUIGalleryDataManager.selectedAssets.count > 0 { self.delegate?.didSeletedGallery?(AssetArr: IMUIGalleryDataManager.selectedAssets) self.featureView.clearAllSelectedGallery() self.updateSendBtnToPhotoSendStatus() return } if inputTextView.text != "" { delegate?.sendTextMessage?(self.inputTextView.text) inputTextView.text = "" self.delegate?.textDidChange?(text: "") fitTextViewSize(inputTextView) } self.updateSendBtnToPhotoSendStatus() } public func updateSendBtnToPhotoSendStatus() { var isAllowToSend = false let seletedPhotoCount = IMUIGalleryDataManager.selectedAssets.count if seletedPhotoCount > 0 { isAllowToSend = true } if inputTextView.text != "" { isAllowToSend = true } self.sendModel.isAllowToSend = isAllowToSend self.sendModel.photoCount = seletedPhotoCount let sendPosition = self.findSendPosition() self.updateInputBarItemCell(sendPosition.position, at: sendPosition.index) } } extension IMUIInputView: IMUIFeatureViewDelegate { public func cameraRecoverScreen() { self.delegate?.cameraRecoverScreen?() } public func cameraFullScreen() { self.delegate?.cameraFullScreen?() } public func didChangeSelectedGallery(with gallerys: [PHAsset]) { self.updateSendBtnToPhotoSendStatus() } public func didSelectPhoto(with images: [UIImage]) { self.updateSendBtnToPhotoSendStatus() } public func didSeletedEmoji(with emoji: IMUIEmojiModel) { switch emoji.emojiType { case .emoji: let inputStr = "\(self.inputTextView.text!)\(emoji.emoji!)" self.inputTextView.text = inputStr self.fitTextViewSize(self.inputTextView) self.updateSendBtnToPhotoSendStatus() self.delegate?.textDidChange?(text: inputStr) default: return } } public func didRecordVoice(with voicePath: String, durationTime: Double) { self.delegate?.finishRecordVoice?(voicePath, durationTime: durationTime) } public func didShotPicture(with image: Data) { self.delegate?.didShootPicture?(picture: image) } public func startRecordVideo() { self.delegate?.startRecordVideo?() } public func startRecordVoice() { self.delegate?.startRecordVoice?() } public func didRecordVideo(with videoPath: String, durationTime: Double) { self.delegate?.finishRecordVideo?(videoPath: videoPath, durationTime: durationTime) } } extension IMUIInputView: IMUICustomInputViewDelegate { public func textDidChange(text: String) { self.updateSendBtnToPhotoSendStatus() self.delegate?.textDidChange?(text: text) } public func keyBoardWillShow(height: CGFloat, durationTime: Double) { self.currentType = .empty self.delegate?.keyBoardWillShow?(height: height, durationTime: durationTime) self.reloadFeaturnView() } } class IMUIEmptyContainerCell: UICollectionViewCell,IMUIFeatureCellProtocol { }
mit
29c5916ddcbb0dd260c60fee183c7b62
31.750529
144
0.642954
4.626941
false
false
false
false
sayheyrickjames/codepath-dev
week5/week5-homework-facebook-photos/week5-homework-facebook-photos/NewsFeedViewController.swift
2
2003
// // NewsFeedViewController.swift // week5-homework-facebook-photos // // Created by Rick James! Chatas on 6/6/15. // Copyright (c) 2015 SayHey. All rights reserved. // import UIKit class NewsFeedViewController: UIViewController { // outlets @IBOutlet weak var NewsFeedScrollView: UIScrollView! // variables var selectedImageView: UIImageView! var imageTransition: ImageTransition! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. NewsFeedScrollView.contentSize = CGSize(width: view.frame.width, height: 1536) NewsFeedScrollView.frame.size = CGSize(width: view.frame.width, height: view.frame.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTap(sender: AnyObject) { selectedImageView = sender.view as! UIImageView performSegueWithIdentifier("photoSegue", sender: self) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destinationViewController = segue.destinationViewController as! PhotoViewController destinationViewController.bigImage = selectedImageView.image // take over the transition imageTransition = ImageTransition() imageTransition.duration = 0.4 destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom destinationViewController.transitioningDelegate = imageTransition // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } }
gpl-2.0
ef4ad725ed215e285f9ad05790b267f6
29.815385
106
0.671493
5.856725
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Extensions/Notifications/Notification+Interface.swift
2
2619
import Foundation /// Encapsulates Notification Interface Helpers /// extension Notification { /// Returns a Section Identifier that can be sorted. Note that this string is not human readable, and /// you should use the *descriptionForSectionIdentifier* method as well!. /// @objc func sectionIdentifier() -> String { // Normalize Dates: Time must not be considered. Just the raw dates let fromDate = timestampAsDate.normalizedDate() let toDate = Date().normalizedDate() // Analyze the Delta-Components let calendar = Calendar.current let components = [.day, .weekOfYear, .month] as Set<Calendar.Component> let dateComponents = calendar.dateComponents(components, from: fromDate, to: toDate) let identifier: Sections // Months if let month = dateComponents.month, month >= 1 { identifier = .Months // Weeks } else if let week = dateComponents.weekOfYear, week >= 1 { identifier = .Weeks // Days } else if let day = dateComponents.day, day > 1 { identifier = .Days } else if let day = dateComponents.day, day == 1 { identifier = .Yesterday } else { identifier = .Today } return identifier.rawValue } /// Translates a Section Identifier into a Human-Readable String. /// @objc class func descriptionForSectionIdentifier(_ identifier: String) -> String { guard let section = Sections(rawValue: identifier) else { return String() } return section.description } // MARK: - Private Helpers fileprivate enum Sections: String { case Months = "0" case Weeks = "2" case Days = "4" case Yesterday = "5" case Today = "6" var description: String { switch self { case .Months: return NSLocalizedString("Older than a Month", comment: "Notifications Months Section Header") case .Weeks: return NSLocalizedString("Older than a Week", comment: "Notifications Weeks Section Header") case .Days: return NSLocalizedString("Older than 2 days", comment: "Notifications +2 Days Section Header") case .Yesterday: return NSLocalizedString("Yesterday", comment: "Notifications Yesterday Section Header") case .Today: return NSLocalizedString("Today", comment: "Notifications Today Section Header") } } } }
gpl-2.0
1458bb68b1f4287c7a58c148b9899a94
34.391892
110
0.599084
5.238
false
false
false
false
pawanpoudel/SwiftNews
SwiftNews/ExternalDependencies/UserInterface/ArticleList/ArticleListTableDataSource.swift
1
2498
import CoreData let DidSelectArticleNotification = "DidSelectArticleNotification" class ArticleListTableDataSource : NSObject, UITableViewDataSource, UITableViewDelegate { var shouldShowArticleLoadingError: Bool! var fetchedResultsController: NSFetchedResultsController? private weak var tableView: UITableView! // MARK: - Configuring table view func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { self.tableView = tableView if shouldShowArticleLoadingError == true { return 1 } let sections = fetchedResultsController?.sections as! [NSFetchedResultsSectionInfo] return sections[section].numberOfObjects } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if shouldShowArticleLoadingError == true { } return articleCellAtIndexPath(indexPath) } private func articleCellAtIndexPath(indexPath: NSIndexPath) -> ArticleCell { let cell = createArticleCell() configureArticleCell(cell, indexPath: indexPath) return cell } private func createArticleCell() -> ArticleCell { let reuseId = ArticleCell.reuseIdentifier() var cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier(reuseId) if cell == nil { let nibName = ArticleCell.nibName() cell = UIView.loadViewFromNibName(nibName) } return cell as! ArticleCell } private func configureArticleCell(cell: ArticleCell, indexPath: NSIndexPath) { if let article = fetchedResultsController?.objectAtIndexPath(indexPath) as? Article { cell.setArticle(article) } } // MARK: - Computing cell height func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if shouldShowArticleLoadingError == true { } return ArticleCell.height() } // MARK: - Handling cell tap func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let article = fetchedResultsController?.articleAtIndexPath(indexPath) let notification = NSNotification(name: DidSelectArticleNotification, object: article) NSNotificationCenter.defaultCenter().postNotification(notification) } }
mit
6dc439eb5ac0ba0b183088f39dfbfd64
33.694444
109
0.675741
6.092683
false
false
false
false
PedroTrujilloV/TIY-Assignments
37--Resurgence/VenueMenu/VenueMenu/SearchVenueTableViewController.swift
1
8131
// // SearchVenueTableViewController.swift // VenueMenu // // Created by Pedro Trujillo on 11/29/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit protocol APIControllerProtocol { func didReceiveAPIResults(results:NSArray) } protocol PopoverViewControllerProtocol { func cityWasChosen(lat:String,long:String, name:String) } class SearchVenueTableViewController: UITableViewController,APIControllerProtocol,UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating,PopoverViewControllerProtocol,UIPopoverPresentationControllerDelegate { var venuesArray:Array<NSDictionary> = [] var venuesIDsArray: Array<String> = [] var selectedVenuesArray:Array<NSDictionary> = [] var shouldShowSearchResults = false var searchController = UISearchController(searchResultsController: nil) var locationString:String = "" var api: APIController! var delegator: SearchTableViewProtocol! override func viewDidLoad() { super.viewDidLoad() title = "Set up the prefered" self.performSegueWithIdentifier("PopoverAddCityViewControllerSegue", sender: self) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() api = APIController(delegate: self) //api.searchApiFoursquareForData("sushi",byCriteria: "ll",location: "28.5542151,-81.34544170000001") //api.searchApiFoursquareForData("sushi",byCriteria: "",location: "Orlando, Fl") searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = true//false searchController.hidesNavigationBarDuringPresentation = false //searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200, height: 80) //searchController.searchBar.center.y = 200 searchController.searchBar.delegate = self searchController.searchBar.placeholder = " type venue!" searchController.searchBar.sizeToFit() tableView.tableHeaderView = searchController.searchBar UIApplication.sharedApplication().networkActivityIndicatorVisible = true tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { print(selectedVenuesArray) delegator.venueWasFound(selectedVenuesArray) venuesArray.removeAll() selectedVenuesArray.removeAll() UIApplication.sharedApplication().networkActivityIndicatorVisible = false //searchController.hidesNavigationBarDuringPresentation = true dismissViewControllerAnimated(true, completion: nil) // this destroy the modal view like the popover } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return venuesArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) // Configure the cell... let venue:NSDictionary = venuesArray[indexPath.row] if !venuesIDsArray.contains( venue["id"] as! NSString as String) { cell.textLabel?.text = venue["name"] as! NSString as String } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let venue:NSDictionary = venuesArray[indexPath.row] if !venuesIDsArray.contains( venue["id"] as! NSString as String) { venuesIDsArray.append(venue["id"] as! NSString as String) selectedVenuesArray.append(venue) } } //MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PopoverAddCityViewControllerSegue" { let destVC = segue.destinationViewController as! PopoverAddCityViewController // 1 destVC.popoverPresentationController?.delegate = self // 2 destVC.delegator = self // 3 nescessary to get the value from the popover destVC.preferredContentSize = CGSizeMake(210.0, 70.0) } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } //MARK: Protocol function func didReceiveAPIResults(results:NSArray) { dispatch_async(dispatch_get_main_queue(), { self.venuesArray = results as! Array<NSDictionary> self.tableView.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) } func cityWasChosen(lat:String,long:String, name:String) { print(" latitudde: " + lat) print(" longitude: " + long) locationString = lat+","+long title = name navigationController?.dismissViewControllerAnimated(true, completion: nil)// this thing hides the popover } //MARK: Search bar methods func searchBarTextDidBeginEditing(searchBar: UISearchBar) { //print("me empieza! usame! soy tuya!") shouldShowSearchResults = true //gitHubFriends.removeAll() tableView.reloadData() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { //print("no pares!!") shouldShowSearchResults = false venuesArray.removeAll() tableView.reloadData() //UIApplication.sharedApplication().networkActivityIndicatorVisible = false dismissViewControllerAnimated(true, completion: nil) // this destroy the modal view like the popover } func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !shouldShowSearchResults { shouldShowSearchResults = true // api.searchApiFoursquareForData(searchBar.text!,byCriteria: "ll",location: "28.5542151,-81.34544170000001") tableView.reloadData() } searchController.searchBar.resignFirstResponder() } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { //print("me estas escribiendo") shouldShowSearchResults = false venuesArray.removeAll() tableView.reloadData() } func searchBarTextDidEndEditing(searchBar: UISearchBar) { //print("no te demores quiero mas") shouldShowSearchResults = true venuesArray.removeAll() api.searchApiFoursquareForData(searchBar.text!,byCriteria: "ll",location: locationString) tableView.reloadData() } func updateSearchResultsForSearchController(searchController: UISearchController) { //print("Hola papy estoy buscando") // Reload the tableview. tableView.reloadData() } //MARK: Action Handlers func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } }
cc0-1.0
4f0980b3f79c2159df36e16817c011b7
30.757813
221
0.670111
5.645833
false
false
false
false
mathcamp/Carlos
Carlos/CacheLevel+Batch.swift
1
1886
import Foundation import PiedPiper extension CacheLevel { /** Performs a batch of get requests on this CacheLevel - parameter keys: The list of keys to batch - returns: A Future that will call the success callback when ALL the keys will be fetched successfully, and the failure callback as soon as JUST ONE of the keys cannot be fetched. */ public func batchGetAll(keys: [KeyType]) -> Future<[OutputType]> { return keys.traverse(get) } /** Performs a batch of get requests on this CacheLevel - parameter keys: The list of keys to batch - returns: A Future that will call the success callback when all the keys will be either fetched or failed, passing a list containing just the successful results */ public func batchGetSome(keys: [KeyType]) -> Future<[OutputType]> { let resultPromise = Promise<[OutputType]>() let resultsLock: ReadWriteLock = PThreadReadWriteLock() let counterLock: ReadWriteLock = PThreadReadWriteLock() var completedRequests = 0 var intermediateResults = Array<OutputType?>(count: keys.count, repeatedValue: nil) var batchedRequests: [Future<OutputType>] = [] keys.enumerate().forEach { (iteration, key) in batchedRequests.append(get(key) .onCompletion { result in if case .Success(let value) = result { resultsLock.withWriteLock { intermediateResults[iteration] = value } } counterLock.withWriteLock { completedRequests += 1 if completedRequests == keys.count { resultPromise.succeed(intermediateResults.flatMap { $0 }) } } } ) } resultPromise.onCancel { batchedRequests.forEach { request in request.cancel() } } return resultPromise.future } }
mit
3f591f3cfde11eaccb4b1c4012c2e342
30.983051
182
0.644221
5.029333
false
false
false
false
bugnitude/SamplePDFViewer
SamplePDFViewer/PDFPageViewController.swift
1
2414
import UIKit class PDFPageViewController: UIViewController { // MARK: - Property private var page: CGPDFPage? var pageNumber: Int? { return self.page?.pageNumber } var alignment: PDFPageAlignment = .center { didSet { self.pageImageView.alignment = self.alignment self.pageDrawView.alignment = self.alignment } } private weak var pageImageView: PDFPageImageView! private weak var pageDrawView: PDFPageDrawView! // MARK: - Initializer convenience init(page: CGPDFPage?, box: CGPDFBox, backgroundColor: UIColor) { self.init(nibName: nil, bundle: nil) // Set Page self.page = page // Setup if let page = self.page { // Set Background Color self.view.backgroundColor = backgroundColor // Setup Page Image View let pageImageView = PDFPageImageView(page: page, box: box, size: UIScreen.main.fixedCoordinateSpace.bounds.size) pageImageView.alignment = self.alignment pageImageView.fillColor = backgroundColor pageImageView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(pageImageView) self.pageImageView = pageImageView // Setup Page Draw View let pageDrawView = PDFPageDrawView(page: page, box: box) pageDrawView.alignment = self.alignment pageDrawView.fillColor = backgroundColor pageDrawView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(pageDrawView) self.pageDrawView = pageDrawView // Add Constraints var constraints = [NSLayoutConstraint]() constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": pageImageView])) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": pageImageView])) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": pageDrawView])) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": pageDrawView])) NSLayoutConstraint.activate(constraints) } } private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
5c7d6839a192057484d066e7bb5263ff
35.029851
156
0.742751
4.190972
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/Tutorial(教程)/View/KYContainerView.swift
1
1728
// // KYContainerView.swift // KYHandMade // // Created by Kerain on 2017/6/20. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // import UIKit class KYContainerView: UIScrollView { var selecdBlock : ((_ index : Int)->())? var childVCs : [UIViewController]? init(frame:CGRect,childVCs:[UIViewController],selecdBlock:@escaping (_ index : Int)->()) { super.init(frame: frame) self.selecdBlock = selecdBlock self.childVCs = childVCs backgroundColor = UIColor.white isPagingEnabled = true showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false self.delegate = self let count : CGFloat = CGFloat((self.childVCs?.count)!) contentSize = CGSize(width:count * SCREEN_WIDTH, height: 0) for (index,subVC) in childVCs.enumerated() { let subViewX = CGFloat(index) * SCREEN_WIDTH subVC.view.frame = CGRect(x:subViewX, y:0, width: SCREEN_WIDTH, height: height) addSubview(subVC.view) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateVCViewFromIndex(index : Int) { setContentOffset(CGPoint(x:CGFloat(index) * SCREEN_WIDTH, y: 0), animated: true) } } extension KYContainerView : UIScrollViewDelegate{ func scrollViewDidScroll(_ scrollView: UIScrollView) { let page = (scrollView.contentOffset.x + SCREEN_WIDTH / 2.0 ) / SCREEN_WIDTH guard let block = self.selecdBlock else { return } block(Int(page)) } }
apache-2.0
3d1130dad15fc89de367a2a1039de0a7
26.852459
94
0.612125
4.367609
false
false
false
false
hughbe/swift
test/Driver/subcommands.swift
2
2022
// Check that each of 'swift', 'swift repl', 'swift run' invoke the REPL. // // REQUIRES: swift_interpreter // // RUN: rm -rf %t.dir // RUN: mkdir -p %t.dir/usr/bin // RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t.dir/usr/bin/swift) // RUN: %t.dir/usr/bin/swift -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s // RUN: %t.dir/usr/bin/swift run -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s // RUN: %t.dir/usr/bin/swift repl -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s // // CHECK-SWIFT-INVOKES-REPL: {{.*}}/swift -frontend -repl // Check that 'swift -', 'swift t.swift', and 'swift /path/to/file' invoke the interpreter // (for shebang line use). We have to run these since we can't get the driver to // dump what it is doing and test the argv[1] processing. // // RUN: %empty-directory(%t.dir) // RUN: %empty-directory(%t.dir/subpath) // RUN: echo "print(\"exec: \" + #file)" > %t.dir/stdin // RUN: echo "print(\"exec: \" + #file)" > %t.dir/t.swift // RUN: echo "print(\"exec: \" + #file)" > %t.dir/subpath/build // RUN: cd %t.dir && %swift_driver_plain - < %t.dir/stdin -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-STDIN-INVOKES-INTERPRETER %s // CHECK-SWIFT-STDIN-INVOKES-INTERPRETER: exec: <stdin> // RUN: cd %t.dir && %swift_driver_plain t.swift -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER %s // CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER: exec: t.swift // RUN: cd %t.dir && %swift_driver_plain subpath/build -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-PATH-INVOKES-INTERPRETER %s // CHECK-SWIFT-PATH-INVOKES-INTERPRETER: exec: subpath/build // Check that 'swift foo' invokes 'swift-foo'. // // RUN: %empty-directory(%t.dir) // RUN: echo "#!/bin/sh" > %t.dir/swift-foo // RUN: echo "echo \"exec: \$0\"" >> %t.dir/swift-foo // RUN: chmod +x %t.dir/swift-foo // RUN: env PATH=%t.dir %swift_driver_plain foo | %FileCheck -check-prefix=CHECK-SWIFT-SUBCOMMAND %s // CHECK-SWIFT-SUBCOMMAND: exec: {{.*}}/swift-foo
apache-2.0
e417e140925f523b05d9454e55b04ba6
49.55
135
0.658754
2.876245
false
false
false
false
ziligy/JGScrollerController
JGScrollerController/ScrollerControls.swift
1
4897
// // ScrollerControls.swift // JGScrollerController // // Created by Jeff on 1/30/16. // Copyright © 2016 Jeff Greenberg. All rights reserved. // import UIKit protocol JGScrollerControlInterface { func createNextAndPreviousControlAndAddToSubview(vc: UIViewController) func createCloseControlAndAddToSubview(vc: UIViewController) func hideNextControl(hidden: Bool) func hidePrevControl(hidden: Bool) var delegateScrollerControl: JGScrollerControlDelegate? { get set } } internal class ScrollerControls: NSObject, JGScrollerControlInterface { internal var delegateScrollerControl: JGScrollerControlDelegate? private let bundle = NSBundle(forClass: JGScrollerController.self) private var nextButton: JGTapButton! private var prevButton: JGTapButton! private var closeButton: JGTapButton! private let buttonColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.75) private let largeButtonSize: CGFloat = 48 private let smallButtonSize: CGFloat = 30 private let nextButtonImage = "ic_chevron_right_white_48pt.png" private let prevButtonImage = "ic_chevron_left_white_48pt.png" private let closeButtonImage = "ic_close_white_12pt_2x.png" // MARK: create buttons internal func createNextAndPreviousControlAndAddToSubview(vc: UIViewController) { let nextButton = JGTapButton(sideSize: largeButtonSize) nextButton.mainColor = buttonColor if let image = UIImage(named: nextButtonImage, inBundle: bundle, compatibleWithTraitCollection: nil) { nextButton.image = image } else { nextButton.title = ">" } nextButton.addTarget(self, action: "next", forControlEvents: UIControlEvents.TouchUpInside) vc.view.addSubview(nextButton) nextButton.translatesAutoresizingMaskIntoConstraints = false nextButton.centerYAnchor.constraintEqualToAnchor(vc.view.centerYAnchor).active = true nextButton.trailingAnchor.constraintEqualToAnchor(vc.view.trailingAnchor, constant: -6).active = true nextButton.widthAnchor.constraintEqualToConstant(largeButtonSize).active = true nextButton.heightAnchor.constraintEqualToConstant(largeButtonSize).active = true let prevButton = JGTapButton(sideSize: largeButtonSize) prevButton.mainColor = buttonColor if let image = UIImage(named: prevButtonImage, inBundle: bundle, compatibleWithTraitCollection: nil) { prevButton.image = image } else { prevButton.title = "<" } prevButton.addTarget(self, action: "previous", forControlEvents: UIControlEvents.TouchUpInside) vc.view.addSubview(prevButton) prevButton.translatesAutoresizingMaskIntoConstraints = false prevButton.centerYAnchor.constraintEqualToAnchor(vc.view.centerYAnchor).active = true prevButton.leadingAnchor.constraintEqualToAnchor(vc.view.leadingAnchor, constant: 6).active = true prevButton.widthAnchor.constraintEqualToConstant(largeButtonSize).active = true prevButton.heightAnchor.constraintEqualToConstant(largeButtonSize).active = true self.nextButton = nextButton self.prevButton = prevButton } internal func createCloseControlAndAddToSubview(vc: UIViewController) { let closeButton = JGTapButton(sideSize: smallButtonSize) closeButton.mainColor = buttonColor if let image = UIImage(named: closeButtonImage, inBundle: bundle, compatibleWithTraitCollection: nil) { closeButton.image = image } else { closeButton.title = "X" } closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside) vc.view.addSubview(closeButton) closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.topAnchor.constraintEqualToAnchor(vc.topLayoutGuide.bottomAnchor, constant: 6).active = true closeButton.trailingAnchor.constraintEqualToAnchor(vc.view.trailingAnchor, constant: -6).active = true closeButton.widthAnchor.constraintEqualToConstant(smallButtonSize).active = true closeButton.heightAnchor.constraintEqualToConstant(smallButtonSize).active = true self.closeButton = closeButton } // MARK: hide functions internal func hideNextControl(hidden: Bool) { nextButton.hidden = hidden } internal func hidePrevControl(hidden: Bool) { prevButton.hidden = hidden } // MARK: trigger the delegates internal func close() { delegateScrollerControl?.close() } internal func next() { delegateScrollerControl?.nextPage() } internal func previous() { delegateScrollerControl?.previousPage() } }
mit
f63de8c36164e1a5a4fb14e5925cad94
40.142857
112
0.709355
5.315961
false
false
false
false
Stitch7/Vaporizer
App/Controllers/FormController.swift
1
2306
// // FormController.swift // Vaporizer // // Created by Christopher Reitz on 29.10.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import Vapor import HTTP final class FormController { // MARK: - Properties let drop: Droplet // MARK: - Initializers init(droplet: Droplet) { drop = droplet Form.database = drop.database } // MARK: - Actions func index(request: Request) throws -> ResponseRepresentable { return JSON(try Form.all().map { try $0.makeJSON() }) } func store(request: Request) throws -> ResponseRepresentable { guard let requestJson = request.json, let userId = try request.user().id?.int else { throw Abort.badRequest } var json = requestJson json["user_id"] = JSON(Node(userId)) var form = try Form(node: json) try form.save() return try form.makeJSON() } func show(request: Request, item form: Form) throws -> ResponseRepresentable { return form } func replace(request: Request, item form: Form) throws -> ResponseRepresentable { guard let json = request.json else { throw Abort.badRequest } var replaced = try Form(node: json) replaced.id = form.id try replaced.save() return replaced } func modify(request: Request, item form: Form) throws -> ResponseRepresentable { var modified = form modified.question1 = request.data["question1"]?.string ?? modified.question1 modified.question2 = request.data["question2"]?.string ?? modified.question2 modified.question3 = request.data["question3"]?.string ?? modified.question3 try modified.save() return modified } func destroy(request: Request, item form: Form) throws -> ResponseRepresentable { try form.delete() return JSON([:]) } } // MARK: - ResourceRepresentable extension FormController: ResourceRepresentable { func makeResource() -> Resource<Form> { return Resource( index: index, store: store, show: show, replace: replace, modify: modify, destroy: destroy ) } }
mit
e97742a60181d297cb36ec558ff9fcee
23.263158
85
0.598265
4.628514
false
false
false
false
andreaperizzato/CoreStore
CoreStoreDemo/CoreStoreDemo/Loggers Demo/CustomLoggerViewController.swift
3
4137
// // CustomLoggerViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/05. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import UIKit import CoreStore import GCDKit // MARK: - CustomLoggerViewController class CustomLoggerViewController: UIViewController, CoreStoreLogger { // MARK: NSObject deinit { CoreStore.logger = DefaultLogger() } let dataStack = DataStack() // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() try! self.dataStack.addSQLiteStoreAndWait(fileName: "emptyStore.sqlite") CoreStore.logger = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let alert = UIAlertController( title: "Logger Demo", message: "This demo shows how to plug-in any logging framework to CoreStore.\n\nThe view controller implements CoreStoreLogger and appends all logs to the text view.", preferredStyle: .Alert ) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } // MARK: CoreStoreLogger func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { GCDQueue.Main.async { [weak self] in let levelString: String switch level { case .Trace: levelString = "Trace" case .Notice: levelString = "Notice" case .Warning: levelString = "Warning" case .Fatal: levelString = "Fatal" } self?.textView?.insertText("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Log:\(levelString)] \(message)\n\n") } } func handleError(error error: NSError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { GCDQueue.Main.async { [weak self] in self?.textView?.insertText("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Error] \(message): \(error)\n\n") } } func assert(@autoclosure condition: () -> Bool, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { if condition() { return } GCDQueue.Main.async { [weak self] in self?.textView?.insertText("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Assert] \(message)\n\n") } } @noreturn func fatalError(message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { Swift.fatalError("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Abort] \(message)") } // MARK: Private @IBOutlet dynamic weak var textView: UITextView? @IBOutlet dynamic weak var segmentedControl: UISegmentedControl? @IBAction dynamic func segmentedControlValueChanged(sender: AnyObject?) { switch self.segmentedControl?.selectedSegmentIndex { case .Some(0): self.dataStack.beginAsynchronous { (transaction) -> Void in transaction.create(Into(Palette)) } case .Some(1): do { try self.dataStack.addSQLiteStoreAndWait(fileName: "emptyStore.sqlite", configuration: "invalidStore") } catch _ { } case .Some(2): self.dataStack.beginAsynchronous { (transaction) -> Void in transaction.commit() transaction.commit() } default: return } } }
mit
c72d6f9d74326b0f1130a71e7c599fc5
30.945736
179
0.58481
5.310567
false
false
false
false
brunomorgado/RxNetworking
RxNetworking/Classes/Authentication/OAuth2/OAuth2Credential.swift
1
3821
// // OAuth2Credential.swift // RxNetworking // // Created by Bruno Morgado on 13/08/16. // Copyright © 2016 KO Computer. All rights reserved. // import Foundation extension K { struct OAuth2Credential { static let kUsernameKey = "username" static let kPasswordKey = "password" static let kAccessTokenKey = "access_token" static let kTokenTypeKey = "token_type" static let kGrantTypeKey = "grant_type" static let kRefreshTokenKey = "refresh_token" static let kExpirationKey = "expires_in" } } public final class OAuth2Credential: NSObject, NSCoding, Credential { let accessToken: String let tokenType: String var refreshToken: String? var expiration: Date var isExpired: Bool { get { return expiration.compare(Date()) == ComparisonResult.orderedAscending } } var readableDescription: String { get { return "OAuth2Credential - accessToken:\(accessToken) tokenType\(tokenType) refreshToken\(refreshToken) expiration\(expiration)" } } public init(withAccessToken accessToken: String, tokenType: String, refreshToken: String? = nil, expiration: Date = Date.distantFuture) { self.accessToken = accessToken self.tokenType = tokenType self.refreshToken = refreshToken self.expiration = expiration } // MARK: NSCoding public required convenience init?(coder decoder: NSCoder) { guard let accessToken = decoder.decodeObject(forKey: K.OAuth2Credential.kAccessTokenKey) as? String, let tokenType = decoder.decodeObject(forKey: K.OAuth2Credential.kTokenTypeKey) as? String else { return nil } let refreshToken: String? = decoder.decodeObject(forKey: K.OAuth2Credential.kRefreshTokenKey) as? String ?? nil let expiration: Date? = decoder.decodeObject(forKey: K.OAuth2Credential.kExpirationKey) as? Date ?? nil self.init(withAccessToken: accessToken, tokenType: tokenType, refreshToken: refreshToken, expiration: expiration ?? Date.distantFuture) } public func encode(with coder: NSCoder) { coder.encode(accessToken, forKey: K.OAuth2Credential.kAccessTokenKey) coder.encode(tokenType, forKey: K.OAuth2Credential.kTokenTypeKey) if let _refreshToken = refreshToken { coder.encode(_refreshToken, forKey: K.OAuth2Credential.kRefreshTokenKey) } coder.encode(expiration, forKey: K.OAuth2Credential.kExpirationKey) } } // MARK: JSONAbleType extension OAuth2Credential: JSONParsableType { public static func fromJSON(_ json: Any?, refreshToken: String?) throws -> OAuth2Credential { guard let _json = json as? [String: Any] else { throw JSONParsingError.invalidJSON } guard let accessToken = _json[K.OAuth2Credential.kAccessTokenKey] as? String else { throw JSONParsingError.fieldNotFound } guard let tokenType = _json[K.OAuth2Credential.kTokenTypeKey] as? String else { throw JSONParsingError.fieldNotFound } let credential = OAuth2Credential(withAccessToken: accessToken, tokenType: tokenType) credential.refreshToken = _json[K.OAuth2Credential.kRefreshTokenKey] as? String ?? refreshToken if let expiresIn = _json[K.OAuth2Credential.kExpirationKey] as? Double { credential.expiration = Date(timeIntervalSinceNow: expiresIn) } else { credential.expiration = Date.distantFuture } return credential } } // MARK: Class functions extension OAuth2Credential { public class func identifierWithClientId(_ clientId: String, clientSecret: String) -> String { return "\(clientId):\(clientSecret)" } }
mit
3dc10f2867d36c7225f2576f9222dc5e
36.821782
143
0.680105
4.681373
false
false
false
false
roambotics/swift
validation-test/compiler_crashers_2_fixed/issue-53328.swift
2
484
// RUN: %target-swift-frontend -emit-sil %s // https://github.com/apple/swift/issues/53328 @propertyWrapper struct Foo<T> { init(wrappedValue: T) { self.wrappedValue = wrappedValue } var wrappedValue: T } @propertyWrapper struct Bar<T> { init(wrappedValue: T) { self.wrappedValue = wrappedValue } var wrappedValue: T } struct Container { @Foo @Foo var x: Int = 0 @Foo @Foo @Bar @Bar var y: Int = 1 @Foo @Bar @Foo @Foo var z: Int = 2 } _ = Container()
apache-2.0
6bf529ba2a074e254603a05760359d2d
15.689655
46
0.650826
3.122581
false
false
false
false
apple/swift-driver
Tests/IncrementalTestFramework/Expectation.swift
1
1281
//===-- Expectation.swift - Swift Testing ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 XCTest import TSCBasic /// Everything expected from a step. public struct Expectation { let compilations: ExpectedCompilations /// If non-nil, the step produces an executable, and running it should produce this result. let output: ExpectedProcessResult? init(_ compilations: ExpectedCompilations, _ output: ExpectedProcessResult? = nil) { self.compilations = compilations self.output = output } public static func expecting(_ compilations: ExpectedCompilations, _ output: ExpectedProcessResult? = nil ) -> Self { self.init(compilations, output) } public static func expecting(_ compilations: ExpectedCompilations, _ output: String ) -> Self { self.init(compilations, ExpectedProcessResult(output: output)) } }
apache-2.0
9c73f1b7501b5dba766ce9d4e17fd226
33.621622
93
0.669789
4.591398
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/AddNewBankAccount/Components/AddNewBankAccountPresenter.swift
1
11871
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import DIKit import Localization import MoneyKit import PlatformKit import RxCocoa import RxRelay import RxSwift import ToolKit final class AddNewBankAccountPagePresenter: DetailsScreenPresenterAPI, AddNewBankAccountPresentable { // MARK: - Types private typealias AnalyticsEvent = AnalyticsEvents.SimpleBuy private typealias LocalizedString = LocalizationConstants.SimpleBuy.TransferDetails private typealias AccessibilityId = Accessibility.Identifier.SimpleBuy.TransferDetails // MARK: - Navigation Properties let reloadRelay: PublishRelay<Void> = .init() let navigationBarTrailingButtonAction: DetailsScreen.BarButtonAction let navigationBarLeadingButtonAction: DetailsScreen.BarButtonAction = .default let titleViewRelay: BehaviorRelay<Screen.Style.TitleView> = .init(value: .none) var navigationBarAppearance: DetailsScreen.NavigationBarAppearance { .custom( leading: .none, trailing: .close, barStyle: .darkContent(ignoresStatusBar: false, background: .white) ) } // MARK: - Screen Properties private(set) var buttons: [ButtonViewModel] = [] private(set) var cells: [DetailsScreen.CellType] = [] // MARK: - Private Properties private let disposeBag = DisposeBag() private let termsTapRelay = PublishRelay<TitledLink>() private let navigationCloseRelay = PublishRelay<Void>() // MARK: - Injected private let fiatCurrency: FiatCurrency private let isOriginDeposit: Bool private let analyticsRecorder: AnalyticsEventRecorderAPI // MARK: - Setup init( isOriginDeposit: Bool, fiatCurrency: FiatCurrency, analyticsRecorder: AnalyticsEventRecorderAPI = resolve() ) { self.isOriginDeposit = isOriginDeposit self.fiatCurrency = fiatCurrency self.analyticsRecorder = analyticsRecorder navigationBarTrailingButtonAction = .custom { [navigationCloseRelay] in navigationCloseRelay.accept(()) } } func connect(action: Driver<AddNewBankAccountAction>) -> Driver<AddNewBankAccountEffects> { let details = action .flatMap { action -> Driver<AddNewBankAccountDetailsInteractionState> in switch action { case .details(let state): return .just(state) } } details .drive(weak: self) { (self, state) in switch state { case .invalid(.valueCouldNotBeCalculated): self.analyticsRecorder.record( event: AnalyticsEvents.SimpleBuy.sbLinkBankLoadingError( currencyCode: self.fiatCurrency.code ) ) case .value(let account): self.setup(account: account) case .calculating, .invalid(.empty): break } } .disposed(by: disposeBag) let closeTapped = navigationCloseRelay .map { _ in AddNewBankAccountEffects.close } .asDriverCatchError() let termsTapped = termsTapRelay .map(AddNewBankAccountEffects.termsTapped) .asDriverCatchError() return Driver.merge(closeTapped, termsTapped) } func viewDidLoad() { analyticsRecorder.record( event: AnalyticsEvents.SimpleBuy.sbLinkBankScreenShown(currencyCode: fiatCurrency.code) ) } private func setup(account: PaymentAccountDescribing) { let contentReducer = ContentReducer( account: account, isOriginDeposit: isOriginDeposit, analyticsRecorder: analyticsRecorder ) // MARK: Nav Bar titleViewRelay.accept(.text(value: contentReducer.title)) // MARK: Cells Setup contentReducer.lineItems .forEach { cells.append(.lineItem($0)) } cells.append(.separator) for noticeViewModel in contentReducer.noticeViewModels { cells.append(.notice(noticeViewModel)) } if let termsTextViewModel = contentReducer.termsTextViewModel { termsTextViewModel.tap .bindAndCatch(to: termsTapRelay) .disposed(by: disposeBag) cells.append(.interactableTextCell(termsTextViewModel)) } reloadRelay.accept(()) } } // MARK: - Content Reducer extension AddNewBankAccountPagePresenter { final class ContentReducer { let title: String let lineItems: [LineItemCellPresenting] let noticeViewModels: [NoticeViewModel] let termsTextViewModel: InteractableTextViewModel! init( account: PaymentAccountDescribing, isOriginDeposit: Bool, analyticsRecorder: AnalyticsEventRecorderAPI ) { typealias FundsString = LocalizedString.Funds if isOriginDeposit { title = "\(FundsString.Title.depositPrefix) \(account.currency)" } else { title = "\(FundsString.Title.addBankPrefix) \(account.currency) \(FundsString.Title.addBankSuffix) " } lineItems = account.fields.transferDetailsCellsPresenting(analyticsRecorder: analyticsRecorder) let font = UIFont.main(.medium, 12) let processingTimeNoticeDescription: String switch account.currency { case .ARS: processingTimeNoticeDescription = FundsString.Notice.ProcessingTime.Description.ARS termsTextViewModel = InteractableTextViewModel( inputs: [ .text(string: FundsString.Notice.recipientNameARS) ], textStyle: .init(color: .descriptionText, font: font), linkStyle: .init(color: .linkableText, font: font) ) case .BRL: processingTimeNoticeDescription = FundsString.Notice.ProcessingTime.Description.BRL termsTextViewModel = InteractableTextViewModel( inputs: [ .text(string: FundsString.Notice.recipientNameBRL) ], textStyle: .init(color: .descriptionText, font: font), linkStyle: .init(color: .linkableText, font: font) ) case .USD: processingTimeNoticeDescription = FundsString.Notice.ProcessingTime.Description.USD termsTextViewModel = InteractableTextViewModel( inputs: [ .text(string: FundsString.Notice.recipientNameUSD) ], textStyle: .init(color: .descriptionText, font: font), linkStyle: .init(color: .linkableText, font: font) ) case .GBP: processingTimeNoticeDescription = FundsString.Notice.ProcessingTime.Description.GBP termsTextViewModel = InteractableTextViewModel( inputs: [ .text(string: FundsString.Notice.recipientNameGBPPrefix), .url(string: " \(FundsString.Notice.termsAndConditions) ", url: TermsUrlLink.gbp), .text(string: FundsString.Notice.recipientNameGBPSuffix) ], textStyle: .init(color: .descriptionText, font: font), linkStyle: .init(color: .linkableText, font: font) ) case .EUR: processingTimeNoticeDescription = FundsString.Notice.ProcessingTime.Description.EUR termsTextViewModel = InteractableTextViewModel( inputs: [.text(string: FundsString.Notice.recipientNameEUR)], textStyle: .init(color: .descriptionText, font: font), linkStyle: .init(color: .linkableText, font: font) ) default: processingTimeNoticeDescription = "" termsTextViewModel = nil } let amount = MoneyValue.one(currency: account.currency) let instructions = String( format: FundsString.Notice.Instructions.description, amount.displayString, account.currency.displayCode ) noticeViewModels = [ ( title: FundsString.Notice.Instructions.title, description: instructions, image: ImageResource.local(name: "Icon-Info", bundle: .platformUIKit) ), ( title: FundsString.Notice.BankTransferOnly.title, description: FundsString.Notice.BankTransferOnly.description, image: ImageResource.local(name: "icon-bank", bundle: .platformUIKit) ), ( title: FundsString.Notice.ProcessingTime.title, description: processingTimeNoticeDescription, image: ImageResource.local(name: "clock-icon", bundle: .platformUIKit) ) ] .map { NoticeViewModel( imageViewContent: ImageViewContent( imageResource: $0.image, renderingMode: .template(.titleText) ), labelContents: [ LabelContent( text: $0.title, font: .main(.semibold, 12), color: .titleText ), LabelContent( text: $0.description, font: .main(.medium, 12), color: .descriptionText ) ], verticalAlignment: .top ) } } } } extension Array where Element == PaymentAccountProperty.Field { private typealias AccessibilityId = Accessibility.Identifier.SimpleBuy.TransferDetails fileprivate func transferDetailsCellsPresenting(analyticsRecorder: AnalyticsEventRecorderAPI) -> [LineItemCellPresenting] { func isCopyable(field: TransactionalLineItem) -> Bool { switch field { case .paymentAccountField(.accountNumber), .paymentAccountField(.iban), .paymentAccountField(.bankCode), .paymentAccountField(.sortCode): return true case .paymentAccountField(.field(name: _, value: _, help: _, copy: let copy)): return copy default: return false } } func analyticsEvent(field: TransactionalLineItem) -> AnalyticsEvents.SimpleBuy? { switch field { case .paymentAccountField: return .sbLinkBankDetailsCopied default: return nil } } return map { TransactionalLineItem.paymentAccountField($0) } .map { field in if isCopyable(field: field) { return field.defaultCopyablePresenter( analyticsEvent: analyticsEvent(field: field), analyticsRecorder: analyticsRecorder, accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) } else { return field.defaultPresenter(accessibilityIdPrefix: AccessibilityId.lineItemPrefix) } } } }
lgpl-3.0
1b1c944ba490673710b45a83c1277ebc
36.444795
127
0.574895
5.695777
false
false
false
false
admkopec/BetaOS
Kernel/Modules/ACPI/AML/Parser.swift
1
56319
// // Parser.swift // Kernel // // Created by Adam Kopeć on 1/17/18. // Copyright © 2018 Adam Kopeć. All rights reserved. // import Loggable enum AMLError: Error { case invalidSymbol(reason: String) case invalidMethod(reason: String) case invalidData(reason: String) case endOfStream case parseError case unimplementedError(reason: String) static func invalidOpcode(value: UInt8) -> AMLError { let reason = "Bad opcode: \(String(value, radix: 16))" return invalidData(reason: reason) } static func invalidOpcode(value: UInt16) -> AMLError { let reason = "Bad opcode: \(String(value, radix: 16))" return invalidData(reason: reason) } static func unimplemented(_ function: String = #function, line: Int = #line) -> AMLError { kprint("AMLError:", "Line: \(line)", function, "is unimplemented") return unimplementedError(reason: function) } } class AMLParser: Loggable { let Name: String = "AML.Parser" private struct ParsedSymbol { var currentOpcode: AMLOpcode? = nil var currentChar: AMLCharSymbol? = nil } private var byteStream: AMLByteStream! private var currentScope: AMLNameString let acpiGlobalObjects: ACPI.GlobalObjects init(globalObjects: ACPI.GlobalObjects) { currentScope = AMLNameString(String(AMLNameString.RootChar)) acpiGlobalObjects = globalObjects } func parse(amlCode: AMLByteBuffer) throws -> () { byteStream = /*try*/ AMLByteStream(buffer: amlCode) try parse() } private func subParser() /*throws*/ -> AMLParser? { //byteStream.dump() let curPos = byteStream.pos guard let pkgLength = /*try*/ parsePkgLength() else { return nil } let bytesRead = byteStream.pos - curPos let byteCount = Int(pkgLength) - bytesRead guard let stream = /*try*/ byteStream.substream(ofLength: byteCount) else { return nil } let parser = AMLParser(byteStream: stream, scope: currentScope, globalObjects: acpiGlobalObjects) return parser } // Called by subParser private init(byteStream: AMLByteStream, scope: AMLNameString, globalObjects: ACPI.GlobalObjects) { self.byteStream = byteStream self.currentScope = scope self.acpiGlobalObjects = globalObjects } private func parse() throws { byteStream.reset() //FIXME: Fix throwable functions //FIXME: Fix AML Parsing // throw AMLError.parseError _ = /*try*/ parseTermList() } private func resolveNameToCurrentScope(path: AMLNameString) -> AMLNameString { return resolveNameTo(scope: currentScope, path: path) } // Package Length in bytes private func parsePkgLength() /*throws*/ -> UInt? { guard let leadByte = /*try*/ nextByte() else { return nil } let byteCount: UInt8 = (leadByte & 0xC0) >> 6 // bits 6-7 if byteCount == 0 { // 1byte, length is 0-63 let pkgLen = UInt(leadByte & 0x3f) return pkgLen } guard leadByte & 0x30 == 0 else { // throw AMLError.invalidData(reason: "Bits 4,5 in PkgLength are not clear") Log("Bits 4,5 in PkgLength are not clear", level: .Error) return nil } guard byteCount <= 3 else { // throw AMLError.invalidData(reason: "byteCount is wrong \(byteCount)") Log("Byte count is wrong \(byteCount)", level: .Error) return nil } // bits 0-3 are lowest nibble var pkgLength = UInt(leadByte & 0x0f) for x in 0..<byteCount { let shift = (x * 8) + 4 guard let byteData = /*try*/ nextByte() else { return nil } pkgLength |= UInt(byteData) << UInt(shift) } return pkgLength } private func nextByte() /*throws*/ -> UInt8? { if let byte = byteStream.nextByte() { return byte } else { return nil // throw AMLError.endOfStream } } private func nextWord() /*throws*/ -> UInt16? { guard let byte0 = /*try*/ nextByte() else { return nil } guard let byte1 = /*try*/ nextByte() else { return nil } return UInt16(byte0) | UInt16(byte1) << 8 } private func nextDWord() /*throws*/ -> UInt32? { guard let word0 = /*try*/ nextWord() else { return nil } guard let word1 = /*try*/ nextWord() else { return nil } return UInt32(word0) | UInt32(word1) << 16 } private func nextQWord() /*throws*/ -> UInt64? { guard let dword0 = /*try*/ nextDWord() else { return nil } guard let dword1 = /*try*/ nextDWord() else { return nil } return UInt64(dword0) | UInt64(dword1) << 32 } // Updates currentChar and currentOpcode and returns true if there's a symbol or false if end of stream private func nextSymbol() /*throws*/ -> ParsedSymbol? { guard let byte = byteStream.nextByte() else { return nil // End of stream } let currentChar = AMLCharSymbol(byte: byte) // Some bytes (eg 0x00) are both chars and opcodes var currentOpcode: AMLOpcode? = nil // clear it now if let op = AMLOpcode(byte: byte) { if op.isTwoByteOpcode { if let byte2 = byteStream.nextByte() { let value = UInt16(withBytes: byte2, byte) currentOpcode = AMLOpcode(rawValue: value) guard currentOpcode != nil else { // throw AMLError.invalidOpcode(value: value) return nil } } else { // This is an error since opcode is missing 2nd byte // throw AMLError.endOfStream return nil } } else { currentOpcode = op } } if currentChar == nil && currentOpcode == nil { // throw AMLError.invalidOpcode(value: byte) return nil } return ParsedSymbol(currentOpcode: currentOpcode, currentChar: currentChar) } // Parse funcs return, true = matched and ran ok, false = no match, // Throws on error func parseTermList() /*throws*/ -> AMLTermList { var termList: AMLTermList = [] while let symbol = /*try*/ nextSymbol() { // do { guard let termObj = /*try*/ parseTermObj(symbol: symbol) else { Log("Skipping invalid method", level: .Warning); continue } termList.append(termObj) // } catch { // Log("Skipping invalid method: \(error)", level: .Warning) // } } return termList } // Parse objects to a more specific type private func parseObjectList() /*throws*/ -> AMLObjectList { var objectList: [AMLObject] = [] for obj in /*try*/ parseTermList() { guard let amlObj = obj as? AMLObject else { Log("\(obj) is not an AMLObject", level: .Error) fatalError() } objectList.append(amlObj) } return objectList } private func parseFieldList(fieldRef: AMLDefFieldRef) /*throws*/ -> AMLFieldList? { var bitOffset: UInt = 0 var fieldList: AMLFieldList = [] func parseFieldElement() /*throws*/ -> AMLFieldElement? { guard let byte = byteStream.nextByte() else { return nil // end of stream } switch byte { case 0x00: guard let pkgLength = /*try*/ parsePkgLength() else { return nil } bitOffset += pkgLength return AMLReservedField(pkglen: pkgLength) case 0x01: guard let val = nextByte() else { return nil } let type = /*try*/ AMLAccessType(value: val) guard let attrib = /*try*/ nextByte() else { return nil } return AMLAccessField(type: type, attrib: attrib) case 0x02: //ConnectField Log("Unimplemented", level: .Error) return nil // throw AMLError.unimplemented() /* case 0x03: let type = try AMLAccessType(value: nextByte()) guard let attrib = try AMLExtendedAccessAttrib(rawValue: nextByte()) else { let r = "Bad AMLExtendedAccessAttrib byte: \(byte)" throw AMLError.invalidData(reason: r) } let length = try AMLByteConst(nextByte()) return AMLExtendedAccessField(type: type, attrib: attrib, length: length) */ default: if let ch = AMLCharSymbol(byte: byte), ch.CharType == .LeadNameChar { let name = /*try*/ AMLNameString(parseNameSeg(1, startingWith: String(ch.character)) ?? "") guard let bitWidth = /*try*/ parsePkgLength() else { return nil } if name == "" || name == " " { return nil } guard let field = /*try*/ AMLNamedField(name: name, bitOffset: bitOffset, bitWidth: bitWidth, fieldRef: fieldRef) else { return nil } /*try*/ addGlobalObject(name: resolveNameToCurrentScope(path: name), object: field) bitOffset += bitWidth return field } // throw AMLError.invalidData(reason: "Bad byte: \(byte)") Log("Bad byte: \(byte)", level: .Error) return nil } } while let element = /*try*/ parseFieldElement() { fieldList.append(element) // TODO: Add in field access defaults etc } return fieldList } private func parseTermObj(symbol: ParsedSymbol) /*throws*/ -> AMLTermObj? { let x = /*try*/ parseSymbol(symbol: symbol) if let obj = x as? AMLTermObj { return obj } // throw AMLError.invalidSymbol(reason: "\(String(describing: symbol.currentOpcode)) is Invalid for termobj") Log("\(symbol.currentOpcode ?? AMLOpcode.zeroOp) is Invalid for TermObj", level: .Error) return nil } private func parseTermArgList(argCount: Int) /*throws*/ -> AMLTermArgList? { var termArgList: AMLTermArgList = [] while termArgList.count < argCount { guard let arg = parseTermArg() else { return nil } termArgList.append(/*try parseTermArg()*/ arg) } return termArgList } private func parseTermArg() /*throws*/ -> AMLTermArg? { guard let symbol = /*try*/ nextSymbol() else { // throw AMLError.endOfStream return nil } if let ch = symbol.currentChar, ch.CharType != .NullChar { guard let name = /*try*/ parseNameStringWith(character: ch) else { return nil } if /*try*/ determineIfMethodOrName(name: name) { return /*try*/ parseMethodInvocation(name: name) } if determineIfObjectOrName(name: name) { return name } return name } if symbol.currentOpcode != nil { if let arg: AMLTermArg = /*try*/ parseSymbol(symbol: symbol) as? AMLTermArg { return arg } } // let r = "Invalid for termarg: \(String(describing: symbol))" // throw AMLError.invalidSymbol(reason: r) Log("Invalid for termarg: \(symbol)", level: .Error) return nil } private func parseTermArgAsInteger() /*throws*/ -> AMLInteger? { guard let arg = /*try*/ parseTermArg() else { return nil } var context = ACPI.AMLExecutionContext(scope: currentScope, args: [], globalObjects: acpiGlobalObjects) guard let integerData = arg.evaluate(context: &context) as? AMLIntegerData else { // throw AMLError.invalidData(reason: "Cant convert \(type(of: arg)) to integer") return nil } return integerData.value } private func parseSuperName(symbol s: ParsedSymbol? = nil) /*throws*/ -> AMLSuperName? { if let symbol = /*try*/ s ?? nextSymbol() { if let x: AMLSuperName = /*try?*/ parseSimpleName(symbol: symbol) { return x } if let x = /*try*/ parseSymbol(symbol: symbol) as? AMLSuperName { return x } Log("\(symbol)", level: .Verbose) } // throw AMLError.invalidData(reason: "Cant find supername") Log("Can't find supername", level: .Error) return nil } private func parseSymbol(symbol: ParsedSymbol) /*throws*/ -> Any? { // Check for method invocation first if let ch = symbol.currentChar, ch.CharType != .NullChar { guard let name = /*try*/ parseNameStringWith(character: ch) else { return nil } return /*try*/ parseMethodInvocation(name: name) } guard let opcode = symbol.currentOpcode else { // throw(AMLError.invalidSymbol(reason: "No opcode")) return nil } switch opcode { // Type1opcodes case .breakOp: return AMLDefBreak() case .breakPointOp: return AMLDefBreakPoint() case .continueOp: return AMLDefContinue() case .elseOp: return /*try*/ parseDefElse() case .fatalOp: return /*try*/ parseDefFatal() case .ifOp: return /*try*/ parseDefIfElse() case .loadOp: return /*try*/ parseDefLoad() case .noopOp: return AMLDefNoop() case .notifyOp: return /*try*/ parseDefNotify() case .releaseOp: return /*try*/ AMLDefRelease(object: parseSuperName()!) case .resetOp: return /*try*/ AMLDefReset(object: parseSuperName()!) case .returnOp: return /*try*/ AMLDefReturn(object: parseTermArg()) case .signalOp: return /*try*/ AMLDefSignal(object: parseSuperName()!) case .sleepOp: return /*try*/ AMLDefSleep(msecTime: parseTermArg()!) case .stallOp: return /*try*/ AMLDefStall(usecTime: parseTermArg()!) case .unloadOp: return /*try*/ AMLDefUnload(object: parseSuperName()!) case .whileOp: return /*try*/ parseDefWhile() // Type2 opcodes case .acquireOp: return /*try*/ parseDefAcquire() case .addOp: return /*try*/ parseDefAdd() case .andOp: return /*try*/ parseDefAnd() case .bufferOp: return /*try*/ parseDefBuffer() case .concatOp: return /*try*/ parseDefConcat() case .concatResOp: return /*try*/ parseDefConcatRes() case .condRefOfOp: return /*try*/ parseDefCondRefOf() case .copyObjectOp: return /*try*/ parseDefCopyObject() case .decrementOp: return /*try*/ AMLDefDecrement(target: parseSuperName()!) case .derefOfOp: return /*try*/ AMLDefDerefOf(name: parseSuperName()!) case .divideOp: return /*try*/ parseDefDivide() case .findSetLeftBitOp: return /*try*/ parseDefFindSetLeftBit() case .findSetRightBitOp: return /*try*/ parseDefFindSetRightBit() case .fromBCDOp: return /*try*/ parseDefFromBCD() case .incrementOp: return /*try*/ AMLDefIncrement(target: parseSuperName()!) case .indexOp: return /*try*/ parseDefIndex() case .lAndOp: return /*try*/ parseDefLAnd() case .lEqualOp: return /*try*/ parseDefLEqual() case .lGreaterOp: return /*try*/ parseDefLGreater() case .lGreaterEqualOp: return /*try*/ parseDefLGreaterEqual() case .lLessOp: return /*try*/ parseDefLLess() case .lLessEqualOp: return /*try*/ parseDefLLessEqual() case .midOp: return /*try*/ parseDefMid() case .lNotOp: return /*try*/ AMLDefLNot(operand: parseOperand()!) case .lNotEqualOp: return /*try*/ parseDefLNotEqual() case .loadTableOp: return /*try*/ parseDefLoadTable() case .lOrOp: return /*try*/ parseDefLOr() case .matchOp: return /*try*/ parseDefMatch() case .modOp: return /*try*/ parseDefMod() case .multiplyOp: return /*try*/ parseDefMultiply() case .nandOp: return /*try*/ parseDefNAnd() case .norOp: return /*try*/ parseDefNOr() case .notOp: return /*try*/ parseDefNot() case .objectTypeOp: return /*try*/ AMLDefObjectType(object: parseSuperName()!) case .orOp: return /*try*/ parseDefOr() case .packageOp: return /*try*/ parseDefPackage() case .varPackageOp: return /*try*/ parseDefVarPackage() case .refOfOp: return /*try*/ AMLDefRefOf(name: parseSuperName()!) case .shiftLeftOp: return /*try*/ parseDefShiftLeft() case .shiftRightOp: return /*try*/ parseDefShiftRight() case .sizeOfOp: return /*try*/ AMLDefSizeOf(name: parseSuperName()!) case .storeOp: return /*try*/ parseDefStore() case .subtractOp: return /*try*/ parseDefSubtract() case .timerOp: return AMLDefTimer() case .toBCDOp: return /*try*/ parseDefToBCD() case .toBufferOp: return /*try*/ parseDefToBuffer() case .toDecimalStringOp: return /*try*/ parseDefToDecimalString() case .toHexStringOp: return /*try*/ parseDefToHexString() case .toIntegerOp: return /*try*/ parseDefToInteger() case .toStringOp: return /*try*/ parseDefToString() case .waitOp: return /*try*/ parseDefWait() case .xorOp: return /*try*/ parseDefXor() // ComputationalData case .bytePrefix: return /*try*/ AMLByteConst(nextByte()!) case .wordPrefix: return /*try*/ AMLWordConst(nextWord()!) case .dwordPrefix: return /*try*/ AMLDWordConst(nextDWord()!) case .qwordPrefix: return /*try*/ AMLQWordConst(nextQWord()!) case .stringPrefix: return /*try*/ parseString() case .revisionOp: return AMLRevisionOp() // Named objects case .bankFieldOp: return /*try*/ parseDefBankField() case .createBitFieldOp: return /*try*/ parseDefCreateBitField() case .createByteFieldOp: return /*try*/ parseDefCreateByteField() case .createDWordFieldOp: return /*try*/ parseDefCreateDWordField() case .createFieldOp: return /*try*/ parseDefCreateField() case .createQWordFieldOp: return /*try*/ parseDefCreateQWordField() case .createWordFieldOp: return /*try*/ parseDefCreateWordField() case .dataRegionOp: return /*try*/ parseDefDataRegion() case .deviceOp: return /*try*/ parseDefDevice() case .externalOp: return /*try*/ parseDefExternal() case .fieldOp: return /*try*/ parseDefField() case .methodOp: return /*try*/ parseDefMethod() case .indexFieldOp: return /*try*/ parseDefIndexField() case .mutexOp: return /*try*/ parseDefMutex() case .opRegionOp: return /*try*/ parseDefOpRegion() case .powerResOp: return /*try*/ parseDefPowerRes() case .processorOp: return /*try*/ parseDefProcessor() case .thermalZoneOp: return /*try*/ parseDefThermalZone() case .zeroOp: return AMLZeroOp() case .oneOp: return AMLOneOp() case .onesOp: return AMLOnesOp() case .aliasOp: return /*try*/ parseDefAlias() case .nameOp: return /*try*/ parseDefName() case .scopeOp: return /*try*/ parseDefScope() case .eventOp: return AMLEvent(name: /*try*/ parseNameString()!) case .debugOp: return AMLDebugObj() case .local0Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local1Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local2Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local3Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local4Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local5Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local6Op: return /*try*/ AMLLocalObj(localOp: opcode) case .local7Op: return /*try*/ AMLLocalObj(localOp: opcode) case .arg0Op: return /*try*/ AMLArgObj(argOp: opcode) case .arg1Op: return /*try*/ AMLArgObj(argOp: opcode) case .arg2Op: return /*try*/ AMLArgObj(argOp: opcode) case .arg3Op: return /*try*/ AMLArgObj(argOp: opcode) case .arg4Op: return /*try*/ AMLArgObj(argOp: opcode) case .arg5Op: return /*try*/ AMLArgObj(argOp: opcode) case .arg6Op: return /*try*/ AMLArgObj(argOp: opcode) // Should already be consumed by nextSymbol() case .extendedOpPrefix: return nil//throw AMLError.invalidSymbol(reason: "extendedOp") } } private func checkForMethodInvocation(symbol: ParsedSymbol) throws -> AMLMethodInvocation? { if let ch = symbol.currentChar, ch.CharType != .NullChar { guard let name = /*try*/ parseNameStringWith(character: ch) else { return nil } return /*try*/ parseMethodInvocation(name: name) } return nil } private func parseMethodInvocation(name: AMLNameString) /*throws*/ -> AMLMethodInvocation? { // TODO: Somehow validate the method at a later stage guard let (object, _) = acpiGlobalObjects.getGlobalObject(currentScope: currentScope, name: name) else { let r = "No such method \(name.value) in \(currentScope.value)" Log(r, level: .Error) return nil // throw AMLError.invalidMethod(reason: r) } guard let method = object.object as? AMLMethod else { // throw AMLError.invalidMethod(reason: "\(name.value) is not a Method") Log("\(name.value) is not a Method", level: .Error) return nil } var args: AMLTermArgList = [] let flags = method.flags if flags.argCount > 0 { guard let arg = /*try*/ parseTermArgList(argCount: flags.argCount) else { return nil } args = arg guard args.count == flags.argCount else { let r = "Method: \(name.value) has argCount of " + "\(flags.argCount) but only parsed \(args.count) args" //throw AMLError.invalidData(reason: r) Log(r, level: .Error) return nil } } return /*try*/ AMLMethodInvocation(method: name, args: args) } // Needs fix for Integer check (AMLOperand = AMLTermArg // => Integer) private func parseOperand() /*throws*/ -> AMLOperand? { guard let operand: AMLOperand = /*try*/ parseTermArg() else { return nil } return operand } // => Buffer, Package or String or Object private func parseBuffPkgStrObj() /*throws*/ -> AMLBuffPkgStrObj? { guard let arg = /*try*/ parseTermArg() else { return nil } guard let result = arg as? AMLBuffPkgStrObj else { // throw AMLError.invalidData(reason: "\(arg) is not a BuffPkgStrObj") Log("\(arg) is not a BuffPkgStrObj", level: .Error) return nil } return result } private func parseString() /*throws*/ -> AMLString? { var result: String = "" while true { guard let byte = /*try*/ nextByte() else { return nil } if byte == 0x00 { // NullChar break } else if byte >= 0x01 && byte <= 0x7F { result.append(Character(UnicodeScalar(byte))) } else { // throw AMLError.invalidData(reason: "Bad asciichar \(byte)") Log("Bad ASCII Char \(byte)", level: .Error) return nil } } return AMLString(result) } private func parseInteger(symbol: ParsedSymbol) throws -> AMLInteger? { var result: AMLInteger = 0 var radix: AMLInteger = 0 guard let symbol = /*try*/ nextSymbol(), let ch = symbol.currentChar else { // throw AMLError.endOfStream return nil } guard let value = ch.numericValue else { // throw AMLError.invalidData(reason: "Not a digit: '\(ch)'") Log("Not a digit: '\\(ch)'", level: .Error) return nil } if value == 0 { // hex or octal radix = 1 } else { radix = 10 result = AMLInteger(value) } while let symbol = /*try*/ nextSymbol(), let ch = symbol.currentChar { if radix == 1 { if ch.character == Character(UnicodeScalar("x")) || ch.character == Character(UnicodeScalar("X")) { radix = 16 continue } } guard let value = ch.numericValueInclHex else { // throw AMLError.invalidData(reason: "Not a digit: '\(ch)'") Log("Not a digit: '\(ch)'", level: .Error) return nil } if radix == 1 { // check if octal if value > 7 { let r = "Invalid octal digit: '\(ch)'" Log(r, level: .Error) // throw AMLError.invalidData(reason: r) return nil } radix = 8 result = AMLInteger(value) continue } if AMLInteger(value) >= radix { let r = "Invalid digit '\(ch)' for radix: \(radix)" Log(r, level: .Error) // throw AMLError.invalidData(reason: r) return nil } result *= radix result += AMLInteger(value) } return result } private func parsePackageElementList(numElements: UInt8) /*throws*/ -> AMLPackageElementList { func parsePackageElement(_ symbol: ParsedSymbol) /*throws*/ -> AMLPackageElement? { if let ch = symbol.currentChar, ch.CharType != .NullChar { guard let val = parseNameStringWith(character: ch) else { return nil } return /*try*/ AMLString(val.value) } guard symbol.currentOpcode != nil else { //throw AMLError.invalidData(reason: "No opcode or valid string found") Log("No opcode or valid string found", level: .Error) return nil } if let obj = /*try*/ parseSymbol(symbol: symbol) as? AMLDataRefObject { return obj //parseDataRefObject(symbol: symbol) } //throw AMLError.invalidSymbol(reason: "\(symbol) is not an AMLDataRefObject") Log("\(symbol) is not an AMLDataRefObject", level: .Error) return nil } var elements: AMLPackageElementList = [] while let symbol = /*try*/ nextSymbol() { guard let element = /*try*/ parsePackageElement(symbol) else { return elements } elements.append(element) if Int(numElements) == elements.count { break } } return elements } private func determineIfMethodOrName(name: AMLNameString) /*throws*/ -> Bool { if let (obj, _) = acpiGlobalObjects.getGlobalObject(currentScope: currentScope, name: name), let _ = obj.object as? AMLMethod { return true } return false } private func determineIfObjectOrName(name: AMLNameString) -> Bool { let fullName = resolveNameToCurrentScope(path: name) return (acpiGlobalObjects.get(fullName.value) != nil) } func addGlobalObject(name: AMLNameString, object: AMLObject) /*throws*/ { // Object should be AMLNamedObhj or AMLDataRefObject let nameStr = name.value guard let ch = nameStr.first, ch == AMLNameString.RootChar else { Log("\(nameStr) is not an absolute name", level: .Error) // throw AMLError.invalidData(reason: "\(nameStr) is not an absolute name") return } guard acpiGlobalObjects.get(nameStr) != nil else { //throw AMLError.invalidData(reason: "\(nameStr) already exists") acpiGlobalObjects.add(nameStr, object) return // Should validate replacement is same type } acpiGlobalObjects.add(nameStr, object) } private func parseDefPackage() /*throws*/ -> AMLDefPackage? { guard let parser = /*try*/ subParser() else { return nil } guard let numElements = /*try*/ parser.nextByte() else { return nil } let elements = /*try*/ parser.parsePackageElementList(numElements: numElements) return AMLDefPackage(numElements: numElements, elements: elements) } private func parseDefVarPackage() /*throws*/ -> AMLDefVarPackage? { // throw AMLError.unimplemented() return nil } private func parseDefAlias() /*throws*/ -> AMLDefAlias { let alias = /*try*/ AMLDefAlias(sourceObject: parseNameString()!, aliasObject: parseNameString()!) return alias } private func parseDefBuffer() /*throws*/ -> AMLBuffer? { guard let parser = /*try*/ subParser() else { return nil } guard let bufSize = /*try*/ parser.parseTermArg() else { return nil } let bytes = parser.byteStream.bytesToEnd() return AMLBuffer(size: bufSize, value: bytes) } private func parseDefName() /*throws*/ -> AMLDefName? { guard let name = /*try*/ parseNameString() else { return nil } guard let symbol = /*try*/ nextSymbol() else { // throw AMLError.invalidSymbol(reason: "parseDefName") return nil } if let dataObj = /*try*/ parseSymbol(symbol: symbol) as? AMLDataRefObject { let obj = AMLDefName(name: name.shortName, value: dataObj) /*try*/ addGlobalObject(name: resolveNameToCurrentScope(path: name), object: obj) return obj } // throw AMLError.invalidSymbol(reason: "\(symbol) is not an AMLDataRefObject") return nil } private func parseDefScope() /*throws*/ -> AMLDefScope? { guard let parser = /*try*/ subParser() else { return nil } let nameString = /*try*/ parser.parseNameString()! parser.currentScope = resolveNameToCurrentScope(path: nameString) let termList = /*try*/ parser.parseTermList() return AMLDefScope(name: nameString, value: termList) } private func parseDefIndexField() /*throws*/ -> AMLDefIndexField? { guard let parser = /*try*/ subParser() else { return nil } let fieldRef = AMLDefFieldRef() let result = /*try*/ AMLDefIndexField(name: parser.parseNameString()!, dataName: parser.parseNameString()!, flags: AMLFieldFlags(flags: parser.nextByte()!), fields: parser.parseFieldList(fieldRef: fieldRef)!) //fieldRef.amlDefField = result return result } private func parseDefMethod() /*throws*/ -> AMLMethod? { guard let parser = /*try*/ subParser() else { return nil } guard let name = /*try*/ parser.parseNameString() else { return nil } let fullPath = resolveNameToCurrentScope(path: name) parser.currentScope = fullPath let flags = /*try*/ AMLMethodFlags(flags: parser.nextByte()!) let m = AMLMethod(name: name.shortName, flags: flags, parser: parser) /*try*/ addGlobalObject(name: fullPath, object: m) return m } private func parseDefMutex() /*throws*/ -> AMLDefMutex { return /*try*/ AMLDefMutex(name: parseNameString()!, flags: AMLMutexFlags(flags: nextByte()!)!) //let fullPath = resolveNameToCurrentScope(path: mutex.name) //try addGlobalObject(name: fullPath, object: mutex) //return mutex } private func parseDefBankField() /*throws*/ -> AMLDefBankField? { // throw AMLError.unimplemented() return nil } private func parseDefCreateBitField() /*throws*/ -> AMLDefCreateBitField { return /*try*/ AMLDefCreateBitField(sourceBuff: parseTermArg()!, bitIndex: parseTermArgAsInteger()!, name: parseNameString()!) } private func parseDefCreateByteField() /*throws*/ -> AMLDefCreateByteField { return /*try*/ AMLDefCreateByteField(sourceBuff: parseTermArg()!, byteIndex: parseTermArgAsInteger()!, name: parseNameString()!) } private func parseDefCreateWordField() /*throws*/ -> AMLDefCreateWordField { return /*try*/ AMLDefCreateWordField(sourceBuff: parseTermArg()!, byteIndex: parseTermArgAsInteger()!, name: parseNameString()!) } private func parseDefCreateDWordField() /*throws*/ -> AMLDefCreateDWordField { return /*try*/ AMLDefCreateDWordField(sourceBuff: parseTermArg()!, byteIndex: parseTermArgAsInteger()!, name: parseNameString()!) } private func parseDefCreateQWordField() /*throws*/ -> AMLDefCreateQWordField { return /*try*/ AMLDefCreateQWordField(sourceBuff: parseTermArg()!, byteIndex: parseTermArgAsInteger()!, name: parseNameString()!) } private func parseDefCreateField() /*throws*/ -> AMLDefCreateField { return /*try*/ AMLDefCreateField(sourceBuff: parseTermArg()!, bitIndex: parseTermArgAsInteger()!, numBits: parseTermArgAsInteger()!, name: parseNameString()!) } private func parseDefDataRegion() /*throws*/ -> AMLDefDataRegion { let name = /*try*/ parseNameString()!.shortName let arg1 = /*try*/ parseTermArg()! let arg2 = /*try*/ parseTermArg()! let arg3 = /*try*/ parseTermArg()! return AMLDefDataRegion(name: name, arg1: arg1, arg2: arg2, arg3: arg3) } private func parseDefExternal() /*throws*/ -> AMLNamedObj? { guard let name = /*try*/ parseNameString() else { return nil } guard let type = /*try*/ nextByte() else { return nil } guard let argCount = /*try*/ nextByte() else { return nil } return /*try*/ AMLDefExternal(name: name.shortName, type: type, argCount: argCount) } private func parseDefDevice() /*throws*/ -> AMLDefDevice? { guard let parser = /*try*/ subParser() else { return nil } let name = /*try*/ parser.parseNameString()!.shortName let fqn = resolveNameToCurrentScope(path: name) // open a new scope. parser.currentScope = fqn _ = /*try*/ parser.parseObjectList() // No need to store any subobject as they get added to the tree as named objects themselves. let dev = AMLDefDevice(name: name, value: []) /*try*/ addGlobalObject(name: fqn, object: dev) return dev } private func parseDefField() /*throws*/ -> AMLDefField? { guard let parser = /*try*/ subParser() else { return nil } guard let name = /*try*/ parser.parseNameString() else { return nil } let flags = /*try*/ AMLFieldFlags(flags: parser.nextByte()!) let fieldRef = AMLDefFieldRef() guard let fields = /*try*/ parser.parseFieldList(fieldRef: fieldRef) else { return nil } let field = AMLDefField(name: name, flags: flags, fields: fields) fieldRef.amlDefField = field return field } private func parseDefOpRegion() /*throws*/ -> AMLDefOpRegion? { let name = /*try*/ parseNameString()!.shortName guard let byte = /*try*/ nextByte() else { return nil } guard let region = AMLRegionSpace(rawValue: byte) else { // throw AMLError.invalidData(reason: "Bad AMLRegionSpace: \(byte)") return nil } //var context = ACPI.AMLExecutionContext(scope: currentScope, args: [], globalObjects: acpiGlobalObjects) guard let offset = /*try*/ parseTermArg() else { return nil } guard let length = /*try*/ parseTermArg() else { return nil } let opRegion = AMLDefOpRegion(name: name, region: region, offset: offset, length: length) /*try*/ addGlobalObject(name: resolveNameToCurrentScope(path: name), object: opRegion) return opRegion } private func parseDefPowerRes() /*throws*/ -> AMLNamedObj? { // throw AMLError.unimplemented() return nil } private func parseDefProcessor() /*throws*/ -> AMLDefProcessor? { guard let parser = /*try*/ subParser() else { return nil } guard let name = /*try*/ parser.parseNameString() else { return nil } parser.currentScope = resolveNameToCurrentScope(path: name) return /*try*/ AMLDefProcessor(name: name.shortName, procId: parser.nextByte()!, pblkAddr: parser.nextDWord()!, pblkLen: parser.nextByte()!, objects: parser.parseObjectList()) } private func parseDefThermalZone() /*throws*/ -> AMLNamedObj? { return nil // throw AMLError.unimplemented() } private func parseDefElse() /*throws*/ -> AMLDefElse { if byteStream.endOfStream() { return AMLDefElse(value: nil) } guard let parser = /*try*/ subParser() else { return AMLDefElse(value: nil) } if parser.byteStream.endOfStream() { return AMLDefElse(value: nil) } let termList = /*try*/ parser.parseTermList() return AMLDefElse(value: termList) } private func parseDefFatal() /*throws*/ -> AMLDefFatal? { guard let type = /*try*/ nextByte() else { return nil } guard let code = /*try*/ nextDWord() else { return nil } guard let arg = /*try*/ parseTermArg() else { return nil } return AMLDefFatal(type: type, code: code, arg: arg) } private func parseDefIfElse() /*throws*/ -> AMLDefIfElse? { guard let parser = /*try*/ subParser() else { return nil } guard let predicate: AMLPredicate = /*try*/ parser.parseTermArg() else { return nil } let termList = /*try*/ parser.parseTermList() var defElse = AMLDefElse(value: nil) // Look ahead to see if the next opcode is an elseOp otherwise there // is nothing more to process in this IfElse so return an empty else block if !byteStream.endOfStream() { let curPosition = byteStream.pos if let symbol = /*try*/ nextSymbol() { if let op = symbol.currentOpcode, op == .elseOp { guard let _defElse = /*try*/ parseSymbol(symbol: symbol) as? AMLDefElse else { Log("should be DefElse but got \(symbol)", level: .Error) fatalError() } defElse = _defElse } else { byteStream.pos = curPosition } } } return AMLDefIfElse(predicate: predicate, value: termList, defElse: defElse) } private func parseDefLoad() /*throws*/ -> AMLDefLoad? { guard let name = /*try*/ parseNameString() else { return nil } guard let value = /*try*/ parseSuperName() else { return nil } return AMLDefLoad(name: name, value: value) } private func parseDefNotify() /*throws*/ -> AMLDefNotify { return /*try*/ AMLDefNotify(object: parseSuperName()!, value: parseTermArg()!) } private func parseDefWhile() /*throws*/ -> AMLDefWhile? { guard let parser = /*try*/ subParser() else { return nil } guard let p = /*try*/ parser.parseTermArg() else { return nil } let l = /*try*/ parser.parseTermList() let defWhile = AMLDefWhile(predicate: p, list: l) // let defWhile = try AMLDefWhile(predicate: parser.parseTermArg(), // list: parser.parseTermList()) return defWhile } private func parseDefAcquire() /*throws*/ -> AMLDefAcquire { return /*try*/ AMLDefAcquire(mutex: parseSuperName()!, timeout: nextWord()!) } private func parseDefAdd() /*throws*/ -> AMLDefAdd { return /*try*/ AMLDefAdd(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefAnd() /*throws*/ -> AMLDefAnd { return /*try*/ AMLDefAnd(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefConcat() /*throws*/ -> AMLDefConcat { return /*try*/ AMLDefConcat(data1: parseTermArg()!, data2: parseTermArg()!, target: parseTarget()!) } private func parseDefConcatRes() /*throws*/ -> AMLDefConcatRes { return /*try*/ AMLDefConcatRes(data1: parseTermArg()!, data2: parseTermArg()!, target: parseTarget()!) } private func parseDefCondRefOf() /*throws*/ -> AMLDefCondRefOf { return /*try*/ AMLDefCondRefOf(name: parseSuperName()!, target: parseTarget()!) } private func parseDefDerefOf() /*throws*/ -> AMLDefCondRefOf { return /*try*/ AMLDefCondRefOf(name: parseSuperName()!, target: parseTarget()!) } private func parseDefCopyObject() /*throws*/ -> AMLDefCopyObject? { guard let arg = /*try*/ parseTermArg() else { return nil } guard let name = /*try*/ parseSimpleName(symbol: nextSymbol()) else { return nil } return AMLDefCopyObject(object: arg, target: name) } private func parseDefDivide() /*throws*/ -> AMLDefDivide { return /*try*/ AMLDefDivide(dividend: parseTermArg()!, divisor: parseTermArg()!, remainder: parseTarget()!, quotient: parseTarget()!) } private func parseDefFindSetLeftBit() /*throws*/ -> AMLDefFindSetLeftBit { return /*try*/ AMLDefFindSetLeftBit(operand: parseOperand()!, target: parseTarget()!) } private func parseDefFindSetRightBit() /*throws*/ -> AMLDefFindSetRightBit { return /*try*/ AMLDefFindSetRightBit(operand: parseOperand()!, target: parseTarget()!) } private func parseDefFromBCD() /*throws*/ -> AMLDefFromBCD { return /*try*/ AMLDefFromBCD(value: parseOperand()!, target: parseTarget()!) } private func parseDefIndex() /*throws*/ -> AMLDefIndex? { guard let b = /*try*/ parseBuffPkgStrObj() else { return nil } Log("\(b)", level: .Verbose) guard let i = /*try*/ parseTermArg() else { return nil } Log("\(i)", level: .Verbose) guard let r = /*try*/ parseTarget() else { return nil } return AMLDefIndex(object:b, index: i, target: r) //return try AMLDefIndex(object: parseBuffPkgStrObj(), index: parseTermArg(), target: parseTarget()) } private func parseDefLAnd() /*throws*/ -> AMLDefLAnd { return /*try*/ AMLDefLAnd(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefLEqual() /*throws*/ -> AMLDefLEqual { return /*try*/ AMLDefLEqual(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefLGreater() /*throws*/ -> AMLDefLGreater { return /*try*/ AMLDefLGreater(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefLGreaterEqual() /*throws*/ -> AMLDefLGreaterEqual { return /*try*/ AMLDefLGreaterEqual(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefLLess() /*throws*/ -> AMLDefLLess { return /*try*/ AMLDefLLess(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefLLessEqual() /*throws*/ -> AMLDefLLessEqual { return /*try*/ AMLDefLLessEqual(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefMid() /*throws*/ -> AMLDefMid { return /*try*/ AMLDefMid(obj: parseTermArg()!, arg1: parseTermArg()!, arg2: parseTermArg()!, target: parseTarget()!) } private func parseDefLNotEqual() /*throws*/ -> AMLDefLNotEqual { return /*try*/ AMLDefLNotEqual(operand1: parseTermArg()!, operand2: parseTermArg()!) } private func parseDefLoadTable() /*throws*/ -> AMLDefLoadTable? { return nil // throw AMLError.unimplemented() } private func parseDefLOr() /*throws*/ -> AMLDefLOr { return /*try*/ AMLDefLOr(operand1: parseOperand()!, operand2: parseOperand()!) } private func parseDefMatch() /*throws*/ -> AMLDefMatch? { // throw AMLError.unimplemented() return nil } private func parseDefMod() /*throws*/ -> AMLDefMod? { // throw AMLError.unimplemented() return nil } private func parseDefMultiply() /*throws*/ -> AMLDefMultiply { return /*try*/ AMLDefMultiply(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefNAnd() /*throws*/ -> AMLDefNAnd { return /*try*/ AMLDefNAnd(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefNOr() /*throws*/ -> AMLDefNOr { return /*try*/ AMLDefNOr(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefNot() /*throws*/ -> AMLDefNot { return /*try*/ AMLDefNot(operand: parseOperand()!, target: parseTarget()!) } private func parseDefOr() /*throws*/ -> AMLDefOr { return /*try*/ AMLDefOr(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefShiftLeft() /*throws*/ -> AMLDefShiftLeft { return /*try*/ AMLDefShiftLeft(operand: parseOperand()!, count: parseOperand()!, target: parseTarget()!) } private func parseDefShiftRight() /*throws*/ -> AMLDefShiftRight { return /*try*/ AMLDefShiftRight(operand: parseOperand()!, count: parseOperand()!, target: parseTarget()!) } private func parseDefStore() /*throws*/ -> AMLDefStore { return /*try*/ AMLDefStore(arg: parseTermArg()!, name: parseSuperName()!) } private func parseDefSubtract() /*throws*/ -> AMLDefSubtract { return /*try*/ AMLDefSubtract(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseDefToBCD() /*throws*/ -> AMLDefToBCD { return /*try*/ AMLDefToBCD(operand: parseOperand()!, target: parseTarget()!) } private func parseDefToBuffer() /*throws*/ -> AMLDefToBuffer { return /*try*/ AMLDefToBuffer(operand: parseOperand()!, target: parseTarget()!) } private func parseDefToDecimalString() /*throws*/ -> AMLDefToDecimalString { return /*try*/ AMLDefToDecimalString(operand: parseOperand()!, target: parseTarget()!) } private func parseDefToHexString() /*throws*/ -> AMLDefToHexString { return /*try*/ AMLDefToHexString(operand: parseOperand()!, target: parseTarget()!) } private func parseDefToInteger() /*throws*/ -> AMLDefToInteger { return /*try*/ AMLDefToInteger(operand: parseOperand()!, target: parseTarget()!) } private func parseDefToString() /*throws*/ -> AMLDefToString { return /*try*/ AMLDefToString(arg: parseTermArg()!, length: parseTermArg()!, target: parseTarget()!) } private func parseDefWait() /*throws*/ -> AMLDefWait? { guard let object = /*try*/ parseSuperName() else { return nil } guard let operand = /*try*/ parseOperand() else { return nil } return AMLDefWait(object: object, operand: operand) } private func parseDefXor() /*throws*/ -> AMLDefXor { return /*try*/ AMLDefXor(operand1: parseOperand()!, operand2: parseOperand()!, target: parseTarget()!) } private func parseTarget() /*throws*/ -> AMLTarget? { guard let symbol = /*try*/ nextSymbol() else { // throw AMLError.endOfStream return nil } if symbol.currentChar?.CharType == .NullChar { return AMLNullName() } if let name = /*try?*/ parseSuperName(symbol: symbol) { return name } // HACK, should not be needed, should be covered with .nullChar above Log("\(symbol)", level: .Verbose) if symbol.currentChar!.value == 0 { return AMLNullName() } // throw AMLError.invalidSymbol(reason: "nextSymbol returned true but symbol: \(symbol)") Log("Next Symbol returned true but symbol is: \(symbol)", level: .Error) return nil } // Lead byte could be opcode or char private func parseSimpleName(symbol: ParsedSymbol?) /*throws*/ -> AMLSimpleName? { guard let s = symbol else { // throw AMLError.endOfStream return nil } if s.currentChar != nil { return /*try*/ parseNameStringWith(character: s.currentChar!) } if let obj = /*try*/ parseSymbol(symbol: s) as? AMLSimpleName { return obj } return nil // throw AMLError.invalidSymbol(reason: "shouldnt get here") } private func nextChar() /*throws*/ -> AMLCharSymbol? { if let ch = /*try*/ nextCharOrEOS() { return ch } else { return nil // throw AMLError.endOfStream // End Of stream } } private func nextCharOrEOS() /*throws*/ -> AMLCharSymbol? { guard let symbol = /*try*/ nextSymbol() else { return nil // End of Stream } guard let char = symbol.currentChar else { // let r = "next char is an opcode \(String(describing: symbol.currentOpcode))" // throw AMLError.invalidSymbol(reason: r) Log("Next char is an opcode \(symbol.currentOpcode ?? AMLOpcode.zeroOp)", level: .Error) return nil } return char } private func parseNameString() /*throws*/ -> AMLNameString? { guard let ch = nextChar() else { return nil } return /*try*/ parseNameStringWith(character: ch) } // NameString := <RootChar NamePath> | <PrefixPath NamePath> private func parseNameStringWith(character: AMLCharSymbol) /*throws*/ -> AMLNameString? { var result = "" var ch = character switch ch.CharType { case .RootChar: result = String(ch.character) guard let c = /*try*/ nextChar() else { return nil } ch = c case .ParentPrefixChar: var c: AMLCharSymbol? = ch while c != nil { result.append(c!.character) guard let cc = /*try*/ nextChar() else { return nil } ch = cc c = (ch.CharType == .ParentPrefixChar) ? ch : nil } default: break } // result is now RootChar | PrefixChar 0+ result += /*try*/ parseNamePath(ch: ch) ?? "" return AMLNameString(result) } // Namepath might start with a char or a prefix private func parseNamePath(ch: AMLCharSymbol) /*throws*/ -> String? { switch ch.CharType { case .LeadNameChar: return /*try*/ parseNameSeg(1, startingWith: String(ch.character)) case .DualNamePrefix: return /*try*/ parseNameSeg(2) case .MultiNamePrefix: guard let segCount = /*try*/ nextByte() else { return nil } guard segCount != 0 else { //throw AMLError.invalidData(reason: "segCount cannot be 0") return nil } return /*try*/ parseNameSeg(segCount) case .NullChar: return "" // fixme should be nullname //return AMLNullName default: let r = "Bad char \(ch)" // throw AMLError.invalidData(reason: r) Log(r, level: .Error) return nil } } private func parseNameSeg(startingWith: String = "") /*throws*/ -> String? { var name = startingWith if let ch = /*try*/ nextCharOrEOS() { if name == "" { guard ch.CharType == .LeadNameChar else { // let r = "Expected .leadNameChar but char was \(ch)" // throw AMLError.invalidSymbol(reason: r) return nil } } name.append(ch.character) let nameLen = name.count for _ in nameLen...3 { if let currentChar = /*try*/ nextCharOrEOS() { guard let ch = /*try*/ parseNameChar(ch: currentChar) else { return nil } name.append(ch.character) } } // Strip trailing '_' padding characters while let e = name.last, e == "_" { name.remove(at: name.index(before: name.endIndex)) } } return name } private func parseNameSeg(_ count: UInt8, startingWith: String = "") /*throws*/ -> String? { let pathSeperator = "." guard count > 0 else { // throw AMLError.invalidData(reason: "Name paths has 0 segments") return nil } var name = /*try*/ parseNameSeg(startingWith: startingWith) ?? "" for _ in 1..<count { name += pathSeperator name += /*try*/ parseNameSeg() ?? "" } return name } private func parseNameChar(ch: AMLCharSymbol) /*throws*/ -> AMLCharSymbol? { if ch.CharType == .DigitChar || ch.CharType == .LeadNameChar { return ch } // let r = "bad name char: \(String(describing: ch))" // throw AMLError.invalidData(reason: r) Log("Bad name char: \(ch)", level: .Error) return nil } } struct AMLByteStream { private let buffer: AMLByteBuffer fileprivate var pos = 0 private var bytesRemaining: Int { return buffer.count - pos } init?(buffer: AMLByteBuffer) /*throws*/ { guard buffer.count > 0 else { return nil // throw AMLError.endOfStream } self.buffer = buffer } mutating func reset() { pos = 0 } func endOfStream() -> Bool { return pos == buffer.endIndex } mutating func nextByte() -> UInt8? { guard pos < buffer.endIndex else { return nil } let byte = buffer[pos] pos += 1 return byte } mutating func bytesToEnd() -> AMLByteList { let bytes: AMLByteList = Array(buffer.suffix(bytesRemaining)) pos = buffer.endIndex return bytes } mutating func substream(ofLength length: Int) /*throws*/ -> AMLByteStream? { guard length > 0 else { return nil // throw AMLError.invalidData(reason: "Length < 1") } guard length <= bytesRemaining else { return nil // throw AMLError.parseError } let substream = AMLByteBuffer(rebasing: buffer[pos...pos + length - 1]) pos += length return /*try*/ AMLByteStream(buffer: substream) } }
apache-2.0
8e6c89301dba5802e223eb626c28117d
41.695982
216
0.576124
4.452914
false
false
false
false
Authman2/Pix
Pods/Hero/Sources/HeroDefaultAnimator.swift
1
3881
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class HeroDefaultAnimator: HeroAnimator { weak public var context: HeroContext! var viewContexts: [UIView: HeroDefaultAnimatorViewContext] = [:] public func seekTo(timePassed: TimeInterval) { for viewContext in viewContexts.values { viewContext.seek(timePassed: timePassed) } } public func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval { var duration: TimeInterval = 0 for (_, context) in viewContexts { context.resume(timePassed: timePassed, reverse: reverse) duration = max(duration, context.duration) } return duration } public func apply(state: HeroTargetState, to view: UIView) { if let context = viewContexts[view] { context.apply(state:state) } } public func canAnimate(view: UIView, appearing: Bool) -> Bool { guard let state = context[view] else { return false } return state.position != nil || state.size != nil || state.transform != nil || state.cornerRadius != nil || state.opacity != nil || state.overlay != nil || state.borderColor != nil || state.borderWidth != nil || state.shadowOpacity != nil || state.shadowRadius != nil || state.shadowOffset != nil || state.shadowColor != nil || state.shadowPath != nil } public func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval { var duration: TimeInterval = 0 // animate for v in fromViews { animate(view: v, appearing: false) } for v in toViews { animate(view: v, appearing: true) } // infinite duration means matching the duration of the longest animation var infiniteDurationViewContexts = [HeroDefaultAnimatorViewContext]() for viewContext in viewContexts.values { if viewContext.duration == .infinity { infiniteDurationViewContexts.append(viewContext) } else { duration = max(duration, viewContext.duration) } } for viewContexts in infiniteDurationViewContexts { duration = max(duration, viewContexts.optimizedDurationAndTimingFunction().duration) } for viewContexts in infiniteDurationViewContexts { viewContexts.apply(state: [.duration(duration)]) } return duration } func animate(view: UIView, appearing: Bool) { let snapshot = context.snapshotView(for: view) let viewContext = HeroDefaultAnimatorViewContext(animator:self, snapshot: snapshot, targetState: context[view]!, appearing: appearing) viewContexts[view] = viewContext } public func clean() { for vc in viewContexts.values { vc.clean() } viewContexts.removeAll() } }
gpl-3.0
58f52dfb02ddd82e4ede9d30f6d6fdd2
35.271028
138
0.68874
4.592899
false
false
false
false
griotspeak/Rational
Carthage/Checkouts/SwiftCheck/Tests/LambdaSpec.swift
1
4390
// // LambdaSpec.swift // SwiftCheck // // Created by Robert Widmann on 1/6/16. // Copyright © 2016 Robert Widmann. All rights reserved. // import SwiftCheck import XCTest struct Name : Arbitrary, Equatable, Hashable, CustomStringConvertible { let unName : String static var arbitrary : Gen<Name> { let gc : Gen<Character> = Gen<Character>.fromElementsIn("a"..."z") return gc.map { Name(unName: String($0)) } } var description : String { return self.unName } var hashValue : Int { return self.unName.hashValue } } func == (l : Name, r : Name) -> Bool { return l.unName == r.unName } private func liftM2<A, B, C>(f : (A, B) -> C, _ m1 : Gen<A>, _ m2 : Gen<B>) -> Gen<C> { return m1.flatMap { x1 in return m2.flatMap { x2 in return Gen.pure(f(x1, x2)) } } } indirect enum Exp : Equatable { case Lam(Name, Exp) case App(Exp, Exp) case Var(Name) } func == (l : Exp, r : Exp) -> Bool { switch (l, r) { case let (.Lam(ln, le), .Lam(rn, re)): return ln == rn && le == re case let (.App(ln, le), .App(rn, re)): return ln == rn && le == re case let (.Var(n1), .Var(n2)): return n1 == n2 default: return false } } extension Exp : Arbitrary { private static func arbExpr(n : Int) -> Gen<Exp> { return Gen<Exp>.frequency([ (2, liftM(Exp.Var, Name.arbitrary)), ] + ((n <= 0) ? [] : [ (5, liftM2(Exp.Lam, Name.arbitrary, arbExpr(n.predecessor()))), (5, liftM2(Exp.App, arbExpr(n/2), arbExpr(n/2))), ])) } static var arbitrary : Gen<Exp> { return Gen<Exp>.sized(self.arbExpr) } static func shrink(e : Exp) -> [Exp] { switch e { case .Var(_): return [] case let .Lam(x, a): return [a] + Exp.shrink(a).map { .Lam(x, $0) } case let .App(a, b): let part1 : [Exp] = [a, b] + [a].flatMap({ (expr : Exp) -> Exp? in if case let .Lam(x, a) = expr { return a.subst(x, b) } return nil }) let part2 : [Exp] = Exp.shrink(a).map { App($0, b) } + Exp.shrink(b).map { App(a, $0) } return part1 + part2 } } var free : Set<Name> { switch self { case let .Var(x): return Set([x]) case let .Lam(x, a): return a.free.subtract([x]) case let .App(a, b): return a.free.union(b.free) } } func rename(x : Name, _ y : Name) -> Exp { if x == y { return self } return self.subst(x, .Var(y)) } func subst(x : Name, _ c : Exp) -> Exp { switch self { case let .Var(y) where x == y : return c case let .Lam(y, a) where x != y: return .Lam(y, a.subst(x, c)) case let .App(a, b): return .App(a.subst(x, c), b.subst(x, c)) default: return self } } var eval : Exp { switch self { case .Var(_): fatalError("Cannot evaluate free variable!") case let .App(a, b): switch a.eval { case let .Lam(x, aPrime): return aPrime.subst(x, b) default: return .App(a.eval, b.eval) } default: return self } } } extension Exp : CustomStringConvertible { var description : String { switch self { case let .Var(x): return "$" + x.description case let .Lam(x, t): return "(λ $\(x.description).\(t.description))" case let .App(a, b): return "(\(a.description) \(b.description))" } } } extension Name { func fresh(ys : Set<Name>) -> Name { let zz = "abcdefghijklmnopqrstuvwxyz".unicodeScalars.map { Name(unName: String($0)) } return Set(zz).subtract(ys).first ?? self } } private func showResult<A>(x : A, f : A -> Testable) -> Property { return f(x).whenFail { print("Result: \(x)") } } class LambdaSpec : XCTestCase { func testAll() { let tiny = CheckerArguments(maxTestCaseSize: 10) property("Free variable capture occurs", arguments: tiny) <- forAll { (a : Exp, x : Name, b : Exp) in return showResult(a.subst(x, b)) { subst_x_b_a in return a.free.contains(x) ==> subst_x_b_a.free == a.free.subtract([x]).union(b.free) } }.expectFailure property("Substitution of a free variable into a fresh expr is idempotent", arguments: tiny) <- forAll { (a : Exp, x : Name, b : Exp) in return showResult(a.subst(x, b)) { subst_x_b_a in return !a.free.contains(x) ==> subst_x_b_a == a } } property("Substitution of a free variable into a fresh expr is idempotent", arguments: tiny) <- forAll { (a : Exp, x : Name, b : Exp) in return showResult(a.subst(x, b)) { subst_x_b_a in return !a.free.contains(x) ==> subst_x_b_a.free == a.free } } } }
mit
12055b00550ff49a3adcabe8ca878651
21.854167
138
0.591386
2.618138
false
false
false
false
brockboland/Vokoder
SwiftSampleProject/SwiftyVokoder/Models/Station.swift
3
2651
// // Station.swift // SwiftyVokoder // // Created by Carl Hill-Popper on 11/13/15. // Copyright © 2015 Vokal. // import Foundation import CoreData import CoreLocation import Vokoder //lets pretend we're using mogenerator to create attribute constants enum StationAttributes: String { case name case longitude case locationString case latitude case identifier case descriptiveName case accessible } @objc(Station) class Station: NSManagedObject { lazy fileprivate(set) var coordinate: CLLocationCoordinate2D = { CLLocationCoordinate2D(latitude: Double(self.latitude ?? 0), longitude: Double(self.longitude ?? 0)) }() } extension Station: VOKMappableModel { static func coreDataMaps() -> [VOKManagedObjectMap] { return [ VOKManagedObjectMap(foreignKeyPath: "MAP_ID", coreDataKeyEnum: StationAttributes.identifier), VOKManagedObjectMap(foreignKeyPath: "STATION_NAME", coreDataKeyEnum: StationAttributes.name), VOKManagedObjectMap(foreignKeyPath: "STATION_DESCRIPTIVE_NAME", coreDataKeyEnum: StationAttributes.descriptiveName), VOKManagedObjectMap(foreignKeyPath: "ADA", coreDataKeyEnum: StationAttributes.accessible), VOKManagedObjectMap(foreignKeyPath: "Location", coreDataKeyEnum: StationAttributes.locationString), ] } static func uniqueKey() -> String? { return StationAttributes.identifier.rawValue } static func importCompletionBlock() -> VOKPostImportBlock { //we aren't using the first param so use the underscore symbol //explicit typing for clarity return { (_, inputObject: NSManagedObject) in guard let station = inputObject as? Station, let locationString = station.locationString else { return } //example locationString: "(41.875478, -87.688436)" //convert parentheses to curly braces to be usable by CGPointFromString var pointString = locationString.replacingOccurrences(of: "(", with: "{") pointString = pointString.replacingOccurrences(of: ")", with: "}") let point = CGPointFromString(pointString) station.latitude = point.x as NSNumber? station.longitude = point.y as NSNumber? } } } //MARK: VokoderTypedManagedObject //the empty protocol implementation is used to mixin the functionality of VokoderTypedManagedObject extension Station: VokoderTypedManagedObject { }
mit
b0db34d39369c6bd0789d0b956b07bdf
33.868421
99
0.660755
4.907407
false
false
false
false
ypopovych/ExpressCommandLine
Sources/swift-express/Core/Process+Task.swift
1
3797
//===--- Process+Task.swift -------------------------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===------------------------------------------------------------------------===// import Foundation #if !os(Linux) import SwiftTryCatch #endif extension Process { convenience public init(task: String, arguments: [String]? = nil, workingDirectory: URL? = nil, environment:[String:String]? = nil, useAppOutput: Bool = false, finishCallback: ((Process, Int32) -> Void)? = nil) { self.init() self.launchPath = task if let arguments = arguments { self.arguments = arguments } if let env = environment { self.environment = env } if let dir = workingDirectory { self.currentDirectoryPath = dir.path } if let finishCb = finishCallback { self.terminationHandler = { p in finishCb(p, p.terminationStatus) } } self.standardInput = Pipe() if useAppOutput { self.standardOutput = FileHandle.standardOutput self.standardError = FileHandle.standardError } else { self.standardOutput = Pipe() self.standardError = Pipe() } } func run() throws { #if !os(Linux) var error: NSException? = nil SwiftTryCatch.try({ self.launch() }, catch: { exc in error = exc }, finallyBlock: {}) if let error = error { throw SwiftExpressError.subtaskError(message: "\(error.name): \(error.reason ?? ""), \(error.userInfo ?? [:])") } #else let path = FileManager.default.currentDirectoryPath let _ = FileManager.default.changeCurrentDirectoryPath(self.currentDirectoryPath) launch() let _ = FileManager.default.changeCurrentDirectoryPath(path) #endif } func runAndWait() throws -> Int32 { try run() waitUntilExit() return terminationStatus } func write(_ string: String) { if let data = string.data(using: .utf8) { write(data: data) } } func write(data: Data) { if let input = standardInput as? Pipe { input.fileHandleForWriting.write(data) } } func read() -> Data? { if let output = standardOutput as? Pipe { return output.fileHandleForReading.readDataToEndOfFile() } return nil } func readString() -> String? { return read().flatMap{String(data: $0, encoding: .utf8)} } func readError() -> Data? { if let error = standardError as? Pipe { return error.fileHandleForReading.readDataToEndOfFile() } return nil } func readErrorString() -> String? { return readError().flatMap{String(data: $0, encoding: .utf8)} } }
gpl-3.0
6bf18eac8c270e557e77f02ae00ef7cb
31.732759
216
0.567553
4.937581
false
false
false
false
ChinaPicture/ZXYRefresh
RefreshDemo/Refresh/RefreshHeaderContainerView.swift
1
4035
// // RefreshHeaderContainerView.swift // RefreshDemo // // Created by developer on 15/03/2017. // Copyright © 2017 developer. All rights reserved. // import UIKit class RefreshHeaderContainerView: RefreshBaseContainerView , RefreshHeaderStatusChangeDelegate { private var header: RefreshBaseHeaderView? func getHeader() -> RefreshBaseHeaderView? { return self.header } func headerRefreshViewStatusChange(_ status: RefreshStatus) { self.stateChangeNow(status) } override func contentSizeChange(newSize: CGSize?) { super.contentSizeChange(newSize: newSize) } func setHeaderView(header: RefreshBaseHeaderView?) { self.header?.removeFromSuperview() guard self.scroll != nil else { self.header?.delegate = nil ; self.header = nil ; return } if let h = header { self.header = h ; self.header!.delegate = self self.header!.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width , height: h.activeOff) self.header?.autoresizingMask = [.flexibleBottomMargin, .flexibleHeight, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleWidth] self.activeHeight = self.header!.activeOff self.addSubview(self.header!) self.header!.prepareRefreshViewLayout() } } override func contentOffsetChanged(newOff: CGPoint?) { super.contentOffsetChanged(newOff: newOff) if self.state == .load { return } guard let off = newOff , self.state != .load , self.state != .noMore else { return } self.header?.refreshViewOffset(scroll: self.scroll!, offset: off) let ratio = self.scroll!.ratioOfHeader(self.activeHeight) if ratio > 0 && off.y <= 0 && (self.state == .initial || self.state == .load || self.state == .willActive) { // only .initial or .load state can deliver the ratio value let ratioToDeliver = ratio > 0 ? (ratio <= 1 ? ratio : 1) : 0 self.header?.refreshRatioChange(scroll: self.scroll!, ratio: ratioToDeliver) } if self.scroll!.isDragging && ratio < 1 && (self.state == .initial || self.state == .willActive) { self.stateChangeNow(.initial) } else if self.state == .initial && self.scroll!.isDragging && ratio >= 1 { self.stateChangeNow(.willActive) } else if self.state == .willActive && !self.scroll!.isDragging { self.stateChangeNow(.load) } } override func stateChangeNow(_ state: RefreshStatus) { guard let scroll = self.scroll ,self.state != state else { return } self.state = state var insetOfScroll: UIEdgeInsets? self.header?.refreshViewStateChanged(scroll: scroll, currentState: self.state) if self.state == .load { insetOfScroll = scroll.contentInset ; insetOfScroll?.top = self.activeHeight } else if self.state == .finish { insetOfScroll = scroll.contentInset ; insetOfScroll?.top = 0 } if let inset = insetOfScroll { self.contentInsetChanged(contentInset: inset) } } override func contentInsetChanged(contentInset: UIEdgeInsets){ guard let scroll = self.scroll else { print("Error : Current scroll is nil or other type view") ; return } UIView.animate(withDuration: 0.3, delay: 0, options: [.allowUserInteraction,.beginFromCurrentState], animations: { if self.state == .load { scroll.setContentOffset(CGPoint.init(x: 0, y: -self.activeHeight), animated: false) } self.scroll!.contentInset = contentInset }, completion: { (Bool) in if self.state == .finish { self.stateChangeNow(.initial) } }) } override func removeFromSuperview() { super.removeFromSuperview() if self.state == .load && self.scroll != nil { var insetOfScroll: UIEdgeInsets = self.scroll!.contentInset insetOfScroll.top = 0 self.scroll!.contentInset = insetOfScroll } } }
apache-2.0
1f295290e05f38961956970453f40024
47.60241
176
0.644522
4.389554
false
false
false
false
abreis/swift-gissumo
scripts/parsers/singles/averageColumn.swift
1
4213
/* This script takes a list of statistical data files containing tab-separated values, * where the first column is a time entry. It then gathers the data in the column * specified in the second argument and returns an average value. * * If a time value is provided as the second argument, only samples that * occur after that time are recorded. */ import Foundation /*** MEASUREMENT SWIFT3 ***/ // A measurement object: load data into 'samples' and all metrics are obtained as computed properties struct Measurement { var samples = [Double]() mutating func add(point: Double) { samples.append(point) } var count: Double { return Double(samples.count) } var sum: Double { return samples.reduce(0,+) } var mean: Double { return sum/count } var min: Double { return samples.min()! } var max: Double { return samples.max()! } // This returns the maximum likelihood estimator(over N), not the minimum variance unbiased estimator (over N-1) var variance: Double { return samples.reduce(0,{$0 + pow($1-mean,2)} )/count } var stdev: Double { return sqrt(variance) } // Specify the desired confidence level (1-significance) before requesting the intervals // func confidenceIntervals(confidence: Double) -> Double {} //var confidence: Double = 0.90 //var confidenceInterval: Double { return 0.0 } } /*** ***/ guard 3...4 ~= CommandLine.arguments.count else { print("usage: \(CommandLine.arguments[0]) [list of data files] [column name or number] [minimum time]") exit(EXIT_FAILURE) } var columnNumber: Int? = nil var cliColName: String? = nil if let cliColNum = UInt(CommandLine.arguments[2]) { columnNumber = Int(cliColNum)-1 } else { cliColName = CommandLine.arguments[2] } // Load minimum sample time var minTime: Double = 0.0 if CommandLine.arguments.count == 4 { guard let inMinTime = Double(CommandLine.arguments[3]) else { print("Error: Invalid minimum time specified.") exit(EXIT_FAILURE) } minTime = inMinTime } var statFiles: String do { let statFilesURL = NSURL.fileURL(withPath: CommandLine.arguments[1]) _ = try statFilesURL.checkResourceIsReachable() statFiles = try String(contentsOf: statFilesURL, encoding: String.Encoding.utf8) } catch { print(error) exit(EXIT_FAILURE) } // Process statistics files var dataMeasurement = Measurement() for statFile in statFiles.components(separatedBy: .newlines).filter({!$0.isEmpty}) { // 1. Open and read the statFile into a string var statFileData: String do { let statFileURL = NSURL.fileURL(withPath: statFile) _ = try statFileURL.checkResourceIsReachable() statFileData = try String(contentsOf: statFileURL, encoding: String.Encoding.utf8) } catch { print(error) exit(EXIT_FAILURE) } // 2. Break the stat file into lines var statFileLines: [String] = statFileData.components(separatedBy: .newlines).filter({!$0.isEmpty}) // [AUX] For the very first file, if a column name was specified instead of a column number, find the column number by name. if columnNumber == nil { let header = statFileLines.first! let colNames = header.components(separatedBy: "\t").filter({!$0.isEmpty}) guard let colIndex = colNames.index(where: {$0 == cliColName}) else { print("ERROR: Can't match column name to a column number.") exit(EXIT_FAILURE) } columnNumber = colIndex } // 3. Drop the first line (header) statFileLines.removeFirst() // 4. Run through the statFile lines for statFileLine in statFileLines { // Split each line by tabs let statFileLineColumns = statFileLine.components(separatedBy: "\t").filter({!$0.isEmpty}) // First column is time index for the dictionary // 'columnNumber' column is the data we want guard let timeEntry = Double(statFileLineColumns[0]), let dataEntry = Double(statFileLineColumns[columnNumber!]) else { print("ERROR: Can't interpret time and/or data.") exit(EXIT_FAILURE) } // Push the data into the measurement's samples if(timeEntry>minTime) { dataMeasurement.add(point: dataEntry) } } } // For each sorted entry in the dictionary, print out the mean, median, min, max, std, var, etcetera print("mean", "count", separator: "\t") print(dataMeasurement.mean, dataMeasurement.count, separator: "\t")
mit
9fd004d783475c2f3cde51b67c8fb720
32.173228
125
0.723
3.564298
false
false
false
false
AniOSDeveloper/SearchTwitterWithOauth
SearchTwitterWithOauth/Cells/DetailCell.swift
1
1241
// // DetailCell.swift // SearchTwitterWithOauth // // Created by Larry on 16/5/16. // Copyright © 2016年 Larry. All rights reserved. // import UIKit import SDWebImage class DetailCell: UITableViewCell { @IBOutlet weak var headerIcon: UIImageView! @IBOutlet weak var nickName: UILabel! @IBOutlet weak var userName: UILabel! @IBOutlet weak var timeAgo: UILabel! @IBOutlet weak var tweetLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func configCells(twitte:TwitteModel) { if twitte.nickName != nil { nickName.text = twitte.nickName! }else{ nickName.text = "" } if twitte.userName != nil { userName.text = "@" + twitte.userName! }else{ userName.text = "" } timeAgo.text = twitte.timeAgo tweetLabel.text = twitte.tweet headerIcon.sd_setImageWithURL(NSURL(string:twitte.headerIcon), placeholderImage: UIImage(named: "cat.png")) } }
mit
cb538f57726c75da2854cf4182144b9f
23.76
115
0.601777
4.239726
false
false
false
false
stripe/stripe-ios
StripeIdentity/StripeIdentityTests/Snapshot/InstructionListViewSnapshotTest.swift
1
1772
// // InstructionListViewSnapshotTest.swift // StripeIdentityTests // // Created by Mel Ludowise on 2/17/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeUICore import iOSSnapshotTestCase @testable import StripeIdentity final class InstructionListViewSnapshotTest: FBSnapshotTestCase { let multiLineText = "Here's a string that spans multiple lines of text\nAnother line!\nAnother line!" let view = InstructionListView() override func setUp() { super.setUp() ActivityIndicator.isAnimationEnabled = false // recordMode = true } override func tearDown() { ActivityIndicator.isAnimationEnabled = true super.tearDown() } func testTextOnly() { verifyView( with: .init( instructionText: multiLineText, listViewModel: nil ) ) } func testListOnly() { verifyView( with: .init( instructionText: nil, listViewModel: ListViewSnapshotTest.manyItemViewModel ) ) } func testTextAndList() { verifyView( with: .init( instructionText: multiLineText, listViewModel: ListViewSnapshotTest.manyItemViewModel ) ) } } extension InstructionListViewSnapshotTest { fileprivate func verifyView( with viewModel: InstructionListView.ViewModel, file: StaticString = #filePath, line: UInt = #line ) { view.configure(with: viewModel) view.autosizeHeight(width: SnapshotTestMockData.mockDeviceWidth) STPSnapshotVerifyView(view, file: file, line: line) } }
mit
48ec1aa3ce159ca2075ac6fe2ae20da8
23.597222
89
0.61773
5.06
false
true
false
false
stripe/stripe-ios
StripeCore/StripeCore/Source/Telemetry/STPTelemetryClient.swift
1
7493
// // STPTelemetryClient.swift // StripeCore // // Created by Ben Guo on 4/18/17. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation import UIKit private let TelemetryURL = URL(string: "https://m.stripe.com/6")! @_spi(STP) public final class STPTelemetryClient: NSObject { @_spi(STP) public static var shared: STPTelemetryClient = STPTelemetryClient( sessionConfiguration: StripeAPIConfiguration.sharedUrlSessionConfiguration ) @_spi(STP) public func addTelemetryFields(toParams params: inout [String: Any]) { params["muid"] = fraudDetectionData.muid params["guid"] = fraudDetectionData.guid fraudDetectionData.resetSIDIfExpired() params["sid"] = fraudDetectionData.sid } @_spi(STP) public func paramsByAddingTelemetryFields( toParams params: [String: Any] ) -> [String: Any] { var mutableParams = params mutableParams["muid"] = fraudDetectionData.muid mutableParams["guid"] = fraudDetectionData.guid fraudDetectionData.resetSIDIfExpired() mutableParams["sid"] = fraudDetectionData.sid return mutableParams } /// Sends a payload of telemetry to the Stripe telemetry service. /// /// - Parameters: /// - forceSend: ⚠️ Always send the request. Only pass this for testing purposes. /// - completion: Called with the result of the telemetry network request. @_spi(STP) public func sendTelemetryData( forceSend: Bool = false, completion: ((Result<[String: Any], Error>) -> Void)? = nil ) { guard forceSend || STPTelemetryClient.shouldSendTelemetry() else { completion?(.failure(NSError.stp_genericConnectionError())) return } sendTelemetryRequest(jsonPayload: payload, completion: completion) } @_spi(STP) public func updateFraudDetectionIfNecessary( completion: @escaping ((Result<FraudDetectionData, Error>) -> Void) ) { fraudDetectionData.resetSIDIfExpired() if fraudDetectionData.muid == nil || fraudDetectionData.sid == nil { sendTelemetryRequest( jsonPayload: [ "muid": fraudDetectionData.muid ?? "", "guid": fraudDetectionData.guid ?? "", "sid": fraudDetectionData.sid ?? "", ]) { result in switch result { case .failure(let error): completion(.failure(error)) case .success: completion(.success(self.fraudDetectionData)) } } } else { completion(.success(fraudDetectionData)) } } private let urlSession: URLSession @_spi(STP) public class func shouldSendTelemetry() -> Bool { #if targetEnvironment(simulator) return false #else return StripeAPI.advancedFraudSignalsEnabled && NSClassFromString("XCTest") == nil #endif } @_spi(STP) public init( sessionConfiguration config: URLSessionConfiguration ) { urlSession = URLSession(configuration: config) super.init() } private var language = Locale.autoupdatingCurrent.identifier private lazy var fraudDetectionData = { return FraudDetectionData.shared }() lazy private var platform = [deviceModel, osVersion].joined(separator: " ") private var deviceModel: String = { var systemInfo = utsname() uname(&systemInfo) let model = withUnsafePointer(to: &systemInfo.machine) { $0.withMemoryRebound(to: CChar.self, capacity: 1) { ptr in String.init(validatingUTF8: ptr) } } return model ?? "Unknown" }() private var osVersion = UIDevice.current.systemVersion private var screenSize: String { let screen = UIScreen.main let screenRect = screen.bounds let width = screenRect.size.width let height = screenRect.size.height let scale = screen.scale return String(format: "%.0fw_%.0fh_%.0fr", width, height, scale) } private var timeZoneOffset: String { let timeZone = NSTimeZone.local as NSTimeZone let hoursFromGMT = Double(timeZone.secondsFromGMT) / (60 * 60) return String(format: "%.0f", hoursFromGMT) } private func encodeValue(_ value: String?) -> [AnyHashable: Any]? { if let value = value { return [ "v": value ] } return nil } private var payload: [String: Any] { var payload: [String: Any] = [:] var data: [String: Any] = [:] if let encode = encodeValue(language) { data["c"] = encode } if let encode = encodeValue(platform) { data["d"] = encode } if let encode = encodeValue(screenSize) { data["f"] = encode } if let encode = encodeValue(timeZoneOffset) { data["g"] = encode } payload["a"] = data // Don't pass expired SIDs to m.stripe.com fraudDetectionData.resetSIDIfExpired() let otherData: [String: Any] = [ "d": fraudDetectionData.muid ?? "", "e": fraudDetectionData.sid ?? "", "k": Bundle.stp_applicationName() ?? "", "l": Bundle.stp_applicationVersion() ?? "", "m": NSNumber(value: StripeAPI.deviceSupportsApplePay()), "o": osVersion, "s": deviceModel, ] payload["b"] = otherData payload["tag"] = STPAPIClient.STPSDKVersion payload["src"] = "ios-sdk" payload["v2"] = NSNumber(value: 1) return payload } private func sendTelemetryRequest( jsonPayload: [String: Any], completion: ((Result<[String: Any], Error>) -> Void)? = nil ) { var request = URLRequest(url: TelemetryURL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let data = try? JSONSerialization.data( withJSONObject: jsonPayload, options: [] ) request.httpBody = data let task = urlSession.dataTask(with: request as URLRequest) { (data, response, error) in guard error == nil, let response = response as? HTTPURLResponse, response.statusCode == 200, let data = data, let responseDict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { completion?(.failure(error ?? NSError.stp_genericFailedToParseResponseError())) return } // Update fraudDetectionData if let muid = responseDict["muid"] as? String { self.fraudDetectionData.muid = muid } if let guid = responseDict["guid"] as? String { self.fraudDetectionData.guid = guid } if self.fraudDetectionData.sid == nil, let sid = responseDict["sid"] as? String { self.fraudDetectionData.sid = sid self.fraudDetectionData.sidCreationDate = Date() } completion?(.success(responseDict)) } task.resume() } }
mit
53e02201b2719094683c50f5626ad8fd
33.990654
96
0.576389
4.824742
false
false
false
false
rockgarden/swift_language
Demo/Demo/main.swift
1
1359
import Foundation // 可选类型:处理值可能缺失的情况 let Str = "1234" let convertNumber = Int(Str) print(convertNumber as Any) //convertNumber 是 optional Int 或者 Int? if convertNumber != nil{ print(convertNumber!)//可选值的强制解析 可去除optional } // 可选绑定:可以用在if和while语句中来对可选类型的值进行判断并把值赋给一个常量或者变量。 if let actualNumber = Int(Str){ print(actualNumber) } // nil表示一个确定的值,表示值缺失 var serverCode: Int? = 404 serverCode = nil //现在serverCode不包含值 var suuny: String? // 隐式解析可选类型:第一次被赋值之后,可以确定一个可选类型总会有值,不要在变量没有值的时候使用 var possibleStr: String! = "value" print(possibleStr) // 字符串 var str1="aa" var str2="bb" var str3=String()//初始化字符串 str1 += "cc" print("\n\(str1)") let char:Character="!" var s:Character="\u{22}" str1.append(char) str1.append(s) print(str1) print("str1 has \(str1.characters.count) chars") var strRepeat = String(repeating: "w", count: 40) var strRepeatU = String(repeating: "\u{3423}", count: 40) strRepeat += strRepeatU var sum = strRepeat.characters.count print(strRepeat, "strPepeat has \(sum) characters") let quotation="same" let sameQu="same" if quotation==sameQu{ print("ture") }
mit
1d2d03c782cc54c29647ebb1aadfd9bd
21.604167
66
0.729954
2.732997
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Mapper/LandingURLMapper.swift
1
2418
// // LandingURLMapper.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ObjectMapper class LandingURLMapper: Mappable { var destination: String? fileprivate var typeString: String? required init?(map: Map) { /* Intentionally left empty */ } func mapping(map: Map) { destination <- map["attributes.url"] typeString <- map["id"] } var type: LandingURLType { if typeString == "ctb-about_us" { return LandingURLType.aboutUs } if typeString == "ctb-terms_of_use" { return LandingURLType.termsOfUse } if typeString == "ctb-privacy_policy" { return LandingURLType.privacyPolicy } if typeString == "ctb-user_profile" { return LandingURLType.userProfile } if typeString == "ctb-registration" { return LandingURLType.registration } if typeString == "ctb-explore" { return LandingURLType.explore } if typeString == "ctb-forgot_password" { return LandingURLType.forgotPassword } if typeString == "cte-account_dashboard" { return LandingURLType.accountDashboard } if typeString == "cte-upload_guidelines" { return LandingURLType.uploadGuidelines } Logger.log(.warning, "Unknown landingURL: \(String(describing: self.typeString))") return .unknown } }
mit
d386ab93b06e808ba347f3ff75417452
44.622642
91
0.715054
4.287234
false
false
false
false
themasterapp/master-app-ios
MasterApp/Extensions/UIColor/UIColor+ColorFromHex.swift
1
722
// // ColorFromHex.swift // Sos // // Created by MasterApp on 9/4/16. // Copyright © 2016 MasterApp. All rights reserved. // import UIKit // http://stackoverflow.com/a/24263296 extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
mit
d1c9e0096ef1b81ba55ef321d8d7e543
29.041667
116
0.60749
3.233184
false
false
false
false
brettg/Signal-iOS
Signal/src/call/WebRTCCallMessageHandler.swift
1
2907
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation @objc(OWSWebRTCCallMessageHandler) class WebRTCCallMessageHandler: NSObject, OWSCallMessageHandler { // MARK - Properties let TAG = "[WebRTCCallMessageHandler]" // MARK: Dependencies let accountManager: AccountManager let callService: CallService let messageSender: MessageSender // MARK: Initializers required init(accountManager: AccountManager, callService: CallService, messageSender: MessageSender) { self.accountManager = accountManager self.callService = callService self.messageSender = messageSender } // MARK: - Call Handlers public func receivedOffer(_ offer: OWSSignalServiceProtosCallMessageOffer, from callerId: String) { AssertIsOnMainThread() Logger.verbose("\(TAG) handling offer from caller:\(callerId)") let thread = TSContactThread.getOrCreateThread(contactId: callerId) self.callService.handleReceivedOffer(thread: thread, callId: offer.id, sessionDescription: offer.sessionDescription) } public func receivedAnswer(_ answer: OWSSignalServiceProtosCallMessageAnswer, from callerId: String) { AssertIsOnMainThread() Logger.verbose("\(TAG) handling answer from caller:\(callerId)") let thread = TSContactThread.getOrCreateThread(contactId: callerId) self.callService.handleReceivedAnswer(thread: thread, callId: answer.id, sessionDescription: answer.sessionDescription) } public func receivedIceUpdate(_ iceUpdate: OWSSignalServiceProtosCallMessageIceUpdate, from callerId: String) { AssertIsOnMainThread() Logger.verbose("\(TAG) handling iceUpdates from caller:\(callerId)") let thread = TSContactThread.getOrCreateThread(contactId: callerId) // Discrepency between our protobuf's sdpMlineIndex, which is unsigned, // while the RTC iOS API requires a signed int. let lineIndex = Int32(iceUpdate.sdpMlineIndex) self.callService.handleRemoteAddedIceCandidate(thread: thread, callId: iceUpdate.id, sdp: iceUpdate.sdp, lineIndex: lineIndex, mid: iceUpdate.sdpMid) } public func receivedHangup(_ hangup: OWSSignalServiceProtosCallMessageHangup, from callerId: String) { AssertIsOnMainThread() Logger.verbose("\(TAG) handling 'hangup' from caller:\(callerId)") let thread = TSContactThread.getOrCreateThread(contactId: callerId) self.callService.handleRemoteHangup(thread: thread) } public func receivedBusy(_ busy: OWSSignalServiceProtosCallMessageBusy, from callerId: String) { AssertIsOnMainThread() Logger.verbose("\(TAG) handling 'busy' from caller:\(callerId)") let thread = TSContactThread.getOrCreateThread(contactId: callerId) self.callService.handleRemoteBusy(thread: thread) } }
gpl-3.0
f0383a8ccc00fb3cac0673f8a170c746
36.753247
157
0.729274
4.918782
false
false
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift
53
4823
// // BarChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet { fileprivate func initialize() { self.highlightColor = NSUIColor.black self.calcStackSize(entries: values as! [BarChartDataEntry]) self.calcEntryCountIncludingStacks(entries: values as! [BarChartDataEntry]) } public required init() { super.init() initialize() } public override init(values: [ChartDataEntry]?, label: String?) { super.init(values: values, label: label) initialize() } // MARK: - Data functions and accessors /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet fileprivate var _stackSize = 1 /// the overall entry count, including counting each stack-value individually fileprivate var _entryCountStacks = 0 /// Calculates the total number of entries this DataSet represents, including /// stacks. All values belonging to a stack are calculated separately. fileprivate func calcEntryCountIncludingStacks(entries: [BarChartDataEntry]) { _entryCountStacks = 0 for i in 0 ..< entries.count { if let vals = entries[i].yValues { _entryCountStacks += vals.count } else { _entryCountStacks += 1 } } } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet fileprivate func calcStackSize(entries: [BarChartDataEntry]) { for i in 0 ..< entries.count { if let vals = entries[i].yValues { if vals.count > _stackSize { _stackSize = vals.count } } } } open override func calcMinMax(entry e: ChartDataEntry) { guard let e = e as? BarChartDataEntry else { return } if !e.y.isNaN { if e.yValues == nil { if e.y < _yMin { _yMin = e.y } if e.y > _yMax { _yMax = e.y } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } calcMinMaxX(entry: e) } } /// - returns: The maximum number of bars that can be stacked upon another in this DataSet. open var stackSize: Int { return _stackSize } /// - returns: `true` if this DataSet is stacked (stacksize > 1) or not. open var isStacked: Bool { return _stackSize > 1 ? true : false } /// - returns: The overall entry count, including counting each stack-value individually open var entryCountStacks: Int { return _entryCountStacks } /// array of labels used to describe the different values of the stacked bars open var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn. open var barBorderWidth : CGFloat = 0.0 /// the color drawing borders around the bars. open var barBorderColor = NSUIColor.black /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) open var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! BarChartDataSet copy._stackSize = _stackSize copy._entryCountStacks = _entryCountStacks copy.stackLabels = stackLabels copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
mit
687eb6d880604ddda60bedcfb1f3dab3
28.230303
148
0.564794
5.163812
false
false
false
false
debugsquad/nubecero
nubecero/Firebase/Storage/FStorage.swift
1
1271
import Foundation import FirebaseStorage class FStorage { enum Parent:String { case user = "user" } private let reference:FIRStorageReference private let kTenMegaBytes:Int64 = 10000000 init() { reference = FIRStorage.storage().reference() } //MARK: public func saveData(path:String, data:Data, completionHandler:@escaping((String?) -> ())) { let childReference:FIRStorageReference = reference.child(path) childReference.put( data, metadata:nil) { (metaData:FIRStorageMetadata?, error:Error?) in let errorString:String? = error?.localizedDescription completionHandler(errorString) } } func loadData(path:String, completionHandler:@escaping((Data?, Error?) -> ())) { let childReference:FIRStorageReference = reference.child(path) childReference.data( withMaxSize:kTenMegaBytes, completion:completionHandler) } func deleteData(path:String, completionHandler:@escaping((Error?) -> ())) { let childReference:FIRStorageReference = reference.child(path) childReference.delete(completion:completionHandler) } }
mit
274c3eb9052cd29aa33dfb1a962eb2e1
26.042553
87
0.623918
4.926357
false
false
false
false
Masteryyz/CSYMicroBlockSina
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Home/HomeTableViewCell/CSYOriginBlogView.swift
1
7795
// // CSYOriginBlogView.swift // CSYMicroBlockSina // // Created by 姚彦兆 on 15/11/14. // Copyright © 2015年 姚彦兆. All rights reserved. // import UIKit import SnapKit import SDWebImage import FFLabel class CSYOriginBlogView: UIView,FFLabelDelegate { //记录约束属性 private var bottomConstraints : Constraint? //数据源方法 var messageModel : CSYMyMicroBlogModel? { didSet{ iconImageView.sd_setImageWithURL(messageModel?.userMessageModel?.iconURL, placeholderImage: UIImage(named: "avatar_default_big")) verifiedImageView.image = messageModel?.userMessageModel?.verified_image rankImageView.image = messageModel?.userMessageModel?.rankImage nameLabel.text = messageModel?.userMessageModel?.name messageLabel.attributedText = CSYEmoticonManager.manager.setTextToImageText(messageModel?.text ?? "", font: messageLabel.font) print("......................\(NSDate.getSinaDateWithString(messageModel?.created_at ?? "")?.getDateDescription())") timeLabel.text = NSDate.getSinaDateWithString(messageModel?.created_at ?? "")?.getDateDescription() sourceLabel.text = "来自--\(messageModel?.getSource?.getSourceStringWithRegularExpression().sourceStr)" //设置图片显示 pictureView.imageURLArray = messageModel?.picURLArray self.bottomConstraints?.uninstall() if let urlArray : [NSURL] = messageModel?.picURLArray where urlArray.count > 0 { pictureView.imageURLArray = urlArray pictureView.backgroundColor = UIColor.whiteColor() pictureView.hidden = false self.snp_updateConstraints(closure: { (make) -> Void in self.bottomConstraints = make.bottom.equalTo(pictureView.snp_bottom).offset(cellMargin).constraint }) }else{ pictureView.hidden = true self.snp_updateConstraints(closure: { (make) -> Void in self.bottomConstraints = make.bottom.equalTo(messageLabel.snp_bottom).offset(cellMargin).constraint }) } } } //构造方法 override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //设置UI private func setUpUI(){ backgroundColor = UIColor.whiteColor() //头像 addSubview(iconImageView) //大V认证 addSubview(verifiedImageView) //等级标识 addSubview(rankImageView) //昵称 addSubview(nameLabel) //发布时间 addSubview(timeLabel) //来源 addSubview(sourceLabel) sourceLabel.labelDelegate = self //详情 addSubview(messageLabel) messageLabel.labelDelegate = self messageLabel.linkTextColor = UIColor.purpleColor() //图片浏览器 addSubview(pictureView) //添加约束 iconImageView.snp_makeConstraints { (make) -> Void in make.top.equalTo(self.snp_top).offset(cellMargin) make.left.equalTo(self.snp_left).offset(cellMargin) make.width.equalTo(iconWidth) make.height.equalTo(iconWidth) } iconImageView.layer.cornerRadius = 17.5 iconImageView.layer.masksToBounds = true verifiedImageView.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(iconImageView.snp_right).offset(-verifiedImageView.bounds.width / 4) make.centerY.equalTo(iconImageView.snp_bottom).offset(-verifiedImageView.bounds.width / 4) } nameLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(iconImageView.snp_right).offset(cellMargin) make.top.equalTo(iconImageView.snp_top) } rankImageView.snp_makeConstraints { (make) -> Void in make.left.equalTo(nameLabel.snp_right).offset(cellMargin) make.top.equalTo(nameLabel.snp_top) } timeLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(nameLabel.snp_left) make.top.equalTo(nameLabel.snp_bottom).offset(5) } sourceLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(timeLabel.snp_right).offset(cellMargin) make.top.equalTo(timeLabel.snp_top) } messageLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(iconImageView.snp_left) make.top.equalTo(iconImageView.snp_bottom).offset(cellMargin) } pictureView.snp_makeConstraints { (make) -> Void in make.left.equalTo(messageLabel.snp_left) make.top.equalTo(messageLabel.snp_bottom).offset(cellMargin) make.width.equalTo(100) make.height.equalTo(100) } self.snp_makeConstraints { (make) -> Void in self.bottomConstraints = make.bottom.equalTo(pictureView.snp_bottom).offset(cellMargin).constraint } } //懒加载所有控件 lazy var iconImageView : UIImageView = UIImageView(image: UIImage(named: "avatar_default_big")) lazy var verifiedImageView : UIImageView = UIImageView(image: UIImage(named: "avatar_vip")) lazy var rankImageView : UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_expired")) lazy var nameLabel : UILabel = UILabel(textInfo: "Hahahahaha", fontSize: 14, infoColor: UIColor.blackColor(), numberOFLines: 0, alphaValue: 1.0) lazy var timeLabel : UILabel = UILabel(textInfo: "11:11", fontSize: 12, infoColor: UIColor.orangeColor(), numberOFLines: 0, alphaValue: 1.0) lazy var sourceLabel : FFLabel = FFLabel(textInfo: "来自--你大爷的", fontSize: 12, infoColor: UIColor.darkGrayColor(), numberOFLines: 1, alphaValue: 1.0) lazy var messageLabel : FFLabel = FFLabel(textInfo: "这是微博的内容", fontSize: 14, numberOFLines: 0, alphaValue: 1.0 , margin: cellMargin) lazy var pictureView : CSYBlogPictureView = CSYBlogPictureView() } extension CSYOriginBlogView { func labelDidSelectedLinkText(label: FFLabel, text: String) { print(text) if let URL : NSURL = NSURL(string: text){ if text.hasPrefix("http://"){ let webVC : CSYShowLinkViewController = CSYShowLinkViewController(url: URL, blogModel: messageModel!) self.getNavController()?.pushViewController(webVC, animated: true) } } } }
mit
4a85bb5e32a40797abf3beb888e959cd
29.293651
151
0.547943
5.316156
false
false
false
false
brentdax/swift
test/SILGen/existential_erasure_mutating_covariant_self.swift
7
2638
// RUN: %target-swift-emit-silgen -enable-sil-ownership -verify %s // RUN: %target-swift-emit-sil -enable-sil-ownership %s | %FileCheck --check-prefix=AFTER-MANDATORY-PASSES %s // ensure escape analysis killed the box allocations used for delayed Self // return buffers // AFTER-MANDATORY-PASSES-NOT: alloc_box extension Error { mutating func covariantReturn(_: Int) -> Self { return self } mutating func covariantOptionalReturn(_: Int) -> Self? { return self } mutating func covariantReturnOrThrow(_: Int) throws -> Self { return self } mutating func covariantClosureArgAndReturn(_: (Self) -> Int) -> Self { return self } } protocol MutatingWithCovariantReturn { mutating func covariantReturn(_: Int) -> Self mutating func covariantOptionalReturn(_: Int) -> Self? mutating func covariantReturnOrThrow(_: Int) throws -> Self mutating func covariantClosureArgAndReturn(_: (Self) -> Int) -> Self } protocol ClassConstrainedRefinement: MutatingWithCovariantReturn, AnyObject {} func int() -> Int { return 0 } func intThrows() throws -> Int { return 0 } func foo(x: inout MutatingWithCovariantReturn, y: inout ClassConstrainedRefinement, z: inout Error) throws { _ = x.covariantReturn(int()) _ = x.covariantReturn(try intThrows()) _ = x.covariantReturn(try! intThrows()) _ = x.covariantOptionalReturn(int()) _ = x.covariantOptionalReturn(try intThrows()) _ = x.covariantOptionalReturn(try! intThrows()) _ = try x.covariantReturnOrThrow(int()) _ = try x.covariantReturnOrThrow(try intThrows()) _ = try x.covariantReturnOrThrow(try! intThrows()) _ = x.covariantClosureArgAndReturn({ _ in 0 }) _ = y.covariantReturn(int()) _ = y.covariantReturn(try intThrows()) _ = y.covariantReturn(try! intThrows()) _ = y.covariantOptionalReturn(int()) _ = y.covariantOptionalReturn(try intThrows()) _ = y.covariantOptionalReturn(try! intThrows()) _ = try y.covariantReturnOrThrow(int()) _ = try y.covariantReturnOrThrow(try intThrows()) _ = try y.covariantReturnOrThrow(try! intThrows()) // FIXME: the dynamic self capture here has to happen after existential // opening as well. //_ = y.covariantClosureArgAndReturn({ _ in 0 }) _ = z.covariantReturn(int()) _ = z.covariantReturn(try intThrows()) _ = z.covariantReturn(try! intThrows()) _ = z.covariantOptionalReturn(int()) _ = z.covariantOptionalReturn(try intThrows()) _ = z.covariantOptionalReturn(try! intThrows()) _ = try z.covariantReturnOrThrow(int()) _ = try z.covariantReturnOrThrow(try intThrows()) _ = try z.covariantReturnOrThrow(try! intThrows()) _ = z.covariantClosureArgAndReturn({ _ in 0 }) }
apache-2.0
6c17813e8bf24f5ee4188113fc4205ee
35.136986
109
0.712661
3.768571
false
false
false
false
gottsohn/ios-swift-boiler
IOSSwiftBoiler/WebViewController.swift
1
1542
// // WebViewController.swift // ios swift boiler // // Created by Godson Ukpere on 3/14/16. // Copyright © 2016 Godson Ukpere. All rights reserved. // import UIKit class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var titleView: UINavigationItem! var url:String! var labelText:String! var timer:NSTimer! override func viewDidLoad() { super.viewDidLoad() webView.delegate = self if url != nil { webView.loadRequest(NSURLRequest(URL: NSURL(string: url)!)) titleView.title = labelText } } func timerCallback() { if progressView.progress < 0.9 { progressView.progress += 0.005 } } func webViewDidStartLoad(webView: UIWebView) { progressView.progress = 0.0 progressView.hidden = false timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(timerCallback), userInfo: nil, repeats: true) } func webViewDidFinishLoad(webView: UIWebView) { doneLoading() } func doneLoading() { progressView.progress = 1.0 progressView.hidden = true timer?.invalidate() } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { if error != nil { doneLoading() Helpers.showError(self, error: error!) } } }
mit
b3703b468130dd353afcaeb2db8e43a7
25.568966
139
0.619079
4.741538
false
false
false
false
willlarche/material-components-ios
components/AnimationTiming/examples/AnimationTimingExample.swift
1
9406
/* Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialAnimationTiming struct Constants { struct AnimationTime { static let interval: Double = 1.0 static let delay: Double = 0.5 } struct Sizes { static let topMargin: CGFloat = 16.0 static let leftGutter: CGFloat = 16.0 static let textOffset: CGFloat = 16.0 static let circleSize: CGSize = CGSize(width: 48.0, height: 48.0) } } class AnimationTimingExample: UIViewController { fileprivate let scrollView: UIScrollView = UIScrollView() fileprivate let linearView: UIView = UIView() fileprivate let materialStandardView: UIView = UIView() fileprivate let materialDecelerationView: UIView = UIView() fileprivate let materialAccelerationView: UIView = UIView() fileprivate let materialSharpView: UIView = UIView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.9, alpha: 1.0) title = "Animation Timing" setupExampleViews() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let timeInterval: TimeInterval = 2 * (Constants.AnimationTime.interval + Constants.AnimationTime.delay) var _: Timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(self.playAnimations), userInfo: nil, repeats: true) playAnimations() } func playAnimations() { let linearCurve: CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) applyAnimation(toView: linearView, withTimingFunction: linearCurve) if let materialStandard = CAMediaTimingFunction.mdc_function(withType: .standard) { applyAnimation(toView: materialStandardView, withTimingFunction: materialStandard) } else { materialStandardView.removeFromSuperview() } if let materialDeceleration = CAMediaTimingFunction.mdc_function(withType: .deceleration) { applyAnimation(toView: materialDecelerationView, withTimingFunction: materialDeceleration) } else { materialDecelerationView.removeFromSuperview() } if let materialAcceleration = CAMediaTimingFunction.mdc_function(withType: .acceleration) { applyAnimation(toView: materialAccelerationView, withTimingFunction: materialAcceleration) } else { materialAccelerationView.removeFromSuperview() } if let materialSharp = CAMediaTimingFunction.mdc_function(withType: .sharp) { applyAnimation(toView: materialSharpView, withTimingFunction: materialSharp) } else { materialSharpView.removeFromSuperview() } } func applyAnimation(toView view: UIView, withTimingFunction timingFunction : CAMediaTimingFunction) { let animWidth: CGFloat = self.view.frame.size.width - view.frame.size.width - 32.0 let transform: CGAffineTransform = CGAffineTransform.init(translationX: animWidth, y: 0) UIView.mdc_animate(with: timingFunction, duration: Constants.AnimationTime.interval, delay: Constants.AnimationTime.delay, options: [], animations: { view.transform = transform }, completion: { Bool in UIView.mdc_animate(with: timingFunction, duration: Constants.AnimationTime.interval, delay: Constants.AnimationTime.delay, options: [], animations: { view.transform = CGAffineTransform.identity }, completion: nil) }) } } extension AnimationTimingExample { fileprivate func setupExampleViews() { let curveLabel: (String) -> UILabel = { labelTitle in let label: UILabel = UILabel() label.text = labelTitle label.font = MDCTypography.captionFont() label.textColor = UIColor(white: 0, alpha: MDCTypography.captionFontOpacity()) label.sizeToFit() return label } let defaultColors: [UIColor] = [UIColor.darkGray.withAlphaComponent(0.8), UIColor.darkGray.withAlphaComponent(0.65), UIColor.darkGray.withAlphaComponent(0.5), UIColor.darkGray.withAlphaComponent(0.35), UIColor.darkGray.withAlphaComponent(0.2)] scrollView.frame = view.bounds scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height + Constants.Sizes.topMargin) scrollView.clipsToBounds = true view.addSubview(scrollView) let lineSpace: CGFloat = (view.frame.size.height - 50.0) / 5.0 let linearLabel: UILabel = curveLabel("Linear") linearLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: Constants.Sizes.topMargin, width: linearLabel.frame.size.width, height: linearLabel.frame.size.height) scrollView.addSubview(linearLabel) let linearViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: Constants.Sizes.leftGutter + Constants.Sizes.topMargin, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height) linearView.frame = linearViewFrame linearView.backgroundColor = defaultColors[0] linearView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0 scrollView.addSubview(linearView) let materialEaseInOutLabel: UILabel = curveLabel("MDCAnimationTimingFunctionEaseInOut") materialEaseInOutLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace, width: materialEaseInOutLabel.frame.size.width, height: materialEaseInOutLabel.frame.size.height) scrollView.addSubview(materialEaseInOutLabel) let materialEaseInOutViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height) materialStandardView.frame = materialEaseInOutViewFrame materialStandardView.backgroundColor = defaultColors[1] materialStandardView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0 scrollView.addSubview(materialStandardView) let materialEaseOutLabel: UILabel = curveLabel("MDCAnimationTimingFunctionEaseOut") materialEaseOutLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 2.0, width: materialEaseOutLabel.frame.size.width, height: materialEaseOutLabel.frame.size.height) scrollView.addSubview(materialEaseOutLabel) let materialEaseOutViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 2.0 + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height) materialDecelerationView.frame = materialEaseOutViewFrame materialDecelerationView.backgroundColor = defaultColors[2] materialDecelerationView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0 scrollView.addSubview(materialDecelerationView) let materialEaseInLabel: UILabel = curveLabel("MDCAnimationTimingFunctionEaseIn") materialEaseInLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 3.0, width: materialEaseInLabel.frame.size.width, height: materialEaseInLabel.frame.size.height) scrollView.addSubview(materialEaseInLabel) let materialEaseInViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 3.0 + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height) materialAccelerationView.frame = materialEaseInViewFrame materialAccelerationView.backgroundColor = defaultColors[3] materialAccelerationView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0 scrollView.addSubview(materialAccelerationView) let materialSharpLabel: UILabel = curveLabel("MDCAnimationTimingSharp") materialSharpLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 4.0, width: materialSharpLabel.frame.size.width, height: materialSharpLabel.frame.size.height) scrollView.addSubview(materialSharpLabel) let materialSharpViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 4.0 + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height) materialSharpView.frame = materialSharpViewFrame materialSharpView.backgroundColor = defaultColors[4] materialSharpView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0 scrollView.addSubview(materialSharpView) } @objc class func catalogBreadcrumbs() -> [String] { return ["Animation Timing", "Animation Timing (Swift)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } }
apache-2.0
3cebf5b3aa5828261b3142de2c494ea8
49.031915
216
0.733468
4.707708
false
false
false
false
HeMet/LSSTools
Sources/ifconvert/Serializer.swift
1
2707
// // Serializer.swift // LSS // // Created by Evgeniy Gubin on 10.02.17. // // import Foundation class Serializer { let declarations: OrderedDictionary<String, Value> init(declarations: OrderedDictionary<Value, String>) { self.declarations = declarations.swapped() } func serialize() -> String { var result = "" for (reference, value) in declarations { let keyword = value.declarationKeyword let declaration = keyword + " " + reference + ": " + value.serialize() + "\n\n" result += declaration } return result } } extension Dictionary where Value: Hashable { func swapped() -> [Value: Key] { var result: [Value: Key] = [:] for (key, value) in self { result[value] = key } return result } } extension OrderedDictionary where Value: Hashable { func swapped() -> OrderedDictionary<Value, Key> { var result = OrderedDictionary<Value, Key>() for (key, value) in self { result[value] = key } return result } } extension Value { var declarationKeyword: String { switch self { case .bool: return "bool" case .color: return "color" case .number: return "number" case .style: return "style" case .alert: return "alert" } } func serialize() -> String { switch self { case .bool(let value): return value ? "true" : "false" case .number(let value): return String(value) case .color(let color): if let a = color.a { return "#(r: " + String(color.r) + " g: " + String(color.g) + " b: " + String(color.b) + " a: " + String(a) + ")" } else { return "#(r: " + String(color.r) + " g: " + String(color.g) + " b: " + String(color.b) + ")" } case .style(let style): return style.serialize() case .alert(let alert): return "#(id: " + String(alert.id) + " volume: " + String(alert.volume) + ")" } } } extension Expression { func serialize() -> String { switch self { case .value(let value): return value.serialize() case .reference(let ref): return ref } } } extension Style { func serialize() -> String { var result = "(\n" for (name, expr) in properties { let prop = " " + name + ": " + expr.serialize() + "\n" result += prop } result += ")" return result } }
mit
a5b63d940a1d292411c9c4735639a771
24.537736
129
0.499446
4.132824
false
false
false
false
apple/swift-nio
Sources/NIOPosix/PendingWritesManager.swift
1
24429
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import Atomics private struct PendingStreamWrite { var data: IOData var promise: Optional<EventLoopPromise<Void>> } /// Does the setup required to issue a writev. /// /// - parameters: /// - pending: The currently pending writes. /// - iovecs: Pre-allocated storage (per `EventLoop`) for `iovecs`. /// - storageRefs: Pre-allocated storage references (per `EventLoop`) to manage the lifetime of the buffers to be passed to `writev`. /// - body: The function that actually does the vector write (usually `writev`). /// - returns: A tuple of the number of items attempted to write and the result of the write operation. private func doPendingWriteVectorOperation(pending: PendingStreamWritesState, iovecs: UnsafeMutableBufferPointer<IOVector>, storageRefs: UnsafeMutableBufferPointer<Unmanaged<AnyObject>>, _ body: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>) throws -> (itemCount: Int, writeResult: IOResult<Int>) { assert(iovecs.count >= Socket.writevLimitIOVectors, "Insufficiently sized buffer for a maximal writev") // Clamp the number of writes we're willing to issue to the limit for writev. let count = min(pending.flushedChunks, Socket.writevLimitIOVectors) // the numbers of storage refs that we need to decrease later. var numberOfUsedStorageSlots = 0 var toWrite: Int = 0 loop: for i in 0..<count { let p = pending[i] switch p.data { case .byteBuffer(let buffer): // Must not write more than Int32.max in one go. guard (numberOfUsedStorageSlots == 0) || (Socket.writevLimitBytes - toWrite >= buffer.readableBytes) else { break loop } let toWriteForThisBuffer = min(Socket.writevLimitBytes, buffer.readableBytes) toWrite += numericCast(toWriteForThisBuffer) buffer.withUnsafeReadableBytesWithStorageManagement { ptr, storageRef in storageRefs[i] = storageRef.retain() iovecs[i] = IOVector(iov_base: UnsafeMutableRawPointer(mutating: ptr.baseAddress!), iov_len: numericCast(toWriteForThisBuffer)) } numberOfUsedStorageSlots += 1 case .fileRegion: assert(numberOfUsedStorageSlots != 0, "first item in doPendingWriteVectorOperation was a FileRegion") // We found a FileRegion so stop collecting break loop } } defer { for i in 0..<numberOfUsedStorageSlots { storageRefs[i].release() } } let result = try body(UnsafeBufferPointer(start: iovecs.baseAddress!, count: numberOfUsedStorageSlots)) /* if we hit a limit, we really wanted to write more than we have so the caller should retry us */ return (numberOfUsedStorageSlots, result) } /// The result of a single write operation, usually `write`, `sendfile` or `writev`. internal enum OneWriteOperationResult { /// Wrote everything asked. case writtenCompletely /// Wrote some portion of what was asked. case writtenPartially /// Could not write as doing that would have blocked. case wouldBlock } /// The result of trying to write all the outstanding flushed data. That naturally includes all `ByteBuffer`s and /// `FileRegions` and the individual writes have potentially been retried (see `WriteSpinOption`). internal struct OverallWriteResult { enum WriteOutcome { /// Wrote all the data that was flushed. When receiving this result, we can unsubscribe from 'writable' notification. case writtenCompletely /// Could not write everything. Before attempting further writes the eventing system should send a 'writable' notification. case couldNotWriteEverything } internal var writeResult: WriteOutcome internal var writabilityChange: Bool } /// This holds the states of the currently pending stream writes. The core is a `MarkedCircularBuffer` which holds all the /// writes and a mark up until the point the data is flushed. /// /// The most important operations on this object are: /// - `append` to add an `IOData` to the list of pending writes. /// - `markFlushCheckpoint` which sets a flush mark on the current position of the `MarkedCircularBuffer`. All the items before the checkpoint will be written eventually. /// - `didWrite` when a number of bytes have been written. /// - `failAll` if for some reason all outstanding writes need to be discarded and the corresponding `EventLoopPromise` needs to be failed. private struct PendingStreamWritesState { private var pendingWrites = MarkedCircularBuffer<PendingStreamWrite>(initialCapacity: 16) public private(set) var bytes: Int64 = 0 public var flushedChunks: Int { return self.pendingWrites.markedElementIndex.map { self.pendingWrites.distance(from: self.pendingWrites.startIndex, to: $0) + 1 } ?? 0 } /// Subtract `bytes` from the number of outstanding bytes to write. private mutating func subtractOutstanding(bytes: Int) { assert(self.bytes >= bytes, "allegedly written more bytes (\(bytes)) than outstanding (\(self.bytes))") self.bytes -= numericCast(bytes) } /// Indicates that the first outstanding write was written in its entirety. /// /// - returns: The `EventLoopPromise` of the write or `nil` if none was provided. The promise needs to be fulfilled by the caller. /// private mutating func fullyWrittenFirst() -> EventLoopPromise<Void>? { let first = self.pendingWrites.removeFirst() self.subtractOutstanding(bytes: first.data.readableBytes) return first.promise } /// Indicates that the first outstanding object has been partially written. /// /// - parameters: /// - bytes: How many bytes of the item were written. private mutating func partiallyWrittenFirst(bytes: Int) { self.pendingWrites[self.pendingWrites.startIndex].data.moveReaderIndex(forwardBy: bytes) self.subtractOutstanding(bytes: bytes) } /// Initialise a new, empty `PendingWritesState`. public init() { } /// Check if there are no outstanding writes. public var isEmpty: Bool { if self.pendingWrites.isEmpty { assert(self.bytes == 0) assert(!self.pendingWrites.hasMark) return true } else { assert(self.bytes >= 0) return false } } /// Add a new write and optionally the corresponding promise to the list of outstanding writes. public mutating func append(_ chunk: PendingStreamWrite) { self.pendingWrites.append(chunk) switch chunk.data { case .byteBuffer(let buffer): self.bytes += numericCast(buffer.readableBytes) case .fileRegion(let fileRegion): self.bytes += numericCast(fileRegion.readableBytes) } } /// Get the outstanding write at `index`. public subscript(index: Int) -> PendingStreamWrite { return self.pendingWrites[self.pendingWrites.index(self.pendingWrites.startIndex, offsetBy: index)] } /// Mark the flush checkpoint. /// /// All writes before this checkpoint will eventually be written to the socket. public mutating func markFlushCheckpoint() { self.pendingWrites.mark() } /// Indicate that a write has happened, this may be a write of multiple outstanding writes (using for example `writev`). /// /// - warning: The promises will be returned in order. If one of those promises does for example close the `Channel` we might see subsequent writes fail out of order. Example: Imagine the user issues three writes: `A`, `B` and `C`. Imagine that `A` and `B` both get successfully written in one write operation but the user closes the `Channel` in `A`'s callback. Then overall the promises will be fulfilled in this order: 1) `A`: success 2) `C`: error 3) `B`: success. Note how `B` and `C` get fulfilled out of order. /// /// - parameters: /// - writeResult: The result of the write operation. /// - returns: A tuple of a promise and a `OneWriteResult`. The promise is the first promise that needs to be notified of the write result. /// This promise will cascade the result to all other promises that need notifying. If no promises need to be notified, will be `nil`. /// The write result will indicate whether we were able to write everything or not. public mutating func didWrite(itemCount: Int, result writeResult: IOResult<Int>) -> (EventLoopPromise<Void>?, OneWriteOperationResult) { switch writeResult { case .wouldBlock(0): return (nil, .wouldBlock) case .processed(let written), .wouldBlock(let written): var promise0: EventLoopPromise<Void>? assert(written >= 0, "allegedly written a negative amount of bytes: \(written)") var unaccountedWrites = written for _ in 0..<itemCount { let headItemReadableBytes = self.pendingWrites.first!.data.readableBytes if unaccountedWrites >= headItemReadableBytes { unaccountedWrites -= headItemReadableBytes /* we wrote at least the whole head item, so drop it and succeed the promise */ if let promise = self.fullyWrittenFirst() { if let p = promise0 { p.futureResult.cascade(to: promise) } else { promise0 = promise } } } else { /* we could only write a part of the head item, so don't drop it but remember what we wrote */ self.partiallyWrittenFirst(bytes: unaccountedWrites) // may try again depending on the writeSpinCount return (promise0, .writtenPartially) } } assert(unaccountedWrites == 0, "after doing all the accounting for the byte written, \(unaccountedWrites) bytes of unaccounted writes remain.") return (promise0, .writtenCompletely) } } /// Is there a pending flush? public var isFlushPending: Bool { return self.pendingWrites.hasMark } /// Remove all pending writes and return a `EventLoopPromise` which will cascade notifications to all. /// /// - warning: See the warning for `didWrite`. /// /// - returns: promise that needs to be failed, or `nil` if there were no pending writes. public mutating func removeAll() -> EventLoopPromise<Void>? { var promise0: EventLoopPromise<Void>? while !self.pendingWrites.isEmpty { if let p = self.fullyWrittenFirst() { if let promise = promise0 { promise.futureResult.cascade(to: p) } else { promise0 = p } } } return promise0 } /// Returns the best mechanism to write pending data at the current point in time. var currentBestWriteMechanism: WriteMechanism { switch self.flushedChunks { case 0: return .nothingToBeWritten case 1: switch self.pendingWrites.first!.data { case .byteBuffer: return .scalarBufferWrite case .fileRegion: return .scalarFileWrite } default: let startIndex = self.pendingWrites.startIndex switch (self.pendingWrites[startIndex].data, self.pendingWrites[self.pendingWrites.index(after: startIndex)].data) { case (.byteBuffer, .byteBuffer): return .vectorBufferWrite case (.byteBuffer, .fileRegion): return .scalarBufferWrite case (.fileRegion, _): return .scalarFileWrite } } } } /// This class manages the writing of pending writes to stream sockets. The state is held in a `PendingWritesState` /// value. The most important purpose of this object is to call `write`, `writev` or `sendfile` depending on the /// currently pending writes. final class PendingStreamWritesManager: PendingWritesManager { private var state = PendingStreamWritesState() private var iovecs: UnsafeMutableBufferPointer<IOVector> private var storageRefs: UnsafeMutableBufferPointer<Unmanaged<AnyObject>> internal var waterMark: ChannelOptions.Types.WriteBufferWaterMark = ChannelOptions.Types.WriteBufferWaterMark(low: 32 * 1024, high: 64 * 1024) internal let channelWritabilityFlag = ManagedAtomic(true) internal var publishedWritability = true internal var writeSpinCount: UInt = 16 private(set) var isOpen = true /// Mark the flush checkpoint. func markFlushCheckpoint() { self.state.markFlushCheckpoint() } /// Is there a flush pending? var isFlushPending: Bool { return self.state.isFlushPending } /// Are there any outstanding writes currently? var isEmpty: Bool { return self.state.isEmpty } /// Add a pending write alongside its promise. /// /// - parameters: /// - data: The `IOData` to write. /// - promise: Optionally an `EventLoopPromise` that will get the write operation's result /// - result: If the `Channel` is still writable after adding the write of `data`. func add(data: IOData, promise: EventLoopPromise<Void>?) -> Bool { assert(self.isOpen) self.state.append(.init(data: data, promise: promise)) if self.state.bytes > waterMark.high && channelWritabilityFlag.compareExchange(expected: true, desired: false, ordering: .relaxed).exchanged { // Returns false to signal the Channel became non-writable and we need to notify the user. self.publishedWritability = false return false } return true } /// Returns the best mechanism to write pending data at the current point in time. var currentBestWriteMechanism: WriteMechanism { return self.state.currentBestWriteMechanism } /// Triggers the appropriate write operation. This is a fancy way of saying trigger either `write`, `writev` or /// `sendfile`. /// /// - parameters: /// - scalarBufferWriteOperation: An operation that writes a single, contiguous array of bytes (usually `write`). /// - vectorBufferWriteOperation: An operation that writes multiple contiguous arrays of bytes (usually `writev`). /// - scalarFileWriteOperation: An operation that writes a region of a file descriptor (usually `sendfile`). /// - returns: The `OneWriteOperationResult` and whether the `Channel` is now writable. func triggerAppropriateWriteOperations(scalarBufferWriteOperation: (UnsafeRawBufferPointer) throws -> IOResult<Int>, vectorBufferWriteOperation: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>, scalarFileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> OverallWriteResult { return try self.triggerWriteOperations { writeMechanism in switch writeMechanism { case .scalarBufferWrite: return try triggerScalarBufferWrite({ try scalarBufferWriteOperation($0) }) case .vectorBufferWrite: return try triggerVectorBufferWrite({ try vectorBufferWriteOperation($0) }) case .scalarFileWrite: return try triggerScalarFileWrite({ try scalarFileWriteOperation($0, $1, $2) }) case .nothingToBeWritten: assertionFailure("called \(#function) with nothing available to be written") return .writtenCompletely } } } /// To be called after a write operation (usually selected and run by `triggerAppropriateWriteOperation`) has /// completed. /// /// - parameters: /// - itemCount: The number of items we tried to write. /// - result: The result of the write operation. private func didWrite(itemCount: Int, result: IOResult<Int>) -> OneWriteOperationResult { let (promise, result) = self.state.didWrite(itemCount: itemCount, result: result) if self.state.bytes < waterMark.low { channelWritabilityFlag.store(true, ordering: .relaxed) } promise?.succeed(()) return result } /// Trigger a write of a single `ByteBuffer` (usually using `write(2)`). /// /// - parameters: /// - operation: An operation that writes a single, contiguous array of bytes (usually `write`). private func triggerScalarBufferWrite(_ operation: (UnsafeRawBufferPointer) throws -> IOResult<Int>) throws -> OneWriteOperationResult { assert(self.state.isFlushPending && !self.state.isEmpty && self.isOpen, "single write called in illegal state: flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty), isOpen: \(self.isOpen)") switch self.state[0].data { case .byteBuffer(let buffer): return self.didWrite(itemCount: 1, result: try buffer.withUnsafeReadableBytes({ try operation($0) })) case .fileRegion: preconditionFailure("called \(#function) but first item to write was a FileRegion") } } /// Trigger a write of a single `FileRegion` (usually using `sendfile(2)`). /// /// - parameters: /// - operation: An operation that writes a region of a file descriptor. private func triggerScalarFileWrite(_ operation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> OneWriteOperationResult { assert(self.state.isFlushPending && !self.state.isEmpty && self.isOpen, "single write called in illegal state: flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty), isOpen: \(self.isOpen)") switch self.state[0].data { case .fileRegion(let file): let readerIndex = file.readerIndex let endIndex = file.endIndex return try file.fileHandle.withUnsafeFileDescriptor { fd in self.didWrite(itemCount: 1, result: try operation(fd, readerIndex, endIndex)) } case .byteBuffer: preconditionFailure("called \(#function) but first item to write was a ByteBuffer") } } /// Trigger a vector write operation. In other words: Write multiple contiguous arrays of bytes. /// /// - parameters: /// - operation: The vector write operation to use. Usually `writev`. private func triggerVectorBufferWrite(_ operation: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>) throws -> OneWriteOperationResult { assert(self.state.isFlushPending && !self.state.isEmpty && self.isOpen, "vector write called in illegal state: flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty), isOpen: \(self.isOpen)") let result = try doPendingWriteVectorOperation(pending: self.state, iovecs: self.iovecs, storageRefs: self.storageRefs, { try operation($0) }) return self.didWrite(itemCount: result.itemCount, result: result.writeResult) } /// Fail all the outstanding writes. This is useful if for example the `Channel` is closed. func failAll(error: Error, close: Bool) { if close { assert(self.isOpen) self.isOpen = false } self.state.removeAll()?.fail(error) assert(self.state.isEmpty) } /// Initialize with a pre-allocated array of IO vectors and storage references. We pass in these pre-allocated /// objects to save allocations. They can be safely be re-used for all `Channel`s on a given `EventLoop` as an /// `EventLoop` always runs on one and the same thread. That means that there can't be any writes of more than /// one `Channel` on the same `EventLoop` at the same time. /// /// - parameters: /// - iovecs: A pre-allocated array of `IOVector` elements /// - storageRefs: A pre-allocated array of storage management tokens used to keep storage elements alive during a vector write operation init(iovecs: UnsafeMutableBufferPointer<IOVector>, storageRefs: UnsafeMutableBufferPointer<Unmanaged<AnyObject>>) { self.iovecs = iovecs self.storageRefs = storageRefs } } internal enum WriteMechanism { case scalarBufferWrite case vectorBufferWrite case scalarFileWrite case nothingToBeWritten } internal protocol PendingWritesManager: AnyObject { var isOpen: Bool { get } var isFlushPending: Bool { get } var writeSpinCount: UInt { get } var currentBestWriteMechanism: WriteMechanism { get } var channelWritabilityFlag: ManagedAtomic<Bool> { get } /// Represents the writability state the last time we published a writability change to the `Channel`. /// This is used in `triggerWriteOperations` to determine whether we need to trigger a writability /// change. var publishedWritability: Bool { get set } } extension PendingWritesManager { // This is called from `Channel` API so must be thread-safe. var isWritable: Bool { return self.channelWritabilityFlag.load(ordering: .relaxed) } internal func triggerWriteOperations(triggerOneWriteOperation: (WriteMechanism) throws -> OneWriteOperationResult) throws -> OverallWriteResult { var result = OverallWriteResult(writeResult: .couldNotWriteEverything, writabilityChange: false) writeSpinLoop: for _ in 0...self.writeSpinCount { var oneResult: OneWriteOperationResult repeat { guard self.isOpen && self.isFlushPending else { result.writeResult = .writtenCompletely break writeSpinLoop } oneResult = try triggerOneWriteOperation(self.currentBestWriteMechanism) if oneResult == .wouldBlock { break writeSpinLoop } } while oneResult == .writtenCompletely } // Please note that the re-entrancy protection in `flushNow` expects this code to try to write _all_ the data // that is flushed. If we receive a `flush` whilst processing a previous `flush`, we won't do anything because // we expect this loop to attempt to attempt all writes, even ones that arrive after this method begins to run. // // In other words, don't return `.writtenCompletely` unless you've written everything the PendingWritesManager // knows to be flushed. // // Also, it is very important to not do any outcalls to user code outside of the loop until the `flushNow` // re-entrancy protection is off again. if !self.publishedWritability { // When we last published a writability change the `Channel` wasn't writable, signal back to the caller // whether we should emit a writability change. result.writabilityChange = self.isWritable self.publishedWritability = result.writabilityChange } return result } } extension PendingStreamWritesManager: CustomStringConvertible { var description: String { return "PendingStreamWritesManager { isFlushPending: \(self.isFlushPending), " + /* */ "writabilityFlag: \(self.channelWritabilityFlag.load(ordering: .relaxed))), state: \(self.state) }" } }
apache-2.0
0f6495b5074a23198cf7398a525a4c26
45.978846
521
0.648901
4.79376
false
false
false
false
Henawey/DevTest
BonialCodingTest/BrochureColelctionViewCell.swift
1
1133
// // BrochureColelctionViewCell.swift // BonialCodingTest // // Created by Ahmed Henawey on 10/22/16. // Copyright © 2016 Ahmed Henawey. All rights reserved. // import UIKit class BrochureColelctionViewCell: UICollectionViewCell { private let imageDownloader:ImageDownloader = ImageDownloader() @IBOutlet private weak var retailerName: UILabel! @IBOutlet private weak var title: UILabel! @IBOutlet private weak var imageView: UIImageView! override func prepareForReuse() { imageView.image = UIImage(named: "placeHolder") } func setRetailerName(retailerName:String,title:String,imageURL:String){ self.retailerName.text = retailerName self.title.text = title imageDownloader.fetchImageFromUrl(imageURL) { (image, error) in if error == nil{ dispatch_async(dispatch_get_main_queue(), { () -> Void in self.imageView.image = image }) }else{ NSLog("Error \(error?.domain) happen during download brochure image from url \(imageURL)") } } } }
unlicense
fd06ce75af197a4544980f5c733a7b3a
31.342857
106
0.640459
4.387597
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Calling/Permissions/CallPermissions.swift
1
2407
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import AVFoundation import UIKit class CallPermissions: CallPermissionsConfiguration { var isPendingAudioPermissionRequest: Bool { if UIDevice.isSimulator { // on iOS simulator microphone permissions are always granted by default return false } return AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) == .notDetermined } var isPendingVideoPermissionRequest: Bool { return AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .notDetermined } var canAcceptAudioCalls: Bool { if UIDevice.isSimulator { // on iOS simulator, microphone permissions are granted by default, but AVCaptureDevice does not // return the correct status return true } return AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) == .authorized } var canAcceptVideoCalls: Bool { return AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized } func requestVideoPermissionWithoutWarning(resultHandler: @escaping (Bool) -> Void) { UIApplication.wr_requestVideoAccess(resultHandler) } func requestOrWarnAboutAudioPermission(resultHandler: @escaping (Bool) -> Void) { if UIDevice.isSimulator { // on iOS simulator microphone permissions are always granted by default resultHandler(true) return } UIApplication.wr_requestOrWarnAboutMicrophoneAccess(resultHandler) } func requestOrWarnAboutVideoPermission(resultHandler: @escaping (Bool) -> Void) { UIApplication.wr_requestOrWarnAboutVideoAccess(resultHandler) } }
gpl-3.0
93ac5008c228375c47273fc557edfb26
34.925373
108
0.71209
5.014583
false
false
false
false
Natoto/arcgis-runtime-samples-ios
LicenseByOrgAccountSample/swift/LicenseByOrgAccount/ViewController.swift
4
4856
/* Copyright 2015 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import ArcGIS class ViewController: UIViewController { @IBOutlet weak var licenseLevelLabel:UILabel! @IBOutlet weak var expiryLabel:UILabel! @IBOutlet weak var licenseButton:UIButton! @IBOutlet weak var networkImageView:UIImageView! @IBOutlet weak var portalConnectionLabel:UILabel! @IBOutlet weak var logTextView:UITextView! var signedIn:Bool { //we're signed in if the LicenseHelper has a credential. return (LicenseHelper.sharedInstance.credential != nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if LicenseHelper.sharedInstance.savedInformationExists() { //if the license helper has saved information, log in immediately self.signInAction(self.licenseButton) self.updateLogWithString("Signing in...") } else { //update UI and wait for user to sign in self.updateLogWithString("") self.updateStatusWithCredential(nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signInAction(sender:UIButton) { if self.signedIn { //User wants to sign out, reset saved information LicenseHelper.sharedInstance.resetSavedInformation() self.updateLogWithString("The application has been signed out and all saved license and credential information has been deleted.") self.networkImageView.image = nil self.portalConnectionLabel.text = "" self.updateStatusWithCredential(nil) } else { //Use the helper to allow the user to sign in and license the app LicenseHelper.sharedInstance.standardLicenseFromPortal(NSURL(string: kPortalUrl)!, parentViewController: self, completion: { (licenseResult, usedSavedLicenseInfo, portal, credential, error) -> Void in if licenseResult == .Valid { if usedSavedLicenseInfo { self.updateLogWithString("The application was licensed at Standard level using the saved license info in the keychain") } else { self.updateLogWithString("The application was licensed at Standard level by logging into the portal.") } } else { let errorDescription = error?.localizedDescription ?? "" self.updateLogWithString("Couldn't initialize a Standard level license.\n license status: \(AGSLicenseResultAsString(licenseResult))\n reason: \(errorDescription)") } if portal != nil { self.networkImageView.image = UIImage(named: "blue-network") self.portalConnectionLabel.text = "Connected to portal" } else{ self.networkImageView.image = UIImage(named: "gray-network") self.portalConnectionLabel.text = "Could not connect to portal" } self.updateStatusWithCredential(credential) }) self.updateLogWithString("Signing in...") } } //MARK: - Internal func updateStatusWithCredential(credential:AGSCredential?) { let license = AGSRuntimeEnvironment.license() self.licenseLevelLabel.text = AGSLicenseLevelAsString(license.licenseLevel) var expiryString:String! if license.licenseLevel == AGSLicenseLevel.Developer || license.licenseLevel == AGSLicenseLevel.Basic { expiryString = "None" } else { expiryString = NSDateFormatter.localizedStringFromDate(license.expiry, dateStyle: .MediumStyle, timeStyle: .ShortStyle) } self.expiryLabel.text = expiryString let name = credential?.username ?? "" self.licenseButton.setTitle(self.signedIn ? "Sign Out \(name)" : "Sign In", forState: .Normal) } func updateLogWithString(logText:String) { if !logText.isEmpty { self.logTextView.text = logText } } }
apache-2.0
1d3661b7e847e5542097d21f16976b65
39.806723
212
0.638797
5.215897
false
false
false
false
yoxisem544/NetworkRequestKit
Source/MultipartNetworkClient.swift
2
1810
// // MultipartNetworkClient.swift // NetworkRequest // // Created by David on 2016/12/12. // Copyright © 2016年 David. All rights reserved. // import Foundation import PromiseKit import Alamofire public protocol MultipartNetworkClientType { func performMultipartRequest<Request: MultipartNetworkRequest>(_ networkRequest: Request) -> Promise<Data> } public struct MultipartNetworkClient : MultipartNetworkClientType { public func performMultipartRequest<Request : MultipartNetworkRequest>(_ networkRequest: Request) -> Promise<Data> { let (promise, seal) = Promise<Data>.pending() upload(multipartFormData: { multipartFormData in multipartFormData.append(networkRequest.multipartUploadData, withName: networkRequest.multipartUploadName, fileName: networkRequest.multipartUploadFileName, mimeType: networkRequest.multipartUploadMimeType) }, usingThreshold: 0, to: networkRequest.url, method: networkRequest.method, headers: networkRequest.headers) { (encodingResult) in switch encodingResult { case .success(request: let request, streamingFromDisk: _, streamFileURL: _): request.response(completionHandler: { (response) in if let data = response.data , response.error == nil { seal.fulfill(data) } else if let error = response.error, let data = response.data { let e = AlamofireErrorHandler.handleNetworkRequestError(error, data: data, urlResponse: response.response) seal.reject(e) } else { seal.reject(NetworkRequestError.unknownError) } }) case .failure(let error): seal.reject(error) } } return promise } }
mit
1162336cee01a77d88de72d2c07a1b86
35.877551
135
0.668511
5.061625
false
false
false
false
mathebox/WorkoutTimer
Workout Timer/Workout Timer/SettingsViewController.swift
1
7230
// // SettingsViewController.swift // Workout Timer // // Created by Max Bothe on 14/02/16. // Copyright © 2016 Max Bothe. All rights reserved. // import UIKit enum TimerSpeechOption : String { case None = "None" case ToGo = "To Go" case Past = "Past" case Combined = "Combined" case Smart = "Smart" static let allValues = [None, ToGo, Past, Combined, Smart] } class SettingsViewController : UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate { let counddownDurationKey = "countdown-duration" let timerSpeechKey = "timer-speech" var countdownPickerIndexPath : NSIndexPath? @IBAction func dismissSettings(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } // MARK: UITableView override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { if self.countdownPickerIndexPath != nil { return 2 } return 1 } return TimerSpeechOption.allValues.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cellId : String if indexPath.section == 0{ if self.countdownPickerIndexPath == indexPath { cellId = "countdown-picker" } else { cellId = "countdown-time" } } else { cellId = "timer-speech" } let cell = tableView.dequeueReusableCellWithIdentifier(cellId) let defaults = NSUserDefaults.standardUserDefaults() if cellId == "countdown-time" { if let duration = defaults.integerForKey(self.counddownDurationKey) as Int? { var durationText = "\(duration) sec" if duration == 0 { durationText = "disabled" } cell?.detailTextLabel?.text = durationText } } else if cellId == "timer-speech" { let text = TimerSpeechOption.allValues[indexPath.row].rawValue cell?.textLabel?.text = text if defaults.stringForKey(self.timerSpeechKey) == text { cell?.accessoryType = .Checkmark } } return cell! } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Countdown" } return "Timer Speech Options" } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if self.countdownPickerIndexPath == indexPath { return 216 } return self.tableView.rowHeight } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath == NSIndexPath(forRow: 0, inSection: 0) { self.displayInlineDatePickerForRowAtIndexPath(indexPath) } else if indexPath.section == 1 { let defaults = NSUserDefaults.standardUserDefaults() if let oldOption = defaults.stringForKey(self.timerSpeechKey) { if let value = TimerSpeechOption(rawValue: oldOption) { if let row = TimerSpeechOption.allValues.indexOf(value) { let indexPath = NSIndexPath(forRow: row, inSection: 1) self.tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None } } } let newOption = TimerSpeechOption.allValues[indexPath.row].rawValue defaults.setObject(newOption, forKey: self.timerSpeechKey) defaults.synchronize() tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func displayInlineDatePickerForRowAtIndexPath(indexPath: NSIndexPath) { self.tableView.beginUpdates() var sameCellClicked = false if let pickerIndexPath = self.countdownPickerIndexPath { sameCellClicked = (pickerIndexPath.row - 1 == indexPath.row) // remove any countdown picker cell if it exists self.tableView.deleteRowsAtIndexPaths([pickerIndexPath], withRowAnimation: .Automatic) self.countdownPickerIndexPath = nil } if !sameCellClicked { self.toggleCountdownPickerForSelectedIndexPath(indexPath) self.countdownPickerIndexPath = NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section) } self.tableView.deselectRowAtIndexPath(indexPath, animated: true) self.tableView.endUpdates() self.updateCountdownPicker() } func toggleCountdownPickerForSelectedIndexPath(indexPath: NSIndexPath) { self.tableView.beginUpdates() let pickerIndexPath = NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section) if self.hasPickerForIndexPath(pickerIndexPath) { self.tableView.deleteRowsAtIndexPaths([pickerIndexPath], withRowAnimation: .Automatic) } else { self.tableView.insertRowsAtIndexPaths([pickerIndexPath], withRowAnimation: .Automatic) } self.tableView.endUpdates() } func hasPickerForIndexPath(indexPath: NSIndexPath) -> Bool { let targetedIndexPath = NSIndexPath(forRow: indexPath.row, inSection: indexPath.section) let pickerCell = self.tableView.cellForRowAtIndexPath(targetedIndexPath) return ((pickerCell?.viewWithTag(99) as? UIPickerView) != nil) } func updateCountdownPicker() { if let pickerIndexPath = self.countdownPickerIndexPath { let pickerCell = self.tableView.cellForRowAtIndexPath(pickerIndexPath) if let picker = pickerCell?.viewWithTag(99) as? UIPickerView { let defaults = NSUserDefaults.standardUserDefaults() if let duration = defaults.integerForKey(self.counddownDurationKey) as Int? { picker.selectRow(duration, inComponent: 0, animated: false) } } } } // MARK: UIPickerView func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 31 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if row == 0 { return "disabled" } return "\(row)" } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(row, forKey: self.counddownDurationKey) defaults.synchronize() let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } }
mit
149ca5d5689db94d6d1c9e5ff886bf21
37.047368
118
0.642551
5.358784
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/SolutionsTests/Hard/Hard_044_Wildcard_Matching_Test.swift
1
2660
// // Hard_044_Wildcard_Matching_Test.swift // Solutions // // Created by Di Wu on 5/23/15. // Copyright (c) 2015 diwu. All rights reserved. // import XCTest class Hard_044_Wildcard_Matching_Test: XCTestCase, SolutionsTestCase { func test_001() { let input: [String] = ["aa", "a"] let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_002() { let input: [String] = ["aa", "aa"] let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_003() { let input: [String] = ["aaa", "aa"] let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_004() { let input: [String] = ["aa", "a*"] let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_005() { let input: [String] = ["aa", "?*"] let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_006() { let input: [String] = ["ab", "?*"] let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_007() { let input: [String] = ["aab", "c*a*b"] let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_008() { let input: [String] = ["aaaaab", "c*a*b"] let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_009() { let input: [String] = ["ab", "c*ab"] let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_010() { let input: [String] = ["aa", "*"] let expected: Bool = true asyncHelper(input: input, expected: expected) } private func asyncHelper(input: [String], expected: Bool) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) serialQueue().async(execute: { () -> Void in let result = Hard_044_Wildcard_Matching.isMatch(s: input[0], p: input[1]) assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected) } } } }
mit
01120f5af71b913ec6ad367877865d7f
33.545455
138
0.57218
4.024206
false
true
false
false
yakaolife/TrackLocations
TrackLocations/Classes/Location.swift
1
1165
// // Location.swift // Pods // // Created by Ya Kao on 7/17/17. // // import Foundation import Alamofire import SwiftyJSON public class Location: Equatable{ public let longitude : Double public let latitude : Double public let name: String //Will also use as identifier for region monitoring public var radius: Double = 1000 //In meters public required init(latitude: Double, longitude: Double, name: String) { self.longitude = longitude self.latitude = latitude self.name = name } public init(_ dictionary : [String: Any]){ self.longitude = dictionary["longitude"] as! Double self.latitude = dictionary["latitude"] as! Double self.name = dictionary["name"] as! String } // A place might have different names, so don't compare the name public static func ==(lhs: Location, rhs: Location) -> Bool{ return lhs.longitude == rhs.longitude && lhs.latitude == rhs.latitude } } extension Location: CustomStringConvertible { public var description: String{ return "\(name): latitude:\(latitude), longitude: \(longitude)" } }
mit
8f659d3805d73ea92f7fe9fee2d56cd2
26.093023
79
0.648069
4.463602
false
false
false
false
nomadik223/twitter-client
TwitterClient/TwitterClient/UserDetailViewController.swift
1
966
import UIKit class UserDetailViewController: UIViewController { var user : User! @IBOutlet weak var userName: UILabel! @IBOutlet weak var screenName: UILabel! @IBOutlet weak var userLocation: UILabel! @IBOutlet weak var userDescription: UILabel! override func viewDidLoad() { super.viewDidLoad() getUser() } func getUser() { API.shared.getOAuthUser { (userB) in guard let aUser = userB else {fatalError("This shit is bananas")} OperationQueue.main.addOperation { self.user = aUser self.userName.text = "User Name: \(self.user.name)" self.screenName.text = "Screen Name: @\(self.user.screenName)" self.userLocation.text = "Location: \(self.user.location)" self.userDescription.text = "Description: \(self.user.profileDescription)" } } } }
mit
7c757f79ff953a8e3b7e556c1905951b
29.1875
90
0.582816
4.83
false
false
false
false
LimonTop/CoreStoreKit
CoreStoreKit/CoreDataExtensions.swift
1
4616
// // CoreDataExtensions.swift // CoreStoreKit // // Created by catch on 15/9/27. // Copyright © 2015年 Limon. All rights reserved. // import Foundation import CoreData public struct CoreStoreKit { private init() {} /** Attempts to commit unsaved changes to registered objects to the specified context's parent store. This function is performed in a block on the context's queue. If the context has no changes, then this function returns immediately and the completion block is not called. - parameter context: The managed object context to save. - parameter wait: If true (the default), perform the save synchronously. - parameter completion: The closure to be executed when the save operation completes. */ public static func saveContext(context: NSManagedObjectContext, wait: Bool = true, completion: ((NSError?) -> Void)? = nil) { guard context.hasChanges else { return } let block = { () -> Void in do { try context.save() completion?(nil) } catch { completion?(error as NSError) } } wait ? context.performBlockAndWait(block) : context.performBlock(block) } /** Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator. - parameter name: The name of an entity. - parameter context: The managed object context to use. - returns: The entity with the specified name from the managed object model associated with context’s persistent store coordinator. */ public static func entity(name name: String, context: NSManagedObjectContext) -> NSEntityDescription { return NSEntityDescription.entityForName(name, inManagedObjectContext: context)! } /** Executes the fetch request in the given context and returns the result. This function is performed synchronously in a block on the context's queue. - parameter request: A fetch request that specifies the search criteria for the fetch. - parameter context: The managed object context in which to search. - throws: If the fetch fails or errors, then this function throws an `NSError`. - returns: An array of objects that meet the criteria specified by the fetch request. This array may be empty. */ public static func fetch <T: NSManagedObject>(request request: CoreStoreFetchRequest<T>, inContext context: NSManagedObjectContext) throws -> [T] { var results = [AnyObject]() var caughtError: NSError? context.performBlockAndWait { () -> Void in do { results = try context.executeFetchRequest(request) } catch { caughtError = error as NSError } } guard caughtError == nil else { throw caughtError! } return results as! [T] } /** Deletes the objects from the specified context. You must save the context after calling this function to remove objects from their persistent store. This function is performed synchronously in a block on the context's queue. - parameter objects: The managed objects to be deleted. - parameter context: The context to which the objects belong. */ public static func deleteObjects <T: NSManagedObject>(objects: [T], inContext context: NSManagedObjectContext) { guard objects.count != 0 else { return } context.performBlockAndWait { () -> Void in for each in objects { context.deleteObject(each) } } } } /** An instance of `FetchRequest <T: NSManagedObject>` describes search criteria used to retrieve data from a persistent store. This is a subclass of `NSFetchRequest` that adds a type parameter specifying the type of managed objects for the fetch request. The type parameter acts as a phantom type. */ public class CoreStoreFetchRequest <T: NSManagedObject>: NSFetchRequest { /** Constructs a new `FetchRequest` instance. - parameter context: The context to use that creates an entity description object from the type of NSManagedObject. - returns: A new `FetchRequest` instance. */ public init(context: NSManagedObjectContext) { let entityName = T.entityName let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)! super.init() self.entity = entity } }
mit
8918cd365ffe71bfaf72abbcaf896aa1
35.291339
151
0.66956
5.249431
false
false
false
false
WorldDownTown/Benchmark
Benchmark/Benchmark.swift
1
1140
// // Benchmark.swift // Benchmark // // Created by shoji on 2016/05/24. // Copyright © 2016年 com.shoji. All rights reserved. // import CoreFoundation public struct Benchmark { private let startTimeInterval: CFAbsoluteTime private let key: String private static var sharedInstance: Benchmark? public init(key: String) { startTimeInterval = CFAbsoluteTimeGetCurrent() self.key = key } public func finish() { let elapsed = CFAbsoluteTimeGetCurrent() - startTimeInterval let formatedElapsed = String(format: "%.5f", elapsed) print("\(key): \(formatedElapsed) sec.") } public static func start(_ key: String = "Benchmark") { sharedInstance = Benchmark(key: key) } public static func finish() { sharedInstance?.finish() sharedInstance = nil } public static func measure(_ key: String = "Benchmark", block: () -> ()) { let benchmark = Benchmark(key: key) block() benchmark.finish() } } prefix operator ⏲ public prefix func ⏲(handler: () -> ()) { Benchmark.measure(block: handler) }
mit
c6f31a0d5401152007bbbc258ffa0353
23.106383
78
0.629303
4.374517
false
false
false
false
creisterer-db/SwiftCharts
Examples/AppDelegate.swift
3
4751
// // AppDelegate.swift // Examples // // Created by ischuetz on 08/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if UIDevice.currentDevice().userInterfaceIdiom == .Pad { let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers.last as! UINavigationController splitViewController.delegate = self if #available(iOS 8.0, *) { navigationController.topViewController?.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() } } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } private func setSplitSwipeEnabled(enabled: Bool) { if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { let splitViewController = UIApplication.sharedApplication().delegate?.window!!.rootViewController as! UISplitViewController splitViewController.presentsWithGesture = enabled } } func splitViewController(svc: UISplitViewController, willHideViewController aViewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController pc: UIPopoverController) { let navigationController = svc.viewControllers[svc.viewControllers.count-1] as! UINavigationController if let topAsDetailController = navigationController.topViewController as? DetailViewController { barButtonItem.title = "Examples" topAsDetailController.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true) } } } // src: http://stackoverflow.com/a/27399688/930450 extension UISplitViewController { func toggleMasterView() { if #available(iOS 8.0, *) { let barButtonItem = self.displayModeButtonItem() UIApplication.sharedApplication().sendAction(barButtonItem.action, to: barButtonItem.target, from: nil, forEvent: nil) } } }
apache-2.0
73ddf15e2bd6706b185f62d9d3d88e4d
48.489583
285
0.726163
6.243101
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Post/PostViewModel.swift
1
2308
// // PostDetailViewModel.swift // RedditOs // // Created by Thomas Ricouard on 10/07/2020. // import Foundation import SwiftUI import Combine import Backend class PostViewModel: ObservableObject { @Published var post: SubredditPost @Published var comments: [Comment]? @AppStorage(SettingsKey.comments_default_sort_order) var commentsSort = Comment.Sort.top { didSet { fechComments() } } private var cancellableStore: [AnyCancellable] = [] init(post: SubredditPost) { self.post = post } func postVisit() { let oldValue = post.visited let cancellable = post.visit() .receive(on: DispatchQueue.main) .sink { [weak self] response in if response.error != nil { self?.post.visited = oldValue } } cancellableStore.append(cancellable) } func postVote(vote: Vote) { let oldValue = post.likes let cancellable = post.vote(vote: vote) .receive(on: DispatchQueue.main) .sink{ [weak self] response in if response.error != nil { self?.post.likes = oldValue } } cancellableStore.append(cancellable) } func toggleSave() { let oldValue = post.saved let cancellable = (post.saved ? post.unsave() : post.save()) .receive(on: DispatchQueue.main) .sink{ [weak self] response in if response.error != nil { self?.post.saved = oldValue } } cancellableStore.append(cancellable) } func fechComments() { comments = nil let cancellable = Comment.fetch(subreddit: post.subreddit, id: post.id, sort: commentsSort) .receive(on: DispatchQueue.main) .map{ $0.last?.comments } .sink{ [weak self] comments in self?.comments = comments } cancellableStore.append(cancellable) } } extension Comment.Sort { public func label() -> String { switch self { case .best: return "Best" default: return self.rawValue.capitalized } } }
mit
f2154068abdeb870f5fa57e028df886b
26.152941
99
0.54636
4.625251
false
false
false
false
ProcedureKit/ProcedureKit
Tests/ProcedureKitCloudTests/CKOperationTests.swift
2
4206
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import XCTest import ProcedureKit import TestingProcedureKit @testable import ProcedureKitCloud class TestCKOperation: Operation, CKOperationProtocol { typealias ServerChangeToken = String typealias RecordZone = String typealias RecordZoneID = String typealias Notification = String typealias NotificationID = String typealias Record = String typealias RecordID = String typealias Subscription = String typealias RecordSavePolicy = Int typealias DiscoveredUserInfo = String typealias Query = String typealias QueryCursor = String typealias UserIdentity = String typealias UserIdentityLookupInfo = String typealias Share = String typealias ShareMetadata = String typealias ShareParticipant = String var container: String? // just a test var allowsCellularAccess: Bool = true //@available(iOS 9.3, tvOS 9.3, OSX 10.12, watchOS 2.3, *) var operationID: String = "" #if swift(>=3.2) var isLongLived: Bool = false #else // Swift 3.x var longLived: Bool = false #endif var longLivedOperationWasPersistedBlock: () -> Void = { } //@available(iOS 10.0, tvOS 10.0, OSX 10.12, watchOS 3.0, *) var timeoutIntervalForRequest: TimeInterval = 0 var timeoutIntervalForResource: TimeInterval = 0 } class CKOperationTests: CKProcedureTestCase { var target: TestCKOperation! var operation: CKProcedure<TestCKOperation>! override func setUp() { super.setUp() target = TestCKOperation() operation = CKProcedure(operation: target) } override func tearDown() { target = nil operation = nil super.tearDown() } func test__set_get__container() { let container = "I'm a cloud kit container" operation.container = container XCTAssertEqual(operation.container, container) XCTAssertEqual(target.container, container) } func test__set_get__allowsCellularAccess() { let allowsCellularAccess = true operation.allowsCellularAccess = allowsCellularAccess XCTAssertEqual(operation.allowsCellularAccess, allowsCellularAccess) XCTAssertEqual(target.allowsCellularAccess, allowsCellularAccess) } @available(iOS 9.3, tvOS 9.3, OSX 10.12, watchOS 2.3, *) func test__get_operationID() { let operationID = "test operationID" target.operationID = operationID XCTAssertEqual(operation.operationID, operationID) } @available(iOS 9.3, tvOS 9.3, OSX 10.12, watchOS 2.3, *) func test__set_get__longLived() { let longLived = true #if swift(>=3.2) operation.isLongLived = longLived XCTAssertEqual(operation.isLongLived, longLived) XCTAssertEqual(target.isLongLived, longLived) #else // Swift < 3.2 (Xcode 8.x) operation.longLived = longLived XCTAssertEqual(operation.longLived, longLived) XCTAssertEqual(target.longLived, longLived) #endif } @available(iOS 9.3, tvOS 9.3, OSX 10.12, watchOS 2.3, *) func test__set_get__longLivedOperationWasPersistedBlock() { var setByBlock = false let block: () -> Void = { setByBlock = true } operation.longLivedOperationWasPersistedBlock = block operation.longLivedOperationWasPersistedBlock() XCTAssertTrue(setByBlock) } @available(iOS 10.0, tvOS 10.0, OSX 10.12, watchOS 3.0, *) func test__set_get__timeoutIntervalForRequest() { let timeout: TimeInterval = 42 operation.timeoutIntervalForRequest = timeout XCTAssertEqual(operation.timeoutIntervalForRequest, timeout) XCTAssertEqual(target.timeoutIntervalForRequest, timeout) } @available(iOS 10.0, tvOS 10.0, OSX 10.12, watchOS 3.0, *) func test__set_get__timeoutIntervalForResource() { let timeout: TimeInterval = 42 operation.timeoutIntervalForResource = timeout XCTAssertEqual(operation.timeoutIntervalForResource, timeout) XCTAssertEqual(target.timeoutIntervalForResource, timeout) } }
mit
7e835f342b6292bfeff7f51d65796f28
32.110236
76
0.681094
4.778409
false
true
false
false
PekanMmd/Pokemon-XD-Code
GoDToolOSX/View Controllers/GoDTreasureViewController.swift
1
5246
// // GoDTreasureViewController.swift // GoD Tool // // Created by The Steez on 03/11/2018. // import Cocoa class GoDTreasureViewController: GoDTableViewController { @IBOutlet var room: GoDRoomPopUpButton! @IBOutlet var model: GoDPopUpButton! @IBOutlet var item: GoDItemPopUpButton! @IBOutlet var quantity: NSTextField! @IBOutlet var angle: NSTextField! @IBOutlet var x: NSTextField! @IBOutlet var y: NSTextField! @IBOutlet var z: NSTextField! var currentTreasure = XGTreasure(index: 0) func sanitise(_ value: Int?, bytes: Int) -> Int { guard let val = value else { return 0 } if val < 0 { return 0 } let max = bytes == 2 ? 0xFFFF : 0xFF return min(val, max) } @IBAction func setTreasureRoom(_ sender: GoDRoomPopUpButton) { self.currentTreasure.roomID = sender.selectedValue.roomID } @IBAction func save(_ sender: Any) { self.currentTreasure.itemID = item.selectedValue.scriptIndex if model.indexOfSelectedItem == 0 { self.currentTreasure.modelID = 0 } else { self.currentTreasure.modelID = model.indexOfSelectedItem == 1 ? 0x24 : 0x44 } self.currentTreasure.angle = sanitise(angle.stringValue.integerValue, bytes: 2) self.currentTreasure.quantity = sanitise(quantity.stringValue.integerValue, bytes: 1) if let val = Float(x.stringValue) { self.currentTreasure.xCoordinate = val } if let val = Float(y.stringValue) { self.currentTreasure.yCoordinate = val } if let val = Float(z.stringValue) { self.currentTreasure.zCoordinate = val } self.currentTreasure.save() self.reloadViewWithActivity() } override func viewDidLoad() { super.viewDidLoad() self.model.setTitles(values: ["-", "Chest", "Sparkle"]) self.reloadViewWithActivity() } func reloadViewWithActivity() { self.showActivityView { self.reloadView() self.hideActivityView() } } func reloadView() { self.room.select(self.currentTreasure.room ?? XGRoom(index: 0)) self.model.selectItem(at: 0) if currentTreasure.modelID == 0x24 { self.model.selectItem(at: 1) } if currentTreasure.modelID == 0x44 { self.model.selectItem(at: 2) } self.item.select(self.currentTreasure.item) self.angle.stringValue = self.currentTreasure.angle.string self.x.stringValue = self.currentTreasure.xCoordinate.string self.y.stringValue = self.currentTreasure.yCoordinate.string self.z.stringValue = self.currentTreasure.zCoordinate.string self.quantity.stringValue = self.currentTreasure.quantity.string } override func numberOfRows(in tableView: NSTableView) -> Int { return CommonIndexes.NumberTreasureBoxes.value } override func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 40 } override func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let room = XGTreasure(index: row).room?.name ?? "-" let cell = (tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) ?? GoDTableCellView(title: "", colour: GoDDesign.colourBlack(), fontSize: 12, width: widthForTable())) as! GoDTableCellView cell.setTitle(row.string + " - " + room) cell.identifier = NSUserInterfaceItemIdentifier(rawValue: "cell") cell.translatesAutoresizingMaskIntoConstraints = false let prefix = room.substring(from: 0, to: 2) let map = XGMaps(rawValue: prefix) if map == nil { cell.setBackgroundColour(GoDDesign.colourWhite().NSColour) } else { var colour = GoDDesign.colourWhite() switch map! { case .AgateVillage: colour = GoDDesign.colourGreen() case .CipherKeyLair: colour = GoDDesign.colourLightPurple() case .CitadarkIsle: colour = GoDDesign.colourPurple() case .GateonPort: colour = GoDDesign.colourBlue() case .KaminkosHouse: colour = GoDDesign.colourLightGrey() case .MtBattle: colour = GoDDesign.colourRed() case .OrreColosseum: colour = GoDDesign.colourBrown() case .OutskirtStand: colour = GoDDesign.colourOrange() case .PhenacCity: colour = GoDDesign.colourLightBlue() case .PokemonHQ: colour = GoDDesign.colourNavy() case .PyriteTown: colour = GoDDesign.colourRed() case .RealgamTower: colour = GoDDesign.colourLightGreen() case .ShadowLab: colour = GoDDesign.colourBabyPink() case .SnagemHideout: colour = GoDDesign.colourRed() case .SSLibra: colour = GoDDesign.colourLightOrange() case .Pokespot: colour = GoDDesign.colourYellow() case .TheUnder: colour = GoDDesign.colourGrey() default: colour = GoDDesign.colourWhite() } cell.setBackgroundColour(colour.NSColour) cell.setTitle(row.string + " - " + room + "\n" + map!.name) } if self.table.selectedRow == row { cell.setBackgroundColour(GoDDesign.colourOrange().NSColour) } if self.table.selectedRow == row { cell.addBorder(colour: GoDDesign.colourBlack(), width: 1) } else { cell.removeBorder() } return cell } override func tableView(_ tableView: GoDTableView, didSelectRow row: Int) { super.tableView(tableView, didSelectRow: row) if row >= 0 { self.currentTreasure = XGTreasure(index: row) } self.reloadViewWithActivity() } }
gpl-2.0
482299ffd0e56abe60f1559b91d965a9
26.756614
234
0.709493
3.380155
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ViewControllers/FeeSelector.swift
1
4453
// // FeeSelector.swift // breadwallet // // Created by Adrian Corscadden on 2017-07-20. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit //TODO:CRYPTO_V2 - these should come from BlockchainDB eventually enum FeeLevel: Int { case economy case regular case priority //Time in millis func preferredTime(forCurrency currency: Currency) -> Int { if currency.uid == Currencies.btc.uid { switch self { case .economy: return Int(C.secondsInMinute) * 60 * 7 * 1000 //7 hrs case .regular: return Int(C.secondsInMinute) * 30 * 1000 //30 mins case .priority: return Int(C.secondsInMinute) * 10 * 1000 //10 mins } } if currency.isEthereumCompatible { switch self { case .economy: return Int(C.secondsInMinute) * 5 * 1000 case .regular: return Int(C.secondsInMinute) * 3 * 1000 case .priority: return Int(C.secondsInMinute) * 1 * 1000 } } if currency.uid == "tezos-mainnet:__native__" { return 60000 } return Int(C.secondsInMinute) * 3 * 1000 // 3 mins } } class FeeSelector: UIView { init(currency: Currency) { self.currency = currency super.init(frame: .zero) setupViews() } var didUpdateFee: ((FeeLevel) -> Void)? private let currency: Currency private let topBorder = UIView(color: .secondaryShadow) private let header = UILabel(font: .customMedium(size: 16.0), color: .darkText) private let subheader = UILabel(font: .customBody(size: 14.0), color: .grayTextTint) private let warning = UILabel.wrapping(font: .customBody(size: 14.0), color: .red) private let control = UISegmentedControl(items: [S.FeeSelector.economy, S.FeeSelector.regular, S.FeeSelector.priority]) private func setupViews() { addSubview(topBorder) addSubview(control) addSubview(header) addSubview(subheader) addSubview(warning) topBorder.constrainTopCorners(height: 1.0) header.constrain([ header.leadingAnchor.constraint(equalTo: leadingAnchor, constant: C.padding[2]), header.topAnchor.constraint(equalTo: topBorder.bottomAnchor, constant: C.padding[1]) ]) subheader.constrain([ subheader.leadingAnchor.constraint(equalTo: header.leadingAnchor), subheader.topAnchor.constraint(equalTo: header.bottomAnchor) ]) warning.constrain([ warning.leadingAnchor.constraint(equalTo: subheader.leadingAnchor), warning.topAnchor.constraint(equalTo: control.bottomAnchor, constant: 4.0), warning.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -C.padding[2]), warning.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -C.padding[1])]) header.text = S.FeeSelector.title subheader.text = currency.feeText(forIndex: 1) control.constrain([ control.leadingAnchor.constraint(equalTo: warning.leadingAnchor), control.topAnchor.constraint(equalTo: subheader.bottomAnchor, constant: 4.0), control.widthAnchor.constraint(equalTo: widthAnchor, constant: -C.padding[4]) ]) control.valueChanged = strongify(self) { myself in switch myself.control.selectedSegmentIndex { case 0: myself.didUpdateFee?(.economy) myself.subheader.text = self.currency.feeText(forIndex: 0) myself.warning.text = S.FeeSelector.economyWarning case 1: myself.didUpdateFee?(.regular) myself.subheader.text = self.currency.feeText(forIndex: 1) myself.warning.text = "" case 2: myself.didUpdateFee?(.priority) myself.subheader.text = self.currency.feeText(forIndex: 2) myself.warning.text = "" default: assertionFailure("Undefined fee selection index") } } control.selectedSegmentIndex = 1 control.tintColor = .primaryButton clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
c8dffea9f07904cd0daed322139c48b9
36.1
123
0.610512
4.676471
false
false
false
false
sora0077/iTunesMusic
Demo/CustomViews/LayerDesignableView.swift
1
1004
// // LayerDesignableView.swift // iTunesMusic // // Created by 林達也 on 2016/08/30. // Copyright © 2016年 jp.sora0077. All rights reserved. // import UIKit @IBDesignable class LayerDesignableView: UIView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var shadowColor: UIColor? { didSet { layer.shadowColor = shadowColor?.cgColor } } @IBInspectable var shadowOffset: CGSize = .zero { didSet { layer.shadowOffset = shadowOffset } } @IBInspectable var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable var shadowOpacity: Float = 0 { didSet { layer.shadowOpacity = shadowOpacity layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale } } }
mit
90f5ad1f700589cc1fc60b0f4df257bc
18.509804
58
0.578894
4.925743
false
false
false
false
wangxin20111/WXWeiBo
WXWeibo/WXWeibo/Classes/Other/OAuth/WXUser.swift
1
5599
// // WXUser.swift // WXWeibo // // Created by 王鑫 on 16/7/8. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit import SVProgressHUD class WXUser: NSObject { //MARK: - 基本属性 var accessToken:String? var expiresIn:NSNumber?{ didSet{ /*这个方法主要是属性被赋值的时候会被调用 *如果是对象初始化的时候,是不会调用的,如果想被调用,要使用kvc */ expiresDate = NSDate(timeIntervalSinceNow: (expiresIn?.doubleValue)!) } } var uid:String? static var shardUser:WXUser? //保存token过期的时间 var expiresDate: NSDate? //屏幕的内容 var screenName:String? //头像大图 var avatorImage:String? //MARK: - 对外提供的对象方法 override init() { super.init() } init(dict:[String:AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } //使用kvc,undefine方法 override func setValue(value: AnyObject?, forUndefinedKey key: String) { if (key as NSString).isEqualToString("expires_in") { //过期时间 expiresIn = value as? NSNumber }else if (key as NSString).isEqualToString("access_token"){ accessToken = value as? String } } //修改复写的东西 override var description:String{ let arr = ["accessToken","expiresIn","uid"] let params = self.dictionaryWithValuesForKeys(arr) return "\(params)" } //MARK: - 对外提供的类方法 //数据本地化存储 //对外接口,保存或者获取存储的用户信息 //save class func saveUserInfo(user : WXUser) { NSKeyedArchiver.archiveRootObject(user, toFile: "https://www.wangqiujia.com/name.plist".docDir()) } //getUser,获取带有所有信息的用户模型,uid,token,name,imageURL,等 class func fetchUserInfo() -> WXUser? //因为有可能这个第一次没有数据,所以我们获取不到,就给个问号? { //因为每一次去fetchUserInfo的话,都要要去解档,虽然现在数据很快,但是还是不太好,每次都这样做,所以我们可以用两种方法处理,1.单利,2.直接给定一个属性,判断他的有无即可 if shardUser == nil { shardUser = NSKeyedUnarchiver.unarchiveObjectWithFile("https://www.wangqiujia.com/name.plist".docDir()) as? WXUser //判断,如果是shardUser.expire的过期时间没到,就返回用户,否则就返回一个nil if (shardUser?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending) {//还没过期 return shardUser } return nil } return shardUser } //获取user的imageURL,name等信息从服务器中,只有刚刚获取token的时候,才去使用这个方法获取更加全面的信息 // func loadUserDetailInfoFromNet(){ // if (accessToken! as NSString).length == 0 // { // SVProgressHUD.showErrorWithStatus("accessToken是空的", maskType: SVProgressHUDMaskType.Black) // return // } // let path = "2/users/show.json" // let params = ["access_token":accessToken!, "uid":uid!] // WXAPITool.shareNetWorkTools().GET(path, parameters: params, success: { (_, JSON) in // print(JSON) // }) { (_, error) in // print(error) // } // } func loadUserInfo(finished: (account: WXUser?, error:NSError?)->()) { assert(accessToken != nil, "没有授权") let path = "2/users/show.json" let params = ["access_token":accessToken!, "uid":uid!] WXAPITool.shareNetWorkTools().GET(path, parameters: params, success: { (_, JSON) -> Void in print(JSON) //判断字典中是否有值 if let dict = JSON as? [NSString:AnyObject] { self.screenName = dict["screen_name"] as? String self.avatorImage = dict["avatar_large"] as? String finished(account: self,error: nil) } finished(account: nil, error: nil) }) { (_, error) -> Void in SVProgressHUD.showErrorWithStatus("\(error)") finished(account: nil, error: error) } } //判断是不是已经有用户登录了 class func isLogin() -> Bool { //从本地获取对象 return (self.fetchUserInfo() != nil); } //MARK: - 私有方法 func encodeWithCoder(aCoder:NSCoder) { aCoder.encodeObject(accessToken,forKey: "accessToken") aCoder.encodeObject(expiresIn,forKey: "expiresIn") aCoder.encodeObject(uid,forKey: "uid") aCoder.encodeObject(expiresDate,forKey: "expiresDate") aCoder.encodeObject(screenName,forKey: "screenName") aCoder.encodeObject(avatorImage,forKey: "avatorImage") } //解档 init(coder deCoder:NSCoder) { accessToken = deCoder.decodeObjectForKey("accessToken") as? String expiresIn = deCoder.decodeObjectForKey("expiresIn") as? NSNumber uid = deCoder.decodeObjectForKey("uid") as? String expiresDate = deCoder.decodeObjectForKey("expiresDate") as? NSDate screenName = deCoder.decodeObjectForKey("screenName") as? String avatorImage = deCoder.decodeObjectForKey("avatorImage") as? String } }
mit
74e856b863eec3cec01ccea963dcc9f6
31.453333
126
0.596138
4.016502
false
false
false
false
mvandervelden/iOSSystemIntegrationsDemo
SearchDemo/Supporting Files/AppDelegate.swift
2
1672
import UIKit import CoreSpotlight @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var dataController : DataController! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool { dataController = DataController.sharedInstance return true } func applicationWillTerminate(application: UIApplication) { dataController.saveContext() } func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool { let navigationController = self.window?.rootViewController as! UINavigationController navigationController.popToRootViewControllerAnimated(false) guard let controller = viewControllerInStack(navigationController) else { return false } if userActivity.activityType == NSUserActivityTypeBrowsingWeb { return controller.restoreFromWeb(userActivity) } if userActivity.activityType == "com.philips.pins.SearchDemo" { return controller.restoreFromActivity(userActivity) } if userActivity.activityType == CSSearchableItemActionType { return controller.restoreFromSpotlight(userActivity) } return false } func viewControllerInStack(navigationController:UINavigationController) -> MasterViewController? { if let controller = navigationController.topViewController as? MasterViewController { return controller } return nil } }
mit
9ad1ed937efd479a1a7f96db84b33a63
34.574468
153
0.711722
6.608696
false
false
false
false
neonichu/NBMaterialDialogIOS
Example/Pods/Nimble/Nimble/Expectation.swift
2
1227
import Foundation public struct Expectation<T> { let expression: Expression<T> public func verify(pass: Bool, _ message: String) { NimbleAssertionHandler.assert(pass, message: message, location: expression.location) } public func to<U where U: Matcher, U.ValueType == T>(matcher: U) { let msg = FailureMessage() let pass = matcher.matches(expression, failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(expression.evaluate()))>" } verify(pass, msg.stringValue()) } public func toNot<U where U: Matcher, U.ValueType == T>(matcher: U) { let msg = FailureMessage() let pass = matcher.doesNotMatch(expression, failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(expression.evaluate()))>" } verify(pass, msg.stringValue()) } public func notTo<U where U: Matcher, U.ValueType == T>(matcher: U) { toNot(matcher) } // see: // - BasicMatcherWrapper for extension // - AsyncMatcherWrapper for extension // - NonNilMatcherWrapper for extension // // - NMBExpectation for Objective-C interface }
mit
decc684f71ead5c3a00619842e599e31
30.461538
92
0.621027
4.445652
false
false
false
false
yhyuan/meteor-ios
Examples/Todos/Todos/FetchedResultsTableViewDataSource.swift
8
5623
// Copyright (c) 2014-2015 Martijn Walraven // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreData @objc public protocol FetchedResultsTableViewDataSourceDelegate: NSObjectProtocol { optional func dataSource(dataSource: FetchedResultsTableViewDataSource, didFailWithError error: NSError) optional func dataSource(dataSource: FetchedResultsTableViewDataSource, cellReuseIdentifierForObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) -> String optional func dataSource(dataSource: FetchedResultsTableViewDataSource, configureCell cell: UITableViewCell, forObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) optional func dataSource(dataSource: FetchedResultsTableViewDataSource, deleteObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) } public class FetchedResultsTableViewDataSource: FetchedResultsDataSource, UITableViewDataSource { weak var tableView: UITableView! weak var delegate: FetchedResultsTableViewDataSourceDelegate? init(tableView: UITableView, fetchedResultsController: NSFetchedResultsController) { self.tableView = tableView super.init(fetchedResultsController: fetchedResultsController) } override func didFailWithError(error: NSError) { delegate?.dataSource?(self, didFailWithError: error) } // MARK: - UITableViewDataSource public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return numberOfSections } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfItemsInSection(section) } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let object = objectAtIndexPath(indexPath) let reuseIdentifier = cellReuseIdentifierForObject(object, atIndexPath: indexPath) let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UITableViewCell configureCell(cell, forObject: object, atIndexPath: indexPath) return cell } public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let object = objectAtIndexPath(indexPath) delegate?.dataSource?(self, deleteObject: object, atIndexPath: indexPath) } } // MARK: Cell Configuration func cellReuseIdentifierForObject(object: NSManagedObject, atIndexPath indexPath: NSIndexPath) -> String { return delegate?.dataSource?(self, cellReuseIdentifierForObject: object, atIndexPath: indexPath) ?? "Cell" } func configureCell(cell: UITableViewCell, forObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { delegate?.dataSource?(self, configureCell: cell, forObject: object, atIndexPath: indexPath) } // MARK: - Change Notification override func reloadData() { tableView.reloadData() } override func didChangeContent(changes: [ChangeDetail]) { // Don't perform incremental updates when the table view is not currently visible if tableView.window == nil { reloadData() return; } tableView.beginUpdates() for change in changes { switch(change) { case .SectionInserted(let sectionIndex): tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) case .SectionDeleted(let sectionIndex): tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) case .ObjectInserted(let newIndexPath): tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic) case .ObjectDeleted(let indexPath): tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) case .ObjectUpdated(let indexPath): if let cell = tableView.cellForRowAtIndexPath(indexPath) { let object = objectAtIndexPath(indexPath) configureCell(cell, forObject: object, atIndexPath: indexPath) } case .ObjectMoved(let indexPath, let newIndexPath): tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic) } } tableView.endUpdates() } // MARK: - Selection var selectedObject: NSManagedObject? { if let selectedIndexPath = tableView.indexPathForSelectedRow() { return objectAtIndexPath(selectedIndexPath) } else { return nil } } }
mit
13ad525a19a2b623d00f6b65c5b7595c
42.929688
181
0.76116
5.651256
false
false
false
false
duliodenis/cs193p-Spring-2016
democode/Pollster-L16/Pollster/QandATableViewController.swift
1
6030
// // QandATableViewController // Pollster // // Created by CS193p Instructor. // Copyright © 2016 Stanford University. All rights reserved. // import UIKit struct QandA { var question: String var answers: [String] } class QandATableViewController: TextTableViewController { // MARK: - Public API var qanda: QandA { get { var answers = [String]() if data?.count > 1 { for answer in data?.last ?? [] { if !answer.isEmpty { answers.append(answer) } } } return QandA(question: data?.first?.first ?? "", answers: answers) } set { data = [[newValue.question], newValue.answers] manageEmptyRow() } } var asking = false { didSet { if asking != oldValue { tableView.editing = asking tableView.reloadData() manageEmptyRow() } } } var answering: Bool { get { return !asking } set { asking = !newValue } } var answer: String? { didSet { var answerIndex = 0 while answerIndex < qanda.answers.count { if qanda.answers[answerIndex] == answer { let indexPath = NSIndexPath(forRow: answerIndex, inSection: Section.Answers) // be sure we're on screen before we do this (for animation, etc.) NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(chooseAnswer(_:)), userInfo: indexPath , repeats: false) break } answerIndex += 1 } } } struct Section { static let Question = 0 static let Answers = 1 } // MARK: - Private Implementation func chooseAnswer(timer: NSTimer) { if let indexPath = timer.userInfo as? NSIndexPath { if tableView.indexPathForSelectedRow != indexPath { tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .None) } } } // override this to set the UITextView up like we want // want .Body font, some margin around the text, and only editable if we are editing the Q&A override func createTextViewForIndexPath(indexPath: NSIndexPath?) -> UITextView { let textView = super.createTextViewForIndexPath(indexPath) let font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) textView.font = font.fontWithSize(font.pointSize * 1.7) textView.textContainerInset = UIEdgeInsets(top: 6, left: 10, bottom: 6, right: 10) textView.userInteractionEnabled = asking return textView } // MARK: UITableViewDataSource override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case Section.Question: return "Question" case Section.Answers: return "Answers" default: return super.tableView(tableView, titleForHeaderInSection: section) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) // only answers can be selected cell.selectionStyle = (indexPath.section == Section.Answers) ? .Gray : .None return cell } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return asking && indexPath.section == Section.Answers } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.None } override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { answer = data?[indexPath.section][indexPath.row] } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { // only answers can be selected return (indexPath.section == Section.Answers) ? indexPath : nil } // MARK: UITextViewDelegate func textViewDidEndEditing(textView: UITextView) { manageEmptyRow() } private func manageEmptyRow() { if data != nil { var emptyRow: Int? var row = 0 while row < data![Section.Answers].count { let answer = data![Section.Answers][row] if answer.isEmpty { if emptyRow != nil { data![Section.Answers].removeAtIndex(emptyRow!) tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: emptyRow!, inSection: Section.Answers)], withRowAnimation: .Automatic) emptyRow = row-1 } else { emptyRow = row row += 1 } } else { row += 1 } } if emptyRow == nil { if asking { data![Section.Answers].append("") let indexPath = NSIndexPath(forRow: data![Section.Answers].count-1, inSection: Section.Answers) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } else if !asking { data![Section.Answers].removeAtIndex(emptyRow!) tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: emptyRow!, inSection: Section.Answers)], withRowAnimation: .Automatic) } } } }
mit
7e92d0a05e48d7bc46a9d3b6b415de7d
34.464706
154
0.586664
5.451175
false
false
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Views/Food/FoodCells/FoodOptionViewCell.swift
1
4546
// // FoodOptionViewCell.swift // WeeklyFoodPlan // // Created by vulgur on 2017/2/22. // Copyright © 2017年 MAD. All rights reserved. // import UIKit protocol FoodOptionCellDelegate { func didAddOption(_ option: String) func didRemoveOption(_ option: String) } class FoodOptionViewCell: UITableViewCell { let cellIdentifier = "FoodOptionCell" let optionSelectedColor = UIColor.green let optionDeselectedColor = UIColor.white var optionTitles = ["早餐", "午餐", "晚餐"] var selectedOptions = [String]() let cellGap:CGFloat = 8 let optionHeight: CGFloat = 30 let maxOptionsInARow = 3 var delegate: FoodOptionCellDelegate? @IBOutlet var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() // Initialization code collectionView.register(UINib.init(nibName: cellIdentifier, bundle: nil), forCellWithReuseIdentifier: cellIdentifier) collectionView.allowsMultipleSelection = true collectionView.dataSource = self collectionView.delegate = self } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { collectionView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: CGFloat.leastNormalMagnitude) collectionView.layoutIfNeeded() return collectionView.collectionViewLayout.collectionViewContentSize } } extension FoodOptionViewCell: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return optionTitles.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! FoodOptionCell let title = self.optionTitles[indexPath.row] if selectedOptions.contains(title) { collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically) cell.isSelected = true cell.backgroundColor = optionSelectedColor } else { cell.backgroundColor = optionDeselectedColor } cell.optionLabel.text = title cell.layer.borderColor = optionSelectedColor.cgColor cell.layer.borderWidth = 2 cell.layer.cornerRadius = 5 return cell } } extension FoodOptionViewCell: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! FoodOptionCell cell.optionLabel.backgroundColor = optionSelectedColor delegate?.didAddOption(cell.optionLabel.text!) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! FoodOptionCell cell.optionLabel.backgroundColor = optionDeselectedColor let removedOption = optionTitles[indexPath.row] delegate?.didRemoveOption(removedOption) } } extension FoodOptionViewCell: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let screenWidth = UIScreen.main.bounds.width let count = CGFloat(maxOptionsInARow) if count > 0 { return CGSize(width: (screenWidth - cellGap * count * 2)/count, height: optionHeight) } else { return CGSize.zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 5 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(8, 8, 8, 8) } }
mit
5ea2f48e7829823a0188c2a8d76652a0
37.726496
193
0.715295
5.512165
false
false
false
false
valentin7/lifetime
Lifetime/CaptureViewController.swift
1
2397
// // CaptureViewController.swift // Lifetime // // Created by Valentin Perez on 8/14/15. // Copyright (c) 2015 Valpe Technologies. All rights reserved. // import UIKit class CaptureViewController: LTViewController, CACameraSessionDelegate { var cameraView : CameraSessionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { var offSetY : CGFloat = 0 var newFrame = CGRectMake(0, offSetY, self.view.frame.width, self.view.frame.height - offSetY) cameraView = CameraSessionView(frame: newFrame) cameraView.delegate = self self.hideButtons() UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade) // UIApplication.sharedApplication().statusBarHidden = true self.view.addSubview(cameraView) self.view.bringSubviewToFront(cameraView) } override func viewWillDisappear(animated: Bool) { } func didCaptureImage(image: UIImage!) { println("cool image: \(image)") // UIImageWriteToSavedPhotosAlbum(image, nil, "shit", ) UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil) //UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); //[self.cameraView removeFromSuperview]; } func didTapDismiss() { self.showButtons() UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade) } func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) { if error == nil { let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } else { let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } } }
mit
11cd2630060dbc8aebb2861b3b7f942c
29.341772
133
0.731331
4.663424
false
false
false
false
jonasman/TeslaSwift
Sources/TeslaSwift/Model/GuiSettings.swift
1
1820
// // GuiSettings.swift // TeslaSwift // // Created by Joao Nunes on 17/03/16. // Copyright © 2016 Joao Nunes. All rights reserved. // import Foundation open class GuiSettings: Codable { open var distanceUnits: String? open var temperatureUnits: String? open var chargeRateUnits: String? open var time24Hours: Bool? open var rangeDisplay: String? open var timeStamp: Double? enum CodingKeys: String, CodingKey { case distanceUnits = "gui_distance_units" case temperatureUnits = "gui_temperature_units" case chargeRateUnits = "gui_charge_rate_units" case time24Hours = "gui_24_hour_time" case rangeDisplay = "gui_range_display" case timeStamp = "timestamp" } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) distanceUnits = try? container.decode(String.self, forKey: .distanceUnits) temperatureUnits = try? container.decode(String.self, forKey: .temperatureUnits) chargeRateUnits = try? container.decode(String.self, forKey: .chargeRateUnits) time24Hours = try? container.decode(Bool.self, forKey: .time24Hours) rangeDisplay = try? container.decode(String.self, forKey: .rangeDisplay) timeStamp = try? container.decode(Double.self, forKey: .timeStamp) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(distanceUnits, forKey: .distanceUnits) try container.encodeIfPresent(temperatureUnits, forKey: .temperatureUnits) try container.encodeIfPresent(chargeRateUnits, forKey: .chargeRateUnits) try container.encodeIfPresent(time24Hours, forKey: .time24Hours) try container.encodeIfPresent(rangeDisplay, forKey: .rangeDisplay) try container.encodeIfPresent(timeStamp, forKey: .timeStamp) } }
mit
a5cd403928dfc3f4fc4d066fdf19107d
37.702128
82
0.764156
3.609127
false
false
false
false
sindanar/PDStrategy
Example/PDStrategy/PDStrategy/SimpleCollectionDataSource.swift
1
1812
// // SimpleCollectionController.swift // PDStrategy // // Created by Pavel Deminov on 12/11/2017. // Copyright © 2017 Pavel Deminov. All rights reserved. // import UIKit class SimpleCollectionDataSource: PDDataSource { override func setup() { let section = PDSection.instantiate() var items = [PDItem]() var item = PDItem.instantiate() item.title = "Title" item.type = StaticCellsTableType.title items.append(item) item = PDItem.instantiate() item.title = "Title" item.value = "Value" item.type = StaticCellsTableType.titleValue items.append(item) item = PDItem.instantiate() item.title = "Title2" item.value = "Value2" item.type = StaticCellsTableType.titleValue2 items.append(item) item = PDItem.instantiate() item.title = "Title" item.value = "Value" item.date = Date() item.type = StaticCellsTableType.titleValueDate items.append(item) item = PDItem.instantiate() item.title = "Title2" item.value = "Value2" item.date = Date() item.type = StaticCellsTableType.titleValueDate2 items.append(item) item = PDItem.instantiate() item.title = "Title3" item.value = "Value3" item.date = Date() item.type = StaticCellsTableType.titleValueDate3 items.append(item) item = PDItem.instantiate() item.title = "Title" item.image = #imageLiteral(resourceName: "image1") item.type = StaticCellsTableType.titleImage items.append(item) section.items = items sections = [section] } }
mit
cffce6ea577eb0cebd482ed78e6d4620
26.029851
58
0.574821
4.231308
false
false
false
false
samburnstone/SwiftStudyGroup
Advanced Swift/Collections.playground/Pages/Sequence Operations.xcplaygroundpage/Contents.swift
1
578
//: [Previous](@previous) // This NSHipster article provides a nice summary of the different Collection types in Swift: http://nshipster.com/swift-collection-protocols/ let names = ["Sam", "Andy", "Rob", "Dan"] // map let initials = names.flatMap // Using flatMap unwraps the result of `characters.first` (as its return type is optional) { $0.characters.first } initials // filter let threeLetterNames = names.filter { $0.characters.count == 3 } threeLetterNames // reduce let groupName = names.reduce("Team: ") { "\($0) \($1)" } groupName //: [Next](@next
mit
3f359acf4b3ad7dc682c472cbb8088cd
17.09375
142
0.681661
3.420118
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift
2
4249
// // CryptoSwift // // Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /// A type that supports incremental updates. For example Digest or Cipher may be updatable /// and calculate result incerementally. public protocol Updatable { /// Update given bytes in chunks. /// /// - parameter bytes: Bytes to process. /// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call. /// - returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> /// Update given bytes in chunks. /// /// - Parameters: /// - bytes: Bytes to process. /// - isLast: Indicate if given chunk is the last one. No more updates after this call. /// - output: Resulting bytes callback. /// - Returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool, output: (_ bytes: Array<UInt8>) -> Void) throws } extension Updatable { @inlinable public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: isLast) if !processed.isEmpty { output(processed) } } @inlinable public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { try self.update(withBytes: bytes, isLast: isLast) } @inlinable public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { try self.update(withBytes: bytes.slice, isLast: isLast) } @inlinable public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { try self.update(withBytes: bytes.slice, isLast: isLast, output: output) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - returns: Processed data. @inlinable public mutating func finish(withBytes bytes: ArraySlice<UInt8>) throws -> Array<UInt8> { try self.update(withBytes: bytes, isLast: true) } @inlinable public mutating func finish(withBytes bytes: Array<UInt8>) throws -> Array<UInt8> { try self.finish(withBytes: bytes.slice) } /// Finish updates. May add padding. /// /// - Returns: Processed data /// - Throws: Error @inlinable public mutating func finish() throws -> Array<UInt8> { try self.update(withBytes: [], isLast: true) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - parameter output: Resulting data /// - returns: Processed data. @inlinable public mutating func finish(withBytes bytes: ArraySlice<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: true) if !processed.isEmpty { output(processed) } } @inlinable public mutating func finish(withBytes bytes: Array<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { try self.finish(withBytes: bytes.slice, output: output) } /// Finish updates. May add padding. /// /// - Parameter output: Processed data /// - Throws: Error @inlinable public mutating func finish(output: (Array<UInt8>) -> Void) throws { try self.finish(withBytes: [], output: output) } }
mit
34d70a9d82e4f5c4ad5c81c093493f85
38.700935
217
0.703154
4.160627
false
false
false
false
Punch-In/PunchInIOSApp
PunchIn/InstructorCourseDraggableViewController.swift
1
7818
// // InstructorCourseDraggableViewController.swift // PunchIn // // Created by Nilesh Agrawal on 10/28/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit import MBProgressHUD class InstructorCourseDraggableViewController: UIViewController { // var course:Course! // var classIndex:Int! // /*Start Class*/ // @IBOutlet weak var startButton: UIButton! // @IBOutlet weak var startClassView: UIView! // @IBOutlet weak var startClassLabel: UILabel! // @IBOutlet var startClassTapGestureRecognizer: UITapGestureRecognizer! // /*Class Details*/ // //private var classIndex: Int! // private var currentClass: Class! // @IBOutlet weak var classDescription: UILabel! // @IBOutlet weak var registeredCount: UILabel! // @IBOutlet weak var attendanceCount: UILabel! // @IBOutlet weak var attendanceView: UIView! // @IBOutlet var attendanceTapGestureRecognizer: UITapGestureRecognizer! // /* Question Details */ // @IBOutlet weak var questionCount: UILabel! // @IBOutlet weak var unansweredQuestionCount: UILabel! // @IBOutlet weak var questionsView: UIView! // @IBOutlet var questionsTapGestureRecognizer: UITapGestureRecognizer! // // /* the Instructor */ // var instructor:Instructor! // // //PageController Property. // var indexNumber:Int! // // override func viewDidLoad() { // super.viewDidLoad() // self.instructor = ParseDB.currentPerson as! Instructor // // setUpUI() // setUpValues() // setUpGestures() // } // // override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { // super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // } // // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder)! // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // // func setUpValues(){ // // show current class // currentClass = course.classes![classIndex] // currentClass.refreshDetails { (error) -> Void in // if error == nil { // dispatch_async(dispatch_get_main_queue()){ // self.classDescription.text = self.currentClass.classDescription // self.attendanceCount.text = "\(self.currentClass.attendance!.count)" // self.questionCount.text = "\(self.currentClass.questions!.count)" // self.unansweredQuestionCount.text = "\(self.currentClass.questions!.filter({!$0.isAnswered}).count)" // // // set "class start" view based on class status // if self.currentClass.isFinished { // self.startClassLabel.text = Class.classFinishedText // self.startClassView.backgroundColor = UIColor.redColor() // }else if self.currentClass.isStarted { // self.startClassLabel.text = Class.classStartedText // self.startClassView.backgroundColor = UIColor.greenColor() // }else { // self.startClassLabel.text = Class.classNotStartedText // ThemeManager.theme().themeForSecondaryContentView(self.startClassView) // } // } // } // } // } // func setUpUI(){ // ThemeManager.theme().themeForContentView(attendanceView) // ThemeManager.theme().themeForContentView(questionsView) // ThemeManager.theme().themeForSecondaryContentView(startClassView) // // //Labels // // ThemeManager.theme().themeForTitleLabels(startClassLabel) // } // // func setUpGestures() { // attendanceTapGestureRecognizer.addTarget(self, action: "attendanceViewTapped") // questionsTapGestureRecognizer.addTarget(self, action: "questionsViewTapped") // startClassTapGestureRecognizer.addTarget(self, action: "startClassTapped") // } // // func attendanceViewTapped(){ // let storyBoardName = "Main" // let storyBoard = UIStoryboard.init(name: storyBoardName, bundle: nil); // let vc = storyBoard.instantiateViewControllerWithIdentifier("AttendanceCollectionViewController") as! AttendanceCollectionViewController // vc.theClass = currentClass // self.navigationController?.pushViewController(vc, animated: true) // } // // func questionsViewTapped(){ // let storyBoardName = "Main" // let storyBoard = UIStoryboard.init(name: storyBoardName, bundle: nil); // let vc = storyBoard.instantiateViewControllerWithIdentifier("QuestionsListViewController") as! QuestionsListViewController // vc.theClass = currentClass // self.navigationController?.pushViewController(vc, animated: true) // } // // // func startClassTapped() { // print("tapped start class!") // // guard !ParseDB.isStudent else { // print("students can't start a class") // let alertController = UIAlertController( // title: "StudentCantStartClass", // message: "Students can't start a class", // preferredStyle: .Alert) // // let dismissAction = UIAlertAction(title: "OK", style: .Default, handler: nil) // alertController.addAction(dismissAction) // self.presentViewController(alertController, animated: true, completion: nil) // return // } // // guard !currentClass.isFinished else { // // class already done... do nothing // return // } // // if currentClass.isStarted { // // stop class // doStopClass() // }else { // doStartClass() // } // } // // // private func doStartClass() { // // TODO: verify class can be started (time, etc) --> alert user if outside of class expected time // // TODO: verify user can start class // let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) // hud.labelText = "Starting class..." // // currentClass.start { (error) -> Void in // if error == nil { // dispatch_async(dispatch_get_main_queue()) { // MBProgressHUD.hideHUDForView(self.view, animated: true) // UIView.animateWithDuration(0.5, animations: { () -> Void in // self.startClassView.backgroundColor = UIColor.greenColor() // self.startClassLabel.text = Class.classStartedText // }) // } // }else{ // MBProgressHUD.hideHUDForView(self.view, animated: true) // print("error getting location for starting class \(error)") // } // } // } // // private func doStopClass() { // currentClass.finish() // UIView.animateWithDuration(0.5, animations: { () -> Void in // self.startClassLabel.text = Class.classFinishedText // self.startClassView.backgroundColor = UIColor.redColor() // }) // } // // // // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // // Get the new view controller using segue.destinationViewController. // // Pass the selected object to the new view controller. // if(segue.identifier == "AttedanceViewControllerSegue"){ // // var vc: // // }else if(segue.identifier == "QuestionsViewControllerSegue"){ // // } // } // }
mit
520d8184e5ddd41b58ef398bd1b636dd
38.882653
146
0.59409
4.398987
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteAuth/route.AuthLogout.swift
1
3417
import Foundation import PerfectLib import PerfectHTTP import OpenbuildExtensionCore import OpenbuildExtensionPerfect import OpenbuildMysql import OpenbuildRepository import OpenbuildRouteRegistry import OpenbuildSingleton public class RequestAuthLogout: OpenbuildExtensionPerfect.RequestProtocol { public var method: String public var uri: String public var description: String = "Allows the user to logout of the system." public var validation: OpenbuildExtensionPerfect.RequestValidation public init(method: String, uri: String){ self.method = method self.uri = uri self.validation = OpenbuildExtensionPerfect.RequestValidation() } } public let handlerRouteAuthLogout = { (request: HTTPRequest, response: HTTPResponse) in guard let handlerResponse = RouteRegistry.getHandlerResponse( uri: request.path.lowercased(), method: request.method, response: response ) else { return } do { var repository = try RepositoryAuth() guard let token = request.token else { //400 Client error handlerResponse.complete( status: 400, model: ResponseModel400Messages(messages: [ "no_token": true, "message": "token not found in header." ]) ) return } let deleted = repository.deleteToken(token: token) print("deleted: \(deleted)") if deleted == nil { handlerResponse.complete( status: 500, model: ResponseModel500Messages(messages: [ "token": "Failed to delete the token." ]) ) } else if deleted! { handlerResponse.complete( status: 200, model: ModelAuthLogout200Messages(messages: [ "logged_out": true, "message": "You have logged out of the system." ]) ) } else { //422 Unprocessable Entity handlerResponse.complete( status: 422, model: ResponseModel422( validation: request.validatedRequestData!, messages: [ "invalid_token": true, "message": "token not found." ] ) ) } } catch { print(error) handlerResponse.complete( status: 500, model: ResponseModel500Messages(messages: [ "message": "Failed to generate a successful response." ]) ) } } public class RouteAuthLogout: OpenbuildRouteRegistry.FactoryRoute { override public func route() -> NamedRoute? { let handlerResponse = ResponseDefined() handlerResponse.register(status: 200, model: "RouteAuth.ModelAuthLogout200Messages") handlerResponse.register(status: 400) handlerResponse.register(status: 422) handlerResponse.register(status: 500) return NamedRoute( handlerRequest: RequestAuthLogout( method: "delete", uri: "/api/auth/login" ), handlerResponse: handlerResponse, handlerRoute: handlerRouteAuthLogout ) } }
gpl-2.0
76cd58dd10972b8e17964584e2ef5b52
24.893939
92
0.56892
5.38959
false
false
false
false
brentsimmons/Evergreen
ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift
1
9017
// // StatusesTable.swift // NetNewsWire // // Created by Brent Simmons on 5/8/16. // Copyright © 2016 Ranchero Software, LLC. All rights reserved. // import Foundation import RSCore import RSDatabase import RSDatabaseObjC import Articles // Article->ArticleStatus is a to-one relationship. // // CREATE TABLE if not EXISTS statuses (articleID TEXT NOT NULL PRIMARY KEY, read BOOL NOT NULL DEFAULT 0, starred BOOL NOT NULL DEFAULT 0, dateArrived DATE NOT NULL DEFAULT 0); final class StatusesTable: DatabaseTable { let name = DatabaseTableName.statuses private let cache = StatusCache() private let queue: DatabaseQueue init(queue: DatabaseQueue) { self.queue = queue } // MARK: - Creating/Updating func ensureStatusesForArticleIDs(_ articleIDs: Set<String>, _ read: Bool, _ database: FMDatabase) -> ([String: ArticleStatus], Set<String>) { #if DEBUG // Check for missing statuses — this asserts that all the passed-in articleIDs exist in the statuses table. defer { if let resultSet = self.selectRowsWhere(key: DatabaseKey.articleID, inValues: Array(articleIDs), in: database) { let fetchedStatuses = resultSet.mapToSet(statusWithRow) let fetchedArticleIDs = Set(fetchedStatuses.map{ $0.articleID }) assert(fetchedArticleIDs == articleIDs) } } #endif // Check cache. let articleIDsMissingCachedStatus = articleIDsWithNoCachedStatus(articleIDs) if articleIDsMissingCachedStatus.isEmpty { return (statusesDictionary(articleIDs), Set<String>()) } // Check database. fetchAndCacheStatusesForArticleIDs(articleIDsMissingCachedStatus, database) let articleIDsNeedingStatus = self.articleIDsWithNoCachedStatus(articleIDs) if !articleIDsNeedingStatus.isEmpty { // Create new statuses. self.createAndSaveStatusesForArticleIDs(articleIDsNeedingStatus, read, database) } return (statusesDictionary(articleIDs), articleIDsNeedingStatus) } // MARK: - Marking @discardableResult func mark(_ statuses: Set<ArticleStatus>, _ statusKey: ArticleStatus.Key, _ flag: Bool, _ database: FMDatabase) -> Set<ArticleStatus>? { // Sets flag in both memory and in database. var updatedStatuses = Set<ArticleStatus>() for status in statuses { if status.boolStatus(forKey: statusKey) == flag { continue } status.setBoolStatus(flag, forKey: statusKey) updatedStatuses.insert(status) } if updatedStatuses.isEmpty { return nil } let articleIDs = updatedStatuses.articleIDs() self.markArticleIDs(articleIDs, statusKey, flag, database) return updatedStatuses } func markAndFetchNew(_ articleIDs: Set<String>, _ statusKey: ArticleStatus.Key, _ flag: Bool, _ database: FMDatabase) -> Set<String> { let (statusesDictionary, newStatusIDs) = ensureStatusesForArticleIDs(articleIDs, flag, database) let statuses = Set(statusesDictionary.values) mark(statuses, statusKey, flag, database) return newStatusIDs } // MARK: - Fetching func fetchUnreadArticleIDs() throws -> Set<String> { return try fetchArticleIDs("select articleID from statuses where read=0;") } func fetchStarredArticleIDs() throws -> Set<String> { return try fetchArticleIDs("select articleID from statuses where starred=1;") } func fetchArticleIDsAsync(_ statusKey: ArticleStatus.Key, _ value: Bool, _ completion: @escaping ArticleIDsCompletionBlock) { queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { var sql = "select articleID from statuses where \(statusKey.rawValue)=" sql += value ? "1" : "0" sql += ";" guard let resultSet = database.executeQuery(sql, withArgumentsIn: nil) else { DispatchQueue.main.async { completion(.success(Set<String>())) } return } let articleIDs = resultSet.mapToSet{ $0.string(forColumnIndex: 0) } DispatchQueue.main.async { completion(.success(articleIDs)) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func fetchArticleIDsForStatusesWithoutArticlesNewerThan(_ cutoffDate: Date, _ completion: @escaping ArticleIDsCompletionBlock) { queue.runInDatabase { databaseResult in var error: DatabaseError? var articleIDs = Set<String>() func makeDatabaseCall(_ database: FMDatabase) { let sql = "select articleID from statuses s where (starred=1 or dateArrived>?) and not exists (select 1 from articles a where a.articleID = s.articleID);" if let resultSet = database.executeQuery(sql, withArgumentsIn: [cutoffDate]) { articleIDs = resultSet.mapToSet(self.articleIDWithRow) } } switch databaseResult { case .success(let database): makeDatabaseCall(database) case .failure(let databaseError): error = databaseError } if let error = error { DispatchQueue.main.async { completion(.failure(error)) } } else { DispatchQueue.main.async { completion(.success(articleIDs)) } } } } func fetchArticleIDs(_ sql: String) throws -> Set<String> { var error: DatabaseError? var articleIDs = Set<String>() queue.runInDatabaseSync { databaseResult in switch databaseResult { case .success(let database): if let resultSet = database.executeQuery(sql, withArgumentsIn: nil) { articleIDs = resultSet.mapToSet(self.articleIDWithRow) } case .failure(let databaseError): error = databaseError } } if let error = error { throw(error) } return articleIDs } func articleIDWithRow(_ row: FMResultSet) -> String? { return row.string(forColumn: DatabaseKey.articleID) } func statusWithRow(_ row: FMResultSet) -> ArticleStatus? { guard let articleID = row.string(forColumn: DatabaseKey.articleID) else { return nil } return statusWithRow(row, articleID: articleID) } func statusWithRow(_ row: FMResultSet, articleID: String) ->ArticleStatus? { if let cachedStatus = cache[articleID] { return cachedStatus } guard let dateArrived = row.date(forColumn: DatabaseKey.dateArrived) else { return nil } let articleStatus = ArticleStatus(articleID: articleID, dateArrived: dateArrived, row: row) cache.addStatusIfNotCached(articleStatus) return articleStatus } func statusesDictionary(_ articleIDs: Set<String>) -> [String: ArticleStatus] { var d = [String: ArticleStatus]() for articleID in articleIDs { if let articleStatus = cache[articleID] { d[articleID] = articleStatus } } return d } // MARK: - Cleanup func removeStatuses(_ articleIDs: Set<String>, _ database: FMDatabase) { deleteRowsWhere(key: DatabaseKey.articleID, equalsAnyValue: Array(articleIDs), in: database) } } // MARK: - Private private extension StatusesTable { // MARK: - Cache func articleIDsWithNoCachedStatus(_ articleIDs: Set<String>) -> Set<String> { return Set(articleIDs.filter { cache[$0] == nil }) } // MARK: - Creating func saveStatuses(_ statuses: Set<ArticleStatus>, _ database: FMDatabase) { let statusArray = statuses.map { $0.databaseDictionary()! } self.insertRows(statusArray, insertType: .orIgnore, in: database) } func createAndSaveStatusesForArticleIDs(_ articleIDs: Set<String>, _ read: Bool, _ database: FMDatabase) { let now = Date() let statuses = Set(articleIDs.map { ArticleStatus(articleID: $0, read: read, dateArrived: now) }) cache.addIfNotCached(statuses) saveStatuses(statuses, database) } func fetchAndCacheStatusesForArticleIDs(_ articleIDs: Set<String>, _ database: FMDatabase) { guard let resultSet = self.selectRowsWhere(key: DatabaseKey.articleID, inValues: Array(articleIDs), in: database) else { return } let statuses = resultSet.mapToSet(self.statusWithRow) self.cache.addIfNotCached(statuses) } // MARK: - Marking func markArticleIDs(_ articleIDs: Set<String>, _ statusKey: ArticleStatus.Key, _ flag: Bool, _ database: FMDatabase) { updateRowsWithValue(NSNumber(value: flag), valueKey: statusKey.rawValue, whereKey: DatabaseKey.articleID, matches: Array(articleIDs), database: database) } } // MARK: - private final class StatusCache { // Serial database queue only. var dictionary = [String: ArticleStatus]() var cachedStatuses: Set<ArticleStatus> { return Set(dictionary.values) } func add(_ statuses: Set<ArticleStatus>) { // Replaces any cached statuses. for status in statuses { self[status.articleID] = status } } func addStatusIfNotCached(_ status: ArticleStatus) { addIfNotCached(Set([status])) } func addIfNotCached(_ statuses: Set<ArticleStatus>) { // Does not replace already cached statuses. for status in statuses { let articleID = status.articleID if let _ = self[articleID] { continue } self[articleID] = status } } subscript(_ articleID: String) -> ArticleStatus? { get { return dictionary[articleID] } set { dictionary[articleID] = newValue } } }
mit
3429d1741e4fcd75b9b48f63df6c56c9
27.165625
177
0.719516
3.74294
false
false
false
false