repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
srn214/Floral
Floral/Floral/Classes/Module/Community(研究院)/Controller/Other/LDRecommendMoreController.swift
1
3044
// // LDRecommendMoreController.swift // Floral // // Created by LDD on 2019/7/21. // Copyright © 2019 文刂Rn. All rights reserved. // import UIKit import RxCocoa import Differentiator import RxDataSources class LDRecommendMoreController: CollectionViewController<LDRecommendMoreVM> { let typeId = BehaviorRelay<String>(value: "") override func viewDidLoad() { super.viewDidLoad() } override func setupUI() { super.setupUI() collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: k_Margin_Fifteen, right: 0) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(cellWithClass: LDRecommendCell.self) collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: LDRecommendReusableView.self) collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: LDRecommendBannerReusableView.self) collectionView.refreshHeader = RefreshNormalHeader() collectionView.refreshFooter = RefreshFooter() beginHeaderRefresh() } override func bindVM() { super.bindVM() //设置代理 collectionView.rx.setDelegate(self) .disposed(by: rx.disposeBag) let input = LDRecommendMoreVM.Input(typeId: typeId.value) let output = viewModel.transform(input: input) output.items.drive(collectionView.rx.items) { (cv, row, item) in let cell = cv.dequeueReusableCell(withClass: LDRecommendCell.self, for: IndexPath(item: row, section: 0)) cell.info = (item.title, item.teacher, item.imgUrl) return cell } .disposed(by: rx.disposeBag) } } extension LDRecommendMoreController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let row: CGFloat = 3 let w = Int((ScreenWidth - autoDistance(5) * (row - 1)) / row) return CGSize(width: CGFloat(w), height: autoDistance(200)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return k_Margin_Fifteen } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return autoDistance(5) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: ScreenWidth, height: k_Margin_Fifteen) } }
mit
a62d6e93a1a2844aa84dfe23fb2a89ea
33.443182
175
0.677994
5.471119
false
false
false
false
carabina/GRDB.swift
GRDB Tests/Public/Core/Row/MetalRowTests.swift
1
8846
import XCTest import GRDB class MetalRowTests: GRDBTestCase { func testRowAsSequence() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)") try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)") var rowFetched = false for row in Row.fetch(db, "SELECT * FROM ints") { rowFetched = true var columnNames = [String]() var ints = [Int]() var bools = [Bool]() for (columnName, databaseValue) in row { columnNames.append(columnName) ints.append(databaseValue.value()! as Int) bools.append(databaseValue.value()! as Bool) } XCTAssertEqual(columnNames, ["a", "b", "c"]) XCTAssertEqual(ints, [0, 1, 2]) XCTAssertEqual(bools, [false, true, true]) } XCTAssertTrue(rowFetched) } } } func testRowValueAtIndex() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)") try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)") var rowFetched = false for row in Row.fetch(db, "SELECT * FROM ints") { rowFetched = true // Int extraction, form 1 XCTAssertEqual(row.value(atIndex: 0) as Int, 0) XCTAssertEqual(row.value(atIndex: 1) as Int, 1) XCTAssertEqual(row.value(atIndex: 2) as Int, 2) // Int extraction, form 2 XCTAssertEqual(row.value(atIndex: 0)! as Int, 0) XCTAssertEqual(row.value(atIndex: 1)! as Int, 1) XCTAssertEqual(row.value(atIndex: 2)! as Int, 2) // Int? extraction XCTAssertEqual((row.value(atIndex: 0) as Int?), 0) XCTAssertEqual((row.value(atIndex: 1) as Int?), 1) XCTAssertEqual((row.value(atIndex: 2) as Int?), 2) // Bool extraction, form 1 XCTAssertEqual(row.value(atIndex: 0) as Bool, false) XCTAssertEqual(row.value(atIndex: 1) as Bool, true) XCTAssertEqual(row.value(atIndex: 2) as Bool, true) // Bool extraction, form 2 XCTAssertEqual(row.value(atIndex: 0)! as Bool, false) XCTAssertEqual(row.value(atIndex: 1)! as Bool, true) XCTAssertEqual(row.value(atIndex: 2)! as Bool, true) // Bool? extraction XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) XCTAssertEqual((row.value(atIndex: 1) as Bool?), true) XCTAssertEqual((row.value(atIndex: 2) as Bool?), true) // Expect fatal error: // // row.value(atIndex: -1) // row.value(atIndex: 3) } XCTAssertTrue(rowFetched) } } } func testRowValueNamed() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)") try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)") var rowFetched = false for row in Row.fetch(db, "SELECT * FROM ints") { rowFetched = true // Int extraction, form 1 XCTAssertEqual(row.value(named: "a") as Int, 0) XCTAssertEqual(row.value(named: "b") as Int, 1) XCTAssertEqual(row.value(named: "c") as Int, 2) // Int extraction, form 2 XCTAssertEqual(row.value(named: "a")! as Int, 0) XCTAssertEqual(row.value(named: "b")! as Int, 1) XCTAssertEqual(row.value(named: "c")! as Int, 2) // Int? extraction XCTAssertEqual((row.value(named: "a") as Int?)!, 0) XCTAssertEqual((row.value(named: "b") as Int?)!, 1) XCTAssertEqual((row.value(named: "c") as Int?)!, 2) // Bool extraction, form 1 XCTAssertEqual(row.value(named: "a") as Bool, false) XCTAssertEqual(row.value(named: "b") as Bool, true) XCTAssertEqual(row.value(named: "c") as Bool, true) // Bool extraction, form 2 XCTAssertEqual(row.value(named: "a")! as Bool, false) XCTAssertEqual(row.value(named: "b")! as Bool, true) XCTAssertEqual(row.value(named: "c")! as Bool, true) // Bool? extraction XCTAssertEqual((row.value(named: "a") as Bool?)!, false) XCTAssertEqual((row.value(named: "b") as Bool?)!, true) XCTAssertEqual((row.value(named: "c") as Bool?)!, true) // Expect fatal error: // row.value(named: "foo") // row.value(named: "foo") as Int? } XCTAssertTrue(rowFetched) } } } func testRowCount() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)") try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)") var rowFetched = false for row in Row.fetch(db, "SELECT * FROM ints") { rowFetched = true XCTAssertEqual(row.count, 3) } XCTAssertTrue(rowFetched) } } } func testRowColumnNames() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)") try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)") var rowFetched = false for row in Row.fetch(db, "SELECT a, b, c FROM ints") { rowFetched = true XCTAssertEqual(Array(row.columnNames), ["a", "b", "c"]) } XCTAssertTrue(rowFetched) } } } func testRowDatabaseValues() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)") try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)") var rowFetched = false for row in Row.fetch(db, "SELECT a, b, c FROM ints") { rowFetched = true XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue, 2.databaseValue]) } XCTAssertTrue(rowFetched) } } } func testRowSubscriptIsCaseInsensitive() { assertNoError { let dbQueue = DatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE stuffs (name TEXT)") try db.execute("INSERT INTO stuffs (name) VALUES ('foo')") var rowFetched = false for row in Row.fetch(db, "SELECT nAmE FROM stuffs") { rowFetched = true XCTAssertEqual(row["name"], "foo".databaseValue) XCTAssertEqual(row["NAME"], "foo".databaseValue) XCTAssertEqual(row["NaMe"], "foo".databaseValue) XCTAssertEqual(row.value(named: "name")! as String, "foo") XCTAssertEqual(row.value(named: "NAME")! as String, "foo") XCTAssertEqual(row.value(named: "NaMe")! as String, "foo") } XCTAssertTrue(rowFetched) } } } }
mit
871670a332931e9da885363b2bc7b6e5
43.23
114
0.46733
5.028994
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/SnapKit/Example-iOS/AppDelegate.swift
17
867
// // AppDelegate.swift // Example-iOS // // Created by Spiros Gerokostas on 01/03/16. // Copyright © 2016 SnapKit Team. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let listViewController:ListViewController = ListViewController() let navigationController:UINavigationController = UINavigationController(rootViewController: listViewController); self.window!.rootViewController = navigationController; self.window!.backgroundColor = UIColor.white self.window!.makeKeyAndVisible() return true } }
mit
b0e52f97162b66479afc9bcb3875c4dd
27.9
144
0.730947
5.660131
false
false
false
false
HYT2016/app
test/WrongVC.swift
1
8579
// // WrongVC.swift // test // // Created by ios135 on 2017/7/25. // Copyright © 2017年 Root HSZ HSU. All rights reserved. // import UIKit class WrongVC: UIViewController,UITableViewDataSource,UITableViewDelegate { var q_category:String? var wrongQFileName:[String]=[] var wrongQIndex:[String]=[] var wrongTableViewQfileNameIndex:String="" var wrongTableViewIndex:String="" var doctor:[String]=[] var dentist:[String]=[] var WrongDoctorSet=Set<String>() var WrongDentistSet=Set<String>() var wrongQfile:String="" var QuesAnum=1 var ansStr = "" @IBOutlet weak var wrongTableView: UITableView! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return wrongQFileName.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) cell.textLabel?.textColor = UIColor.black // cell字體大小 cell.textLabel?.font = UIFont(name:"Avenir", size:22) cell.textLabel?.text="第"+String(indexPath.row+1)+"題:"+wrongQFileName[indexPath.row]+"-"+wrongQIndex[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(indexPath.row) QuesAnum=Int(wrongQIndex[indexPath.row])! let vc = self.storyboard?.instantiateViewController(withIdentifier: "gameStartVC2") as! gameStartVC2 vc.isWrongQuestion=true vc.wrongQFileName=self.wrongQFileName vc.wrongQIndex=self.wrongQIndex // vc.wrongTableViewQfileNameIndex=wrongQFileName[indexPath.row] wrongTableViewQfileNameIndex=wrongQFileName[indexPath.row] vc.wrongTableViewQfileNameIndex=wrongTableViewQfileNameIndex // vc.wrongTableViewIndex=wrongQIndex[indexPath.row] wrongTableViewIndex=wrongQIndex[indexPath.row] vc.wrongTableViewIndex=wrongTableViewIndex vc.wrongTableViewCellName="第"+String(indexPath.row+1)+"題:"+wrongQFileName[indexPath.row]+"-"+wrongQIndex[indexPath.row] vc.indexPath_row=indexPath.row+1 vc.indexPath_max=wrongQFileName.count vc.doctor=self.doctor vc.dentist=self.dentist self.navigationController?.pushViewController(vc, animated: true) } //If you want to change title func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Delete" } // 做刪除動作 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete{ print("wrongQFileName 1:\(wrongQFileName)") print("wrongQIndex 1:\(wrongQIndex)") // print("wrongTableViewQfileNameIndex 1:\(wrongTableViewQfileNameIndex)") // WrongDoctorSet.remove("\(wrongQFileName[indexPath.row]):\(wrongQIndex[indexPath.row])\n") // print("WrongDoctorSet:\(wrongQFileName)") wrongQFileName.remove(at: indexPath.row) wrongQIndex.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) print("wrongQFileName 2:\(wrongQFileName)") print("wrongQIndex 2:\(wrongQIndex)") // // 發送方 // let notificationName3 = Notification.Name("updateItQ") // NotificationCenter.default.post(name: notificationName3, object: nil, userInfo: ["PASS": wrongQFileName]) // let notificationName2 = Notification.Name("updateIt") // NotificationCenter.default.post(name: notificationName2, object: nil, userInfo: ["PASS":wrongQIndex]) removeData() copyit() } } override func viewDidLoad() { super.viewDidLoad() // 讓tableViewCell填滿tableView self.view.layoutIfNeeded() self.parseTxtFile() // print("wrongQFileName.count:\(wrongQFileName.count)") // print("wrongQFileName:\(wrongQFileName)") wrongTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func parseTxtFile(){ var tmpStr="" let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first! let file:URL if self.q_category == "醫學國考-答錯題目"{ file = dir.appendingPathComponent("doctorAns.txt") print(file) do { let text2 = try String(contentsOf: file, encoding:String.Encoding.utf8) tmpStr = text2 } catch {/* error handling here */} }else if self.q_category == "牙醫國考-答錯題目"{ file = dir.appendingPathComponent("dentistAns.txt") do { let text2 = try String(contentsOf: file, encoding:String.Encoding.utf8) tmpStr = text2 } catch {/* error handling here */} } var strArys=tmpStr.components(separatedBy: "\n") strArys.removeLast() for str in strArys{ wrongQfile=str let eachStr = str.components(separatedBy: ":") self.wrongQFileName.append(eachStr[0]) self.wrongQIndex.append(eachStr[1]) } } // 刪除"整個"txt檔 func removeData(){ // Fine documents directory on device let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first! if self.q_category == doctor[0]{ ansStr = "doctorAns.txt" }else if self.q_category == dentist[0]{ ansStr = "dentistANS.txt" } let fileurl = dir.appendingPathComponent(ansStr) print("remove:\(fileurl)") do { let fileManager = FileManager.default // Check if file exists if fileManager.fileExists(atPath: fileurl.path) { // Delete file try fileManager.removeItem(atPath: fileurl.path) } else { print("File does not exist") } } catch let error as NSError { print("An error took place: \(error)") } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if (indexPath.row % 2 == 0) { cell.backgroundColor=UIColor.white } else { cell.backgroundColor=UIColor(red: 204/255, green: 255/255, blue: 255/255, alpha: 0.5) } } override func viewWillAppear(_ animated: Bool) { self.wrongTableView.reloadData() } // 檔案被刪除後重建 func copyit() { let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first! if self.q_category == doctor[0]{ ansStr = "doctorAns.txt" }else if self.q_category == dentist[0]{ ansStr = "dentistAns.txt" } let fileurl = dir.appendingPathComponent(ansStr) print(fileurl) for i in 0...wrongQFileName.count-1 { let string = "\(wrongQFileName[i]):\(wrongQIndex[i])\n" let data = string.data(using: .utf8, allowLossyConversion: false)! if FileManager.default.fileExists(atPath: fileurl.path) { if let fileHandle = try? FileHandle(forUpdating: fileurl) { fileHandle.seekToEndOfFile() fileHandle.write(data) fileHandle.closeFile() } } else { try! data.write(to: fileurl, options: Data.WritingOptions.atomic) } } } }
mit
1328c851a320a0248908debb909ad4dd
34.170124
156
0.594738
4.564351
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/OrderFinancialStatus.swift
1
1870
// // OrderFinancialStatus.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Represents the order's current financial status. public enum OrderFinancialStatus: String { /// Displayed as **Authorized**. case authorized = "AUTHORIZED" /// Displayed as **Paid**. case paid = "PAID" /// Displayed as **Partially paid**. case partiallyPaid = "PARTIALLY_PAID" /// Displayed as **Partially refunded**. case partiallyRefunded = "PARTIALLY_REFUNDED" /// Displayed as **Pending**. case pending = "PENDING" /// Displayed as **Refunded**. case refunded = "REFUNDED" /// Displayed as **Voided**. case voided = "VOIDED" case unknownValue = "" } }
mit
b5f2e530b5a17d9d65f8d28d9e8b24b5
33
81
0.716043
4.030172
false
false
false
false
ankitthakur/SHSwiftKit
Sources/Shared/ErrorDomains.swift
1
429
// // ErrorDomains.swift // SHSwiftKit // // Created by Ankit Thakur on 06/03/16. // Copyright © 2016 Ankit Thakur. All rights reserved. // import Foundation let FILEMANAGER_ERROR_DOMAIN = "FileManager" ///// error codes // FILE MANAGER 12XX let FILE_NOT_FOUND = 1200 let APPS_NOT_FOUND = 1201 let EXCEPTION_THROWNN_FOUND = 1202 let FILE_NOT_FOUND_MESSAGE = "File not found" let APPS_NOT_FOUND_MESSAGE = "No App found"
mit
19ba199c613b8398ff576f31dbddf7ad
19.380952
55
0.712617
3.124088
false
false
false
false
grafiti-io/SwiftCharts
SwiftCharts/AxisValues/ChartAxisValueFloat.swift
2
1203
// // ChartAxisValueFloat.swift // swift_charts // // Created by ischuetz on 15/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit @available(*, deprecated: 0.2.5, message: "use ChartAxisValueDouble instead") open class ChartAxisValueFloat: ChartAxisValue { open let formatter: NumberFormatter open var float: CGFloat { return CGFloat(scalar) } public init(_ float: CGFloat, formatter: NumberFormatter = ChartAxisValueFloat.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.formatter = formatter super.init(scalar: Double(float), labelSettings: labelSettings) } override open func copy(_ scalar: Double) -> ChartAxisValueFloat { return ChartAxisValueFloat(CGFloat(scalar), formatter: formatter, labelSettings: labelSettings) } static var defaultFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.maximumFractionDigits = 2 return formatter }() // MARK: CustomStringConvertible override open var description: String { return formatter.string(from: NSNumber(value: Float(float)))! } }
apache-2.0
0e082796d39a6382c79daed87aa0746c
29.075
160
0.698254
5.16309
false
false
false
false
davidozhang/spycodes
Spycodes/Managers/SCGameSettingsManager.swift
1
1463
class SCGameSettingsManager: SCLogger { static let instance = SCGameSettingsManager() enum GameSettingType: Int { case minigame = 0 case validateClues = 1 } fileprivate var gameSettings = [SCGameSettingType: Bool]() override init() { super.init() self.reset() } override func getIdentifier() -> String? { return SCConstants.loggingIdentifier.gameSettingsManager.rawValue } // MARK: Public func enableGameSetting(_ type: SCGameSettingType, enabled: Bool) { if self.gameSettings[type] == enabled { return } self.gameSettings[type] = enabled if type == .minigame { if enabled { GameMode.instance.setMode(mode: .miniGame) } else { GameMode.instance.setMode(mode: .regularGame) } } super.log("Game settings changed.") } func isGameSettingEnabled(_ type: SCGameSettingType) -> Bool { if type == .minigame { return GameMode.instance.getMode() == GameMode.Mode.miniGame } if let setting = self.gameSettings[type] { return setting } return false } func reset() { for key in self.gameSettings.keys { self.gameSettings[key] = false } GameMode.instance.setMode(mode: .regularGame) } }
mit
7b7063763b1632190a10e404b2237638
23.79661
73
0.555707
4.586207
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/arithmetic-slices-ii-subsequence.swift
2
2495
/** * https://leetcode.com/problems/arithmetic-slices-ii-subsequence/ * * https://discuss.leetcode.com/topic/67413/detailed-explanation-for-java-o-n-2-solution * This article shows the idea of generalized sequence with two elements only. * * https://discuss.leetcode.com/topic/66566/can-anyone-explain-the-algorithm-in-words/2 * This article cleared all the confusion about the generalized sequence idea. */ class Solution { func numberOfArithmeticSlices(_ A: [Int]) -> Int { let n = A.count guard n>=3 else {return 0} // build dictionary for i, of number of sequences // (including length 2) end at i var mark = Array(repeating: [Int : Int](), count: n) var total = 0 for i in 1..<n { for j in 0..<i { // use all j < i to update mark[i][diff] // the number of sequences end at i with distance dist // add the number of sequences of all dist to ans let diff = A[i] - A[j] if let _ = mark[i][diff] {} else {mark[i][diff] = 0} if let _ = mark[j][diff] {} else {mark[j][diff] = 0} // Add elements i to the sequence, // Add (A[j], A[i]) as part of solution. let s = 1 + mark[j][diff]! mark[i][diff] = s + mark[i][diff]! total += s } // print("\(A[i]) : \(mark[i])") // remove the length 2 sequences // (A[j], A[i]) for all the j (0...i-1) smaller than i. total -= i } return total } } print("\(numberOfArithmeticSlices([2,2,3,4]))") //print("\(numberOfArithmeticSlices([1,2,3,4]))") //print("\(numberOfArithmeticSlices([2,4,6,8,10]))") /** * https://leetcode.com/problems/arithmetic-slices-ii-subsequence/ * * */ // Date: Sat Sep 11 01:10:39 PDT 2021 class Solution { func numberOfArithmeticSlices(_ nums: [Int]) -> Int { let n = nums.count var dp = Array(repeating: [Int : Int](), count: n) var result = 0 for end in stride(from: 1, to: n, by: 1) { for start in stride(from: 0, to: end, by: 1) { let diff = nums[end] - nums[start] if let x = dp[start][diff] { result += x } dp[end][diff, default: 0] += dp[start][diff, default: 0] + 1 } } return result } }
mit
508786b333f6bca1d6a65a6be7c8394a
35.705882
88
0.516232
3.729447
false
false
false
false
bsmith11/ScoreReporter
ScoreReporter/Controllers/NavigationButton.swift
1
1613
// // NavigationButton.swift // ScoreReporter // // Created by Bradley Smith on 11/1/16. // Copyright © 2016 Brad Smith. All rights reserved. // import UIKit enum NavigationButtonPosition { case left case right } class NavigationButton: UIButton { init?(viewController: UIViewController, position: NavigationButtonPosition) { let item: UIBarButtonItem? switch position { case .left: item = viewController.navigationItem.leftBarButtonItem case .right: item = viewController.navigationItem.rightBarButtonItem } guard let barButtonItem = item else { return nil } super.init(frame: .zero) if let image = barButtonItem.image { setImage(image, for: .normal) contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 11.0, bottom: 0.0, right: 11.0) tintColor = barButtonItem.tintColor ?? viewController.navigationController?.navigationBar.tintColor } else if let title = barButtonItem.title { let attributes = barButtonItem.titleTextAttributes(for: .normal) let attributedTitle = NSAttributedString(string: title, attributes: attributes) setAttributedTitle(attributedTitle, for: .normal) } sizeToFit() let width = bounds.width let height = CGFloat(30.0) let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height) self.frame = frame } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
eeb5f0fc2933ff747011da1d37997746
28.309091
111
0.635236
4.769231
false
false
false
false
northwoodspd/FluentConstraints
FluentConstraints/FluentConstraintSet.swift
1
3748
// // FluentConstraintSet.swift // FluentConstraints // // Created by Steve Madsen on 6/26/15. // Copyright (c) 2015 Northwoods Consulting Partners. All rights reserved. // import Foundation open class FluentConstraintSet { var firstView: UIView var constraints: [FluentConstraint] = [] public init(_ view: UIView) { self.firstView = view } open func build() -> [NSLayoutConstraint] { return constraints.map { $0.build() } } open func activate() -> [NSLayoutConstraint] { let constraints = build() NSLayoutConstraint.activate(constraints) return constraints } // MARK: relationship to view open var inSuperview: FluentConstraintSet { precondition(self.firstView.superview != nil, "View does not have a superview") self.constraints.forEach { $0.secondView = self.firstView.superview! } return self } open func onView(_ view: UIView) -> FluentConstraintSet { self.constraints.forEach { $0.secondView = view } return self } open func asView(_ view: UIView) -> FluentConstraintSet { return onView(view) } // MARK: internal helpers func fluentConstraintForView(_ view: UIView, attribute: NSLayoutConstraint.Attribute, constant: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> FluentConstraint { let constraint = FluentConstraint(view) constraint.firstAttribute = attribute constraint.relation = relation constraint.secondAttribute = attribute constraint.constant = constant return constraint } // MARK: builds collections of fluent constraints open var centered: FluentConstraintSet { constraints.append(fluentConstraintForView(self.firstView, attribute: .centerX)) constraints.append(fluentConstraintForView(self.firstView, attribute: .centerY)) return self } open var sameSize: FluentConstraintSet { constraints.append(fluentConstraintForView(self.firstView, attribute: .width)) constraints.append(fluentConstraintForView(self.firstView, attribute: .height)) return self } open func inset(_ insets: UIEdgeInsets) -> FluentConstraintSet { constraints.append(fluentConstraintForView(self.firstView, attribute: .left, constant: insets.left)) constraints.append(fluentConstraintForView(self.firstView, attribute: .right, constant: -insets.right)) constraints.append(fluentConstraintForView(self.firstView, attribute: .top, constant: insets.top)) constraints.append(fluentConstraintForView(self.firstView, attribute: .bottom, constant: -insets.bottom)) return self } open func inset(_ constant: CGFloat) -> FluentConstraintSet { return inset(UIEdgeInsets(top: constant, left: constant, bottom: constant, right: constant)) } open func insetAtLeast(_ insets: UIEdgeInsets) -> FluentConstraintSet { constraints.append(fluentConstraintForView(self.firstView, attribute: .left, constant: insets.left, relation: .greaterThanOrEqual)) constraints.append(fluentConstraintForView(self.firstView, attribute: .right, constant: -insets.right, relation: .lessThanOrEqual)) constraints.append(fluentConstraintForView(self.firstView, attribute: .top, constant: insets.top, relation: .greaterThanOrEqual)) constraints.append(fluentConstraintForView(self.firstView, attribute: .bottom, constant: -insets.bottom, relation: .lessThanOrEqual)) return self } open func insetAtLeast(_ constant: CGFloat) -> FluentConstraintSet { return insetAtLeast(UIEdgeInsets(top: constant, left: constant, bottom: constant, right: constant)) } }
mit
4e57659e8d9902e1b044430721e7e063
37.639175
182
0.705977
4.756345
false
false
false
false
tullie/CareerCupAPI
CCQuestionsSearch.swift
1
3903
// // QuestionsSearch.swift // AlgorithmMatch // // Created by Tullie on 24/03/2015. // Copyright (c) 2015 Tullie. All rights reserved. // import UIKit class CCQuestionsSearch: NSObject { // Retrieves all recently added interview questions func loadRecentQuestions(page: UInt, companyID: String?, job: String?, topic: String?) -> [CCQuestion] { var questions: [CCQuestion] = [] let questionsURLString = buildQuestionsURLString(page, company: companyID, job: job, topic: topic) let questionsURL = NSURL(string: questionsURLString) // Ensure CareerCup html data was found if let questionsPageHTMLData = NSData(contentsOfURL: questionsURL!) { let questionsParser = TFHpple(HTMLData: questionsPageHTMLData) let questionsQuery = "//li[@class='question']" let questionsNodes = questionsParser.searchWithXPathQuery(questionsQuery) // Iterate through each question text for element in questionsNodes as [TFHppleElement] { let questionText = extractQuestionText(element) let id = extractID(element) let company = extractCompany(element) let tags = extractTags(element) // Create question as long as question text is found if var safeText = questionText { var question = CCQuestion(text: safeText, id: id, company: company, tags: tags) questions += [question] } } } else { println("Career Cup page data can not be retrived") } return questions; } // Build url for recent Career Cup interview questions based on supplied paramters private func buildQuestionsURLString(page: UInt, company: String?, job: String?, topic: String?) -> String { var questionsURLString = "\(CareerCup.DOMAIN)/page?n=\(page)" if company != nil { questionsURLString += "&pid=\(company!)" } if job != nil { questionsURLString += "&job=\(job!)" } if topic != nil { questionsURLString += "&topic=\(topic!)" } return questionsURLString } // Extract question text from question element private func extractQuestionText(element: TFHppleElement) -> String? { let entryElement = element.firstChildWithClassName("entry") let questionElement = entryElement.firstChildWithTagName("a") return questionElement.content } // Extract question ID by parsing the id parameter from the question url endpoint private func extractID(element: TFHppleElement) -> String? { let entryElement = element.firstChildWithClassName("entry") let questionElement = entryElement.firstChildWithTagName("a") let hrefString = questionElement.attributes["href"] as String let startIndex = advance(find(hrefString, "=")!, 1) let range = Range(start: startIndex, end: hrefString.endIndex) return hrefString.substringWithRange(range) } // Extract company by looking at title attribute of image private func extractCompany(element: TFHppleElement) -> String? { let companyAndVoteElement = element.firstChildWithClassName("companyAndVote") let companyElement = companyAndVoteElement.childrenWithClassName("company") let imgElement = companyElement.first!.firstChildWithTagName("img") return imgElement.attributes["title"] as String? } // Extract any found tags private func extractTags(element: TFHppleElement) -> [String] { let tagsElement = element.firstChildWithClassName("tags") let tagsLinkElements = tagsElement.children as [TFHppleElement] return tagsLinkElements.map({$0.content as String}) } }
mit
803d998417603b646b2c367746502011
41.89011
112
0.643607
4.909434
false
false
false
false
TangentMicroServices/HoursService.iOSClient
HoursService.iOSClient/HoursService.iOSClient/EntryModel.swift
1
1882
// // UserModel.swift // HoursService.iOSClient // // Created by Ian Roberts on 2/21/15. // Copyright (c) 2015 Ian Roberts. All rights reserved. // import Foundation /* { comments = "did a bunch I work"; created = "2015-02-22T12:42:01.789679Z"; day = "2015-02-19"; "end_time" = "14:13:09"; hours = "8.00"; id = 20; overtime = 0; "project_id" = 1; "project_task_id" = 1; "start_time" = "14:13:09"; status = Open; tags = ""; updated = "2015-02-22T12:42:01.789729Z"; user = 1; } */ class EntryModel : NSObject { var id: Int var comments: String var hours: NSString var created:NSString var date:NSString var endtime:NSString var overtime:Bool var project_id:Int var project_task_id:Int var start_time:NSString var status:NSString var tags:NSString var updated:NSString var user:Int init(dictEntry:NSDictionary){ id = dictEntry["id"] as Int comments = dictEntry["comments"] as String hours = dictEntry["hours"] as String created = dictEntry["created"] as String date = dictEntry["day"] as String endtime = dictEntry["end_time"] as String overtime = dictEntry["overtime"] as Bool project_id = dictEntry["project_id"] as Int project_task_id = dictEntry["project_task_id"] as Int start_time = dictEntry["start_time"] as String status = dictEntry["status"] as String tags = dictEntry["tags"] as String updated = dictEntry["updated"] as String user = dictEntry["user"] as Int } override init() { id = 0 comments = "" hours = "" created = "" date = "" endtime = "" overtime = false project_id = 0 project_task_id = 0 start_time = "" status = "" tags = "" updated = "" user = 0 } }
mit
4b55e6028f907b2fd2430dc1e5b8147f
23.141026
61
0.580765
3.511194
false
false
false
false
jboullianne/EndlessTunes
EndlessSoundFeed/FollowingController.swift
1
3818
// // FollowersController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 6/19/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit class FollowingController: UITableViewController, FollowingDataDelegate { override func viewDidLoad() { super.viewDidLoad() // 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() self.tableView.tableFooterView = UIView() AccountManager.sharedInstance.followingDataDelegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in 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 AccountManager.sharedInstance.following.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell let index = indexPath.row let follower = AccountManager.sharedInstance.followers[index] cell.displayNameLabel.text = follower[0] //Display Name cell.emailLabel.text = follower[1] // Email //UID Not Displayed But used later for lookup return cell } func newFollowingDataReceived() { self.tableView.reloadData() } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } protocol FollowingDataDelegate { func newFollowingDataReceived() }
gpl-3.0
59702275e8a75d0b617ef3f6afec1ad9
33.080357
137
0.66623
5.421875
false
false
false
false
lkzhao/Hero
Sources/Debug Plugin/HeroDebugView.swift
1
6937
// 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. #if canImport(UIKit) && os(iOS) import UIKit protocol HeroDebugViewDelegate: class { func onProcessSliderChanged(progress: Float) func onPerspectiveChanged(translation: CGPoint, rotation: CGFloat, scale: CGFloat) func on3D(wants3D: Bool) func onDisplayArcCurve(wantsCurve: Bool) func onDone() } class HeroDebugView: UIView { var backgroundView: UIView! var debugSlider: UISlider! var perspectiveButton: UIButton! var doneButton: UIButton! var arcCurveButton: UIButton? weak var delegate: HeroDebugViewDelegate? var panGR: UIPanGestureRecognizer! var pinchGR: UIPinchGestureRecognizer! var showControls: Bool = false { didSet { layoutSubviews() } } var showOnTop: Bool = false var rotation: CGFloat = π / 6 var scale: CGFloat = 0.6 var translation: CGPoint = .zero var progress: Float { return debugSlider.value } init(initialProcess: Float, showCurveButton: Bool, showOnTop: Bool) { super.init(frame: .zero) self.showOnTop = showOnTop backgroundView = UIView(frame: .zero) backgroundView.backgroundColor = UIColor(white: 1.0, alpha: 0.95) backgroundView.layer.shadowColor = UIColor.darkGray.cgColor backgroundView.layer.shadowOpacity = 0.3 backgroundView.layer.shadowRadius = 5 backgroundView.layer.shadowOffset = CGSize.zero addSubview(backgroundView) doneButton = UIButton(type: .system) doneButton.setTitle("Done", for: .normal) doneButton.addTarget(self, action: #selector(onDone), for: .touchUpInside) backgroundView.addSubview(doneButton) perspectiveButton = UIButton(type: .system) perspectiveButton.setTitle("3D View", for: .normal) perspectiveButton.addTarget(self, action: #selector(onPerspective), for: .touchUpInside) backgroundView.addSubview(perspectiveButton) if showCurveButton { arcCurveButton = UIButton(type: .system) arcCurveButton!.setTitle("Show Arcs", for: .normal) arcCurveButton!.addTarget(self, action: #selector(onDisplayArcCurve), for: .touchUpInside) backgroundView.addSubview(arcCurveButton!) } debugSlider = UISlider(frame: .zero) debugSlider.layer.zPosition = 1000 debugSlider.minimumValue = 0 debugSlider.maximumValue = 1 debugSlider.addTarget(self, action: #selector(onSlide), for: .valueChanged) debugSlider.isUserInteractionEnabled = true debugSlider.value = initialProcess backgroundView.addSubview(debugSlider) panGR = UIPanGestureRecognizer(target: self, action: #selector(pan)) panGR.delegate = self panGR.maximumNumberOfTouches = 1 addGestureRecognizer(panGR) pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(pinch)) pinchGR.delegate = self addGestureRecognizer(pinchGR) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() var backgroundFrame = bounds let safeInset: CGFloat if #available(iOS 11.0, *) { safeInset = showOnTop ? safeAreaInsets.top : safeAreaInsets.bottom } else { safeInset = 0 } backgroundFrame.size.height = 72 + safeInset if showOnTop { backgroundFrame.origin.y = showControls ? 0 : -80 } else { backgroundFrame.origin.y = bounds.maxY - CGFloat(showControls ? 72.0 + safeInset : -8.0) } backgroundView.frame = backgroundFrame var sliderFrame = bounds.insetBy(dx: 10, dy: 0) sliderFrame.size.height = 44 sliderFrame.origin.y = showOnTop ? 28 + safeInset : 28 debugSlider.frame = sliderFrame perspectiveButton.sizeToFit() perspectiveButton.frame.origin = CGPoint(x: bounds.maxX - perspectiveButton.bounds.width - 10, y: showOnTop ? 4 + safeInset : 4) doneButton.sizeToFit() doneButton.frame.origin = CGPoint(x: 10, y: showOnTop ? 4 + safeInset : 4) arcCurveButton?.sizeToFit() arcCurveButton?.center = CGPoint(x: center.x, y: doneButton.center.y) } var startRotation: CGFloat = 0 @objc public func pan() { if panGR.state == .began { startRotation = rotation } rotation = startRotation + panGR.translation(in: nil).x / 150 if rotation > π { rotation -= 2 * π } else if rotation < -π { rotation += 2 * π } delegate?.onPerspectiveChanged(translation: translation, rotation: rotation, scale: scale) } var startLocation: CGPoint = .zero var startTranslation: CGPoint = .zero var startScale: CGFloat = 1 @objc public func pinch() { switch pinchGR.state { case .began: startLocation = pinchGR.location(in: nil) startTranslation = translation startScale = scale fallthrough case .changed: if pinchGR.numberOfTouches >= 2 { scale = min(1, max(0.2, startScale * pinchGR.scale)) translation = startTranslation + pinchGR.location(in: nil) - startLocation delegate?.onPerspectiveChanged(translation: translation, rotation: rotation, scale: scale) } default: break } } @objc public func onDone() { delegate?.onDone() } @objc public func onPerspective() { perspectiveButton.isSelected = !perspectiveButton.isSelected delegate?.on3D(wants3D: perspectiveButton.isSelected) } @objc public func onDisplayArcCurve() { arcCurveButton!.isSelected = !arcCurveButton!.isSelected delegate?.onDisplayArcCurve(wantsCurve: arcCurveButton!.isSelected) } @objc public func onSlide() { delegate?.onProcessSliderChanged(progress: debugSlider.value) } } extension HeroDebugView: UIGestureRecognizerDelegate { public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return perspectiveButton.isSelected } } #endif
mit
4f970516d5b8cc7ec5a1fdbe033f4a71
33.834171
132
0.718696
4.300248
false
false
false
false
SPECURE/rmbt-ios-client
Sources/MapOptionResponse.swift
1
9392
/***************************************************************************************************** * Copyright 2016 SPECURE GmbH * * 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 ObjectMapper /// open class MapOptionResponse: BasicResponse { public enum MapTypesIdentifier: String { case mobile case wifi case cell case browser case all } public enum MapSubTypesIdentifier: String { case download case upload case ping case signal } var mapTypes: [MapType] = [] var mapSubTypes: [MapSubType] = [] var mapCellularTypes: [MapCellularTypes] = [] var mapPeriodFilters: [MapPeriodFilters] = [] var mapOverlays: [MapOverlays] = [] var mapStatistics: [MapStatistics] = [] var mapLayouts: [MapLayout] = [] override open func mapping(map: Map) { super.mapping(map: map) mapCellularTypes <- map["mapCellularTypes"] mapSubTypes <- map["mapSubTypes"] mapStatistics <- map["mapStatistics"] mapOverlays <- map["mapOverlays"] mapTypes <- map["mapTypes"] mapLayouts <- map["mapLayouts"] mapPeriodFilters <- map["mapPeriodFilters"] } open class MapSubType: DefaultMappable, Equatable { open var heatmapCaptions: [String] = [] open var heatmapColors: [String] = [] open var isDefault: Bool = false open var index: Int = 0 open var id: MapSubTypesIdentifier = .download open var title: String? open override func mapping(map: Map) { heatmapCaptions <- map["heatmap_captions"] heatmapColors <- map["heatmap_colors"] isDefault <- map["default"] index <- map["index"] id <- map["id"] title <- map["title"] } public static func == (lhs: MapOptionResponse.MapSubType, rhs: MapOptionResponse.MapSubType) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } } open class MapType: DefaultMappable, Equatable { open var id: MapTypesIdentifier = .mobile open var title: String? open var mapListOptions: Int = 0 open var mapSubTypeOptions: [Int] = [] open var isMapCellularTypeOptions: Bool = false open var isDefault: Bool = false open override func mapping(map: Map) { id <- map["id"] title <- map["title"] mapListOptions <- map["mapListOptions"] mapSubTypeOptions <- map["mapSubTypeOptions"] isMapCellularTypeOptions <- map["mapCellularTypeOptions"] isDefault <- map["default"] } public static func == (lhs: MapOptionResponse.MapType, rhs: MapOptionResponse.MapType) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } open func toProviderType() -> OperatorsRequest.ProviderType { /// mobile|cell|browser switch id { case .mobile: return OperatorsRequest.ProviderType.mobile case .wifi: return OperatorsRequest.ProviderType.WLAN case .cell: return OperatorsRequest.ProviderType.mobile case .browser: return OperatorsRequest.ProviderType.browser default: return OperatorsRequest.ProviderType.all } } } open class MapCellularTypes: DefaultMappable, Equatable { open var id: Int? open var title: String? open var isDefault: Bool = false required public init?(map: Map) { super.init() } open override func mapping(map: Map) { id <- map["id"] title <- map["title"] isDefault <- map["default"] } public static func == (lhs: MapOptionResponse.MapCellularTypes, rhs: MapOptionResponse.MapCellularTypes) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } } open class MapPeriodFilters: DefaultMappable, Equatable { open var period: Int = 0 open var title: String? open var isDefault: Bool = false required public init?(map: Map) { super.init() } open override func mapping(map: Map) { period <- map["period"] title <- map["title"] isDefault <- map["default"] } public static func == (lhs: MapOptionResponse.MapPeriodFilters, rhs: MapOptionResponse.MapPeriodFilters) -> Bool { return lhs.period == rhs.period && lhs.title == rhs.title } } open class MapOverlays: MapOptionResponse.DefaultMappable, Equatable { enum ResponseType: String { case auto = "MAP_FILTER_AUTOMATIC" case heatmap = "MAP_FILTER_HEATMAP" case points = "MAP_FILTER_POINTS" case regions = "MAP_FILTER_REGIONS" case shapes = "MAP_FILTER_SHAPES" case municipality = "MAP_FILTER_MUNICIPALITY" case settlements = "MAP_FILTER_SETTLEMENTS" case whitespots = "MAP_FILTER_WHITESPOTS" func toMapOverlaysIdentifier() -> String { switch self { case .auto: return "auto" case .heatmap: return "heatmap" case .points: return "points" case .regions: return "regions" case .shapes: return "shapes" case .municipality: return "municipality" case .settlements: return "settlements" case .whitespots: return "whitespots" } } static func toMapOverlaysIdentifier(value: String) -> String { if let identifier = ResponseType(rawValue: value) { return identifier.toMapOverlaysIdentifier() } else { let components = value.components(separatedBy: "_") return components.last?.lowercased() ?? "unknown" } } } open var identifier: String? open var title: String? open var isDefault: Bool = false open var overlayIdentifier: String { if let identifier = identifier { if let type = ResponseType(rawValue: identifier) { return type.toMapOverlaysIdentifier() } else { return ResponseType.toMapOverlaysIdentifier(value: identifier) } } else { return title?.lowercased() ?? "" } } init(identifier: String, title: String, isDefault: Bool = false) { super.init() self.identifier = identifier self.title = title self.isDefault = isDefault } required public init?(map: Map) { super.init() } open override func mapping(map: Map) { identifier <- map["value"] title <- map["title"] isDefault <- map["default"] } public static func == (lhs: MapOptionResponse.MapOverlays, rhs: MapOptionResponse.MapOverlays) -> Bool { return lhs.identifier == rhs.identifier && lhs.title == rhs.title } } open class MapStatistics: DefaultMappable { var title: String? var value: Float = 0.0 open override func mapping(map: Map) { title <- map["title"] value <- map["value"] } } open class MapLayout: DefaultMappable { var title: String? var isDefault: Bool = false var apiLink: String? var accessToken: String? var layer: String? open override func mapping(map: Map) { title <- map["title"] apiLink <- map["apiLink"] accessToken <- map["accessToken"] layer <- map["layer"] isDefault <- map["default"] } } open class DefaultMappable: Mappable { open func mapping(map: Map) { } init() { } required public init?(map: Map) { } } }
apache-2.0
9641a1c0cc73073fc0f65c6ff3a34d9d
33.914498
122
0.52023
5.044039
false
false
false
false
MobileOrg/mobileorg
Classes/Sync/CloudTransferManager.swift
1
10277
// // ICloudTransferManager.swift // MobileOrg // // Created by Artem Loenko on 08/10/2019. // Copyright © 2019 Artem Loenko. All rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // import Foundation final class CloudTransferManager: NSObject { @objc public var iCloudStorageDocumentsURL: URL? { return self.containerURL } @objc public let indexFilename = "index.org" // FIXME: customizable via Settings? private var transfers = [ TransferContext ]() private var activeTransfer: TransferContext? = nil private var paused = false private var active = false private let cloudSynchronizationQueue = DispatchQueue(label: "mobileorg.cloudSynchronizationQueue", qos: .background) override init() { super.init() self.obtainContainer() { [weak self] (success) in guard let self = self else { return } if success { NotificationCenter.default.addObserver(self, selector: #selector(self.askCloudStorageToSynchronizeDocuments), name: UIApplication.didBecomeActiveNotification, object: nil) } } } deinit { NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } @objc var isAvailable: Bool { return self.ubiquityIdentityToken != nil } // MARK: Private functions // Reflects the current state of iCloud account private var ubiquityIdentityToken: NSObjectProtocol? { assert(Thread.isMainThread) return FileManager.default.ubiquityIdentityToken } // We populate it in the init but the execution is asynchronous, can be nil if you are too fast private var containerURL: URL? // This function is called during the initalization of the class // No fatalErrors here, please, or it will be impossible to run an application to access the data private func obtainContainer(completion: @escaping (Bool) -> Void) { guard self.containerURL == nil else { completion(false) return } DispatchQueue.global().async { // If you specify nil for this parameter, this method returns the first container listed in the com.apple.developer.ubiquity-container-identifiers entitlement array let url = FileManager.default.url(forUbiquityContainerIdentifier: nil) guard let documentURL = url?.appendingPathComponent("Documents") else { completion(false) return } if !FileManager.default.fileExists(atPath: documentURL.path) { do { try FileManager.default.createDirectory(at: documentURL, withIntermediateDirectories: true, attributes: nil) } catch { UIAlertController.show("iCloud Error", message: error.localizedDescription) completion(false) return } } DispatchQueue.main.async { self.containerURL = documentURL completion(true) } } } @objc private func askCloudStorageToSynchronizeDocuments() { guard let documentURL = self.containerURL else { return } self.cloudSynchronizationQueue.async { do { // If a cloud-based file or directory has not been downloaded yet, calling this method starts the download process. // If the item exists locally, calling this method synchronizes the local copy with the version in the cloud. try FileManager.default.startDownloadingUbiquitousItem(at: documentURL) } catch { DispatchQueue.main.async { UIAlertController.show("iCloud Synchronisation Error", message: error.localizedDescription) } } } } // MARK: Processing requests private func dispatchNextTransfer() { guard !self.paused else { return } guard let syncManager = SyncManager.instance(), self.transfers.count > 0, self.transfers.first?.remoteUrl != nil, !self.active else { return } let activeTransfer = transfers.removeFirst() activeTransfer.success = true syncManager.transferFilename = activeTransfer.remoteUrl.lastPathComponent syncManager.progressTotal = 0 syncManager.updateStatus() self.active = true self.processRequest(activeTransfer) } private func processRequest(_ transfer: TransferContext) { self.activeTransfer = transfer guard self.containerURL != nil else { transfer.errorText = "Cannot reach iCloud storage."; transfer.statusCode = 503 transfer.success = false self.requestFinished(transfer) return } guard !transfer.dummy else { transfer.success = true self.requestFinished(transfer) return } guard let remoteURL = transfer.remoteUrl.path.removingPercentEncoding else { fatalError("Cannot create remote URL from \(transfer.remoteUrl.path)") } guard let localURL = transfer.localFile.removingPercentEncoding else { fatalError("Cannot create local URL from \(String(describing: transfer.localFile))") } let processFileOperationResult: FileOperationCompletion = { result in switch result { case .success(_): transfer.success = true case .failure(let error): transfer.errorText = error.localizedDescription transfer.statusCode = 404 transfer.success = false } SyncManager.instance()?.progressTotal = 100 SyncManager.instance()?.progressCurrent = 100 SyncManager.instance()?.updateStatus() self.requestFinished(transfer) } switch transfer.transferType { case TransferTypeDownload: self.downloadFile(from: remoteURL, to: localURL, completionHandler: processFileOperationResult) case TransferTypeUpload: self.uploadFile(to: remoteURL, from: localURL, completionHandler: processFileOperationResult) default: fatalError("Unsupported transfer type: \(transfer.transferType)") } } private func requestFinished(_ transfer: TransferContext) { if !transfer.success && transfer.abortOnFailure { self.transfers.removeAll() } if transfer.success { transfer.delegate.transferComplete?(transfer) } else { transfer.delegate.transferFailed?(transfer) } self.active = false self.activeTransfer = nil self.dispatchNextTransfer() } // MARK: Upload & download typealias FileOperationResult = Result<Any?, Error> typealias FileOperationCompletion = (FileOperationResult) -> Void /// Upload the file to iCloud storage. /// - Parameter to: The destination as an absolute path /// - Parameter from: The source as an absolute path /// - Parameter completionHandler: Will be executed on the main-thread. Trigger `FileOperationResult` as a result. private func uploadFile(to: String, from: String, completionHandler: @escaping FileOperationCompletion) { DispatchQueue.global().async { do { assert(FileManager.default.fileExists(atPath: from)) assert(FileManager.default.isReadableFile(atPath: from)) if FileManager.default.fileExists(atPath: to) { try FileManager.default.removeItem(atPath: to) } try FileManager.default.copyItem(atPath: from, toPath: to) } catch { print(error.localizedDescription) DispatchQueue.main.async { completionHandler(.failure(error)) } } DispatchQueue.main.async { completionHandler(.success(nil)) } } } /// Download the file from iCloud storage. /// - Parameter from: The source as an absolute path /// - Parameter to: The destination as an absolute path /// - Parameter completionHandler: Will be executed on the main-thread. Trigger `FileOperationResult` as a result. private func downloadFile(from: String, to: String, completionHandler: @escaping FileOperationCompletion) { DispatchQueue.global(qos: .userInitiated).async { do { if FileManager.default.fileExists(atPath: to) { try FileManager.default.removeItem(atPath: to) } try FileManager.default.copyItem(atPath: from, toPath: to) } catch { print(error.localizedDescription) DispatchQueue.main.async { completionHandler(.failure(error)) } } DispatchQueue.main.async { completionHandler(.success(nil)) } } } } // Mimic TransferManager conformance extension CloudTransferManager { @objc static let instance = CloudTransferManager() @objc func enqueueTransfer(_ transfer: TransferContext) { self.transfers.append(transfer) ShowStatusView() self.dispatchNextTransfer() } @objc func resume() { self.paused = false self.dispatchNextTransfer() } @objc func pause() { self.paused = true } @objc func busy() -> Bool { return (transfers.count > 0 || active) } @objc func queueSize() -> Int { return self.transfers.count } @objc func abort() { self.transfers.removeAll() } }
gpl-2.0
a5c43b5437c428c65a257aec59946924
40.603239
187
0.647334
5.218893
false
false
false
false
ruiying123/YRPageView
YRPageView/Sources/YRPageViewCell.swift
1
4819
// // YRPageViewCell.swift // YRPageView // // Created by kilrae on 2017/4/12. // Copyright © 2017年 yang. All rights reserved. // import UIKit open class YRPageViewCell: UICollectionViewCell { /// Returns the label used for the main textual content of the pager view cell. open var textLabel: UILabel? { if let _ = _textLabel { return _textLabel } let view = UIView(frame: .zero) view.isUserInteractionEnabled = false view.backgroundColor = UIColor.black.withAlphaComponent(0.6) let textLabel = UILabel(frame: .zero) textLabel.textColor = .white textLabel.font = UIFont.preferredFont(forTextStyle: .body) self.contentView.addSubview(view) view.addSubview(textLabel) textLabel.addObserver(self, forKeyPath: "font", options: [.old,.new], context: kvoContext) _textLabel = textLabel return textLabel } /// Returns the image view of the pager view cell. Default is nil. open var imageView: UIImageView? { if let _ = _imageView { return _imageView } let imageView = UIImageView(frame: .zero) self.contentView.addSubview(imageView) _imageView = imageView return imageView } fileprivate weak var _textLabel: UILabel? fileprivate weak var _imageView: UIImageView? fileprivate let kvoContext = UnsafeMutableRawPointer(bitPattern: 0) fileprivate let selectionColor = UIColor(white: 0.2, alpha: 0.2) fileprivate weak var _selectedForegroundView: UIView? fileprivate var selectedForegroundView: UIView? { if let _ = _selectedForegroundView { return _selectedForegroundView } let view = UIView(frame: self.contentView.bounds) self.contentView.addSubview(view) _selectedForegroundView = view return view } open override var isHighlighted: Bool { set { super.isHighlighted = newValue if newValue { self.selectedForegroundView?.layer.backgroundColor = self.selectionColor.cgColor } else if !super.isSelected { self.selectedForegroundView?.layer.backgroundColor = UIColor.clear.cgColor } } get { return super.isHighlighted } } open override var isSelected: Bool { set { super.isSelected = newValue self.selectedForegroundView?.layer.backgroundColor = newValue ? self.selectionColor.cgColor : UIColor.clear.cgColor } get { return super.isSelected } } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { self.contentView.backgroundColor = UIColor.clear self.backgroundColor = UIColor.clear self.contentView.layer.shadowColor = UIColor.black.cgColor self.contentView.layer.shadowRadius = 5 self.contentView.layer.shadowOpacity = 0.75 self.contentView.layer.shadowOffset = .zero } deinit { if let textLabel = _textLabel { textLabel.removeObserver(self, forKeyPath: "font", context: kvoContext) } } override open func layoutSubviews() { super.layoutSubviews() if let imageView = _imageView { imageView.frame = self.contentView.bounds } if let textLabel = _textLabel { textLabel.superview!.frame = { var rect = self.contentView.bounds let height = textLabel.font.pointSize*1.5 rect.size.height = height rect.origin.y = self.contentView.frame.height-height return rect }() textLabel.frame = { var rect = textLabel.superview!.bounds rect = rect.insetBy(dx: 8, dy: 0) rect.size.height -= 1 rect.origin.y += 1 return rect }() } if let selectedForegroundView = _selectedForegroundView { selectedForegroundView.frame = self.contentView.bounds } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == kvoContext { if keyPath == "font" { self.setNeedsLayout() } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } }
mit
4f4a16006cacd16f0b1d78500fb6b31e
31.540541
156
0.596346
5.042932
false
false
false
false
limaoxuan/MXAlertView
MXAlertView/MXAlertView/AppDelegate.swift
1
15959
// // AppDelegate.swift // CoinAnimation // // Created by 李茂轩 on 15/2/14. // Copyright (c) 2015年 lee. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var coinTrackArrays = NSMutableArray() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.backgroundColor = UIColor.whiteColor() self.window?.makeKeyAndVisible() let viewController = ViewController() self.window?.rootViewController = viewController // let mxAlertView = MXAlertView() // self.window?.addSubview(mxAlertView) // var minutes = 1 * Double(NSEC_PER_SEC) // // var dtime = dispatch_time(DISPATCH_TIME_NOW, Int64(minutes)) // dispatch_after(dtime, dispatch_get_main_queue()) { () -> Void in // // // // mxAlertView.showAlertAnimation() // // // } // // minutes = 3 * Double(NSEC_PER_SEC) // dtime = dispatch_time(DISPATCH_TIME_NOW, Int64(minutes)) // dispatch_after(dtime, dispatch_get_main_queue()) { () -> Void in // // // mxAlertView.hiddenAlertAnimation() // // } return true } func MXScaleAnimation()->CABasicAnimation{ let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.fromValue = 1.2 scaleAnimation.toValue = 0.3 // scaleAnimation.speed = 2 // Autoreverses scaleAnimation.removedOnCompletion = false; //完成后是否回到原来状态,如果为NO 就是停留在动画结束时的状态 // 当你设定这个属性为 YES 时,在它到达目的地之后,动画的返回到开始的值,代替了直接跳转到 开始的值。 scaleAnimation.autoreverses = false //是否重播,原动画的倒播 //animation.fillMode = kCAFillModeRemoved;//动画完成后返回到原来状态 scaleAnimation.fillMode = kCAFillModeForwards //当动画完成时,保留在动画结束的状态 scaleAnimation.repeatCount = 0 scaleAnimation.duration = 2 // currentView.layer.addAnimation(scaleAnimation, forKey: "scaleAnimation") return scaleAnimation } func MXPositionAnimation(currentView:UIView)->CABasicAnimation{ let positionAnimation = CABasicAnimation(keyPath: "position") // UIGeometry // println(currentView.layer.position) positionAnimation.fromValue = NSValue(CGPoint: currentView.layer.position) positionAnimation.toValue = NSValue(CGPoint: CGPointMake(currentView.layer.position.x, currentView.layer.position.y+100)) positionAnimation.autoreverses = false positionAnimation.fillMode = kCAFillModeForwards positionAnimation.removedOnCompletion = false; positionAnimation.repeatCount = 0 positionAnimation.duration = 2 return positionAnimation // currentView.layer.addAnimation(positionAnimation, forKey: "position") // = NSValue(currentView.la) } func MXRotateAnimation()->CABasicAnimation{ let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.x") rotateAnimation.fromValue = 0 rotateAnimation.toValue = 6 * M_PI rotateAnimation.autoreverses = false rotateAnimation.removedOnCompletion = false rotateAnimation.repeatCount = 0 rotateAnimation.fillMode = kCAFillModeForwards rotateAnimation.duration = 2 return rotateAnimation // currentView.layer.addAnimation(rotateAnimation, forKey: "transform.rotation.x") } func MXGroupAnimation(animationOne:CABasicAnimation,animationTwo:CABasicAnimation,animationThree:CABasicAnimation,currentView:UIView){ let groupAnimation = CAAnimationGroup() groupAnimation.duration = 2 groupAnimation.fillMode = kCAFillModeForwards groupAnimation.autoreverses = false groupAnimation.repeatCount = 0 groupAnimation.removedOnCompletion = false groupAnimation.animations = [animationOne,animationTwo,animationThree] currentView.layer.addAnimation(groupAnimation, forKey: "groupAnnimation") } func MXKeyframePositionAnimation(currentView:UIView){ let layerPosition = currentView.layer.position let keyframeAnimation = CAKeyframeAnimation(keyPath: "position") // keyframeAnimation.duration = 1.0 keyframeAnimation.delegate = self //设定关键帧位置,必须含起始与终止位置 keyframeAnimation.values = [NSValue(CGPoint: CGPointMake(layerPosition.x+5, layerPosition.y-3)),NSValue(CGPoint: CGPointMake(layerPosition.x-5, layerPosition.y+6)),NSValue(CGPoint: CGPointMake(layerPosition.x+5, layerPosition.y-6)),NSValue(CGPoint: CGPointMake(layerPosition.x-5, layerPosition.y+3))] // timeFunctions属性 keyframeAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] // 用过UIKit层动画的同学应该对这个属性不陌生,这个属性用以指定时间函数,类似于运动的加速度,有以下几种类型。上例子的AB段就是用了淡入淡出效果。记住,这是一个数组,你有几个子路径就应该传入几个元素 //设定每个关键帧的时长,如果没有显式地设置,则默认每个帧的时间=总duration/(values.count - 1) keyframeAnimation.keyTimes = [0,0.4,0.8,1.0] keyframeAnimation.autoreverses = false keyframeAnimation.removedOnCompletion = false keyframeAnimation.fillMode = kCAFillModeForwards currentView.layer.position = CGPointMake(layerPosition.x, layerPosition.y) keyframeAnimation.duration = 0.5 currentView.layer.addAnimation(keyframeAnimation, forKey: "ss") } // // func MXDismissAnimation(currentView:UIView){ // // let layerPosition = currentView.layer.position // let keyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale") // // keyframeAnimation.duration = 1.0 // keyframeAnimation.delegate = self // // //设定关键帧位置,必须含起始与终止位置 // keyframeAnimation.values = [1,0.9,0.8,0.7] // // // // timeFunctions属性 // keyframeAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear),CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear),CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear),CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)] // // // 用过UIKit层动画的同学应该对这个属性不陌生,这个属性用以指定时间函数,类似于运动的加速度,有以下几种类型。上例子的AB段就是用了淡入淡出效果。记住,这是一个数组,你有几个子路径就应该传入几个元素 // // //设定每个关键帧的时长,如果没有显式地设置,则默认每个帧的时间=总duration/(values.count - 1) // keyframeAnimation.keyTimes = [0,0.4,0.8,1] // keyframeAnimation.autoreverses = false // keyframeAnimation.removedOnCompletion = false // keyframeAnimation.fillMode = kCAFillModeForwards //// currentView.layer.position = CGPointMake(layerPosition.x, layerPosition.y) // keyframeAnimation.duration = 0.6 // // currentView.layer.addAnimation(keyframeAnimation, forKey: "ss") // // } // // func MXKeyframeScaleAnimation(currentView:UIView){ // // let layerPosition = currentView.layer.position // let keyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale") // // keyframeAnimation.duration = 1.0 //// keyframeAnimation.delegate = self // // //设定关键帧位置,必须含起始与终止位置 // keyframeAnimation.values = [1.2,1,1.1,1] // // // // timeFunctions属性 // keyframeAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear),CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear),CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear),CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)] // // // 用过UIKit层动画的同学应该对这个属性不陌生,这个属性用以指定时间函数,类似于运动的加速度,有以下几种类型。上例子的AB段就是用了淡入淡出效果。记住,这是一个数组,你有几个子路径就应该传入几个元素 // // //设定每个关键帧的时长,如果没有显式地设置,则默认每个帧的时间=总duration/(values.count - 1) // keyframeAnimation.keyTimes = [0,0.4,0.7,1.0] // keyframeAnimation.autoreverses = false // keyframeAnimation.removedOnCompletion = false // keyframeAnimation.fillMode = kCAFillModeForwards // // currentView.layer.position = CGPointMake(layerPosition.x, layerPosition.y) // keyframeAnimation.duration = 0.6 // // currentView.layer.addAnimation(keyframeAnimation, forKey: "ss") // // // // } 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lee.CoinAnimation" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CoinAnimation", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoinAnimation.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
apache-2.0
3061a54064c18d3cb45584de5e991769
43.52994
308
0.666577
5.098732
false
false
false
false
eldesperado/SpareTimeAlarmApp
SpareTimeMusicApp/DateTimeHelper.swift
1
3897
// // DateTimeHelper.swift // SpareTimeAlarmApp // // Created by Pham Nguyen Nhat Trung on 8/11/15. // Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved. // import UIKit import Foundation enum NumberToDate: Int, RawRepresentable { case Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday var simpleDescription: String { get { return getDescription() } } var date: Int { get { return rawValue } } init?(dateNumber: Int) { self.init(rawValue: dateNumber) } private func getDescription() -> String { switch self { case .Monday: return "Monday" case .Tuesday: return "Tuesday" case .Wednesday: return "Wednesday" case .Thursday: return "Thursday" case .Friday: return "Friday" case .Saturday: return "Saturday" case .Sunday: return "Sunday" } } func getIsRepeat(repeatDate: RepeatDate) -> Bool { switch self { case .Monday: return repeatDate.isMon.boolValue case .Tuesday: return repeatDate.isTue.boolValue case .Wednesday: return repeatDate.isWed.boolValue case .Thursday: return repeatDate.isThu.boolValue case .Friday: return repeatDate.isFri.boolValue case .Saturday: return repeatDate.isSat.boolValue case .Sunday: return repeatDate.isSun.boolValue } } } struct DateTimeHelper { static func getRemainingTimeFromCurrentTime(destinatedTime: NSNumber) -> NSNumber { let currentTime = getCurrentTime() let currentTimeInMinutes: Int = getMinutesForHoursMinutes(currentTime.hours, minutes: currentTime.minutes) if currentTimeInMinutes > destinatedTime.integerValue { return 1440 - currentTimeInMinutes + destinatedTime.integerValue } else { return currentTimeInMinutes - destinatedTime.integerValue } } static func getCurrentTime() -> (hours: Int, minutes: Int, seconds: Int) { let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Hour, .Minute, .Second], fromDate: date) return (components.hour, components.minute, components.second) } static func getCurrentTimeInMinutes() -> NSNumber { let currentTime = getCurrentTime() return getMinutesForHoursMinutes(currentTime.hours, minutes: currentTime.minutes) } static func getCurrentTimeInSeconds() -> NSNumber { let currentTime = getCurrentTime() return getMinutesForHoursMinutesSeconds(currentTime.hours, minutes: currentTime.minutes, seconds: currentTime.seconds) } static func getMinutesForHoursMinutes(hours: Int, minutes: Int) -> Int { return hours * 60 + minutes } static func getMinutesForHoursMinutesSeconds(hours: Int, minutes: Int, seconds: Int) -> Int { return hours * 360 + minutes * 60 + seconds } static func getCurrentDate() -> (month: Int, day: Int, dayOfWeek: Int, dayOfWeekAsString: String) { let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Month, .Day, .Weekday], fromDate: date) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE" let weekdayString = dateFormatter.stringFromDate(date) return (components.hour, components.day, components.weekday, weekdayString) } static func getAlarmTime(let alarmTime time: NSNumber) -> String { let hour = time.integerValue / 60 let minute = time.integerValue - hour * 60 let hourString = hour < 10 ? "0\(hour)" : "\(hour)" let minuteString = minute < 10 ? "0\(minute)" : "\(minute)" return "\(hourString):\(minuteString)" } static func getAlarmTimeComponents(let alarmTime time: NSNumber) -> (hour: Int, minutes: Int) { let hour = time.integerValue / 60 let minute = time.integerValue - hour * 60 return (hour, minute) } }
mit
ce78833d316986b723a9407f19d241b1
29.209302
122
0.685912
4.310841
false
false
false
false
borisyurkevich/ECAB
ECAB/FlankerViewController.swift
1
21311
// // FlankerViewController.swift // ECAB // // Created by Boris Yurkevich on 6/20/15. // Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved. // import UIKit import AVFoundation class FlankerViewController: CounterpointingViewController { var smallImages = false let barWidth: CGFloat = 72 var isFlankerRandomized = false override func viewDidLoad() { greeingMessage = "Example stimuli..." isFlankerRandomized = UserDefaults.standard.bool(forKey: "isFlankerRandmoized") if isFlankerRandomized { sessionType = SessionType.flankerRandomized.rawValue } else { sessionType = SessionType.flanker.rawValue } super.viewDidLoad() if (smallImages) { session.imageSizeComment = "Small images (1.5x)" } else { session.imageSizeComment = "Normal images (2x)" } addMenu() } override func addTouchTargetButtons() { let screen = UIScreen.main.bounds let screenAreaLeft = CGRect(x: 0, y: menuBarHeight, width: barWidth, height: screen.size.height-menuBarHeight) let screenAreaRight = CGRect(x: UIScreen.main.bounds.size.width - barWidth, y: menuBarHeight, width: barWidth, height: screen.size.height-menuBarHeight) let buttonLeft = UIButton(frame: screenAreaLeft) let buttonRight = UIButton(frame: screenAreaRight) buttonLeft.backgroundColor = UIColor.orange buttonRight.backgroundColor = UIColor.green buttonLeft.addTarget(self, action: #selector(CounterpointingViewController.handleTouchLeft), for: UIControl.Event.touchDown) buttonRight.addTarget(self, action: #selector(CounterpointingViewController.handleTouchRight), for: UIControl.Event.touchDown) let star = UIImage(named: "star") buttonLeft.setImage(star, for: UIControl.State()) buttonLeft.imageView!.contentMode = UIView.ContentMode.center buttonRight.setImage(star, for: UIControl.State()) buttonRight.imageView!.contentMode = UIView.ContentMode.center view.addSubview(buttonLeft) view.addSubview(buttonRight) } enum Picture { case empty case mouse case fish case mouseInverted case fishInverted } enum Position { case left case middle case right } func updateScreen(_ left: Picture, middle: Picture, right: Picture) { addImage(left, position: Position.left) addImage(middle, position: Position.middle) addImage(right, position: Position.right) toggleNavigationButtons(isEnabled: false) } func addImage(_ image: Picture, position:Position) { let fishImage = UIImage(named: "fish") let mouseImage = UIImage(named: "mouse") let fishInvertedImage = UIImage(named: "fish_iverse") let mouseInvertedImage = UIImage(named: "mouse_inverse") var scaleFactor:CGFloat = 2.0 var mouseOffset = (view.frame.size.width / 4) if (smallImages) { scaleFactor = 1.5 mouseOffset = (view.frame.size.width / 4) * 0.75 } var imageView = UIImageView() switch image { case .mouse: imageView = UIImageView(image: mouseImage) imageView.frame = CGRect(x: 0, y: 0, width: mouseImage!.size.width*scaleFactor, height: mouseImage!.size.height*scaleFactor) case .fish: imageView = UIImageView(image: fishImage) imageView.frame = CGRect(x: 0, y: 0, width: fishImage!.size.width*scaleFactor, height: fishImage!.size.height*scaleFactor) leftTarget = false case .mouseInverted: imageView = UIImageView(image: mouseInvertedImage) imageView.frame = CGRect(x: 0, y: 0, width: mouseImage!.size.width*scaleFactor, height: mouseImage!.size.height*scaleFactor) case .fishInverted: imageView = UIImageView(image: fishInvertedImage) imageView.frame = CGRect(x: 0, y: 0, width: fishImage!.size.width*scaleFactor, height: fishImage!.size.height*scaleFactor) leftTarget = true default: break } switch position { case .left: imageView.center = CGPoint(x: view.center.x - mouseOffset, y: view.center.y) case .middle: imageView.center = CGPoint(x: view.center.x, y: view.center.y) case .right: imageView.center = CGPoint(x: view.center.x + mouseOffset, y: view.center.y) } view.addSubview(imageView) } override func skip() { currentScreenShowing = 22 presentNextScreen() } override func getComment() -> String { return session.comment } override func presentPreviousScreen() { if trainingMode { currentScreenShowing = -1 presentNextScreen() } else { currentScreenShowing = 22 presentNextScreen() } } override func presentNextScreen() { currentScreenShowing += 1 cleanView() screenPresentedDate = Date() if isFlankerRandomized == false { switch currentScreenShowing { case 0: presentMessage(greeingMessage) case 1: updateScreen(.empty, middle: .fish, right: .empty) case 2: updateScreen(.empty, middle: .fishInverted, right: .empty) case 3: updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 4: updateScreen(.mouse, middle: .mouse, right: .fish) case 5: updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 6: updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 7: presentMessage("Practice 1. Ready...") // Next line is to insert white space in the log. model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) case 8: updateScreen(.fish, middle: .mouse, right: .mouse) case 9: updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 10: updateScreen(.fish, middle: .mouse, right: .mouse) case 11: updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 12: updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 13: updateScreen(.fish, middle: .mouse, right: .mouse) case 14: presentMessage("...stop") case 15: presentMessage("Practice 2. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) case 16: updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 17: updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 18: updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 19: updateScreen(.mouse, middle: .mouse, right: .fishInverted) case 20: updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 21: updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) case 22: presentMessage("...stop") case 23: presentMessage("Game 1. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) gameModeInversed = false trainingMode = false case 24: // 0 updateScreen(.mouse, middle: .mouse, right: .fish) case 25: // 1 updateScreen(.mouse, middle: .fish, right: .mouse) case 26: // 2 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) case 27: // 3 updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 28: // 4 updateScreen(.mouse, middle: .fish, right: .mouse) case 29: // 5 updateScreen(.mouse, middle: .mouse, right: .fish) case 30: // 6 updateScreen(.mouse, middle: .fish, right: .mouse) case 31: // 7 updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 32: // 8 updateScreen(.mouse, middle: .mouse, right: .fish) case 33: // 9 updateScreen(.fish, middle: .mouse, right: .mouse) case 34: presentMessage("...stop") case 35: presentMessage("Game 2. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) gameModeInversed = true case 36: // 10 updateScreen(.mouseInverted, middle: .fish, right: .mouseInverted) case 37: // 11 updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 38: // 12 updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 39: // 13 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 40: // 14 updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 41: // 15 updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) case 42: // 16 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 43: // 17 updateScreen(.mouseInverted, middle: .fish, right: .mouseInverted) case 44: // 18 updateScreen(.mouse, middle: .mouse, right: .fishInverted) case 45: // 19 updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 46: presentMessage("...stop") case 47: presentMessage("Game 3. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) gameModeInversed = true case 48: // 20 updateScreen(.mouse, middle: .mouse, right: .fishInverted) case 49: // 21 updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 50: // 22 updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 51: // 23 updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) case 52: // 24 updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 53: // 25 updateScreen(.mouseInverted, middle: .fish, right: .mouseInverted) case 54: // 26 updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) case 55: // 27 updateScreen(.mouse, middle: .mouse, right: .fishInverted) case 56: // 28 updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 57: // 29 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 58: presentMessage("...stop") case 59: presentMessage("Game 4. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) gameModeInversed = false case 60: // 30 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) case 61: // 31 updateScreen(.mouse, middle: .mouse, right: .fish) case 62: // 32 updateScreen(.mouse, middle: .fish, right: .mouse) case 63: // 33 updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 64: // 34 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) case 65: // 35 updateScreen(.mouse, middle: .mouse, right: .fish) case 66: // 36 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) case 67: // 37 updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 68: // 38 updateScreen(.fish, middle: .mouse, right: .mouse) case 69: // 39 updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 70: presentMessage("...stop") case 71: presentPause() default: break } } else { /* The initial practice blocks are unchanged. After that, we have two blocks each of which contains 15 trials randomized between ‘inverted’ and ‘normal’ versions. I have added gameModeInversed = false before a trial every time we are changing from inverted to normal. Similarly I have added gameModeInversed = true when we change from normal to inverted. These are inserted before the relevant case nn: line. I hope this is the right place and will mean that the results from the two types of trials will be correctly sorted for calculating the average times. I have adjusted the lines like case 25: //1 so that there are successive numbers for each new screen including the screens that contain messages. I hope this is correct. To make sure I was keeping track of which trial was of which type, I have included a number such as 6i in red ( i meaning the sixth trial is inverted, with n for normal (non-inverted) trials) at the beginning of each updateScreen line. I presume you will need to strip these off, but I hope they will help you to ensure that the two types are correctly handled. Oliver B. */ switch currentScreenShowing { case 0: presentMessage("Example stimuli...") case 1: updateScreen(.empty, middle: .fish, right: .empty) case 2: updateScreen(.empty, middle: .fishInverted, right: .empty) case 3: updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 4: updateScreen(.mouse, middle: .mouse, right: .fish) case 5: updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 6: updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 7: presentMessage("Practice 1. Ready...") // Next line is to insert white space in the log. model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) case 8: updateScreen(.fish, middle: .mouse, right: .mouse) case 9: updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 10: updateScreen(.fish, middle: .mouse, right: .mouse) case 11: updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 12: updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) case 13: updateScreen(.fish, middle: .mouse, right: .mouse) case 14: presentMessage("...stop") case 15: presentMessage("Practice 2. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) case 16: updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 17: updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 18: updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 19: updateScreen(.mouse, middle: .mouse, right: .fishInverted) case 20: updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 21: updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) case 22: presentMessage("...stop") case 23: presentMessage("Game 1. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) trainingMode = false gameModeInversed = true case 24: // 0 updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) gameModeInversed = true case 25: // 1 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) gameModeInversed = false case 26: // 2 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) gameModeInversed = false case 27: // 3 updateScreen(.mouseInverted, middle: .fish, right: .mouseInverted) gameModeInversed = true case 28: // 4 updateScreen(.mouse, middle: .fish, right: .mouse) gameModeInversed = false case 29: // 5 updateScreen(.fishInverted, middle: .mouse, right: .mouse) gameModeInversed = true case 30: // 6 updateScreen(.fish, middle: .mouse, right: .mouse) gameModeInversed = false case 31: // 7 updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 32: // 8 updateScreen(.mouse, middle: .mouse, right: .fish) case 33: // 9 updateScreen(.mouse, middle: .fish, right: .mouse) gameModeInversed = false case 34: // 10 updateScreen(.mouse, middle: .fishInverted, right: .mouse) gameModeInversed = true case 35: // 11 updateScreen(.mouse, middle: .fishInverted, right: .mouse) gameModeInversed = true case 36: // 12 updateScreen(.fishInverted, middle: .mouseInverted, right: .mouseInverted) gameModeInversed = false case 37: // 13 gameModeInversed = true updateScreen(.mouseInverted, middle: .fish, right: .mouseInverted) case 38: // 14 updateScreen(.fishInverted, middle: .mouse, right: .mouse) gameModeInversed = true case 39: presentMessage("...stop") case 40: presentMessage("Game 2. Ready...") model.addCounterpointingMove(blankSpaceTag, positionY: 0, success: false, interval: 0.0, inverted: false, delay:0.0) trainingMode = false gameModeInversed = false case 41: // 15 updateScreen(.mouseInverted, middle: .fishInverted, right: .mouseInverted) case 42: // 16 updateScreen(.mouse, middle: .mouse, right: .fish) case 43: // 17 updateScreen(.mouse, middle: .mouse, right: .fish) case 44: // 18 updateScreen(.mouse, middle: .mouse, right: .fishInverted) gameModeInversed = true case 45: // 19 updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 46: //20 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) case 47: //21 updateScreen(.mouse, middle: .mouse, right: .fish) gameModeInversed = false case 48: //22 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fishInverted) case 49: //23 updateScreen(.mouseInverted, middle: .mouseInverted, right: .fish) gameModeInversed = true case 50: //24 updateScreen(.mouse, middle: .fish, right: .mouse) gameModeInversed = false case 51: //25 gameModeInversed = true updateScreen(.mouse, middle: .mouse, right: .fishInverted) case 52: //26 updateScreen(.mouse, middle: .fishInverted, right: .mouse) case 53: //27 updateScreen(.fishInverted, middle: .mouse, right: .mouse) case 54: //28 updateScreen(.fish, middle: .mouseInverted, right: .mouseInverted) gameModeInversed = true case 55: //29 updateScreen(.mouse, middle: .fish, right: .mouse) gameModeInversed = false case 56: presentMessage("...stop") case 57: presentPause() default: break } } } }
mit
ba5fee9dd9c96b9cf705146ac971518e
43.197095
414
0.579308
4.452968
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/tests/Storage/SDSDatabaseStorageObservationTest.swift
1
36238
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import XCTest @testable import SignalServiceKit class MockObserver { var updateCount: UInt = 0 var externalUpdateCount: UInt = 0 var resetCount: UInt = 0 var lastChange: SDSDatabaseStorageChange? private var expectation: XCTestExpectation? init() { AssertIsOnMainThread() SDSDatabaseStorage.shared.add(databaseStorageObserver: self) } func set(expectation: XCTestExpectation) { AssertIsOnMainThread() self.expectation = expectation } func clear() { updateCount = 0 externalUpdateCount = 0 resetCount = 0 lastChange = nil } } // MARK: - extension MockObserver: SDSDatabaseStorageObserver { func databaseStorageDidUpdate(change: SDSDatabaseStorageChange) { AssertIsOnMainThread() // YDB sometimes posts empty updates when no write has // occurred. The tests are simpler and more meaningful // if we ignore these. guard !change.isEmptyYDBChange else { return } updateCount += 1 lastChange = change expectation?.fulfill() expectation = nil } func databaseStorageDidUpdateExternally() { AssertIsOnMainThread() Logger.verbose("") externalUpdateCount += 1 expectation?.fulfill() expectation = nil } func databaseStorageDidReset() { AssertIsOnMainThread() Logger.verbose("") resetCount += 1 expectation?.fulfill() expectation = nil } } // MARK: - class SDSDatabaseStorageObservationTest: SSKBaseTestSwift { // MARK: - Dependencies var storageCoordinator: StorageCoordinator { return SSKEnvironment.shared.storageCoordinator } // MARK: - YDB func testYDBSyncWrite() { guard let primaryStorage = primaryStorage else { XCTFail("Missing primaryStorage.") return } // Make sure there's already at least one thread. var someThread: TSThread? self.yapWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+1222333444") someThread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction.asAnyWrite) } // First flush any pending notifications in OWSPrimaryStorage // from setup. primaryStorage.updateUIDatabaseConnectionToLatest() // First flush any pending notifications in SDSDatabaseStorageObservation // from setup. let flushExpectation = self.expectation(description: "Database Storage Observer") DispatchQueue.global().async { DispatchQueue.main.async { flushExpectation.fulfill() } } self.waitForExpectations(timeout: 1.0, handler: nil) let mockObserver = MockObserver() XCTAssertEqual(0, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNil(mockObserver.lastChange) mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) let keyValueStore = SDSKeyValueStore(collection: "test") let otherKeyValueStore = SDSKeyValueStore(collection: "other") self.yapWrite { transaction in keyValueStore.setBool(true, key: "test", transaction: transaction.asAnyWrite) Logger.verbose("write 1 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertFalse(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertTrue(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.yapWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+15551234567") _ = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction.asAnyWrite) Logger.verbose("write 2 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) var lastMessage: TSInteraction? var unsavedMessage: TSInteraction? self.yapWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+12345678900") let thread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction.asAnyWrite) let message = TSOutgoingMessage(in: thread, messageBody: "Hello Alice", attachmentId: nil) message.anyInsert(transaction: transaction.asAnyWrite) lastMessage = message unsavedMessage = TSOutgoingMessage(in: thread, messageBody: "Goodbyte Alice", attachmentId: nil) Logger.verbose("write 3 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.yapWrite { transaction in self.databaseStorage.touch(thread: someThread!, transaction: transaction.asAnyWrite) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertFalse(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.yapWrite { transaction in self.databaseStorage.touch(interaction: lastMessage!, transaction: transaction.asAnyWrite) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() } func testYDBAsyncWrite() { guard let primaryStorage = primaryStorage else { XCTFail("Missing primaryStorage.") return } // Make sure there's already at least one thread. var someThread: TSThread? self.yapWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+1222333444") someThread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction.asAnyWrite) } // First flush any pending notifications in OWSPrimaryStorage // from setup. primaryStorage.updateUIDatabaseConnectionToLatest() // First flush any pending notifications in SDSDatabaseStorageObservation // from setup. let flushExpectation = self.expectation(description: "Database Storage Observer") DispatchQueue.global().async { DispatchQueue.main.async { flushExpectation.fulfill() } } self.waitForExpectations(timeout: 1.0, handler: nil) let mockObserver = MockObserver() XCTAssertEqual(0, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNil(mockObserver.lastChange) mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) let keyValueStore = SDSKeyValueStore(collection: "test") let otherKeyValueStore = SDSKeyValueStore(collection: "other") self.yapAsyncWrite { transaction in keyValueStore.setBool(true, key: "test", transaction: transaction.asAnyWrite) Logger.verbose("write 1 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertFalse(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertTrue(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.yapAsyncWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+15551234567") _ = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction.asAnyWrite) Logger.verbose("write 2 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) var lastMessage: TSInteraction? var unsavedMessage: TSInteraction? self.yapAsyncWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+12345678900") let thread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction.asAnyWrite) let message = TSOutgoingMessage(in: thread, messageBody: "Hello Alice", attachmentId: nil) message.anyInsert(transaction: transaction.asAnyWrite) lastMessage = message unsavedMessage = TSOutgoingMessage(in: thread, messageBody: "Goodbyte Alice", attachmentId: nil) Logger.verbose("write 3 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.yapAsyncWrite { transaction in self.databaseStorage.touch(thread: someThread!, transaction: transaction.asAnyWrite) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertFalse(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.yapAsyncWrite { transaction in self.databaseStorage.touch(interaction: lastMessage!, transaction: transaction.asAnyWrite) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() } // MARK: - GRDB func testGRDBSyncWrite() { try! databaseStorage.grdbStorage.setupUIDatabase() // Make sure there's already at least one thread. var someThread: TSThread? self.write { transaction in let recipient = SignalServiceAddress(phoneNumber: "+1222333444") someThread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction) } // First flush any pending notifications in SDSDatabaseStorageObservation // from setup. let flushExpectation = self.expectation(description: "Database Storage Observer") DispatchQueue.main.async { DispatchQueue.main.async { flushExpectation.fulfill() } } self.waitForExpectations(timeout: 1.0, handler: nil) let mockObserver = MockObserver() XCTAssertEqual(0, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNil(mockObserver.lastChange) mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) let keyValueStore = SDSKeyValueStore(collection: "test") let otherKeyValueStore = SDSKeyValueStore(collection: "other") self.write { transaction in keyValueStore.setBool(true, key: "test", transaction: transaction) Logger.verbose("write 1 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertFalse(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertTrue(lastChange.didUpdate(keyValueStore: keyValueStore)) // Note: For GRDB, didUpdate(keyValueStore:) currently returns true // if any key value stores was updated. if self.storageCoordinator.state == .YDB || self.storageCoordinator.state == .ydbTests { XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } else { XCTAssertTrue(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.write { transaction in let recipient = SignalServiceAddress(phoneNumber: "+15551234567") _ = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction) Logger.verbose("write 2 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) var lastMessage: TSInteraction? var unsavedMessage: TSInteraction? self.write { transaction in let recipient = SignalServiceAddress(phoneNumber: "+12345678900") let thread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction) let message = TSOutgoingMessage(in: thread, messageBody: "Hello Alice", attachmentId: nil) message.anyInsert(transaction: transaction) message.anyReload(transaction: transaction) lastMessage = message unsavedMessage = TSOutgoingMessage(in: thread, messageBody: "Goodbyte Alice", attachmentId: nil) Logger.verbose("write 3 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.write { transaction in self.databaseStorage.touch(thread: someThread!, transaction: transaction) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertFalse(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.write { transaction in self.databaseStorage.touch(interaction: lastMessage!, transaction: transaction) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() } func testGRDBAsyncWrite() { try! databaseStorage.grdbStorage.setupUIDatabase() // Make sure there's already at least one thread. var someThread: TSThread? self.write { transaction in let recipient = SignalServiceAddress(phoneNumber: "+1222333444") someThread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction) } // First flush any pending notifications in SDSDatabaseStorageObservation // from setup. let flushExpectation = self.expectation(description: "Database Storage Observer") DispatchQueue.main.async { DispatchQueue.main.async { flushExpectation.fulfill() } } self.waitForExpectations(timeout: 1.0, handler: nil) let mockObserver = MockObserver() XCTAssertEqual(0, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNil(mockObserver.lastChange) mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) let keyValueStore = SDSKeyValueStore(collection: "test") let otherKeyValueStore = SDSKeyValueStore(collection: "other") self.asyncWrite { transaction in keyValueStore.setBool(true, key: "test", transaction: transaction) Logger.verbose("write 1 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertFalse(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertTrue(lastChange.didUpdate(keyValueStore: keyValueStore)) // Note: For GRDB, didUpdate(keyValueStore:) currently returns true // if any key value stores was updated. if self.storageCoordinator.state == .YDB || self.storageCoordinator.state == .ydbTests { XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } else { XCTAssertTrue(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.asyncWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+15551234567") _ = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction) Logger.verbose("write 2 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) var lastMessage: TSInteraction? var unsavedMessage: TSInteraction? self.asyncWrite { transaction in let recipient = SignalServiceAddress(phoneNumber: "+12345678900") let thread = TSContactThread.getOrCreateThread(withContactAddress: recipient, transaction: transaction) let message = TSOutgoingMessage(in: thread, messageBody: "Hello Alice", attachmentId: nil) message.anyInsert(transaction: transaction) message.anyReload(transaction: transaction) lastMessage = message unsavedMessage = TSOutgoingMessage(in: thread, messageBody: "Goodbyte Alice", attachmentId: nil) Logger.verbose("write 3 complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.asyncWrite { transaction in self.databaseStorage.touch(thread: someThread!, transaction: transaction) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertFalse(lastChange.didUpdateInteractions) XCTAssertTrue(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertFalse(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() mockObserver.set(expectation: self.expectation(description: "Database Storage Observer")) self.asyncWrite { transaction in self.databaseStorage.touch(interaction: lastMessage!, transaction: transaction) Logger.verbose("Touch complete") } self.waitForExpectations(timeout: 1.0, handler: nil) XCTAssertEqual(1, mockObserver.updateCount) XCTAssertEqual(0, mockObserver.externalUpdateCount) XCTAssertEqual(0, mockObserver.resetCount) XCTAssertNotNil(mockObserver.lastChange) if let lastChange = mockObserver.lastChange { XCTAssertTrue(lastChange.didUpdateInteractions) XCTAssertFalse(lastChange.didUpdateThreads) XCTAssertTrue(lastChange.didUpdateInteractionsOrThreads) XCTAssertFalse(lastChange.didUpdateModel(collection: OWSDevice.collection())) XCTAssertFalse(lastChange.didUpdateModel(collection: "invalid collection name")) XCTAssertFalse(lastChange.didUpdate(keyValueStore: keyValueStore)) XCTAssertFalse(lastChange.didUpdate(keyValueStore: otherKeyValueStore)) XCTAssertTrue(lastChange.didUpdate(interaction: lastMessage!)) XCTAssertFalse(lastChange.didUpdate(interaction: unsavedMessage!)) } mockObserver.clear() } }
gpl-3.0
7b90642ab63a4ae5b781fa1313b9639b
44.184539
126
0.697831
5.427288
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCoin/Sources/FeatureCoinUI/CoinView/Components/Accounts/AccountListView.swift
1
5103
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import BlockchainNamespace import Combine import ComposableArchitecture import FeatureCoinDomain import Foundation import Localization import MoneyKit import SwiftUI public struct AccountListView: View { private typealias Localization = LocalizationConstants.Coin.Accounts @BlockchainApp var app @Environment(\.context) var context let accounts: [Account.Snapshot] let currency: CryptoCurrency let interestRate: Double? let kycStatus: KYCStatus? var __accounts: [Account.Snapshot] { switch kycStatus { case .none, .unverified, .inReview: return accounts.filter(\.isPrivateKey) case .silver, .silverPlus, .gold: return accounts } } var isDefiMode: Bool { accounts.count == 1 && accounts.first?.accountType == .privateKey } public var body: some View { VStack(spacing: 0) { if accounts.isEmpty { loading() } else { ForEach(__accounts) { account in AccountRow( account: account, assetColor: currency.color, interestRate: interestRate ) .context( [ blockchain.ux.asset.account.id: account.id, blockchain.ux.asset.account: account ] ) PrimaryDivider() } switch kycStatus { case .none, .unverified, .inReview: locked() case .silver, .silverPlus, .gold: EmptyView() } } } .overlay( RoundedRectangle(cornerRadius: 16) .stroke(isDefiMode ? Color.semantic.medium : .clear, lineWidth: 1) ) .padding(.horizontal, Spacing.padding1) } @ViewBuilder func loading() -> some View { Group { ForEach(1...3, id: \.self) { _ in LockedAccountRow( title: Localization.tradingAccountTitle, subtitle: Localization.tradingAccountSubtitle, icon: .trade ) PrimaryDivider() } } .disabled(true) .redacted(reason: .placeholder) } @ViewBuilder func locked() -> some View { if currency.supports(product: .custodialWalletBalance) { LockedAccountRow( title: Localization.tradingAccountTitle, subtitle: Localization.tradingAccountSubtitle, icon: .trade ) .context([blockchain.ux.asset.account.type: Account.AccountType.trading]) PrimaryDivider() } if currency.supports(product: .interestBalance) { LockedAccountRow( title: Localization.rewardsAccountTitle, subtitle: Localization.rewardsAccountSubtitle.interpolating(interestRate.or(0)), icon: .interestCircle ) .context([blockchain.ux.asset.account.type: Account.AccountType.interest]) PrimaryDivider() } } } // swiftlint:disable type_name struct AccountListView_PreviewProvider: PreviewProvider { static var previews: some View { AccountListView( accounts: [ .preview.privateKey, .preview.trading, .preview.rewards ], currency: .bitcoin, interestRate: nil, kycStatus: .gold ) .previewDisplayName("Gold") AccountListView( accounts: [ .preview.privateKey, .preview.trading, .preview.rewards ], currency: .bitcoin, interestRate: nil, kycStatus: .silver ) .previewDisplayName("Silver") AccountListView( accounts: [ .preview.privateKey, .preview.trading, .preview.rewards ], currency: .bitcoin, interestRate: nil, kycStatus: .unverified ) .previewDisplayName("Unverified") AccountListView( accounts: [ .preview.privateKey ], currency: .bitcoin, interestRate: nil, kycStatus: .unverified ) .previewDisplayName("Single Account Defi") AccountListView( accounts: [ .preview.privateKey, .preview.privateKey ], currency: .bitcoin, interestRate: nil, kycStatus: .unverified ) .previewDisplayName("Double Account Defi") } } extension Account.Snapshot { var isPrivateKey: Bool { accountType == .privateKey } }
lgpl-3.0
6fce25b51787a8bdfcb6712eb5594d92
28.836257
96
0.52254
5.486022
false
false
false
false
juliangrosshauser/Countdown
Countdown/Source/BirthdayController.swift
1
2223
// // BirthdayController.swift // Countdown // // Created by Julian Grosshauser on 19/10/15. // Copyright © 2015 Julian Grosshauser. All rights reserved. // import UIKit import CountdownKit class BirthdayController: UIViewController { //MARK: Properties private let viewModel: CountdownViewModel private let datePicker: UIDatePicker = { let datePicker = UIDatePicker() datePicker.translatesAutoresizingMaskIntoConstraints = false datePicker.datePickerMode = .Date datePicker.minimumDate = NSDate.date(day: 1, month: 1, year: 1900) datePicker.maximumDate = NSDate() return datePicker }() //MARK: Initialization init(viewModel: CountdownViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) title = NSLocalizedString("Birthday", comment: "Title of birthday date picker") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "save:") view.addSubview(datePicker) if let birthday = viewModel.birthday { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancel:") datePicker.setDate(birthday, animated: true) } NSLayoutConstraint(item: datePicker, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0).active = true NSLayoutConstraint(item: datePicker, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0).active = true } //MARK: Button Actions @objc private func save(sender: UIBarButtonItem) { viewModel.birthday = datePicker.date presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @objc private func cancel(sender: UIBarButtonItem) { presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } }
mit
341d5286fceebb8fb5d885e11f8fb5ba
32.164179
161
0.691719
5.073059
false
false
false
false
toshiapp/toshi-ios-client
Toshi/Views/TitleLabel.swift
1
1050
// Copyright (c) 2018 Token Browser, Inc // // 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 UIKit import SweetUIKit class TitleLabel: UILabel { convenience init(_ title: String) { self.init(withAutoLayout: true) textColor = Theme.darkTextColor font = Theme.preferredSemibold() adjustsFontForContentSizeCategory = true numberOfLines = 0 text = title textAlignment = .center } }
gpl-3.0
47a61c77286058c471a51f9431478957
32.870968
72
0.712381
4.525862
false
false
false
false
Tea-and-Coffee/CollectionView-Sample-Swift
CollectionView-Sample/Model/WEForecast.swift
1
890
// // WEForecast.swift // // Create by masato arai on 1/9/2016 // Copyright © 2016. All rights reserved. // Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation struct WEForecast{ var date : String? var dateLabel : String? var image : WEImage? var telop : String? var temperature : WETemperature? /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary){ date = dictionary["date"] as? String dateLabel = dictionary["dateLabel"] as? String if let imageData = dictionary["image"] as? NSDictionary{ image = WEImage(fromDictionary: imageData) } telop = dictionary["telop"] as? String if let temperatureData = dictionary["temperature"] as? NSDictionary{ temperature = WETemperature(fromDictionary: temperatureData) } } }
mit
31e9d3edc2324cdaefbb975f48cd8459
25.147059
92
0.727784
3.815451
false
false
false
false
Conche/Conche
Conche/Task.swift
2
943
protocol Task { var name: String { get } var dependencies: [Task] { get } var isRequired: Bool { get } func run() throws } extension Task { var dependencies: [Task] { return [] } var isRequired: Bool { return true } } func runTask(task: Task) throws { func innerRunTask(task: Task) throws -> Bool { let results = try task.dependencies.map { try innerRunTask($0) } let didRun = results.filter { $0 }.first ?? false if didRun || task.isRequired { print("-> \(task.name)") try task.run() return true } return false } try innerRunTask(task) } class AnonymousTask : Task { let name: String let closure: () throws -> () var dependencies: [Task] init(_ name: String, dependencies: [Task]? = nil, closure: () throws -> ()) { self.name = name self.dependencies = dependencies ?? [] self.closure = closure } func run() throws { try closure() } }
bsd-2-clause
8fea2adf8e21699f59218247bd1fa56a
18.244898
79
0.604454
3.756972
false
false
false
false
kazazor/jxcore-nodejs-socketio-c-plus-plus
Winnery/SocketIOClient/SocketEngine.swift
2
26325
// // SocketEngine.swift // Socket.IO-Client-Swift // // Created by Erik Little on 3/3/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public final class SocketEngine: NSObject, SocketEngineSpec, WebSocketDelegate { public private(set) var sid = "" public private(set) var cookies: [NSHTTPCookie]? public private(set) var socketPath = "/engine.io" public private(set) var urlPolling = "" public private(set) var urlWebSocket = "" public private(set) var ws: WebSocket? public weak var client: SocketEngineClient? private weak var sessionDelegate: NSURLSessionDelegate? private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData]) private typealias ProbeWaitQueue = [Probe] private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet private let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL) private let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL) private let logType = "SocketEngine" private let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL) private let url: String private let workQueue = NSOperationQueue() private var connectParams: [String: AnyObject]? private var closed = false private var extraHeaders: [String: String]? private var fastUpgrade = false private var forcePolling = false private var forceWebsockets = false private var invalidated = false private var pingInterval: Double? private var pingTimer: NSTimer? private var pingTimeout = 0.0 { didSet { pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25)) } } private var pongsMissed = 0 private var pongsMissedMax = 0 private var postWait = [String]() private var probing = false private var probeWait = ProbeWaitQueue() private var secure = false private var session: NSURLSession? private var voipEnabled = false private var waitingForPoll = false private var waitingForPost = false private var websocketConnected = false private(set) var connected = false private(set) var polling = true private(set) var websocket = false public init(client: SocketEngineClient, url: String, options: Set<SocketIOClientOption>) { self.client = client self.url = url for option in options { switch option { case .SessionDelegate(let delegate): sessionDelegate = delegate case .ForcePolling(let force): forcePolling = force case .ForceWebsockets(let force): forceWebsockets = force case .Cookies(let cookies): self.cookies = cookies case .Path(let path): socketPath = path case .ExtraHeaders(let headers): extraHeaders = headers case .VoipEnabled(let enable): voipEnabled = enable case .Secure(let secure): self.secure = secure default: continue } } } public convenience init(client: SocketEngineClient, url: String, options: NSDictionary?) { self.init(client: client, url: url, options: Set<SocketIOClientOption>.NSDictionaryToSocketOptionsSet(options ?? [:])) } deinit { DefaultSocketLogger.Logger.log("Engine is being deinit", type: logType) closed = true stopPolling() } private func checkAndHandleEngineError(msg: String) { guard let stringData = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return } do { if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { guard let code = dict["code"] as? Int else { return } guard let error = dict["message"] as? String else { return } switch code { case 0: // Unknown transport logAndError(error) case 1: // Unknown sid. clear and retry connect sid = "" open(connectParams) case 2: // Bad handshake request logAndError(error) case 3: // Bad request logAndError(error) default: logAndError(error) } } } catch { logAndError("Got unknown error from server") } } private func checkIfMessageIsBase64Binary(var message: String) -> Bool { if message.hasPrefix("b4") { // binary in base64 string message.removeRange(Range(start: message.startIndex, end: message.startIndex.advancedBy(2))) if let data = NSData(base64EncodedString: message, options: .IgnoreUnknownCharacters) { client?.parseBinaryData(data) } return true } else { return false } } public func close() { DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType) pingTimer?.invalidate() closed = true connected = false if websocket { sendWebSocketMessage("", withType: .Close) } else { sendPollMessage("", withType: .Close) } ws?.disconnect() stopPolling() client?.engineDidClose("Disconnect") } private func createBinaryDataForSend(data: NSData) -> Either<NSData, String> { if websocket { var byteArray = [UInt8](count: 1, repeatedValue: 0x0) byteArray[0] = 4 let mutData = NSMutableData(bytes: &byteArray, length: 1) mutData.appendData(data) return .Left(mutData) } else { let str = "b4" + data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) return .Right(str) } } private func createURLs(params: [String: AnyObject]?) -> (String, String) { if client == nil { return ("", "") } let socketURL = "\(url)\(socketPath)/?transport=" var urlPolling: String var urlWebSocket: String if secure { urlPolling = "https://" + socketURL + "polling" urlWebSocket = "wss://" + socketURL + "websocket" } else { urlPolling = "http://" + socketURL + "polling" urlWebSocket = "ws://" + socketURL + "websocket" } if params != nil { for (key, value) in params! { let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters( allowedCharacterSet)! urlPolling += "&\(keyEsc)=" urlWebSocket += "&\(keyEsc)=" if value is String { let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters( allowedCharacterSet)! urlPolling += "\(valueEsc)" urlWebSocket += "\(valueEsc)" } else { urlPolling += "\(value)" urlWebSocket += "\(value)" } } } return (urlPolling, urlWebSocket) } private func createWebsocketAndConnect(connect: Bool) { let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)") ws = WebSocket(url: NSURL(string: wsUrl)!) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) for (key, value) in headers { ws?.headers[key] = value } } if extraHeaders != nil { for (headerName, value) in extraHeaders! { ws?.headers[headerName] = value } } ws?.queue = handleQueue ws?.voipEnabled = voipEnabled ws?.delegate = self if connect { ws?.connect() } } private func doFastUpgrade() { if waitingForPoll { DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," + "we'll probably disconnect soon. You should report this.", type: logType) } sendWebSocketMessage("", withType: .Upgrade, datas: nil) websocket = true polling = false fastUpgrade = false probing = false flushProbeWait() } private func flushProbeWait() { DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType) dispatch_async(emitQueue) {[weak self] in if let this = self { for waiter in this.probeWait { this.write(waiter.msg, withType: waiter.type, withData: waiter.data) } this.probeWait.removeAll(keepCapacity: false) if this.postWait.count != 0 { this.flushWaitingForPostToWebSocket() } } } } private func handleClose(reason: String) { client?.engineDidClose(reason) } private func handleMessage(message: String) { client?.parseSocketMessage(message) } private func handleNOOP() { doPoll() } private func handleOpen(openData: String) { let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! do { let json = try NSJSONSerialization.JSONObjectWithData(mesData, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary if let sid = json?["sid"] as? String { let upgradeWs: Bool self.sid = sid connected = true if let upgrades = json?["upgrades"] as? [String] { upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0 } else { upgradeWs = false } if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double { self.pingInterval = pingInterval / 1000.0 self.pingTimeout = pingTimeout / 1000.0 } if !forcePolling && !forceWebsockets && upgradeWs { createWebsocketAndConnect(true) } } } catch { DefaultSocketLogger.Logger.error("Error parsing open packet", type: logType) return } startPingTimer() if !forceWebsockets { doPoll() } } private func handlePong(pongMessage: String) { pongsMissed = 0 // We should upgrade if pongMessage == "3probe" { upgradeTransport() } } // A poll failed, tell the client about it private func handlePollingFailed(reason: String) { connected = false ws?.disconnect() pingTimer?.invalidate() waitingForPoll = false waitingForPost = false if !closed { client?.didError(reason) client?.engineDidClose(reason) } } private func logAndError(error: String) { DefaultSocketLogger.Logger.error(error, type: logType) client?.didError(error) } public func open(opts: [String: AnyObject]? = nil) { connectParams = opts if connected { DefaultSocketLogger.Logger.error("Tried to open while connected", type: logType) client?.didError("Tried to open engine while connected") return } DefaultSocketLogger.Logger.log("Starting engine", type: logType) DefaultSocketLogger.Logger.log("Handshaking", type: logType) resetEngine() (urlPolling, urlWebSocket) = createURLs(opts) if forceWebsockets { polling = false websocket = true createWebsocketAndConnect(true) return } let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) reqPolling.allHTTPHeaderFields = headers } if let extraHeaders = extraHeaders { for (headerName, value) in extraHeaders { reqPolling.setValue(value, forHTTPHeaderField: headerName) } } doLongPoll(reqPolling) } private func parseEngineData(data: NSData) { DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data) client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1))) } private func parseEngineMessage(var message: String, fromPolling: Bool) { DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message) let reader = SocketStringReader(message: message) guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else { if !checkIfMessageIsBase64Binary(message) { checkAndHandleEngineError(message) } return } if fromPolling && type != .Noop { fixDoubleUTF8(&message) } switch type { case .Message: message.removeAtIndex(message.startIndex) handleMessage(message) case .Noop: handleNOOP() case .Pong: handlePong(message) case .Open: message.removeAtIndex(message.startIndex) handleOpen(message) case .Close: handleClose(message) default: DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType) } } private func probeWebSocket() { if websocketConnected { sendWebSocketMessage("probe", withType: .Ping) } } private func resetEngine() { closed = false connected = false fastUpgrade = false polling = true probing = false invalidated = false session = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: sessionDelegate, delegateQueue: workQueue) sid = "" waitingForPoll = false waitingForPost = false websocket = false websocketConnected = false } /// Send an engine message (4) public func send(msg: String, withData datas: [NSData]) { if probing { probeWait.append((msg, .Message, datas)) } else { write(msg, withType: .Message, withData: datas) } } @objc private func sendPing() { //Server is not responding if pongsMissed > pongsMissedMax { pingTimer?.invalidate() client?.engineDidClose("Ping timeout") return } ++pongsMissed write("", withType: .Ping, withData: []) } // Starts the ping timer private func startPingTimer() { if let pingInterval = pingInterval { pingTimer?.invalidate() pingTimer = nil dispatch_async(dispatch_get_main_queue()) { self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self, selector: Selector("sendPing"), userInfo: nil, repeats: true) } } } private func upgradeTransport() { if websocketConnected { DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType) fastUpgrade = true sendPollMessage("", withType: .Noop) // After this point, we should not send anymore polling messages } } /** Write a message, independent of transport. */ public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) { dispatch_async(emitQueue) { if self.connected { if self.websocket { DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg, data.count != 0) self.sendWebSocketMessage(msg, withType: type, datas: data) } else { DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg, data.count != 0) self.sendPollMessage(msg, withType: type, datas: data) } } } } } // Polling methods extension SocketEngine { private func addHeaders(req: NSMutableURLRequest) { if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) req.allHTTPHeaderFields = headers } if extraHeaders != nil { for (headerName, value) in extraHeaders! { req.setValue(value, forHTTPHeaderField: headerName) } } } private func doPoll() { if websocket || waitingForPoll || !connected || closed { return } waitingForPoll = true let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!) addHeaders(req) doLongPoll(req) } private func doRequest(req: NSMutableURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) { if !polling || closed || invalidated { DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: logType) return } DefaultSocketLogger.Logger.log("Doing polling request", type: logType) req.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData session?.dataTaskWithRequest(req, completionHandler: callback).resume() } private func doLongPoll(req: NSMutableURLRequest) { doRequest(req) {[weak self] data, res, err in guard let this = self else {return} if err != nil || data == nil { DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: this.logType) if this.polling { this.handlePollingFailed(err?.localizedDescription ?? "Error") } return } DefaultSocketLogger.Logger.log("Got polling response", type: this.logType) if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String { dispatch_async(this.parseQueue) {[weak this] in this?.parsePollingMessage(str) } } this.waitingForPoll = false if this.fastUpgrade { this.doFastUpgrade() } else if !this.closed && this.polling { this.doPoll() } } } private func flushWaitingForPost() { if postWait.count == 0 || !connected { return } else if websocket { flushWaitingForPostToWebSocket() return } var postStr = "" for packet in postWait { let len = packet.characters.count postStr += "\(len):\(packet)" } postWait.removeAll(keepCapacity: false) let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!) addHeaders(req) req.HTTPMethod = "POST" req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type") let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! req.HTTPBody = postData req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length") waitingForPost = true DefaultSocketLogger.Logger.log("POSTing: %@", type: logType, args: postStr) doRequest(req) {[weak self] data, res, err in guard let this = self else {return} if err != nil { DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: this.logType) if this.polling { this.handlePollingFailed(err?.localizedDescription ?? "Error") } return } this.waitingForPost = false dispatch_async(this.emitQueue) {[weak this] in if !(this?.fastUpgrade ?? true) { this?.flushWaitingForPost() this?.doPoll() } } } } // We had packets waiting for send when we upgraded // Send them raw private func flushWaitingForPostToWebSocket() { guard let ws = self.ws else {return} for msg in postWait { ws.writeString(msg) } postWait.removeAll(keepCapacity: true) } func parsePollingMessage(str: String) { guard str.characters.count != 1 else { return } var reader = SocketStringReader(message: str) while reader.hasNext { if let n = Int(reader.readUntilStringOccurence(":")) { let str = reader.read(n) dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } } else { dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } break } } } /// Send polling message. /// Only call on emitQueue private func sendPollMessage(var msg: String, withType type: SocketEnginePacketType, datas:[NSData]? = nil) { DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: logType, args: msg, type.rawValue) doubleEncodeUTF8(&msg) let strMsg = "\(type.rawValue)\(msg)" postWait.append(strMsg) for data in datas ?? [] { if case let .Right(bin) = createBinaryDataForSend(data) { postWait.append(bin) } } if !waitingForPost { flushWaitingForPost() } } private func stopPolling() { invalidated = true session?.finishTasksAndInvalidate() } } // WebSocket methods extension SocketEngine { /// Send message on WebSockets /// Only call on emitQueue private func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, datas:[NSData]? = nil) { DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: logType, args: str, type.rawValue) ws?.writeString("\(type.rawValue)\(str)") for data in datas ?? [] { if case let Either.Left(bin) = createBinaryDataForSend(data) { ws?.writeData(bin) } } } // Delagate methods public func websocketDidConnect(socket:WebSocket) { websocketConnected = true if !forceWebsockets { probing = true probeWebSocket() } else { connected = true probing = false polling = false } } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { websocketConnected = false probing = false if closed { client?.engineDidClose("Disconnect") return } if websocket { pingTimer?.invalidate() connected = false websocket = false let reason = error?.localizedDescription ?? "Socket Disconnected" if error != nil { client?.didError(reason) } client?.engineDidClose(reason) } else { flushProbeWait() } } public func websocketDidReceiveMessage(socket: WebSocket, text: String) { parseEngineMessage(text, fromPolling: false) } public func websocketDidReceiveData(socket: WebSocket, data: NSData) { parseEngineData(data) } }
apache-2.0
b029d2f853999520a1bddb4ba8414fac
31.82419
119
0.557189
5.430074
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/DownloadContentScript.swift
2
2918
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import WebKit class DownloadContentScript: TabContentScript { fileprivate weak var tab: Tab? // Non-blob URLs use the webview to download, by navigating in the webview to the requested URL. // Blobs however, use the JS content script to download using XHR fileprivate static var blobUrlForDownload: URL? class func name() -> String { return "DownloadContentScript" } required init(tab: Tab) { self.tab = tab } func scriptMessageHandlerName() -> String? { return "downloadManager" } static func requestDownload(url: URL, tab: Tab) { let safeUrl = url.absoluteString.replacingOccurrences(of: "'", with: "%27") blobUrlForDownload = url.scheme == "blob" ? URL(string: safeUrl) : nil tab.webView?.evaluateJavaScript("window.__firefox__.download('\(safeUrl)', '\(UserScriptManager.securityToken)')") UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .downloadLinkButton) } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { guard let browserViewController = tab?.browserViewController, let dictionary = message.body as? [String: Any?], let _url = dictionary["url"] as? String, let url = URL(string: _url), let mimeType = dictionary["mimeType"] as? String, let size = dictionary["size"] as? Int64, let base64String = dictionary["base64String"] as? String, let data = Bytes.decodeBase64(base64String) else { return } defer { browserViewController.pendingDownloadWebView = nil DownloadContentScript.blobUrlForDownload = nil } guard let requestedUrl = DownloadContentScript.blobUrlForDownload else { print("DownloadContentScript: no url was requested") return } guard requestedUrl == url else { print("DownloadContentScript: URL mismatch") return } // Note: url.lastPathComponent fails on blob: URLs (shrug). var filename = url.absoluteString.components(separatedBy: "/").last ?? "data" if filename.isEmpty { filename = "data" } if !filename.contains(".") { if let fileExtension = MIMEType.fileExtensionFromMIMEType(mimeType) { filename += ".\(fileExtension)" } } let download = BlobDownload(filename: filename, mimeType: mimeType, size: size, data: data) tab?.browserViewController?.downloadQueue.enqueue(download) } }
mpl-2.0
54cd9c915e5ec8151a6d0a9b461ff4ba
37.394737
132
0.642563
4.895973
false
false
false
false
Tj3n/TVNExtensions
Rx/ActivityIndicator.swift
1
2177
// // ActivityIndicator.swift // TVNExtensions // // Created by TienVu on 2/14/19. // import RxSwift import RxCocoa private struct ActivityToken<E> : ObservableConvertibleType, Disposable { private let _source: Observable<E> private let _dispose: Cancelable init(source: Observable<E>, disposeAction: @escaping () -> ()) { _source = source _dispose = Disposables.create(with: disposeAction) } func dispose() { _dispose.dispose() } func asObservable() -> Observable<E> { return _source } } /** Enables monitoring of sequence computation. If there is at least one sequence computation in progress, `true` will be sent. When all activities complete `false` will be sent. */ public class ActivityIndicator : SharedSequenceConvertibleType { public typealias Element = Bool public typealias SharingStrategy = DriverSharingStrategy private let _lock = NSRecursiveLock() private let _relay = BehaviorRelay(value: 0) private let _loading: SharedSequence<SharingStrategy, Bool> public init() { _loading = _relay.asDriver() .map { $0 > 0 } .distinctUntilChanged() } fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.Element> { return Observable.using({ () -> ActivityToken<O.Element> in self.increment() return ActivityToken(source: source.asObservable(), disposeAction: self.decrement) }) { t in return t.asObservable() } } private func increment() { _lock.lock() _relay.accept(_relay.value + 1) _lock.unlock() } private func decrement() { _lock.lock() _relay.accept(_relay.value - 1) _lock.unlock() } public func asSharedSequence() -> SharedSequence<SharingStrategy, Element> { return _loading } } extension ObservableConvertibleType { public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<Element> { return activityIndicator.trackActivityOfObservable(self) } }
mit
cac6664374175d65a92c64bb1ef3dd58
26.556962
116
0.640331
4.816372
false
false
false
false
Andgfaria/MiniGitClient-iOS
MiniGitClient/MiniGitClientTests/Scenes/Detail/Cell/PullRequestCellViewModelSpec.swift
1
2689
/* Copyright 2017 - André Gimenez Faria 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 Quick import Nimble @testable import MiniGitClient class PullRequestCellViewModelSpec: QuickSpec { override func spec() { describe("The PullRequestCellViewModel") { var testPullRequest = PullRequest() beforeEach { testPullRequest.title = "Test" testPullRequest.body = "Test Body" var testUser = User() testUser.name = "André" testUser.avatarURL = URL(string: "https://camo.mybb.com/e01de90be6012adc1b1701dba899491a9348ae79/687474703a2f2f7777772e6a71756572797363726970742e6e65742f696d616765732f53696d706c6573742d526573706f6e736976652d6a51756572792d496d6167652d4c69676874626f782d506c7567696e2d73696d706c652d6c69676874626f782e6a7067") testPullRequest.user = testUser } context("configures", { it("the PullRequestTableViewCell") { let cell = PullRequestTableViewCell(style: .default, reuseIdentifier: nil) PullRequestCellViewModel.configure(cell, withPullRequest: testPullRequest) expect(cell.titleLabel.text) == testPullRequest.title expect(cell.bodyTextView.text) == testPullRequest.body expect(cell.authorLabel.text) == testPullRequest.user?.name expect(cell.avatarImageView.image).toEventuallyNot(beNil(), timeout: 30.0, pollInterval: 10.0) } }) } } }
mit
0362aad5ccc12c6410584a64dc716d85
51.686275
461
0.67808
4.697552
false
true
false
false
eRGoon/RGPageViewController
Example/RGViewPager/Examples/ExampleTopBarViewController.swift
1
2806
// // ExampleTopBarViewController.swift // RGViewPager // // Created by Ronny Gerasch on 10.11.14. // Copyright (c) 2014 Ronny Gerasch. All rights reserved. // import Foundation import RGPageViewController import UIKit class ExampleTopBarViewController: RGPageViewController { override var pagerOrientation: UIPageViewControllerNavigationOrientation { return .horizontal } override var tabbarPosition: RGTabbarPosition { return .top } override var tabbarStyle: RGTabbarStyle { return .blurred } override var tabIndicatorColor: UIColor { return UIColor.white } override var barTintColor: UIColor? { return self.navigationController?.navigationBar.barTintColor } override var tabStyle: RGTabStyle { return .inactiveFaded } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.currentTabIndex = 3 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.currentTabIndex = 3 } override func viewDidLoad() { super.viewDidLoad() datasource = self delegate = self } @IBAction func reloadPager(_ sender: UIBarButtonItem) { reloadData() } } // MARK: - RGPageViewControllerDataSource extension ExampleTopBarViewController: RGPageViewControllerDataSource { func numberOfPages(for pageViewController: RGPageViewController) -> Int { return movies.count } func pageViewController(_ pageViewController: RGPageViewController, tabViewForPageAt index: Int) -> UIView { let tabView = UILabel() tabView.font = UIFont.systemFont(ofSize: 17) tabView.text = movies[index]["title"] as? String tabView.textColor = UIColor.white tabView.sizeToFit() return tabView } func pageViewController(_ pageViewController: RGPageViewController, viewControllerForPageAt index: Int) -> UIViewController? { if (movies.count == 0) || (index >= movies.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard!.instantiateViewController(withIdentifier: "MovieViewController") as! MovieViewController dataViewController.movieData = movies[index] return dataViewController } } // MARK: - RGPageViewController Delegate extension ExampleTopBarViewController: RGPageViewControllerDelegate { // use this to set a custom width for a tab func pageViewController(_ pageViewController: RGPageViewController, widthForTabAt index: Int) -> CGFloat { var tabSize = (movies[index]["title"] as! String).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17)]) tabSize.width += 32 return tabSize.width } }
mit
619750e73e216b88b9adf84dc125fc9e
25.980769
129
0.720955
4.863085
false
false
false
false
JerrySir/YCOA
YCOA/Main/My/Controller/MyInfoTableViewController.swift
1
8643
// // MyInfoTableViewController.swift // YCOA // // Created by Jerry on 2016/12/14. // Copyright © 2016年 com.baochunsteel. All rights reserved. // import UIKit import Alamofire import UITableView_FDTemplateLayoutCell import MJRefresh class MyInfoTableViewController: UITableViewController { var userInfo : (name: String?, user: String?, deptname: String?, ranking: String?, face: String?, companyid: String?, tel: String?, mobile: String?, email: String?, gender: String?, company: String?)? override func viewDidLoad() { super.viewDidLoad() self.title = "个人中心" self.view.backgroundColor = UIColor.groupTableViewBackground self.tableView.backgroundColor = UIColor.groupTableViewBackground self.tableView.separatorStyle = .none self.tableView.register(UINib(nibName: "MyInfoDescriptionTableViewCell", bundle: nil), forCellReuseIdentifier: "MyInfoDescriptionTableViewCell") self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(reloadData)) self.tableView.mj_header.beginRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if(UserCenter.shareInstance().isLogin){ self.reloadData() } } func reloadData() { guard UserCenter.shareInstance().isLogin else { self.view.jrShow(withTitle: "未登录!") self.tableView.mj_header.endRefreshing() return } let parameters: Parameters = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!, "uid": UserCenter.shareInstance().uid!] guard let url = URL.JRURLEnCoding(string: YCOA_REQUEST_URL.appending("/index.php?d=taskrun&m=user|appapi&a=gereninfor&ajaxbool=true")) else { self.tableView.mj_header.endRefreshing() return } Alamofire.request(url, parameters: parameters).responseJSON(completionHandler: { (response) in self.tableView.mj_header.endRefreshing() guard response.result.isSuccess else{ self.view.jrShow(withTitle: "网络错误") return } guard let returnValue : NSDictionary = response.result.value as? NSDictionary else{ self.view.jrShow(withTitle: "服务器错误") return } guard returnValue.value(forKey: "code") as! Int == 200 else{ self.view.jrShow(withTitle: "\(returnValue.value(forKey: "msg")!)") return } guard let data : NSDictionary = returnValue.value(forKey: "data") as? NSDictionary else{ self.view.jrShow(withTitle: "服务器故障") return } //同步数据 let name = data["name"] as? String let user = data["user"] as? String let deptname = data["deptname"] as? String let ranking = data["ranking"] as? String let face = data["face"] as? String let companyid = data["companyid"] as? String let tel = data["tel"] as? String let mobile = data["mobile"] as? String let email = data["email"] as? String let gender = data["gender"] as? String let company = data["company"] as? String self.userInfo = (name, user, deptname, ranking, face, companyid, tel, mobile, email, gender, company) self.tableView.reloadData() }) } // MARK: - Table view data source override func numberOfSections(in 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 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : MyInfoDescriptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MyInfoDescriptionTableViewCell", for: indexPath) as! MyInfoDescriptionTableViewCell guard self.userInfo != nil else { return cell } cell.configure(headIconURL: YCOA_REQUEST_URL + "/" + self.userInfo!.face!, name: self.userInfo!.name, department: self.userInfo!.deptname, position: self.userInfo!.ranking, account: self.userInfo!.user, company: self.userInfo!.company, uid: self.userInfo!.companyid) cell.configureLogout { let alert = UIAlertView(title: "退出登录", message: "您确定要退出登录吗?", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定") alert.show() alert.rac_buttonClickedSignal().subscribeNext({ (index) in if((index as! Int) == 1){ UserCenter.shareInstance().didLogout() self.navigationController!.present(LoginViewController(nibName: "LoginViewController", bundle: nil), animated: false, completion: nil) } }) } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard self.userInfo != nil else { return 0 } let returnValue = tableView.fd_heightForCell(withIdentifier: "MyInfoDescriptionTableViewCell", cacheBy: indexPath, configuration: { (cell) in let cell_ : MyInfoDescriptionTableViewCell = cell as! MyInfoDescriptionTableViewCell cell_.configure(headIconURL: YCOA_REQUEST_URL + "/" + self.userInfo!.face!, name: self.userInfo!.name, department: self.userInfo!.deptname, position: self.userInfo!.ranking, account: self.userInfo!.user, company: self.userInfo!.company, uid: self.userInfo!.companyid) }) return returnValue } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
71f4d88353cfa39555cddb02005ab4ce
39.72381
219
0.593545
5.18932
false
false
false
false
Seanalair/GreenAR
GreenAR/Classes/Controllers/FeatureFactory.swift
1
1582
// // FeatureFactory.swift // GreenAR // // Created by Daniel Grenier on 10/19/17. // import Foundation /** The factory which keeps track of `Feature` implementations by `typeIdentifier` and deserializes `Features` from json using that reference. */ public class FeatureFactory { /// The key where the `typeIdentifier` of a `Feature` is stored when it is serialized. public static let typeKey = "Type" /// The key where the `position` of a `Feature` is stored when it is serialized. public static let positionKey = "Position" /** A mapping containing references to all the types this factory can deserialize, stored by the type's `typeIdentifier`. It is necessary to override this in an extension or subclass to deserialize custom `Feature`s. */ public static var implementations = [SimpleFeature.typeIdentifier: SimpleFeature.self] /** Deserializes a `Feature` from a json object. - Parameter jsonObject: A jsonObject containing the `typeIdentifier` and other properties of the serialized `Feature`. - Returns: An initialized `Feature` of the appropriate type, or `nil` if the `jsonObject` was invalid or incomplete. */ public static func deserializeFeature(jsonObject dictionary:[String: Any]) -> Feature? { if let featureTypeIdentifier = dictionary[typeKey] as? String, let featureType = implementations[featureTypeIdentifier] { return featureType.init(jsonObject: dictionary) } else { return nil } } }
mit
07938e035c9b065507d2c5166c8c2d85
35.790698
139
0.686473
4.722388
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKCore/NKCSocket/NKC_SocketTCP.swift
1
8681
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /* * Creates _tcp javascript value that inherits from EventEmitter * _tcp.on("connection", function(_tcp)) * _tcp.on("afterConnect", function()) * _tcp.on('data', function(chunk)) * _tcp.on('end') * _tcp.writeBytes(data) * _tcp.fd returns {fd} * _tcp.remoteAddress returns {String addr, int port} * _tcp.localAddress returns {String addr, int port} * _tcp.bind(String addr, int port) * _tcp.listen(int backlog) * _tcp.connect(String addr, int port) * _tcp.close() * */ class NKC_SocketTCP: NSObject, NKScriptExport { // NKScripting class func attachTo(context: NKScriptContext) { context.loadPlugin(NKC_SocketTCP.self, namespace: "io.nodekit.platform.TCP", options: [String:AnyObject]()) } class func rewriteGeneratedStub(stub: String, forKey: String) -> String { switch (forKey) { case ".global": return NKStorage.getPluginWithStub(stub, "lib-core.nkar/lib-core/platform/tcp.js", NKC_SocketTCP.self) default: return stub } } private static let exclusion: Set<String> = { var methods = NKInstanceMethods(forProtocol: NKC_SwiftSocketProtocol.self) return Set<String>(methods.union([ ]).map({selector in return selector.description })) }() class func isExcludedFromScript(selector: String) -> Bool { return exclusion.contains(selector) } class func rewriteScriptNameForKey(name: String) -> String? { return (name == "initWithOptions:" ? "" : nil) } // local variables and init private let connections: NSMutableSet = NSMutableSet() private var _socket: NKC_SwiftSocket? private var _server: NKC_SocketTCP? override init() { self._socket = NKC_SwiftSocket(domain: NKC_DomainAddressFamily.INET, type: NKC_SwiftSocketType.Stream, proto: NKC_CommunicationProtocol.TCP) super.init() self._socket!.setDelegate(self, delegateQueue: NKScriptContextFactory.defaultQueue ) } init(options: AnyObject) { self._socket = NKC_SwiftSocket(domain: NKC_DomainAddressFamily.INET, type: NKC_SwiftSocketType.Stream, proto: NKC_CommunicationProtocol.TCP) super.init() self._socket!.setDelegate(self, delegateQueue: NKScriptContextFactory.defaultQueue ) } init(socket: NKC_SwiftSocket, server: NKC_SocketTCP?) { self._socket = socket self._server = server super.init() } // public methods func bindSync(address: String, port: Int) -> Int { do { try self._socket!.bind(host: address, port: Int32(port)) } catch let error as NKC_Error { print("!Socket Bind Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") return error.associated.value as? Int ?? 500 } catch { fatalError() } return 0 } func connect(address: String, port: Int) -> Void { do { try self._socket!.connect(host: address, port: Int32(port)) } catch let error as NKC_Error { print("!Socket Connect Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func listen(backlog: Int) -> Void { do { try self._socket!.listen(Int32(backlog)) } catch let error as NKC_Error { print("!Socket Connect Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func fdSync() -> Int { return Int(self._socket!.fd) } func remoteAddressSync() -> Dictionary<String, AnyObject> { let address: String = self._socket?.connectedHost ?? "" let port: Int = Int(self._socket?.connectedPort ?? 0) return ["address": address, "port": port] } func localAddressSync() -> Dictionary<String, AnyObject> { let address: String = self._socket!.localHost ?? "" let port: Int = Int(self._socket!.localPort ?? 0) return ["address": address, "port": port] } func writeString(string: String) -> Void { guard let data = NSData(base64EncodedString: string, options: NSDataBase64DecodingOptions(rawValue: 0)) else {return;} do { try self._socket?.write(data) } catch let error as NKC_Error { print("!Socket Send Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func close() -> Void { if (self._socket !== nil) { do { try self._socket!.close() } catch let error as NKC_Error { print("!Socket Close Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } if (self._server !== nil) { self._server!.close() } self._socket = nil self._server = nil } } // DELEGATE METHODS FOR NKC_SwiftSocket extension NKC_SocketTCP: NKC_SwiftSocketProtocol { func socket(socket: NKC_SwiftSocket, didAcceptNewSocket newSocket: NKC_SwiftSocket) { let socketConnection = NKC_SocketTCP(socket: newSocket, server: self) connections.addObject(socketConnection) newSocket.setDelegate(socketConnection, delegateQueue: NKScriptContextFactory.defaultQueue ) self.emitConnection(socketConnection) do { try newSocket.beginReceiving(tag: 1) } catch let error as NKC_Error { print("!Socket Accept Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func socket(socket: NKC_SwiftSocket, didConnectToHost host: String!, port: Int32) { self.emitAfterConnect(host, port: Int(port)) do { try socket.beginReceiving(tag: 1) } catch let error as NKC_Error { print("!Socket Connect Receive Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func socket(socket: NKC_SwiftSocket, didReceiveData data: NSData!, withTag tag: Int) { self.emitData(data) } func socket(socket: NKC_SwiftSocket, didReceiveData data: NSData!, sender host: String?, port: Int32) { self.emitData(data) } func socket(socket: NKC_SwiftSocket, didDisconnectWithError err: NSError) { self._socket = nil self.emitEnd() if (self._server != nil) { self._server!.connectionDidClose(self) } self._server = nil } // private methods private func connectionDidClose(socketConnection: NKC_SocketTCP) { connections.removeObject(socketConnection) } private func emitConnection(tcp: NKC_SocketTCP) -> Void { self.NKscriptObject?.invokeMethod("emit", withArguments: ["connection", tcp], completionHandler: nil) } private func emitAfterConnect(host: String, port: Int) { self.NKscriptObject?.invokeMethod("emit", withArguments:["afterConnect", host, port], completionHandler: nil) } private func emitData(data: NSData!) { let str: NSString! = data.base64EncodedStringWithOptions([]) self.NKscriptObject?.invokeMethod("emit", withArguments: ["data", str], completionHandler: nil) } private func emitEnd() { self.NKscriptObject?.invokeMethod("emit", withArguments: ["end", ""], completionHandler: nil) } }
apache-2.0
9e81a421c9d35df094ce12657254f841
33.312253
148
0.604884
4.306052
false
false
false
false
jhonny-me/test-mobile
QRApp/QRApp/QRGeneratorViewController.swift
1
4322
// // QRGeneratorViewController.swift // QRApp // // Created by 顾强 on 16/5/19. // Copyright © 2016年 johnny. All rights reserved. // import UIKit import Alamofire import QRCode import PKHUD class QRGeneratorViewController: UIViewController { /// generated qr view @IBOutlet weak var qrView: UIImageView! /// count down label @IBOutlet weak var countdownLb: UILabel! private var SeedAPI = "http://10.0.2.9:3000/seed" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if let qrSaver = QRLocalSaver.readFromLocal() { if qrSaver.ExpiredDate.timeIntervalSinceNow > 0 { return self.renderQRStratCounting(qrSaver.dataString, expiredDate: qrSaver.ExpiredDate) } } self.requestForQRData() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.countdownLb.cancelCounting() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func requestForQRData() -> Void { // show waiting HUD PKHUD.sharedHUD.contentView = PKHUDProgressView.init(title: "QRApp", subtitle: "loading...") PKHUD.sharedHUD.show() // start the request Alamofire.request(.GET, SeedAPI).responseJSON { (response) in // get data string var resultJson: NSDictionary? var dataString: String? if let resultValue = response.result.value { resultJson = resultValue as? NSDictionary }else{ return self.handleBadResponse(nil) } if let dataInJson = resultJson!["data"]!["data"] { dataString = dataInJson as? String }else{ return self.handleBadResponse(nil) } // get expired date var endingDateString: NSString = resultJson!["data"]!["expiredDate"] as! String endingDateString = endingDateString.substringToIndex(19) let dateFormate = NSDateFormatter() dateFormate.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" dateFormate.timeZone = NSTimeZone(forSecondsFromGMT: 0) let expiredDate = dateFormate.dateFromString(endingDateString as String) // if the request is too early that server has not refreshed if expiredDate!.timeIntervalSinceNow < 1 { return self.requestForQRData() } //save data to local QRLocalSaver.saveToLocal(dataString!, date: expiredDate!) // render and count self.renderQRStratCounting(dataString, expiredDate: expiredDate) // hide HUD PKHUD.sharedHUD.hide(animated: true, completion: nil) } } func handleBadResponse(hint:String?) -> Void { if PKHUD.sharedHUD.isVisible { PKHUD.sharedHUD.hide(animated: false, completion: nil) } let msg = (hint != nil) ? hint : "bad response" PKHUD.sharedHUD.contentView = PKHUDTextView.init(text: msg) PKHUD.sharedHUD.show() PKHUD.sharedHUD.hide(afterDelay: 2, completion: nil) } func renderQRStratCounting(dataString:String!, expiredDate:NSDate!) -> Void { // generate qr-code the show it self.qrView.image = QRCode(dataString)?.image // label start count down self.countdownLb.startCountingWithEndingDate(expiredDate, countClosure: { (remainTime) in if remainTime < 1 { self.requestForQRData() } }) } /* // 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?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
3a633da51f0e3914c707398fc359135d
33.246032
106
0.607184
4.920182
false
false
false
false
carabina/SwiftStore
Example/SwiftStoreExample/SwiftStoreExample/SimpleRowView.swift
1
4501
// // RowView.swift // SwiftStoreExample // // Created by Hemanta Sapkota on 31/05/2015. // Copyright (c) 2015 Hemanta Sapkota. All rights reserved. // import Foundation import UIKit import SnapKit /* Simple Row View */ class SimpleRowView : UIView { /* Label */ var label: UILabel! /* Key Text */ var keyText: UITextField! /* Value Text */ var valueText: UITextField! /* Save Button */ var saveBtn: UIButton! /* Delete */ var deleteBtn: UIButton! /* Handler */ var onSave: ( (String, String) -> Void)? /* Handler */ var onDelete: ( (String) -> Void)? init(rowNumber: Int, key: String) { super.init(frame: UIScreen.mainScreen().bounds) label = UILabel() label.text = "\(rowNumber)" label.textColor = UIColor(rgba: "#2c3e50") addSubview(label) label.snp_makeConstraints { (make) -> Void in make.top.equalTo(5) make.left.equalTo(5) } keyText = UITextField() keyText.layer.borderWidth = 0.5 keyText.layer.borderColor = UIColor(rgba: "#bdc3c7").CGColor! keyText.placeholder = "Key" keyText.text = "\(key)" keyText.enabled = false addSubview(keyText) keyText.snp_makeConstraints { (make) -> Void in make.top.greaterThanOrEqualTo(5) make.left.equalTo(label.snp_right).offset(10) make.width.equalTo(self.snp_width).offset(-60) make.height.equalTo(30) } valueText = UITextField() valueText.placeholder = "Value" valueText.layer.borderWidth = 0.5 valueText.layer.borderColor = UIColor(rgba: "#bdc3c7").CGColor! addSubview(valueText) valueText.snp_makeConstraints { (make) -> Void in make.top.greaterThanOrEqualTo(keyText.snp_bottom).offset(5) make.left.equalTo(label.snp_right).offset(10) make.width.equalTo(self.snp_width).offset(-60) make.height.equalTo(30) } saveBtn = UIButton.buttonWithType(UIButtonType.System) as! UIButton saveBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) saveBtn.setTitle("Save", forState: UIControlState.Normal) saveBtn.backgroundColor = UIColor(rgba: "#27ae60") addSubview(saveBtn) saveBtn.snp_makeConstraints { (make) -> Void in make.top.greaterThanOrEqualTo(valueText.snp_bottom).offset(5) make.left.equalTo(valueText.snp_left) make.width.equalTo(self.snp_width).dividedBy(3) } deleteBtn = UIButton.buttonWithType(UIButtonType.System) as! UIButton deleteBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) deleteBtn.setTitle("Delete", forState: UIControlState.Normal) deleteBtn.backgroundColor = UIColor(rgba: "#e74c3c") addSubview(deleteBtn) deleteBtn.snp_makeConstraints { (make) -> Void in make.top.greaterThanOrEqualTo(valueText.snp_bottom).offset(5) make.right.equalTo(valueText.snp_right) make.width.equalTo(self.snp_width).dividedBy(3) } let sep = UILabel() sep.backgroundColor = UIColor(rgba: "#bdc3c7") addSubview(sep) sep.snp_makeConstraints { (make) -> Void in make.height.equalTo(0.5) make.bottom.equalTo(self.snp_bottom) make.width.equalTo(self.snp_width) } saveBtn.addTarget(self, action: "handleSave", forControlEvents: UIControlEvents.TouchUpInside) deleteBtn.addTarget(self, action: "handleDelete", forControlEvents: UIControlEvents.TouchUpInside) } func handleSave() { if let executeSave = onSave { let key = keyText.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let value = valueText.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) executeSave(key, value) } } func handleDelete() { valueText.text = "" if let executeDelete = onDelete { let key = keyText.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) executeDelete(key) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
322b324894992e211f95c87f7181a188
33.630769
111
0.617418
4.469712
false
false
false
false
VernonVan/SmartClass
SmartClass/Paper/Preview Paper/View/TopicCell.swift
1
890
// // TopicCell.swift // SmartClass // // Created by Vernon on 16/7/22. // Copyright © 2016年 Vernon. All rights reserved. // import UIKit class TopicCell: UITableViewCell { @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var topicLabel: UILabel! } extension TopicCell { func configureForQuestion(_ question: Question) { switch QuestionType(typeNum: question.type) { case .some(.singleChoice): typeLabel.text = NSLocalizedString("单选题", comment: "") case .some(.multipleChoice): typeLabel.text = NSLocalizedString("多选题", comment: "") case .some(.trueOrFalse): typeLabel.text = NSLocalizedString("判断题", comment: "") default: typeLabel.text = nil } topicLabel.text = "\(question.index+1).\(question.topic!)" } }
mit
a289d487f9265289f61a7fd6399173a0
21.868421
66
0.605293
4.218447
false
false
false
false
brave/browser-ios
UITests/TopSitesTests.swift
3
6693
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit @testable import Storage @testable import Client class TopSitesTests: KIFTestCase { private var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() } func createNewTab(){ tester().tapViewWithAccessibilityLabel("Show Tabs") tester().tapViewWithAccessibilityLabel("Add Tab") tester().waitForViewWithAccessibilityLabel("Search or enter address") } func openURLForPageNumber(pageNo: Int) { let url = "\(webRoot)/numberedPage.html?page=\(pageNo)" tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)") } func rotateToLandscape() { // Rotate to landscape. let value = UIInterfaceOrientation.LandscapeLeft.rawValue UIDevice.currentDevice().setValue(value, forKey: "orientation") } func rotateToPortrait() { // Rotate to landscape. let value = UIInterfaceOrientation.Portrait.rawValue UIDevice.currentDevice().setValue(value, forKey: "orientation") } // A bit internal :/ func extractTextSizeFromThumbnail(thumbnail: UIView) -> CGFloat? { guard let contentView = thumbnail.subviews.first, let wrapper = contentView.subviews.first, let textWrapper = wrapper.subviews.last, let label = textWrapper.subviews.first as? UILabel else { return nil } return label.font.pointSize } func testRotatingOnTopSites() { // go to top sites. rotate to landscape, rotate back again. ensure it doesn't crash createNewTab() rotateToLandscape() rotateToPortrait() // go to top sites. rotate to landscape, switch to another tab, switch back to top sites, ensure it doesn't crash rotateToLandscape() tester().tapViewWithAccessibilityLabel("History") tester().tapViewWithAccessibilityLabel("Top sites") rotateToPortrait() // go to web page. rotate to landscape. click URL Bar, rotate to portrait. ensure it doesn't crash. openURLForPageNumber(1) rotateToLandscape() tester().tapViewWithAccessibilityIdentifier("url") tester().waitForViewWithAccessibilityLabel("Top sites") rotateToPortrait() tester().tapViewWithAccessibilityLabel("Cancel") } func testChangingDyamicFontOnTopSites() { DynamicFontUtils.restoreDynamicFontSize(tester()) createNewTab() let thumbnail = tester().waitForViewWithAccessibilityLabel("The Mozilla Project") let size = extractTextSizeFromThumbnail(thumbnail) DynamicFontUtils.bumpDynamicFontSize(tester()) let bigSize = extractTextSizeFromThumbnail(thumbnail) DynamicFontUtils.lowerDynamicFontSize(tester()) let smallSize = extractTextSizeFromThumbnail(thumbnail) XCTAssertGreaterThan(bigSize!, size!) XCTAssertGreaterThanOrEqual(size!, smallSize!) openURLForPageNumber(1) // Needed for the teardown } func testRemovingSite() { // Load a page tester().tapViewWithAccessibilityIdentifier("url") let url1 = "\(webRoot)/numberedPage.html?page=1" tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") // Open top sites tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Top sites") // Verify the row exists and that the Remove Page button is hidden let row = tester().waitForViewWithAccessibilityLabel("127.0.0.1") tester().waitForAbsenceOfViewWithAccessibilityLabel("Remove page") // Long press the row and click the remove button row.longPressAtPoint(CGPointZero, duration: 1) tester().tapViewWithAccessibilityLabel("Remove page") // Close editing mode tester().tapViewWithAccessibilityLabel("Done") // Close top sites tester().tapViewWithAccessibilityLabel("Cancel") } func testRotationAndDeleteShowsCorrectTile() { // Load in the top Alexa sites to populate some top site tiles with let topDomainsPath = NSBundle.mainBundle().pathForResource("topdomains", ofType: "txt")! let data = try! NSString(contentsOfFile: topDomainsPath, encoding: NSUTF8StringEncoding) let topDomains = data.componentsSeparatedByString("\n") var collection = tester().waitForViewWithAccessibilityIdentifier("Top Sites View") as! UICollectionView let thumbnailCount = (collection.collectionViewLayout as! TopSitesLayout).thumbnailCount // Navigate to enough sites to fill top sites plus a couple of more (0..<thumbnailCount + 3).forEach { index in let site = topDomains[index] tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(site)\n") } tester().waitForTimeInterval(2) // Open top sites tester().tapViewWithAccessibilityIdentifier("url") tester().swipeViewWithAccessibilityIdentifier("Top Sites View", inDirection: .Down) tester().waitForAnimationsToFinish() // Rotate system().simulateDeviceRotationToOrientation(.LandscapeLeft) tester().waitForAnimationsToFinish() // Delete collection = tester().waitForViewWithAccessibilityIdentifier("Top Sites View") as! UICollectionView let firstCell = collection.visibleCells().first! firstCell.longPressAtPoint(CGPointZero, duration: 3) tester().tapViewWithAccessibilityLabel("Remove page") // Rotate system().simulateDeviceRotationToOrientation(.Portrait) tester().waitForAnimationsToFinish() // Get last cell after rotation let lastCell = collection.visibleCells().last! // Verify that the last cell is not a default tile DefaultSuggestedSites.sites["default"]!.forEach { site in XCTAssertFalse(lastCell.accessibilityLabel == site.title) } // Close top sites tester().tapViewWithAccessibilityLabel("Cancel") } override func tearDown() { DynamicFontUtils.restoreDynamicFontSize(tester()) BrowserUtils.resetToAboutHome(tester()) } }
mpl-2.0
007fbf50cbabc3a933d52b47ac82774b
38.60355
123
0.690572
5.676845
false
true
false
false
PonyGroup/PonyChatUI-Swift
PonyChatUI/Classes/User Interface/View/MenuViewController.swift
1
9137
// // MenuViewController.swift // PonyChatUIProject // // Created by 崔 明辉 on 15/10/30. // // import UIKit protocol PCUMenuViewControllerDelegate: NSObjectProtocol { func menuItemDidPressed(menuViewController: PonyChatUI.UserInterface.MenuViewController, itemIndex: Int) } extension PonyChatUI.UserInterface { class MenuViewController: UIViewController { weak var delegate: PCUMenuViewControllerDelegate? var titles: [String] { didSet { reloadData() } } var isDown: Bool = false var upTriangleView = MenuUpTriangleView(frame: CGRect(x: 0, y: 0, width: 40, height: 20)) let downTriangleView = MenuDownTriangleView(frame: CGRect(x: 0, y: 0, width: 40, height: 20)) let segmentedControl = UISegmentedControl() init(titles: [String]) { self.titles = titles super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func showMenuView(referencePoint: CGPoint) { var sFrame = CGRectMake( referencePoint.x - widthOfSegmentedControl() / 2.0, referencePoint.y - 14.0 - 36.0, widthOfSegmentedControl(), 36.0) if sFrame.origin.y < 0.0 { sFrame.origin.y = UIApplication.sharedApplication().statusBarFrame.size.height isDown = false } else { isDown = false } var triangleX = referencePoint.x - 20.0 if referencePoint.x < 20.0 { triangleX = 20.0 } else if referencePoint.x > view.bounds.width - 66.0 { triangleX = view.bounds.width - 66.0 } upTriangleView.frame = CGRect(x: triangleX, y: sFrame.origin.y - 20.0, width: 40, height: 20) downTriangleView.frame = CGRect(x: triangleX, y: sFrame.origin.y + 36.0, width: 40, height: 20) if sFrame.origin.x < 0 + 8.0 { sFrame.origin.x = 0.0 + 8.0 } else if sFrame.origin.x + sFrame.size.width > view.bounds.width - 8.0 { sFrame.origin.x = view.bounds.width - sFrame.size.width - 8.0 } segmentedControl.frame = sFrame if let window = UIApplication.sharedApplication().keyWindow { self.segmentedControl.alpha = 1.0 if self.isDown { self.upTriangleView.alpha = 1.0 } else { self.downTriangleView.alpha = 1.0 } window.addSubview(view) UIView.animateWithDuration(0.35, animations: { () -> Void in self.view.alpha = 1.0 }, completion: { (_) -> Void in self.view.alpha = 1.0 }) } } func dismiss() { self.segmentedControl.alpha = 0.0 self.upTriangleView.alpha = 0.0 self.downTriangleView.alpha = 0.0 self.view.removeFromSuperview() } override func viewDidLoad() { super.viewDidLoad() configureViews() view.addSubview(self.upTriangleView) view.addSubview(self.downTriangleView) view.addSubview(self.segmentedControl) reloadData() } func reloadData() { segmentedControl.removeAllSegments() var index = 0 for title in self.titles { segmentedControl.insertSegmentWithTitle(title, atIndex: index, animated: false) let textSize = (title as NSString).boundingRectWithSize(CGSize(width: CGFloat.max, height: CGFloat.max), options: [], attributes: [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil) segmentedControl.setWidth(textSize.width + 32, forSegmentAtIndex: index) index++ } } func configureViews() { configureUpTriangle() configureDownTriangle() configureSegmentedControl() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismiss")) } func configureUpTriangle() { upTriangleView.backgroundColor = UIColor.clearColor() upTriangleView.alpha = 0.0 } func configureDownTriangle() { downTriangleView.backgroundColor = UIColor.clearColor() downTriangleView.alpha = 0.0 } func configureSegmentedControl() { segmentedControl.tintColor = UIColor.clearColor() segmentedControl.backgroundColor = UIColor(white: 0.0, alpha: 0.85) segmentedControl.layer.cornerRadius = 6 segmentedControl.layer.masksToBounds = true segmentedControl.setTitleTextAttributes([ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(14) ], forState: UIControlState.Normal) segmentedControl.setTitleTextAttributes([ NSForegroundColorAttributeName: UIColor(white: 1.0, alpha: 0.5), NSFontAttributeName: UIFont.systemFontOfSize(14) ], forState: UIControlState.Highlighted) segmentedControl.setDividerImage(imageWithColor(UIColor(white: 1.0, alpha: 0.25)), forLeftSegmentState: .Normal, rightSegmentState: .Normal, barMetrics: .Default) segmentedControl.addTarget(self, action: "handleValueChanged", forControlEvents: .ValueChanged) } func widthOfSegmentedControl() -> CGFloat { var width:CGFloat = 0.0 for title in self.titles { let textSize = (title as NSString).boundingRectWithSize(CGSize(width: CGFloat.max, height: CGFloat.max), options: [], attributes: [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil) width += textSize.width width += 32.0 } if self.titles.count > 1 { width += 4.0 } return width } func imageWithColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func handleValueChanged() { if let delegate = delegate { delegate.menuItemDidPressed(self, itemIndex: segmentedControl.selectedSegmentIndex) } segmentedControl.selectedSegmentIndex = -1 dismiss() } } class MenuUpTriangleView: UIView { override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context); CGContextTranslateCTM(context, 20, 17); let polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPoint(x: 0, y: -7.25)) polygonPath.addLineToPoint(CGPoint(x: 9.74, y: 3.62)) polygonPath.addLineToPoint(CGPoint(x: -9.74, y: 3.63)) polygonPath.closePath() UIColor(white: 0.0, alpha: 0.85).setFill() polygonPath.fill() CGContextRestoreGState(context) } } class MenuDownTriangleView: UIView { override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context); CGContextTranslateCTM(context, 20, 3); CGContextRotateCTM(context, -180.0 * CGFloat(M_PI) / 180.0); let polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPoint(x: 0, y: -7.25)) polygonPath.addLineToPoint(CGPoint(x: 9.74, y: 3.62)) polygonPath.addLineToPoint(CGPoint(x: -9.74, y: 3.63)) polygonPath.closePath() UIColor(white: 0.0, alpha: 0.85).setFill() polygonPath.fill() CGContextRestoreGState(context) } } }
mit
805843eb8feafccbe17f2e7237c02027
36.422131
120
0.546271
5.327305
false
false
false
false
codestergit/swift
test/Generics/superclass_constraint.swift
3
5415
// RUN: %target-typecheck-verify-swift // RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump class A { func foo() { } } class B : A { func bar() { } } class Other { } func f1<T : A>(_: T) where T : Other {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'Other' and 'A'}} // expected-note@-1{{superclass constraint 'T' : 'A' written here}} func f2<T : A>(_: T) where T : B {} // expected-warning@-1{{redundant superclass constraint 'T' : 'A'}} // expected-note@-2{{superclass constraint 'T' : 'B' written here}} class GA<T> {} class GB<T> : GA<T> {} protocol P {} func f3<T, U>(_: T, _: U) where U : GA<T> {} func f4<T, U>(_: T, _: U) where U : GA<T> {} func f5<T, U : GA<T>>(_: T, _: U) {} func f6<U : GA<T>, T : P>(_: T, _: U) {} func f7<U, T>(_: T, _: U) where U : GA<T>, T : P {} func f8<T : GA<A>>(_: T) where T : GA<B> {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'GA<B>' and 'GA<A>'}} // expected-note@-1{{superclass constraint 'T' : 'GA<A>' written here}} func f9<T : GA<A>>(_: T) where T : GB<A> {} // expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}} // expected-note@-2{{superclass constraint 'T' : 'GB<A>' written here}} func f10<T : GB<A>>(_: T) where T : GA<A> {} // expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}} // expected-note@-2{{superclass constraint 'T' : 'GB<A>' written here}} func f11<T : GA<T>>(_: T) { } // expected-error{{superclass constraint 'T' : 'GA<T>' is recursive}} func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } // expected-error{{superclass constraint 'U' : 'GB<T>' is recursive}} // expected-error{{superclass constraint 'T' : 'GA<U>' is recursive}} func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{inheritance from non-protocol, non-class type 'U'}} // rdar://problem/24730536 // Superclass constraints can be used to resolve nested types to concrete types. protocol P3 { associatedtype T } protocol P2 { associatedtype T : P3 } class C : P3 { typealias T = Int } class S : P2 { typealias T = C } extension P2 where Self.T : C { // CHECK: superclass_constraint.(file).P2.concreteTypeWitnessViaSuperclass1 // CHECK: Generic signature: <Self where Self : P2, Self.T : C> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P2, τ_0_0.T : C> func concreteTypeWitnessViaSuperclass1(x: Self.T.T) {} } // CHECK: superclassConformance1 // CHECK: Requirements: // CHECK-NEXT: τ_0_0 : C [τ_0_0: Explicit @ {{.*}}:11] // CHECK-NEXT: τ_0_0 : _NativeClass [τ_0_0: Explicit @ {{.*}}:11 -> Superclass] // CHECK-NEXT: τ_0_0 : P3 [τ_0_0: Explicit @ {{.*}}:11 -> Superclass (C: P3)] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C> func superclassConformance1<T>(t: T) where T : C, // expected-note{{conformance constraint 'T': 'P3' implied here}} T : P3 {} // expected-warning{{redundant conformance constraint 'T': 'P3'}} // CHECK: superclassConformance2 // CHECK: Requirements: // CHECK-NEXT: τ_0_0 : C [τ_0_0: Explicit @ {{.*}}:11] // CHECK-NEXT: τ_0_0 : _NativeClass [τ_0_0: Explicit @ {{.*}}:11 -> Superclass] // CHECK-NEXT: τ_0_0 : P3 [τ_0_0: Explicit @ {{.*}}:11 -> Superclass (C: P3)] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C> func superclassConformance2<T>(t: T) where T : C, // expected-note{{conformance constraint 'T': 'P3' implied here}} T : P3 {} // expected-warning{{redundant conformance constraint 'T': 'P3'}} protocol P4 { } class C2 : C, P4 { } // CHECK: superclassConformance3 // CHECK: Requirements: // CHECK-NEXT: τ_0_0 : C2 [τ_0_0: Explicit @ {{.*}}:46] // CHECK-NEXT: τ_0_0 : _NativeClass [τ_0_0: Explicit @ {{.*}}:46 -> Superclass] // CHECK-NEXT: τ_0_0 : P4 [τ_0_0: Explicit @ {{.*}}:61 -> Superclass (C2: P4)] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C2> func superclassConformance3<T>(t: T) where T : C, T : P4, T : C2 {} // expected-warning@-1{{redundant superclass constraint 'T' : 'C'}} // expected-note@-2{{superclass constraint 'T' : 'C2' written here}} // expected-warning@-3{{redundant conformance constraint 'T': 'P4'}} // expected-note@-4{{conformance constraint 'T': 'P4' implied here}} protocol P5: A { } // expected-error{{non-class type 'P5' cannot inherit from class 'A'}} protocol P6: A, Other { } // expected-error {{protocol 'P6' cannot be a subclass of both 'Other' and 'A'}} // expected-error@-1{{non-class type 'P6' cannot inherit from class 'A'}} // expected-error@-2{{non-class type 'P6' cannot inherit from class 'Other'}} // expected-note@-3{{superclass constraint 'Self' : 'A' written here}} func takeA(_: A) { } func takeP5<T: P5>(_ t: T) { takeA(t) // okay } protocol P7 { associatedtype Assoc: A, Other // FIXME: expected-error@-1{{multiple inheritance from classes 'A' and 'Other'}} // expected-note@-2{{superclass constraint 'Self.Assoc' : 'A' written here}} // expected-error@-3{{'Self.Assoc' cannot be a subclass of both 'Other' and 'A'}} } // CHECK: superclassConformance4 // CHECK: Generic signature: <T, U where T : P3, U : P3, T.T : C, T.T == U.T> func superclassConformance4<T: P3, U: P3>(_: T, _: U) where T.T: C, // expected-note{{superclass constraint 'T.T' : 'C' written here}} U.T: C, // expected-warning{{redundant superclass constraint 'U.T' : 'C'}} T.T == U.T { }
apache-2.0
fca01775f4dbb89e2a033ca764bb7544
38.043478
186
0.622866
2.92667
false
false
false
false
quickthyme/PUTcat
PUTcat/Application/Data/_Shared/WebRequest/WebRequestDelivery/MultipartFormUploadWebRequestDelivery.swift
1
1539
import Foundation class MultipartFormUploadWebRequestDelivery : HTTPWebRequestDelivery { lazy var boundary : String = self.generateBoundary() var filename : String? var filetype : String? enum FileTypes : String { case imageJPEG = "image/jpeg" case imagePNG = "image/png" } override func getHeaders(request: WebRequest) -> [String:String]? { var headers : [String:String] = request.headers ?? [:] headers["Content-Type"] = "multipart/form-data; boundary=\(boundary)" return headers } override func getBodyData(request: WebRequest) -> Data? { guard let bodyData = request.bodyData else { return nil } var body = Data() body.append("--\(boundary)\r\n".data(using: .utf8)!) let filename = self.filename ?? "userfile" body.append("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"\(filename)\"\r\n".data(using: .utf8)!) if let filetype = self.filetype { body.append("Content-Type: \(filetype)\r\n".data(using: .utf8)!) } body.append("Content-Transfer-Encoding: binary\r\n\r\n".data(using: .utf8)!) body.append(bodyData) body.append("\r\n".data(using: .utf8)!) body.append("--\(boundary)--\r\n".data(using: .utf8)!) return body } private func generateBoundary() -> String { return UUID().uuidString.trimmingCharacters(in: CharacterSet(charactersIn: "-")) } }
apache-2.0
8d0812fc49d368cff4672da7ea342881
33.2
125
0.595841
4.093085
false
false
false
false
songhailiang/NLScrollingNavigationBar
NLScrollingNavigationBarDemo/ViewController.swift
1
1307
// // ViewController.swift // NLScrollingNavigationBarDemo // // Created by songhailiang on 09/06/2017. // Copyright © 2017 hailiang.song. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var table: UITableView! let demos = ["ScrollView", "MultiScrollView", "TableView", "ChildController"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.title = "NLScrollingNavigationBar" table.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = demos[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let demo = demos[indexPath.row] performSegue(withIdentifier: demo, sender: nil) } }
mit
ec0bba5494f9a77c513c39794973c490
29.372093
100
0.679939
5.081712
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Settings/VSettingsCellSounds.swift
1
2497
import UIKit class VSettingsCellSounds:VSettingsCell { private weak var segmented:UISegmentedControl! private let kLabelRight:CGFloat = -15 private let kLabelWidth:CGFloat = 200 private let kCheckRight:CGFloat = -5 private let kCheckTop:CGFloat = 22 private let kCheckWidth:CGFloat = 70 private let kCheckHeight:CGFloat = 60 override init(frame:CGRect) { super.init(frame:frame) let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.backgroundColor = UIColor.clear labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.font = UIFont.regular(size:14) labelTitle.textColor = UIColor.white labelTitle.textAlignment = NSTextAlignment.right labelTitle.text = String.localized(key:"VSettingsCellSounds_labelTitle") let check:UISwitch = UISwitch() check.translatesAutoresizingMaskIntoConstraints = false check.onTintColor = UIColor.colourSuccess check.addTarget( self, action:#selector(actionCheck(sender:)), for:UIControlEvents.valueChanged) addSubview(labelTitle) addSubview(check) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.rightToLeft( view:labelTitle, toView:check, constant:kLabelRight) NSLayoutConstraint.width( view:labelTitle, constant:kLabelWidth) NSLayoutConstraint.topToTop( view:check, toView:self, constant:kCheckTop) NSLayoutConstraint.height( view:check, constant:kCheckHeight) NSLayoutConstraint.rightToRight( view:check, toView:self, constant:kCheckRight) NSLayoutConstraint.width( view:check, constant:kCheckWidth) guard let sounds:Bool = MSession.sharedInstance.settings?.sounds else { return } check.isOn = sounds } required init?(coder:NSCoder) { return nil } //MARK: actions func actionCheck(sender check:UISwitch) { let sounds:Bool = check.isOn MSession.sharedInstance.settings?.changeSounds(sounds:sounds) } }
mit
c2c4139d86619c59a14bd4c2aa5decbc
27.701149
80
0.606328
5.475877
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/YPImagePicker/Source/Helpers/Extensions/AVAsset+Extensions.swift
2
2526
// // AVAsset+Extensions.swift // YPImagePicker // // Created by Nik Kov on 23.04.2018. // Copyright © 2018 Yummypets. All rights reserved. // import AVFoundation // MARK: Trim extension AVAsset { func assetByTrimming(startTime: CMTime, endTime: CMTime) throws -> AVAsset { let timeRange = CMTimeRangeFromTimeToTime(start: startTime, end: endTime) let composition = AVMutableComposition() do { for track in tracks { let compositionTrack = composition.addMutableTrack(withMediaType: track.mediaType, preferredTrackID: track.trackID) try compositionTrack?.insertTimeRange(timeRange, of: track, at: CMTime.zero) } } catch let error { throw YPTrimError("Error during composition", underlyingError: error) } // Reaply correct transform to keep original orientation. if let videoTrack = self.tracks(withMediaType: .video).last, let compositionTrack = composition.tracks(withMediaType: .video).last { compositionTrack.preferredTransform = videoTrack.preferredTransform } return composition } /// Export the video /// /// - Parameters: /// - destination: The url to export /// - videoComposition: video composition settings, for example like crop /// - removeOldFile: remove old video /// - completion: resulting export closure /// - Throws: YPTrimError with description func export(to destination: URL, videoComposition: AVVideoComposition? = nil, removeOldFile: Bool = false, completion: @escaping () -> Void) throws { guard let exportSession = AVAssetExportSession(asset: self, presetName: YPConfig.video.compression) else { throw YPTrimError("Could not create an export session") } exportSession.outputURL = destination exportSession.outputFileType = YPConfig.video.fileType exportSession.shouldOptimizeForNetworkUse = true exportSession.videoComposition = videoComposition if removeOldFile { try FileManager.default.removeFileIfNecessary(at: destination) } exportSession.exportAsynchronously(completionHandler: completion) if let error = exportSession.error { throw YPTrimError("error during export", underlyingError: error) } } }
mit
908c559a621905410b34981604d0e4e2
37.846154
114
0.634851
5.465368
false
false
false
false
atuooo/notGIF
notGIF/Views/Cell/GIF/GIFLisCell.swift
1
2811
// // GIFListCollectionViewCell.swift // notGIF // // Created by Atuooo on 09/10/2016. // Copyright © 2016 xyz. All rights reserved. // import UIKit class GIFListCell: GIFBaseCell { @IBOutlet weak var timeLabel: UILabel! public var actionHandler: ((GIFActionType) -> Void)? fileprivate var popShareView: GIFListActionView? fileprivate var isChoosed: Bool = false fileprivate lazy var chooseIndicator: UILabel = { let label = UILabel(iconCode: .checkO, color: UIColor.textTint, fontSize: 20) label.frame = CGRect(x: 6, y: 6, width: 26, height: 26) return label }() override func prepareForReuse() { super.prepareForReuse() timeLabel.text = nil } override func awakeFromNib() { super.awakeFromNib() timeLabel.text = nil let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(GIFListCell.longPressGesHandler(ges:))) addGestureRecognizer(longPressGes) } deinit { printLog("deinited") } public func setChoosed(_ isChoosed: Bool, animate: Bool) { guard self.isChoosed != isChoosed else { return } self.isChoosed = isChoosed func update() { if isChoosed { transform = CGAffineTransform(scaleX: 0.96, y: 0.96) contentView.alpha = 0.3 addSubview(self.chooseIndicator) } else { transform = .identity contentView.alpha = 1 chooseIndicator.removeFromSuperview() } } if animate { UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.4, options: [.allowAnimatedContent, .curveEaseInOut], animations: { update() }, completion: nil) } else { update() } } // MARK: - Gesture Handler func longPressGesHandler(ges: UILongPressGestureRecognizer) { let keyWindow = UIApplication.shared.keyWindow let location = ges.location(in: keyWindow) switch ges.state { case .began: if let cellFrame = superview?.convert(frame, to: keyWindow) { popShareView = GIFListActionView(popOrigin: location, cellRect: cellFrame) keyWindow?.addSubview(popShareView!) } case .changed: popShareView?.update(with: location) case .ended, .failed, .cancelled: if let type = popShareView?.end(with: location) { actionHandler?(type) } default: break } } }
mit
9adfc315191fbdf0a56456be4ba1a623
28.270833
177
0.564057
4.929825
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Services/HATDataPlugsService.swift
1
16631
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ import Alamofire import SwiftyJSON // MARK: Struct /// The data plugs service class public struct HATDataPlugsService { // MARK: - Get available data plugs /** Gets the available data plugs for the user to enable - parameter succesfulCallBack: A function of type ([HATDataPlugObject], String?) -> Void, executed on a successful result - parameter failCallBack: A function of type (DataPlugError) -> Void, executed on an unsuccessful result */ public static func getAvailableDataPlugs(succesfulCallBack: @escaping ([HATDataPlug], String?) -> Void, failCallBack: @escaping (DataPlugError) -> Void) { let url: String = "https://dex.hubofallthings.com/api/dataplugs" HATNetworkHelper.asynchronousRequest(url, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: [:], headers: [:], completion: { (response: HATNetworkHelper.ResultType) -> Void in switch response { // in case of error call the failCallBack case .error(let error, let statusCode, _): if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." { failCallBack(.noInternetConnection) } else { let message: String = NSLocalizedString("Server responded with error", comment: "") failCallBack(.generalError(message, statusCode, error)) } // in case of success call the succesfulCallBack case .isSuccess(let isSuccess, let statusCode, let result, let token): if isSuccess { var returnValue: [HATDataPlug] = [] for item: JSON in result.arrayValue { if let object: HATDataPlug = HATDataPlug.decode(from: item.dictionaryValue) { returnValue.append(object) } } succesfulCallBack(returnValue, token) } else { let message: String = NSLocalizedString("Server response was unexpected", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } }) } // MARK: - Claiming offers /** Check if offer is claimed - parameter offerID: The offerID as a String - parameter appToken: The application token as a String - parameter succesfulCallBack: A function to call if everything is ok - parameter failCallBack: A function to call if fail */ public static func checkIfOfferIsClaimed(offerID: String, appToken: String, succesfulCallBack: @escaping (String) -> Void, failCallBack: @escaping (DataPlugError) -> Void) { // setup parameters and headers let parameters: Dictionary<String, String> = [:] let headers: [String: String] = ["X-Auth-Token": appToken] // contruct the url let url: String = "https://dex.hubofallthings.com/api/v2.6/offer/\(offerID)/userClaim" // make async request HATNetworkHelper.asynchronousRequest(url, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: parameters, headers: headers, completion: { (response: HATNetworkHelper.ResultType) -> Void in switch response { // in case of error call the failCallBack case .error(let error, let statusCode, _): if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." { failCallBack(.noInternetConnection) } else if statusCode != 404 { let message: String = NSLocalizedString("Server responded with error", comment: "") failCallBack(.generalError(message, statusCode, error)) } else { let message: String = NSLocalizedString("Expected response, 404", comment: "") failCallBack(.generalError(message, statusCode, error)) } // in case of success call succesfulCallBack case .isSuccess(let isSuccess, let statusCode, let result, _): if isSuccess { if statusCode == 200 { if !result["confirmed"].boolValue { succesfulCallBack(result["dataDebitId"].stringValue) } else { failCallBack(.noValueFound) } } else { let message: String = NSLocalizedString("Server responded with different code than 200", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } else { let message: String = NSLocalizedString("Server response was unexpected", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } }) } /** Claim offer with this ID - parameter offerID: The offerID as a String - parameter appToken: The application token as a String - parameter succesfulCallBack: A function to call if everything is ok - parameter failCallBack: A function to call if fail */ public static func claimOfferWithOfferID(_ offerID: String, appToken: String, succesfulCallBack: @escaping (String) -> Void, failCallBack: @escaping (DataPlugError) -> Void) { // setup parameters and headers let parameters: Dictionary<String, String> = [:] let headers: [String: String] = ["X-Auth-Token": appToken] // contruct the url let url: String = "https://dex.hubofallthings.com/api/v2.6/offer/\(offerID)/claim" // make async request HATNetworkHelper.asynchronousRequest(url, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: parameters, headers: headers, completion: { (response: HATNetworkHelper.ResultType) -> Void in switch response { // in case of error call the failCallBack case .error(let error, let statusCode, _): if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." { failCallBack(.noInternetConnection) } else { let message: String = NSLocalizedString("Server responded with error", comment: "") failCallBack(.generalError(message, statusCode, error)) } // in case of success call succesfulCallBack case .isSuccess(let isSuccess, let statusCode, let result, _): if isSuccess { if statusCode == 200 { succesfulCallBack(result["dataDebitId"].stringValue) } else if statusCode == 400 { failCallBack(.offerClaimed) } else { let message: String = NSLocalizedString("Server responded with different code than 200", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } else { let message: String = NSLocalizedString("Server response was unexpected", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } }) } // MARK: - Data debits /** Approve data debit - parameter dataDebitID: The data debit ID as a String - parameter userToken: The user's token - parameter userDomain: The user's domain - parameter succesfulCallBack: A function to call if everything is ok - parameter failCallBack: A function to call if fail */ public static func approveDataDebit(_ dataDebitID: String, userToken: String, userDomain: String, succesfulCallBack: @escaping (String) -> Void, failCallBack: @escaping (DataPlugError) -> Void) { // setup parameters and headers let parameters: Dictionary<String, String> = [:] let headers: [String: String] = ["X-Auth-Token": userToken] // contruct the url let url: String = "https://\(userDomain)/api/v2.6/data-debit/\(dataDebitID)/enable" // make async request HATNetworkHelper.asynchronousRequest(url, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: parameters, headers: headers, completion: { (response: HATNetworkHelper.ResultType) -> Void in switch response { // in case of error call the failCallBack case .error(let error, let statusCode, _): if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." { failCallBack(.noInternetConnection) } else { let message: String = NSLocalizedString("Server responded with error", comment: "") failCallBack(.generalError(message, statusCode, error)) } // in case of success call succesfulCallBack case .isSuccess(let isSuccess, let statusCode, _, _): if isSuccess { if statusCode == 400 { failCallBack(.offerClaimed) } succesfulCallBack("enabled") } else { let message: String = NSLocalizedString("Server response was unexpected", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } }) } /** Check if data debit with this ID is enabled or not - parameter dataDebitID: The data debit ID as a String - parameter userToken: The user's token - parameter userDomain: The user's domain - parameter succesfulCallBack: A function to call if everything is ok - parameter failCallBack: A function to call if fail */ public static func checkDataDebit(_ dataDebitID: String, userToken: String, userDomain: String, succesfulCallBack: @escaping (Bool) -> Void, failCallBack: @escaping (DataPlugError) -> Void) { // setup parameters and headers let parameters: Dictionary<String, String> = [:] let headers: [String: String] = ["X-Auth-Token": userToken] // contruct the url let url: String = "https://\(userDomain)/api/v2.6/data-debit/\(dataDebitID)" // make async request HATNetworkHelper.asynchronousRequest(url, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: parameters, headers: headers, completion: { (response: HATNetworkHelper.ResultType) -> Void in switch response { // in case of error call the failCallBack case .error( let error, let statusCode, _): if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." { failCallBack(.noInternetConnection) } else if statusCode != 404 { let message: String = NSLocalizedString("Server responded with error", comment: "") failCallBack(.generalError(message, statusCode, error)) } else { let message: String = NSLocalizedString("Expected response, 404", comment: "") failCallBack(.generalError(message, statusCode, error)) } // in case of success call succesfulCallBack case .isSuccess(let isSuccess, let statusCode, let result, _): guard isSuccess, let dataDebit: HATDataDebit = HATDataDebit.decode(from: result.dictionaryValue) else { let message: String = NSLocalizedString("Server response was unexpected", comment: "") failCallBack(.generalError(message, statusCode, nil)) return } succesfulCallBack(dataDebit.isActive) } }) } // /** Check social plug expiry date - parameter facebookUrlStatus: The plug's status url to connect to - parameter succesfulCallBack: A function to call if everything is ok - parameter failCallBack: A function to call if fail */ public static func checkSocialPlugExpiry(facebookUrlStatus: String, succesfulCallBack: @escaping (String) -> Void, failCallBack: @escaping (DataPlugError) -> Void) -> (_ appToken: String) -> Void { return { (appToken: String) in // setup parameters and headers let parameters: Dictionary<String, String> = [:] let headers: [String: String] = ["X-Auth-Token": appToken] // make async request HATNetworkHelper.asynchronousRequest(facebookUrlStatus, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: parameters, headers: headers, completion: { (response: HATNetworkHelper.ResultType) -> Void in switch response { // in case of error call the failCallBack case .error(let error, let statusCode, _): if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." { failCallBack(.noInternetConnection) } else if statusCode == 404 { let message: String = NSLocalizedString("Expected response, 404", comment: "") failCallBack(.generalError(message, statusCode, error)) } else { let message: String = NSLocalizedString("Server responded with error", comment: "") failCallBack(.generalError(message, statusCode, error)) } // in case of success call succesfulCallBack case .isSuccess(let isSuccess, let statusCode, let result, _): if isSuccess { succesfulCallBack(String(result["expires"].stringValue)) } else { let message: String = NSLocalizedString("Server response was unexpected", comment: "") failCallBack(.generalError(message, statusCode, nil)) } } }) } } }
mpl-2.0
947f7aa189dfafc43ed5f9b2a73a55a7
45.325905
260
0.545788
5.808942
false
false
false
false
moltin/ios-sdk
Sources/SDK/Requests/CustomerRequest.swift
1
7624
// // CustomerRequest.swift // moltin // // Created by Craig Tweedy on 25/04/2018. // import Foundation /// An entry point to make API calls relating to `Customer` and related items public class CustomerRequest: MoltinRequest { /** The API endpoint for this resource. */ public var endpoint: String = "/customers" /** A typealias which allows automatic casting of a collection to `[Customer]`. */ public typealias DefaultCollectionRequestHandler = CollectionRequestHandler<[Customer]> /** A typealias which allows automatic casting of an object to `Customer`. */ public typealias DefaultObjectRequestHandler = ObjectRequestHandler<Customer> /** A typealias which allows automatic casting of a collection to `[Address]`. */ public typealias DefaultAddressCollectionRequestHandler = CollectionRequestHandler<[Address]> /** A typealias which allows automatic casting of an object to `Address`. */ public typealias DefaultAddressObjectRequestHandler = ObjectRequestHandler<Address> /** Get a token for a `Customer` - Author: Craig Tweedy - parameters: - withEmail: The email for the customer - withPassword: The password for the customer - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func getToken(withEmail email: String, withPassword password: String, completionHandler: @escaping ObjectRequestHandler<CustomerToken>) -> MoltinRequest { let data = [ "type": "token", "email": email, "password": password ] return super.post(withPath: "\(self.endpoint)/tokens", withData: data, completionHandler: completionHandler) } /** Return all instances of type `Customer` - Author: Craig Tweedy - parameters: - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func all(completionHandler: @escaping DefaultCollectionRequestHandler) -> MoltinRequest { return super.list(withPath: "\(self.endpoint)", completionHandler: completionHandler) } /** Return all instances of type `Customer` by `id` - Author: Craig Tweedy - parameters: - forID: The ID of the object - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func get(forID id: String, completionHandler: @escaping DefaultObjectRequestHandler) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(id)", completionHandler: completionHandler) } /** Update a `Customer` - Author: Craig Tweedy - parameters: - customer: The `UpdateCustomer` data object to update this `Customer` with. - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func update(_ customer: UpdateCustomer, completionHandler: @escaping DefaultObjectRequestHandler) -> MoltinRequest { return super.put(withPath: "\(self.endpoint)/\(customer.id ?? "")", withData: customer.toDictionary(), completionHandler: completionHandler) } /** Return all instances of `Address` for a `Customer` - Author: Craig Tweedy - parameters: - forCustomer: The customer ID - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func addresses(forCustomer customer: String, completionHandler: @escaping DefaultAddressCollectionRequestHandler) -> MoltinRequest { return super.list(withPath: "\(self.endpoint)/\(customer)/addresses", completionHandler: completionHandler) } /** Get a specific `Address` for a `Customer` - Author: Craig Tweedy - parameters: - withID: The `Address` ID - forCustomer: The `Customer` ID - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func getAddress(withID id: String, forCustomer customer: String, completionHandler: @escaping DefaultAddressObjectRequestHandler) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(customer)/addresses/\(id)", completionHandler: completionHandler) } /** Create an `Address` for a `Customer` - Author: Craig Tweedy - parameters: - address: The `Address` object to create - forCustomer: The `Customer` ID to associate this address with - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. */ @discardableResult public func createAddress(_ address: Address, forCustomer customer: String, completionHandler: @escaping DefaultAddressObjectRequestHandler) -> MoltinRequest { return super.post(withPath: "\(self.endpoint)/\(customer)/addresses", withData: address.toDictionary(), completionHandler: completionHandler) } /** Update an `Address` for a `Customer` - Author: Craig Tweedy - parameters: - address: The `Address` object to create - forCustomer: The `Customer` ID to associate this address with - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. Ensure the `Address` contains the ID for the `Address` that you wish to create, and then fill in any variables you want to update in the request. */ @discardableResult public func updateAddress(_ address: Address, forCustomer customer: String, completionHandler: @escaping DefaultAddressObjectRequestHandler) -> MoltinRequest { return super.put(withPath: "\(self.endpoint)/\(customer)/addresses/\(address.id ?? "")", withData: address.toDictionary(), completionHandler: completionHandler) } /** Delete an `Address` for a `Customer` - Author: Craig Tweedy - parameters: - withID: The address ID - forCustomer: The `Customer` ID to associate this address with - completionHandler: The handler to be called on success or failure - returns: A instance of `MoltinRequest` which encapsulates the request. Ensure the `Address` contains the ID for the `Address` that you wish to create, and then fill in any variables you want to update in the request. */ @discardableResult public func deleteAddress(withID id: String, forCustomer customer: String, completionHandler: @escaping DefaultAddressObjectRequestHandler) -> MoltinRequest { return super.delete(withPath: "\(self.endpoint)/\(customer)/addresses/\(id)", completionHandler: completionHandler) } }
mit
20c175b7c37f669d475e3e81fb80b5b4
40.89011
178
0.661595
5.320307
false
false
false
false
cacawai/Tap2Read
tap2read/Pods/ReactiveUI/ReactiveUI/ReactiveUI/UIControl.swift
1
2881
// // UIControl.swift // ReactiveControl // // Created by Zhixuan Lai on 1/8/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit public extension UIControl { convenience init(action: @escaping (UIControl) -> (), forControlEvents events: UIControlEvents) { self.init() addAction(action, forControlEvents: events) } convenience init(forControlEvents events: UIControlEvents, action: @escaping (UIControl) -> ()) { self.init() addAction(action, forControlEvents: events) } func addAction(_ action: @escaping (UIControl) -> (), forControlEvents events: UIControlEvents) { removeAction(forControlEvents: events) let proxyTarget = RUIControlProxyTarget(action: action) proxyTargets[keyForEvents(events)] = proxyTarget addTarget(proxyTarget, action: RUIControlProxyTarget.actionSelector(), for: events) } func forControlEvents(_ events: UIControlEvents, addAction action: @escaping (UIControl) -> ()) { addAction(action, forControlEvents: events) } func removeAction(forControlEvents events: UIControlEvents) { if let proxyTarget = proxyTargets[keyForEvents(events)] { removeTarget(proxyTarget, action: RUIControlProxyTarget.actionSelector(), for: events) proxyTargets.removeValue(forKey: keyForEvents(events)) } } func actionForControlEvent(_ events: UIControlEvents) -> ((UIControl) -> ())? { return proxyTargets[keyForEvents(events)]?.action } var actions: [(UIControl) -> ()] { return [RUIControlProxyTarget](proxyTargets.values).map({$0.action}) } } internal extension UIControl { typealias RUIControlProxyTargets = [String: RUIControlProxyTarget] class RUIControlProxyTarget : RUIProxyTarget { var action: (UIControl) -> () init(action: @escaping (UIControl) -> ()) { self.action = action } func performAction(_ control: UIControl) { action(control) } } func keyForEvents(_ events: UIControlEvents) -> String { return "UIControlEvents: \(events.rawValue)" } var proxyTargets: RUIControlProxyTargets { get { if let targets = objc_getAssociatedObject(self, &RUIProxyTargetsKey) as? RUIControlProxyTargets { return targets } else { return setProxyTargets(RUIControlProxyTargets()) } } set { setProxyTargets(newValue) } } fileprivate func setProxyTargets(_ newValue: RUIControlProxyTargets) -> RUIControlProxyTargets { objc_setAssociatedObject(self, &RUIProxyTargetsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC); return newValue } }
mit
efb04cdaa9c6916176fbfb817f4fd479
31.011111
109
0.635196
4.891341
false
false
false
false
massimoksi/Ticker
Source/Ticker.swift
1
4501
// Copyright (c) 2016 Massimo Peri (@massimoksi) // // 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 var logger: TickerLogger? var minimumLogLevel = LogLevel.Debug // MARK: Setup public func setup(level: LogLevel = .Info, style: LogLevelStyle = .Funny, showTimestamp: Bool = true) { logger = TickerLogger(levelStyle: style, showTimestamp: showTimestamp) minimumLogLevel = level } // MARK: Logging /** Logs an info message on console. - parameter message: The info message to be logged. */ public func info(message: String) { logger?.log(message, level: .Info) } /** Logs a debug message on console. - parameter message: The debug message to be logged. */ public func debug(message: String) { logger?.log(message, level: .Debug) } /** Logs a warning message on console. - parameter message: The warning message to be logged. */ public func warning(message: String) { logger?.log(message, level: .Warning) } /** Logs an error message on console. - parameter message: The error message to be logged. */ public func error(message: String) { logger?.log(message, level: .Error) } /** Logs a failure message on console. - parameter message: The severe error message to be logged. */ public func failure(message: String) { logger?.log(message, level: .Failure) } // MARK: - LogLevelStyle public enum LogLevelStyle { case Hidden case Verbose case Symbolic case Funny case Casual(urban: Bool) func description(level: LogLevel) -> String { switch self { case .Hidden: return "" case .Verbose: return level.verboseDescription() + ": " case .Symbolic: return level.symbolicDescription() + " " case .Funny: return level.funnyDescription() + " " case .Casual(let urban): return level.casualDescription(urban) + " " } } } // MARK: - LogLevel public enum LogLevel { case Info case Debug case Warning case Error case Failure private func verboseDescription() -> String { switch self { case .Info: return "Info" case .Debug: return "Debug" case .Warning: return "Warning" case .Error: return "Error" case .Failure: return "Failure" } } private func symbolicDescription() -> String { switch self { case .Info: return "[NFO]" case .Debug: return "[DBG]" case .Warning: return "[WRN]" case .Error: return "[ERR]" case .Failure: return "[FLR]" } } private func funnyDescription() -> String { switch self { case .Info: return "📢" case .Debug: return "🐞" case .Warning: return "⚠️" case .Error: return "💩" case .Failure: return "💣" } } private func casualDescription(urban: Bool) -> String { switch self { case .Info: return "Psst!" case .Debug: return "Look!" case .Warning: return "Wait!" case .Error: return urban ? "S**t!" : "Oops!" case .Failure: return urban ? "F**k!" : "Ouch!" } } }
mit
3b0ee8460a8117d3e998f498a18bba2b
21.651515
103
0.604459
4.304223
false
false
false
false
brunophilipe/Noto
Noto/Application/AppDelegate.swift
1
6913
// // AppDelegate.swift // Noto // // Created by Bruno Philipe on 14/1/17. // Copyright © 2017 Bruno Philipe. All rights reserved. // // 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 Cocoa import CCNPreferencesWindowController import TRexAboutWindowController #if SPARKLE import Sparkle #endif let kNotoErrorDomain = "com.brunophilipe.Noto" @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { fileprivate let preferencesController = CCNPreferencesWindowController() fileprivate let aboutWindowController = TRexAboutWindowController(windowNibName: "PFAboutWindow") @IBOutlet weak var disabledInfoBarMenuItem: NSMenuItem! @IBOutlet weak var hudInfoBarMenuItem: NSMenuItem! @IBOutlet weak var statusBarInfoBarMenuItem: NSMenuItem! static let helpBookName = Bundle.main.object(forInfoDictionaryKey: "CFBundleHelpBookName") as! String struct HelpAnchor { static let preferencesGeneral = "general-prefs" static let preferencesEditor = "editor-prefs" static let preferencesThemes = "themes" static let preferencesInfoBar = "infobar-prefs" static let customThemes = "custom-themes" static let startDocument = "start-a-document" static let saveDocument = "save-a-document" static let openDocument = "open-a-document" static let changeDocumentEncoding = "change-document-encoding" static let hearDocumentAloud = "hear-document-aloud" static let overview = "overview" } // Cocoa Bindings @objc var keyDocumentCanReopen: NSNumber { return NSNumber(value: NSDocumentController.shared.currentDocument?.fileURL != nil) } @objc var hasUpdaterFeature: NSNumber { #if SPARKLE return true #else return false #endif } // App Delegate func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application makePreferencesController() makeAboutWindow() updateInfoBarModeMenuItems() Preferences.instance.addObserver(self, forKeyPath: "infoBarMode", options: .new, context: nil) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application Preferences.instance.removeObserver(self, forKeyPath: "infoBarMode") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if object is Preferences && keyPath == "infoBarMode" { updateInfoBarModeMenuItems() } } func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool { if FileManager.default.ubiquityIdentityToken != nil { // Show open panel instead of building a new file right away. let panel = NSOpenPanel() panel.makeKeyAndOrderFront(self) return false } else { return true } } // Private Methods private func updateInfoBarModeMenuItems() { let mode = Preferences.instance.infoBarMode disabledInfoBarMenuItem.state = (mode == .none ? .on : .off) hudInfoBarMenuItem.state = (mode == .hud ? .on : .off) statusBarInfoBarMenuItem.state = (mode == .status ? .on : .off) } private func makeAboutWindow() { let bundle = Bundle.main aboutWindowController.appURL = URL(string: "https://www.brunophilipe.com/software/noto")! aboutWindowController.appName = (bundle.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "Noto" if let creditsHtmlUrl = bundle.url(forResource: "acknowledgements", withExtension: "html"), let creditsHtmlData: Data = try? Data(contentsOf: creditsHtmlUrl), let creditsHtmlString = NSAttributedString(html: creditsHtmlData, options: [:], documentAttributes: nil) { aboutWindowController.appCredits = creditsHtmlString } let font: NSFont = NSFont(name: "HelveticaNeue", size: 11) ?? NSFont.systemFont(ofSize: 11) let color: NSColor = NSColor.tertiaryLabelColor let copyright = (bundle.object(forInfoDictionaryKey: "NSHumanReadableCopyright") as? String) ?? "Copyright © 2017 Bruno Philipe. All rights reserved." let attribs: [NSAttributedString.Key : AnyObject] = [.foregroundColor: color, .font: font] aboutWindowController.appCopyright = NSAttributedString(string: copyright, attributes: attribs) aboutWindowController.windowShouldHaveShadow = true } private func makePreferencesController() { preferencesController.centerToolbarItems = true let types: [PreferencesController.Type] = [ GeneralPreferencesController.self, EditorPreferencesViewController.self, ThemePreferencesController.self ] if let window = preferencesController.window { let controllers: [PreferencesController] = types.reduce([]) { (controllers, controllerType) -> [PreferencesController] in if let controller = controllerType.make(preferencesWindow: window) { return controllers + [controller] } else { return controllers } } preferencesController.setPreferencesViewControllers(controllers) } } } extension AppDelegate { @IBAction func showPreferences(_ sender: AnyObject) { preferencesController.showPreferencesWindow() } @IBAction func setInfoBarMode(_ sender: AnyObject) { if let menuItem = sender as? NSMenuItem, let mode = Preferences.InfoBarMode(rawValue: menuItem.tag) { Preferences.instance.infoBarMode = mode } } @IBAction func showAboutWindow(_ sender: Any) { aboutWindowController.showWindow(sender) } @IBAction func increaseFontSize(_ sender: Any) { Preferences.instance.increaseFontSize() } @IBAction func decreaseFontSize(_ sender: Any) { Preferences.instance.decreaseFontSize() } @IBAction func resetFontSize(_ sender: Any) { Preferences.instance.resetFontSize() } @IBAction func checkForUpdates(_ sender: Any) { #if SPARKLE SUUpdater.shared().checkForUpdates(sender) #endif } @IBAction func newDocumentAndActivate(_ sender: Any) { NSDocumentController.shared.newDocument(sender) // Invoked from Dock, that's why ignoringOtherApps is true. NSApplication.shared.activate(ignoringOtherApps: true) } @IBAction func openDocumentAndActivate(_ sender: Any) { NSDocumentController.shared.openDocument(sender) // Invoked from Dock, that's why ignoringOtherApps is true. NSApplication.shared.activate(ignoringOtherApps: true) } }
gpl-3.0
ee08631826b509f585d0af538118e525
27.32377
152
0.746057
3.856585
false
false
false
false
CosmicMind/Motion
Sources/Transition/MotionTransition.swift
3
23982
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit @objc(MotionViewControllerDelegate) public protocol MotionViewControllerDelegate { /** An optional delegation method that is executed motion will start the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motionWillStartTransition(motion: MotionTransition) /** An optional delegation method that is executed motion did end the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motionDidEndTransition(motion: MotionTransition) /** An optional delegation method that is executed motion did cancel the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motionDidCancelTransition(motion: MotionTransition) /** An optional delegation method that is executed when the source view controller will start the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motion(motion: MotionTransition, willStartTransitionFrom viewController: UIViewController) /** An optional delegation method that is executed when the source view controller did end the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motion(motion: MotionTransition, didEndTransitionFrom viewController: UIViewController) /** An optional delegation method that is executed when the source view controller did cancel the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motion(motion: MotionTransition, didCancelTransitionFrom viewController: UIViewController) /** An optional delegation method that is executed when the destination view controller will start the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motion(motion: MotionTransition, willStartTransitionTo viewController: UIViewController) /** An optional delegation method that is executed when the destination view controller did end the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motion(motion: MotionTransition, didEndTransitionTo viewController: UIViewController) /** An optional delegation method that is executed when the destination view controller did cancel the transition. - Parameter motion: A MotionTransition instance. - Parameter willStartTransitionFrom viewController: A UIViewController. */ @objc optional func motion(motion: MotionTransition, didCancelTransitionTo viewController: UIViewController) } /** ### The singleton class/object for controlling interactive transitions. ```swift Motion.shared ``` #### Use the following methods for controlling the interactive transition: ```swift func update(progress: Double) func end() func cancel() func apply(transitions: [MotionTargetState], to view: UIView) ``` */ public typealias MotionCancelBlock = (Bool) -> Void public class Motion: NSObject {} extension Motion { /** Executes a block of code asynchronously on the main thread. - Parameter execute: A block that is executed asynchronously on the main thread. */ public class func async(_ execute: @escaping () -> Void) { DispatchQueue.main.async(execute: execute) } /** Executes a block of code after a time delay. - Parameter _ time: A delay time. - Parameter execute: A block that is executed once delay has passed. - Returns: An optional MotionCancelBlock. */ @discardableResult public class func delay(_ time: TimeInterval, execute: @escaping () -> Void) -> MotionCancelBlock? { var cancelable: MotionCancelBlock? let delayed: MotionCancelBlock = { if !$0 { async(execute) } cancelable = nil } cancelable = delayed DispatchQueue.main.asyncAfter(deadline: .now() + time) { cancelable?(false) } return cancelable } /** Cancels the delayed MotionCancelBlock. - Parameter delayed completion: An MotionCancelBlock. */ public class func cancel(delayed completion: MotionCancelBlock) { completion(true) } /** Disables the default animations set on CALayers. - Parameter animations: A callback that wraps the animations to disable. */ public class func disable(_ animations: (() -> Void)) { animate(duration: 0, animations: animations) } /** Runs an animation with a specified duration. - Parameter duration: An animation duration time. - Parameter animations: An animation block. - Parameter timingFunction: A CAMediaTimingFunction. - Parameter completion: A completion block that is executed once the animations have completed. */ public class func animate(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction = .easeInOut, animations: (() -> Void), completion: (() -> Void)? = nil) { CATransaction.begin() CATransaction.setAnimationDuration(duration) CATransaction.setCompletionBlock(completion) CATransaction.setAnimationTimingFunction(timingFunction) animations() CATransaction.commit() } /** Creates a CAAnimationGroup. - Parameter animations: An Array of CAAnimation objects. - Parameter timingFunction: A CAMediaTimingFunction. - Parameter duration: An animation duration time for the group. - Returns: A CAAnimationGroup. */ public class func animate(group animations: [CAAnimation], timingFunction: CAMediaTimingFunction = .easeInOut, duration: CFTimeInterval = 0.5) -> CAAnimationGroup { let group = CAAnimationGroup() group.animations = animations group.duration = duration group.timingFunction = timingFunction return group } } public enum MotionTransitionState: Int { /// Motion is able to start a new transition. case possible /// UIKit has notified Motion about a pending transition. /// Motion hasn't started preparation. case notified /// Motion's `start` method has been called. Preparing the animation. case starting /// Motions's `animate` method has been called. Animation has started. case animating /// Motions's `complete` method has been called. Transition has ended or has /// been cancelled. Motion is cleaning up. case completing } open class MotionTransition: NSObject { /// Shared singleton object for controlling the transition public static let shared = MotionTransition() /// Default animation type. internal var defaultAnimation = MotionTransitionAnimationType.auto /// The color of the transitioning container. internal var containerBackgroundColor = UIColor.black /// A boolean indicating if the user may interact with the /// view controller while in transition. public var isUserInteractionEnabled = false /// A reference to the MotionViewOrderStrategy. public var viewOrderStrategy = MotionViewOrderStrategy.auto /// State of the transition. public internal(set) var state = MotionTransitionState.possible { didSet { guard .notified != state, .starting != state else { return } beginCallback?(.animating == state) beginCallback = nil } } /// A boolean indicating whether a transition is active. public var isTransitioning: Bool { return state != .possible } /// Whether or not we are presenting the destination view controller. public internal(set) var isPresenting = true /** A boolean indicating if the transition is of modal type. True if `viewController.present(_:animated:completion:)` or `viewController.dismiss(animated:completion:)` is called, false otherwise. */ public internal(set) var isModalTransition = false /// A boolean indicating whether the transition interactive or not. public var isInteractive: Bool { return !progressRunner.isRunning } /** A view container used to hold all the animating views during a transition. */ public internal(set) var container: UIView! /// UIKit's supplied transition container. internal var transitionContainer: UIView? /// An optional begin callbcak. internal var beginCallback: ((Bool) -> Void)? /// An optional completion callback. internal var completionCallback: ((Bool) -> Void)? /// An Array of MotionPreprocessors used during a transition. internal lazy var preprocessors = [MotionPreprocessor]() /// An Array of MotionAnimators used during a transition. internal lazy var animators = [MotionAnimator]() /// An Array of MotionPlugins used during a transition. internal lazy var plugins = [MotionPlugin]() /// The matching fromViews to toViews based on the motionIdentifier value. internal var animatingFromViews = [UIView]() internal var animatingToViews = [UIView]() /// Plugins that are enabled during the transition. internal static var enabledPlugins = [MotionPlugin.Type]() /// Source view controller. public internal(set) var fromViewController: UIViewController? /// A reference to the fromView, fromViewController.view. internal var fromView: UIView? { return fromViewController?.view } /// Destination view controller. public internal(set) var toViewController: UIViewController? /// A reference to the toView, toViewController.view. internal var toView: UIView? { return toViewController?.view } /// A reference to the MotionContext. public internal(set) var context: MotionContext! /// An Array of observers that are updated during a transition. internal var transitionObservers: [MotionTargetStateObserver]? /// Max duration used by MotionAnimators and MotionPlugins. public internal(set) var totalDuration: TimeInterval = 0 /// Progress of the current transition. 0 if no transition is happening. public internal(set) var progress: TimeInterval = 0 { didSet { guard .animating == state else { return } updateTransitionObservers() if isInteractive { updateAnimators() } else { updatePlugins() } transitionContext?.updateInteractiveTransition(CGFloat(progress)) } } /// A reference to a MotionProgressRunner. lazy var progressRunner: MotionProgressRunner = { let runner = MotionProgressRunner() runner.delegate = self return runner }() /** A UIViewControllerContextTransitioning object provided by UIKit, which might be nil when isTransitioning. This happens when calling motionReplaceViewController */ internal weak var transitionContext: UIViewControllerContextTransitioning? /// A reference to a fullscreen snapshot. internal var fullScreenSnapshot: UIView? /** By default, Motion will always appear to be interactive to UIKit. This forces it to appear non-interactive. Used when doing a motionReplaceViewController within a UINavigationController, to fix a bug with UINavigationController.setViewControllers not able to handle interactive transitions. */ internal var forceNonInteractive = false internal var forceFinishing: Bool? internal var startingProgress: TimeInterval? /// A weak reference to the currently transitioning view controller. internal weak var transitioningViewController: UIViewController? /// Indicates whether a UINavigationController is transitioning. internal var isNavigationController: Bool { return transitioningViewController is UINavigationController } /// Indicates whether a UITabBarController is transitioning. internal var isTabBarController: Bool { return transitioningViewController is UITabBarController } /// Indicates whether a UINavigationController or UITabBarController is transitioning. internal var isContainerController: Bool { return isNavigationController || isTabBarController } /// Indicates whether the to view controller is full screen. internal var toOverFullScreen: Bool { return !isContainerController && (toViewController?.modalPresentationStyle == .overFullScreen || toViewController?.modalPresentationStyle == .overCurrentContext) } /// Indicates whether the from view controller is full screen. internal var fromOverFullScreen: Bool { return !isContainerController && (fromViewController?.modalPresentationStyle == .overFullScreen || fromViewController?.modalPresentationStyle == .overCurrentContext) } /// An initializer. internal override init() { super.init() } /** Complete the transition. - Parameter after: A TimeInterval. - Parameter isFinishing: A Boolean indicating if the transition has completed. */ func complete(after: TimeInterval, isFinishing: Bool) { guard [MotionTransitionState.animating, .starting, .notified].contains(state) else { return } if after <= 1.0 / 120 { complete(isFinishing: isFinishing) return } let duration = after / (isFinishing ? max((1 - progress), 0.01) : max(progress, 0.01)) progressRunner.start(progress: progress * duration, duration: duration, isReversed: !isFinishing) } private func delegate(respondingTo selector: Selector?) -> NSObjectProtocol? { guard let selector = selector else { return nil } /// Workaround for recursion happening during navigationController transtion. /// Avoiding private selectors (e.g _shouldCrossFadeBottomBars) guard !selector.description.starts(with: "_") else { return nil } /// Get relevant delegate according to controller type let delegate: NSObjectProtocol? = { if isTabBarController { return transitioningViewController?.previousTabBarDelegate } if isNavigationController { return transitioningViewController?.previousNavigationDelegate } return nil }() return true == delegate?.responds(to: selector) ? delegate : nil } open override func forwardingTarget(for aSelector: Selector!) -> Any? { guard let superTarget = super.forwardingTarget(for: aSelector) else { return delegate(respondingTo: aSelector) } return superTarget } open override func responds(to aSelector: Selector!) -> Bool { return super.responds(to: aSelector) || nil != delegate(respondingTo: aSelector) } } extension MotionTransition: MotionProgressRunnerDelegate { func update(progress: TimeInterval) { self.progress = progress } } extension MotionTransition { /** Receive callbacks on each animation frame. Observers will be cleaned when a transition completes. - Parameter observer: A MotionTargetStateObserver. */ func addTransitionObserver(observer: MotionTargetStateObserver) { if nil == transitionObservers { transitionObservers = [] } transitionObservers?.append(observer) } } fileprivate extension MotionTransition { /// Updates the transition observers. func updateTransitionObservers() { guard let observers = transitionObservers else { return } for v in observers { v.motion(transitionObserver: v, didUpdateWith: progress) } } /// Updates the animators. func updateAnimators() { let t = progress * totalDuration for v in animators { v.seek(to: t) } } /// Updates the plugins. func updatePlugins() { let t = progress * totalDuration for v in plugins where v.requirePerFrameCallback { v.seek(to: t) } } } internal extension MotionTransition { /** Checks if a given plugin is enabled. - Parameter plugin: A MotionPlugin.Type. - Returns: A boolean indicating if the plugin is enabled or not. */ static func isEnabled(plugin: MotionPlugin.Type) -> Bool { return nil != enabledPlugins.firstIndex(where: { return $0 == plugin }) } /** Enables a given plugin. - Parameter plugin: A MotionPlugin.Type. */ static func enable(plugin: MotionPlugin.Type) { disable(plugin: plugin) enabledPlugins.append(plugin) } /** Disables a given plugin. - Parameter plugin: A MotionPlugin.Type. */ static func disable(plugin: MotionPlugin.Type) { guard let index = enabledPlugins.firstIndex(where: { return $0 == plugin }) else { return } enabledPlugins.remove(at: index) } } public extension MotionTransition { /// Turn off built-in animations for the next transition. func disableDefaultAnimationForNextTransition() { defaultAnimation = .none } /** Set the default animation for the next transition. This may override the root-view's motionModifiers during the transition. - Parameter animation: A MotionTransitionAnimationType. */ func setAnimationForNextTransition(_ animation: MotionTransitionAnimationType) { defaultAnimation = animation } /** Set the container background color for the next transition. - Parameter _ color: A UIColor. */ func setContainerBackgroundColorForNextTransition(_ color: UIColor) { containerBackgroundColor = color } /** Set the completion callback closure for the next transition. - Parameter _ completion: An optional closure receiving a Boolean indicating if transition is finishing or cancelling. */ func setCompletionCallbackForNextTransition(_ completion: ((Bool) -> Void)?) { completionCallback = completion } } internal extension MotionTransition { /** Processes the start transition delegation methods. - Parameter transitionContext: An optional UIViewControllerContextTransitioning. - Parameter fromViewController: An optional UIViewController. - Parameter toViewController: An optional UIViewController. */ func processStartTransitionDelegation(transitionContext: UIViewControllerContextTransitioning?, fromViewController: UIViewController?, toViewController: UIViewController?) { guard let fvc = fromViewController else { return } guard let tvc = toViewController else { return } if transitionContext == nil { fvc.beginAppearanceTransition(false, animated: true) tvc.beginAppearanceTransition(true, animated: true) } processForMotionDelegate(viewController: fvc) { [weak self] in guard let `self` = self else { return } $0.motion?(motion: self, willStartTransitionTo: tvc) $0.motionWillStartTransition?(motion: self) } processForMotionDelegate(viewController: tvc) { [weak self] in guard let `self` = self else { return } $0.motion?(motion: self, willStartTransitionFrom: fvc) $0.motionWillStartTransition?(motion: self) } } /** Processes the end transition delegation methods. - Parameter transitionContext: An optional UIViewControllerContextTransitioning. - Parameter fromViewController: An optional UIViewController. - Parameter toViewController: An optional UIViewController. */ func processEndTransitionDelegation(transitionContext: UIViewControllerContextTransitioning?, fromViewController: UIViewController?, toViewController: UIViewController?) { guard let fvc = fromViewController else { return } guard let tvc = toViewController else { return } if transitionContext == nil { tvc.endAppearanceTransition() fvc.endAppearanceTransition() } processForMotionDelegate(viewController: fvc) { [weak self] in guard let `self` = self else { return } $0.motion?(motion: self, didEndTransitionTo: tvc) $0.motionDidEndTransition?(motion: self) } processForMotionDelegate(viewController: tvc) { [weak self] in guard let `self` = self else { return } $0.motion?(motion: self, didEndTransitionFrom: fvc) $0.motionDidEndTransition?(motion: self) } transitionContext?.finishInteractiveTransition() } /** Processes the cancel transition delegation methods. - Parameter transitionContext: An optional UIViewControllerContextTransitioning. - Parameter fromViewController: An optional UIViewController. - Parameter toViewController: An optional UIViewController. */ func processCancelTransitionDelegation(transitionContext: UIViewControllerContextTransitioning?, fromViewController: UIViewController?, toViewController: UIViewController?) { guard let fvc = fromViewController else { return } guard let tvc = toViewController else { return } if transitionContext == nil { tvc.beginAppearanceTransition(false, animated: true) tvc.endAppearanceTransition() fvc.beginAppearanceTransition(true, animated: true) fvc.endAppearanceTransition() } processForMotionDelegate(viewController: fvc) { [weak self] in guard let `self` = self else { return } $0.motion?(motion: self, didCancelTransitionTo: tvc) $0.motionDidCancelTransition?(motion: self) } processForMotionDelegate(viewController: tvc) { [weak self] in guard let `self` = self else { return } $0.motion?(motion: self, didCancelTransitionFrom: fvc) $0.motionDidCancelTransition?(motion: self) } transitionContext?.cancelInteractiveTransition() } } internal extension MotionTransition { /** Helper for processing the MotionViewControllerDelegate. - Parameter viewController: A UIViewController of type `T`. - Parameter execute: A callback for execution during processing. */ func processForMotionDelegate<T: UIViewController>(viewController: T, execute: (MotionViewControllerDelegate) -> Void) { if let delegate = viewController as? MotionViewControllerDelegate { execute(delegate) } if let v = viewController as? UINavigationController, let delegate = v.topViewController as? MotionViewControllerDelegate { execute(delegate) } if let v = viewController as? UITabBarController, let delegate = v.viewControllers?[v.selectedIndex] as? MotionViewControllerDelegate { execute(delegate) } } }
mit
c1e831b2ad059ceeb12cc7d857d4895d
31.762295
176
0.719665
5.230534
false
false
false
false
bromas/Architect
UIArchitect/ConstrainingPins.swift
1
3277
// // PinArchitectures.swift // LayoutArchitect // // Created by Brian Thomas on 8/2/14. // Copyright (c) 2014 Brian Thomas. All rights reserved. // public typealias ExtendedPinningOptions = (toEdge: BlueprintGuide, relation: BlueprintRelation, magnitude: CGFloat, priority: BlueprintPriority) public typealias PinResult = [BlueprintGuide: NSLayoutConstraint] public typealias EdgeGuide = (view: UIView, edge: BlueprintGuide) import Foundation import UIKit public func pin(#top: UIView, #toBottom: UIView, #magnitude: CGFloat) -> NSLayoutConstraint { return pin((top, .Top), to: (toBottom, .Bottom), magnitude: magnitude) } public func pin(#right: UIView, #toLeft: UIView, #magnitude: CGFloat) -> NSLayoutConstraint { return pin((right, .Right), to: (toLeft, .Left), magnitude: magnitude) } public func pin(#bottom: UIView, #toTop: UIView, #magnitude: CGFloat) -> NSLayoutConstraint { return pin((bottom, .Bottom), to: (toTop, .Top), magnitude: magnitude) } public func pin(#left: UIView, #toRight: UIView, #magnitude: CGFloat) -> NSLayoutConstraint { return pin((left, .Left), to: (toRight, .Right), magnitude: magnitude) } public func pin(view: UIView, #edge:BlueprintGuide, #toGuide: UILayoutSupport, #inController: UIViewController, #constant: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: toGuide, attribute: .Bottom, multiplier: 1.0, constant: constant) inController.view.addConstraint(constraint) return constraint } public func pin(from: EdgeGuide, #to: EdgeGuide, #magnitude: CGFloat) -> NSLayoutConstraint { var newOptions = [BlueprintGuide: ExtendedPinningOptions]() newOptions[from.edge] = (to.edge, BlueprintRelation.Equal, magnitude, BlueprintPriority.Required) return pin(from.view, to: to.view, withExtendedOptions: newOptions)[from.edge]! } public func pin(view: UIView, to toView: UIView, with options: [BlueprintGuide: (toEdge: BlueprintGuide, magnitude: CGFloat)]) -> PinResult { var newOptions = [BlueprintGuide: ExtendedPinningOptions]() for (guide, option) in options { let newOption = (option.toEdge, BlueprintRelation.Equal, option.magnitude, BlueprintPriority.Required) newOptions[guide] = newOption } return pin(view, to: toView, withExtendedOptions: newOptions) } public func pin(view: UIView, to toView: UIView, withExtendedOptions options: [BlueprintGuide: (toEdge: BlueprintGuide, relation: BlueprintRelation, magnitude: CGFloat, priority: BlueprintPriority)]) -> PinResult { let superview = assertCommonSuperview(view, and: toView) var constraints = [BlueprintGuide: NSLayoutConstraint]() for (attribute: BlueprintGuide, with: ExtendedPinningOptions) in options { let toEdge = with.toEdge let priority = with.priority.float() for (guide, option) in options { let newConstraint = NSLayoutConstraint(item: view, attribute: attribute.layoutAttribute(), relatedBy: option.relation.layoutRelation(), toItem: toView, attribute: toEdge.layoutAttribute(), multiplier: 1, constant: CGFloat(option.magnitude)) newConstraint.priority = priority constraints[guide] = newConstraint superview.addConstraint(constraints[guide]!) } } return constraints }
mit
6edef2cbb0b79e6d3a5214718a1dadd2
43.297297
214
0.745194
4.132409
false
false
false
false
codepath-volunteer-app/VolunteerMe
VolunteerMe/VolunteerMe/Event.swift
1
9725
// // Event.swift // VolunteerMe // // Created by Auster Chen on 10/14/17. // Copyright © 2017 volunteer_me. All rights reserved. // import Foundation import Parse import DateToolsSwift class Event:PFObject, PFSubclassing { fileprivate static let DEFAULT_MAX_ATTENDEES = 100 fileprivate static let DEFAULT_SEARCH_MILES_RADIUS = 5 fileprivate static let DEFAULT_NUMBER_OF_ITEMS_TO_SEARCH = 20 fileprivate static let DEFAULT_NUMBER_OF_SECONDS_EVENT = 3600 @NSManaged var name: String? @NSManaged var nameLower: String? @NSManaged var eventDescription: String? @NSManaged var eventDescriptionLower: String? @NSManaged var imageUrl: String? @NSManaged var location: PFGeoPoint? @NSManaged var tags: [Tag]? // unix timestamp representing datetime of event @NSManaged var datetime: String? @NSManaged var maxAttendees: NSNumber? // number of seconds the event lasts @NSManaged var duration: NSNumber? var humanReadableDateString: String? { get { if let datetime = datetime { let date = Date(timeIntervalSince1970: Double(datetime)!) return date.format(with: .long) } return nil } } var humanReadableTimeString: String? { get { if let datetime = datetime { let date = Date(timeIntervalSince1970: Double(datetime)!) let formatter = DateFormatter() formatter.dateFormat = "h:mm a" formatter.amSymbol = "AM" formatter.pmSymbol = "PM" return formatter.string(from: date) } return nil } } var humanReadableTimeRange: String? { get { if let datetime = datetime { if let duration = duration { let startDate = Date(timeIntervalSince1970: (Double(datetime)!)) let endDate = Date(timeIntervalSince1970: (Double(datetime)! + Double(duration))) let formatter = DateFormatter() formatter.dateFormat = "h:mm a" formatter.amSymbol = "AM" formatter.pmSymbol = "PM" return "\(formatter.string(from: startDate)) - \(formatter.string(from: endDate))" } } return nil } } var attendees: [User] = [] fileprivate class func _getEvents(radiusInMiles: Double, targetLocation: (Double, Double), searchString: String?, tags: [Tag]?, limit: Int?, successCallback: @escaping ([Event]) -> ()) -> () { let (lat, long) = targetLocation let geoPoint = PFGeoPoint(latitude: lat, longitude: long) let query = PFQuery(className: "Event") query.includeKey("tags") query.whereKey("location", nearGeoPoint: geoPoint, withinMiles: radiusInMiles) if let tags = tags { if tags.count > 0 { query.whereKey("tags", containsAllObjectsIn: tags) } } if let searchString = searchString { query.whereKey("nameLower", hasPrefix: searchString.lowercased()) } if let limit = limit { query.limit = limit } else { query.limit = Event.DEFAULT_NUMBER_OF_ITEMS_TO_SEARCH } query.findObjectsInBackground { (results: [PFObject]?, error: Error?) in if let results = results { let events = results as! [Event] successCallback(events) } else if error != nil { print(error?.localizedDescription) } } } fileprivate class func _createEvent(name: String, datetime: String, duration: NSNumber?, latLong: (Double, Double), eventDescription: String?, imageUrl: String?, maxAttendees: Int?, tags: [Tag]?, successCallback: @escaping (Event) -> ()) -> (){ let event = Event() event.name = name event.nameLower = name.lowercased() event.datetime = datetime let (lat, long) = latLong event.location = PFGeoPoint(latitude: lat, longitude: long) if let duration = duration { event.duration = duration } else { event.duration = DEFAULT_NUMBER_OF_SECONDS_EVENT as! NSNumber } if let eventDescription = eventDescription { event.eventDescription = eventDescription event.eventDescriptionLower = eventDescription.lowercased() } if let imageUrl = imageUrl { event.imageUrl = imageUrl } if let tags = tags { event.tags = tags } if let maxAttendees = maxAttendees { event.maxAttendees = NSNumber(value: maxAttendees) } else { event.maxAttendees = NSNumber(value: Event.DEFAULT_MAX_ATTENDEES) } event.saveInBackground { (success: Bool, error: Error?) in if success { successCallback(event) } else if error != nil { print(error?.localizedDescription) } } } class func createEvent(name: String, datetime: String, duration: NSNumber?, latLong: (Double, Double), eventDescription: String?, imageUrl: String?, maxAttendees: Int?, tags: [String]?, successCallback: @escaping (Event) -> ()) -> (){ if let tags = tags { Tag.getTagsByNameArray(tags) { (tags: [Tag]) in Event._createEvent(name: name, datetime: datetime, duration: duration, latLong: latLong, eventDescription: eventDescription, imageUrl: imageUrl, maxAttendees: maxAttendees, tags: tags, successCallback: successCallback) } } else { Event._createEvent(name: name, datetime: datetime, duration: duration, latLong: latLong, eventDescription: eventDescription, imageUrl: imageUrl, maxAttendees: maxAttendees, tags: nil, successCallback: successCallback) } } // Uses current location to find events class func getNearbyEvents(radiusInMiles: Double, searchString: String?, tags: [String]?, limit: Int?, successCallback: @escaping ([Event]) -> ()) -> () { PFGeoPoint.geoPointForCurrentLocation { (geoPoint: PFGeoPoint?, error: Error?) in if let geoPoint = geoPoint { Event.getEvents(radiusInMiles: radiusInMiles, targetLocation: (geoPoint.latitude, geoPoint.longitude), searchString: searchString, tags: tags, limit: limit, successCallback: successCallback) } else if error != nil { print(error?.localizedDescription) } } } class func getEvents(radiusInMiles: Double, targetLocation: (Double, Double), searchString: String?, tags: [String]?, limit: Int?, successCallback: @escaping ([Event]) -> ()) -> () { if let tags = tags { Tag.getTagsByNameArray(tags) { (tags: [Tag]) in Event._getEvents(radiusInMiles: radiusInMiles, targetLocation: targetLocation, searchString: searchString, tags: tags, limit: limit, successCallback: successCallback) } } else { Event._getEvents(radiusInMiles: radiusInMiles, targetLocation: targetLocation, searchString: searchString, tags: nil, limit: limit, successCallback: successCallback) } } func isInPast() -> Bool { let date: Date = Date(timeIntervalSince1970: Double(datetime!)!) return date.isEarlier(than: .init(timeIntervalSinceNow: 0)) } func isInFuture() -> Bool { let date: Date = Date(timeIntervalSince1970: Double(datetime!)!) return date.isLater(than: .init(timeIntervalSinceNow: 0)) } class func parseClassName() -> String { return "Event" } func getTags(successCallback: @escaping ([Tag]) -> ()) -> () { PFQuery(className: "Event").includeKey("tags").whereKey("objectId", equalTo: objectId!).findObjectsInBackground() { (results: [PFObject]?, error: Error?) in if let results = results { if results.count > 0 { let event = results[0] as! Event successCallback(event.tags ?? []) } } else if error != nil { print(error?.localizedDescription) } } } func getRemainingSpots() -> Int { if let maxAttendees = maxAttendees { return Int(maxAttendees) - attendees.count } else { return Event.DEFAULT_MAX_ATTENDEES - attendees.count } } func registerUser(user: User, successCallback: @escaping (Bool) -> ()) -> () { EventAttendee.createNewEventAttendee(user: user, event: self, successCallback: successCallback) } func fetchAttendees(successCallback: @escaping ([User]) -> ()) { EventAttendee.getUsersForEvent(event: self) { (users: [User]) in self.attendees = users successCallback(users) } } func isUserRegisteredForEvent(user: User, successCallback: @escaping (Bool) -> ()) -> () { return EventAttendee.isUserRegisteredForEvent(user: user, event: self, successCallback: successCallback) } func printHumanReadableTestString() -> () { print("event name: \(name)") print("event description: \(eventDescription)") print("event time: \(humanReadableDateString)") print("event url: \(imageUrl)") print("event location: lat: \(location!.latitude), long: \(location!.longitude)") } }
mit
b7a43be1d413e5f8621142a50031a774
38.528455
248
0.591218
4.825806
false
false
false
false
GoodGuysLabs/PebbleGum
PebbleGum/CredentialDetailViewController.swift
1
13086
// // CredentialViewController.swift // PebbleGum // // Created by Anthony Da Mota on 14/02/15. // Copyright (c) 2015 GoodGuysLabs. All rights reserved. // import UIKit import Realm class CredentialDetailViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource { let connectedPebble: AnyObject = theFunctions().pebbleInfos() var credTitle:String! var credId:Int! let credentials = Credential.allObjects() let realm = RLMRealm.defaultRealm() var choosenCredential:RLMResults? var inputTitle:FloatLabelTextField! var categoryPicker:UIPickerView! var selectedIcon:String = "" var keychainNewIcon:UILabel! var inputEmail:FloatLabelTextField! var inputPassword:FloatLabelTextField! var inputNotes:UITextView! let theCategories = Category.allObjects().sortedResultsUsingProperty("categoryName", ascending: true) override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewWillAppear(animated: Bool) { let backBarButton: UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("BackKeychain", comment: "Back button title"), style: .Bordered, target: nil, action: nil) self.navigationItem.backBarButtonItem = backBarButton let addCredentialCheckButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "AddCredentialCheck:") navigationItem.rightBarButtonItem = addCredentialCheckButton var credDataResults:RLMResults credDataResults = Credential.objectsWhere("credentialId = %d", credId) var credDataObject = credDataResults.firstObject() as Credential // Keychain icon font keychainNewIcon = UILabel(frame: CGRectMake(self.view.frame.width/14, self.view.frame.height/7, self.view.frame.width - self.view.frame.width/7, self.view.frame.height/10)) keychainNewIcon.font = UIFont.fontAwesomeOfSize(self.view.frame.height/10) keychainNewIcon.textColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.7) var theIcon:Category = credDataObject.category! as Category keychainNewIcon.text = String.fontAwesomeIconWithName(theIcon.categoryIcon) self.view.addSubview(keychainNewIcon) NSNotificationCenter.defaultCenter().addObserver(self, selector: "TextDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "TextDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil) // Credential Input Title inputTitle = FloatLabelTextField(frame: CGRectMake(self.view.frame.width - self.view.frame.width/1.5, self.view.frame.height/6, self.view.frame.width - self.view.frame.width/2.3, self.view.frame.height/14)) inputTitle.attributedPlaceholder = NSAttributedString(string: String(format: NSLocalizedString("AddCredentialInputTitle", comment: "")), attributes:[NSForegroundColorAttributeName: theFunctions().UIColorFromRGB("D1CCC0", alpha: 0.8)]) inputTitle.titleActiveTextColour = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.5) inputTitle.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.12) inputTitle.textColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.8) inputTitle.leftView = UIView(frame: CGRectMake(0, 0, 5, 20)) inputTitle.leftViewMode = UITextFieldViewMode.Always inputTitle.clearButtonMode = UITextFieldViewMode.WhileEditing inputTitle.keyboardAppearance = .Dark inputTitle.text = credDataObject.credentialTitle self.view.addSubview(inputTitle) // Credential Category Picker View categoryPicker = UIPickerView(frame: CGRectMake(self.view.frame.width/14, self.view.frame.height/3.5, self.view.frame.width - self.view.frame.width/6, self.view.frame.height/12)) categoryPicker.delegate = self categoryPicker.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.12) categoryPicker.showsSelectionIndicator = true categoryPicker.selectRow(9, inComponent: 0, animated: true) self.view.addSubview(categoryPicker) // Credential Input Email/Username inputEmail = FloatLabelTextField(frame: CGRectMake(self.view.frame.width/14, self.view.frame.height/1.8, self.view.frame.width - self.view.frame.width/6, self.view.frame.height/14)) inputEmail.attributedPlaceholder = NSAttributedString(string: String(format: NSLocalizedString("AddCredentialInputLogin", comment: "")), attributes:[NSForegroundColorAttributeName: theFunctions().UIColorFromRGB("D1CCC0", alpha: 0.8)]) inputEmail.titleActiveTextColour = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.5) inputEmail.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.12) inputEmail.textColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.8) inputEmail.leftView = UIView(frame: CGRectMake(0, 0, 5, 20)) inputEmail.leftViewMode = UITextFieldViewMode.Always inputEmail.clearButtonMode = UITextFieldViewMode.WhileEditing inputEmail.autocapitalizationType = .None inputEmail.autocorrectionType = .No inputEmail.keyboardType = .EmailAddress inputEmail.keyboardAppearance = .Dark inputEmail.text = credDataObject.credentialEmail self.view.addSubview(inputEmail) // Credential Input Password inputPassword = FloatLabelTextField(frame: CGRectMake(self.view.frame.width/14, self.view.frame.height/1.5, self.view.frame.width - self.view.frame.width/6, self.view.frame.height/14)) inputPassword.attributedPlaceholder = NSAttributedString(string: String(format: NSLocalizedString("AddCredentialInputPassword", comment: "")), attributes:[NSForegroundColorAttributeName: theFunctions().UIColorFromRGB("D1CCC0", alpha: 0.8)]) inputPassword.titleActiveTextColour = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.5) inputPassword.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.12) inputPassword.textColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.8) inputPassword.leftView = UIView(frame: CGRectMake(0, 0, 5, 20)) inputPassword.leftViewMode = UITextFieldViewMode.Always inputPassword.clearButtonMode = UITextFieldViewMode.WhileEditing inputPassword.autocapitalizationType = .None inputPassword.autocorrectionType = .No inputPassword.keyboardAppearance = .Dark inputPassword.secureTextEntry = true inputPassword.tag = 3 inputPassword.text = credDataObject.credentialPassword self.view.addSubview(inputPassword) // Credential Input Notes inputNotes = UITextView(frame: CGRectMake(self.view.frame.width/14, self.view.frame.height/1.3, self.view.frame.width - self.view.frame.width/6, self.view.frame.height/7)) inputNotes.delegate = self inputNotes.text = NSLocalizedString("AddCredentialInputNotes", comment: "") inputNotes.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.12) inputNotes.textColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.8) inputNotes.keyboardAppearance = .Dark inputNotes.tag = 4 inputPassword.text = credDataObject.credentialNotes self.view.addSubview(inputNotes) } override func viewDidLoad() { super.viewDidLoad() } // MARK: - loadView override func loadView() { let view = CredentialDetailView(frame: UIScreen.mainScreen().bounds) self.title = credTitle choosenCredential = Credential.objectsWhere("credentialId = %d", credId) view.viewController = self self.view = view println("> CredentialViewController") } func AddCredentialCheck(sender: AnyObject) { println(selectedIcon) let realm = RLMRealm.defaultRealm() var theCategory:RLMResults if (selectedIcon != "") { theCategory = Category.objectsWhere("categoryName = %@", selectedIcon) } else { theCategory = Category.objectsWhere("categoryName = 'Apple'") } let categoryObject:Category = theCategory.firstObject() as Category let updateCredential = Credential() updateCredential.credentialId = credId updateCredential.credentialTitle = inputTitle.text updateCredential.credentialEmail = inputEmail.text updateCredential.credentialPassword = inputPassword.text updateCredential.credentialNotes = inputNotes.text updateCredential.category = categoryObject realm.beginWriteTransaction() realm.addOrUpdateObject(updateCredential) realm.commitWriteTransaction() let confirmEntry = JSSAlertView().success(self, title: String(format: NSLocalizedString("CredentialModifiedTitle", comment: "Alert UI title when modyfing a credential after tapping the button Done")), text: String(format: NSLocalizedString("CredentialModifiedMessage", comment: "Alert UI message when modyfing a credential after tapping the button Done"), inputTitle.text) ) confirmEntry.addAction({ () -> Void in var afterEntryRedirect = TrousseauViewController(nibName: "TrousseauViewController", bundle: nil) self.navigationController?.popViewControllerAnimated(true) }) } func TextDidBeginEditing(sender: AnyObject) { let theTextField:FloatLabelTextField = sender.object! as FloatLabelTextField let thePlaceholder = theTextField.placeholder theTextField.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.5) theTextField.textColor = theFunctions().UIColorFromRGB("46474f") theTextField.attributedPlaceholder = NSAttributedString(string: thePlaceholder!, attributes:[NSForegroundColorAttributeName: theFunctions().UIColorFromRGB("434553", alpha: 0.8)]) theTextField.titleActiveTextColour = theFunctions().UIColorFromRGB("434553", alpha: 0.5) if (theTextField.tag == 3) { theTextField.secureTextEntry = false } } func TextDidEndEditing(sender: AnyObject) { let theTextField:FloatLabelTextField = sender.object! as FloatLabelTextField let thePlaceholder = theTextField.placeholder theTextField.backgroundColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.12) theTextField.textColor = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.8) theTextField.attributedPlaceholder = NSAttributedString(string: thePlaceholder!, attributes:[NSForegroundColorAttributeName: theFunctions().UIColorFromRGB("D1CCC0", alpha: 0.8)]) theTextField.titleActiveTextColour = theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.5) if (theTextField.tag == 3) { theTextField.secureTextEntry = true } } func textViewDidBeginEditing(textView: UITextView) { if (textView.text == NSLocalizedString("AddCredentialInputNotes", comment: "") ) { textView.text = "" } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return Int(theCategories.count) } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let cat: Category = theCategories.objectAtIndex(UInt(row)) as Category var catIcon = cat.categoryIcon keychainNewIcon.text = String.fontAwesomeIconWithName(catIcon) selectedIcon = cat.categoryName } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { let cat: Category = theCategories.objectAtIndex(UInt(row)) as Category var catName = cat.categoryName return catName } func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let cat: Category = theCategories.objectAtIndex(UInt(row)) as Category let attributedString = NSAttributedString(string: cat.categoryName, attributes: [NSForegroundColorAttributeName:theFunctions().UIColorFromRGB("FFFFFF", alpha: 0.8)]) return attributedString } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7a316ee7220446c22196633557f73420
49.72093
248
0.706786
5.021489
false
false
false
false
jmcd/AvoidMegaController
DemoApp/TodoViewController.swift
1
1195
import UIKit class TodoViewController: UIViewController { // deps var initalSourceOrNil: TodoItem? var writeAction: ((TodoViewModel) -> ())? var completion: (() -> ())? private let todoView = TodoView() private var cancelChanges = false override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) exposeNavigation() } override func viewDidLoad() { assert(writeAction != nil) view.backgroundColor = UIColor.whiteColor() view.addSubviews([todoView]) view.addConstraints( todoView.constraintsMaximizingInView(view, topLayoutGuide: topLayoutGuide, insets: UIEdgeInsets.uniform(20)) ) if let s = initalSourceOrNil { todoView.dataSource = TodoViewModel(copyingValuesFrom: s) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) todoView.becomeFirstResponder() } override func viewWillDisappear(animated: Bool) { if !cancelChanges { writeAction?(todoView.dataSource) } todoView.resignFirstResponder() super.viewWillDisappear(true) } func commit() { // todo: we could add validation here completion?() } func cancel() { cancelChanges = true completion?() } }
apache-2.0
ac4f65dd11ba1bb290fece6a3bec25bb
18.933333
111
0.714644
3.854839
false
false
false
false
minikin/Algorithmics
Pods/Charts/Charts/Classes/Components/ChartXAxis.swift
3
5841
// // ChartXAxis.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class ChartXAxis: ChartAxisBase { @objc public enum XAxisLabelPosition: Int { case Top case Bottom case BothSided case TopInside case BottomInside } public var values = [String?]() /// width of the x-axis labels in pixels - this is automatically calculated by the computeAxis() methods in the renderers public var labelWidth = CGFloat(1.0) /// height of the x-axis labels in pixels - this is automatically calculated by the computeAxis() methods in the renderers public var labelHeight = CGFloat(1.0) /// width of the (rotated) x-axis labels in pixels - this is automatically calculated by the computeAxis() methods in the renderers public var labelRotatedWidth = CGFloat(1.0) /// height of the (rotated) x-axis labels in pixels - this is automatically calculated by the computeAxis() methods in the renderers public var labelRotatedHeight = CGFloat(1.0) /// This is the angle for drawing the X axis labels (in degrees) public var labelRotationAngle = CGFloat(0.0) /// the space that should be left out (in characters) between the x-axis labels /// This only applies if the number of labels that will be skipped in between drawn axis labels is not custom set. /// /// **default**: 4 public var spaceBetweenLabels = Int(4) /// the modulus that indicates if a value at a specified index in an array(list) for the x-axis-labels is drawn or not. Draw when `(index % modulus) == 0`. public var axisLabelModulus = Int(1) /// Is axisLabelModulus a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic modulus) private var _isAxisModulusCustom = false /// the modulus that indicates if a value at a specified index in an array(list) for the y-axis-labels is drawn or not. Draw when `(index % modulus) == 0`. /// Used only for Horizontal BarChart public var yAxisLabelModulus = Int(1) /// if set to true, the chart will avoid that the first and last label entry in the chart "clip" off the edge of the chart public var avoidFirstLastClippingEnabled = false /// Custom formatter for adjusting x-value strings private var _xAxisValueFormatter: ChartXAxisValueFormatter = ChartDefaultXAxisValueFormatter() /// Custom XValueFormatter for the data object that allows custom-formatting of all x-values before rendering them. /// Provide null to reset back to the default formatting. public var valueFormatter: ChartXAxisValueFormatter? { get { return _xAxisValueFormatter } set { _xAxisValueFormatter = newValue ?? ChartDefaultXAxisValueFormatter() } } /// the position of the x-labels relative to the chart public var labelPosition = XAxisLabelPosition.Top /// if set to true, word wrapping the labels will be enabled. /// word wrapping is done using `(value width * labelRotatedWidth)` /// /// *Note: currently supports all charts except pie/radar/horizontal-bar* public var wordWrapEnabled = false /// - returns: true if word wrapping the labels is enabled public var isWordWrapEnabled: Bool { return wordWrapEnabled } /// the width for wrapping the labels, as percentage out of one value width. /// used only when isWordWrapEnabled = true. /// /// **default**: 1.0 public var wordWrapWidthPercent: CGFloat = 1.0 public override init() { super.init() self.yOffset = 4.0; } public override func getLongestLabel() -> String { var longest = "" for (var i = 0; i < values.count; i++) { let text = values[i] if (text != nil && longest.characters.count < (text!).characters.count) { longest = text! } } return longest } public var isAvoidFirstLastClippingEnabled: Bool { return avoidFirstLastClippingEnabled } /// Sets the number of labels that should be skipped on the axis before the next label is drawn. /// This will disable the feature that automatically calculates an adequate space between the axis labels and set the number of labels to be skipped to the fixed number provided by this method. /// Call `resetLabelsToSkip(...)` to re-enable automatic calculation. public func setLabelsToSkip(count: Int) { _isAxisModulusCustom = true if (count < 0) { axisLabelModulus = 1 } else { axisLabelModulus = count + 1 } } /// Calling this will disable a custom number of labels to be skipped (set by `setLabelsToSkip(...)`) while drawing the x-axis. Instead, the number of values to skip will again be calculated automatically. public func resetLabelsToSkip() { _isAxisModulusCustom = false } /// - returns: true if a custom axis-modulus has been set that determines the number of labels to skip when drawing. public var isAxisModulusCustom: Bool { return _isAxisModulusCustom } public var valuesObjc: [NSObject] { get { return ChartUtils.bridgedObjCGetStringArray(swift: values); } set { self.values = ChartUtils.bridgedObjCGetStringArray(objc: newValue); } } }
mit
fdf223eb14f365d4743d23a9d5620034
34.186747
209
0.651601
4.768163
false
false
false
false
Alex-ZHOU/XYQSwift
XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/04-Control-Flow/07-guard.playground/Contents.swift
1
1186
// // 4-7 Swift 2.0逻辑控制之guard 及代码风格初探 // 07-guard.playground // // Created by AlexZHOU on 21/05/2017. // Copyright © 2016年 AlexZHOU. All rights reserved. // import UIKit var str = "07-guard" print(str) func buy( money: Int , price: Int , capacity: Int , volume: Int){ if money >= price{ if capacity >= volume{ print("I can buy it!") print("\(money-price) Yuan left.") print("\(capacity-volume) cubic meters left") } else{ print("No enough capacity") } } else{ print("Not enough money") } } func buy2( money: Int, price: Int, capacity: Int, volume: Int){ guard money >= price else { print("Not enough money") return } guard capacity >= volume else { print("No enough capacity") return } print("I can buy it!") print("\(money-price) Yuan left.") print("\(capacity-volume) cubic meters left") } buy2(money: 100, price: 150, capacity: 100, volume: 80) buy2(money: 100, price: 50, capacity: 100, volume: 180) buy2(money: 100, price: 50, capacity: 100, volume: 80)
apache-2.0
2e1c992451153ebdb19b8555e7ddfc5f
21.72549
65
0.566005
3.588235
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/MyPow.swift
1
656
// // MyPow.swift // LeetCode // // Created by 黄伯驹 on 2021/4/27. // Copyright © 2021 伯驹 黄. All rights reserved. // import Foundation // https://leetcode-cn.com/problems/powx-n/submissions/ func myPow(_ x: Double, _ n: Int) -> Double { var result: Double = 1 var x = x var n = n if n < 0 { /// 如果小于 0 x = 1 / x n = -n } while n > 0 { if n % 2 == 1 { /// 有余数,说明是奇数 result = result * x } /// 二倍 x *= x /// 除一半 n /= 2 } return result } // 5 / 2 = 2 2/ 2 = 1 1/2 = 0
mit
3c5ffa105f11d0409d81ded1aa0c35c7
14.564103
55
0.426689
3.035
false
false
false
false
arslan2012/Lazy-Hackintosh-Image-Generator
LazyGenHelper/HelperAuthorization.swift
1
11065
// // HelperAuthorization.swift // MyApplication // // Created by Erik Berglund on 2016-12-06. // Copyright © 2016 Erik Berglund. All rights reserved. // import Foundation import ServiceManagement struct AuthorizationRightKey { static let rightName = "authRightName" static let rightDefaultRule = "authRightDefault" static let rightDescription = "authRightDescription" } class HelperAuthorization: NSObject { func commandInfo() -> Dictionary<String, Any> { // Set up the authorization rule // The defaultRights can be either a String or a custom dictionary. I'm using a custom dictionary below, if changing to a string constant, you need to change the cast in setupAuthorizationRights, see the mark. // List of defaultRights constants: https://developer.apple.com/reference/security/1669767-authorization_services_c/1670045-policy_database_constants?language=objc let ruleAdminRightsExtended: [String: Any] = ["class": "user", "group": "admin", // Timeout defines how long the authorization is valid until the user need to authorize again. // 0 means authorize every time, and to remove it like this makes it never expire until the AuthorizationRef is destroyed. // "timeout" : 0, "version": 1] // Define all authorization right definitions this application will use. // These will be added to the authorization database to then be used by the Security system to verify authorization of each command // The format of this dict is: // key == the command selector as string // value == Dictionary containing: // rightName == The name of the authorization right definition // rightDefaultRule == The rule to decide if the user is authorized for this definition // rightName == The Description is the text that will be shown to the user if prompted by the Security system let sCommandInfo: [String: Dictionary<String, Any>] = [ NSStringFromSelector(#selector(HelperProtocol.runTask(_:_:_:_:_:))): [AuthorizationRightKey.rightName: "com.github.erikberglund.MyApplication.runCommandLs", AuthorizationRightKey.rightDefaultRule: ruleAdminRightsExtended, AuthorizationRightKey.rightDescription: "MyApplication want's to run the command /bin/ls"] ] return sCommandInfo } /* Returns the rightName for the selector string passed */ func authorizationRightNameFor(command: String) -> String { let commandDict = self.commandInfo()[command] as! Dictionary<String, Any> return commandDict[AuthorizationRightKey.rightName] as! String } /* Returns an NSData object containing an empty AuthorizationRef in it's external form, to be passed to the helper */ func authorizeHelper() -> NSData? { var status: OSStatus var authData: NSData var authRef: AuthorizationRef? var authRefExtForm: AuthorizationExternalForm = AuthorizationExternalForm.init() // Create empty AuthorizationRef status = AuthorizationCreate(nil, nil, AuthorizationFlags(), &authRef) if (status != OSStatus(errAuthorizationSuccess)) { print("AuthorizationCreate failed.") return nil; } // Make an external form of the AuthorizationRef status = AuthorizationMakeExternalForm(authRef!, &authRefExtForm) if (status != OSStatus(errAuthorizationSuccess)) { print("AuthorizationMakeExternalForm failed.") return nil; } // Encapsulate the external form AuthorizationRef in an NSData object authData = NSData.init(bytes: &authRefExtForm, length: kAuthorizationExternalFormLength) // Add all or update all required authorization right definitions to the authorization databse if ((authRef) != nil) { self.setupAuthorizationRights(authRef: authRef!) } return authData; } /* Verifies that the passed AuthorizationRef contains authorization for the command to be run. If not ask the user to supply that. */ func checkAuthorization(authData: NSData?, command: String) -> Bool { var status: OSStatus var authRef: AuthorizationRef? // Verify the passed authData looks reasonable if authData?.length == 0 || authData?.length != kAuthorizationExternalFormLength { return false } /* Begin ugly workaround To convert the AuthorizationExternalForm (authData) it requires an UnsafePointer<AuthorizationExternalForm>. I haven't found a good way of going from an NSData object to that specific c array, (or tuple as it's represented in Swift). Therefore this workaround first put all bytes in an array, then convert that array into a tuple. That tuple can be used to call AuthorizationExternalForm.init(bytes: ) In Objective-C it's written like this: AuthorizationCreateFromExternalForm(authData.bytes, &authRef); */ // Create empty array of correct length var array = [Int8](repeating: 0, count: kAuthorizationExternalFormLength) // Copy all bytes into array authData?.getBytes(&array, length: kAuthorizationExternalFormLength * MemoryLayout<AuthorizationExternalForm>.size) // Create the expected tuple to initialize the AuthorizationExternalForm by assigning each byte one by one... let tuple: (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8) = (array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7], array[8], array[9], array[10], array[11], array[12], array[13], array[14], array[15], array[16], array[17], array[18], array[19], array[20], array[21], array[22], array[23], array[24], array[25], array[26], array[27], array[28], array[29], array[30], array[31]) // Create the AuthorizationExternalForm item by initializing it with the tuple var authRefExtForm: AuthorizationExternalForm = AuthorizationExternalForm.init(bytes: tuple) /* End ugly workaround */ // Extract the AuthorizationRef from it's external form status = AuthorizationCreateFromExternalForm(&authRefExtForm, &authRef) if (status == errAuthorizationSuccess) { // Get the authorization right definition name of the function calling this let authName = authorizationRightNameFor(command: command) // Create an AuthorizationItem using that definition's name var authItem = AuthorizationItem(name: (authName as NSString).utf8String!, valueLength: 0, value: UnsafeMutableRawPointer(bitPattern: 0), flags: 0) // Create the AuthorizationRights for using the AuthorizationItem var authRight: AuthorizationRights = AuthorizationRights(count: 1, items: &authItem) // MARK: Check if the user is authorized for the AuthorizationRights. If not it might ask the user for their or an admins credentials. status = AuthorizationCopyRights(authRef!, &authRight, nil, [.extendRights, .interactionAllowed], nil); if (status == errAuthorizationSuccess) { return true } } if (status != errAuthorizationSuccess) { let errorMessage = SecCopyErrorMessageString(status, nil) // This error is not really handled, shoud probably return it to let the caller know it failed. // This will not be printed in the Xcode console as this function is called from the helper. print(errorMessage ?? "AuthorizationCreateFromExternalForm Unknown Error") } return false } /* Adds or updates all authorization right definitions to the authorization database */ func setupAuthorizationRights(authRef: AuthorizationRef) -> Void { // Enumerate through all authorization right definitions and check them one by one against the authorization database self.enumerateAuthorizationRights(right: { rightName, rightDefaultRule, rightDescription in var status: OSStatus var currentRight: CFDictionary? // Try to get the authorization right definition from the database status = AuthorizationRightGet((rightName as NSString).utf8String!, &currentRight) if (status == errAuthorizationDenied) { // If not found, add or update the authorization entry in the database // MARK: Change "rightDefaultRule as! CFDictionary" to "rightDefaultRule as! CFString" if changing defaultRule to string status = AuthorizationRightSet(authRef, (rightName as NSString).utf8String!, rightDefaultRule as! CFDictionary, rightDescription as CFString, nil, "Common" as CFString) } if (status != errAuthorizationSuccess) { let errorMessage = SecCopyErrorMessageString(status, nil) // This error is not really handled, shoud probably return it to let the caller know it failed. // This will not be printed in the Xcode console as this function is called from the helper. print(errorMessage ?? "Error adding authorization right: \(rightName)") } }) } /* Convenience to enumerate all right definitions by returning each right's name, description and default */ func enumerateAuthorizationRights(right: (_ rightName: String, _ rightDefaultRule: Any, _ rightDescription: String) -> ()) { // Loop through all authorization right definitions for commandInfoDict in self.commandInfo().values { // FIXME: There is no error handling here, other than returning early if it fails. That should be added to better find possible errors. guard let commandDict = commandInfoDict as? Dictionary<String, Any> else { return } guard let rightName = commandDict[AuthorizationRightKey.rightName] as? String else { return } guard let rightDescription = commandDict[AuthorizationRightKey.rightDescription] as? String else { return } let rightDefaultRule = commandDict[AuthorizationRightKey.rightDefaultRule] as Any // Use the supplied block code to return the authorization right definition Name, Default, and Description right(rightName, rightDefaultRule, rightDescription) } } }
agpl-3.0
215046b2a572e63ea459feca2c06a665
49.063348
556
0.657809
4.999548
false
false
false
false
huonw/swift
test/IRGen/objc_property_attrs.swift
15
2244
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation @objc protocol P { } @objc protocol Q { } class Foo: NSManagedObject { // -- POD types: // nonatomic, readonly, ivar b // CHECK: private unnamed_addr constant {{.*}} c"Tq,N,R,Va\00" let a: Int = 0 // nonatomic, ivar b // CHECK: private unnamed_addr constant {{.*}} c"Tq,N,Vb\00" var b: Int = 0 // nonatomic, readonly // CHECK: private unnamed_addr constant {{.*}} c"Tq,N,R\00" var c: Int { return 0 } // nonatomic, assign // CHECK: private unnamed_addr constant {{.*}} c"Tq,N\00" var d: Int { get { return 0 } set {} } // nonatomic, dynamic // CHECK: private unnamed_addr constant {{.*}} c"Tq,N,D\00" @NSManaged var e: Int // -- Class types: // TODO: These should use the elaborated @"ClassName" encoding. // nonatomic, retain, ivar f // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSData\22,N,&,Vf\00" var f: NSData = NSData() // nonatomic, weak, assign, ivar g // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSData\22,N,W,Vg\00" weak var g: NSData? = nil // nonatomic, copy, ivar h // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSData\22,N,C,Vh\00" @NSCopying var h: NSData! = nil // nonatomic, dynamic, assign // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSData\22,N,D,&\00" @NSManaged var i: NSData // nonatomic, readonly // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSData\22,N,R\00" var j: NSData { return NSData() } // -- Bridged value types // nonatomic, copy, ivar k // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSString\22,N,C,Vk\00" var k: String = "" // nonatomic, readonly, ivar l // CHECK: private unnamed_addr constant {{.*}} c"T@\22NSString\22,N,R,Vl\00" let l: String? = nil // -- Protocol types: // CHECK: private unnamed_addr constant {{.*}} c"T@\22<_TtP19objc_property_attrs1P_>\22,N,&,Vp\00" var p: P? // CHECK: private unnamed_addr constant {{.*}} c"T@\22<_TtP19objc_property_attrs1P_><_TtP19objc_property_attrs1Q_>\22,N,&,Vpq\00" var pq: (P & Q)? }
apache-2.0
fef8a3ee794993768b56ee513f097519
33.523077
131
0.628342
3.061392
false
false
false
false
btanner/Eureka
Source/Rows/Controllers/MultipleSelectorViewController.swift
8
6590
// MultipleSelectorViewController.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit /// Selector Controller that enables multiple selection open class _MultipleSelectorViewController<Row: SelectableRowType, OptionsRow: OptionsProviderRow> : FormViewController, TypedRowControllerType where Row: BaseRow, Row.Cell.Value == OptionsRow.OptionsProviderType.Option, OptionsRow.OptionsProviderType.Option: Hashable { /// The row that pushed or presented this controller public var row: RowOf<Set<OptionsRow.OptionsProviderType.Option>>! public var selectableRowSetup: ((_ row: Row) -> Void)? public var selectableRowCellSetup: ((_ cell: Row.Cell, _ row: Row) -> Void)? public var selectableRowCellUpdate: ((_ cell: Row.Cell, _ row: Row) -> Void)? /// A closure to be called when the controller disappears. public var onDismissCallback: ((UIViewController) -> Void)? /// A closure that should return key for particular row value. /// This key is later used to break options by sections. public var sectionKeyForValue: ((Row.Cell.Value) -> (String))? /// A closure that returns header title for a section for particular key. /// By default returns the key itself. public var sectionHeaderTitleForKey: ((String) -> String?)? = { $0 } /// A closure that returns footer title for a section for particular key. public var sectionFooterTitleForKey: ((String) -> String?)? public var optionsProviderRow: OptionsRow { return row as! OptionsRow } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience public init(_ callback: ((UIViewController) -> Void)?) { self.init(nibName: nil, bundle: nil) onDismissCallback = callback } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func viewDidLoad() { super.viewDidLoad() setupForm() } open func setupForm() { optionsProviderRow.optionsProvider?.options(for: self) { [weak self] (options: [OptionsRow.OptionsProviderType.Option]?) in guard let strongSelf = self, let options = options else { return } strongSelf.optionsProviderRow.cachedOptionsData = options strongSelf.setupForm(with: options) } } open func setupForm(with options: [OptionsRow.OptionsProviderType.Option]) { if let optionsBySections = optionsBySections(with: options) { for (sectionKey, options) in optionsBySections { form +++ section(with: options, header: sectionHeaderTitleForKey?(sectionKey), footer: sectionFooterTitleForKey?(sectionKey)) } } else { form +++ section(with: options, header: row.title, footer: nil) } } open func optionsBySections(with options: [OptionsRow.OptionsProviderType.Option]) -> [(String, [Row.Cell.Value])]? { guard let sectionKeyForValue = sectionKeyForValue else { return nil } let sections = options.reduce([:]) { (reduced, option) -> [String: [Row.Cell.Value]] in var reduced = reduced let key = sectionKeyForValue(option) var items = reduced[key] ?? [] items.append(option) reduced[key] = items return reduced } return sections.sorted(by: { (lhs, rhs) in lhs.0 < rhs.0 }) } func section(with options: [OptionsRow.OptionsProviderType.Option], header: String?, footer: String?) -> SelectableSection<Row> { let section = SelectableSection<Row>(header: header ?? "", footer: footer ?? "", selectionType: .multipleSelection) { section in section.onSelectSelectableRow = { [weak self] _, selectableRow in var newValue: Set<OptionsRow.OptionsProviderType.Option> = self?.row.value ?? [] if let selectableValue = selectableRow.value { newValue.insert(selectableValue) } else { newValue.remove(selectableRow.selectableValue!) } self?.row.value = newValue } } for option in options { section <<< Row.init { lrow in lrow.title = String(describing: option) lrow.selectableValue = option lrow.value = self.row.value?.contains(option) ?? false ? option : nil self.selectableRowSetup?(lrow) }.cellSetup { [weak self] cell, row in self?.selectableRowCellSetup?(cell, row) }.cellUpdate { [weak self] cell, row in self?.selectableRowCellUpdate?(cell, row) } } return section } } open class MultipleSelectorViewController<OptionsRow: OptionsProviderRow>: _MultipleSelectorViewController<ListCheckRow<OptionsRow.OptionsProviderType.Option>, OptionsRow> where OptionsRow.OptionsProviderType.Option: Hashable{ override public init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
c3176c640ef0efd669621d86f6963f8a
43.228188
270
0.66085
4.903274
false
false
false
false
sahandnayebaziz/Play
Play/HomeCodeView.swift
1
2129
// // HomeCodeView.swift // Play // // Created by Sahand Nayebaziz on 12/12/15. // Copyright © 2015 Sahand Nayebaziz. All rights reserved. // import UIKit class HomeCodeView: UIView, PlayCodeTransportDelegate { private var results = HomeCodeResultsView() private var entry = HomeCodeEntryView() var delegates: [PlayCodeTransportDelegate] = [] init() { super.init(frame: CGRectZero) addSubview(results) results.snp_makeConstraints { make in make.top.equalTo(snp_top) make.height.equalTo(200) make.width.equalTo(snp_width).offset(-50) make.left.equalTo(snp_left) } results.delegate = self delegates.append(results) addSubview(entry) entry.snp_makeConstraints { make in make.bottom.equalTo(snp_bottom) make.width.equalTo(snp_width).offset(-50) make.left.equalTo(snp_left) make.top.equalTo(results.snp_bottom).offset(40) } entry.delegate = self let fontConfiguration = HomeCodeEntryFontConfigurationView(delegate: entry) addSubview(fontConfiguration) fontConfiguration.snp_makeConstraints { make in make.bottom.equalTo(snp_bottom) make.height.equalTo(100) make.right.equalTo(snp_right) make.width.equalTo(50) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func receiveCodeTransportPacket(header: PlayCodeTransportType, code: String) { switch header { case .PreProcess: PlaySocket.go.sendCode(self, code: code) case .PostProcess: for delegate in delegates { delegate.receiveCodeTransportPacket(PlayCodeTransportType.PostProcess, code: code) } } } override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand(input: "r", modifierFlags: .Command, action: "run", discoverabilityTitle: "Run") ] } }
mit
4d2e49903785ea7b6fb658da87cec08e
28.971831
105
0.607613
4.360656
false
true
false
false
brentdax/swift
benchmark/single-source/Array2D.swift
4
1200
//===--- Array2D.swift ----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let Array2D = BenchmarkInfo( name: "Array2D", runFunction: run_Array2D, tags: [.validation, .api, .Array], setUpFunction: { blackHole(inputArray) }, tearDownFunction: { inputArray = nil }) var inputArray: [[Int]]! = { var A: [[Int]] = [] A.reserveCapacity(1024) for _ in 0 ..< 1024 { A.append(Array(0 ..< 1024)) } return A }() @inline(never) func modifyArray(_ A: inout [[Int]], _ N: Int) { for _ in 0..<N { for i in 0 ..< 1024 { for y in 0 ..< 1024 { A[i][y] = A[i][y] + 1 A[i][y] = A[i][y] - 1 } } } } @inline(never) public func run_Array2D(_ N: Int) { modifyArray(&inputArray, N) }
apache-2.0
31a338f4ab2630e007c35b37c0179689
25.086957
80
0.545
3.625378
false
false
false
false
bhajian/raspi-remote
Carthage/Checkouts/ios-sdk/Source/DocumentConversionV1/Models/AnswerUnits.swift
1
1689
/** * Copyright IBM Corporation 2016 * * 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 Freddy /** **Answer Units** Answer Units are a format that can be used with other Watson services, such as the Watson Retrieve and Rank Service */ public struct AnswerUnits: JSONDecodable { /** an Id for the unit */ public let id: String? /** type of the unit */ public let type: String? /** Id of the parent, should the unit have one */ public let parentId: String? /** title of the current unit */ public let title: String? /** the direction the current unit is read (left to right, etc) */ public let direction: String? /** see **Content** */ public let content: [Content]? /** used internally to initialize AnswerUnits objects */ public init(json: JSON) throws { id = try? json.string("id") type = try? json.string("type") parentId = try? json.string("parent_id") title = try? json.string("title") direction = try? json.string("direction") content = try? json.arrayOf("content", type: Content.self) } }
mit
e6169f700513104ed23f798e9f11b736
28.12069
83
0.655417
4.319693
false
false
false
false
brentdax/swift
test/Interpreter/protocol_initializers.swift
16
15000
// RUN: %empty-directory(%t) // RUN: %target-build-swift -swift-version 5 %s -o %t/a.out // RUN: %target-codesign %t/a.out // // RUN: %target-run %t/a.out // REQUIRES: executable_test import StdlibUnittest var ProtocolInitTestSuite = TestSuite("ProtocolInit") func mustThrow<T>(_ f: () throws -> T) { do { _ = try f() preconditionFailure("Didn't throw") } catch {} } func mustFail<T>(f: () -> T?) { if f() != nil { preconditionFailure("Didn't fail") } } enum E : Error { case X } protocol TriviallyConstructible { init(x: LifetimeTracked) init(x: LifetimeTracked, throwsDuring: Bool) throws init?(x: LifetimeTracked, failsDuring: Bool) } extension TriviallyConstructible { init(x: LifetimeTracked, throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) } init(x: LifetimeTracked, throwsAfter: Bool) throws { self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) } init(x: LifetimeTracked, throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init?(x: LifetimeTracked, failsBefore: Bool) { if failsBefore { return nil } self.init(x: x) } init?(x: LifetimeTracked, failsAfter: Bool) { self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) } init?(x: LifetimeTracked, failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsDuring: Bool, failsAfter: Bool) { self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } } class TrivialClass : TriviallyConstructible { let tracker: LifetimeTracked // Protocol requirements required init(x: LifetimeTracked) { self.tracker = x } required convenience init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } required convenience init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } // Class initializers delegating to protocol initializers convenience init(throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) } convenience init(throwsAfter: Bool) throws { self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) } convenience init(throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init?(failsBefore: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) } convenience init?(failsAfter: Bool) { self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) } convenience init?(failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsDuring: Bool, failsAfter: Bool) { self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } } ProtocolInitTestSuite.test("ExtensionInit_Success") { _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false)! _ = TrivialClass(x: LifetimeTracked(0), failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false)! _ = TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ClassInit_Success") { _ = try! TrivialClass(throwsBefore: false) _ = try! TrivialClass(throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(failsBefore: false)! _ = TrivialClass(failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false)! _ = TrivialClass(failsDuring: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ExtensionInit_Failure") { mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: true) } } ProtocolInitTestSuite.test("ClassInit_Failure") { mustThrow { try TrivialClass(throwsBefore: true) } mustThrow { try TrivialClass(throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(failsBefore: true) } mustFail { TrivialClass(failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true) } mustFail { TrivialClass(failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsDuring: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: false, failsAfter: true) } } struct TrivialStruct : TriviallyConstructible { let x: LifetimeTracked init(x: LifetimeTracked) { self.x = x } init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } } struct AddrOnlyStruct : TriviallyConstructible { let x: LifetimeTracked let y: Any init(x: LifetimeTracked) { self.x = x self.y = "Hello world" } init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } } extension TriviallyConstructible { init(throwsFirst: Bool, throwsSecond: Bool, initThenInit: ()) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsFirst) try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond) } init(throwsFirst: Bool, throwsSecond: Bool, initThenAssign: ()) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsFirst) self = try Self(x: LifetimeTracked(0), throwsDuring: throwsSecond) } init(throwsFirst: Bool, throwsSecond: Bool, assignThenInit: ()) throws { self = try Self(x: LifetimeTracked(0), throwsDuring: throwsFirst) try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond) } init(throwsFirst: Bool, throwsSecond: Bool, assignThenAssign: ()) throws { self = try Self(x: LifetimeTracked(0), throwsDuring: throwsFirst) try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond) } } ProtocolInitTestSuite.test("Struct_Success") { _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, initThenInit: ()) _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, initThenAssign: ()) _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, assignThenInit: ()) _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, assignThenAssign: ()) } ProtocolInitTestSuite.test("Struct_Failure") { mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, initThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, initThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, initThenAssign: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, initThenAssign: ()) } mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, assignThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, assignThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, assignThenAssign: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, assignThenAssign: ()) } } ProtocolInitTestSuite.test("AddrOnlyStruct_Success") { _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, initThenInit: ()) _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, initThenAssign: ()) _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, assignThenInit: ()) _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, assignThenAssign: ()) } ProtocolInitTestSuite.test("AddrOnlyStruct_Failure") { mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, initThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, initThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, initThenAssign: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, initThenAssign: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, assignThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, assignThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, assignThenAssign: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, assignThenAssign: ()) } } runAllTests()
apache-2.0
d65fce915f2584e82da7c93f36d85582
33.168565
116
0.701667
4.137931
false
false
false
false
tomizimobile/AsyncDisplayKit
examples_extra/ASLayoutSpecPlayground-Swift/Sample/Sample.playground/Sources/PhotoWithInsetTextOverlay.swift
15
1175
import AsyncDisplayKit public class PhotoWithInsetTextOverlay: ASDisplayNode, ASPlayground { public let photoNode = ASNetworkImageNode() public let titleNode = ASTextNode() override public init() { super.init() backgroundColor = .white automaticallyManagesSubnodes = true setupNodes() } private func setupNodes() { photoNode.url = URL(string: "http://asyncdisplaykit.org/static/images/layout-examples-photo-with-inset-text-overlay-photo.png") photoNode.backgroundColor = .black titleNode.backgroundColor = .blue titleNode.maximumNumberOfLines = 2 titleNode.truncationAttributedText = NSAttributedString.attributedString(string: "...", fontSize: 16, color: .white, firstWordColor: nil) titleNode.attributedText = NSAttributedString.attributedString(string: "family fall hikes", fontSize: 16, color: .white, firstWordColor: nil) } // This is used to expose this function for overriding in extensions override public func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASLayoutSpec() } public func show() { display(inRect: CGRect(x: 0, y: 0, width: 120, height: 120)) } }
bsd-3-clause
44c247c25c2881f3404b40dccf13a4b1
34.606061
145
0.741277
4.571984
false
false
false
false
borglab/SwiftFusion
Tests/SwiftFusionTests/Inference/SwitchingMCMCTests.swift
1
6811
// // SwitchingMCMCTests.swift // // // Frank Dellaert and Marc Rasi // July 2020 import _Differentiation import Foundation import TensorFlow import XCTest import PenguinStructures @testable import SwiftFusion /// A between factor on `Pose2`. public typealias SwitchingBetweenFactor2 = SwitchingBetweenFactor<Pose2> /// A between factor on `Pose3`. public typealias SwitchingBetweenFactor3 = SwitchingBetweenFactor<Pose3> class Scratch: XCTestCase { let origin = Pose2(0,0,0) let forwardMove = Pose2(1,0,0) let (z1, z2, z3) = (Pose2(10, 0, 0),Pose2(11, 0, 0),Pose2(12, 0, 0)) var expectedTrackingError : Double = 0.0 // Calculate error by hand in test fixture override func setUp() { super.setUp() expectedTrackingError = 0.5*(2 * origin.localCoordinate(z1).squaredNorm + origin.localCoordinate(z2).squaredNorm + origin.localCoordinate(z3).squaredNorm + 2 * origin.localCoordinate(forwardMove).squaredNorm) } /// Create an example tracking graph func createTrackingFactorGraph() -> (FactorGraph, VariableAssignments) { // First get 3 pose variables var variables = VariableAssignments() let x1 = variables.store(origin) let x2 = variables.store(origin) let x3 = variables.store(origin) // Use ids x1,x2,x3 to create factors var graph = FactorGraph() graph.store(PriorFactor(x1, z1)) // prior graph.store(PriorFactor(x1, z1)) graph.store(PriorFactor(x2, z2)) graph.store(PriorFactor(x3, z3)) graph.store(BetweenFactor(x1, x2, forwardMove)) graph.store(BetweenFactor(x2, x3, forwardMove)) return (graph, variables) } /// Just a helper for debugging func printPoses(_ variables : VariableAssignments) { print(variables[TypedID<Pose2>(0)]) print(variables[TypedID<Pose2>(1)]) print(variables[TypedID<Pose2>(2)]) } /// Tracking example from Figure 2.a in Annual Reviews paper func testTrackingExample() { // create a factor graph var (graph, variables) = createTrackingFactorGraph() _ = graph as FactorGraph // // check number of factor types XCTAssertEqual(graph.storage.count, 2) // check error at initial estimate XCTAssertEqual(graph.error(at: variables), expectedTrackingError) // optimize var opt = LM() try! opt.optimize(graph: graph, initial: &variables) // print printPoses(variables) } /// Switching system example from Figure 2.b in that same paper func createSwitchingFactorGraph() -> (FactorGraph, VariableAssignments) { var variables = VariableAssignments() let x1 = variables.store(origin) let x2 = variables.store(origin) let x3 = variables.store(origin) // We now have discrete labels, as well let q1 = variables.store(0) let q2 = variables.store(0) // Model parameters include a 3x3 transition matrix and 3 motion models. let labelCount = 3 let transitionMatrix: [Double] = [ 0.8, 0.1, 0.1, 0.1, 0.8, 0.1, 0.1, 0.1, 0.8 ] let movements = [ forwardMove, // go forwards Pose2(1, 0, .pi / 4), // turn left Pose2(1, 0, -.pi / 4) // turn right ] // Create the graph itself var graph = FactorGraph() graph.store(PriorFactor(x1, z1)) // prior graph.store(PriorFactor(x1, z1)) graph.store(PriorFactor(x2, z2)) graph.store(PriorFactor(x3, z3)) graph.store(SwitchingBetweenFactor2(x1, q1, x2, movements)) graph.store(SwitchingBetweenFactor2(x2, q2, x3, movements)) graph.store(DiscreteTransitionFactor(q1, q2, labelCount, transitionMatrix)) return (graph, variables) } /// Just a helper for debugging func printLabels(_ variables : VariableAssignments) { print(variables[TypedID<Int>(0)]) print(variables[TypedID<Int>(1)]) } /// Returns the gradient of the error function of `graph` at `x`. func errorGradient(_ graph: FactorGraph, _ x: VariableAssignments) -> AllVectors { let l = graph.linearized(at: x) return l.errorVectors_linearComponent_adjoint(l.errorVectors(at: x.tangentVectorZeros)) } func printGradient(_ grad: AllVectors) { for i in 0..<3 { print(" \(grad[TypedID<Vector3>(i)])") } } /// Tracking switching from Figure 2.b func testSwitchingExample() { // create a factor graph var (graph, variables) = createSwitchingFactorGraph() _ = graph as FactorGraph _ = variables as VariableAssignments // check number of factor types XCTAssertEqual(graph.storage.count, 3) // check error at initial estimate, allow slack to account for discrete transition XCTAssertEqual(graph.error(at: variables), 234, accuracy:0.3) // optimize var opt = LM() try! opt.optimize(graph: graph, initial: &variables) // print // printLabels(variables) // printPoses(variables) // Create initial state for MCMC sampler let current_state = variables // Do MCMC the tfp way let num_results = 50 let num_burnin_steps = 30 /// Proposal to change one label, and re-optimize let flipAndOptimize = {(x:VariableAssignments, r: inout AnyRandomNumberGenerator) -> VariableAssignments in let labelVars = x.storage[ObjectIdentifier(Int.self)] // let positionVars = x.storage[ObjectIdentifier(Pose2.self)] // Randomly change one label. let i = Int.random(in: 0..<labelVars!.count, using: &r) let id = TypedID<Int>(i) var y = x y[id] = Int.random(in: 0..<3) // Pose2SLAM to find new proposed positions. // print("Pose2SLAM starting at:") // self.printLabels(y) // self.printPoses(y) do { try opt.optimize(graph: graph, initial: &y) } catch { // TODO: Investigate why the optimizer fails to make progress when it's near the solution. // print("ignoring optimizer error") } // Check that we found a local minimum by asserting that the gradient is 0. The optimizer // isn't good at getting precisely to the minimum, so the assertion has a pretty big // `accuracy` argument. let grad = self.errorGradient(graph, y) XCTAssertEqual(grad.squaredNorm, 0, accuracy: 0.1) // print("Pose2SLAM solution:") // self.printLabels(y) // self.printPoses(y) // print("Gradient of error function at solution:") // self.printGradient(grad) return y } let kernel = RandomWalkMetropolis( target_log_prob_fn: {(x:VariableAssignments) in 0.0}, new_state_fn: flipAndOptimize ) let states = sampleChain( num_results, current_state, kernel, num_burnin_steps ) _ = states as Array XCTAssertEqual(states.count, num_results) } }
apache-2.0
8d3f0682653ee244787982f9f4741d5c
30.243119
111
0.656585
3.771318
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/CommentService+Likes.swift
1
5613
extension CommentService { /** Fetches a list of users from remote that liked the comment with the given IDs. @param commentID The ID of the comment to fetch likes for @param siteID The ID of the site that contains the post @param count Number of records to retrieve. Optional. Defaults to the endpoint max of 90. @param before Filter results to likes before this date/time. Optional. @param excludingIDs An array of user IDs to exclude from the returned results. Optional. @param purgeExisting Indicates if existing Likes for the given post and site should be purged before new ones are created. Defaults to true. @param success A success block returning: - Array of LikeUser - Total number of likes for the given comment - Number of likes per fetch @param failure A failure block */ func getLikesFor(commentID: NSNumber, siteID: NSNumber, count: Int = 90, before: String? = nil, excludingIDs: [NSNumber]? = nil, purgeExisting: Bool = true, success: @escaping (([LikeUser], Int, Int) -> Void), failure: @escaping ((Error?) -> Void)) { guard let remote = restRemote(forSite: siteID) else { DDLogError("Unable to create a REST remote for comments.") failure(nil) return } remote.getLikesForCommentID(commentID, count: NSNumber(value: count), before: before, excludeUserIDs: excludingIDs, success: { remoteLikeUsers, totalLikes in self.createNewUsers(from: remoteLikeUsers, commentID: commentID, siteID: siteID, purgeExisting: purgeExisting) { let users = self.likeUsersFor(commentID: commentID, siteID: siteID) success(users, totalLikes.intValue, count) LikeUserHelper.purgeStaleLikes() } }, failure: { error in DDLogError(String(describing: error)) failure(error) }) } /** Fetches a list of users from Core Data that liked the comment with the given IDs. @param commentID The ID of the comment to fetch likes for. @param siteID The ID of the site that contains the post. @param after Filter results to likes after this Date. Optional. */ func likeUsersFor(commentID: NSNumber, siteID: NSNumber, after: Date? = nil) -> [LikeUser] { let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = { if let after = after { // The date comparison is 'less than' because Likes are in descending order. return NSPredicate(format: "likedSiteID = %@ AND likedCommentID = %@ AND dateLiked < %@", siteID, commentID, after as CVarArg) } return NSPredicate(format: "likedSiteID = %@ AND likedCommentID = %@", siteID, commentID) }() request.sortDescriptors = [NSSortDescriptor(key: "dateLiked", ascending: false)] if let users = try? managedObjectContext.fetch(request) { return users } return [LikeUser]() } } private extension CommentService { func createNewUsers(from remoteLikeUsers: [RemoteLikeUser]?, commentID: NSNumber, siteID: NSNumber, purgeExisting: Bool, onComplete: @escaping (() -> Void)) { guard let remoteLikeUsers = remoteLikeUsers, !remoteLikeUsers.isEmpty else { onComplete() return } let derivedContext = ContextManager.shared.newDerivedContext() derivedContext.perform { let likers = remoteLikeUsers.map { remoteUser in LikeUserHelper.createOrUpdateFrom(remoteUser: remoteUser, context: derivedContext) } if purgeExisting { self.deleteExistingUsersFor(commentID: commentID, siteID: siteID, from: derivedContext, likesToKeep: likers) } ContextManager.shared.save(derivedContext) { DispatchQueue.main.async { onComplete() } } } } func deleteExistingUsersFor(commentID: NSNumber, siteID: NSNumber, from context: NSManagedObjectContext, likesToKeep: [LikeUser]) { let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = NSPredicate(format: "likedSiteID = %@ AND likedCommentID = %@ AND NOT (self IN %@)", siteID, commentID, likesToKeep) do { let users = try context.fetch(request) users.forEach { context.delete($0) } } catch { DDLogError("Error fetching comment Like Users: \(error)") } } }
gpl-2.0
c783e78a18df698c451a00c623ab25a9
42.511628
144
0.528594
5.971277
false
false
false
false
jonasman/TeslaSwift
TeslaSwiftDemo/VehicleViewController.swift
1
6310
// // VehicleViewController.swift // TeslaSwift // // Created by Joao Nunes on 22/10/2016. // Copyright © 2016 Joao Nunes. All rights reserved. // import UIKit import CoreLocation class VehicleViewController: UIViewController { @IBOutlet weak var textView: UITextView! var vehicle: Vehicle? @IBAction func getVehicle(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let vehicle2 = try await api.getVehicle(vehicle) self.textView.text = "Inside temp: \(vehicle2.jsonString!)" } } @IBAction func getTemps(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let climateState = try await api.getVehicleClimateState(vehicle) self.textView.text = "Inside temp: \(String(describing: climateState.insideTemperature?.celsius))\n" + climateState.jsonString! } } @IBAction func getChargeState(_ sender: AnyObject) { guard let vehicle = vehicle else { return } Task { @MainActor in let chargeState = try await api.getVehicleChargeState(vehicle) self.textView.text = "Battery: \(chargeState.batteryLevel!) % (\(chargeState.idealBatteryRange!.kms) km)\n" + "charge rate: \(chargeState.chargeRate!.kilometersPerHour) km/h\n" + "energy added: \(chargeState.chargeEnergyAdded!) kWh\n" + "distance added (ideal): \(chargeState.chargeDistanceAddedIdeal!.kms) km\n" + "power: \(chargeState.chargerPower ?? 0) kW\n" + "\(chargeState.chargerVoltage ?? 0)V \(chargeState.chargerActualCurrent ?? 0)A\n" + "charger max current: \(String(describing: chargeState.chargerPilotCurrent))\n\(chargeState.jsonString!)" } } @IBAction func getVehicleState(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let vehicleState = try await api.getVehicleState(vehicle) self.textView.text = "FW: \(String(describing: vehicleState.firmwareVersion))\n" + vehicleState.jsonString! } } @IBAction func getDriveState(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let driveState = try await api.getVehicleDriveState(vehicle) self.textView.text = "Location: \(String(describing: driveState.position))\n" + driveState.jsonString! } } @IBAction func getGUISettings(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let guiSettings = try await api.getVehicleGuiSettings(vehicle) self.textView.text = "Charge rate units: \(String(describing: guiSettings.chargeRateUnits))\n" + guiSettings.jsonString! } } @IBAction func gettAll(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let extendedVehicle = try await api.getAllData(vehicle) self.textView.text = "All data:\n" + extendedVehicle.jsonString! } } @IBAction func getConfig(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let config = try await api.getVehicleConfig(vehicle) self.textView.text = "All data:\n" + config.jsonString! } } @IBAction func command(_ sender: AnyObject) { guard let vehicle = vehicle else { return } Task { @MainActor in let response = try await api.sendCommandToVehicle(vehicle, command: .setMaxDefrost(on: false)) self.textView.text = (response.result! ? "true" : "false") if let reason = response.reason { self.textView.text.append(reason) } } } @IBAction func wakeup(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let response = try await api.wakeUp(vehicle) self.textView.text = response.state } } @IBAction func speedLimit(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let response = try await api.sendCommandToVehicle(vehicle, command: .speedLimitClearPin(pin: "1234")) self.textView.text = (response.result! ? "true" : "false") if let reason = response.reason { self.textView.text.append(reason) } } } @IBAction func getNearbyChargingSites(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let nearbyChargingSites = try await api.getNearbyChargingSites(vehicle) self.textView.text = "NearbyChargingSites:\n" + nearbyChargingSites.jsonString! } } @IBAction func refreshToken(_ sender: Any) { Task { @MainActor in do { let token = try await api.refreshWebToken() self.textView.text = "New access Token:\n \(token)" } catch { self.textView.text = "Refresh Token:\n CATCH" } } } @IBAction func ampsTo16(_ sender: Any) { guard let vehicle = vehicle else { return } Task { @MainActor in let response = try await api.sendCommandToVehicle(vehicle, command: .setCharging(amps: 16)) self.textView.text = (response.result! ? "true" : "false") if let reason = response.reason { self.textView.text.append(reason) } } } @IBAction func revokeToken(_ sender: Any) { Task { @MainActor in do { let status = try await api.revokeWeb() self.textView.text = "Revoked: \(status)" } catch { self.textView.text = "Revoke Token:\n CATCH" } } } @IBAction func logout(_ sender: Any) { api.logout() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == "toStream" { let vc = segue.destination as! StreamViewController vc.vehicle = self.vehicle } } }
mit
29798d59560b5700eb70d3284dd931d7
34.24581
121
0.596767
4.22572
false
false
false
false
manfengjun/KYMart
AppDelegate/SingleManager.swift
1
1317
// // SingleManager.swift // HNLYSJB // // Created by jun on 2017/5/22. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import YYCache class SingleManager: NSObject { /// 单例 static let instance = SingleManager() /// 验证码 var verify_code:String? /// 登录token var access_token:String? /// 购买对象 var productBuyInfoModel:KYProductBuyInfoModel? /// 登录对象 var loginInfo:KYLoginInfoModel? /// 用户信息对象 var userInfo:KYUserInfoModel? /// 跳转分类显示的默认 var selectId:Int = 0 /// 是否登录 var isLogin:Bool = false /// 获取UUID /// /// - Returns: return value description class func getUUID() -> String { var retriveuuid = SSKeychain.password(forService: "kymart.key", account: "uuid") if let text = retriveuuid { retriveuuid = text } else { let uuidRef = CFUUIDCreate(kCFAllocatorDefault) let strRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef) retriveuuid = (strRef! as String).replacingOccurrences(of: "-", with: "") SSKeychain.setPassword(retriveuuid, forService: "kymart.key", account: "uuid") } return retriveuuid! } }
mit
7eb04aa91d37a47a980576f8d0eb216c
24.346939
90
0.60467
4.045603
false
false
false
false
cylim/CSCI342-Asgn1-Memory-Game-ios
Memory Game/TileView.swift
1
2150
// // TileView.swift // Memory Game // // Created by CY Lim on 29/03/2016. // Copyright © 2016 CY Lim. All rights reserved. // import UIKit class TileView: UIView { // Part 3a var image: UIImage? = nil var imageView: UIImageView = UIImageView() var delegate: UIViewController? = nil var tileIndex: Int? = nil required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Part 3b //Important: We need this to stop the system from auto generating constraints, otherwise we'll get autolayout errors: imageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imageView) //Position and size the innerView with these autolayout constraints: let width = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0) let height = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0) let top = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Top , relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) let left = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) //Add the constraints: self.addConstraints([width, height, top, left]) } // Part 3c func revealImage(){ userInteractionEnabled = false imageView.alpha = 0 imageView.image = image UIImageView.animateWithDuration(0.5, animations: { self.imageView.alpha = 1 }) } func coverImage(){ userInteractionEnabled = true imageView.alpha = 0 imageView.image = UIImage(named: "question") UIImageView.animateWithDuration(0.5, animations: { self.imageView.alpha = 1 }) } func hideTileView(){ imageView.hidden = true } } // Part 3d protocol TileViewDelegate{ func didSelectTile(tileView: TileView) }
mit
44b3eb2a4404565c8b41bb9f02269160
28.040541
201
0.739879
4.085551
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Utils/ChartColorTemplates.swift
7
7604
// // ChartColorTemplates.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ChartColorTemplates: NSObject { public class func liberty () -> [NSUIColor] { return [ NSUIColor(red: 207/255.0, green: 248/255.0, blue: 246/255.0, alpha: 1.0), NSUIColor(red: 148/255.0, green: 212/255.0, blue: 212/255.0, alpha: 1.0), NSUIColor(red: 136/255.0, green: 180/255.0, blue: 187/255.0, alpha: 1.0), NSUIColor(red: 118/255.0, green: 174/255.0, blue: 175/255.0, alpha: 1.0), NSUIColor(red: 42/255.0, green: 109/255.0, blue: 130/255.0, alpha: 1.0) ] } public class func joyful () -> [NSUIColor] { return [ NSUIColor(red: 217/255.0, green: 80/255.0, blue: 138/255.0, alpha: 1.0), NSUIColor(red: 254/255.0, green: 149/255.0, blue: 7/255.0, alpha: 1.0), NSUIColor(red: 254/255.0, green: 247/255.0, blue: 120/255.0, alpha: 1.0), NSUIColor(red: 106/255.0, green: 167/255.0, blue: 134/255.0, alpha: 1.0), NSUIColor(red: 53/255.0, green: 194/255.0, blue: 209/255.0, alpha: 1.0) ] } public class func pastel () -> [NSUIColor] { return [ NSUIColor(red: 64/255.0, green: 89/255.0, blue: 128/255.0, alpha: 1.0), NSUIColor(red: 149/255.0, green: 165/255.0, blue: 124/255.0, alpha: 1.0), NSUIColor(red: 217/255.0, green: 184/255.0, blue: 162/255.0, alpha: 1.0), NSUIColor(red: 191/255.0, green: 134/255.0, blue: 134/255.0, alpha: 1.0), NSUIColor(red: 179/255.0, green: 48/255.0, blue: 80/255.0, alpha: 1.0) ] } public class func colorful () -> [NSUIColor] { return [ NSUIColor(red: 193/255.0, green: 37/255.0, blue: 82/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 102/255.0, blue: 0/255.0, alpha: 1.0), NSUIColor(red: 245/255.0, green: 199/255.0, blue: 0/255.0, alpha: 1.0), NSUIColor(red: 106/255.0, green: 150/255.0, blue: 31/255.0, alpha: 1.0), NSUIColor(red: 179/255.0, green: 100/255.0, blue: 53/255.0, alpha: 1.0) ] } public class func vordiplom () -> [NSUIColor] { return [ NSUIColor(red: 192/255.0, green: 255/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 247/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 208/255.0, blue: 140/255.0, alpha: 1.0), NSUIColor(red: 140/255.0, green: 234/255.0, blue: 255/255.0, alpha: 1.0), NSUIColor(red: 255/255.0, green: 140/255.0, blue: 157/255.0, alpha: 1.0) ] } public class func colorFromString(colorString: String) -> NSUIColor { let leftParenCharset: NSCharacterSet = NSCharacterSet(charactersInString: "( ") let commaCharset: NSCharacterSet = NSCharacterSet(charactersInString: ", ") let colorString = colorString.lowercaseString if colorString.hasPrefix("#") { var argb: [UInt] = [255, 0, 0, 0] let colorString = colorString.unicodeScalars var length = colorString.count var index = colorString.startIndex let endIndex = colorString.endIndex index = index.advancedBy(1) length = length - 1 if length == 3 || length == 6 || length == 8 { var i = length == 8 ? 0 : 1 while index < endIndex { var c = colorString[index] index = index.advancedBy(1) var val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30 argb[i] = UInt(val) * 16 if length == 3 { argb[i] = argb[i] + UInt(val) } else { c = colorString[index] index = index.advancedBy(1) val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30 argb[i] = argb[i] + UInt(val) } i += 1 } } return NSUIColor(red: CGFloat(argb[1]) / 255.0, green: CGFloat(argb[2]) / 255.0, blue: CGFloat(argb[3]) / 255.0, alpha: CGFloat(argb[0]) / 255.0) } else if colorString.hasPrefix("rgba") { var a: Float = 1.0 var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: NSScanner = NSScanner(string: colorString) scanner.scanString("rgba", intoString: nil) scanner.scanCharactersFromSet(leftParenCharset, intoString: nil) scanner.scanInt(&r) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&g) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&b) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanFloat(&a) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) ) } else if colorString.hasPrefix("argb") { var a: Float = 1.0 var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: NSScanner = NSScanner(string: colorString) scanner.scanString("argb", intoString: nil) scanner.scanCharactersFromSet(leftParenCharset, intoString: nil) scanner.scanFloat(&a) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&r) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&g) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&b) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) ) } else if colorString.hasPrefix("rgb") { var r: Int32 = 0 var g: Int32 = 0 var b: Int32 = 0 let scanner: NSScanner = NSScanner(string: colorString) scanner.scanString("rgb", intoString: nil) scanner.scanCharactersFromSet(leftParenCharset, intoString: nil) scanner.scanInt(&r) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&g) scanner.scanCharactersFromSet(commaCharset, intoString: nil) scanner.scanInt(&b) return NSUIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0 ) } return NSUIColor.clearColor() } }
apache-2.0
6da83c9aca49d5b3c965ba9cefee9978
37.80102
157
0.517228
3.81344
false
false
false
false
manfengjun/KYMart
Section/Mine/Controller/KYMineViewController.swift
1
14626
// // KYMineViewController.swift // KYMart // // Created by jun on 2017/6/14. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import PopupDialog import SVProgressHUD import TZImagePickerController class KYMineViewController: BaseViewController { @IBOutlet var headView: UIView! @IBOutlet weak var portraitBgV: UIView! @IBOutlet weak var portraitIV: UIImageView! @IBOutlet var tableView: UITableView! @IBOutlet weak var nameL: UILabel! @IBOutlet weak var recommendL: UILabel! @IBOutlet weak var usermoneyL: UILabel! @IBOutlet weak var bonusL: UILabel! @IBOutlet weak var userTypeL: UILabel! @IBOutlet weak var pendingLabel: UILabel! @IBOutlet weak var tgfyLabel: UILabel! @IBOutlet weak var pointLabel: UILabel! var userInfoModel:KYUserInfoModel?{ didSet { dataMenu() } } var dataDic:NSMutableDictionary?{ didSet { tableView.reloadData() if let text = userInfoModel?.nickname { nameL.text = text } if let imgUrl = userInfoModel?.head_pic { portraitIV.sd_setImage(with: URL(string: baseHref + imgUrl), placeholderImage: nil) } if let text = userInfoModel?.bonus { bonusL.text = "¥\(text)" } if let text = userInfoModel?.user_money { usermoneyL.text = "¥\(text)" } if let text = userInfoModel?.bonus1 { tgfyLabel.text = "¥\(text)" } if let text = userInfoModel?.pay_points { pointLabel.text = "\(text)" } if let text = userInfoModel?.total_sell { if let text2 = userInfoModel?.total_bonus1 { pendingLabel.text = "¥\(Float(text)! - Float(text2)!)" } } if let text = userInfoModel?.user_id { if let operatorStatus = userInfoModel?.operator_status{ if operatorStatus == 0 { recommendL.text = "会员ID:\(text)" } else { recommendL.text = "会员ID:\(text)(运营商)" } } else { recommendL.text = "会员ID:\(text)" } } if let text = userInfoModel?.level_name { userTypeL.text = text } // if let text = userInfoModel?.sell_status { // userTypeL.text = (text == 0 ? "预备会员" : "开心果") // } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.subviews[0].alpha = 0 SVProgressHUD.show() setupUI() dataRequest() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.subviews[0].alpha = 1 } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white // Do any additional setup after loading the view. } func setupUI() { portraitBgV.layer.masksToBounds = true portraitBgV.layer.cornerRadius = SCREEN_WIDTH/12 portraitIV.layer.masksToBounds = true portraitIV.layer.cornerRadius = (SCREEN_WIDTH*1/6 - 6)/2 headView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*4/5) tableView.tableHeaderView = headView navigationController?.navigationBar.isTranslucent = true tableView.backgroundColor = UIColor.hexStringColor(hex: "#F2F2F2") // setRightButtonInNav(title: SingleManager.instance.isLogin ? "退出登录" : "登录", action: #selector(isLoginAction(sender:)), size:CGSize(width: 80, height: 24)) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "M_setting_SegueID" { let vc = segue.destination as! KYUserInfoViewController vc.backResult { self.tabBarController?.tabBar.isHidden = false } } if segue.identifier == "M_bonusToMoney_SegudID" { let vc = segue.destination as! KYBonusToMoneyViewController vc.bonus = userInfoModel?.bonus } if segue.identifier == "M_tgfyToMoney_SegudID" { let vc = segue.destination as! KYTgfyToMoneyViewController vc.bonus1 = userInfoModel?.bonus1 } if segue.identifier == "M_pendToPoint_SegudID" { let vc = segue.destination as! KYPendToPointViewController vc.pay_points = userInfoModel?.pay_points } if segue.identifier == "M_recharge_SegudID" { let vc = segue.destination as! KYRechargeViewController vc.userMoney = userInfoModel?.user_money } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 业务逻辑 extension KYMineViewController:TZImagePickerControllerDelegate { /// 获取菜单列表 func dataMenu() { let filePath = Bundle.main.path(forResource: "data", ofType: "plist") let dic = NSMutableDictionary(contentsOfFile: filePath!) let jsonData = (dic?["mine"] as! String).data(using: String.Encoding.utf8) do { let resultDic = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary dataDic = resultDic } catch{ } } /// 数据请求 func dataRequest() { if SingleManager.instance.isLogin { SJBRequestModel.pull_fetchUserInfoData { (response, status) in SVProgressHUD.dismiss() if status == 1{ SingleManager.instance.userInfo = response as? KYUserInfoModel self.userInfoModel = SingleManager.instance.userInfo } } } else{ Toast(content: "未登录") } } /// 个人资料 /// /// - Parameter sender: sender description @IBAction func setUserInfoAction(_ sender: UIButton) { self.performSegue(withIdentifier: "M_setting_SegueID", sender: "") } /// 跳转到充值界面 /// /// - Parameter sender: sender description @IBAction func userMoneyAction(_ sender: UITapGestureRecognizer) { self.performSegue(withIdentifier: "M_recharge_SegudID", sender: sender) } /// 修改头像 /// /// - Parameter sender: sender description @IBAction func changePortrait(_ sender: UITapGestureRecognizer) { let imagePicker = TZImagePickerController(maxImagesCount: 1, delegate: self) imagePicker?.naviBgColor = BAR_TINTCOLOR imagePicker?.allowCrop = true imagePicker?.needCircleCrop = true imagePicker?.title = "选择图片" imagePicker?.allowPickingOriginalPhoto = true imagePicker?.cropRect = CGRect(x: SCREEN_WIDTH/2 - 100, y: SCREEN_HEIGHT/2 - 100, width: 200, height: 200) imagePicker?.didFinishPickingPhotosHandle = {(photos,assets,isSelectOriginalPhoto) -> Void in if isSelectOriginalPhoto { //原图 // 你可以通过一个asset获得原图,通过这个方法:[[TZImageManager manager] getOriginalPhotoWithAsset:completion:] if let array = assets { TZImageManager.default().getOriginalPhoto(withAsset: array[0], completion: { (image, info) in if let temImage = image{ self.uploadImage(image: temImage) } }) } } else{ //非原图 if let array = photos{ self.uploadImage(image: array[0]) } } } self.present(imagePicker!, animated: true, completion: nil) } func uploadImage(image:UIImage) { SJBRequestModel.push_fetchChangePortraitData(image: image) { (response, status) in if status == 1 { self.Toast(content: "上传成功!") self.portraitIV.image = image } } } } extension KYMineViewController:UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { if let dic = dataDic { return dic.allKeys.count + 1 } return 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let dic = dataDic { if section == dic.allKeys.count { return 1 } else { if let array = dic["\(section)"]{ return (array as! [NSDictionary]).count } } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == dataDic?.allKeys.count { let cell = tableView.dequeueReusableCell(withIdentifier: "kYMineOtherTVCell", for: indexPath) as! KYMineOtherTVCell return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "kYMineTVCell", for: indexPath) as! KYMineTVCell if let array = dataDic?["\(indexPath.section)"]{ let dic = (array as! [NSDictionary])[indexPath.row] if let text = dic["image"] { cell.cellIV.image = UIImage(named:text as! String) } if let text = dic["title"] { cell.titleL.text = text as? String } } return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == dataDic?.allKeys.count { return 20 } return 10 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor.hexStringColor(hex: "#F2F2F2") return view } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { self.performSegue(withIdentifier: "M_orderList_SegudID", sender: nil) } if indexPath.section == 1 { switch indexPath.row { case 0: let sellListVC = KYSellListViewController() sellListVC.navTitle = "我的钱包" sellListVC.bonusMoney = userInfoModel?.user_money self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(sellListVC, animated: true) self.hidesBottomBarWhenPushed = false break case 1: let bonusListVC = KYBonusListViewController() bonusListVC.navTitle = "优惠券明细" bonusListVC.userMoney = userInfoModel?.bonus self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(bonusListVC, animated: true) self.hidesBottomBarWhenPushed = false break case 2: let withdrawListVC = KYWithdrawListViewController() self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(withdrawListVC, animated: true) self.hidesBottomBarWhenPushed = false break case 3: self.performSegue(withIdentifier: "M_bonusToMoney_SegudID", sender: "") break case 4: self.performSegue(withIdentifier: "M_tgfyToMoney_SegudID", sender: "") break case 5: self.performSegue(withIdentifier: "M_pendToPoint_SegudID", sender: "") break default: break } } else if indexPath.section == 2 { if indexPath.row == 0 { let shopAddressVC = KYShopAddressViewController() navigationController?.pushViewController(shopAddressVC, animated: true) shopAddressVC.backResult({ self.tabBarController?.tabBar.isHidden = false }) } if indexPath.row == 1 { self.performSegue(withIdentifier: "M_member_SegueID", sender: "") } if indexPath.row == 2 { self.performSegue(withIdentifier: "M_shareQrCode_SegudID", sender: "") } if indexPath.row == 3 { self.performSegue(withIdentifier: "M_afterService_SegudID", sender: "") } if indexPath.row == 4 { self.performSegue(withIdentifier: "M_setting_SegueID", sender: "") } } else if indexPath.section == dataDic?.allKeys.count { self.popupDialog(content: "确认退出登录", sure: { //退出登录 SingleManager.instance.isLogin = false SingleManager.instance.loginInfo = nil self.tabBarController?.selectedIndex = 0 }, cancel: { }) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let sectionHeaderHeight:CGFloat = 10; if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0); } else if (scrollView.contentOffset.y>=sectionHeaderHeight) { scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0); } } }
mit
455e0d7f87bba11adf7266820e2d0ae5
36.025707
163
0.562661
5.018467
false
false
false
false
ddohler/swift-doodles
playgrounds/guard-defer.playground/Contents.swift
1
2374
// Guard/Defer examples, from http://nshipster.com/guard-and-defer/ import UIKit enum ConversionError : ErrorType { case InvalidFormat, OutOfBounds, Unknown } // This... //extension UInt8 { // init(fromString string: String) throws { // // check the string's format // if let _ = string.rangeOfString("^\\d+$", options: [.RegularExpressionSearch]) { // // // make sure the value is in bounds // if string.compare("\(UInt8.max)", options: [.NumericSearch]) != NSComparisonResult.OrderedAscending { // throw ConversionError.OutOfBounds // } // // // do the built-in conversion // if let value = UInt8(string) { // self.init(value) // } else { // throw ConversionError.Unknown // } // } // // throw ConversionError.InvalidFormat // } //} // To this... extension UInt8 { init(fromString string: String) throws { // check the string's format guard let _ = string.rangeOfString("^\\d+$", options: [.RegularExpressionSearch]) else { throw ConversionError.InvalidFormat } // make sure the value is in bounds guard string.compare("\(UInt8.max)", options: [.NumericSearch]) != NSComparisonResult.OrderedDescending else { throw ConversionError.OutOfBounds } // do the built-in conversion guard let value = UInt(string) else { throw ConversionError.Unknown } self.init(value) } } // DEFER func resizeImage(url: NSURL) -> UIImage? { // ... let dataSize: Int = ... let destData = UnsafeMutablePointer<UInt8>.alloc(dataSize) // Defers are called in reverse definition order // Limit use to cleanup resources defer { destData.dealloc(dataSize) } var destBuffer = vImage_Buffer(data: destData, ...) // scale the image from sourceBuffer to destBuffer var error = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, ...) guard error == kvImageNoError else { return nil } // create a CGImage from the destBuffer guard let destCGImage = vImageCreateCGImageFromBuffer(&destBuffer, &format, ...) else { return nil } // ... } // Implementation of postfix operator postfix func ++(inout x: Int) -> Int { let current = x x += 1 return current } // Doing it this way is possible, but dangerous, far less readable postfix func ++(inout x: Int) -> Int { defer { x += 1 } return x }
apache-2.0
24edb01a5d12499f21386c4c9889ab40
25.977273
109
0.646588
4.086059
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Tokens/ViewModels/TokenViewModel.swift
1
9400
// Copyright DApps Platform Inc. All rights reserved. import Foundation import BigInt import RealmSwift import TrustKeystore import TrustCore final class TokenViewModel { private let shortFormatter = EtherNumberFormatter.short private let config: Config private let store: TokensDataStore private let session: WalletSession private var tokensNetwork: NetworkProtocol private let transactionsStore: TransactionsStorage private var tokenTransactions: Results<Transaction>? private var tokenTransactionSections: [TransactionSection] = [] private var notificationToken: NotificationToken? private var transactionToken: NotificationToken? let token: TokenObject private lazy var tokenObjectViewModel: TokenObjectViewModel = { return TokenObjectViewModel(token: token) }() var title: String { return tokenObjectViewModel.title } var imageURL: URL? { return tokenObjectViewModel.imageURL } var imagePlaceholder: UIImage? { return tokenObjectViewModel.placeholder } private var symbol: String { return token.symbol } var amountFont: UIFont { return UIFont.systemFont(ofSize: 18, weight: .medium) } let titleFormmater: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MMM d yyyy" return formatter }() let backgroundColor: UIColor = { return .white }() lazy var transactionsProvider: EthereumTransactionsProvider = { return EthereumTransactionsProvider(server: server) }() var amount: String { return String( format: "%@ %@", shortFormatter.string(from: BigInt(token.value) ?? BigInt(), decimals: token.decimals), symbol ) } var numberOfSections: Int { return tokenTransactionSections.count } var server: RPCServer { return TokensDataStore.getServer(for: token) } lazy var currentAccount: Account = { return session.account.accounts.filter { $0.coin == token.coin }.first! }() init( token: TokenObject, config: Config = Config(), store: TokensDataStore, transactionsStore: TransactionsStorage, tokensNetwork: NetworkProtocol, session: WalletSession ) { self.token = token self.transactionsStore = transactionsStore self.config = config self.store = store self.tokensNetwork = tokensNetwork self.session = session prepareDataSource(for: token) } var ticker: CoinTicker? { return store.coinTicker(by: token.address) } var allTransactions: [Transaction] { return Array(tokenTransactions!) } var pendingTransactions: [Transaction] { return Array(tokenTransactions!.filter { $0.state == TransactionState.pending }) } // Market Price var marketPrice: String? { return TokensLayout.cell.marketPrice(for: ticker) } var marketPriceFont: UIFont { return UIFont.systemFont(ofSize: 14, weight: .regular) } var marketPriceTextColor: UIColor { return TokensLayout.cell.fiatAmountTextColor } var totalFiatAmount: String? { guard let value = TokensLayout.cell.totalFiatAmount(token: token) else { return .none } return " (" + value + ")" } var fiatAmountTextColor: UIColor { return TokensLayout.cell.fiatAmountTextColor } var fiatAmountFont: UIFont { return UIFont.systemFont(ofSize: 14, weight: .regular) } var amountTextColor: UIColor { return TokensLayout.cell.amountTextColor } var currencyAmountTextColor: UIColor { return TokensLayout.cell.currencyAmountTextColor } var percentChangeColor: UIColor { return TokensLayout.cell.percentChangeColor(for: ticker) } var percentChangeFont: UIFont { return UIFont.systemFont(ofSize: 12, weight: .light) } var percentChange: String? { return TokensLayout.cell.percentChange(for: ticker) } var currencyAmountFont: UIFont { return UIFont.systemFont(ofSize: 13, weight: .regular) } func fetch() { updateTokenBalance() fetchTransactions() updatePending() } func tokenObservation(with completion: @escaping (() -> Void)) { notificationToken = token.observe { change in switch change { case .change, .deleted, .error: completion() } } } func transactionObservation(with completion: @escaping (() -> Void)) { transactionToken = tokenTransactions?.observe { [weak self] _ in self?.updateSections() completion() } } func numberOfItems(for section: Int) -> Int { return tokenTransactionSections[section].items.count } func item(for row: Int, section: Int) -> Transaction { return tokenTransactionSections[section].items[row] } func convert(from title: String) -> Date? { return titleFormmater.date(from: title) } func titleForHeader(in section: Int) -> String { let stringDate = tokenTransactionSections[section].title guard let date = convert(from: stringDate) else { return stringDate } if NSCalendar.current.isDateInToday(date) { return R.string.localizable.today() } if NSCalendar.current.isDateInYesterday(date) { return R.string.localizable.yesterday() } return stringDate } func cellViewModel(for indexPath: IndexPath) -> TransactionCellViewModel { return TransactionCellViewModel( transaction: tokenTransactionSections[indexPath.section].items[indexPath.row], config: config, chainState: ChainState(server: server), currentAccount: currentAccount, server: token.coin.server, token: token ) } func hasContent() -> Bool { return !tokenTransactionSections.isEmpty } private func updateTokenBalance() { guard let provider = TokenViewModel.balance(for: token, wallet: session.account) else { return } let _ = provider.balance().done { [weak self] balance in self?.store.update(balance: balance, for: provider.addressUpdate) } } static func balance(for token: TokenObject, wallet: WalletInfo) -> BalanceNetworkProvider? { let first = wallet.accounts.filter { $0.coin == token.coin }.first guard let account = first else { return .none } let networkBalance: BalanceNetworkProvider? = { switch token.type { case .coin: return CoinNetworkProvider( server: token.coin.server, address: EthereumAddress(string: account.address.description)!, addressUpdate: token.address ) case .ERC20: return TokenNetworkProvider( server: token.coin.server, address: EthereumAddress(string: account.address.description)!, contract: token.address, addressUpdate: token.address ) } }() return networkBalance } func updatePending() { let transactions = pendingTransactions for transaction in transactions { transactionsProvider.update(for: transaction) { result in switch result { case .success(let transaction, let state): self.transactionsStore.update(state: state, for: transaction) case .failure: break } } } } private func fetchTransactions() { let contract: String? = { switch token.type { case .coin: return .none case .ERC20: return token.contract } }() tokensNetwork.transactions(for: currentAccount.address, on: server, startBlock: 1, page: 0, contract: contract) { result in guard let transactions = result.0 else { return } self.transactionsStore.add(transactions) } } private func prepareDataSource(for token: TokenObject) { switch token.type { case .coin: tokenTransactions = transactionsStore.realm.objects(Transaction.self) .filter(NSPredicate(format: "rawCoin = %d", server.coin.rawValue)) .sorted(byKeyPath: "date", ascending: false) case .ERC20: tokenTransactions = transactionsStore.realm.objects(Transaction.self) .filter(NSPredicate(format: "rawCoin = %d && %K ==[cd] %@", server.coin.rawValue, "to", token.contract)) .sorted(byKeyPath: "date", ascending: false) } updateSections() } private func updateSections() { guard let tokens = tokenTransactions else { return } tokenTransactionSections = transactionsStore.mappedSections(for: Array(tokens)) } func invalidateObservers() { notificationToken?.invalidate() notificationToken = nil transactionToken?.invalidate() transactionToken = nil } }
gpl-3.0
9f52c04b1f4bbc1502d5ce6bbc337cc8
29.420712
131
0.62117
4.968288
false
false
false
false
JohnSansoucie/MyProject2
BlueCap/Peripheral/PeripheralManagerBeaconsViewController.swift
1
5194
// // PeripheralManagerBeaconsViewController.swift // BlueCap // // Created by Troy Stribling on 9/28/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit import BlueCapKit class PeripheralManagerBeaconsViewController: UITableViewController { struct MainStoryboard { static let peripheralManagerBeaconCell = "PeripheralManagerBeaconCell" static let peripheralManagerEditBeaconSegue = "PeripheralManagerEditBeacon" static let peripheralManagerAddBeaconSegue = "PeripheralManagerAddBeacon" } var peripheral : String? var peripheralManagerViewController : PeripheralManagerViewController? override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() self.navigationItem.title = "Beacons" NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject?) { if segue.identifier == MainStoryboard.peripheralManagerAddBeaconSegue { } else if segue.identifier == MainStoryboard.peripheralManagerEditBeaconSegue { if let selectedIndexPath = self.tableView.indexPathForCell(sender as UITableViewCell) { let viewController = segue.destinationViewController as PeripheralManagerBeaconViewController let beaconNames = PeripheralStore.getBeaconNames() viewController.beaconName = beaconNames[selectedIndexPath.row] if let peripheralManagerViewController = self.peripheralManagerViewController { viewController.peripheralManagerViewController = peripheralManagerViewController } } } } func didResignActive() { Logger.debug("PeripheralManagerBeaconsViewController#didResignActive") if let peripheralManagerViewController = self.peripheralManagerViewController { self.navigationController?.popToViewController(peripheralManagerViewController, animated:false) } } func didBecomeActive() { Logger.debug("PeripheralManagerBeaconsViewController#didBecomeActive") } override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int { return PeripheralStore.getBeaconNames().count } override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralManagerBeaconCell, forIndexPath: indexPath) as PeripheralManagerBeaconCell let name = PeripheralStore.getBeaconNames()[indexPath.row] cell.nameLabel.text = name if let uuid = PeripheralStore.getBeacon(name) { let beaconConfig = PeripheralStore.getBeaconConfig(name) cell.uuidLabel.text = uuid.UUIDString cell.majorLabel.text = "\(beaconConfig[1])" cell.minorLabel.text = "\(beaconConfig[0])" cell.accessoryType = .None if let peripheral = self.peripheral { if let advertisedBeacon = PeripheralStore.getAdvertisedBeacon(peripheral) { if advertisedBeacon == name { cell.accessoryType = .Checkmark } } } } return cell } override func tableView(tableView:UITableView, canEditRowAtIndexPath indexPath:NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { if let peripheral = self.peripheral { let beaconNames = PeripheralStore.getBeaconNames() PeripheralStore.setAdvertisedBeacon(peripheral, beacon:beaconNames[indexPath.row]) self.navigationController?.popViewControllerAnimated(true) } } override func tableView(tableView:UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath) { if editingStyle == .Delete { let beaconNames = PeripheralStore.getBeaconNames() PeripheralStore.removeBeacon(beaconNames[indexPath.row]) if let peripheral = self.peripheral { PeripheralStore.removeAdvertisedBeacon(peripheral) PeripheralStore.removeBeaconEnabled(peripheral) } tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Fade) } } }
mit
d6a88113592385f420fef3b9e2272695
42.283333
162
0.696188
6.168646
false
false
false
false
morgz/SwiftGoal
SwiftGoal/Action.swift
2
4285
import Foundation import RxSwift import RxCocoa /// Typealias for compatibility with UIButton's rx_action property. public typealias CocoaAction = Action<Void, Void> /// Possible errors from invoking execute() public enum ActionError: ErrorType { case NotEnabled case UnderlyingError(ErrorType) } /// TODO: Add some documentation. public final class Action<Input, Element> { public typealias WorkFactory = Input -> Observable<Element> public let _enabledIf: Observable<Bool> public let workFactory: WorkFactory /// Errors aggrevated from invocations of execute(). /// Delivered on whatever scheduler they were sent from. public var errors: Observable<ActionError> { return self._errors.asObservable() } private let _errors = PublishSubject<ActionError>() /// Whether or not we're currently executing. /// Delivered on whatever scheduler they were sent from. public var elements: Observable<Element> { return self._elements.asObservable() } private let _elements = PublishSubject<Element>() /// Whether or not we're currently executing. /// Always observed on MainScheduler. public var executing: Observable<Bool> { return self._executing.asObservable().observeOn(MainScheduler.instance) } private let _executing = Variable(false) /// Whether or not we're enabled. Note that this is a *computed* sequence /// property based on enabledIf initializer and if we're currently executing. /// Always observed on MainScheduler. public var enabled: Observable<Bool> { return _enabled.asObservable().observeOn(MainScheduler.instance) } public private(set) var _enabled = BehaviorSubject(value: true) private let executingQueue = dispatch_queue_create("com.ashfurrow.Action.executingQueue", DISPATCH_QUEUE_SERIAL) private let disposeBag = DisposeBag() public init<B: BooleanType>(enabledIf: Observable<B>, workFactory: WorkFactory) { self._enabledIf = enabledIf.map { booleanType in return booleanType.boolValue } self.workFactory = workFactory Observable.combineLatest(self._enabledIf, self.executing) { (enabled, executing) -> Bool in return enabled && !executing }.bindTo(_enabled).addDisposableTo(disposeBag) } } // MARK: Convenience initializers. public extension Action { /// Always enabled. public convenience init(workFactory: WorkFactory) { self.init(enabledIf: .just(true), workFactory: workFactory) } } // MARK: Execution! public extension Action { public func execute(input: Input) -> Observable<Element> { // Buffer from the work to a replay subject. let buffer = ReplaySubject<Element>.createUnbounded() // See if we're already executing. var startedExecuting = false self.doLocked { if self._enabled.valueOrFalse { self._executing.value = true startedExecuting = true } } // Make sure we started executing and we're accidentally disabled. guard startedExecuting else { let error = ActionError.NotEnabled self._errors.onNext(error) buffer.onError(error) return buffer } let work = self.workFactory(input) defer { // Subscribe to the work. work.multicast(buffer).connect() } buffer.subscribe(onNext: { element in self._elements.onNext(element) }, onError: { error in self._errors.onNext(ActionError.UnderlyingError(error)) }, onCompleted: nil, onDisposed: { self.doLocked { self._executing.value = false } }) .addDisposableTo(disposeBag) return buffer.asObservable() } } private extension Action { private func doLocked(closure: () -> Void) { dispatch_sync(executingQueue, closure) } } internal extension BehaviorSubject where Element: BooleanLiteralConvertible { var valueOrFalse: Element { guard let value = try? value() else { return false } return value } }
mit
20f0ad0ad00fd741993f24440a452962
30.740741
116
0.646908
4.970998
false
false
false
false
wuzhenli/MyDailyTestDemo
swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/typealias.xcplaygroundpage/Contents.swift
2
643
import UIKit typealias Location = CGPoint typealias Distance = Double func distance(from location: Location, to anotherLocation: Location) -> Distance { let dx = Distance(location.x - anotherLocation.x) let dy = Distance(location.y - anotherLocation.y) return sqrt(dx * dx + dy * dy) } let origin: Location = Location(x: 0, y: 0) let point: Location = Location(x: 1, y: 1) let d = distance(from: origin, to: point) class Person<T> {} typealias WorkId = String typealias Worker = Person<WorkId> //class Person<T> {} typealias WorkerGeneric<T> = Person<T> let w1 = Worker() let w2 = WorkerGeneric<WorkId>()
apache-2.0
958e78ed608d68a2735553550fa693c2
21.172414
57
0.684292
3.348958
false
false
false
false
kingwangboss/OneJWeiBo
OneJWeiBo/OneJWeiBo/Classes/Compost(发布)/CompostTitleView.swift
1
1503
// // CompostTitleView.swift // OneJWeiBo // // Created by One'J on 16/4/11. // Copyright © 2016年 One'J. All rights reserved. // import UIKit import SnapKit class CompostTitleView: UIView { // MARK:- 懒加载 private lazy var titleView : UILabel = UILabel() private lazy var screenNameLabel : UILabel = UILabel() // MARK:- 构造函数 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI extension CompostTitleView { private func setupUI() { //将子控件添加到View中 addSubview(titleView) addSubview(screenNameLabel) //设置frame titleView.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self) } screenNameLabel.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(titleView.snp_centerX) make.top.equalTo(titleView.snp_bottom).offset(3) } //设置控件属性 titleView.font = UIFont.systemFontOfSize(16) screenNameLabel.font = UIFont.systemFontOfSize(14) screenNameLabel.textColor = UIColor.lightGrayColor() //设置文字内容 titleView.text = "发微博" screenNameLabel.text = UserAccountViewModel.shareIntance.account?.screen_name } }
apache-2.0
eb03e10bbe882019b22b602070327d15
22.866667
85
0.613827
4.365854
false
false
false
false
renatorodrigues/chat-window-ios
Sources/ChatView.swift
1
20243
// // ChatView.swift // Example-Swift // // Created by Łukasz Jerciński on 06/03/2017. // Copyright © 2017 LiveChat Inc. All rights reserved. // import Foundation import WebKit @objc protocol ChatViewDelegate : NSObjectProtocol { func closedChatView() func handle(URL: URL) } let iOSMessageHandlerName = "iosMobileWidget" class ChatView : UIView, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, UIScrollViewDelegate, LoadingViewDelegate { private var webView = WKWebView() private let loadingView = LoadingView() weak var delegate : ChatViewDelegate? private let jsonCache = JSONRequestCache() private var keyboardFrame = CGRect.zero private var animating = false private let keyboardAnimationDelayed = true var configuration : LiveChatConfiguration? { didSet { if let oldValue = oldValue, let configuration = configuration { if oldValue != configuration { reloadWithDelay() } } } } var customVariables : Dictionary<String, String>? { didSet { reloadWithDelay() } } var webViewBridge : WebViewBridge? { didSet { if let webViewBridge = webViewBridge { webViewBridge.webView = webView } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override init(frame: CGRect) { super.init(frame: frame) let configuration = WKWebViewConfiguration() let contentController = WKUserContentController() contentController.add(self, name:iOSMessageHandlerName) configuration.userContentController = contentController let podBundle = Bundle(for: ChatView.self) var scriptContent : String? do { if let path = podBundle.path(forResource: "LiveChatWidget", ofType: "js") { scriptContent = try String(contentsOfFile: path, encoding: String.Encoding.utf8) } } catch { print("Exception while injecting LiveChatWidget.js script") } let script = WKUserScript(source: scriptContent!, injectionTime: .atDocumentStart, forMainFrameOnly: true) contentController.addUserScript(script) let frame = webViewFrame(forKeyboardFrame: keyboardFrame, topInset: topInset()) webView = WKWebView(frame: frame, configuration: configuration) webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] HideInputAccessoryHelper().removeInputAccessoryView(from: webView) webView.navigationDelegate = self webView.uiDelegate = self webView.scrollView.isScrollEnabled = false webView.scrollView.delegate = self webView.scrollView.minimumZoomScale = 1.0 webView.scrollView.maximumZoomScale = 1.0 webView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0) webView.frame = webViewFrame(forKeyboardFrame: keyboardFrame, topInset: topInset()) addSubview(webView) webView.alpha = 0 backgroundColor = UIColor.clear loadingView.autoresizingMask = [.flexibleWidth, .flexibleHeight] loadingView.delegate = self loadingView.frame = bounds loadingView.startAnimation() addSubview(loadingView) let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(keyboardWillChangeFrameNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil) nc.addObserver(self, selector: #selector(keyboardWillChangeFrameNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil) nc.addObserver(self, selector: #selector(keyboardDidChangeFrameNotification), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil) nc.addObserver(self, selector: #selector(applicationDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive , object: nil) nc.addObserver(self, selector: #selector(applicationWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) } deinit { webView.scrollView.delegate = nil webView.stopLoading() webView.configuration.userContentController.removeScriptMessageHandler(forName:(iOSMessageHandlerName)) } override func layoutSubviews() { super.layoutSubviews() webView.frame = webViewFrame(forKeyboardFrame: keyboardFrame, topInset: topInset()) loadingView.frame = webView.frame } // MARK: Public Methods func presentChat(animated: Bool, completion: ((Bool) -> Void)? = nil) { if !LiveChatState.isChatOpenedBefore() { delayed_reload() } LiveChatState.markChatAsOpened() let animations = { self.webView.frame = CGRect(x: 0, y: self.topInset(), width: self.bounds.size.width, height: self.bounds.size.height - self.topInset()) self.loadingView.frame = self.webView.frame self.webView.alpha = 1 } let completion = { (finished : Bool) in self.animating = false if finished { self.webViewBridge?.postFocusEvent() } if let completion = completion { completion(finished) } } if animated { animating = true webView.frame = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height - topInset()) loadingView.frame = webView.frame UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: animations, completion: completion) } else { animations() completion(true) } } func dismissChat(animated: Bool, completion: ((Bool) -> Void)? = nil) { if animating { return } webView.endEditing(true) let animations = { self.webView.frame = CGRect(x: 0, y: self.bounds.size.height, width: self.bounds.size.width, height: self.bounds.size.height - self.topInset()) self.loadingView.frame = self.webView.frame self.webView.alpha = 0 } let completion = { (finished : Bool) in self.animating = false if finished { self.webViewBridge?.postBlurEvent() self.chatHidden() } if let completion = completion { completion(finished) } } if animated { animating = true UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: animations, completion: completion) } else { animations() completion(true) } } private func chatHidden() { delegate?.closedChatView() } // MARK: Animation private func shouldAnimateKeyboard() -> Bool { if webView.alpha > 0 { return true } else { return false } } // MARK: Application state management func applicationDidBecomeActiveNotification(_ notification: Notification) { if self.webView.alpha > 0 { self.webViewBridge?.postFocusEvent() } } func applicationWillResignActiveNotification(_ notification: Notification) { if self.webView.alpha > 0 { self.webViewBridge?.postBlurEvent() } } // MARK: Keyboard frame changes func keyboardWillChangeFrameNotification(_ notification: Notification) { let notification = KeyboardNotification(notification) let keyboardScreenEndFrame = notification.screenFrameEnd keyboardFrame = keyboardScreenEndFrame if keyboardAnimationDelayed { NSObject.cancelPreviousPerformRequests(withTarget: self) perform(#selector(delayedWillKeyboardFrameChange), with: notification, afterDelay: 0) } else { delayedWillKeyboardFrameChange(notification) } } func keyboardDidChangeFrameNotification(_ notification: Notification) { let notification = KeyboardNotification(notification) keyboardFrame = notification.screenFrameEnd if keyboardAnimationDelayed { NSObject.cancelPreviousPerformRequests(withTarget: self) perform(#selector(delayedDidKeyboardFrameChange), with: notification, afterDelay: 0) } else { delayedDidKeyboardFrameChange(notification) } } @objc func delayedWillKeyboardFrameChange(_ notification: KeyboardNotification) { if keyboardFrame.equalTo(notification.screenFrameEnd) { webView.scrollView.isScrollEnabled = !shouldAnimateKeyboard() if shouldAnimateKeyboard() { animateKeyboard(frameBegin: notification.screenFrameBegin, frameEnd: notification.screenFrameEnd, duration: notification.animationDuration, animationCurve: notification.animationCurve) } else { webView.frame = webViewFrame(forKeyboardFrame: keyboardFrame, topInset: topInset()) } } } @objc func delayedDidKeyboardFrameChange(_ notification: KeyboardNotification) { if keyboardFrame.equalTo(notification.screenFrameEnd) { webView.scrollView.isScrollEnabled = false if keyboardFrame.origin.y >= self.bounds.size.height { keyboardFrame = CGRect.zero } webView.frame = webViewFrame(forKeyboardFrame:keyboardFrame, topInset: topInset()) webView.layer.transform = CATransform3DIdentity } } // MARK: Private Methods private func webViewFrame(forKeyboardFrame keyboardFrame: CGRect?, topInset: CGFloat) -> CGRect { if (self.bounds.size.width == 0) { return CGRect(origin: CGPoint(x: 0, y: self.bounds.size.height), size:CGSize(width: self.bounds.size.width, height: 1)) } guard let keyboardFrame = keyboardFrame, keyboardFrame != CGRect.zero else { let frame = CGRect(x: 0, y: topInset, width: self.bounds.size.width, height: max(self.bounds.size.height - topInset, 0)) return frame } let frame = CGRect(x: 0, y: topInset, width: self.bounds.size.width, height: keyboardFrame.origin.y - topInset) return frame } private func topInset() -> CGFloat { let statusBarFrame = UIApplication.shared.statusBarFrame; guard let viewWindow = self.window else { return statusBarFrame.size.height; } let statusBarWindowRect = viewWindow.convert(statusBarFrame, from: nil); let statusBarViewRect = self.convert(statusBarWindowRect, from: nil); return statusBarViewRect.size.height; } private func animateKeyboard(frameBegin: CGRect, frameEnd: CGRect, duration: TimeInterval, animationCurve: Int) { let beginViewFrame = webViewFrame(forKeyboardFrame: frameBegin, topInset: topInset()) let endViewFrame = webViewFrame(forKeyboardFrame: frameEnd, topInset: topInset()) webView.layer.transform = CATransform3DIdentity webView.layer.removeAllAnimations() UIGraphicsBeginImageContextWithOptions(webView.bounds.size, false, 0) webView.drawHierarchy(in: webView.bounds, afterScreenUpdates: false) let beginImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext(); webView.frame = endViewFrame webView.scrollView.layer.removeAllAnimations() //prevents animation glitch let beginMaskImageView = UIImageView() beginMaskImageView.frame = beginViewFrame beginMaskImageView.image = beginImage self.addSubview(beginMaskImageView) beginMaskImageView.layer.removeAllAnimations() let yScale = beginViewFrame.size.height / endViewFrame.size.height let scaleTransform = CATransform3DMakeScale(1.0, yScale, 1.0) webView.layer.transform = scaleTransform webView.layer.removeAllAnimations() UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve)), animations: { beginMaskImageView.frame = endViewFrame beginMaskImageView.alpha = 0 self.webView.layer.transform = CATransform3DIdentity }) { (finished) in beginMaskImageView.removeFromSuperview() } } private func displayLoadingError(withMessage message: String) { DispatchQueue.main.async(execute: { [weak self] in if let `self` = self { self.loadingView.displayLoadingError(withMessage: message) } }) } @objc func delayed_reload() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(delayed_reload), object: nil) if jsonCache.currentTask == nil || jsonCache.currentTask?.state != .running { loadingView.alpha = 1.0 loadingView.startAnimation() jsonCache.request(withCompletionHandler: { [weak self] (templateURL, error) in if let `self` = self { if let error = error { self.displayLoadingError(withMessage: error.localizedDescription) return } guard let templateURL = templateURL else { self.displayLoadingError(withMessage: "Template URL not provided.") return } guard let configuration = self.configuration else { self.displayLoadingError(withMessage: "Configuration not provided.") return } let url = buildUrl(templateURL: templateURL, configuration: configuration, customVariables: self.customVariables, maxLength: 2000) if let url = url { let request = URLRequest(url: url) if #available(iOS 9.0, *) { // Changing UserAgent string: self.webView.evaluateJavaScript("navigator.userAgent") {[weak self] (result, error) in if let `self` = self, let userAgent = result as? String { self.webView.customUserAgent = userAgent + " WebView_Widget_iOS/2.0.0" if LiveChatState.isChatOpenedBefore() { self.webView.load(request) } } } } else { if LiveChatState.isChatOpenedBefore() { self.webView.load(request) } } } else { print("error: Invalid url") self.displayLoadingError(withMessage: "Invalid url") } } }) } } // MARK: LoadingViewDelegate func reloadWithDelay() { self.perform(#selector(delayed_reload), with: nil, afterDelay: 0.2) } func reload() { self.loadingView.alpha = 1.0 self.loadingView.startAnimation() self.webView.reload() } func close() { dismissChat(animated: true) { (finished) in if finished { if let delegate = self.delegate { delegate.closedChatView() } } } } // MARK: UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { if shouldAnimateKeyboard() { scrollView.contentOffset = CGPoint.zero; } } public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return nil // No zooming } // MARK: WKNavigationDelegate func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("Did fail navigation error: " + error.localizedDescription) } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { if let URL = navigationAction.request.url , UIApplication.shared.canOpenURL(URL) { if let delegate = self.delegate { delegate.handle(URL: URL) } else { if #available(iOS 10, *) { UIApplication.shared.open(URL, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(URL) } } decisionHandler(.cancel) } else { decisionHandler(.allow) } } else { decisionHandler(.allow) } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { let error = error as NSError loadingView.alpha = 1.0 if error.domain == NSURLErrorDomain && error.code == -999 { loadingView.displayLoadingError(withMessage: error.localizedDescription) } else { loadingView.displayLoadingError(withMessage: error.localizedDescription) } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if self.webView.alpha == 0 { self.webViewBridge?.postBlurEvent() } UIView.animate(withDuration: 0.3, delay: 0.4, options: UIViewAnimationOptions(), animations: { self.loadingView.alpha = 0 }, completion: { (finished) in }) } // MARK: WKUIDelegate func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if (navigationAction.targetFrame == nil) { let popup = WKWebView(frame: webView.frame, configuration: configuration) popup.uiDelegate = self self.addSubview(popup) return popup } return nil; } func webViewDidClose(_ webView: WKWebView) { webView.removeFromSuperview() } // MARK: WKScriptMessageHandler func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if (message.body is NSDictionary) { webViewBridge?.handle(message.body as! NSDictionary); } } }
mit
bbe4fb6b4ec49759234441a207944dd7
37.045113
200
0.580435
5.817764
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Profile/Columnist/View/AuthorIntroViewCell.swift
1
3133
// // AuthorIntroViewCell.swift // Floral // // Created by 孙林 on 16/5/21. // Copyright © 2016年 ALin. All rights reserved. // import UIKit class AuthorIntroViewCell: UserParentViewCell { override var author : Author? { didSet{ if let _ = author { identityLabel.text = author!.identity! authView.image = author!.authImage dingyueLabel.text = "已有\(author!.subscibeNum)人订阅" } } } override func setup() { super.setup() backgroundColor = UIColor.whiteColor() contentView.addSubview(dingyueBtn) contentView.addSubview(dingyueLabel) contentView.addSubview(identityLabel) contentView.addSubview(authView) headImgView.snp_makeConstraints { (make) in make.top.equalTo(20) make.left.equalTo(10) make.size.equalTo(CGSize(width: 51, height: 51)) } authView.snp_makeConstraints { (make) in make.bottom.right.equalTo(headImgView) make.size.equalTo(CGSize(width: 14, height: 14)) } authorLabel.snp_makeConstraints { (make) in make.top.equalTo(headImgView).offset(2) make.left.equalTo(headImgView.snp_right).offset(10) } identityLabel.snp_makeConstraints { (make) in make.top.equalTo(authorLabel).offset(2) make.left.equalTo(authorLabel.snp_right).offset(15) } desLabel.snp_makeConstraints { (make) in make.top.equalTo(authorLabel.snp_bottom).offset(10) make.left.equalTo(authorLabel) } dingyueLabel.snp_makeConstraints { (make) in make.right.equalTo(contentView).offset(-10) make.top.equalTo(desLabel).offset(3) } dingyueBtn.snp_makeConstraints { (make) in make.top.equalTo(headImgView.snp_bottom).offset(10) make.left.equalTo(headImgView) make.right.equalTo(dingyueLabel) make.height.equalTo(30) } } // MARK - 懒加载 /// 称号 private lazy var identityLabel : UILabel = { let label = UILabel() label.font = UIFont.init(name: "CODE LIGHT", size: 12.0) label.text = "资深专家"; label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.9) return label }() /// 认证 private lazy var authView : UIImageView = { let auth = UIImageView() auth.image = UIImage(named: "personAuth") return auth }() /// 订阅数 private lazy var dingyueLabel : UILabel = UILabel(textColor: UIColor.lightGrayColor(), font: UIFont.systemFontOfSize(12)) /// 定义按钮 private lazy var dingyueBtn : UIButton = { let btn = UIButton(title: "订阅", imageName: nil, target: nil, selector: nil, font: defaultFont14, titleColor: UIColor.blackColor()) btn.setBackgroundImage(UIImage(named:"loginBtn"), forState: .Normal) return btn }() }
mit
284c1a445463d9c4929db35e0b16d6b9
29.76
137
0.585826
4.213699
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/GroupCallTitleView.swift
1
17541
// // GroupCallTitleView.swift // Telegram // // Created by Mikhail Filimonov on 06.04.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit import SwiftSignalKit import TelegramCore import Postbox private final class GroupCallSpeakingView : View { private let animationView: View = View() private let textView = TextView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(animationView) addSubview(textView) textView.userInteractionEnabled = false textView.isSelectable = false let animation = CAKeyframeAnimation(keyPath: "contents") animationView.layer?.contents = GroupCallTheme.titleSpeakingAnimation.first animationView.setFrameSize(GroupCallTheme.titleSpeakingAnimation.first!.backingSize) animation.values = GroupCallTheme.titleSpeakingAnimation animation.duration = 0.7 animationView.layer?.removeAllAnimations() animation.repeatCount = .infinity animation.isRemovedOnCompletion = false animationView.layer?.add(animation, forKey: "contents") } func update(_ peers:[PeerGroupCallData], maxWidth: CGFloat, animated: Bool) { let text: String = peers.map { $0.peer.compactDisplayTitle }.joined(separator: ", ") let layout = TextViewLayout(.initialize(string: text, color: GroupCallTheme.greenStatusColor, font: .normal(.text)), maximumNumberOfLines: 1) layout.measure(width: maxWidth) textView.update(layout) self.change(size: NSMakeSize(animationView.frame.width + textView.frame.width, max(animationView.frame.height, textView.frame.height)), animated: animated) needsLayout = true } override func layout() { super.layout() animationView.centerY(x: 0, addition: -3) textView.centerY(x: animationView.frame.maxX - 2) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private final class GroupCallRecordingView : Control { private let indicator: View = View() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(indicator) indicator.isEventLess = true self.set(handler: { [weak self] control in self?.recordClick?() }, for: .Click) indicator.backgroundColor = GroupCallTheme.customTheme.redColor indicator.setFrameSize(NSMakeSize(8, 8)) indicator.layer?.cornerRadius = indicator.frame.height / 2 let animation = CABasicAnimation(keyPath: "opacity") animation.timingFunction = .init(name: .easeInEaseOut) animation.fromValue = 0.5 animation.toValue = 1.0 animation.duration = 1.0 animation.autoreverses = true animation.repeatCount = .infinity animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards indicator.layer?.add(animation, forKey: "opacity") } private var recordingStartTime: Int32 = 0 private var account: Account? private var recordClick:(()->Void)? = nil var updateParentLayout:(()->Void)? = nil func update(recordingStartTime: Int32, account: Account, recordClick: (()->Void)?) { self.account = account self.recordClick = recordClick self.recordingStartTime = recordingStartTime self.backgroundColor = .clear self.updateParentLayout?() setFrameSize(NSMakeSize(8, 8)) } override func layout() { super.layout() indicator.center() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } final class GroupCallTitleView : Control { fileprivate let titleView: TextView = TextView() fileprivate let statusView: DynamicCounterTextView = DynamicCounterTextView() private var recordingView: GroupCallRecordingView? private var speakingView: GroupCallSpeakingView? let pinWindow = ImageButton() let hidePeers = ImageButton() private let backgroundView: View = View() enum Mode { case normal case transparent } fileprivate var mode: Mode = .normal required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(backgroundView) backgroundView.addSubview(titleView) backgroundView.addSubview(statusView) backgroundView.addSubview(pinWindow) backgroundView.addSubview(hidePeers) titleView.isSelectable = false titleView.userInteractionEnabled = false statusView.userInteractionEnabled = false titleView.disableBackgroundDrawing = true pinWindow.autohighlight = false pinWindow.scaleOnClick = true set(handler: { [weak self] _ in self?.window?.performZoom(nil) }, for: .DoubleClick) } override var backgroundColor: NSColor { didSet { titleView.backgroundColor = .clear statusView.backgroundColor = .clear } } func updateMode(_ mode: Mode, animated: Bool) { self.mode = mode backgroundView.backgroundColor = mode == .transparent ? .clear : GroupCallTheme.windowBackground if animated { backgroundView.layer?.animateBackground() } } override func draw(_ layer: CALayer, in ctx: CGContext) { super.draw(layer, in: ctx) let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: colorSpace, colors: NSArray(array: [NSColor.black.withAlphaComponent(0.6).cgColor, NSColor.black.withAlphaComponent(0).cgColor]), locations: nil)! ctx.drawLinearGradient(gradient, start: CGPoint(), end: CGPoint(x: 0.0, y: layer.bounds.height), options: CGGradientDrawingOptions()) } override var mouseDownCanMoveWindow: Bool { return true } func updateLayout(size: CGSize, transition: ContainedViewLayoutTransition) { transition.updateFrame(view: backgroundView, frame: NSMakeRect(0, 0, bounds.width, 54)) transition.updateFrame(view: statusView, frame: statusView.centerFrameX(y: backgroundView.frame.midY)) if let speakingView = speakingView { transition.updateFrame(view: speakingView, frame: speakingView.centerFrameX(y: backgroundView.frame.midY)) } var add: CGFloat = 0 if !self.pinWindow.isHidden { add += self.pinWindow.frame.width + 5 } if !self.hidePeers.isHidden { add += self.hidePeers.frame.width + 5 } if let recordingView = recordingView { let layout = titleView.textLayout layout?.measure(width: backgroundView.frame.width - 125 - recordingView.frame.width - 10 - 30 - add) titleView.update(layout) let rect = backgroundView.focus(titleView.frame.size) transition.updateFrame(view: titleView, frame: CGRect(origin: NSMakePoint(max(100, rect.minX), backgroundView.frame.midY - titleView.frame.height), size: titleView.frame.size)) transition.updateFrame(view: recordingView, frame: CGRect(origin: NSMakePoint(titleView.frame.maxX + 5, titleView.frame.minY + 6), size: recordingView.frame.size)) } else { let layout = titleView.textLayout layout?.measure(width: backgroundView.frame.width - 125 - add) titleView.update(layout) let rect = backgroundView.focus(titleView.frame.size) transition.updateFrame(view: titleView, frame: CGRect(origin: NSMakePoint(max(100, rect.minX), backgroundView.frame.midY - titleView.frame.height), size: titleView.frame.size)) } transition.updateFrame(view: pinWindow, frame: pinWindow.centerFrameY(x: frame.width - pinWindow.frame.width - 20)) transition.updateFrame(view: hidePeers, frame: hidePeers.centerFrameY(x: pinWindow.frame.minX - 10 - hidePeers.frame.width)) } override func layout() { super.layout() updateLayout(size: frame.size, transition: .immediate) } private var currentState: GroupCallUIState? private var currentPeer: Peer? func update(_ peer: Peer, _ state: GroupCallUIState, _ account: Account, recordClick: @escaping()->Void, resizeClick: @escaping()->Void, hidePeersClick: @escaping()->Void, animated: Bool) { let oldMode = self.mode let mode: Mode = .normal self.updateMode(mode, animated: animated) let windowIsPinned = window?.level == NSWindow.Level.popUpMenu pinWindow.set(image: !windowIsPinned ? GroupCallTheme.pin_window : GroupCallTheme.unpin_window, for: .Normal) pinWindow.sizeToFit() let title: String = state.title let oldTitle: String? = currentState?.title let titleUpdated = title != oldTitle let recordingUpdated = state.state.recordingStartTimestamp != currentState?.state.recordingStartTimestamp let participantsUpdated = state.summaryState?.participantCount != currentState?.summaryState?.participantCount || state.state.scheduleTimestamp != currentState?.state.scheduleTimestamp let pinned = state.pinnedData.focused?.id ?? state.pinnedData.permanent let speaking = state.memberDatas.filter { member in if state.videoActive(.list).isEmpty { return false } if !state.hideParticipants && state.isFullScreen { return false } if member.isSpeaking && member.peer.id != peer.id { if pinned == nil { return member.videoEndpoint == nil && member.presentationEndpoint == nil } else { return member.videoEndpoint != pinned && member.presentationEndpoint != pinned } } else { return false } } if (!state.isFullScreen || state.tooltipSpeaker == nil) && !speaking.isEmpty { let current: GroupCallSpeakingView var presented = false if let view = self.speakingView { current = view } else { current = GroupCallSpeakingView(frame: .zero) self.speakingView = current addSubview(current) presented = true if animated { current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } current.update(speaking, maxWidth: 200, animated: animated) if presented { current.frame = current.centerFrameX(y: backgroundView.frame.midY) } } else { if let speakingView = self.speakingView { self.speakingView = nil if animated { speakingView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak speakingView] _ in speakingView?.removeFromSuperview() }) } else { speakingView.removeFromSuperview() } } } statusView.change(opacity: speakingView == nil ? 1 : 0, animated: animated) let hidePeers = state.hideParticipants let oldHidePeers = currentState?.hideParticipants == true let hidePeersButtonHide = state.mode != .video || state.activeVideoViews.isEmpty || !state.isFullScreen || state.isStream let oldHidePeersButtonHide = currentState?.mode != .video || currentState?.activeVideoViews.isEmpty == true || currentState?.isFullScreen == false || currentState?.isStream == true let updated = titleUpdated || recordingUpdated || participantsUpdated || mode != oldMode || hidePeers != oldHidePeers || oldHidePeersButtonHide != hidePeersButtonHide guard updated else { self.currentState = state self.currentPeer = peer return } self.hidePeers.isHidden = hidePeersButtonHide self.hidePeers.set(image: hidePeers ? GroupCallTheme.unhide_peers : GroupCallTheme.hide_peers, for: .Normal) self.hidePeers.sizeToFit() self.hidePeers.autohighlight = false self.hidePeers.scaleOnClick = true self.hidePeers.removeAllHandlers() self.hidePeers.set(handler: { _ in hidePeersClick() }, for: .Click) if titleUpdated { let layout = TextViewLayout(.initialize(string: title, color: GroupCallTheme.titleColor, font: .medium(.title)), maximumNumberOfLines: 1) layout.measure(width: frame.width - 125 - (recordingView != nil ? 80 : 0)) titleView.update(layout) } if recordingUpdated { if let recordingStartTimestamp = state.state.recordingStartTimestamp { let view: GroupCallRecordingView if let current = self.recordingView { view = current } else { view = GroupCallRecordingView(frame: .zero) backgroundView.addSubview(view) self.recordingView = view updateLayout(size: frame.size, transition: .immediate) if animated { recordingView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } view.update(recordingStartTime: recordingStartTimestamp, account: account, recordClick: recordClick) view.updateParentLayout = { [weak self] in self?.needsLayout = true } } else { if let recordingView = recordingView { self.recordingView = nil if animated { recordingView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false,completion: { [weak recordingView] _ in recordingView?.removeFromSuperview() }) } else { recordingView.removeFromSuperview() } } } } if participantsUpdated || oldMode != mode { let status: String let count: Int if state.state.scheduleTimestamp != nil { status = strings().voiceChatTitleScheduledSoon count = 0 } else if let summaryState = state.summaryState { if summaryState.participantCount == 0 { status = strings().voiceChatStatusStream count = summaryState.participantCount } else { if state.isStream { status = strings().voiceChatStatusViewersCountable(summaryState.participantCount) } else { status = strings().voiceChatStatusMembersCountable(summaryState.participantCount) } count = summaryState.participantCount } } else { status = strings().voiceChatStatusLoading count = 0 } let dynamicResult = DynamicCounterTextView.make(for: status, count: "\(count)", font: .normal(.text), textColor: mode == .transparent ? NSColor.white.withAlphaComponent(0.8) : GroupCallTheme.grayStatusColor, width: frame.width - 140) self.statusView.update(dynamicResult, animated: animated && oldMode == mode) self.statusView.change(size: dynamicResult.size, animated: animated) self.statusView.change(pos: NSMakePoint(floorToScreenPixels(backingScaleFactor, (frame.width - dynamicResult.size.width) / 2), frame.midY), animated: animated) } self.currentState = state self.currentPeer = peer if updated { needsLayout = true } pinWindow.removeAllHandlers() pinWindow.set(handler: { control in guard let window = control.window as? Window else { return } let windowIsPinned = control.window?.level == NSWindow.Level.popUpMenu control.window?.level = (windowIsPinned ? NSWindow.Level.normal : NSWindow.Level.popUpMenu) (control as? ImageButton)?.set(image: windowIsPinned ? GroupCallTheme.pin_window : GroupCallTheme.unpin_window, for: .Normal) showModalText(for: window, text: !windowIsPinned ? strings().voiceChatTooltipPinWindow : strings().voiceChatTooltipUnpinWindow) }, for: .Click) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
113dd7b69848c00702e8f61b1a937159
38.064588
245
0.600684
5.152761
false
false
false
false
remlostime/one
one/Pods/SwiftDate/Sources/SwiftDate/DateInRegionFormatter.swift
2
17175
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // 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 //MARK: - DateZeroBehaviour OptionSet /// Define how the formatter must work when values contain zeroes. public struct DateZeroBehaviour: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// None, it does not remove components with zero values static let none = DateZeroBehaviour(rawValue: 1) /// Units whose values are 0 are dropped starting at the beginning of the sequence until the /// first non-zero component static let dropLeading = DateZeroBehaviour(rawValue: 3) /// Units whose values are 0 are dropped from anywhere in the middle of a sequence. static let dropMiddle = DateZeroBehaviour(rawValue: 4) /// Units whose value is 0 are dropped starting at the end of the sequence back to the first /// non-zero component static let dropTrailing = DateZeroBehaviour(rawValue: 3) /// This behavior drops all units whose values are 0. For example, when days, hours, /// minutes, and seconds are allowed, the abbreviated version of one hour is displayed as “1h”. static let dropAll: DateZeroBehaviour = [.dropLeading,.dropMiddle,.dropTrailing] } //MARK: - DateInRegionFormatter /// The DateFormatter class is used to get a string representation of a time interval between two /// dates or a relative representation of a date public class DateInRegionFormatter { /// Tell what kind of time units should be part of the output. Allowed values are a subset of /// `Calendar.Component` option set. /// By default is `[.year, .month, .day, .hour, .minute, .second]` public var allowedComponents: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second] private var timeOrderedComponents: [Calendar.Component] = [.year, .month, .day, .hour, .minute, .second, .nanosecond] /// How the formatter threat zero components. Default implementation drop all zero values from /// the output string. public var zeroBehavior: DateZeroBehaviour = .dropAll /// Number of units to print from the higher to the lower. Default is unlimited, all values /// could be part of the output. By default no limit is set (`nil`). public var maxComponentCount: Int? /// Described the style in which each unit will be printed out. Default is `.full` public var unitStyle: DateComponentsFormatter.UnitsStyle = .full /// This describe the separator string between each component when you print data in non /// colloquial format. Default is `,`. public var unitSeparator: String = "," /// For interval less than 5 minutes if this value is true the equivalent of 'just now' is /// printed in the output string. By default is `true`. public var useImminentInterval: Bool = true // If true numbers in timeComponents() function receive a padding if necessary public var zeroPadding: Bool = true /// Locale to use when print the date. By default is the same locale set by receiver's `DateInRegion`. /// If not set default device locale is used instead. public var locale: Locale? // number of a days in a week let DAYS_IN_WEEK = 7 public init() { } /// Return the main bundle with resources used to localize time components private lazy var resourceBundle: Bundle? = { var framework = Bundle(for: DateInRegion.self) let path = NSURL(fileURLWithPath: framework.resourcePath!).appendingPathComponent("SwiftDate.bundle") let bundle = Bundle(url: path!) guard let _ = bundle else { return nil } return bundle! }() /// If you have specified a custom `Locale` this function return the localized bundle for this locale /// If no locale is specified it return the default system locale. /// /// - returns: bundle where current localization strings are available private func localizedResourceBundle() -> Bundle? { guard let locale = self.locale else { return self.resourceBundle } let localeID = locale.collatorIdentifier guard let innerLanguagePath = self.resourceBundle!.path(forResource: localeID, ofType: "lproj") else { //fallback to language only if let languageCode = locale.languageCode { //example : get french traduction even though you are live in belgium if let localOnlyPath = self.resourceBundle!.path(forResource: "\(languageCode)-\(languageCode.uppercased())" , ofType: "lproj") { return Bundle(path: localOnlyPath) } } // fallback to english if language was not found let englishPath = self.resourceBundle!.path(forResource: "en-US", ofType: "lproj")! return Bundle(path: englishPath) } return Bundle(path: innerLanguagePath) } /// String representation of an absolute interval expressed in seconds. /// For example "4 days" or "33s". /// /// - parameter interval: interval in seconds /// /// - throws: throw `.MissingRsrcBundle` if required localized string are missing from the SwiftDate bundle /// /// - returns: time components string public func timeComponents(interval: TimeInterval) throws -> String { let UTCRegion = Region(tz: TimeZoneName.gmt, cal: CalendarName.current, loc: LocaleName.current) let date = Date() let fromDate = DateInRegion(absoluteDate: date.addingTimeInterval(-interval), in: UTCRegion) let toDate = DateInRegion(absoluteDate: date, in: UTCRegion) return try self.timeComponents(from: fromDate, to: toDate) } /// String representation of the interval between two dates printed in terms of time unit components. /// For example "3 days" or "4d, 5h" etc. /// /// - parameter from: first date /// - parameter to: date to compare /// /// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar, `.MissingRsrcBundle` if /// required localized string are missing from the SwiftDate bundle /// /// - returns: time components string public func timeComponents(from: DateInRegion, to: DateInRegion) throws -> String { guard from.region.calendar == to.region.calendar else { throw DateError.DifferentCalendar } let cal = from.region.calendar let componentFlags: [Calendar.Component] = [.year, .month, .day, .hour, .minute, .second] var output: [String] = [] var nonZeroUnitFound: Int = 0 var intervalIsNegative = false let cmps = cal.dateComponents(allowedComponents, from: from.absoluteDate, to: to.absoluteDate) for component in componentFlags { let value = cmps.value(for: component) if value != nil && value != Int(NSDateComponentUndefined) && value! < 0 { intervalIsNegative = true } let isValueZero = (value != nil && value! == 0) let willDrop = (isValueZero == true && self.zeroBehavior == .dropAll) || (self.zeroBehavior == .dropLeading && nonZeroUnitFound == 0) || (self.zeroBehavior == .dropMiddle) if willDrop == false { var cmp = DateComponents() cmp.setValue(abs(value!), for: component) let localizedUnit = DateComponentsFormatter.localizedString(from: cmp, unitsStyle: unitStyle)! output.append(localizedUnit) } nonZeroUnitFound += (isValueZero == false ? 1 : 0) // limit the number of values to show if maxComponentCount != nil && nonZeroUnitFound == maxComponentCount! { break } } return (intervalIsNegative ? "-" : "") + output.joined(separator: self.unitSeparator) } /// Print a colloquial representation of the difference between two dates. /// For example "1 year ago", "just now", "3s" etc. /// /// - parameter fDate: date a /// - parameter tDate: date b /// /// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar, `.MissingRsrcBundle` if /// required localized string are missing from the SwiftDate bundle /// /// - returns: a colloquial string representing the difference between two dates public func colloquial(from fDate: DateInRegion, to tDate: DateInRegion) throws -> (colloquial: String, time: String?) { guard fDate.region.calendar == tDate.region.calendar else { throw DateError.DifferentCalendar } let cal = fDate.region.calendar let cmp = cal.dateComponents(self.allowedComponents, from: fDate.absoluteDate, to: tDate.absoluteDate) let isFuture = (fDate > tDate) if cmp.year != nil && (cmp.year != 0 || !hasLowerAllowedComponents(than: .year)) { let colloquial_time = try self.colloquial_time(forUnit: .year, withValue: cmp.year!, date: fDate) let colloquial_date = try self.localized(unit: .year, withValue: cmp.year!, asFuture: isFuture, args: abs(fDate.year)) return (colloquial_date,colloquial_time) } if cmp.month != nil && (cmp.month != 0 || !hasLowerAllowedComponents(than: .month)) { let colloquial_time = try self.colloquial_time(forUnit: .month, withValue: cmp.month!, date: fDate) let colloquial_date = try self.localized(unit: .month, withValue: cmp.month!, asFuture: isFuture, args: abs(cmp.month!)) return (colloquial_date,colloquial_time) } if cmp.day != nil { if abs(cmp.day!) >= DAYS_IN_WEEK { let colloquial_time = try self.colloquial_time(forUnit: .day, withValue: cmp.day!, date: fDate) let weeksNo = (abs(cmp.day!) / DAYS_IN_WEEK) let colloquial_date = try self.localized(unit: .weekOfYear, withValue: weeksNo, asFuture: isFuture, args: weeksNo) return (colloquial_date,colloquial_time) } if cmp.day != 0 || !hasLowerAllowedComponents(than: .day) { // case 1: > 0 days difference // case 2: same day difference and no lower time components to print (-> today) let colloquial_time = try self.colloquial_time(forUnit: .day, withValue: cmp.day!, date: fDate) let colloquial_date = try self.localized(unit: .day, withValue: cmp.day!, asFuture: isFuture, args: abs(cmp.day!)) return (colloquial_date,colloquial_time) } } if cmp.hour != nil && (cmp.hour != 0 || !hasLowerAllowedComponents(than: .hour)) { let colloquial_time = try self.colloquial_time(forUnit: .hour, withValue: cmp.hour!, date: fDate) let colloquial_date = try self.localized(unit: .hour, withValue: cmp.hour!, asFuture: isFuture, args: abs(cmp.hour!)) return (colloquial_date,colloquial_time) } if cmp.minute != nil && (cmp.minute != 0 || !hasLowerAllowedComponents(than: .minute)) { if self.useImminentInterval && abs(cmp.minute!) < 5 { let colloquial_date = try self.stringLocalized(identifier: "colloquial_now", arguments: []) return (colloquial_date,nil) } else { let colloquial_date = try self.localized(unit: .minute, withValue: cmp.minute!, asFuture: isFuture, args: abs(cmp.minute!)) return (colloquial_date,nil) } } if cmp.second != nil && (cmp.second != 0 || cmp.second == 0) { // Seconds difference let colloquial_date = try self.stringLocalized(identifier: "colloquial_now", arguments: []) return (colloquial_date,nil) } throw DateError.FailedToCalculate } /// Return `true` if time components lower than given `component` are part of the `allowedComponents` /// of the formatter. /// /// - Parameter component: target components /// - Returns: true or false private func hasLowerAllowedComponents(than component: Calendar.Component) -> Bool { guard let fIndex = timeOrderedComponents.index(of: component) else { // this should happend only if calendar component is not part of allowed components // so, in fact, this should not never happends return false } guard (timeOrderedComponents.count - 1) - fIndex > 0 else { return false // no other lower time components to check } for idx in fIndex+1..<timeOrderedComponents.count { if self.allowedComponents.contains(timeOrderedComponents[idx]) == true { return true // there is a lower component to check } } return false } /// Return a localized representation of a value for a particular calendar component /// /// - parameter unit: calendar unit to evaluate /// - parameter value: value associated /// - parameter date: reference date /// /// - throws: throw `.MissingRsrcBundle` if required localized string are missing from the SwiftDate bundle /// /// - returns: a localized representation of time interval in term of passed calendar component private func colloquial_time(forUnit unit: Calendar.Component, withValue value: Int, date: DateInRegion) throws -> String? { guard let bundle = self.localizedResourceBundle() else { throw DateError.MissingRsrcBundle } let unitStr = unit.localizedKey(forValue: value) let id_relative = "relevanttime_\(unitStr)" let relative_localized = NSLocalizedString(id_relative, tableName: "SwiftDate", bundle: bundle, value: "", comment: "") if (relative_localized as NSString).length == 0 { return nil } let relevant_time = date.string(format: .custom(relative_localized)) return relevant_time } /// Return the colloquial representation of a value for a particular calendar component /// /// - parameter unit: unit of calendar component /// - parameter value: the value associated with the unit /// - parameter asFuture: `true` if value referred to a future, `false` if it's a past event /// - parameter args: variadic arguments to append /// /// - throws: throw `.MissingRsrcBundle` if required localized string are missing from the SwiftDate bundle /// /// - returns: localized colloquial string with passed unit of time private func localized(unit: Calendar.Component, withValue value: Int, asFuture: Bool, args: CVarArg...) throws -> String { guard let bundle = self.localizedResourceBundle() else { throw DateError.MissingRsrcBundle } let future_key = (value == 0 ? "n" : (asFuture ? "f" : "p")) let unitStr = unit.localizedKey(forValue: value) let identifier = "colloquial_\(future_key)_\(unitStr)" let localized_date = withVaList(args) { (pointer: CVaListPointer) -> String in let localized = NSLocalizedString(identifier, tableName: "SwiftDate", bundle: bundle, value: "", comment: "") return NSString(format: localized, arguments: pointer) as String } return localized_date } /// Helper methods to print a localized string with variadic number of arguments /// /// - parameter identifier: identifier of the string into localized table file /// - parameter arguments: arguments to append /// /// - throws: throw `.MissingRsrcBundle` if required localized string are missing from the SwiftDate bundle /// /// - returns: localized string with arguments private func stringLocalized(identifier: String, arguments: CVarArg...) throws -> String { guard let bundle = self.localizedResourceBundle() else { throw DateError.MissingRsrcBundle } var localized_str = NSLocalizedString(identifier, tableName: "SwiftDate", bundle: bundle, comment: "") localized_str = String(format: localized_str, arguments: arguments) return localized_str } } internal extension Calendar.Component { /// Return the localized identifier of a calendar component /// /// - parameter unit: unit /// - parameter value: value /// /// - returns: return the plural or singular form of the time unit used to compose a valid identifier for search a localized /// string in resource bundle internal func localizedKey(forValue value: Int) -> String { let locKey = self.localizedKey let absValue = abs(value) switch absValue { case 0: // zero difference for this unit return "0\(locKey)" case 1: // one unit of difference return locKey default: // more than 1 unit of difference return "\(locKey)\(locKey)" } } internal var localizedKey: String { switch self { case .year: return "y" case .month: return "m" case .weekOfYear: return "w" case .day: return "d" case .hour: return "h" case .minute: return "M" case .second: return "s" default: return "" } } }
gpl-3.0
c4fbc0a254d1bde93e673015c0359e3f
40.778589
146
0.70456
3.852591
false
false
false
false
russbishop/swift
stdlib/public/SDK/Dispatch/IO.swift
1
4849
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public extension DispatchIO { public enum StreamType : UInt { case stream = 0 case random = 1 } public struct CloseFlags : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let stop = CloseFlags(rawValue: 1) } public struct IntervalFlags : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public init(nilLiteral: ()) { self.rawValue = 0 } public static let strictInterval = IntervalFlags(rawValue: 1) } public class func read(fromFileDescriptor: Int32, maxLength: Int, runningHandlerOn queue: DispatchQueue, handler: (data: DispatchData, error: Int32) -> Void) { __dispatch_read(fromFileDescriptor, maxLength, queue) { (data: __DispatchData, error: Int32) in handler(data: DispatchData(data: data), error: error) } } public class func write(fromFileDescriptor: Int32, data: DispatchData, runningHandlerOn queue: DispatchQueue, handler: (data: DispatchData?, error: Int32) -> Void) { __dispatch_write(fromFileDescriptor, data as __DispatchData, queue) { (data: __DispatchData?, error: Int32) in handler(data: data.flatMap { DispatchData(data: $0) }, error: error) } } public convenience init( type: StreamType, fileDescriptor: Int32, queue: DispatchQueue, cleanupHandler: (error: Int32) -> Void) { self.init(__type: type.rawValue, fd: fileDescriptor, queue: queue, handler: cleanupHandler) } public convenience init( type: StreamType, path: UnsafePointer<Int8>, oflag: Int32, mode: mode_t, queue: DispatchQueue, cleanupHandler: (error: Int32) -> Void) { self.init(__type: type.rawValue, path: path, oflag: oflag, mode: mode, queue: queue, handler: cleanupHandler) } public convenience init( type: StreamType, io: DispatchIO, queue: DispatchQueue, cleanupHandler: (error: Int32) -> Void) { self.init(__type: type.rawValue, io: io, queue: queue, handler: cleanupHandler) } public func read(offset: off_t, length: Int, queue: DispatchQueue, ioHandler: (done: Bool, data: DispatchData?, error: Int32) -> Void) { __dispatch_io_read(self, offset, length, queue) { (done: Bool, data: __DispatchData?, error: Int32) in ioHandler(done: done, data: data.flatMap { DispatchData(data: $0) }, error: error) } } public func write(offset: off_t, data: DispatchData, queue: DispatchQueue, ioHandler: (done: Bool, data: DispatchData?, error: Int32) -> Void) { __dispatch_io_write(self, offset, data as __DispatchData, queue) { (done: Bool, data: __DispatchData?, error: Int32) in ioHandler(done: done, data: data.flatMap { DispatchData(data: $0) }, error: error) } } public func setInterval(interval: DispatchTimeInterval, flags: IntervalFlags = []) { __dispatch_io_set_interval(self, interval.rawValue, flags.rawValue) } public func close(flags: CloseFlags = []) { __dispatch_io_close(self, flags.rawValue) } } extension DispatchIO { @available(*, deprecated, renamed: "DispatchIO.read(fromFileDescriptor:maxLength:runningHandlerOn:handler:)") public class func read(fd: Int32, length: Int, queue: DispatchQueue, handler: (DispatchData, Int32) -> Void) { DispatchIO.read(fromFileDescriptor: fd, maxLength: length, runningHandlerOn: queue, handler: handler) } @available(*, deprecated, renamed: "DispatchIO.write(fromFileDescriptor:data:runningHandlerOn:handler:)") public class func write(fd: Int32, data: DispatchData, queue: DispatchQueue, handler: (DispatchData?, Int32) -> Void) { DispatchIO.write(fromFileDescriptor: fd, data: data, runningHandlerOn: queue, handler: handler) } @available(*, deprecated, renamed: "DispatchIO.barrier(self:execute:)") public func withBarrier(barrier work: () -> ()) { barrier(execute: work) } @available(*, deprecated, renamed: "DispatchIO.setLimit(self:highWater:)") public func setHighWater(highWater: Int) { setLimit(highWater: highWater) } @available(*, deprecated, renamed: "DispatchIO.setLimit(self:lowWater:)") public func setLowWater(lowWater: Int) { setLimit(lowWater: lowWater) } @available(*, deprecated, renamed: "DispatchIO.setInterval(self:interval:flags:)") public func setInterval(interval: UInt64, flags: IntervalFlags) { setInterval(interval: .nanoseconds(Int(interval)), flags: flags) } }
apache-2.0
0c30b74be8c7a2b47d2c052defa6c73f
37.181102
166
0.699526
3.68465
false
false
false
false
antitypical/Manifold
Manifold/Term+Construction.swift
1
3909
// Copyright © 2015 Rob Rix. All rights reserved. extension Term { public static var Type: Term { return Type(0) } public static func Type(n: Int) -> Term { return Term(.Type(n)) } public static func Variable(name: Name) -> Term { return .In([ name ], .Variable(name)) } public static func Abstraction(name: Name, _ scope: Term) -> Term { return .In(scope.freeVariables.subtract([ name ]), .Abstraction(name, scope)) } public static func Application(a: Term, _ b: Term) -> Term { return Term(.Application(a, b)) } public static func Lambda(name: Name, _ type: Term, _ body: Term) -> Term { return Term(.Lambda(type, .Abstraction(name, body))) } public static func Lambda(type: Term, _ body: Term) -> Term { return Term(.Lambda(type, body)) } public static func Embedded(name: String, _ type: Term, _ evaluator: Term throws -> Term) -> Term { let equal: (Any, Any) -> Bool = { a, b in guard let a = a as? (String, Term throws -> Term), b = b as? (String, Term throws -> Term) else { return false } return a.0 == b.0 } return Term(.Embedded((name, evaluator), equal, type)) } public static func Embedded<A>(name: String, _ type: Term, _ evaluator: A throws -> Term) -> Term { return Embedded(name, type) { term in guard case let .Identity(.Embedded(value as A, _, _)) = term.out else { throw "Illegal application of '\(name)' : '\(type)' to '\(term)' (expected term of embedded type '\(A.self)')" } return try evaluator(value) } } public static func Embedded<A>(value: A, _ equal: (A, A) -> Bool, _ type: Term) -> Term { let equal: (Any, Any) -> Bool = { a, b in guard let a = a as? A, b = b as? A else { return false } return equal(a, b) } return Term(.Embedded(value as Any, equal, type)) } public static func Embedded<A: Equatable>(value: A, _ type: Term) -> Term { return .Embedded(value, ==, type) } public static func Embedded<A: Equatable>(value: A) -> Term { return .Embedded(value, .Embedded(A.self)) } public static func Embedded<A: Equatable>(type: A.Type) -> Term { return .Embedded(A.self, (==) as (A.Type, A.Type) -> Bool, .Type) } public static var Implicit: Term { return nil } public subscript (operands: Term...) -> Term { return operands.reduce(self, combine: Term.Application) } public init<T: TermContainerType>(term: T) { self.init(term.out.map { Term(term: $0) }) } } infix operator --> { associativity right precedence 120 } infix operator => { associativity right precedence 120 } public func --> (left: Term, right: Term) -> Term { return .Lambda(left, right) } public func => (type: Term, body: Term -> Term) -> Term { let proposed1 = Name.Local(0) let body1 = body(.Variable(proposed1)) let v1 = body1.freeVariables.union(body1.boundVariables) let proposed2 = proposed1.fresh(v1) if proposed1 == proposed2 { return .Lambda(type, body1) } let body2 = body(.Variable(proposed2)) let v2 = body2.freeVariables.union(body2.boundVariables) return v1.subtract([ proposed1 ]) == v2.subtract([ proposed2 ]) ? .Lambda(proposed1, type, body1) : .Lambda(proposed2, type, body2) } public func => (left: (Term, Term), right: (Term, Term) -> Term) -> Term { return left.0 => { a in left.1 => { b in right(a, b) } } } public func => (left: (Term, Term, Term), right: (Term, Term, Term) -> Term) -> Term { return left.0 => { a in left.1 => { b in left.2 => { c in right(a, b, c) } } } } public func => (left: (Term, Term, Term, Term), right: (Term, Term, Term, Term) -> Term) -> Term { return left.0 => { a in left.1 => { b in left.2 => { c in left.3 => { d in right(a, b, c, d) } } } } } public func => (left: (Name, Term), right: Term) -> Term { return .Lambda(left.0, left.1, right) } public func => (left: DictionaryLiteral<Name, Term>, right: Term) -> Term { return left.reverse().reduce(right) { into, each in each => into } } import Prelude
mit
86b87cc4c27979696e0c9ffd1bd21d21
27.948148
187
0.633572
2.987768
false
false
false
false
sarvex/SwiftRecepies
Health/Retrieving User’s Date of Birth/Retrieving User’s Date of Birth/ViewController.swift
1
2875
// // ViewController.swift // Retrieving User’s Date of Birth // // Created by vandad on 237//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import HealthKit class ViewController: UIViewController { let dateOfBirthCharacteristicType = HKCharacteristicType.characteristicTypeForIdentifier( HKCharacteristicTypeIdentifierDateOfBirth) lazy var types: Set<NSObject>! = { return Set([self.dateOfBirthCharacteristicType]) }() lazy var healthStore = HKHealthStore() func readDateOfBirthInformation(){ var dateOfBirthError: NSError? let birthDate = healthStore.dateOfBirthWithError(&dateOfBirthError) as NSDate? if let error = dateOfBirthError{ println("Could not read user's date of birth") } else { if let dateOfBirth = birthDate{ let formatter = NSNumberFormatter() let now = NSDate() let components = NSCalendar.currentCalendar().components( .YearCalendarUnit, fromDate: dateOfBirth, toDate: now, options: .WrapComponents) let age = components.year println("The user is \(age) years old") } else { println("User has not specified her date of birth yet") } } } /* Ask for permission to access the health store */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if HKHealthStore.isHealthDataAvailable(){ healthStore.requestAuthorizationToShareTypes(nil, readTypes: types, completion: {[weak self] (succeeded: Bool, error: NSError!) in let strongSelf = self! if succeeded && error == nil{ dispatch_async(dispatch_get_main_queue(), strongSelf.readDateOfBirthInformation) } else { if let theError = error{ println("Error occurred = \(theError)") } } }) } else { println("Health data is not available") } } }
isc
77ddfb5b3ccb2266ed4f97b651c4644d
28.020202
83
0.645318
4.82047
false
false
false
false
benlangmuir/swift
stdlib/public/core/StringUTF8View.swift
6
19890
//===--- StringUTF8.swift - A UTF8 view of String -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-8 code units. /// /// You can access a string's view of UTF-8 code units by using its `utf8` /// property. A string's UTF-8 view encodes the string's Unicode scalar /// values as 8-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf8 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 240 /// // 159 /// // 146 /// // 144 /// /// A string's Unicode scalar values can be up to 21 bits in length. To /// represent those scalar values using 8-bit integers, more than one UTF-8 /// code unit is often required. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf8 { /// print(v) /// } /// // 240 /// // 159 /// // 146 /// // 144 /// /// In the encoded representation of a Unicode scalar value, each UTF-8 code /// unit after the first is called a *continuation byte*. /// /// UTF8View Elements Match Encoded C Strings /// ========================================= /// /// Swift streamlines interoperation with C string APIs by letting you pass a /// `String` instance to a function as an `Int8` or `UInt8` pointer. When you /// call a C function using a `String`, Swift automatically creates a buffer /// of UTF-8 code units and passes a pointer to that buffer. The code units /// of that buffer match the code units in the string's `utf8` view. /// /// The following example uses the C `strncmp` function to compare the /// beginning of two Swift strings. The `strncmp` function takes two /// `const char*` pointers and an integer specifying the number of characters /// to compare. Because the strings are identical up to the 14th character, /// comparing only those characters results in a return value of `0`. /// /// let s1 = "They call me 'Bell'" /// let s2 = "They call me 'Stacey'" /// /// print(strncmp(s1, s2, 14)) /// // Prints "0" /// print(String(s1.utf8.prefix(14))!) /// // Prints "They call me '" /// /// Extending the compared character count to 15 includes the differing /// characters, so a nonzero result is returned. /// /// print(strncmp(s1, s2, 15)) /// // Prints "-17" /// print(String(s1.utf8.prefix(15))!) /// // Prints "They call me 'B" @frozen public struct UTF8View: Sendable { @usableFromInline internal var _guts: _StringGuts @inlinable @inline(__always) internal init(_ guts: _StringGuts) { self._guts = guts _invariantCheck() } } } extension String.UTF8View { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // TODO: Ensure index alignment } #endif // INTERNAL_CHECKS_ENABLED } extension String.UTF8View: BidirectionalCollection { public typealias Index = String.Index public typealias Element = UTF8.CodeUnit /// The position of the first code unit if the UTF-8 view is /// nonempty. /// /// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In an empty UTF-8 view, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } /// Returns the next consecutive position after `i`. /// /// - Precondition: The next position is representable. @inlinable @inline(__always) public func index(after i: Index) -> Index { let i = _guts.ensureMatchingEncoding(i) if _fastPath(_guts.isFastUTF8) { // Note: deferred bounds check return i.strippingTranscoding.nextEncoded._knownUTF8 } _precondition(i._encodedOffset < _guts.count, "String index is out of bounds") return _foreignIndex(after: i) } @inlinable @inline(__always) public func index(before i: Index) -> Index { let i = _guts.ensureMatchingEncoding(i) _precondition(!i.isZeroPosition, "String index is out of bounds") if _fastPath(_guts.isFastUTF8) { return i.strippingTranscoding.priorEncoded._knownUTF8 } _precondition(i._encodedOffset <= _guts.count, "String index is out of bounds") return _foreignIndex(before: i) } @inlinable @inline(__always) public func index(_ i: Index, offsetBy n: Int) -> Index { let i = _guts.ensureMatchingEncoding(i) if _fastPath(_guts.isFastUTF8) { let offset = n + i._encodedOffset _precondition(offset >= 0 && offset <= _guts.count, "String index is out of bounds") return Index(_encodedOffset: offset)._knownUTF8 } return _foreignIndex(i, offsetBy: n) } @inlinable @inline(__always) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { let i = _guts.ensureMatchingEncoding(i) if _fastPath(_guts.isFastUTF8) { // Check the limit: ignore limit if it precedes `i` (in the correct // direction), otherwise must not be beyond limit (in the correct // direction). let iOffset = i._encodedOffset let result = iOffset + n let limitOffset = limit._encodedOffset if n >= 0 { guard limitOffset < iOffset || result <= limitOffset else { return nil } } else { guard limitOffset > iOffset || result >= limitOffset else { return nil } } _precondition(result >= 0 && result <= _guts.count, "String index is out of bounds") return Index(_encodedOffset: result) } return _foreignIndex(i, offsetBy: n, limitedBy: limit) } @inlinable @inline(__always) public func distance(from i: Index, to j: Index) -> Int { let i = _guts.ensureMatchingEncoding(i) let j = _guts.ensureMatchingEncoding(j) if _fastPath(_guts.isFastUTF8) { return j._encodedOffset &- i._encodedOffset } _precondition( i._encodedOffset <= _guts.count && j._encodedOffset <= _guts.count, "String index is out of bounds") return _foreignDistance(from: i, to: j) } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-8 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf8.startIndex /// print("First character's UTF-8 code unit: \(greeting.utf8[i])") /// // Prints "First character's UTF-8 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` /// must be less than the view's end index. @inlinable @inline(__always) public subscript(i: Index) -> UTF8.CodeUnit { let i = _guts.ensureMatchingEncoding(i) _precondition(i._encodedOffset < _guts.count, "String index is out of bounds") return self[_unchecked: i] } @_alwaysEmitIntoClient @inline(__always) internal subscript(_unchecked i: Index) -> UTF8.CodeUnit { if _fastPath(_guts.isFastUTF8) { return _guts.withFastUTF8 { utf8 in utf8[_unchecked: i._encodedOffset] } } return _foreignSubscript(position: i) } } extension String.UTF8View: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(_guts) } } extension String.UTF8View: CustomDebugStringConvertible { public var debugDescription: String { return "UTF8View(\(self.description.debugDescription))" } } extension String { /// A UTF-8 encoding of `self`. @inlinable public var utf8: UTF8View { @inline(__always) get { return UTF8View(self._guts) } set { self = String(newValue._guts) } } /// A contiguously stored null-terminated UTF-8 representation of the string. /// /// To access the underlying memory, invoke `withUnsafeBufferPointer` on the /// array. /// /// let s = "Hello!" /// let bytes = s.utf8CString /// print(bytes) /// // Prints "[72, 101, 108, 108, 111, 33, 0]" /// /// bytes.withUnsafeBufferPointer { ptr in /// print(strlen(ptr.baseAddress!)) /// } /// // Prints "6" public var utf8CString: ContiguousArray<CChar> { @_effects(readonly) @_semantics("string.getUTF8CString") get { if _fastPath(_guts.isFastUTF8) { var result = _guts.withFastCChar { ContiguousArray($0) } result.append(0) return result } return _slowUTF8CString() } } @usableFromInline @inline(never) // slow-path internal func _slowUTF8CString() -> ContiguousArray<CChar> { var result = ContiguousArray<CChar>() result.reserveCapacity(self._guts.count + 1) for c in self.utf8 { result.append(CChar(bitPattern: c)) } result.append(0) return result } /// Creates a string corresponding to the given sequence of UTF-8 code units. @available(swift, introduced: 4.0, message: "Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode") @inlinable @inline(__always) public init(_ utf8: UTF8View) { self = String(utf8._guts) } } extension String.UTF8View { @inlinable @inline(__always) public var count: Int { if _fastPath(_guts.isFastUTF8) { return _guts.count } return _foreignCount() } } // Index conversions extension String.UTF8View.Index { /// Creates an index in the given UTF-8 view that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `utf8` view. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.firstIndex(of: 32)! /// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)! /// /// print(Array(cafe.utf8[..<utf8Index])) /// // Prints "[67, 97, 102, 195, 169]" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `utf8`, the result of the initializer is /// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code /// points differently, an attempt to convert the position of the trailing /// surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `utf8`, but the /// index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.UTF8View.Index(emojiLow, within: cafe.utf8)) /// // Prints "nil" /// /// - Parameters: /// - sourcePosition: A position in a `String` or one of its views. /// - target: The `UTF8View` in which to find the new position. public init?(_ idx: String.Index, within target: String.UTF8View) { // Note: This method used to be inlinable until Swift 5.7. // As a special exception, we allow `idx` to be an UTF-16 index when `self` // is a UTF-8 string (or vice versa), to preserve compatibility with // (broken) code that keeps using indices from a bridged string after // converting the string to a native representation. Such indices are // invalid, but returning nil here can break code that appeared to work fine // for ASCII strings in Swift releases prior to 5.7. let idx = target._guts.ensureMatchingEncoding(idx) guard idx._encodedOffset <= target._guts.count else { return nil } if _slowPath(target._guts.isForeign) { guard idx._foreignIsWithin(target) else { return nil } } else { // All indices that are in range are valid, except sub-scalar UTF-16 // indices pointing at trailing surrogates. guard idx.transcodedOffset == 0 else { return nil } } self = idx } } #if SWIFT_ENABLE_REFLECTION // Reflection extension String.UTF8View: CustomReflectable { /// Returns a mirror that reflects the UTF-8 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } #endif //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex] /// /// was deduced to be of type `String.UTF8View`. Provide a more-specific /// Swift-3-only `subscript` overload that continues to produce /// `String.UTF8View`. extension String.UTF8View { public typealias SubSequence = Substring.UTF8View @inlinable @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UTF8View.SubSequence { let r = _guts.validateSubscalarRange(r) return Substring.UTF8View(self, _bounds: r) } } extension String.UTF8View { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate /// `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` /// are initialized. @inlinable @inline(__always) public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) { guard buffer.baseAddress != nil else { _preconditionFailure( "Attempt to copy string contents into nil buffer pointer") } guard let written = _guts.copyUTF8(into: buffer) else { _preconditionFailure( "Insufficient space allocated to copy string contents") } let it = String().utf8.makeIterator() return (it, buffer.index(buffer.startIndex, offsetBy: written)) } } // Foreign string support extension String.UTF8View { // Align a foreign UTF-16 index to a valid UTF-8 position. If there is a // transcoded offset already, this is already a valid UTF-8 position // (referring to a continuation byte) and returns `idx`. Otherwise, this will // scalar-align the index. This is needed because we may be passed a // non-scalar-aligned foreign index from the UTF16View. @inline(__always) internal func _utf8AlignForeignIndex(_ idx: String.Index) -> String.Index { _internalInvariant(_guts.isForeign) guard idx.transcodedOffset == 0 else { return idx } return _guts.scalarAlign(idx) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after idx: Index) -> Index { _internalInvariant(_guts.isForeign) _internalInvariant(idx._encodedOffset < _guts.count) let idx = _utf8AlignForeignIndex(idx) let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar( startingAt: idx.strippingTranscoding) let utf8Len = UTF8.width(scalar) if utf8Len == 1 { _internalInvariant(idx.transcodedOffset == 0) return idx.nextEncoded._scalarAligned._knownUTF16 } // Check if we're still transcoding sub-scalar if idx.transcodedOffset < utf8Len - 1 { return idx.nextTranscoded._knownUTF16 } // Skip to the next scalar _internalInvariant(idx.transcodedOffset == utf8Len - 1) return idx.encoded(offsetBy: scalarLen)._scalarAligned._knownUTF16 } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before idx: Index) -> Index { _internalInvariant(_guts.isForeign) _internalInvariant(idx._encodedOffset <= _guts.count) let idx = _utf8AlignForeignIndex(idx) if idx.transcodedOffset != 0 { _internalInvariant((1...3) ~= idx.transcodedOffset) return idx.priorTranscoded._knownUTF16 } let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar( endingAt: idx.strippingTranscoding) let utf8Len = UTF8.width(scalar) return idx.encoded( offsetBy: -scalarLen ).transcoded(withOffset: utf8Len &- 1)._knownUTF16 } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignSubscript(position idx: Index) -> UTF8.CodeUnit { _internalInvariant(_guts.isForeign) let idx = _utf8AlignForeignIndex(idx) let scalar = _guts.foreignErrorCorrectedScalar( startingAt: idx.strippingTranscoding).0 let encoded = Unicode.UTF8.encode(scalar)._unsafelyUnwrappedUnchecked _internalInvariant(idx.transcodedOffset < 1+encoded.count) return encoded[ encoded.index(encoded.startIndex, offsetBy: idx.transcodedOffset)] } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index { _internalInvariant(_guts.isForeign) return _index(i, offsetBy: n) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { _internalInvariant(_guts.isForeign) return _index(i, offsetBy: n, limitedBy: limit) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignDistance(from i: Index, to j: Index) -> Int { _internalInvariant(_guts.isForeign) let i = _utf8AlignForeignIndex(i) let j = _utf8AlignForeignIndex(j) #if _runtime(_ObjC) // Currently, foreign means NSString if let count = _cocoaStringUTF8Count( _guts._object.cocoaObject, range: i._encodedOffset ..< j._encodedOffset ) { // _cocoaStringUTF8Count gave us the scalar aligned count, but we still // need to compensate for sub-scalar indexing, e.g. if `i` is in the // middle of a two-byte UTF8 scalar. let refinedCount = (count - i.transcodedOffset) + j.transcodedOffset _internalInvariant(refinedCount == _distance(from: i, to: j)) return refinedCount } #endif return _distance(from: i, to: j) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignCount() -> Int { _internalInvariant(_guts.isForeign) return _foreignDistance(from: startIndex, to: endIndex) } } extension String.Index { @usableFromInline @inline(never) // opaque slow-path @_effects(releasenone) internal func _foreignIsWithin(_ target: String.UTF8View) -> Bool { _internalInvariant(target._guts.isForeign) return self == target._utf8AlignForeignIndex(self) } } extension String.UTF8View { @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { guard _guts.isFastUTF8 else { return nil } return try _guts.withFastUTF8(body) } }
apache-2.0
1af986038dac40391383b73287a67492
32.97265
80
0.653819
4.015761
false
false
false
false
jhurray/SQLiteModel-Example-Project
tvOS+SQLiteModel/tvOS+SQLiteModel/ViewController.swift
1
1882
// // ViewController.swift // tvOS+SQLiteModel // // Created by Jeff Hurray on 4/24/16. // Copyright © 2016 jhurray. All rights reserved. // import UIKit import SQLiteModel import SQLite class ViewController: UIViewController { var nodes: [Node] = [] var n0: Node? var n1: Node? let nodeCount = 6 let label = UILabel() override func viewDidLoad() { super.viewDidLoad() label.frame = view.bounds label.font = UIFont.systemFontOfSize(48) label.textAlignment = .Center view.addSubview(label) label.text = "Loading Nodes from SQLite" createNodesWithCompletion { self.label.text = "There are \(self.nodes.count) nodes. There should be \(self.nodeCount) nodes" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func createNodesWithCompletion(completion: Void -> Void) { Node.newInBackground([Node.Name <- "my first node"]) { (node: Node?, error: SQLiteModelError?) -> Void in if let node = node { self.n0 = node self.nodes.append(node) } else { fatalError("Error: \(error)") } for index in 1..<self.nodeCount { let node = try! Node.new([Node.Name <- "node.\(index)"], relationshipSetters: [Node.Children <- self.nodes]) if index == 1 { node <| Node.Parent |> self.n0 self.n1 = node } if let lastNode = self.nodes.last { node <| Node.Parent |> lastNode } self.nodes.append(node) } completion() } } }
mit
80aecef65244ab0d7ddd33d900ba0a75
26.661765
124
0.527911
4.565534
false
false
false
false
therealglazou/quaxe-for-swift
quaxe/core/Event.swift
1
4121
/** * Quaxe for Swift * * Copyright 2016-2017 Disruptive Innovations * * Original author: * Daniel Glazman <[email protected]> * * Contributors: * */ import Foundation /** * https://dom.spec.whatwg.org/#interface-event * * status: done */ public class Event: pEvent { static let NONE: ushort = 0 static let CAPTURING_PHASE: ushort = 1 static let AT_TARGET: ushort = 1 static let BUBBLING_PHASE: ushort = 1 static let STOP_PROPAGATION_FLAG: ushort = 1 static let STOP_IMMEDIATE_PROPAGATION_FLAGS: ushort = 2 static let CANCELED_FLAG: ushort = 4 static let INITIALIZED_FLAG: ushort = 8 static let DISPATCH_FLAG: ushort = 16 static let IN_PASSIVE_LISTENER_FLAG: ushort = 32 internal var mFlags: ushort = 0 internal var flags: ushort { get { return mFlags } set { mFlags = newValue } } internal func hasFlag(_ flag: ushort) -> Bool { return 0 != (flags & flag) } internal func setFlag(_ flag: ushort) -> Void { flags = flags | flag } internal func unsetFlag(_ flag: ushort) -> Void { if hasFlag(flag) { flags = flags - flag } } internal func clearFlags() -> Void { flags = 0 } internal var mType: DOMString internal var mTarget: pEventTarget? internal var mCurrentTarget: pEventTarget? internal var mEventPhase: ushort internal var mBubbles: Bool internal var mCancelable: Bool internal var mIsTrusted: Bool internal var mTimeStamp: DOMTimeStamp /* * https://dom.spec.whatwg.org/#dom-event-type */ public var type: DOMString { return mType } /* * https://dom.spec.whatwg.org/#dom-event-target */ public var target: pEventTarget? { return mTarget } public var currentTarget: pEventTarget? { return mCurrentTarget } /* * https://dom.spec.whatwg.org/#dom-event-eventphase */ public var eventPhase: ushort { return mEventPhase } /* * https://dom.spec.whatwg.org/#dom-event-stoppropagation */ public func stopPropagation() -> Void { flags = flags | Event.STOP_PROPAGATION_FLAG } /* * https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation */ public func stopImmediatePropagation() -> Void { flags = flags | Event.STOP_PROPAGATION_FLAG | Event.STOP_IMMEDIATE_PROPAGATION_FLAGS } /* * https://dom.spec.whatwg.org/#dom-event-bubbles */ public var bubbles: Bool { return mBubbles } public var cancelable: Bool { return mCancelable } /* * https://dom.spec.whatwg.org/#dom-event-preventdefault */ public func preventDefault() -> Void { if cancelable && !hasFlag(Event.IN_PASSIVE_LISTENER_FLAG) { flags = flags | Event.CANCELED_FLAG } } /* * https://dom.spec.whatwg.org/#dom-event-defaultprevented */ public var defaultPrevented: Bool { return hasFlag(Event.CANCELED_FLAG) } /* * https://dom.spec.whatwg.org/#dom-event-istrusted */ public var isTrusted: Bool { return mIsTrusted } /* * https://dom.spec.whatwg.org/#dom-event-timestamp */ public var timeStamp: DOMTimeStamp { return mTimeStamp } /* * https://dom.spec.whatwg.org/#dom-event-initevent */ public func initEvent(_ type: DOMString, _ bubbles: Bool, _ cancelable: Bool) -> Void { if !hasFlag(Event.DISPATCH_FLAG) { mType = type mBubbles = bubbles mCancelable = cancelable } } /* * https://dom.spec.whatwg.org/#constructing-events */ public required init(_ aType: DOMString, _ aEventInitDict: Dictionary<String, Any>, _ aIsTrusted: Bool = false) { mType = aType mFlags = 0 mTarget = nil mCurrentTarget = nil mEventPhase = Event.NONE mIsTrusted = aIsTrusted mBubbles = false mCancelable = false mTimeStamp = (UInt64(NSDate().timeIntervalSince1970) * 1000) if let _bubbles = aEventInitDict["bubbles"] { mBubbles = _bubbles as! Bool } if let _cancelable = aEventInitDict["cancelable"] { mCancelable = _cancelable as! Bool } setFlag(Event.INITIALIZED_FLAG) } }
mpl-2.0
c0e4b2cb084a0c3717d99dd3faf13daa
24.918239
89
0.648629
3.558722
false
false
false
false
zSher/BulletThief
BulletThief/BulletThief/CrossPathBulletEffect.swift
1
1109
// // CrossPathBulletEffect.swift // BulletThief // // Created by Zachary on 5/17/15. // Copyright (c) 2015 Zachary. All rights reserved. // import UIKit import SpriteKit /// This bullet effect... /// /// * angles bullet paths so they shoot in a cross class CrossPathBulletEffect: NSObject, NSCoding, BulletEffectProtocol { var leftRotation = CGAffineTransformMakeRotation(degreesToRad(15)) var rightRotation = CGAffineTransformMakeRotation(degreesToRad(-15)) override init(){ super.init() } required init(coder aDecoder: NSCoder) { } func encodeWithCoder(aCoder: NSCoder) { } func applyEffect(gun: Gun) { var isRight = false for bullet in gun.bulletPool { var augBullet = bullet.path!.copy() as UIBezierPath if isRight { augBullet.applyTransform(leftRotation) } else { augBullet.applyTransform(rightRotation) } bullet.path = augBullet isRight = !isRight } } }
mit
d14e64976548c327a2aa575c91ad2e19
22.104167
72
0.592426
4.679325
false
false
false
false
jeevanRao7/Swift_Playgrounds
Swift Playgrounds/Algorithms/Sorting/Quick Sort.playground/Contents.swift
1
1060
/************************ Quick Sort Pscedocode (Recursion): procedure quicksort(List values) if values.size <= 1 then return values pivot = random element of values Divide values into the following lists list1 = { elements with value higher than the pivot } list2 = { pivot } list3 = { elements with value lower than the pivot } return quicksort(list1) + list2 + quicksort(list3) ************************/ import Foundation //Unsorted Array input var arr = [5, 8, 1, 9, 10, 2, 6]; let n = arr.count func quicksort(_ a: [Int]) -> [Int] { guard a.count > 1 else { return a } let pivot = a[a.count/2] let less = a.filter { $0 < pivot } let equal = a.filter { $0 == pivot } let greater = a.filter { $0 > pivot } // Uncomment this following line to see in detail what the // pivot is in each step and how the subarrays are partitioned. // print(pivot, less, equal, greater) return quicksort(less) + equal + quicksort(greater) } //Sorted Array - ascending order. print(quicksort(arr))
mit
41951a66809a98a486225b59a692c957
22.043478
67
0.620755
3.642612
false
false
false
false
SoneeJohn/WWDC
ConfCoreTests/AdapterTests.swift
1
16611
// // AdapterTests.swift // WWDC // // Created by Guilherme Rambo on 07/02/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import XCTest import SwiftyJSON @testable import ConfCore class AdapterTests: XCTestCase { private let dateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = ConfCoreDateFormat formatter.locale = Locale(identifier: "en-US") formatter.timeZone = TimeZone.current return formatter }() private func getJson(from filename: String) -> JSON { guard let fileURL = Bundle(for: AdapterTests.self).url(forResource: filename, withExtension: "json") else { XCTFail("Unable to find URL for fixture named \(filename)") fatalError() } guard let data = try? Data(contentsOf: fileURL) else { XCTFail("Unable to load fixture named \(filename)") fatalError() } return JSON(data: data) } func testEventsAdapter() { let json = getJson(from: "contents") guard let eventsArray = json["events"].array else { XCTFail("Sessions.json fixture doesn't have an \"events\" array") fatalError() } let result = EventsJSONAdapter().adapt(eventsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let events): XCTAssertEqual(events.count, 5) XCTAssertEqual(events[0].name, "WWDC 2017") XCTAssertEqual(events[0].identifier, "wwdc2017") XCTAssertEqual(events[0].isCurrent, true) XCTAssertEqual(events[4].name, "WWDC 2013") XCTAssertEqual(events[4].identifier, "wwdc2013") XCTAssertEqual(events[4].isCurrent, false) } } func testRoomsAdapter() { let json = getJson(from: "contents") guard let roomsArray = json["rooms"].array else { XCTFail("Sessions.json fixture doesn't have a \"rooms\" array") fatalError() } let result = RoomsJSONAdapter().adapt(roomsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let rooms): XCTAssertEqual(rooms.count, 35) XCTAssertEqual(rooms[0].identifier, "63") XCTAssertEqual(rooms[0].name, "Hall 3") XCTAssertEqual(rooms[34].identifier, "83") XCTAssertEqual(rooms[34].name, "San Pedro Square") } } func testTracksAdapter() { let json = getJson(from: "contents") guard let tracksArray = json["tracks"].array else { XCTFail("Sessions.json fixture doesn't have a \"tracks\" array") fatalError() } let result = TracksJSONAdapter().adapt(tracksArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let tracks): XCTAssertEqual(tracks.count, 8) XCTAssertEqual(tracks[0].name, "Featured") XCTAssertEqual(tracks[0].lightColor, "#3C5B72") XCTAssertEqual(tracks[0].lightBackgroundColor, "#d8dee3") XCTAssertEqual(tracks[0].darkColor, "#223340") XCTAssertEqual(tracks[0].titleColor, "#223B4D") XCTAssertEqual(tracks[7].name, "Distribution") XCTAssertEqual(tracks[7].lightColor, "#8C61A6") XCTAssertEqual(tracks[7].lightBackgroundColor, "#E8DFED") XCTAssertEqual(tracks[7].darkColor, "#35243E") XCTAssertEqual(tracks[7].titleColor, "#4C2B5F") } } func testKeywordsAdapter() { let json = getJson(from: "sessions") guard let keywordsArray = json["response"]["sessions"][0]["keywords"].array else { XCTFail("Couldn't find a session in sessions.json with an array of keywords") fatalError() } let result = KeywordsJSONAdapter().adapt(keywordsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let keywords): XCTAssertEqual(keywords.count, 10) XCTAssertEqual(keywords.map({ $0.name }), [ "audio", "editing", "export", "hls", "http live streaming", "imaging", "media", "playback", "recording", "video" ]); } } func testFocusesAdapter() { let json = getJson(from: "sessions") guard let focusesArray = json["response"]["sessions"][0]["focus"].array else { XCTFail("Couldn't find a session in sessions.json with an array of focuses") fatalError() } let result = FocusesJSONAdapter().adapt(focusesArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let focuses): XCTAssertEqual(focuses.count, 3) XCTAssertEqual(focuses.map({ $0.name }), [ "iOS", "macOS", "tvOS" ]); } } // TODO: disabled test, SessionAssetsJSONAdapter is not working func _testAssetsAdapter() { let json = getJson(from: "videos") guard let sessionsArray = json["sessions"].array else { XCTFail("Couldn't find an array of sessions in videos.json") fatalError() } let result = SessionAssetsJSONAdapter().adapt(sessionsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let assets): let flattenedAssets = assets.flatMap({ $0 }) XCTAssertEqual(flattenedAssets.count, 2947) XCTAssertEqual(flattenedAssets[0].assetType, SessionAssetType(rawValue: SessionAssetType.streamingVideo.rawValue)) XCTAssertEqual(flattenedAssets[0].remoteURL, "http://devstreaming.apple.com/videos/wwdc/2016/210e4481b1cnwor4n1q/210/hls_vod_mvp.m3u8") XCTAssertEqual(flattenedAssets[0].year, 2016) XCTAssertEqual(flattenedAssets[0].sessionId, "210") XCTAssertEqual(flattenedAssets[1].assetType, SessionAssetType(rawValue: SessionAssetType.hdVideo.rawValue)) XCTAssertEqual(flattenedAssets[1].remoteURL, "http://devstreaming.apple.com/videos/wwdc/2016/210e4481b1cnwor4n1q/210/210_hd_mastering_uikit_on_tvos.mp4") XCTAssertEqual(flattenedAssets[1].relativeLocalURL, "2016/210_hd_mastering_uikit_on_tvos.mp4") XCTAssertEqual(flattenedAssets[1].year, 2016) XCTAssertEqual(flattenedAssets[1].sessionId, "210") XCTAssertEqual(flattenedAssets[2].assetType, SessionAssetType(rawValue: SessionAssetType.sdVideo.rawValue)) XCTAssertEqual(flattenedAssets[2].remoteURL, "http://devstreaming.apple.com/videos/wwdc/2016/210e4481b1cnwor4n1q/210/210_sd_mastering_uikit_on_tvos.mp4") XCTAssertEqual(flattenedAssets[2].relativeLocalURL, "2016/210_sd_mastering_uikit_on_tvos.mp4") XCTAssertEqual(flattenedAssets[2].year, 2016) XCTAssertEqual(flattenedAssets[2].sessionId, "210") XCTAssertEqual(flattenedAssets[3].assetType, SessionAssetType(rawValue: SessionAssetType.slides.rawValue)) XCTAssertEqual(flattenedAssets[3].remoteURL, "http://devstreaming.apple.com/videos/wwdc/2016/210e4481b1cnwor4n1q/210/210_mastering_uikit_on_tvos.pdf") XCTAssertEqual(flattenedAssets[3].year, 2016) XCTAssertEqual(flattenedAssets[3].sessionId, "210") XCTAssertEqual(flattenedAssets[4].assetType, SessionAssetType(rawValue: SessionAssetType.webpage.rawValue)) XCTAssertEqual(flattenedAssets[4].remoteURL, "https://developer.apple.com/wwdc16/210") XCTAssertEqual(flattenedAssets[4].year, 2016) XCTAssertEqual(flattenedAssets[4].sessionId, "210") XCTAssertEqual(flattenedAssets[5].assetType, SessionAssetType(rawValue: SessionAssetType.image.rawValue)) XCTAssertEqual(flattenedAssets[5].remoteURL, "http://devstreaming.apple.com/videos/wwdc/2016/210e4481b1cnwor4n1q/210/images/210_734x413.jpg") XCTAssertEqual(flattenedAssets[5].year, 2016) XCTAssertEqual(flattenedAssets[5].sessionId, "210") } } func testLiveAssetsAdapter() { let json = getJson(from: "videos_live") guard let sessionsDict = json["live_sessions"].dictionary else { XCTFail("Couldn't find a dictionary of live sessions in videos_live.json") fatalError() } let sessionsArray = sessionsDict.map { key, value -> JSON in var v = value v["sessionId"] = JSON.init(rawValue: key)! return v } let result = LiveVideosAdapter().adapt(sessionsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let assets): let sortedAssets = assets.sorted(by: { $0.sessionId < $1.sessionId }) XCTAssertEqual(sortedAssets[0].assetType, SessionAssetType(rawValue: SessionAssetType.liveStreamVideo.rawValue)) XCTAssertGreaterThan(sortedAssets[0].year, 2016) XCTAssertEqual(sortedAssets[0].sessionId, "201") XCTAssertEqual(sortedAssets[0].remoteURL, "http://devstreaming.apple.com/videos/wwdc/2016/live/mission_ghub2yon5yewl2i/atv_mvp.m3u8") } } func testSessionsAdapter() { let json = getJson(from: "contents") guard let sessionsArray = json["contents"].array else { XCTFail("Couldn't find an array of sessions in videos.json") fatalError() } let result = SessionsJSONAdapter().adapt(sessionsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let sessions): XCTAssertEqual(sessions.count, 771) XCTAssertEqual(sessions[0].title, "Express Yourself!") XCTAssertEqual(sessions[0].trackName, "") XCTAssertEqual(sessions[0].number, "820") XCTAssertEqual(sessions[0].summary, "iMessage Apps help people easily create and share content, play games, and collaborate with friends without needing to leave the conversation. Explore how you can design iMessage apps and sticker packs that are perfectly suited for a deeply social context.") XCTAssertEqual(sessions[0].focuses[0].name, "iOS") } } func testSessionInstancesAdapter() { let json = getJson(from: "contents") guard let instancesArray = json["contents"].array else { XCTFail("Couldn't find an array of sessions in sessions.json") fatalError() } let result = SessionInstancesJSONAdapter().adapt(instancesArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let instances): XCTAssertEqual(instances.count, 307) // Lab XCTAssertNotNil(instances[0].session) XCTAssertEqual(instances[0].session?.number, "8080") XCTAssertEqual(instances[0].session?.title, "User Interface Design By Appointment Lab") XCTAssertEqual(instances[0].session?.trackName, "") XCTAssertEqual(instances[0].session?.summary, "Get advice on making your apps simple to use and more visually compelling. Come prepared with a working prototype, development build or your released app. Appointments are required and limited to one per developer for the duration of the conference. You may request an appointment beginning at 7 a.m. for that day only. Appointments fill quickly.") XCTAssertEqual(instances[0].session?.focuses.count, 4) XCTAssertEqual(instances[0].session?.focuses[0].name, "iOS") XCTAssertEqual(instances[0].session?.focuses[1].name, "macOS") XCTAssertEqual(instances[0].session?.focuses[2].name, "tvOS") XCTAssertEqual(instances[0].identifier, "2017-8080") XCTAssertEqual(instances[0].number, "wwdc2017-8080") XCTAssertEqual(instances[0].sessionType, 1) XCTAssertEqual(instances[0].keywords.count, 0) XCTAssertEqual(instances[0].startTime, dateTimeFormatter.date(from: "2017-06-09T09:00:00-07:00")) XCTAssertEqual(instances[0].endTime, dateTimeFormatter.date(from: "2017-06-09T15:30:00-07:00")) // Session XCTAssertNotNil(instances[2].session) XCTAssertEqual(instances[2].session?.number, "4170") XCTAssertEqual(instances[2].session?.title, "Source Control, Simulator, Testing, and Continuous Integration with Xcode Lab") XCTAssertEqual(instances[2].session?.trackName, "") XCTAssertEqual(instances[2].session?.summary, "Learn how to get the most out of the new source control workflows in Xcode. Talk with Apple engineers about how to create a build and test strategy using Unit and UI Testing, testing with Simulator, or how to set up workflows using the new standalone Xcode Server. Bring your code and your questions.") XCTAssertEqual(instances[2].session?.focuses.count, 4) XCTAssertEqual(instances[2].session?.focuses[0].name, "iOS") XCTAssertEqual(instances[2].session?.focuses[1].name, "macOS") XCTAssertEqual(instances[2].session?.focuses[2].name, "tvOS") XCTAssertEqual(instances[2].identifier, "2017-4170") XCTAssertEqual(instances[2].number, "wwdc2017-4170") XCTAssertEqual(instances[2].sessionType, 1) XCTAssertEqual(instances[2].keywords.count, 0) XCTAssertEqual(instances[2].startTime, dateTimeFormatter.date(from: "2017-06-08T16:10:00-07:00")) XCTAssertEqual(instances[2].endTime, dateTimeFormatter.date(from: "2017-06-08T18:00:00-07:00")) } } func testNewsAndPhotoAdapters() { let json = getJson(from: "news") guard let newsArray = json["items"].array else { XCTFail("Couldn't find an array of items in news.json") fatalError() } let result = NewsItemsJSONAdapter().adapt(newsArray) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let items): XCTAssertEqual(items.count, 16) // Regular news XCTAssertEqual(items[0].identifier, "991DF480-4435-4930-B0BC-8F75EFB85002") XCTAssertEqual(items[0].title, "Welcome") XCTAssertEqual(items[0].body, "We’re looking forward to an exciting week at the Apple Worldwide Developers Conference. Use this app to stream session videos, browse the conference schedule, mark schedule items as favorites, keep up with the latest conference news, and view maps of Moscone West.") XCTAssertEqual(items[0].date, Date(timeIntervalSince1970: 1464973210)) // Photo gallery XCTAssertEqual(items[5].identifier, "047E4F0B-2B8C-499A-BB23-F2CFDB3EB730") XCTAssertEqual(items[5].title, "Scholarship Winners Get the Excitement Started") XCTAssertEqual(items[5].body, "") XCTAssertEqual(items[5].date, Date(timeIntervalSince1970: 1465833604)) XCTAssertEqual(items[5].photos[0].identifier, "6F3D98B4-71A9-4321-9D4E-974346E784FD") XCTAssertEqual(items[5].photos[0].representations[0].width, 256) XCTAssertEqual(items[5].photos[0].representations[0].remotePath, "6F3D98B4-71A9-4321-9D4E-974346E784FD/256.jpeg") } } func testTranscriptsAdapter() { let json = getJson(from: "transcript") let result = TranscriptsJSONAdapter().adapt(json) switch result { case .error(let error): XCTFail(error.localizedDescription) case .success(let transcript): XCTAssertEqual(transcript.identifier, "2014-101") XCTAssertEqual(transcript.fullText.characters.count, 92023) XCTAssertEqual(transcript.annotations.count, 2219) XCTAssertEqual(transcript.annotations.first!.timecode, 0.506) XCTAssertEqual(transcript.annotations.first!.body, "[ Silence ]") } } }
bsd-2-clause
bb9b1ec85bac9c6b3b3b85aca5294b29
43.288
407
0.639511
4.439455
false
true
false
false
f22labs/onboard-ios
onboarding/Classes/UIFOnboardingView.swift
1
7718
// // UIFOnboardingView.swift // Pods // // Created by Ranjith Kumar on 03/11/2016. // Copyright © 2016 F22Labs. All rights reserved. public protocol UIFOnboardingViewProtocol:class { func pushNextScreen() } open class UIFOnboardingView: UIView,UIScrollViewDelegate { fileprivate var dataSource:[[String:String]]? fileprivate var scrollView:UIScrollView? fileprivate var pageControl:UIPageControl? fileprivate var nextButton:UIButton? fileprivate var skipButton:UIButton? fileprivate var imageViewArray = [UIImageView]() fileprivate var titleLabelArray = [UILabel]() fileprivate var subTitleArray = [UILabel]() open weak var delegate:UIFOnboardingViewProtocol? public override init(frame:CGRect) { super.init(frame:frame) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @available(iOS 8.2, *) public convenience init(dataSource:[Dictionary<String,String>]) { self.init() self.dataSource = dataSource self.createViews() } open override func layoutSubviews() { super.layoutSubviews() var leftInset:CGFloat = 20.0 let padding:CGFloat = 20.0 var maxScrollHeight:CGFloat = 0.0 for index in 0..<self.imageViewArray.count{ let im = self.imageViewArray[index] im.frame = CGRect(x:leftInset, y:0, width:self.bounds.width-(2*padding), height:self.bounds.width-(2*padding)) let title = self.titleLabelArray[index] title.sizeToFit() let titleHeight = max(title.bounds.height, 30) title.frame = CGRect(x:leftInset, y:im.frame.maxY+10, width:self.bounds.width-(2*padding), height:titleHeight) let subtTitle = self.subTitleArray[index] subtTitle.sizeToFit() let subTitleHeight = max(subtTitle.bounds.height, 30) subtTitle.frame = CGRect(x:leftInset, y:title.frame.maxY+10, width:self.bounds.width-(2*padding), height:subTitleHeight) leftInset = leftInset + self.bounds.width maxScrollHeight = max(maxScrollHeight, subtTitle.frame.maxY) } self.pageControl?.numberOfPages = self.imageViewArray.count let numberOfPages:CGFloat = CGFloat((self.pageControl?.numberOfPages)!) let scrollViewWidth = numberOfPages * self.bounds.width self.scrollView?.contentSize = CGSize(width:scrollViewWidth, height:maxScrollHeight) self.scrollView?.frame = CGRect(x:0, y:0, width:self.bounds.width, height:maxScrollHeight) let height:CGFloat = 40.0 self.pageControl?.frame = CGRect(x:(self.bounds.width-60)/2, y:(self.scrollView?.frame.maxY)!+10, width:60, height:30) self.pageControl?.currentPage = 0 self.nextButton?.frame = CGRect(x:(self.bounds.width-200)/2, y:(self.pageControl?.frame.maxY)!+10, width:200, height:height+10) self.nextButton?.layer.cornerRadius = (self.nextButton?.frame.height)!/2 self.skipButton?.frame = CGRect(x:(self.bounds.width-200)/2, y:(self.nextButton?.frame.maxY)!+10, width:200, height:height+10) } //MARK:: UIScrollView Delegates open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageWidth = scrollView.frame.width let nextPage = floor(scrollView.contentOffset.x - pageWidth / 2) / pageWidth + 1 self.pageControl?.currentPage = Int(nextPage) } //MARK:: Private Functions @objc fileprivate func didTapNextButton() { if ((self.pageControl?.currentPage)!==self.imageViewArray.count-1) { self.delegate?.pushNextScreen() }else { let currentPage = CGFloat((self.pageControl?.currentPage)!)+1.0 let x = currentPage * (self.scrollView?.frame.width)! self.pageControl?.currentPage = Int(currentPage) self.scrollView?.setContentOffset(CGPoint(x:x, y:0), animated: true) } } @objc fileprivate func didTapSkipButton() { guard (self.pageControl?.numberOfPages)!>0 else { return } let currentPage = CGFloat((self.pageControl?.numberOfPages)!)-1.0 let x = currentPage * (self.scrollView?.frame.width)! self.scrollView?.setContentOffset(CGPoint(x:x, y:0), animated: true) self.pageControl?.currentPage = Int(currentPage) self.delegate?.pushNextScreen() } @available(iOS 8.2, *) fileprivate func createViews() { self.backgroundColor = .clear self.scrollView = UIScrollView() self.scrollView?.isPagingEnabled = true self.scrollView?.backgroundColor = .white self.scrollView?.delegate = self self.scrollView?.showsHorizontalScrollIndicator = false self.scrollView?.showsVerticalScrollIndicator = false self.scrollView?.bounces = false self.addSubview(self.scrollView!) self.pageControl = UIPageControl() self.pageControl?.pageIndicatorTintColor = UIColor.UIFrgba(0x15B4F1, alpha: 0.2) self.pageControl?.currentPageIndicatorTintColor = UIColor.UIFrgb(0x15B4F1) self.addSubview(self.pageControl!) self.nextButton = UIButton() self.nextButton?.setTitle("NEXT", for: .normal) self.nextButton?.setTitleColor(.white, for: .normal) self.nextButton?.backgroundColor = UIColor.UIFrgb(0x15B4F1) self.nextButton?.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium) self.nextButton?.addTarget(self, action: #selector(didTapNextButton), for: .touchUpInside) self.addSubview(self.nextButton!) self.skipButton = UIButton() self.skipButton?.setTitle("Skip", for: .normal) self.skipButton?.setTitleColor(.black, for: .normal) self.skipButton?.layer.cornerRadius = 8.0 self.skipButton?.addTarget(self, action: #selector(didTapSkipButton), for: .touchUpInside) self.skipButton?.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: UIFontWeightLight) self.addSubview(self.skipButton!) for dictionary in self.dataSource! { let imageView = UIImageView() let image = UIImage(named: dictionary["imageName"]!) imageView.contentMode = .scaleAspectFit imageView.image = image self.imageViewArray.append(imageView) self.scrollView?.addSubview(imageView) let titleLabel = UILabel() titleLabel.text = dictionary["title"] titleLabel.textAlignment = .center titleLabel.numberOfLines = 1 if UIScreen.main.bounds.height<600 { titleLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular) }else { titleLabel.font = UIFont.systemFont(ofSize: 20, weight: UIFontWeightRegular) } titleLabel.textColor = UIColor.UIFrgb(0x424242) self.scrollView?.addSubview(titleLabel) self.titleLabelArray.append(titleLabel) let subTitle = UILabel() subTitle.text = dictionary["subTitle"] subTitle.textAlignment = .center subTitle.numberOfLines = 0 subTitle.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular) subTitle.textColor = UIColor.UIFrgba(0x424242, alpha: 0.55) self.scrollView?.addSubview(subTitle) self.subTitleArray.append(subTitle) } } }
mit
eccd91f4fef106b2e3ad762e50647e98
41.169399
135
0.644033
4.598927
false
false
false
false
memexapp/memex-swift-sdk
Sources/User.swift
1
2612
import Foundation import ObjectMapper /// Object that represents Memex user public class User: JSONRepresentable { public struct Constants { /// This constant should be used instead of userID always when you want tel SDK when you want you own user object. public static let myselfUserID = -1 } /// Unique user ID public var ID: Int? /// Timestamp when was user create public var createdAt: Date? /// Timestamp when was user object modified public var updatedAt: Date? /// User full name in format (FirstName LastName) public var fullname: String? /// Avatar of user. public var avatar: Media? /// MUID of users origin space (root, entry point) public var originSpaceMUID: String? /// User email public var email: String? /// Email Verification Flag public var isEmailVerified: Bool? /// User phone public var phone: String? /// Email Verification Flag public var isPhoneVerified: Bool? /// User full name in format (FirstName LastName) public var password: String? /// Date of last password change public var passwordChangedAt: Date? /// Flag that tells if user set his password or he can be only authenticated using onboarding token public var hasPassword: Bool? /// Onboarding token public var onboardingToken: String? /// Two Factor Authorization Flag public var isTFAEnabled: Bool? /// Flag that tells if user has enabled advanced features. This will be in future replaced with full feature flags set. public var permissions: [String: Any]? public override var hashValue: Int { return self.ID!.hashValue } public required init() { super.init() } public required init?(map: Map) { super.init(map: map) } override public func mapping(map: Map) { self.ID <- map["id"] self.createdAt <- map["created_at"] self.updatedAt <- map["updated_at"] self.fullname <- map["fullname"] self.email <- map["email"] self.phone <- map["phone"] self.password <- map["password"] self.avatar <- map["avatar"] self.originSpaceMUID <- map["origin_space_muid"] self.hasPassword <- map["has_password"] self.isEmailVerified <- map["is_email_verified"] self.isPhoneVerified <- map["is_phone_verified"] self.isTFAEnabled <- map["is_tfa_enabled"] self.passwordChangedAt <- map["password_changed_at"] self.permissions <- map["permissions"] self.onboardingToken <- map["onboarding_token"] } } public func ==(lhs: User, rhs: User) -> Bool { if lhs.ID == nil || rhs.ID == nil { return lhs === rhs } return lhs.ID == rhs.ID }
mit
851d39075ce56c3ad43254a62d82b49d
28.348315
121
0.678407
4.172524
false
false
false
false
CassiusPacheco/sweettrex
Sources/App/Service/TickerService.swift
1
2125
// // TickerService.swift // sweettrex // // Created by Cassius Pacheco on 24/9/17. // // import Foundation protocol TickerServiceProtocol { func tick(_ market: Market) throws -> Result<Ticker> } struct TickerService: TickerServiceProtocol { private let service: HttpServiceProtocol init() { self.init(httpService: HttpService()) } init(httpService: HttpServiceProtocol) { self.service = httpService } func tick(_ market: Market) throws -> Result<Ticker> { var result: Result<Ticker> = .failed(.unknown) do { print("\nTick \(market.name)...") let requestResult = try service.request(.ticker(market), httpMethod: .GET, bodyData: nil) switch requestResult { case .successful(let json): do { let tick = try self.parse(json, for: market) result = .successful(tick) } catch { // TODO: handle errors print("TickerService 💥 failed to parse Ticker") result = .failed(.parsing) } case .failed(_): // TODO: handle errors print("TickerService response error") result = .failed(.unknown) } } catch { // TODO: handle errors print("TickerService - failed to request ticker") result = .failed(.unknown) } return result } func parse(_ json: JSON, for market: Market) throws -> Ticker { guard let result: JSON = try json.get("result") else { throw Abort.badRequest } guard let price: Double = try result.get("Last") else { throw Abort.badRequest } return Ticker(market: market, lastPrice: price) } }
mit
ba4b6999cc9c08e2d1812c1e4b69174d
24.878049
101
0.474081
5.305
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Stock/View/SAMProductImageOpetationView.swift
1
2121
// // SAMProductImageOpetationView.swift // SaleManager // // Created by apple on 16/12/4. // Copyright © 2016年 YZH. All rights reserved. // import UIKit protocol SAMProductImageOpetationViewDelegate: NSObjectProtocol { func opetationViewDidClickCameraBtn() func opetationViewDidClickSelectBtn() func opetationViewDidClickSaveBtn() func opetationViewDidClickCancelBtn() func opetationViewDidClickSaveProductStockImageBtn() } class SAMProductImageOpetationView: UIView { weak var delegate: SAMProductImageOpetationViewDelegate? //对外提供类方法实例化对象 class func instacne() -> SAMProductImageOpetationView? { let view = Bundle.main.loadNibNamed("SAMProductImageOpetationView", owner: nil, options: nil)![0] as! SAMProductImageOpetationView return view } override func awakeFromNib() { super.awakeFromNib() if !hasTP_SZ_Auth { selectImageButton.isHidden = true topSeperaterView.isHidden = true cameraButton.isHidden = true centerSeperaterView.isHidden = true } } //MARK: - 点击事件 @IBAction func cameraBtnClick(_ sender: AnyObject) { delegate?.opetationViewDidClickCameraBtn() } @IBAction func selectBtnClick(_ sender: AnyObject) { delegate?.opetationViewDidClickSelectBtn() } @IBAction func saveStockImageBtnClick(_ sender: UIButton) { delegate?.opetationViewDidClickSaveProductStockImageBtn() } @IBAction func saveBtnClick(_ sender: AnyObject) { delegate?.opetationViewDidClickSaveBtn() } @IBAction func cancelBtnClick(_ sender: AnyObject) { delegate?.opetationViewDidClickCancelBtn() } //MARK: - XIB链接属性 @IBOutlet weak var selectImageButton: UIButton! @IBOutlet weak var cameraButton: UIButton! @IBOutlet weak var topSeperaterView: UIView! @IBOutlet weak var centerSeperaterView: UIView! //MARK: - 属性 ///新增图片权限 fileprivate lazy var hasTP_SZ_Auth: Bool = SAMUserAuth.checkAuth(["TP_SZ_APP"]) }
apache-2.0
a7f9cbb7e2de0314d98d958cf30a8949
30.723077
137
0.697381
4.251546
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/iOS Collection/Business/Business/IAP/IAPTool.swift
1
3108
// // IAPTool.swift // Business // // Created by 朱双泉 on 2018/11/3. // Copyright © 2018 Castie!. All rights reserved. // import UIKit import StoreKit class IAPTool: NSObject { static let shared = IAPTool() typealias ResultClosure = (_ products: [SKProduct]) -> () typealias StateClosure = (_ state: SKPaymentTransactionState) -> () var resultClosure: ResultClosure? var stateClosure: StateClosure? override init() { super.init() SKPaymentQueue.default().add(self) } deinit { SKPaymentQueue.default().remove(self) } class func requiredProducts(result: (_ productIdentifiers: Set<String>) -> ()) { let productIdentifiers: Set<String> = ["coderZsq.Business.id1", "coderZsq.Business.id2", "coderZsq.Business.id3"] result(productIdentifiers) } func requestAvaliableProducts(productIdentifiers: Set<String>, result: @escaping ResultClosure) { resultClosure = result; let request = SKProductsRequest(productIdentifiers: productIdentifiers) request.delegate = self request.start() } func purchase(product: SKProduct, result: StateClosure?) { stateClosure = result guard SKPaymentQueue.canMakePayments() else { return } let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } func restore() { SKPaymentQueue.default().restoreCompletedTransactions() } } extension IAPTool: SKProductsRequestDelegate { func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { print(response.invalidProductIdentifiers) print(response.products) guard let resultClosure = resultClosure else { return } resultClosure(response.products) } } extension IAPTool: SKPaymentTransactionObserver { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { if let stateClosure = stateClosure { stateClosure(transaction.transactionState) } switch transaction.transactionState { case .deferred: print("延迟处理") case .failed: print("失败") queue.finishTransaction(transaction) case .purchased: print("支付成功") queue.finishTransaction(transaction) case .purchasing: print("正在支付") case .restored: print("恢复购买") queue.finishTransaction(transaction) } } } func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) { print("移除交易时调用") print(transactions) } func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { print("回复购买成功") } }
mit
abaf8152f273483c48ac3f7e09ee958d
27.669811
121
0.619612
5.285217
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/DirectConnect/DirectConnect_Error.swift
1
2434
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for DirectConnect public struct DirectConnectErrorType: AWSErrorType { enum Code: String { case directConnectClientException = "DirectConnectClientException" case directConnectServerException = "DirectConnectServerException" case duplicateTagKeysException = "DuplicateTagKeysException" case tooManyTagsException = "TooManyTagsException" } private let error: Code public let context: AWSErrorContext? /// initialize DirectConnect public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// One or more parameters are not valid. public static var directConnectClientException: Self { .init(.directConnectClientException) } /// A server-side error occurred. public static var directConnectServerException: Self { .init(.directConnectServerException) } /// A tag key was specified more than once. public static var duplicateTagKeysException: Self { .init(.duplicateTagKeysException) } /// You have reached the limit on the number of tags that can be assigned. public static var tooManyTagsException: Self { .init(.tooManyTagsException) } } extension DirectConnectErrorType: Equatable { public static func == (lhs: DirectConnectErrorType, rhs: DirectConnectErrorType) -> Bool { lhs.error == rhs.error } } extension DirectConnectErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
205addfb915ba2e67ecaa93e3bbcb467
35.878788
117
0.668036
4.987705
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/DataSources/DashboardDataManager.swift
1
5498
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation /** * A shared resource manager for obtaining Business and Accounts specific data from MobileFirst Platform */ public class DashboardDataManager: NSObject{ // Callback function that will execute after the call returns var callback : ((Bool, [Business]!)->())! // Holds the business objects returned from MFP var businesses: [Business]! // Index to intiate the dashboard with var businessIndex = 0 // Class variable that will return a singleton when requested public class var sharedInstance : DashboardDataManager{ struct Singleton { static let instance = DashboardDataManager() } return Singleton.instance } /** Calls the MobileFirst Platform service - parameter callback: Callback to determine success */ func getDashboardData(callback: ((Bool, [Business]!)->())!){ self.callback = callback let adapterName : String = "SBBAdapter" let procedureName : String = "getDashboardData" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName) let params = [] caller.invokeWithResponse(self, params: nil) var userExists = false } /** Method used for testing */ public func getDashboardDataTest(){ getDashboardData(nil) } /** Method that is fired when a retry is attempted for dashboard data. */ func retryGetDashboardData(){ getDashboardData(callback) } /** Parses MobileFirst Platform's response and returns an array of account objects. - parameter worklightResponseJson: JSON response from MobileFirst Platform with Dashboard data. - returns: Array of account objects. */ func parseDashboardResponse(worklightResponseJson: NSDictionary) -> [Business]{ let businessesJsonString = worklightResponseJson["result"] as! String let data = businessesJsonString.dataUsingEncoding(NSUTF8StringEncoding) let businessJsonArray = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))) as! [AnyObject] var businesses: [Business] = [] for businessJson in businessJsonArray as! [[String: AnyObject]] { let business = Business() business.name = (businessJson["businessName"] as! String).uppercaseString business.imageName = businessJson["imageFile"] as! String var accounts : [Account] = [] for accountJson in businessJson["accounts"] as! [[String: AnyObject]] { let account = Account() account.id = accountJson["_id"] as! String account.accountName = (accountJson["name"] as! String).uppercaseString account.accountType = AccountType.Account account.balance = accountJson["balance"] as! Float account.hasTransactions = (account.accountName == "CHECKING") || (account.accountName == "SAVINGS") accounts.append(account) } business.accounts = accounts var spendings : [Account] = [] for spendingJson in businessJson["spending"] as! [[String: AnyObject]] { let spending = Account() spending.id = spendingJson["_id"] as! String spending.accountName = (spendingJson["name"] as! String).uppercaseString spending.accountType = AccountType.Spending spending.balance = spendingJson["balance"] as! Float spendings.append(spending) } business.spendings = spendings businesses.append(business) } return businesses } } extension DashboardDataManager: WLDataDelegate{ /** Delegate method for MobileFirst Platform. Called when connection and return is successful - parameter response: Response from MobileFirst Platform */ public func onSuccess(response: WLResponse!) { let responseJson = response.getResponseJson() as NSDictionary // Parse JSON response into dashboard format and store in accounts businesses = parseDashboardResponse(responseJson) // Execute the callback from the view controller that instantiated the dashboard call callback(true, businesses) } /** Delegate method for MobileFirst Platform. Called when connection or return is unsuccessful - parameter response: Response from MobileFirst Platform */ public func onFailure(response: WLFailResponse!) { MQALogger.log("Response: \(response.responseText)") if (response.errorCode.rawValue == 0) { MILAlertViewManager.sharedInstance.show("Can not connect to the server, click to refresh", callback: retryGetDashboardData) } callback(false, nil) } /** Delegate method for MobileFirst Platform. Task to do before executing a call. */ public func onPreExecute() { } /** Delegate method for MobileFirst Platform. Task to do after executing a call. */ public func onPostExecute() { } }
epl-1.0
810c8360bd1a57f61853c85c6a1a7fa2
33.3625
145
0.627251
5.563765
false
false
false
false