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
llb1119/LB_OCR
LB_OCR/Manager.swift
1
8263
// // Manager.swift // Pods // // Created by liulibo on 16/7/21. // // import Foundation import TesseractOCR public typealias LanguageOptions = [Language] public typealias CompletionHandler = ((recognizedText:String?, error:NSError?)->()) /** * The percentage of progress of recognition (between 0 and 100). */ public typealias ProgessBlock = ((percent:UInt) ->()) /// manager which is the engine's entry point public class Manager{ let operationQueue:NSOperationQueue let languages:LanguageOptions //private let delegates = TesseractDelegateCollections() let delegate = TesseractDelegate() private var tesseract:G8Tesseract? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? public init(languages:LanguageOptions = [Language.Chinese, Language.English]) throws{ self.languages = languages guard !languages.combineString.isEmpty else{ let failureReason = "init the engine failure" throw Error.error(code: Error.Code.InitEngineFailed, failureReason: failureReason) } self.operationQueue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1; if #available(OSX 10.10, *){ operationQueue.qualityOfService = NSQualityOfService.Utility } return operationQueue }() } /** Performs ocr on the image - parameter image: The image used for OCR - parameter squarePoint: The Four corner vertex of image used for OCR - parameter progressBlock: The percentage of progress of recognition (between 0 and 100). - parameter completionHandler: The completion handler that gets invoked after the ocr is finished. */ public func recognize(image:UIImage, squarePoint:SquarePoint? = nil, progressBlock:ProgessBlock? = nil, completionHandler:CompletionHandler) -> () { var preHandledImage:UIImage = image // pre handle image if let squarePoint = squarePoint { if let tmpImage = image.getTransformImageWithSquare(squarePoint)?.threshold { print("Success to pre-handle image with squarePoint"); preHandledImage = tmpImage; } else{ print("fail to pre-handle image with squarePoint") } } else { // if let tmpImage = image.threshold { // print("Success to pre-handle image"); // preHandledImage = tmpImage; // } else{ // print("fail to pre-handle image") // } } do { tesseract = try newTesseract() }catch { let error = Error.error(code: Error.Code.InitEngineFailed, failureReason: "init the engine failure") completionHandler(recognizedText: nil, error: error) return } //new a operation let operation = newOperation(preHandledImage, progressBlock: progressBlock) operation.recognitionCompleteBlock = makeCompletionHandler(operation, completionHandler: completionHandler) startTime = CFAbsoluteTimeGetCurrent() operationQueue.addOperation(operation) } // MARK: - TesseractDelegate final class TesseractDelegate:NSObject,G8TesseractDelegate{ var progressBlock:ProgessBlock? init(progressBlock:ProgessBlock? = nil) { self.progressBlock = progressBlock super.init() } /** * An optional method to be called periodically during recognition so * the recognition's progress can be observed. * * @param tesseract The `G8Tesseract` object performing the recognition. */ func progressImageRecognitionForTesseract(tesseract: G8Tesseract!) { dispatch_async(dispatch_get_main_queue()) { [weak self] in self?.progressBlock?(percent: tesseract.progress) } } /** * An optional method to be called periodically during recognition so * the user can choose whether or not to cancel recognition. * * @param tesseract The `G8Tesseract` object performing the recognition. * * @return Whether or not to cancel the recognition in progress. */ func shouldCancelImageRecognitionForTesseract(tesseract: G8Tesseract!) -> Bool { return false } } private class TesseractDelegateCollections { var delegates = [String:TesseractDelegate]() let delegatesQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) subscript(queue:RecognitionOperation)->TesseractDelegate?{ get { var delegate:TesseractDelegate? = nil dispatch_async(delegatesQueue) { [weak self] in if let key = queue.name { delegate = self?.delegates[key] } } return delegate } set { dispatch_barrier_async(delegatesQueue) { [weak self] in if let key = queue.name { self?.delegates[key] = newValue } } } } } } //MARK: private functions extension Manager { func newTesseract() throws -> G8Tesseract? { let dataPath = NSBundle(forClass: RecognitionOperation.self) let tesseract = G8Tesseract(language: languages.combineString, configDictionary: nil, configFileNames: nil, absoluteDataPath: dataPath.resourcePath, engineMode: .TesseractOnly, copyFilesFromResources: false) if let tesseract = tesseract { // Use the original Tesseract engine mode in performing the recognition // (see G8Constants.h) for other engine mode options tesseract.engineMode = .TesseractOnly; // Let Tesseract automatically segment the page into blocks of text // based on its analysis (see G8Constants.h) for other page segmentation // mode options tesseract.pageSegmentationMode = .AutoOnly; // Optionally limit the time Tesseract should spend performing the // recognition // operation.tesseract.maximumRecognitionTime = 1.0; return tesseract } else { let failureReason = "init the engine failure" throw Error.error(code: Error.Code.InitEngineFailed, failureReason: failureReason) return nil } } func newOperation(image:UIImage, progressBlock:ProgessBlock? = nil) -> RecognitionOperation { //let operation = RecognitionOperation(engine: tesseract) let operation = RecognitionOperation(language: languages.combineString) //let delegate = TesseractDelegate(progressBlock: progressBlock) //tesseract?.image = image delegate.progressBlock = progressBlock operation.delegate = delegate operation.tesseract.image = image //delegates[operation] = delegate return operation } func makeCompletionHandler(operation:RecognitionOperation, completionHandler:CompletionHandler) -> G8RecognitionOperationCallback { return { [weak self, weak operation](tesseract: G8Tesseract! )in //self?.delegates[operation!] = nil self?.endTime = CFAbsoluteTimeGetCurrent() let spendTime = (self?.endTime!)!-(self?.startTime!)! let seconds = Float(Int(100*spendTime))/100 if let tesseract = tesseract, recognizeString = tesseract.recognizedText { print("spend time \(seconds)s recoginzedText is \(tesseract.recognizedText)"); completionHandler(recognizedText: recognizeString, error: nil) } else{ completionHandler(recognizedText: nil, error: nil) } self?.tesseract = nil } } }
mit
2d602b3b3b6c58986b7f5cf674dbad76
37.976415
215
0.608496
5.421916
false
false
false
false
idappthat/UTANow-iOS
UTANow/AdminAddOrganizationTableViewController.swift
1
2902
// // AdminSelectOrganizationTableViewController.swift // UTANow // // Created by Cameron Moreau on 11/13/15. // Copyright © 2015 Mobi. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class AdminAddOrganizationTableViewController: UITableViewController { @IBAction func btnCancel(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } var orgs: NSMutableArray = [] override func viewDidLoad() { super.viewDidLoad() let paramFields = "picture.type(large), name, about, id, emails" FBSDKGraphRequest(graphPath: "/me/accounts", parameters: ["fields": paramFields]).startWithCompletionHandler({ (connection, result, error) -> Void in if error == nil { self.orgs = result["data"] as! NSMutableArray self.tableView.reloadData() } else { print(error) } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section) { case 0: return orgs.count default: return 1 } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch(section) { case 0: return "Found Organizations" default: return nil } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch(indexPath.section) { case 0: return CGFloat(65) default: return CGFloat(45) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //Organization cell if indexPath.section == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("organizationCell", forIndexPath: indexPath) as! AdminAddOrganizationTableViewCell let org = orgs[indexPath.row] as! NSDictionary let imageUrl = org.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as! String cell.labelName.text = org["name"] as? String cell.imagePicture.kf_setImageWithURL(NSURL(string: imageUrl)!) return cell } //Other/ not found else { return tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) } } }
mit
da55fe4a7a2cea4b999836b1483e8b9c
28.602041
157
0.600138
5.515209
false
false
false
false
prashnts/kbswift
kbswift/Extensions/String+Noop.swift
1
1035
// // String+Noop.swift // kbswift // // Created by Prashant Sinha on 09/01/17. // Copyright © 2017 Noop. All rights reserved. // import Foundation let VALID_HEX = "abcdef0123456789" extension String { /// Obtain chunks of the string. func chunks(withLength length: Int) -> Array<String> { return stride(from: 0, to: self.characters.count, by: length).map { let start = self.index(self.startIndex, offsetBy: $0) let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex return self[start..<end] } } /// Convert from hexed representation back to Byte Buffer. func unhex() -> CryptoBuffer? { let convertible = self.lowercased().characters .reduce(true) { (prev, c) -> Bool in prev && VALID_HEX.characters.contains(c) } guard self.characters.count % 2 == 0 && convertible else { return nil } return self.chunks(withLength: 2).map { UInt8.init($0, radix: 16)! } } }
mit
ff80359b10b872c42fb3d901c43f1550
30.333333
100
0.61412
3.787546
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Filters/SamplePercentFilter.swift
1
1553
// // SamplePercentFilter.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class SamplePercentFilter { init(withSamplePercentStorage storage: SamplePercentMemoryProtocol) { self.storage = storage } /// Class that keeps persistent data. private let storage: SamplePercentMemoryProtocol private func isPartOfRandomGroup(surveyId: Int, withSamplePercent percent: Int) -> Bool { let isPartOfRandomGroup = getRandomNumber(forSurveyId: surveyId) < percent if isPartOfRandomGroup == false { Qualaroo.log("Not showing survey with id: \(surveyId). Survey should be displayed only for \(percent)% of users.") return false } return true } private func getRandomNumber(forSurveyId surveyId: Int) -> Int { if let randomNumber = storage.getSamplePercent(forSurveyId: surveyId) { return randomNumber } return newRandomNumber(forSurveyId: surveyId) } private func newRandomNumber(forSurveyId surveyId: Int) -> Int { let newNumber = Int(arc4random_uniform(100)) storage.saveSamplePercent(newNumber, forSurveyId: surveyId) return newNumber } } extension SamplePercentFilter: FilterProtocol { func shouldShow(survey: Survey) -> Bool { return isPartOfRandomGroup(surveyId: survey.surveyId, withSamplePercent: survey.requireMap.samplePercent) } }
mit
80312f6f3419b3f160aeeaaab26a332d
30.693878
120
0.723117
4.141333
false
false
false
false
lexchou/swallow
stdlib/core/_RandomAccessIndexType.swift
1
1217
/// This protocol is an implementation detail of `RandomAccessIndexType`; do /// not use it directly. /// /// Its requirements are inherited by `RandomAccessIndexType` and thus must /// be satisfied by types conforming to that protocol. protocol _RandomAccessIndexType : _BidirectionalIndexType, Strideable { /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). /// /// Axioms:: /// /// x.distanceTo(x.successor())) == 1 /// x.distanceTo(x.predecessor())) == -1 /// x.advancedBy(x.distanceTo(y)) == y func distanceTo(other: Self) -> Self.Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) /// /// Axioms:: /// /// x.advancedBy(0) == x /// x.advancedBy(1) == x.successor() /// x.advancedBy(-1) == x.predecessor() /// x.distanceTo(x.advancedBy(m)) == m func advancedBy(n: Self.Distance) -> Self }
bsd-3-clause
14d46199d52a852b4379f90ffea417ac
33.771429
76
0.589975
3.744615
false
false
false
false
xuanyi0627/jetstream-ios
Jetstream/PingMessage.swift
1
2611
// // PingMessage.swift // Jetstream // // Copyright (c) 2014 Uber Technologies, Inc. // // 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 class PingMessage: NetworkMessage { class var messageType: String { return "Ping" } override var type: String { return PingMessage.messageType } public let ack: UInt public let resendMissing: Bool init(index: UInt, ack: UInt, resendMissing: Bool) { self.ack = ack self.resendMissing = resendMissing super.init(index: index) } public convenience init(session: Session) { self.init(index: 0, ack: session.serverIndex, resendMissing: false) } public convenience init(session: Session, resendMissing: Bool) { self.init(index: 0, ack: session.serverIndex, resendMissing: resendMissing) } public override func serialize() -> [String: AnyObject] { var dictionary = super.serialize() dictionary["ack"] = ack dictionary["resendMissing"] = resendMissing return dictionary } public class func unserialize(dictionary: [String: AnyObject]) -> NetworkMessage? { var index = dictionary["index"] as? UInt var ack = dictionary["ack"] as? UInt var resendMissing = dictionary["resendMissing"] as? Bool if index == nil || ack == nil || resendMissing == nil { return nil } else { return PingMessage(index: index!, ack: ack!, resendMissing: resendMissing!) } } }
mit
e463ddafee29581a796aeed4e54870d3
35.774648
87
0.675603
4.463248
false
false
false
false
kickstarter/ios-oss
KsApi/models/graphql/adapters/Backing+BackingFragmentTests.swift
1
28039
import Apollo @testable import KsApi import XCTest final class Backing_BackingFragmentTests: XCTestCase { func test() { do { let variables = [ "withStoredCards": true, "includeShippingRules": true, "includeLocalPickup": true ] let fragment = try GraphAPI.BackingFragment(jsonObject: backingDictionary(), variables: variables) XCTAssertNotNil(fragment) guard let backing = Backing.backing(from: fragment) else { XCTFail("Backing should created from fragment") return } XCTAssertNotNil(backing) XCTAssertEqual(backing.amount, 90.0) XCTAssertNotNil(backing.backer) XCTAssertNotNil(backing.backerId) XCTAssertEqual(backing.backerCompleted, false) XCTAssertEqual(backing.bonusAmount, 5.0) XCTAssertEqual(backing.cancelable, true) XCTAssertEqual(backing.id, decompose(id: "QmFja2luZy0xNDQ5NTI3MTc=")) XCTAssertEqual(backing.locationId, decompose(id: "TG9jYXRpb24tMjM0MjQ3NzU=")) XCTAssertEqual(backing.locationName, "Canada") XCTAssertEqual(backing.paymentSource?.type, .visa) XCTAssertEqual(backing.pledgedAt, 1_625_613_342.0) XCTAssertEqual(backing.projectCountry, "US") XCTAssertEqual(backing.projectId, 1_596_594_463) XCTAssertNotNil(backing.reward) XCTAssertEqual(backing.rewardId, decompose(id: "UmV3YXJkLTgxNzM5MDE=")) XCTAssertEqual(backing.sequence, 148) XCTAssertEqual(backing.shippingAmount, 10.0) XCTAssertEqual(backing.status, .pledged) guard let reward = backing.reward else { XCTFail("reward should exist") return } XCTAssertTrue(reward.hasAddOns) } catch { XCTFail(error.localizedDescription) } } func test_noReward() { do { let variables = [ "withStoredCards": true, "includeShippingRules": true ] var dict = backingDictionary() dict["addOns"] = NSNull() dict["reward"] = NSNull() let fragment = try GraphAPI.BackingFragment(jsonObject: dict, variables: variables) XCTAssertNotNil(fragment) let backing = Backing.backing(from: fragment) XCTAssertNotNil(backing) XCTAssertEqual(backing?.reward?.isNoReward, true) XCTAssertEqual(backing?.reward?.convertedMinimum, 1.23244501) XCTAssertEqual(backing?.reward?.minimum, 1.0) } catch { XCTFail(error.localizedDescription) } } } private func backingDictionary() -> [String: Any] { let json = """ { "__typename": "Backing", "addOns": { "__typename": "RewardTotalCountConnection", "nodes": [ { "__typename": "Reward", "amount": { "__typename": "Money", "amount": "30.0", "currency": "USD", "symbol": "$" }, "allowedAddons": { "__typename": "RewardConnection", "pageInfo": { "__typename": "PageInfo", "startCursor": null } }, "backersCount": 2, "convertedAmount": { "__typename": "Money", "amount": "37.0", "currency": "CAD", "symbol": "$" }, "description": "", "displayName": "Art of the Quietly Quixotic ($30)", "endsAt": null, "estimatedDeliveryOn": "2021-12-01", "id": "UmV3YXJkLTgxNzM5Mjg=", "isMaxPledge": false, "items": { "__typename": "RewardItemsConnection", "edges": [ { "__typename": "RewardItemEdge", "quantity": 1, "node": { "__typename": "RewardItem", "id": "UmV3YXJkSXRlbS0xMTcwODA4", "name":"Art Book (8.5x11)" } } ] }, "localReceiptLocation": null, "limit": null, "limitPerBacker": 10, "name": "Art of the Quietly Quixotic", "remainingQuantity": null, "shippingPreference": "unrestricted", "shippingSummary": "Ships worldwide", "shippingRules": [ { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDEzMzg0", "location": { "__typename": "Location", "country": "ZZ", "countryName": null, "displayableName": "Earth", "id": "TG9jYXRpb24tMQ==", "name": "Rest of World" } }, { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExMjc4ODEw", "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "United States", "id": "TG9jYXRpb24tMjM0MjQ5Nzc=", "name": "United States" } } ], "startsAt": null }, { "__typename": "Reward", "amount": { "__typename": "Money", "amount": "10.0", "currency": "USD", "symbol": "$" }, "allowedAddons": { "__typename": "RewardConnection", "pageInfo": { "__typename": "PageInfo", "startCursor": null } }, "localReceiptLocation": null, "backersCount": 23, "convertedAmount": { "__typename": "Money", "amount": "13.0", "currency": "CAD", "symbol": "$" }, "description": "A 160 page coloring book and tarot journal with all 78 cards available for your enjoyment!", "displayName": "Wee William Journal & Coloring Book ($10)", "endsAt": null, "estimatedDeliveryOn": "2021-12-01", "id": "UmV3YXJkLTgyNDgxOTM=", "isMaxPledge": false, "items": { "__typename": "RewardItemsConnection", "edges": [] }, "limit": null, "limitPerBacker": 10, "name": "Wee William Journal & Coloring Book", "remainingQuantity": null, "shippingPreference": "unrestricted", "shippingSummary": "Ships worldwide", "shippingRules": [ { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDY2NTM4", "location": { "__typename": "Location", "country": "ZZ", "countryName": null, "displayableName": "Earth", "id": "TG9jYXRpb24tMQ==", "name": "Rest of World" } }, { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDY2NTM5", "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "United States", "id": "TG9jYXRpb24tMjM0MjQ5Nzc=", "name": "United States" } } ], "startsAt": null }, { "__typename": "Reward", "amount": { "__typename": "Money", "amount": "10.0", "currency": "USD", "symbol": "$" }, "localReceiptLocation": null, "allowedAddons": { "__typename": "RewardConnection", "pageInfo": { "__typename": "PageInfo", "startCursor": null } }, "backersCount": 23, "convertedAmount": { "__typename": "Money", "amount": "13.0", "currency": "CAD", "symbol": "$" }, "description": "A 160 page coloring book and tarot journal with all 78 cards available for your enjoyment!", "displayName": "Wee William Journal & Coloring Book ($10)", "endsAt": null, "estimatedDeliveryOn": "2021-12-01", "id": "UmV3YXJkLTgyNDgxOTM=", "isMaxPledge": false, "items": { "__typename": "RewardItemsConnection", "edges": [] }, "limit": null, "limitPerBacker": 10, "name": "Wee William Journal & Coloring Book", "remainingQuantity": null, "shippingPreference": "unrestricted", "shippingSummary": "Ships worldwide", "shippingRules": [ { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDY2NTM4", "location": { "__typename": "Location", "country": "ZZ", "countryName": null, "displayableName": "Earth", "id": "TG9jYXRpb24tMQ==", "name": "Rest of World" } }, { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDY2NTM5", "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "United States", "id": "TG9jYXRpb24tMjM0MjQ5Nzc=", "name": "United States" } } ], "startsAt": null }, { "__typename": "Reward", "amount": { "__typename": "Money", "amount": "10.0", "currency": "USD", "symbol": "$" }, "localReceiptLocation": null, "allowedAddons": { "__typename": "RewardConnection", "pageInfo": { "__typename": "PageInfo", "startCursor": null } }, "backersCount": 23, "convertedAmount": { "__typename": "Money", "amount": "13.0", "currency": "CAD", "symbol": "$" }, "description": "A 160 page coloring book and tarot journal with all 78 cards available for your enjoyment!", "displayName": "Wee William Journal & Coloring Book ($10)", "endsAt": null, "estimatedDeliveryOn": "2021-12-01", "id": "UmV3YXJkLTgyNDgxOTM=", "isMaxPledge": false, "items": { "__typename": "RewardItemsConnection", "edges": [] }, "limit": null, "limitPerBacker": 10, "name": "Wee William Journal & Coloring Book", "remainingQuantity": null, "shippingPreference": "unrestricted", "shippingSummary": "Ships worldwide", "shippingRules": [ { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDY2NTM4", "location": { "__typename": "Location", "country": "ZZ", "countryName": null, "displayableName": "Earth", "id": "TG9jYXRpb24tMQ==", "name": "Rest of World" } }, { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDY2NTM5", "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "United States", "id": "TG9jYXRpb24tMjM0MjQ5Nzc=", "name": "United States" } } ], "startsAt": null } ] }, "amount": { "__typename": "Money", "amount": "90.0", "currency": "USD", "symbol": "$" }, "backer": { "__typename": "User", "chosenCurrency": "USD", "backings":{ "__typename": "UserBackingsConnection", "nodes":[ { "__typename": "Backing", "errorReason":null }, { "__typename": "Backing", "errorReason":"Something went wrong" }, { "__typename": "Backing", "errorReason":null } ] }, "backingsCount": 3, "email": "[email protected]", "createdProjects": { "__typename": "UserCreatedProjectsConnection", "totalCount": 16 }, "membershipProjects": { "__typename": "MembershipProjectsConnection", "totalCount": 10 }, "savedProjects": { "__typename": "UserSavedProjectsConnection", "totalCount": 11 }, "hasUnreadMessages": false, "hasUnseenActivity": true, "surveyResponses": { "__typename": "SurveyResponsesConnection", "totalCount": 2 }, "optedOutOfRecommendations": true, "hasPassword": true, "id": "VXNlci0xMTA4OTI0NjQw", "imageUrl": "https://ksr-qa-ugc.imgix.net/assets/014/148/024/902b3aee57c0325f82d93af888194c5e_original.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1476734758&auto=format&frame=1&q=92&s=81a3c902ee2131666a590702b71ba5c2", "isAppleConnected": false, "isCreator": false, "isDeliverable": true, "isEmailVerified": true, "isFacebookConnected": true, "isKsrAdmin": false, "isFollowing": true, "name": "Justin Swart", "isSocializing": true, "newsletterSubscriptions": null, "notifications": null, "needsFreshFacebookToken": true, "showPublicProfile": true, "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "Las Vegas, NV", "id": "TG9jYXRpb24tMjQzNjcwNA==", "name": "Las Vegas" }, "storedCards": { "__typename": "UserCreditCardTypeConnection", "nodes": [ { "__typename": "CreditCard", "expirationDate": "2023-01-01", "id": "6", "lastFour": "4242", "type": "VISA" } ], "totalCount": 1 }, "uid": "1108924640" }, "backerCompleted": false, "bonusAmount": { "__typename": "Money", "amount": "5.0", "currency": "USD", "symbol": "$" }, "cancelable": true, "creditCard": { "__typename": "CreditCard", "expirationDate": "2033-03-01", "id": "69021181", "lastFour": "4242", "paymentType": "CREDIT_CARD", "state": "ACTIVE", "type": "VISA" }, "id": "QmFja2luZy0xNDQ5NTI3MTc=", "location": { "__typename": "Location", "country": "CA", "countryName": "Canada", "displayableName": "Canada", "id": "TG9jYXRpb24tMjM0MjQ3NzU=", "name": "Canada" }, "pledgedOn": 1625613342, "project": { "__typename": "Project", "availableCardTypes": [ "VISA", "MASTERCARD", "AMEX" ], "backersCount": 135, "backing": { "__typename": "Backing", "backer": { "__typename": "User", "uid": "618005886", "isSocializing": true, "newsletterSubcriptions": null, "notifications": null } }, "category": { "__typename": "Category", "id": "Q2F0ZWdvcnktNDc=", "name": "Fiction", "analyticsName": "Comic Books", "parentCategory": { "__typename": "Category", "id": "Q2F0ZWdvcnktMTg=", "name": "Publishing", "analyticsName": "Publishing" } }, "story": "API returns this as HTML wrapped in a string. But here HTML breaks testing because the serializer does not recognize escape characters within a string.", "environmentalCommitments": [ { "__typename": "EnvironmentalCommitment", "commitmentCategory": "longLastingDesign", "description": "High quality materials and cards - there is nothing design or tech-wise that would render Dustbiters obsolete besides losing the cards.", "id": "RW52aXJvbm1lbnRhbENvbW1pdG1lbnQtMTI2NTA2" } ], "faqs": { "__typename": "ProjectFaqConnection", "nodes": [ { "__typename": "ProjectFaq", "question": "Are you planning any expansions for Dustbiters?", "answer": "This may sound weird in the world of big game boxes with hundreds of tokens, cards and thick manuals, but through years of playtesting and refinement we found our ideal experience is these 21 unique cards we have now. Dustbiters is balanced for quick and furious games with different strategies every time you jump back in, and we currently have no plans to mess with that.", "id": "UHJvamVjdEZhcS0zNzA4MDM=", "createdAt": 1628103400 } ] }, "risks": "As with any project of this nature, there are always some risks involved with manufacturing and shipping. That's why we're collaborating with the iam8bit team, they have many years of experience producing and delivering all manner of items to destinations all around the world. We do not expect any delays or hiccups with reward fulfillment. But if anything comes up, we will be clear and communicative about what is happening and how it might affect you.", "canComment": false, "commentsCount": 0, "country": { "__typename": "Country", "code": "US", "name": "the United States" }, "creator": { "__typename": "User", "chosenCurrency": "USD", "backings":{ "__typename": "UserBackingsConnection", "nodes":[ { "__typename": "Backing", "errorReason":null }, { "__typename": "Backing", "errorReason":"Something went wrong" }, { "__typename": "Backing", "errorReason":null } ] }, "backingsCount": 23, "email": "[email protected]", "hasPassword": true, "id": "VXNlci02MzE4MTEzODc=", "imageUrl": "https://ksr-qa-ugc.imgix.net/assets/026/582/411/0064c9eba577b99cbb09d9bb197e215a_original.jpeg?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1617736562&auto=format&frame=1&q=92&s=085218a7258d22c455492bed76f5433a", "isAppleConnected": false, "isCreator": null, "isDeliverable": true, "isEmailVerified": true, "isFacebookConnected": true, "isKsrAdmin": false, "isFollowing": true, "name": "Hugh Alan Samples", "newsletterSubscriptions": null, "notifications": null, "isSocializing": true, "needsFreshFacebookToken": true, "showPublicProfile": true, "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "Las Vegas, NV", "id": "TG9jYXRpb24tMjQzNjcwNA==", "name": "Las Vegas" }, "createdProjects": { "__typename": "UserCreatedProjectsConnection", "totalCount": 16 }, "membershipProjects": { "__typename": "MembershipProjectsConnection", "totalCount": 10 }, "savedProjects": { "__typename": "UserSavedProjectsConnection", "totalCount": 11 }, "hasUnreadMessages": false, "hasUnseenActivity": true, "surveyResponses": { "__typename": "SurveyResponsesConnection", "totalCount": 2 }, "optedOutOfRecommendations": true, "storedCards": { "__typename": "UserCreditCardTypeConnection", "nodes": [ { "__typename": "CreditCard", "expirationDate": "2023-01-01", "id": "6", "lastFour": "4242", "type": "VISA" } ], "totalCount": 1 }, "uid": "631811387" }, "currency": "USD", "deadlineAt": 1620478771, "description": "Dark Fantasy Novel & Tarot Cards", "finalCollectionDate": null, "friends": { "__typename": "ProjectBackerFriendsConnection", "nodes": [] }, "fxRate": 1.23244501, "goal": { "__typename": "Money", "amount": "3000.0", "currency": "USD", "symbol": "$" }, "image": { "__typename": "Photo", "id": "UGhvdG8tMzI0NTYxMDE=", "url": "https://ksr-qa-ugc.imgix.net/assets/032/456/101/d32b5e2097301e5ccf4aa1e4f0be9086_original.tiff?ixlib=rb-4.0.2&crop=faces&w=1024&h=576&fit=crop&v=1613880671&auto=format&frame=1&q=92&s=617def65783295f2dabdff1b39005eca" }, "isProjectWeLove": true, "isProjectOfTheDay": false, "isWatched": false, "launchedAt": 1617886771, "isLaunched": true, "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "Henderson, KY", "id": "TG9jYXRpb24tMjQxOTk0NA==", "name": "Henderson" }, "maxPledge": 8500, "minPledge": 1, "name": "WEE WILLIAM WITCHLING", "pid": 1596594463, "pledged": { "__typename": "Money", "amount": "9841.0", "currency": "USD", "symbol": "$" }, "posts": { "__typename": "PostConnection", "totalCount": 3 }, "prelaunchActivated": true, "slug": "parliament-of-rooks/wee-william-witchling", "state": "LIVE", "stateChangedAt": 1617886773, "tags": [ { "__typename": "Tag", "name": "LGBTQIA+" } ], "url": "https://staging.kickstarter.com/projects/parliament-of-rooks/wee-william-witchling", "usdExchangeRate": 1, "video": { "__typename": "Video", "id": "VmlkZW8tMTExNjQ0OA==", "videoSources": { "__typename": "VideoSources", "high": { "__typename": "VideoSourceInfo", "src": "https://v.kickstarter.com/1631480664_a23b86f39dcfa7b0009309fa0f668ceb5e13b8a8/projects/4196183/video-1116448-h264_high.mp4" }, "hls": { "__typename": "VideoSourceInfo", "src": "https://v.kickstarter.com/1631480664_a23b86f39dcfa7b0009309fa0f668ceb5e13b8a8/projects/4196183/video-1116448-hls_playlist.m3u8" } } } }, "reward": { "__typename": "Reward", "amount": { "__typename": "Money", "amount": "25.0", "currency": "USD", "symbol": "$" }, "localReceiptLocation": null, "allowedAddons": { "__typename": "RewardConnection", "pageInfo": { "__typename": "PageInfo", "startCursor": "WzIsODMzNzczN10=" } }, "backersCount": 13, "convertedAmount": { "__typename": "Money", "amount": "31.0", "currency": "CAD", "symbol": "$" }, "description": "", "displayName": "Soft Cover Book (Signed) ($25)", "endsAt": null, "estimatedDeliveryOn": "2021-12-01", "id": "UmV3YXJkLTgxNzM5MDE=", "isMaxPledge": false, "items": { "__typename": "RewardItemsConnection", "edges": [ { "__typename": "RewardItemEdge", "quantity": 1, "node": { "__typename": "RewardItem", "id": "UmV3YXJkSXRlbS0xMTcwNzk5", "name": "Soft-Cover Book (Signed)" } }, { "__typename": "RewardItemEdge", "quantity": 1, "node": { "__typename": "RewardItem", "id": "UmV3YXJkSXRlbS0xMjY0ODAz", "name": "GALLERY PRINT (30x45cm)" } } ] }, "limit": null, "limitPerBacker": 1, "name": "Soft Cover Book (Signed)", "project": { "__typename": "Project", "id": "UHJvamVjdC0xNTk2NTk0NDYz", "friends": { "__typename": "ProjectBackerFriendsConnection", "nodes": [] }, "isWatched": false }, "remainingQuantity": null, "shippingPreference": "unrestricted", "shippingSummary": "Ships worldwide", "shippingRules": [ { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDEzMzc5", "location": { "__typename": "Location", "country": "ZZ", "countryName": null, "displayableName": "Earth", "id": "TG9jYXRpb24tMQ==", "name": "Rest of World" } }, { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExMjc4NzUy", "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "United States", "id": "TG9jYXRpb24tMjM0MjQ5Nzc=", "name": "United States" } } ], "startsAt": null }, "sequence": 148, "shippingAmount": { "__typename": "Money", "amount": "10.0", "currency": "USD", "symbol": "$" }, "status": "pledged" } """ let data = Data(json.utf8) var resultMap = (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]) ?? [:] resultMap["environmentalCommitments"] = [[ "__typename": "EnvironmentalCommitment", "commitmentCategory": GraphAPI.EnvironmentalCommitmentCategory.longLastingDesign, "description": "High quality materials and cards - there is nothing design or tech-wise that would render Dustbiters obsolete besides losing the cards.", "id": "RW52aXJvbm1lbnRhbENvbW1pdG1lbnQtMTI2NTA2" ]] return resultMap }
apache-2.0
13d03ee6afbd11f126446fabfb003274
31.191734
473
0.48404
4.102268
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/RewardCardContainerViewModelTests.swift
1
24262
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions import ReactiveExtensions_TestHelpers import ReactiveSwift import XCTest final class RewardCardContainerViewModelTests: TestCase { fileprivate let vm: RewardCardContainerViewModelType = RewardCardContainerViewModel() private let pledgeButtonStyleType = TestObserver<ButtonStyleType, Never>() private let pledgeButtonEnabled = TestObserver<Bool, Never>() private let pledgeButtonHidden = TestObserver<Bool, Never>() private let pledgeButtonTitleText = TestObserver<String?, Never>() private let rewardSelected = TestObserver<Int, Never>() let availableHasAddOns = Reward.postcards |> Reward.lens.hasAddOns .~ true let availableLimitedReward = Reward.postcards |> Reward.lens.limit .~ 100 |> Reward.lens.remaining .~ 25 |> Reward.lens.endsAt .~ nil let availableTimebasedReward = Reward.postcards |> Reward.lens.limit .~ nil |> Reward.lens.remaining .~ nil |> Reward.lens.endsAt .~ (MockDate().timeIntervalSince1970 + 60.0 * 60.0 * 24.0) let availableLimitedTimebasedReward = Reward.postcards |> Reward.lens.limit .~ 100 |> Reward.lens.remaining .~ 25 |> Reward.lens.endsAt .~ (MockDate().timeIntervalSince1970 + 60.0 * 60.0 * 24.0) let availableNonLimitedReward = Reward.postcards |> Reward.lens.limit .~ nil |> Reward.lens.remaining .~ nil |> Reward.lens.endsAt .~ nil let unavailableLimitedReward = Reward.postcards |> Reward.lens.limit .~ 100 |> Reward.lens.remaining .~ 0 |> Reward.lens.endsAt .~ nil let unavailableTimebasedReward = Reward.postcards |> Reward.lens.limit .~ nil |> Reward.lens.remaining .~ nil |> Reward.lens.endsAt .~ (MockDate().date.timeIntervalSince1970 - 1) let unavailableLimitedTimebasedReward = Reward.postcards |> Reward.lens.limit .~ 100 |> Reward.lens.remaining .~ 0 |> Reward.lens.endsAt .~ (MockDate().date.timeIntervalSince1970 - 1) let availableLimitedUnavailableTimebasedReward = Reward.postcards |> Reward.lens.limit .~ 100 |> Reward.lens.remaining .~ 25 |> Reward.lens.endsAt .~ (MockDate().date.timeIntervalSince1970 - 1) private var allRewards: [Reward] { return [ availableHasAddOns, availableLimitedReward, availableTimebasedReward, availableLimitedTimebasedReward, availableNonLimitedReward, unavailableLimitedReward, unavailableTimebasedReward, unavailableLimitedTimebasedReward, availableLimitedUnavailableTimebasedReward, Reward.noReward ] } override func setUp() { super.setUp() self.vm.outputs.pledgeButtonStyleType.observe(self.pledgeButtonStyleType.observer) self.vm.outputs.pledgeButtonEnabled.observe(self.pledgeButtonEnabled.observer) self.vm.outputs.pledgeButtonHidden.observe(self.pledgeButtonHidden.observer) self.vm.outputs.pledgeButtonTitleText.observe(self.pledgeButtonTitleText.observer) self.vm.outputs.rewardSelected.observe(self.rewardSelected.observer) } func testLive_BackedProject_BackedReward() { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .live |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.backing .~ ( .template |> Backing.lens.reward .~ reward |> Backing.lens.rewardId .~ reward.id |> Backing.lens.shippingAmount .~ 10 |> Backing.lens.amount .~ 700.0 ) self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues([ .green, .black, .black, .black, .black, .black, .black, .black, .black, .black ]) self.pledgeButtonEnabled.assertValues( [true, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonHidden.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonTitleText.assertValues([ "Continue", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected" ]) } func testLive_BackedProject_NonBackedReward() { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .live |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.backing .~ ( .template |> Backing.lens.reward .~ Reward.otherReward |> Backing.lens.rewardId .~ Reward.otherReward.id |> Backing.lens.shippingAmount .~ 10 |> Backing.lens.amount .~ 700.0 ) self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues( [.green, .green, .green, .green, .green, .green, .green, .green, .green, .green] ) self.pledgeButtonEnabled.assertValues([true, true, true, true, true, false, false, false, false, true]) self.pledgeButtonHidden.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonTitleText.assertValues([ "Select", "Select", "Select", "Select", "Select", "No longer available", "No longer available", "No longer available", "No longer available", "Select" ]) } func testLive_NonBackedProject_LoggedIn() { withEnvironment(currentUser: .template) { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .live |> Project.lens.personalization.isBacking .~ false self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues( [.green, .green, .green, .green, .green, .green, .green, .green, .green, .green] ) self.pledgeButtonEnabled.assertValues([true, true, true, true, true, false, false, false, false, true]) self.pledgeButtonHidden.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonTitleText.assertValues([ "Select", "Select", "Select", "Select", "Select", "No longer available", "No longer available", "No longer available", "No longer available", "Select" ]) } } func testLive_NonBackedProject_LoggedOut() { withEnvironment(currentUser: nil) { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .live |> Project.lens.personalization.isBacking .~ nil |> Project.lens.personalization.backing .~ nil self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues( [.green, .green, .green, .green, .green, .green, .green, .green, .green, .green] ) self.pledgeButtonEnabled.assertValues([true, true, true, true, true, false, false, false, false, true]) self.pledgeButtonHidden.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonTitleText.assertValues([ "Select", "Select", "Select", "Select", "Select", "No longer available", "No longer available", "No longer available", "No longer available", "Select" ]) } } func testNonLive_BackedProject_BackedReward() { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .successful |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.backing .~ ( .template |> Backing.lens.reward .~ reward |> Backing.lens.rewardId .~ reward.id |> Backing.lens.shippingAmount .~ 10 |> Backing.lens.amount .~ 700.0 ) self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues( [.black, .black, .black, .black, .black, .black, .black, .black, .black, .black] ) self.pledgeButtonEnabled.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonHidden.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonTitleText.assertValues([ "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected", "Selected" ]) } func testNonLive_BackedProject_NonBackedReward() { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .successful |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.backing .~ ( .template |> Backing.lens.reward .~ Reward.otherReward |> Backing.lens.rewardId .~ Reward.otherReward.id |> Backing.lens.shippingAmount .~ 10 |> Backing.lens.amount .~ 700.0 ) self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues([ .none, .none, .none, .none, .none, .none, .none, .none, .none, .none ]) self.pledgeButtonEnabled.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonHidden.assertValues([true, true, true, true, true, true, true, true, true, true]) self.pledgeButtonTitleText.assertValues([nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]) } func testNonLive_NonBackedProject() { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .successful |> Project.lens.personalization.isBacking .~ false self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues([ .none, .none, .none, .none, .none, .none, .none, .none, .none, .none ]) self.pledgeButtonEnabled.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonHidden.assertValues( [true, true, true, true, true, true, true, true, true, true] ) self.pledgeButtonTitleText.assertValues( [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] ) } func testLive_BackedProject_BackedReward_Errored() { // only test reward states that we can get to let rewards = [ availableLimitedReward, availableTimebasedReward, availableLimitedTimebasedReward, availableNonLimitedReward, Reward.noReward ] self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in rewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .live |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.backing .~ ( .template |> Backing.lens.reward .~ reward |> Backing.lens.rewardId .~ reward.id |> Backing.lens.shippingAmount .~ 10 |> Backing.lens.amount .~ 700.0 |> Backing.lens.status .~ .errored ) self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(rewards.count) self.pledgeButtonEnabled.assertValueCount(rewards.count) self.pledgeButtonHidden.assertValueCount(rewards.count) self.pledgeButtonTitleText.assertValueCount(rewards.count) self.pledgeButtonStyleType.assertValues([.black, .black, .black, .black, .black]) self.pledgeButtonEnabled.assertValues([false, false, false, false, false]) self.pledgeButtonHidden.assertValues([false, false, false, false, false]) self.pledgeButtonTitleText.assertValues([ "Selected", "Selected", "Selected", "Selected", "Selected" ]) } func testNonLive_BackedProject_BackedReward_Errored() { // only test reward states that we can get to let rewards = [ availableLimitedReward, availableTimebasedReward, availableLimitedTimebasedReward, availableNonLimitedReward, Reward.noReward ] self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in rewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.state .~ .successful |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.backing .~ ( .template |> Backing.lens.reward .~ reward |> Backing.lens.rewardId .~ reward.id |> Backing.lens.shippingAmount .~ 10 |> Backing.lens.amount .~ 700.0 |> Backing.lens.status .~ .errored ) self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(rewards.count) self.pledgeButtonEnabled.assertValueCount(rewards.count) self.pledgeButtonHidden.assertValueCount(rewards.count) self.pledgeButtonTitleText.assertValueCount(rewards.count) self.pledgeButtonStyleType.assertValues([.black, .black, .black, .black, .black]) self.pledgeButtonEnabled.assertValues([false, false, false, false, false]) self.pledgeButtonHidden.assertValues([false, false, false, false, false]) self.pledgeButtonTitleText.assertValues([ "Selected", "Selected", "Selected", "Selected", "Selected" ]) } func testLive_IsCreator_LoggedIn() { let creator = User.template |> User.lens.id .~ 5 withEnvironment(currentUser: creator) { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.creator .~ creator |> Project.lens.state .~ .live |> Project.lens.personalization.isBacking .~ false self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues( [.none, .none, .none, .none, .none, .none, .none, .none, .none, .none] ) self.pledgeButtonEnabled.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonHidden.assertValues( [true, true, true, true, true, true, true, true, true, true] ) self.pledgeButtonTitleText.assertValues([nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]) } } func testNonLive_IsCreator_LoggedIn() { let creator = User.template |> User.lens.id .~ 5 withEnvironment(currentUser: creator) { self.pledgeButtonStyleType.assertValueCount(0) self.pledgeButtonEnabled.assertValueCount(0) self.pledgeButtonHidden.assertValueCount(0) self.pledgeButtonTitleText.assertValueCount(0) for (index, reward) in self.allRewards.enumerated() { let project = Project.cosmicSurgery |> Project.lens.creator .~ creator |> Project.lens.state .~ .successful |> Project.lens.personalization.isBacking .~ false self.vm.inputs.configureWith(project: project, rewardOrBacking: .init(reward)) let emissionCount = index + 1 self.pledgeButtonStyleType.assertValueCount(emissionCount) self.pledgeButtonEnabled.assertValueCount(emissionCount) self.pledgeButtonHidden.assertValueCount(emissionCount) self.pledgeButtonTitleText.assertValueCount(emissionCount) } self.pledgeButtonStyleType.assertValueCount(self.allRewards.count) self.pledgeButtonEnabled.assertValueCount(self.allRewards.count) self.pledgeButtonHidden.assertValueCount(self.allRewards.count) self.pledgeButtonTitleText.assertValueCount(self.allRewards.count) self.pledgeButtonStyleType.assertValues( [.none, .none, .none, .none, .none, .none, .none, .none, .none, .none] ) self.pledgeButtonEnabled.assertValues( [false, false, false, false, false, false, false, false, false, false] ) self.pledgeButtonHidden.assertValues( [true, true, true, true, true, true, true, true, true, true] ) self.pledgeButtonTitleText.assertValues( [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] ) } } func testPledgeButtonTapped() { self.vm.inputs.configureWith(project: .template, rewardOrBacking: .left(.template)) self.vm.inputs.pledgeButtonTapped() self.rewardSelected.assertValues([Reward.template.id]) } }
apache-2.0
de5c477c195d15efe68b56a8985b6c44
37.268139
109
0.702209
4.412075
false
false
false
false
Acumen004/ConvertibleCollection
ConvertibleCollection/MainVC.swift
1
8194
// // MainVC.swift // ConvertibleCollection // // Created by Appinventiv on 13/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit //MARK: Class MainVC class MainVC: UIViewController { //Outlet of collection view @IBOutlet weak var sampleGallery: UICollectionView! //Outlet of button that toggles between grid and list view @IBOutlet weak var buttonToChangeView: UIButton! //Outlet that shows the current view Type @IBOutlet weak var viewType: UILabel! //delete button outlet @IBOutlet weak var deleteButton: UIButton! //enumeration that stores the current view layout var currentView = ViewFlowLayout.isInGridView let listFlowLayout = ListLayout() let gridFlowLayout = GridLayout() //stores indexpath of items to be deleted var selectedArray = [IndexPath]() var data: [[String:String]] = [ ["Name": "Iron man", "Image": "IM"], ["Name": "Green Arrow", "Image": "Arrow"], ["Name": "Flash", "Image": "flash"], ["Name": "Reverse Flash", "Image": "revFlash"], ["Name": "Zoom", "Image": "Zoom"], ["Name": "Black Hawk", "Image": "bx"], ["Name": "Green Lantern", "Image": "GL"], ["Name": "Captain America", "Image": "CA"], ["Name": "Tin Man", "Image": "tin"] ] //MARK: viewDidLoad override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.automaticallyAdjustsScrollViewInsets = false sampleGallery.dataSource = self sampleGallery.delegate = self //registery to list cell nib let nibList = UINib(nibName: "ListCell", bundle: nil) sampleGallery.register(nibList, forCellWithReuseIdentifier: "ListCellID") //registery to grid cell nib let nibGrid = UINib(nibName: "GridCell", bundle: nil) sampleGallery.register(nibGrid, forCellWithReuseIdentifier: "GridCellID") // initial view set to grid sampleGallery.collectionViewLayout = gridFlowLayout deleteButton.isHidden = true sampleGallery.allowsSelection = false //Handling tap gesture let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:))) longPress.minimumPressDuration = 0.4 // longPress.numberOfTouchesRequired = 1 self.sampleGallery.addGestureRecognizer(longPress) } //perform deletion of selected element @IBAction func deleteButtonAction(_ sender: UIButton) { for indexPath in selectedArray.sorted().reversed(){ data.remove(at: indexPath.item) sampleGallery.deleteItems(at: [indexPath]) } selectedArray = [IndexPath]() deleteButton.isHidden = true buttonToChangeView.isHidden = false sampleGallery.allowsSelection = false } // action to performed when the button is clicked @IBAction func buttonClicked(_ sender: UIButton) { sampleGallery.reloadData() if currentView == .isInGridView { viewType.text = "List" currentView = .isInListView UIView.animate(withDuration: 0.2) { () -> Void in self.sampleGallery.collectionViewLayout.invalidateLayout() self.sampleGallery.setCollectionViewLayout(self.listFlowLayout, animated: true)} } else{ viewType.text = "Grid" currentView = .isInGridView UIView.animate(withDuration: 0.2) { () -> Void in self.sampleGallery.collectionViewLayout.invalidateLayout() self.sampleGallery.setCollectionViewLayout(self.gridFlowLayout, animated: true)} } buttonToChangeView.isSelected = !buttonToChangeView.isSelected //reload datasource to toggle between views. } //function to handle long press //MARK: longPressAction func longPressAction(gesture: UILongPressGestureRecognizer){ buttonToChangeView.isHidden = true deleteButton.isHidden = false gesture.allowableMovement = 4 if gesture.state == .ended{ return } sampleGallery.allowsMultipleSelection = true //indetifying index path of item cell at the press point on screen let pressPoint = gesture.location(in: self.sampleGallery) if let indexPath = self.sampleGallery.indexPathForItem(at: pressPoint){ if selectedArray .contains(indexPath){ selectedArray.remove(at: selectedArray.index(of: indexPath)!) } sampleGallery.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.centeredVertically) collectionView(sampleGallery, didSelectItemAt: indexPath) } } } //MARK: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate extension MainVC: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate{ //returns number of items func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } //returns item cell at particular index func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if currentView == .isInGridView{ guard let cell = sampleGallery.dequeueReusableCell(withReuseIdentifier: "GridCellID", for: indexPath) as? GridCell else{fatalError("Error! No Cell found")} //update data in cell cell.sampleImage.image = UIImage(named: data[indexPath.item]["Image"]!) cell.sampleLabelText.text = data[indexPath.item]["Name"] cell.backgroundColor = nil if selectedArray .contains(indexPath){ cell.backgroundColor = .blue } return cell } else{ guard let cell = sampleGallery.dequeueReusableCell(withReuseIdentifier: "ListCellID", for: indexPath) as? ListCell else{fatalError("Error! No Cell found")} //update data in cell cell.sampleImage.image = UIImage(named: data[indexPath.item]["Image"]!) cell.sampleLabelText.text = data[indexPath.item]["Name"] cell.backgroundColor = nil if selectedArray .contains(indexPath){ cell.backgroundColor = .blue } return cell } } //customization to perform on item cell when selected func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if (selectedArray.count == 4){ sampleGallery.deselectItem(at: indexPath, animated: false) let alert = UIAlertController(title: "Whooops!!", message: "Selection reached max limit", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Back", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { selectedArray.append(indexPath) print(selectedArray) let cell = sampleGallery.cellForItem(at: indexPath) cell?.backgroundColor = .blue } } //resume initial state of item cell when deselected func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { print(#function) let cell = sampleGallery.cellForItem(at: indexPath) cell?.backgroundColor = nil selectedArray.remove(at: selectedArray.index(of: indexPath)!) if selectedArray.isEmpty{ deleteButton.isHidden = true buttonToChangeView.isHidden = false } } }
mit
7547db7c2a1f94432aabb5544c526b3a
34.314655
167
0.623703
5.440239
false
false
false
false
lokinfey/MyPerfectframework
Examples/Ultimate Noughts and Crosses/Ultimate Noughts and Crosses Server/PerfectHandlers.swift
1
1596
// // PerfectHandlers.swift // Ultimate Noughts and Crosses // // Created by Kyle Jessup on 2015-11-12. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectLib import Darwin let GAME_DB_PATH = PerfectServer.staticPerfectServer.homeDir() + serverSQLiteDBs + "utictactoe" // This is the function which all Perfect Server modules must expose. // The system will load the module and call this function. // In here, register any handlers or perform any one-time tasks. public func PerfectServerModuleInit() { // Register our handler class with the PageHandlerRegistry. // The name "FAHandler", which we supply here, is used within a moustache template to associate the template with the handler. PageHandlerRegistry.addPageHandler("UNCHandler") { // This closure is called in order to create the handler object. // It is called once for each relevant request. // The supplied WebResponse object can be used to tailor the return value. // However, all request processing should take place in the `valuesForResponse` function. (r:WebResponse) -> PageHandler in return UNCHandler() } GameState().initializeDatabase() }
apache-2.0
5915e53fc76a0436a95c053b19ff70e3
33.673913
127
0.672727
4.406077
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieCore/Json/Json.swift
1
10605
// // Json.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public enum Json: Hashable { case null case boolean(Bool) case string(String) case number(Number) case array([Json]) case dictionary([String: Json]) } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Json: Sendable { } extension Json { @inlinable public init(_ value: Bool) { self = .boolean(value) } @inlinable public init(_ value: String) { self = .string(value) } @inlinable public init<S: StringProtocol>(_ value: S) { self = .string(String(value)) } @inlinable public init<T: FixedWidthInteger & SignedInteger>(_ value: T) { self = .number(Number(value)) } @inlinable public init<T: FixedWidthInteger & UnsignedInteger>(_ value: T) { self = .number(Number(value)) } @inlinable public init<T: BinaryFloatingPoint>(_ value: T) { self = .number(Number(value)) } @inlinable public init(_ value: Decimal) { self = .number(Number(value)) } @inlinable public init(_ value: Number) { self = .number(value) } @inlinable public init<Wrapped: JsonConvertible>(_ value: Wrapped?) { self = value.toJson() } @inlinable public init<S: Sequence>(_ elements: S) where S.Element: JsonConvertible { self = .array(elements.map { $0.toJson() }) } @inlinable public init<Value: JsonConvertible>(_ elements: [String: Value]) { self = .dictionary(elements.mapValues { $0.toJson() }) } @inlinable public init<Value: JsonConvertible>(_ elements: OrderedDictionary<String, Value>) { self = .dictionary(Dictionary(elements.mapValues { $0.toJson() })) } } extension Json: ExpressibleByNilLiteral { @inlinable public init(nilLiteral value: Void) { self = .null } } extension Json: ExpressibleByBooleanLiteral { @inlinable public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension Json: ExpressibleByIntegerLiteral { @inlinable public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension Json: ExpressibleByFloatLiteral { @inlinable public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension Json: ExpressibleByStringInterpolation { @inlinable public init(stringLiteral value: StringLiteralType) { self.init(value) } @inlinable public init(stringInterpolation: String.StringInterpolation) { self.init(String(stringInterpolation: stringInterpolation)) } } extension Json: ExpressibleByArrayLiteral { @inlinable public init(arrayLiteral elements: Json ...) { self.init(elements) } } extension Json: ExpressibleByDictionaryLiteral { @inlinable public init(dictionaryLiteral elements: (String, Json) ...) { self.init(Dictionary(uniqueKeysWithValues: elements)) } } extension Json: CustomStringConvertible { public var description: String { switch self { case .null: return "nil" case let .boolean(bool): return "\(bool)" case let .string(string): return "\"\(string.escaped(asASCII: false))\"" case let .number(value): return "\(value)" case let .array(array): return "\(array)" case let .dictionary(dictionary): return "\(dictionary)" } } } extension Json { @inlinable public var isNil: Bool { switch self { case .null: return true default: return false } } @inlinable public var isBool: Bool { switch self { case .boolean: return true default: return false } } @inlinable public var isString: Bool { switch self { case .string: return true default: return false } } @inlinable public var isArray: Bool { switch self { case .array: return true default: return false } } @inlinable public var isObject: Bool { switch self { case .dictionary: return true default: return false } } @inlinable public var isNumber: Bool { switch self { case .number: return true default: return false } } } extension Json { @inlinable public var boolValue: Bool? { switch self { case let .boolean(value): return value default: return nil } } @inlinable public var int8Value: Int8? { switch self { case let .number(value): return value.int8Value default: return nil } } @inlinable public var uint8Value: UInt8? { switch self { case let .number(value): return value.uint8Value default: return nil } } @inlinable public var int16Value: Int16? { switch self { case let .number(value): return value.int16Value default: return nil } } @inlinable public var uint16Value: UInt16? { switch self { case let .number(value): return value.uint16Value default: return nil } } @inlinable public var int32Value: Int32? { switch self { case let .number(value): return value.int32Value default: return nil } } @inlinable public var uint32Value: UInt32? { switch self { case let .number(value): return value.uint32Value default: return nil } } @inlinable public var int64Value: Int64? { switch self { case let .number(value): return value.int64Value default: return nil } } @inlinable public var uint64Value: UInt64? { switch self { case let .number(value): return value.uint64Value default: return nil } } @inlinable public var intValue: Int? { switch self { case let .number(value): return value.intValue default: return nil } } @inlinable public var uintValue: UInt? { switch self { case let .number(value): return value.uintValue default: return nil } } @inlinable public var floatValue: Float? { switch self { case let .number(value): return value.floatValue default: return nil } } @inlinable public var doubleValue: Double? { switch self { case let .number(value): return value.doubleValue default: return nil } } @inlinable public var decimalValue: Decimal? { switch self { case let .number(value): return value.decimalValue default: return nil } } @inlinable public var numberValue: Number? { switch self { case let .number(value): return value default: return nil } } @inlinable public var stringValue: String? { switch self { case let .string(value): return value default: return nil } } @inlinable public var array: [Json]? { switch self { case let .array(value): return value default: return nil } } @inlinable public var dictionary: [String: Json]? { switch self { case let .dictionary(value): return value default: return nil } } } extension Json { @inlinable public var count: Int { switch self { case let .array(value): return value.count case let .dictionary(value): return value.count default: fatalError("Not an array or object.") } } @inlinable public subscript(index: Int) -> Json { get { guard 0..<count ~= index else { return nil } switch self { case let .array(value): return value[index] default: return nil } } set { switch self { case var .array(value): replaceValue(&self) { if index >= value.count { value.append(contentsOf: repeatElement(nil, count: index - value.count + 1)) } value[index] = newValue return Json(value) } default: fatalError("Not an array.") } } } @inlinable public var keys: Dictionary<String, Json>.Keys { guard case let .dictionary(value) = self else { return [:].keys } return value.keys } @inlinable public subscript(key: String) -> Json { get { guard case let .dictionary(value) = self else { return nil } return value[key] ?? nil } set { guard case var .dictionary(value) = self else { fatalError("Not an object.") } replaceValue(&self) { value[key] = newValue.isNil ? nil : newValue return Json(value) } } } }
mit
13dee471ef7f08fc836b23250bafa9cb
23.102273
100
0.572937
4.661538
false
false
false
false
Tricertops/YAML
Sources/Parsing/Parser+Error.swift
1
1380
// // Parser+Error.swift // YAML.framework // // Created by Martin Kiss on 14 May 2016. // https://github.com/Tricertops/YAML // // The MIT License (MIT) // Copyright © 2016 Martin Kiss // extension Parser.Error { init?(_ parser: yaml_parser_t) { guard let kind: Parser.Error.Kind = .from(parser.error) else { return nil } self.kind = kind self.message = String(cString: parser.problem) self.contextMessage = parser.context == nil ? "" : String(cString: parser.context) let value = Int(parser.problem_value) self.value = (value == -1 ? nil : value) self.mark = Parser.Mark(parser.problem_mark) self.contextMark = Parser.Mark(parser.context_mark) } } extension Parser.Error.Kind { static func from(_ yaml_error: yaml_error_type_t) -> Parser.Error.Kind? { switch yaml_error { case YAML_NO_ERROR: return nil case YAML_MEMORY_ERROR: return .allocation case YAML_READER_ERROR: return .decoding case YAML_SCANNER_ERROR: return .scanning case YAML_PARSER_ERROR: return .parsing default: return .unspecified } } }
mit
3cd5cd5d5b6889c3e588e6c38b2e00af
21.606557
90
0.531545
4.166163
false
false
false
false
sunzeboy/realm-cocoa
RealmSwift-swift2.0/List.swift
6
13482
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the list. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type } /// Returns the number of objects in this list. public var count: Int { return Int(_rlmArray.count) } } /** `List<T>` is the container type in Realm used to define to-many relationships. Lists hold a single `Object` subclass (`T`) which defines the "type" of the list. Lists can be filtered and sorted with the same predicates as `Results<T>`. When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { // MARK: Properties /// The Realm the objects in this list belong to, or `nil` if the list's owning /// object does not belong to a realm (the list is standalone). public var realm: Realm? { if let rlmRealm = _rlmArray.realm { return Realm(rlmRealm) } else { return nil } } /// Indicates if the list can no longer be accessed. public var invalidated: Bool { return _rlmArray.invalidated } // MARK: Initializers /// Creates a `List` that holds objects of type `T`. public override init() { // FIXME: use T.className() super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the list. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the list. */ public func indexOf(object: T) -> Int? { return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given `index` on get. Replaces the object at the given `index` on set. - warning: You can only set an object during a write transaction. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return _rlmArray[UInt(index)] as! T } set { throwForNegativeIndex(index) return _rlmArray[UInt(index)] = unsafeBitCast(newValue, RLMObject.self) } } /// Returns the first object in the list, or `nil` if empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the list, or `nil` if empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return _rlmArray.valueForKey(key) } /** Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return _rlmArray.setValue(value, forKey: key) } // MARK: Filtering /** Returns `Results` containing list elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing list elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns `Results` containing list elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing list elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` containing list elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing list elements sorted by the given property. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is from a different Realm it is copied to the List's Realm. - warning: This method can only be called during a write transaction. - parameter object: An object. */ public func append(object: T) { _rlmArray.addObject(unsafeBitCast(object, RLMObject.self)) } /** Appends the objects in the given sequence to the end of the list. - warning: This method can only be called during a write transaction. - parameter objects: A sequence of objects. */ public func extend<S: SequenceType where S.Generator.Element == T>(objects: S) { for obj in objects { _rlmArray.addObject(unsafeBitCast(obj, RLMObject.self)) } } /** Inserts the given object at the given index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(object: T, atIndex index: Int) { throwForNegativeIndex(index) _rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index)) } /** Removes the object at the given index from the list. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter index: The index at which to remove the object. */ public func removeAtIndex(index: Int) { throwForNegativeIndex(index) _rlmArray.removeObjectAtIndex(UInt(index)) } /** Removes the last object in the list. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the List. Does not remove the objects from the Realm. - warning: This method can only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter index: The list index of the object to be replaced. - parameter object: An object to replace at the specified index. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self)) } /** Moves the object at the given source index to the given destination index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to)) } /** Exchanges the objects in the list at given indexes. - warning: Throws an exception when either index exceeds the bounds of the list. - warning: This method can only be called during a write transaction. - parameter index1: The index of the object with which to replace the object at index `index2`. - parameter index2: The index of the object with which to replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2)) } } extension List: RangeReplaceableCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the list. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support /** Replace the given `subRange` of elements with `newElements`. - parameter subRange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the list. */ public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>, with newElements: C) { for _ in subRange { removeAtIndex(subRange.startIndex) } for x in newElements.reverse() { insert(x, atIndex: subRange.startIndex) } } /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). public var endIndex: Int { return count } /// This method has no effect. public func reserveCapacity(capacity: Int) { } }
apache-2.0
31eb9a9290f47b857a14d270e3168ba0
35.048128
139
0.669337
4.68125
false
false
false
false
Cosmo/TinyConsole
TinyConsole/Extensions/UIAlertActionExtensions.swift
1
2362
// // UIAlertActionExtensions.swift // TinyConsole // // Created by Devran on 30.09.19. // import MessageUI internal extension UIAlertAction { static let cancel: UIAlertAction = { UIAlertAction(title: "Cancel", style: .cancel, handler: nil) }() static let clear: UIAlertAction = { UIAlertAction(title: "Clear", style: .destructive) { (action: UIAlertAction) in TinyConsole.clear() } }() static func okAddLog(with alert: UIAlertController) -> UIAlertAction { return UIAlertAction(title: "Add Log", style: .default) { (action: UIAlertAction) in guard let text = alert.textFields?.first?.text, !text.isEmpty else { return } TinyConsole.print(text) } } static func ok() -> UIAlertAction { return UIAlertAction(title: "OK", style: .default, handler: nil) } } internal extension UIAlertAction { typealias MailInitiator = UIViewController & MFMailComposeViewControllerDelegate static func sendMail(on viewController: MailInitiator) -> UIAlertAction { UIAlertAction(title: "Send Email", style: .default) { (action: UIAlertAction) in DispatchQueue.main.async { guard let text = TinyConsole.shared.textView?.text else { return } if MFMailComposeViewController.canSendMail() { let composeViewController = MFMailComposeViewController() composeViewController.mailComposeDelegate = viewController composeViewController.setSubject("Console Log") composeViewController.setMessageBody(text, isHTML: false) viewController.present(composeViewController, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Email account required", message: "Please configure an email account in Mail", preferredStyle: .alert) alert.addAction(UIAlertAction.ok()) viewController.present(alert, animated: true, completion: nil) } } } } }
mit
d26fcbc99b1e309b6d503345c82ef3d0
35.90625
103
0.570279
5.705314
false
false
false
false
amdaza/HackerBooks
HackerBooks/HackerBooks/Note+CoreDataClass.swift
1
2819
// // Note+CoreDataClass.swift // HackerBooks // // Created by Home on 22/9/16. // Copyright © 2016 Alicia Daza. All rights reserved. // import Foundation import CoreData import UIKit @objc public class Note: NSManagedObject { static let entityName = "Note" convenience init(book: Book, image: UIImage, inContext context: NSManagedObjectContext){ // Get entity description let ent = NSEntityDescription.entity(forEntityName: Note.entityName, in: context)! // Call super self.init(entity: ent, insertInto: context) // Assign properties self.text = "" self.book = book creationDate = NSDate() modificationDate = NSDate() // Create photo photo = Photo(note: self, image: image, inContext: context) } convenience init(book: Book, inContext context : NSManagedObjectContext) { let ent = NSEntityDescription.entity(forEntityName: Note.entityName, in: context)! self.init(entity: ent, insertInto: context) // Assign properties self.text = "" self.book = book creationDate = NSDate() modificationDate = NSDate() // Save empty photo photo = Photo(note: self, inContext: context) } } //MARK: - KVO extension Note { @nonobjc static let observableKeys = ["name", "notes"] func setupKVO(){ // Subscribe notifications to some properties for key in Book.observableKeys { self.addObserver(self, forKeyPath: key, options: [], context: nil) } } func teardownKVO(){ // Unsubscribe for key in Note.observableKeys { self.removeObserver(self, forKeyPath: key) } } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { modificationDate = NSDate() } } //MARK: - Lifecycle extension Note { // Called only once public override func awakeFromInsert() { super.awakeFromInsert() setupKVO() } // Called many times public override func awakeFromFetch() { super.awakeFromFetch() setupKVO() } public override func willTurnIntoFault() { super.willTurnIntoFault() teardownKVO() } }
gpl-3.0
484f7c6cae6707422986019df57b1abe
23.504348
76
0.521292
5.514677
false
false
false
false
tipparti/PodImage
PodImage/GetResourceFromURI.swift
1
6888
// // GetResourceFromURI.swift // Shared // // Created by Etienne Goulet-Lang on 1/14/16. // Copyright © 2016 Heine Frifeldt. All rights reserved. // import Foundation import BaseUtils /// This operation will either fetch a resource or check if the resource has changed - pass in checkForUpdatesOnly to /// to choose the behavior. /// /// The fetch path forcefully checks for an update by passing in ReloadIgnoringLocalCacheData for the caching parameter /// on the request object. /// /// The check for update path tries to attach the Etag and Last-Modified headers stored in the ImageHelperRef's cache /// object. /// /// - MP4 resources create an MP4ResourceDescriptor object /// - Animated Resources create a GIFResourceDescriptor object /// - Non-animated Resources create a UIImage object class GetResourceFromURI: UniqueOperation { private var retry = 0; // MARK: - Unique id - // required for UniqueOperationQueue override func getUniqueId() -> String? { return self.uri } // MARK: - Initialization - // GIF & MP4 uris are downloaded to the phone's disk - for offline purposes - on a separate process. // This can be time consuming, and eat up cpu. The stillImage flag provides a way // to bypass this process when it is unnecessary // checkForUpdateOnly causes this operation to only create UIImage objs if the object has changed on the server. convenience init(uri: String, checkForUpdateOnly: Bool, etag: String?, lastModified: String?) { self.init() self.uri = uri self.checkForUpdateOnly = checkForUpdateOnly self.etag = etag self.lastModified = lastModified } // MARK: - Convenience Variables - private var uri: String? private var checkForUpdateOnly = false private var etag: String? private var lastModified: String? private static let networkQueue: OperationQueue = { var queue = OperationQueue() queue.name = "get.resource.from.uri" queue.maxConcurrentOperationCount = 1 return queue }() // MARK: - Starting and Completing the Operation - override func run() { guard let u = uri, !u.isEmpty else { complete(result: nil) return } getResource(uri: u) } private func complete(result: ImageResponse?) { self.deactivate(result: result) } // MARK: - Operation - // MARK: IMPORTANT: Remember to call complete(..) whether or not the operation was successful. Otherwise, // MARK: it will descrease the bandwidth on the operation queue. The AsynchronousOperation will eventually // MARK: timeout and the queue will recover, however performance will be reduced for a time. - private func getResource(uri: String) { // Select a handler if uri.endsWith(".mp4") { MP4Handler(uri: uri) } else { defaultHandler(uri: uri) } } private func MP4Handler(uri: String) { // TODO: build MP4 resource self.complete(result: nil) } private func defaultHandler(uri: String) { // Ignore stillImage and downloadToDisk only apply to MP4 and GIF handlers. // Download the image guard let url = URL(string: uri) else { complete(result: nil) return } self.makeRequest(url: url) { (data: Data?, etag: String?, lastModified: String?) -> Void in guard let d = data else { // If request was to check for updated content only, this makeRequest is expected to return nil // However, if we wanted some contents and didn't get any, log the error self.complete(result: nil) return } let imageResponse = ImageResponse.web(key: uri, image: GifDecoder.getCoverImage(d)) imageResponse.etag = etag imageResponse.lastModified = lastModified self.complete(result: imageResponse) } } private func makeRequest(url: URL, completion: @escaping (Data?, String?, String?)->Void) { // .ReloadIgnoringLocalCacheData --- Skip the local cache to actually go check with the server. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 5) // TODO: Handle cache-control header - might be a good place to start: http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/ // Check the cache for etag & lastModified. Only set the headers if checkForUpdateOnly is set. if self.checkForUpdateOnly { if let etag = self.etag { request.addValue(etag, forHTTPHeaderField: "If-None-Match") } if let lastModified = self.lastModified { request.addValue(lastModified, forHTTPHeaderField: "If-Modified-Since") } } // make the request to the server // 200 means that the data has changed. // 304 means that the resource is unchanged based on the Etag and last modified at, the copy in the // NSURLCache can be used. // NOTE: NSURLSession does not seem to work in the extension... this call will continue to be use let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: GetResourceFromURI.networkQueue) let task = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let res = response as? HTTPURLResponse { print(res.statusCode) switch (res.statusCode) { // if the response from the server is 200, the resource has been fetched successfully case 200: completion(data, res.allHeaderFields["Etag"] as? String, res.allHeaderFields["Last-Modified"] as? String) // if the response from the server is 304, the resource has not been updated. case 304: completion(nil, nil, nil) default: if (!self.checkForUpdateOnly && (res.statusCode / 100 == 4) && (self.retry < 3)) { Thread.sleep(forTimeInterval: 1) self.retry += 1 self.makeRequest(url: url, completion: completion) } else { completion(nil, nil, nil) } } } else { completion(nil, nil, nil) } } task.resume() } }
mit
0edc1e4a62ca41216f06bc85863d5aee
38.809249
144
0.598229
4.976156
false
false
false
false
gokselkoksal/Lightning
Lightning/Sources/Components/KeyValueStore/Storable.swift
1
3313
// // Storable.swift // Lightning // // Created by Göksel Köksal on 30.11.2019. // Copyright © 2019 GK. All rights reserved. // import Foundation /// Any value that is storable in a key value store. public protocol Storable { associatedtype RawValue var rawValue: RawValue { get } init?(rawValue: RawValue) } // MARK: - Storable + Optional extension Optional: Storable where Wrapped: Storable { public typealias RawValue = Optional<Wrapped.RawValue> public init?(rawValue: Optional<Wrapped.RawValue>) { guard let rawValue = rawValue else { return nil } self = Wrapped(rawValue: rawValue) } public var rawValue: Optional<Wrapped.RawValue> { return self?.rawValue } } // MARK: - Storable + Array extension Array: Storable where Element: Storable { public var rawValue: [Element.RawValue] { return map({ $0.rawValue }) } public init?(rawValue: RawValue) { let value = rawValue.compactMap({ Element(rawValue: $0) }) guard value.count == rawValue.count else { return nil } self = value } } // MARK: - Storable + Dictionary extension Dictionary: Storable where Key: Storable, Value: Storable, Key.RawValue: Hashable { public var rawValue: [Key.RawValue: Value.RawValue] { var rawDictionary: [Key.RawValue: Value.RawValue] = [:] for (key, value) in self { rawDictionary[key.rawValue] = value.rawValue } return rawDictionary } public init?(rawValue rawDictionary: [Key.RawValue: Value.RawValue]) { var dictionary: [Key: Value] = [:] for (rawKey, rawValue) in rawDictionary { guard let key = Key(rawValue: rawKey) else { return nil } guard let value = Value(rawValue: rawValue) else { return nil } dictionary[key] = value } self = dictionary } } // MARK: - Storable + Primitives public protocol StorablePrimitive: Storable { } public extension StorablePrimitive { var rawValue: Self { return self } init?(rawValue: Self) { self = rawValue } } extension Data: StorablePrimitive { } extension String: StorablePrimitive { } extension Date: StorablePrimitive { } extension NSNumber: StorablePrimitive { } extension Int: StorablePrimitive { } extension UInt: StorablePrimitive { } extension Double: StorablePrimitive { } extension Float: StorablePrimitive { } extension Bool: StorablePrimitive { } // MARK: - Storable + URL extension URL: Storable { public var rawValue: String { return absoluteString } public init?(rawValue: String) { self.init(string: rawValue) } } // MARK: - Storable + Codable public protocol StorableCodable: Codable, Storable { static var storeEncoder: JSONEncoder { get } static var storeDecoder: JSONDecoder { get } } extension StorableCodable { public static var storeEncoder: JSONEncoder { return JSONEncoder() } public static var storeDecoder: JSONDecoder { return JSONDecoder() } public var rawValue: Data { do { return try Self.storeEncoder.encode(self) } catch { fatalError("[Codable+Storable] Encoding failed on object of type \(type(of: self))") } } public init?(rawValue: Data) { guard let value = try? Self.storeDecoder.decode(Self.self, from: rawValue) else { return nil } self = value } }
mit
c0e917ecef7dfdfeb51fea0a12579b1b
21.986111
93
0.679154
4.189873
false
false
false
false
NSDengChen/Uber
Uber/Global/DCLocation.swift
1
1672
// // DCLocation.swift // Uber // // Created by dengchen on 15/12/11. // Copyright © 2015年 name. All rights reserved. // import CoreLocation class DCLocation: NSObject,CLLocationManagerDelegate { private var manager:CLLocationManager? internal func startLocation() { if CLLocationManager.locationServicesEnabled(){ manager = CLLocationManager() manager?.delegate = self manager?.desiredAccuracy = kCLLocationAccuracyBest manager?.distanceFilter = 100.0 manager?.requestAlwaysAuthorization() manager?.startUpdatingLocation() } } internal func searchAddress(Location:CLLocation) { let coder = CLGeocoder() coder.reverseGeocodeLocation(Location) { (marks:[CLPlacemark]?, error:NSError?) -> Void in if marks != nil && error == nil { for mark in marks! { DCLog(mark.name!) } }else { print(error) } } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { print(status) } func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { searchAddress(newLocation) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { searchAddress(locations.first!) manager.stopUpdatingLocation() } }
mit
94f12faf065901421d9fc1ae340bac25
25.078125
137
0.594368
6.003597
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAccountPicker/UI/AccountPickerView.swift
1
10879
import Combine import ComposableArchitecture import ComposableArchitectureExtensions import FeatureAccountPickerDomain import Localization import SwiftUI import UIComponentsKit public struct AccountPickerView< BadgeView: View, IconView: View, MultiBadgeView: View, WithdrawalLocksView: View >: View { // MARK: - Internal properties let store: Store<AccountPickerState, AccountPickerAction> @ViewBuilder let badgeView: (AnyHashable) -> BadgeView @ViewBuilder let iconView: (AnyHashable) -> IconView @ViewBuilder let multiBadgeView: (AnyHashable) -> MultiBadgeView @ViewBuilder let withdrawalLocksView: () -> WithdrawalLocksView // MARK: - Private properties @State private var isSearching: Bool = false // MARK: - Init init( store: Store<AccountPickerState, AccountPickerAction>, @ViewBuilder badgeView: @escaping (AnyHashable) -> BadgeView, @ViewBuilder iconView: @escaping (AnyHashable) -> IconView, @ViewBuilder multiBadgeView: @escaping (AnyHashable) -> MultiBadgeView, @ViewBuilder withdrawalLocksView: @escaping () -> WithdrawalLocksView ) { self.store = store self.badgeView = badgeView self.iconView = iconView self.multiBadgeView = multiBadgeView self.withdrawalLocksView = withdrawalLocksView } public init( environment: AccountPickerEnvironment, @ViewBuilder badgeView: @escaping (AnyHashable) -> BadgeView, @ViewBuilder iconView: @escaping (AnyHashable) -> IconView, @ViewBuilder multiBadgeView: @escaping (AnyHashable) -> MultiBadgeView, @ViewBuilder withdrawalLocksView: @escaping () -> WithdrawalLocksView ) { self.init( store: Store( initialState: AccountPickerState( rows: .loading, header: .init(headerStyle: .none, searchText: nil), fiatBalances: [:], cryptoBalances: [:], currencyCodes: [:] ), reducer: accountPickerReducer, environment: environment ), badgeView: badgeView, iconView: iconView, multiBadgeView: multiBadgeView, withdrawalLocksView: withdrawalLocksView ) } // MARK: - Body public var body: some View { StatefulView( store: store.scope(state: \.rows), loadedAction: AccountPickerAction.rowsLoaded, loadingAction: AccountPickerAction.rowsLoading, successAction: LoadedRowsAction.success, failureAction: LoadedRowsAction.failure, loading: { _ in LoadingStateView(title: "") }, success: { successStore in WithViewStore(successStore.scope { $0.content.isEmpty }) { viewStore in if viewStore.state { EmptyStateView( title: LocalizationConstants.AccountPicker.noWallets, subHeading: "", image: ImageAsset.emptyActivity.image ) } else { contentView(successStore: successStore) } } }, failure: { _ in ErrorStateView(title: LocalizationConstants.Errors.genericError) } ) .onAppear { ViewStore(store).send(.subscribeToUpdates) } } struct HeaderScope: Equatable { var header: AccountPickerState.HeaderState var selected: AnyHashable? } @ViewBuilder func contentView( successStore: Store<Rows, SuccessRowsAction> ) -> some View { VStack(spacing: .zero) { WithViewStore(store.scope { HeaderScope(header: $0.header, selected: $0.selected) }) { viewStore in HeaderView( viewModel: viewStore.header.headerStyle, searchText: Binding<String?>( get: { viewStore.header.searchText }, set: { viewStore.send(.search($0)) } ), isSearching: $isSearching ) .onChange(of: viewStore.selected) { _ in isSearching = false viewStore.send(.deselect) } } List { WithViewStore( successStore, removeDuplicates: { $0.identifier == $1.identifier }, content: { viewStore in ForEach(viewStore.content.indexed(), id: \.element.id) { index, row in WithViewStore(self.store.scope { $0.balances(for: row.id) }) { balancesStore in AccountPickerRowView( model: row, send: { action in viewStore.send(action) }, badgeView: badgeView, iconView: iconView, multiBadgeView: multiBadgeView, withdrawalLocksView: withdrawalLocksView, fiatBalance: balancesStore.fiat, cryptoBalance: balancesStore.crypto, currencyCode: balancesStore.currencyCode ) .id(row.id) .onAppear { ViewStore(store) .send(.prefetching(.onAppear(index: index))) } } } } ) } .listStyle(PlainListStyle()) .environment(\.defaultMinListRowHeight, 1) .animation(.easeInOut, value: isSearching) } } } struct AccountPickerView_Previews: PreviewProvider { static let allIdentifier = UUID() static let btcWalletIdentifier = UUID() static let btcTradingWalletIdentifier = UUID() static let ethWalletIdentifier = UUID() static let bchWalletIdentifier = UUID() static let bchTradingWalletIdentifier = UUID() static let fiatBalances: [AnyHashable: String] = [ allIdentifier: "$2,302.39", btcWalletIdentifier: "$2,302.39", btcTradingWalletIdentifier: "$10,093.13", ethWalletIdentifier: "$807.21", bchWalletIdentifier: "$807.21", bchTradingWalletIdentifier: "$40.30" ] static let currencyCodes: [AnyHashable: String] = [ allIdentifier: "USD" ] static let cryptoBalances: [AnyHashable: String] = [ btcWalletIdentifier: "0.21204887 BTC", btcTradingWalletIdentifier: "1.38294910 BTC", ethWalletIdentifier: "0.17039384 ETH", bchWalletIdentifier: "0.00388845 BCH", bchTradingWalletIdentifier: "0.00004829 BCH" ] static let accountPickerRowList: [AccountPickerRow] = [ .accountGroup( AccountPickerRow.AccountGroup( id: allIdentifier, title: "All Wallets", description: "Total Balance" ) ), .button( AccountPickerRow.Button( id: UUID(), text: "See Balance" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: btcWalletIdentifier, title: "BTC Wallet", description: "Bitcoin" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: btcTradingWalletIdentifier, title: "BTC Trading Wallet", description: "Bitcoin" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: ethWalletIdentifier, title: "ETH Wallet", description: "Ethereum" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: bchWalletIdentifier, title: "BCH Wallet", description: "Bitcoin Cash" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: bchTradingWalletIdentifier, title: "BCH Trading Wallet", description: "Bitcoin Cash" ) ) ] static let header = AccountPickerState.HeaderState( headerStyle: .normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: ImageAsset.iconSend.image, tableTitle: "Select a Wallet", searchable: false ), searchText: nil ) @ViewBuilder static func view( rows: LoadingState<Result<Rows, AccountPickerError>> ) -> some View { AccountPickerView( store: Store( initialState: AccountPickerState( rows: rows, header: header, fiatBalances: fiatBalances, cryptoBalances: cryptoBalances, currencyCodes: currencyCodes ), reducer: accountPickerReducer, environment: AccountPickerEnvironment( rowSelected: { _ in }, uxSelected: { _ in }, backButtonTapped: {}, closeButtonTapped: {}, search: { _ in }, sections: { Just(Array(accountPickerRowList)).eraseToAnyPublisher() }, updateSingleAccounts: { _ in .just([:]) }, updateAccountGroups: { _ in .just([:]) }, header: { Just(header.headerStyle).setFailureType(to: Error.self).eraseToAnyPublisher() } ) ), badgeView: { _ in EmptyView() }, iconView: { _ in EmptyView() }, multiBadgeView: { _ in EmptyView() }, withdrawalLocksView: { EmptyView() } ) } static var previews: some View { view(rows: .loaded(next: .success(Rows(content: accountPickerRowList)))) .previewDisplayName("Success") view(rows: .loaded(next: .success(Rows(content: [])))) .previewDisplayName("Empty") view(rows: .loaded(next: .failure(.testError))) .previewDisplayName("Error") view(rows: .loading) .previewDisplayName("Loading") } }
lgpl-3.0
088969a975f17a4544002a2a5b2bad1c
35.263333
111
0.520636
5.725789
false
false
false
false
ChrisLowe-Takor/ALCameraViewController
ALCameraViewController/Views/ALPermissionsView.swift
1
4209
// // ALPermissionsView.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/24. // Copyright (c) 2015 zero. All rights reserved. // import UIKit internal class ALPermissionsView: UIView { let iconView = UIImageView() let titleLabel = UILabel() let descriptionLabel = UILabel() let settingsButton = UIButton() let horizontalPadding: CGFloat = 50 let verticalPadding: CGFloat = 20 let verticalSpacing: CGFloat = 10 required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit() { backgroundColor = UIColor(white: 0.2, alpha: 1) titleLabel.textColor = UIColor.whiteColor() titleLabel.numberOfLines = 0 titleLabel.textAlignment = NSTextAlignment.Center titleLabel.font = UIFont(name: "AppleSDGothicNeo-Light", size: 22) titleLabel.text = LocalizedString("permissions.title") descriptionLabel.textColor = UIColor.lightGrayColor() descriptionLabel.numberOfLines = 0 descriptionLabel.textAlignment = NSTextAlignment.Center descriptionLabel.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 16) descriptionLabel.text = LocalizedString("permissions.description") let icon = UIImage(named: "permissionsIcon", inBundle: NSBundle(forClass: ALCameraViewController.self), compatibleWithTraitCollection: nil)! iconView.image = icon settingsButton.contentEdgeInsets = UIEdgeInsetsMake(6, 12, 6, 12) settingsButton.setTitle(LocalizedString("permissions.settings"), forState: UIControlState.Normal) settingsButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) settingsButton.layer.cornerRadius = 4 settingsButton.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 14) settingsButton.backgroundColor = UIColor(red: 52.0/255.0, green: 183.0/255.0, blue: 250.0/255.0, alpha: 1) settingsButton.addTarget(self, action: "openSettings", forControlEvents: UIControlEvents.TouchUpInside) addSubview(iconView) addSubview(titleLabel) addSubview(descriptionLabel) addSubview(settingsButton) } func openSettings() { if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) { UIApplication.sharedApplication().openURL(appSettings) } } override func layoutSubviews() { super.layoutSubviews() let size = frame.size let maxLabelWidth = size.width - horizontalPadding * 2 let iconSize = iconView.image!.size let titleSize = titleLabel.sizeThatFits(CGSizeMake(maxLabelWidth, CGFloat.max)) let descriptionSize = descriptionLabel.sizeThatFits(CGSizeMake(maxLabelWidth, CGFloat.max)) let settingsSize = settingsButton.sizeThatFits(CGSizeMake(maxLabelWidth, CGFloat.max)) let iconX = size.width/2 - iconSize.width/2 let iconY: CGFloat = size.height/2 - (iconSize.height + verticalSpacing + verticalSpacing + titleSize.height + verticalSpacing + descriptionSize.height)/2; iconView.frame = CGRectMake(iconX, iconY, iconSize.width, iconSize.height) let titleX = size.width/2 - titleSize.width/2 let titleY = iconY + iconSize.height + verticalSpacing + verticalSpacing titleLabel.frame = CGRectMake(titleX, titleY, titleSize.width, titleSize.height) let descriptionX = size.width/2 - descriptionSize.width/2 let descriptionY = titleY + titleSize.height + verticalSpacing descriptionLabel.frame = CGRectMake(descriptionX, descriptionY, descriptionSize.width, descriptionSize.height) let settingsX = size.width/2 - settingsSize.width/2 let settingsY = descriptionY + descriptionSize.height + verticalSpacing settingsButton.frame = CGRectMake(settingsX, settingsY, settingsSize.width, settingsSize.height) } }
mit
d51ecf4273002464ad269bb788c440a3
40.264706
163
0.679734
5.120438
false
false
false
false
Tea-and-Coffee/CollectionView-Sample-Swift
CollectionView-Sample/Model/WEImage.swift
1
673
// // WEImage.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 WEImage{ var height : Int? var link : String? var title : String? var url : String? var width : Int? /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary){ height = dictionary["height"] as? Int link = dictionary["link"] as? String title = dictionary["title"] as? String url = dictionary["url"] as? String width = dictionary["width"] as? Int } }
mit
a72afa042f9695271a753350ed914164
21.4
92
0.699405
3.5
false
false
false
false
leancloud/objc-sdk
AVOS/LeanCloudObjcTests/LCIMClientTestCase.swift
1
21991
// // LCIMClientTestCase.swift // LeanCloudObjcTests // // Created by 黄驿峰 on 2021/12/15. // Copyright © 2021 LeanCloud Inc. All rights reserved. // import Foundation import XCTest @testable import LeanCloudObjc extension LCIMClientTestCase { class SignatureDelegator: NSObject, LCIMSignatureDataSource { var sessionToken: String? func getOpenSignature(client: LCIMClient, completion: @escaping (LCIMSignature?) -> Void) { guard let sessionToken = self.sessionToken else { XCTFail() return } let paasClient = LCPaasClient.sharedInstance() let request = paasClient?.request(withPath: "https://s5vdi3ie.lc-cn-n1-shared.com/1.2/rtm/clients/sign", method: "GET", headers: nil, parameters: ["session_token": sessionToken]) paasClient?.perform(request as URLRequest?, success: { response, responseObject in guard let value = responseObject as? [String: Any], let client_id = value["client_id"] as? String, client_id == client.clientId, let signature = value["signature"] as? String, let timestamp = value["timestamp"] as? Int64, let nonce = value["nonce"] as? String else { XCTFail() return } let ret = LCIMSignature.init() ret.signature = signature ret.timestamp = timestamp ret.nonce = nonce completion(ret) }, failure: { _, _, _ in completion(nil) XCTFail() }) } func client(_ client: LCIMClient, action: LCIMSignatureAction, conversation: LCIMConversation?, clientIds: [String]?, signatureHandler handler: @escaping (LCIMSignature?) -> Void) { if action == .open { getOpenSignature(client: client, completion: handler) } else { XCTFail() } } } } class LCIMClientTestCase: RTMBaseTestCase { func testInit() { do { let invalidID: String = Array<String>.init(repeating: "a", count: 65).joined() let _ = try LCIMClient.init(clientId: invalidID) XCTFail() } catch { } do { let invalidTag: String = "default" let _ = try LCIMClient(clientId: uuid, tag: invalidTag) XCTFail() } catch { } do { let _ = try LCIMClient.init(clientId: uuid) let _ = try LCIMClient.init(clientId: uuid, tag: uuid) } catch { XCTFail("\(error)") } } func testInitWithUser() { let user = LCUser() user.username = uuid user.password = uuid expecting { exp in user.signUpInBackground { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() } } do { let client = try LCIMClient.init(user: user) XCTAssertNotNil(client.user) XCTAssertEqual(client.clientId, user.objectId) } catch { XCTFail("\(error)") } } func testDeinit() { var client: LCIMClient? = try? LCIMClient.init(clientId: uuid, tag: uuid) XCTAssertNotNil(client) weak var wClient: LCIMClient? = client client = nil delay() XCTAssertNil(wClient) } func testOpenAndClose() { let client: LCIMClient! = try? LCIMClient.init(clientId: uuid) XCTAssertNotNil(client) expecting { (exp) in client.open { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) XCTAssertNotNil(client.sessionToken) XCTAssertNotNil(client.sessionTokenExpiration) XCTAssertNil(client.openingCompletion) XCTAssertEqual(client.status, .opened) XCTAssertNotNil(client.connectionDelegator.delegate) exp.fulfill() } } expecting { (exp) in client.open { ret, error in XCTAssertFalse(ret) XCTAssertNotNil(error) exp.fulfill() } } expecting { (exp) in client.close { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) XCTAssertNil(client.sessionToken) XCTAssertNil(client.sessionTokenExpiration) XCTAssertNil(client.openingCompletion) XCTAssertEqual(client.status, .closed) XCTAssertNil(client.connectionDelegator.delegate) exp.fulfill() } } } func testOpenWithSignature() { let user = LCUser() user.username = uuid user.password = uuid expecting { exp in user.signUpInBackground { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() } } guard let objectID = user.objectId, let sessionToken = user.sessionToken else { XCTFail() return } var clientFromUser: LCIMClient! = try? LCIMClient.init(user: user) XCTAssertNotNil(clientFromUser) expecting { (exp) in clientFromUser.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } clientFromUser = nil delay() let signatureDelegator = SignatureDelegator() signatureDelegator.sessionToken = sessionToken let client: LCIMClient! = try? LCIMClient.init(clientId: objectID) XCTAssertNotNil(client) client.signatureDataSource = signatureDelegator expecting { (exp) in client.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } } func testDelegateEvent() { let delegator = LCIMClientDelegator.init() let client = newOpenedClient(clientID: uuid, delegator: delegator) expecting { exp in client.connection.disconnect() delegator.imClientPaused = { imClient, error in XCTAssertEqual(imClient, client) XCTAssertNotNil(error) exp.fulfill() } } expecting(count: 2) { exp in client.connection.testConnect() delegator.imClientResumed = { imClient in XCTAssertEqual(imClient, client) exp.fulfill() } delegator.imClientResuming = { imClient in XCTAssertEqual(imClient, client) exp.fulfill() } } } func testSessionConflict() { let clientID: String = uuid let tag: String = "tag" let installation1: LCInstallation! = LCInstallation.init() installation1.setDeviceTokenHexString(uuid, teamId: "LeanCloud") XCTAssertTrue(installation1.save()) let delegator1 = LCIMClientDelegator.init() let client1: LCIMClient! = try? LCIMClient.init(clientId: clientID, tag: tag, option: nil, installation: installation1) XCTAssertNotNil(client1) client1.delegate = delegator1 expecting { (exp) in client1.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects() LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects() let installation2 = LCInstallation.init() installation2.setDeviceTokenHexString(uuid, teamId: "LeanCloud") XCTAssertTrue(installation2.save()) let delegator2 = LCIMClientDelegator.init() let client2: LCIMClient! = try? LCIMClient.init(clientId: clientID, tag: tag, option: nil, installation: installation2) XCTAssertNotNil(client2) client2.delegate = delegator2 expecting( description: "client2 open success & kick client1 success", count: 2) { exp in client2.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } delegator1.imClientClosed = { imClient, error in XCTAssertNotNil(error) if let error = error as NSError? { XCTAssertEqual(LCIMErrorCode.sessionConflict.rawValue, error.code) } else { XCTFail() } exp.fulfill() } } expecting( description: "client1 resume with deviceToken1 fail", count: 1) { (exp) in client1.open(with: .reopen) { ret, error in if let error = error as NSError? { XCTAssertEqual(LCIMErrorCode.sessionConflict.rawValue, error.code) } else { XCTFail() } exp.fulfill() } } expecting( description: "client1 set deviceToken2 then resume success", count: 1) { (exp) in client1.open(with: .reopen) { ret, error in if let error = error as NSError? { XCTAssertEqual(LCIMErrorCode.sessionConflict.rawValue, error.code) } else { XCTFail() } exp.fulfill() } } installation1.setDeviceTokenHexString(installation2.deviceToken!, teamId: "LeanCloud") XCTAssertTrue(installation1.save()) expecting( description: "client1 set deviceToken2 then resume success", count: 1) { (exp) in client1.open(with: .reopen) { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } } func testSessionTokenExpired() { let delegator = LCIMClientDelegator.init() let client = newOpenedClient(clientID: uuid, tag: nil, delegator: delegator) client.sessionToken = self.uuid client.sessionTokenExpiration = Date(timeIntervalSinceNow: 36000) // var ob: NSObjectProtocol? = nil expecting( description: "Pause -> Resume -> First-Reopen Then session token expired, Final Second-Reopen success", count: 3) { (exp) in delegator.imClientPaused = { imClient, error in XCTAssertEqual(imClient, client) XCTAssertNotNil(error) exp.fulfill() } delegator.imClientResumed = { imClient in XCTAssertEqual(imClient, client) exp.fulfill() } delegator.imClientResuming = { imClient in XCTAssertEqual(imClient, client) exp.fulfill() } // ob = NotificationCenter.default.addObserver( // forName: IMClient.TestSessionTokenExpiredNotification, // object: client, // queue: .main // ) { (notification) in // XCTAssertEqual( // (notification.userInfo?["error"] as? LCError)?.code, // LCError.ServerErrorCode.sessionTokenExpired.rawValue) // exp.fulfill() // } client.connection.disconnect() client.connection.testConnect() } // if let ob = ob { // NotificationCenter.default.removeObserver(ob) // } } // func testReportDeviceToken() { // let application = LCApplication.default // let currentDeviceToken = application.currentInstallation.deviceToken?.value // let client: IMClient = try! IMClient(application: application, ID: uuid, options: []) // delay() // XCTAssertEqual(currentDeviceToken, client.currentDeviceToken) // // let exp = expectation(description: "client report device token success") // exp.expectedFulfillmentCount = 2 // let otherDeviceToken: String = uuid // let ob = NotificationCenter.default.addObserver(forName: IMClient.TestReportDeviceTokenNotification, object: client, queue: OperationQueue.main) { (notification) in // let result = notification.userInfo?["result"] as? RTMConnection.CommandCallback.Result // XCTAssertEqual(result?.command?.cmd, .report) // XCTAssertEqual(result?.command?.op, .uploaded) // exp.fulfill() // } // client.open { (result) in // XCTAssertTrue(result.isSuccess) // client.installation.set(deviceToken: otherDeviceToken, apnsTeamId: "") // exp.fulfill() // } // wait(for: [exp], timeout: timeout) // XCTAssertEqual(otherDeviceToken, client.currentDeviceToken) // NotificationCenter.default.removeObserver(ob) // } func testSessionQuery() { let client1ID = uuid let client2ID = uuid let client1 = newOpenedClient(clientID: client1ID) expecting { exp in client1.queryOnlineClients(inClients: []) { inClients, error in XCTAssertEqual(inClients, []) XCTAssertNil(error) exp.fulfill() } } var set = [String]() for _ in 0...20 { set.append(uuid) } expecting { exp in client1.queryOnlineClients(inClients: set) { inClients, error in XCTAssertNotNil(error) XCTAssertNil(inClients) exp.fulfill() } } expecting { exp in client1.queryOnlineClients(inClients: [client2ID]) { inClients, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertEqual(inClients?.count, 0) exp.fulfill() } } let client2 = newOpenedClient(clientID: client2ID) expecting { exp in client1.queryOnlineClients(inClients: [client2ID]) { inClients, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertEqual(inClients?.count, 1) XCTAssertEqual(inClients?.first, client2.clientId) exp.fulfill() } } } //#if canImport(GRDB) // func testPrepareLocalStorage() { // expecting { (exp) in // let notUseLocalStorageClient = try! IMClient(ID: uuid, options: []) // do { // try notUseLocalStorageClient.prepareLocalStorage(completion: { (_) in }) // XCTFail() // } catch { // XCTAssertTrue(error is LCError) // } // exp.fulfill() // } // // let client = try! IMClient(ID: uuid) // // expecting { (exp) in // try! client.prepareLocalStorage(completion: { (result) in // XCTAssertTrue(Thread.isMainThread) // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // exp.fulfill() // }) // } // } // // func testGetAndLoadStoredConversations() { // expecting { (exp) in // let notUseLocalStorageClient = try! IMClient(ID: uuid, options: []) // do { // try notUseLocalStorageClient.getAndLoadStoredConversations(completion: { (_) in }) // XCTFail() // } catch { // XCTAssertTrue(error is LCError) // } // exp.fulfill() // } // // let client = try! IMClient(ID: uuid) // // expecting { (exp) in // try! client.prepareLocalStorage(completion: { (result) in // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // exp.fulfill() // }) // } // // expecting { (exp) in // try! client.getAndLoadStoredConversations(completion: { (result) in // XCTAssertTrue(Thread.isMainThread) // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // XCTAssertEqual(result.value?.count, 0) // XCTAssertTrue(client.convCollection.isEmpty) // exp.fulfill() // }) // } // // expecting { (exp) in // client.open(completion: { (result) in // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // exp.fulfill() // }) // } // // for _ in 0...1 { // var conv: IMConversation! // // expecting { (exp) in // try! client.createConversation(clientIDs: [uuid], completion: { (result) in // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // conv = result.value // exp.fulfill() // }) // } // // delay(seconds: 0.1) // // expecting { (exp) in // try! conv.refresh(completion: { (result) in // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // exp.fulfill() // }) // } // // delay(seconds: 0.1) // // expecting { (exp) in // let message = IMMessage() // try! message.set(content: .string("test")) // try! conv.send(message: message, completion: { (result) in // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // exp.fulfill() // }) // } // } // // let checker: (IMClient.StoredConversationOrder) -> Void = { order in // self.expecting { (exp) in // try! client.getAndLoadStoredConversations(order: order, completion: { (result) in // XCTAssertTrue(result.isSuccess) // XCTAssertNil(result.error) // XCTAssertEqual(result.value?.count, 2) // switch order { // case let .lastMessageSentTimestamp(descending: descending): // let firstTimestamp = result.value?.first?.lastMessage?.sentTimestamp // let lastTimestamp = result.value?.last?.lastMessage?.sentTimestamp // if descending { // XCTAssertGreaterThanOrEqual(firstTimestamp!, lastTimestamp!) // } else { // XCTAssertGreaterThanOrEqual(lastTimestamp!, firstTimestamp!) // } // case let .createdTimestamp(descending: descending): // let firstTimestamp = result.value?.first?.createdAt?.timeIntervalSince1970 // let lastTimestamp = result.value?.last?.createdAt?.timeIntervalSince1970 // if descending { // XCTAssertGreaterThanOrEqual(firstTimestamp!, lastTimestamp!) // } else { // XCTAssertGreaterThanOrEqual(lastTimestamp!, firstTimestamp!) // } // case let .updatedTimestamp(descending: descending): // let firstTimestamp = result.value?.first?.updatedAt?.timeIntervalSince1970 // let lastTimestamp = result.value?.last?.updatedAt?.timeIntervalSince1970 // if descending { // XCTAssertGreaterThanOrEqual(firstTimestamp!, lastTimestamp!) // } else { // XCTAssertGreaterThanOrEqual(lastTimestamp!, firstTimestamp!) // } // } // exp.fulfill() // }) // } // } // // checker(.lastMessageSentTimestamp(descending: true)) // checker(.lastMessageSentTimestamp(descending: false)) // checker(.updatedTimestamp(descending: true)) // checker(.updatedTimestamp(descending: false)) // checker(.createdTimestamp(descending: true)) // checker(.createdTimestamp(descending: false)) // // XCTAssertEqual(client.convCollection.count, 2) // } //#endif }
apache-2.0
51c300d4432044a5d43135378e73e68e
34.688312
190
0.507142
5.114937
false
false
false
false
17thDimension/AudioKit
Tests/Tests/AKThreePoleLowpassFilter.swift
2
2090
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/26/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let phasor = AKPhasor() auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:phasor) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let distortion = AKLine(firstPoint: 0.1.ak, secondPoint: 0.9.ak, durationBetweenPoints: testDuration.ak) let cutoffFrequency = AKLine(firstPoint: 300.ak, secondPoint: 3000.ak, durationBetweenPoints: testDuration.ak) let resonance = AKLine(firstPoint: 0.ak, secondPoint: 1.ak, durationBetweenPoints: testDuration.ak) let threePoleLowpassFilter = AKThreePoleLowpassFilter(input: audioSource) threePoleLowpassFilter.distortion = distortion threePoleLowpassFilter.cutoffFrequency = cutoffFrequency threePoleLowpassFilter.resonance = resonance setAudioOutput(threePoleLowpassFilter) enableParameterLog( "Distortion = ", parameter: threePoleLowpassFilter.distortion, timeInterval:0.1 ) enableParameterLog( "Cutoff Frequency = ", parameter: threePoleLowpassFilter.cutoffFrequency, timeInterval:0.1 ) enableParameterLog( "Resonance = ", parameter: threePoleLowpassFilter.resonance, timeInterval:0.1 ) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() let manager = AKManager.sharedManager() while(manager.isRunning) {} //do nothing println("Test complete!")
lgpl-3.0
514572abae435985ad2467d108de1e0b
26.142857
118
0.68756
4.75
false
true
false
false
BruceFight/JHB_HUDView
JHB_HUDView/JHB_HUDView.swift
1
14580
/********************** JHB_HUDView.swift ***********************/ /******* (JHB) ************************************************/ /******* Created by Leon_pan on 16/6/12. ***********************/ /******* Copyright © 2016年 CoderBala. All rights reserved.*****/ /********************** JHB_HUDView.swift ***********************/ /// --- --- --- <= 0.1.5 --- --- --- /// /* Points For Attention: Well, I want to say thanks for your support and concern firstly ! And at present,You can get the follows methods from the bottom to integrate into your projects according to your demands .In fact, there are two main parts : the regular-part and diy-part. In regular-part ,you can use most effects that comes from system, it is the initial part I designed, cooperated with follows nine display-dismiss types ! And then I optimized some disadvantages , and expaned five methods to display-sidmiss diy-image(you'd better let it be lower or equal to imageView's size of 50×50) type of HUD,and it's a unique style belong to 'JHB_HUDView'. So you'd better make a distinction between the two parts! At the same times, the good news is that it can supprot the screen-rotation ,just including 'Portrait','PortraitUpsideDown','LandscapeLeft','LandscapeRight'. For example , if your project initialed with Portrait-type, it will also show in center of the screen ,and change appropriate angle by-itself,but if your project initialed with other types , the screen rotation will be limited except the HUD dismissed . At last but not least , You need let your 'Controller' inherits 'JHB_HUDTopViewController', and then it can be run ! At last, I will tell you that I hope you can support me always ,becasue it's main reason I can go down all the way .And I will keep improving and perfecting it ,Thanks for reading . */ /// --- --- --- > 0.1.5 --- --- --- /// /* New For Attention: Before 0.1.5,no matter normal-hud-type or diy-hud-type,This part of coreView is showed on another new Window ,So it's abrupted from Your coreView which's on Your coreWindo.So ,if a process that decide the show-HUD progress is seized up,it means the whole APP-progress is stopped. But ,it's also a good way to suit to the screen-rotation.So ,after 0.1.5, you can use 'ifCanBeMoved' to control that if it can be dismissed by longpress-gesture. After 0.1.5 ,it's expended with another system that can be added on A custom-view for each method.So its also can be controlled by your custom object.And the hide of the func is'n changed. */ import UIKit /* There are nine 'HUDTypes' for coreview-hud's display provided,including 'Deafault','ShowImmediately','ShowSlightly','ShowFromBottomToTop','ShowFromTopToBottom','ShowFromLeftToRight','ShowFromRightToLeft','ScaleFromInsideToOutside','ScaleFromOutsideToInside' . */ public enum HUDType { /**Default**/ case kHUDTypeDefaultly/*默认*/ /**Show And Hide**/ case kHUDTypeShowImmediately/*马上出现,没有延时*/ case kHUDTypeShowSlightly/*淡入淡出,延时效果*/ /**Top And Bottom**/ case kHUDTypeShowFromBottomToTop/*从底部到顶部并有默认效果*/ case kHUDTypeShowFromTopToBottom/*从顶部到底部并有默认效果*/ /**Left And Right**/ case kHUDTypeShowFromLeftToRight/*从左边到右边并有默认效果*/ case kHUDTypeShowFromRightToLeft/*从右边到左边并有默认效果*/ /**Inside And Outside**/ case kHUDTypeScaleFromInsideToOutside/*从内部向外部放大*/ case kHUDTypeScaleFromOutsideToInside/*从外部向内部缩小*/ } /*********➕NewAddition➕NewAddition➕NewAddition➕*********/ /* There are four 'DiyHUDTypes' for diy-image's display provided,including 'Deafault','RotateWithY','RotateWithZ','ShakeWithX' . */ public enum DiyHUDType { case kDiyHUDTypeDefault/*默认*/ case kDiyHUDTypeRotateWithY/*Y轴旋转*/ case kDiyHUDTypeRotateWithZ/*Z轴旋转*/ case kDiyHUDTypeShakeWithX/*Y轴左右摇晃*/ } var hud = JHB_HUDManager() var diyHud = JHB_HUDDiyManager() open class JHB_HUDView:NSObject{ /// --- Decide HUD-process can be stopped by Long-tap-gesture. open class func ifCanBeMoved(bool:Bool) { hud.ifBeMoved(bool:bool) diyHud.ifBeMoved(bool:bool) } /*************✅显示进程************/ /// --- new window --- /// open class func showProgress(){ hud = JHB_HUDManager.init() hud.showProgress(ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgress(to:UIView){ hud = JHB_HUDManager.init() hud.showProgress(ifCustom:true,to:to) } /***********✅显示进程+HUDType**********/ /// --- new window --- /// open class func showProgressWithType(_ HudType:HUDType){ hud = JHB_HUDManager.init() hud.showProgressWithType(HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressWithType(_ HudType:HUDType,to:UIView){ hud = JHB_HUDManager.init() hud.showProgressWithType(HudType,ifCustom:false, to: to) } /**********✅显示进程及信息************/ /// --- new window --- /// open class func showProgressMsg(_ msg:NSString) { hud = JHB_HUDManager.init() hud.showProgressMsgs(msg,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressMsg(_ msg:NSString,to:UIView) { hud = JHB_HUDManager.init() hud.showProgressMsgs(msg,ifCustom:true,to:to) } /*********✅显示进程及信息+HUDType*********/ /// --- new window --- /// open class func showProgressMsgWithType(_ msg:NSString,HudType:HUDType){ hud = JHB_HUDManager.init() hud.showProgressMsgsWithType(msg, HudType: HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressMsgWithType(_ msg:NSString,HudType:HUDType,to:UIView){ hud = JHB_HUDManager.init() hud.showProgressMsgsWithType(msg, HudType: HudType,ifCustom:true,to:to) } /***********✅显示单行信息(自行执行Hide)**********/ /// --- new window --- /// open class func showMsg(_ msg:NSString) { hud = JHB_HUDManager.init() hud.show(msg, ifCustom: false, to: UIView()) } /// --- custom --- /// open class func jhb_showMsg(_ msg:NSString,to:UIView) { hud = JHB_HUDManager.init() hud.show(msg, ifCustom: true, to: to) } /********✅显示单行信息(自行执行Hide)+HUDType**********/ /// --- new window --- /// open class func showMsgWithType(_ msg:NSString,HudType:HUDType) { hud = JHB_HUDManager.init() hud.showWithType(msg, HudType: HudType, ifCustom: false, to: UIView()) } /// --- custom --- /// open class func jhb_showMsgWithType(_ msg:NSString,HudType:HUDType,to:UIView) { hud = JHB_HUDManager.init() hud.showWithType(msg, HudType: HudType, ifCustom: true, to: to) } /************✅显示多行信息(自行执行Hide)************/ /// --- new window --- /// open class func showMsgMultiLine(_ msg:NSString, coreInSet: CGFloat, labelInSet: CGFloat, delay: Double) { hud = JHB_HUDManager.init() hud.showMultiLine(msg, coreInSet: coreInSet, labelInSet: labelInSet, delay: delay,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showMsgMultiLine(_ msg:NSString, coreInSet: CGFloat, labelInSet: CGFloat, delay: Double,to:UIView) { hud = JHB_HUDManager.init() hud.showMultiLine(msg, coreInSet: coreInSet, labelInSet: labelInSet, delay: delay,ifCustom:true,to:to) } /*********✅显示多行信息(自行执行Hide)+HUDType***********/ /// --- new window --- /// open class func showMsgMultiLineWithType(_ msg:NSString, coreInSet: CGFloat, labelInSet: CGFloat, delay: Double ,HudType:HUDType) { hud = JHB_HUDManager.init() hud.showMultiLineWithType(msg, coreInSet: coreInSet, labelInSet: labelInSet, delay: delay, HudType: HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showMsgMultiLineWithType(_ msg:NSString, coreInSet: CGFloat, labelInSet: CGFloat, delay: Double ,HudType:HUDType,to:UIView) { hud = JHB_HUDManager.init() hud.showMultiLineWithType(msg, coreInSet: coreInSet, labelInSet: labelInSet, delay: delay, HudType: HudType,ifCustom:true,to:to) } /*********✅HIDE隐藏并移除(Pre + HUDType)**********/ /* In current method lists ,there are two methods can hide your HUD, but it is different from each other , this one can only be used when you created HUD without diy-image */ open class func hideProgress() { hud.hideProgress() } /*********➕NewAddition➕NewAddition➕NewAddition➕*********/ /* There are four new methods can be used according to your demand , And those are basic of previous methods , Like these on the top , So each of method also has the param - 'HudType',as you know ,is shows the coreview display and dismiss's type.and except for that, there are some other params you should know well.So then I will give you the detail of each of them !And attention that if you want wo show a group of images ,there will be no 'diyHudType' can be selected ! */ /**********✅自定义展示图片+HUDType*********/ /* -- img:the image file that you want to show ,it can be your program's logo or company's logo, etc.And attention that you can just delivery the image's name without suffix . -- diySpeed:if you set animation for your diy-image ,this param will limit your animation-speed . -- diyHudType:it comes from the enum 'DiyHUDType',it improve four types of diy-image's animation that you can choose . */ /// --- new window --- /// open class func showProgressOfDIYTypeWith(_ img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType) { diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressWithType(img,diySpeed:diySpeed, diyHudType: diyHudType, HudType: HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressOfDIYTypeWith(_ img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType,to:UIView) { diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressWithType(img,diySpeed:diySpeed, diyHudType: diyHudType, HudType: HudType,ifCustom:true,to:to) } /**********✅自定义展示图片+AnimationType+HUDType*********/ /* -- imgsName:if you want show animation created by a group of images,you can pinpoint the images' main name that can be without suffix . -- imgsNumber:this param will let it knows that how many images will be showed ,it can not be null . -- diySpeed:this param will limit your animation-speed. */ /// --- new window --- /// open class func showProgressOfDIYTypeWithAnimation(_ imgsName:NSString,imgsNumber:NSInteger,diySpeed:TimeInterval, HudType:HUDType){ diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressAnimated(imgsName,imgsNumber:imgsNumber,diySpeed:diySpeed, HudType:HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressOfDIYTypeWithAnimation(_ imgsName:NSString,imgsNumber:NSInteger,diySpeed:TimeInterval, HudType:HUDType,to:UIView){ diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressAnimated(imgsName,imgsNumber:imgsNumber,diySpeed:diySpeed, HudType:HudType,ifCustom:true,to:to) } /**********✅自定义展示图片和信息+HUDType**********/ /* -- msg:display the message that you need to show . -- img:the image file that you want to show ,it can be your program's logo or company's logo, etc.And attention that you can just delivery the image's name without suffix . -- diySpeed:if you set animation for your diy-image ,this param will limit your animation-speed . -- diyHudType:it comes from the enum 'DiyHUDType',it improve four types of diy-image's animation that you can choose . */ /// --- new window --- /// open class func showProgressMsgOfDIYTypeWith(_ msg:NSString,img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType) { diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressMsgsWithType(msg,img:img,diySpeed:diySpeed,diyHudType:diyHudType, HudType: HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressMsgOfDIYTypeWith(_ msg:NSString,img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType,to:UIView) { diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressMsgsWithType(msg,img:img,diySpeed:diySpeed,diyHudType:diyHudType, HudType: HudType,ifCustom:true,to:to) } /*********✅自定义展示图片和信息+AnimationType+HUDType**********/ /* -- msg:display the message that you need to show . -- imgsName:if you want show animation created by a group of images,you can pinpoint the images' main name that can be without suffix . -- imgsNumber:this param will let it knows that how many images will be showed ,it can not be null . -- diySpeed:if you set animation for your diy-image ,this param will limit your animation-speed . */ /// --- new window --- /// open class func showProgressMsgOfDIYTypeWithAnimation(_ msg:NSString,imgsName:NSString,imgsNumber:NSInteger, diySpeed:CFTimeInterval, HudType:HUDType) { diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressMsgsAnimated(msg as NSString,imgsName:imgsName,imgsNumber:imgsNumber,diySpeed:diySpeed, HudType:HudType,ifCustom:false,to:UIView()) } /// --- custom --- /// open class func jhb_showProgressMsgOfDIYTypeWithAnimation(_ msg:NSString,imgsName:NSString,imgsNumber:NSInteger, diySpeed:CFTimeInterval, HudType:HUDType,to:UIView) { diyHud = JHB_HUDDiyManager.init() diyHud.showDIYProgressMsgsAnimated(msg as NSString,imgsName:imgsName,imgsNumber:imgsNumber,diySpeed:diySpeed, HudType:HudType,ifCustom:true,to:to) } /*********✅自定义类型HIDE隐藏并移除+HUDType**********/ /* In current method lists ,there are two methods can hide your HUD, but it is different from each other , this one can only be used when you created diy-image-type HUD */ open class func hideProgressOfDIYType() { diyHud.hideProgress() } }
mit
121fb0f80270d474ebd79edbd3b6674c
55.031746
812
0.670609
3.646694
false
false
false
false
plu/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/iOSRunner.swift
1
6851
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBSimulatorControl import FBDeviceControl extension CommandResultRunner { static func unimplementedActionRunner(_ action: Action, target: FBiOSTarget, format: FBiOSTargetFormat) -> Runner { let (eventName, maybeSubject) = action.reportable var actionMessage = eventName.rawValue if let subject = maybeSubject { actionMessage += " \(subject.description)" } let message = "Action \(actionMessage) is unimplemented for target \(format.format(target))" return CommandResultRunner(result: CommandResult.failure(message)) } } struct iOSActionProvider { let context: iOSRunnerContext<(Action, FBiOSTarget, iOSReporter)> func makeRunner() -> Runner? { let (action, target, reporter) = self.context.value switch action { case .diagnose(let query, let format): return DiagnosticsRunner(reporter, query, query, format) case .install(let appPath, let codeSign): return iOSTargetRunner.simple(reporter, .install, ControlCoreSubject(appPath as NSString)) { let (extractedAppPath, cleanupDirectory) = try FBApplicationDescriptor.findOrExtract(atPath: appPath) if codeSign { try FBCodesignProvider.codeSignCommandWithAdHocIdentity().recursivelySignBundle(atPath: extractedAppPath) } try target.installApplication(withPath: extractedAppPath) if let cleanupDirectory = cleanupDirectory { try? FileManager.default.removeItem(at: cleanupDirectory) } } case .uninstall(let appBundleID): return iOSTargetRunner.simple(reporter, .uninstall, ControlCoreSubject(appBundleID as NSString)) { try target.uninstallApplication(withBundleID: appBundleID) } case .core(let action): return iOSTargetRunner.core(reporter, action.eventName, target, action) case .listApps: return iOSTargetRunner.simple(reporter, nil, ControlCoreSubject(target as! ControlCoreValue)) { let subject = ControlCoreSubject(target.installedApplications().map { $0.jsonSerializableRepresentation() } as NSArray) reporter.reporter.reportSimple(.listApps, .discrete, subject) } case .record(let record): switch record { case .start(let maybePath): return iOSTargetRunner.handled(reporter, nil, record) { return try target.startRecording(toFile: maybePath) } case .stop: return iOSTargetRunner.simple(reporter, nil, record) { try target.stopRecording() } } case .stream(let maybeOutput): return iOSTargetRunner.handled(reporter, .stream, ControlCoreSubject(target as! ControlCoreValue)) { let stream = try target.createStream() if let output = maybeOutput { try stream.startStreaming(output.makeWriter()) } else { let attributes = try stream.streamAttributes() reporter.reportValue(.stream, .discrete, attributes) } return stream } case .terminate(let bundleID): return iOSTargetRunner.simple(reporter, .terminate, ControlCoreSubject(bundleID as NSString)) { try target.killApplication(withBundleID: bundleID) } default: return nil } } } struct iOSTargetRunner : Runner { let reporter: iOSReporter let name: EventName? let subject: EventReporterSubject let action:(Void)throws -> FBTerminationHandle? private init(reporter: iOSReporter, name: EventName?, subject: EventReporterSubject, action: @escaping (Void) throws -> FBTerminationHandle?) { self.reporter = reporter self.name = name self.subject = subject self.action = action } static func simple(_ reporter: iOSReporter, _ name: EventName?, _ subject: EventReporterSubject, _ action: @escaping (Void) throws -> Void) -> iOSTargetRunner { return iOSTargetRunner(reporter: reporter, name: name, subject: subject) { try action() return nil } } static func core(_ reporter: iOSReporter, _ name: EventName?, _ target: FBiOSTarget, _ action: FBiOSTargetAction) -> iOSTargetRunner { return iOSTargetRunner(reporter: reporter, name: name, subject: ControlCoreSubject(action as! ControlCoreValue)) { return try action.runAction(target: target, reporter: reporter.reporter) } } static func handled(_ reporter: iOSReporter, _ name: EventName?, _ subject: EventReporterSubject, _ action: @escaping (Void) throws -> FBTerminationHandle?) -> iOSTargetRunner { return iOSTargetRunner(reporter: reporter, name: name, subject: subject, action: action) } func run() -> CommandResult { do { if let name = self.name { self.reporter.report(name, .started, self.subject) } var handles: [FBTerminationHandle] = [] if let handle = try self.action() { handles = [handle] } if let name = self.name { self.reporter.report(name, .ended, self.subject) } return CommandResult(outcome: .success(nil), handles: handles) } catch let error as NSError { return .failure(error.description) } catch let error as JSONError { return .failure(error.description) } catch { return .failure("Unknown Error") } } } private struct DiagnosticsRunner : Runner { let reporter: iOSReporter let subject: ControlCoreValue let query: FBDiagnosticQuery let format: DiagnosticFormat init(_ reporter: iOSReporter, _ subject: ControlCoreValue, _ query: FBDiagnosticQuery, _ format: DiagnosticFormat) { self.reporter = reporter self.subject = subject self.query = query self.format = format } func run() -> CommandResult { reporter.reportValue(.diagnose, .started, query) let diagnostics = self.fetchDiagnostics() reporter.reportValue(.diagnose, .ended, query) let subjects: [EventReporterSubject] = diagnostics.map { diagnostic in return SimpleSubject( .diagnostic, .discrete, ControlCoreSubject(diagnostic) ) } return .success(CompositeSubject(subjects)) } func fetchDiagnostics() -> [FBDiagnostic] { let diagnostics = self.reporter.target.diagnostics let format = self.format return diagnostics.perform(query).map { diagnostic in switch format { case .CurrentFormat: return diagnostic case .Content: return FBDiagnosticBuilder(diagnostic: diagnostic).readIntoMemory().build() case .Path: return FBDiagnosticBuilder(diagnostic: diagnostic).writeOutToFile().build() } } } }
bsd-3-clause
b4e6fef87a3fb6a3c584adb1add30afc
36.032432
179
0.6926
4.388853
false
false
false
false
DMeechan/Rick-and-Morty-Soundboard
Rick and Morty Soundboard/Pods/Eureka/Source/Rows/Common/FieldRow.swift
2
17535
// FieldRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol InputTypeInitiable { init?(string stringValue: String) } public protocol FieldRowConformance: FormatterConformance { var textFieldPercentage: CGFloat? { get set } var placeholder: String? { get set } var placeholderColor: UIColor? { get set } } extension Int: InputTypeInitiable { public init?(string stringValue: String) { self.init(stringValue, radix: 10) } } extension Float: InputTypeInitiable { public init?(string stringValue: String) { self.init(stringValue) } } extension String: InputTypeInitiable { public init?(string stringValue: String) { self.init(stringValue) } } extension URL: InputTypeInitiable {} extension Double: InputTypeInitiable { public init?(string stringValue: String) { self.init(stringValue) } } open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell { /// A formatter to be used to format the user's input open var formatter: Formatter? /// If the formatter should be used while the user is editing the text. open var useFormatterDuringInput = false open var useFormatterOnDidBeginEditing: Bool? public required init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let v = value else { return nil } guard let formatter = self.formatter else { return String(describing: v) } if (self.cell.textInput as? UIView)?.isFirstResponder == true { return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v) } return formatter.string(for: v) } } } open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell { /// Configuration for the keyboardReturnType of this row open var keyboardReturnType: KeyboardReturnTypeConfiguration? /// The percentage of the cell that should be occupied by the textField open var textFieldPercentage: CGFloat? /// The placeholder for the textField open var placeholder: String? /// The textColor for the textField's placeholder open var placeholderColor: UIColor? public required init(tag: String?) { super.init(tag: tag) } } /** * Protocol for cells that contain a UITextField */ public protocol TextInputCell { var textInput: UITextInput { get } } public protocol TextFieldCell: TextInputCell { var textField: UITextField! { get } } extension TextFieldCell { public var textInput: UITextInput { return textField } } open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable { @IBOutlet public weak var textField: UITextField! @IBOutlet public weak var titleLabel: UILabel? fileprivate var observingTitleText = false private var awakeFromNibCalled = false open var dynamicConstraints = [NSLayoutConstraint]() public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { let textField = UITextField() self.textField = textField textField.translatesAutoresizingMaskIntoConstraints = false super.init(style: style, reuseIdentifier: reuseIdentifier) titleLabel = self.textLabel titleLabel?.translatesAutoresizingMaskIntoConstraints = false titleLabel?.setContentHuggingPriority(500, for: .horizontal) titleLabel?.setContentCompressionResistancePriority(1000, for: .horizontal) contentView.addSubview(titleLabel!) contentView.addSubview(textField) NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } guard me.observingTitleText else { return } me.titleLabel?.removeObserver(me, forKeyPath: "text") me.observingTitleText = false } NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } guard !me.observingTitleText else { return } me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) me.observingTitleText = true } NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in self?.titleLabel = self?.textLabel self?.setNeedsUpdateConstraints() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func awakeFromNib() { super.awakeFromNib() awakeFromNibCalled = true } deinit { textField?.delegate = nil textField?.removeTarget(self, action: nil, for: .allEvents) guard !awakeFromNibCalled else { return } if observingTitleText { titleLabel?.removeObserver(self, forKeyPath: "text") } imageView?.removeObserver(self, forKeyPath: "image") NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil) } open override func setup() { super.setup() selectionStyle = .none if !awakeFromNibCalled { titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) observingTitleText = true imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil) } textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged) } open override func update() { super.update() detailTextLabel?.text = nil if !awakeFromNibCalled { if let title = row.title { textField.textAlignment = title.isEmpty ? .left : .right textField.clearButtonMode = title.isEmpty ? .whileEditing : .never } else { textField.textAlignment = .left textField.clearButtonMode = .whileEditing } } textField.delegate = self textField.text = row.displayValueFor?(row.value) textField.isEnabled = !row.isDisabled textField.textColor = row.isDisabled ? .gray : .black textField.font = .preferredFont(forTextStyle: .body) if let placeholder = (row as? FieldRowConformance)?.placeholder { if let color = (row as? FieldRowConformance)?.placeholderColor { textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color]) } else { textField.placeholder = (row as? FieldRowConformance)?.placeholder } } if row.isHighlighted { textLabel?.textColor = tintColor } } open override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textField?.canBecomeFirstResponder == true } open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool { return textField?.becomeFirstResponder() ?? false } open override func cellResignFirstResponder() -> Bool { return textField?.resignFirstResponder() ?? true } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let obj = object as AnyObject? if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey], ((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) && (changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue { setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } // MARK: Helpers open func customConstraints() { guard !awakeFromNibCalled else { return } contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views: [String: AnyObject] = ["textField": textField] dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: views) if let label = titleLabel, let text = label.text, !text.isEmpty { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["titleLabel": label]) dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0)) } if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["label"] = titleLabel dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-[textField]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .equal : .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views) } } else { if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["label"] = titleLabel dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-[textField]-|", options: [], metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .equal : .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views) } } contentView.addConstraints(dynamicConstraints) } open override func updateConstraints() { customConstraints() super.updateConstraints() } open func textFieldDidChange(_ textField: UITextField) { guard let textValue = textField.text else { row.value = nil return } guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else { row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) return } if fieldRow.useFormatterDuringInput { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) { row.value = value.pointee as? T guard var selStartPos = textField.selectedTextRange?.start else { return } let oldVal = textField.text textField.text = row.displayValueFor?(row.value) selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos) return } } else { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) { row.value = value.pointee as? T } else { row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) } } } // MARK: Helpers private func displayValue(useFormatter: Bool) -> String? { guard let v = row.value else { return nil } if let formatter = (row as? FormatterConformance)?.formatter, useFormatter { return textField?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v) } return String(describing: v) } // MARK: TextFieldDelegate open func textFieldDidBeginEditing(_ textField: UITextField) { formViewController()?.beginEditing(of: self) formViewController()?.textInputDidBeginEditing(textField, cell: self) if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput { textField.text = displayValue(useFormatter: true) } else { textField.text = displayValue(useFormatter: false) } } open func textFieldDidEndEditing(_ textField: UITextField) { formViewController()?.endEditing(of: self) formViewController()?.textInputDidEndEditing(textField, cell: self) textFieldDidChange(textField) textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil) } open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true } open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true } open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true } open func textFieldShouldClear(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldClear(textField, cell: self) ?? true } open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true } }
apache-2.0
b19402ef066c4e8e166992ffbe8f0b0a
44.310078
204
0.651896
5.474555
false
false
false
false
coach-plus/ios
CoachPlus/ui/tableheader/ParticipationTableHeaderView.swift
1
2798
// // ParticipationTableHeaderView.swift // CoachPlus // // Created by Maurice Breit on 23.06.18. // Copyright © 2018 Mathandoro GbR. All rights reserved. // import UIKit import NibDesignable import SwiftIcons class ParticipationTableHeaderView: NibDesignable { @IBOutlet weak var titleL: UILabel! @IBOutlet weak var unknownL: UILabel! @IBOutlet weak var yesL: UILabel! @IBOutlet weak var noL: UILabel! override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var participations = [ParticipationItem]() var eventIsInPast: Bool = false func initLabels() { self.unknownL.text = "" self.yesL.text = "" self.noL.text = "" } func setTitle(title: String) { self.titleL.text = title } func setLabels(participations: [ParticipationItem]?) { guard participations != nil else { self.initLabels() return } self.participations = participations! self.showParticipationNumbers() } func showParticipationNumbers() { let unknownCount = self.participations.filter { $0.participation == nil || $0.participation!.getValue(eventIsInPast: self.eventIsInPast) == nil }.count let yesCount = self.participations.filter { $0.participation != nil && $0.participation!.getValue(eventIsInPast: self.eventIsInPast) == true }.count let noCount = self.participations.filter { $0.participation != nil && $0.participation!.getValue(eventIsInPast: self.eventIsInPast) == false }.count self.setLabel(label: self.unknownL, icon: .fontAwesomeSolid(.questionCircle), count: unknownCount, iconColor: UIColor.coachPlusBlue) self.setLabel(label: self.yesL, icon: .fontAwesomeSolid(.checkCircle), count: yesCount, iconColor: UIColor.coachPlusParticipationYesColor) self.setLabel(label: self.noL, icon: .fontAwesomeSolid(.timesCircle), count: noCount, iconColor: UIColor.coachPlusParticipationNoColor) if (unknownCount == 0) { self.unknownL.isHidden = true } else { self.unknownL.isHidden = false } } func setLabel(label: UILabel, icon: FontType, count: Int, iconColor: UIColor) { let color = self.titleL.textColor label.setIcon(prefixText: "", prefixTextColor: color!, icon: icon, iconColor: iconColor, postfixText:" \(count)", postfixTextColor: color!, size: 15, iconSize: 15) } func refresh() { self.showParticipationNumbers() } }
mit
e3189e719528437a16f3e9a82f8212e0
29.736264
171
0.620665
4.370313
false
false
false
false
iwantooxxoox/CVCalendar
CVCalendar/CVCalendarDayView.swift
8
19322
// // CVCalendarDayView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarDayView: UIView { // MARK: - Public properties public let weekdayIndex: Int! public weak var weekView: CVCalendarWeekView! public var date: CVDate! public var dayLabel: UILabel! public var circleView: CVAuxiliaryView? public var topMarker: CALayer? public var dotMarkers = [CVAuxiliaryView?]() public var isOut = false public var isCurrentDay = false public weak var monthView: CVCalendarMonthView! { get { var monthView: MonthView! if let weekView = weekView, let activeMonthView = weekView.monthView { monthView = activeMonthView } return monthView } } public weak var calendarView: CVCalendarView! { get { var calendarView: CVCalendarView! if let weekView = weekView, let activeCalendarView = weekView.calendarView { calendarView = activeCalendarView } return calendarView } } public override var frame: CGRect { didSet { if oldValue != frame { circleView?.setNeedsDisplay() topMarkerSetup() preliminarySetup() supplementarySetup() } } } public override var hidden: Bool { didSet { userInteractionEnabled = hidden ? false : true } } // MARK: - Initialization public init(weekView: CVCalendarWeekView, weekdayIndex: Int) { self.weekView = weekView self.weekdayIndex = weekdayIndex if let size = weekView.calendarView.dayViewSize { let hSpace = weekView.calendarView.appearance.spaceBetweenDayViews! let x = (CGFloat(weekdayIndex - 1) * (size.width + hSpace)) + (hSpace/2) super.init(frame: CGRectMake(x, 0, size.width, size.height)) } else { super.init(frame: CGRectZero) } date = dateWithWeekView(weekView, andWeekIndex: weekdayIndex) labelSetup() setupDotMarker() topMarkerSetup() if (frame.width > 0) { preliminarySetup() supplementarySetup() } if !calendarView.shouldShowWeekdaysOut && isOut { hidden = true } } public func dateWithWeekView(weekView: CVCalendarWeekView, andWeekIndex index: Int) -> CVDate { func hasDayAtWeekdayIndex(weekdayIndex: Int, weekdaysDictionary: [Int : [Int]]) -> Bool { for key in weekdaysDictionary.keys { if key == weekdayIndex { return true } } return false } var day: Int! let weekdaysIn = weekView.weekdaysIn if let weekdaysOut = weekView.weekdaysOut { if hasDayAtWeekdayIndex(weekdayIndex, weekdaysOut) { isOut = true day = weekdaysOut[weekdayIndex]![0] } else if hasDayAtWeekdayIndex(weekdayIndex, weekdaysIn!) { day = weekdaysIn![weekdayIndex]![0] } } else { day = weekdaysIn![weekdayIndex]![0] } if day == monthView.currentDay && !isOut { let dateRange = Manager.dateRange(monthView.date) let currentDateRange = Manager.dateRange(NSDate()) if dateRange.month == currentDateRange.month && dateRange.year == currentDateRange.year { isCurrentDay = true } } let dateRange = Manager.dateRange(monthView.date) let year = dateRange.year let week = weekView.index + 1 var month = dateRange.month if isOut { day > 20 ? month-- : month++ } return CVDate(day: day, month: month, week: week, year: year) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Subviews setup extension CVCalendarDayView { public func labelSetup() { let appearance = calendarView.appearance dayLabel = UILabel() dayLabel!.text = String(date.day) dayLabel!.textAlignment = NSTextAlignment.Center dayLabel!.frame = bounds var font = appearance.dayLabelWeekdayFont var color: UIColor? if isOut { color = appearance.dayLabelWeekdayOutTextColor } else if isCurrentDay { let coordinator = calendarView.coordinator if coordinator.selectedDayView == nil { let touchController = calendarView.touchController touchController.receiveTouchOnDayView(self) calendarView.didSelectDayView(self) } else { color = appearance.dayLabelPresentWeekdayTextColor if appearance.dayLabelPresentWeekdayInitallyBold! { font = appearance.dayLabelPresentWeekdayBoldFont } else { font = appearance.dayLabelPresentWeekdayFont } } } else { color = appearance.dayLabelWeekdayInTextColor } if color != nil && font != nil { dayLabel!.textColor = color! dayLabel!.font = font } addSubview(dayLabel!) } public func preliminarySetup() { if let delegate = calendarView.delegate, shouldShow = delegate.preliminaryView?(shouldDisplayOnDayView: self) where shouldShow { if let preView = delegate.preliminaryView?(viewOnDayView: self) { insertSubview(preView, atIndex: 0) preView.layer.zPosition = CGFloat(-MAXFLOAT) } } } public func supplementarySetup() { if let delegate = calendarView.delegate, shouldShow = delegate.supplementaryView?(shouldDisplayOnDayView: self) where shouldShow { if let supView = delegate.supplementaryView?(viewOnDayView: self) { insertSubview(supView, atIndex: 0) } } } // TODO: Make this widget customizable public func topMarkerSetup() { safeExecuteBlock({ func createMarker() { let height = CGFloat(0.5) let layer = CALayer() layer.borderColor = UIColor.grayColor().CGColor layer.borderWidth = height layer.frame = CGRectMake(0, 1, CGRectGetWidth(self.frame), height) self.topMarker = layer self.layer.addSublayer(self.topMarker!) } if let delegate = self.calendarView.delegate { if self.topMarker != nil { self.topMarker?.removeFromSuperlayer() self.topMarker = nil } if let shouldDisplay = delegate.topMarker?(shouldDisplayOnDayView: self) where shouldDisplay { createMarker() } } else { if self.topMarker == nil { createMarker() } else { self.topMarker?.removeFromSuperlayer() self.topMarker = nil createMarker() } } }, collapsingOnNil: false, withObjects: weekView, weekView.monthView, weekView.monthView) } public func setupDotMarker() { for (index, dotMarker) in enumerate(dotMarkers) { dotMarkers[index]!.removeFromSuperview() dotMarkers[index] = nil } if let delegate = calendarView.delegate { if let shouldShow = delegate.dotMarker?(shouldShowOnDayView: self) where shouldShow { let (width: CGFloat, height: CGFloat) = (13, 13) let colors = isOut ? [.grayColor()] : delegate.dotMarker?(colorOnDayView: self) var yOffset = bounds.height / 5 if let y = delegate.dotMarker?(moveOffsetOnDayView: self) { yOffset = y } let y = CGRectGetMidY(frame) + yOffset let markerFrame = CGRectMake(0, 0, width, height) if (colors!.count > 3) { assert(false, "Only 3 dot markers allowed per day") } for (index, color) in enumerate(colors!) { var x: CGFloat = 0 switch(colors!.count) { case 1: x = frame.width / 2 case 2: x = frame.width * CGFloat(2+index)/5.00 // frame.width * (2/5, 3/5) case 3: x = frame.width * CGFloat(2+index)/6.00 // frame.width * (1/3, 1/2, 2/3) default: break } let dotMarker = CVAuxiliaryView(dayView: self, rect: markerFrame, shape: .Circle) dotMarker.fillColor = color dotMarker.center = CGPointMake(x, y) insertSubview(dotMarker, atIndex: 0) dotMarker.setNeedsDisplay() dotMarkers.append(dotMarker) } let coordinator = calendarView.coordinator if self == coordinator.selectedDayView { moveDotMarkerBack(false, coloring: false) } } } } } // MARK: - Dot marker movement extension CVCalendarDayView { public func moveDotMarkerBack(unwinded: Bool, var coloring: Bool) { for dotMarker in dotMarkers { if let calendarView = calendarView, let dotMarker = dotMarker { var shouldMove = true if let delegate = calendarView.delegate, let move = delegate.dotMarker?(shouldMoveOnHighlightingOnDayView: self) where !move { shouldMove = move } func colorMarker() { if let delegate = calendarView.delegate { let appearance = calendarView.appearance let frame = dotMarker.frame var color: UIColor? if unwinded { if let myColor = delegate.dotMarker?(colorOnDayView: self) { color = (isOut) ? appearance.dayLabelWeekdayOutTextColor : myColor.first } } else { color = appearance.dotMarkerColor } dotMarker.fillColor = color dotMarker.setNeedsDisplay() } } func moveMarker() { var transform: CGAffineTransform! if let circleView = circleView { let point = pointAtAngle(CGFloat(-90).toRadians(), withinCircleView: circleView) let spaceBetweenDotAndCircle = CGFloat(1) let offset = point.y - dotMarker.frame.origin.y - dotMarker.bounds.height/2 + spaceBetweenDotAndCircle transform = unwinded ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(0, offset) if dotMarker.center.y + offset > CGRectGetMaxY(frame) { coloring = true } } else { transform = CGAffineTransformIdentity } if !coloring { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { dotMarker.transform = transform }, completion: { _ in }) } else { moveDotMarkerBack(unwinded, coloring: coloring) } } if shouldMove && !coloring { moveMarker() } else { colorMarker() } } } } } // MARK: - Circle geometry extension CGFloat { public func toRadians() -> CGFloat { return CGFloat(self) * CGFloat(M_PI / 180) } public func toDegrees() -> CGFloat { return CGFloat(180/M_PI) * self } } extension CVCalendarDayView { public func pointAtAngle(angle: CGFloat, withinCircleView circleView: UIView) -> CGPoint { let radius = circleView.bounds.width / 2 let xDistance = radius * cos(angle) let yDistance = radius * sin(angle) let center = circleView.center var x = floor(cos(angle)) < 0 ? center.x - xDistance : center.x + xDistance var y = center.y - yDistance let result = CGPointMake(x, y) return result } public func moveView(view: UIView, onCircleView circleView: UIView, fromAngle angle: CGFloat, toAngle endAngle: CGFloat, straight: Bool) { let condition = angle > endAngle ? angle > endAngle : angle < endAngle if straight && angle < endAngle || !straight && angle > endAngle { UIView.animateWithDuration(pow(10, -1000), delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseIn, animations: { let angle = angle.toRadians() view.center = self.pointAtAngle(angle, withinCircleView: circleView) }) { _ in let speed = CGFloat(750).toRadians() let newAngle = straight ? angle + speed : angle - speed self.moveView(view, onCircleView: circleView, fromAngle: newAngle, toAngle: endAngle, straight: straight) } } } } // MARK: - Day label state management extension CVCalendarDayView { public func setSelectedWithType(type: SelectionType) { let appearance = calendarView.appearance var backgroundColor: UIColor! var backgroundAlpha: CGFloat! var shape: CVShape! switch type { case let .Single: shape = .Circle if isCurrentDay { dayLabel?.textColor = appearance.dayLabelPresentWeekdaySelectedTextColor! dayLabel?.font = appearance.dayLabelPresentWeekdaySelectedFont backgroundColor = appearance.dayLabelPresentWeekdaySelectedBackgroundColor backgroundAlpha = appearance.dayLabelPresentWeekdaySelectedBackgroundAlpha } else { dayLabel?.textColor = appearance.dayLabelWeekdaySelectedTextColor dayLabel?.font = appearance.dayLabelWeekdaySelectedFont backgroundColor = appearance.dayLabelWeekdaySelectedBackgroundColor backgroundAlpha = appearance.dayLabelWeekdaySelectedBackgroundAlpha } case let .Range: shape = .Rect if isCurrentDay { dayLabel?.textColor = appearance.dayLabelPresentWeekdayHighlightedTextColor! dayLabel?.font = appearance.dayLabelPresentWeekdayHighlightedFont backgroundColor = appearance.dayLabelPresentWeekdayHighlightedBackgroundColor backgroundAlpha = appearance.dayLabelPresentWeekdayHighlightedBackgroundAlpha } else { dayLabel?.textColor = appearance.dayLabelWeekdayHighlightedTextColor dayLabel?.font = appearance.dayLabelWeekdayHighlightedFont backgroundColor = appearance.dayLabelWeekdayHighlightedBackgroundColor backgroundAlpha = appearance.dayLabelWeekdayHighlightedBackgroundAlpha } default: break } if let circleView = circleView where circleView.frame != dayLabel.bounds { circleView.frame = dayLabel.bounds } else { circleView = CVAuxiliaryView(dayView: self, rect: dayLabel.bounds, shape: shape) } circleView!.fillColor = backgroundColor circleView!.alpha = backgroundAlpha circleView!.setNeedsDisplay() insertSubview(circleView!, atIndex: 0) moveDotMarkerBack(false, coloring: false) } public func setDeselectedWithClearing(clearing: Bool) { if let calendarView = calendarView, let appearance = calendarView.appearance { var color: UIColor? if isOut { color = appearance.dayLabelWeekdayOutTextColor } else if isCurrentDay { color = appearance.dayLabelPresentWeekdayTextColor } else { color = appearance.dayLabelWeekdayInTextColor } var font: UIFont? if isCurrentDay { if appearance.dayLabelPresentWeekdayInitallyBold! { font = appearance.dayLabelPresentWeekdayBoldFont } else { font = appearance.dayLabelWeekdayFont } } else { font = appearance.dayLabelWeekdayFont } dayLabel?.textColor = color dayLabel?.font = font moveDotMarkerBack(true, coloring: false) if clearing { circleView?.removeFromSuperview() } } } } // MARK: - Content reload extension CVCalendarDayView { public func reloadContent() { setupDotMarker() dayLabel?.frame = bounds var shouldShowDaysOut = calendarView.shouldShowWeekdaysOut! if !shouldShowDaysOut { if isOut { hidden = true } } else { if isOut { hidden = false } } if circleView != nil { setSelectedWithType(.Single) } } } // MARK: - Safe execution extension CVCalendarDayView { public func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
mit
01fa3deb2ac5eb2a3c6f2c25c01cc3b2
35.050373
180
0.534365
5.760883
false
false
false
false
chrisjmendez/swift-exercises
GUI/Speedometer/Speedometer/Gague.swift
1
2490
// // LoaderView.swift // Custom UIX // // Created by tommy trojan on 4/18/15. // Copyright (c) 2015 Chris Mendez. All rights reserved. // import UIKit let NoOfGlasses = 8 let π:CGFloat = CGFloat(M_PI) @IBDesignable class Gague: UIView { @IBInspectable var counter: Int = 5 { didSet { if counter <= NoOfGlasses { //the view needs to be refreshed setNeedsDisplay() } } } @IBInspectable var outlineColor: UIColor = UIColor.blueColor() @IBInspectable var counterColor: UIColor = UIColor.orangeColor() override func drawRect(rect: CGRect) { // 1 let center = CGPoint(x:bounds.width/2, y:bounds.height/2) // 2 let radius: CGFloat = max(bounds.width, bounds.height) // 3 let arcWidth: CGFloat = 76 // 4 let startAngle: CGFloat = 3 * π / 4 let endAngle: CGFloat = π / 4 // 5 let path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) // 6 path.lineWidth = arcWidth counterColor.setStroke() path.stroke() //Draw the outline //1 - first calculate the difference between the two angles //ensuring it is positive let angleDifference: CGFloat = 2 * π - startAngle + endAngle //then calculate the arc for each single glass let arcLengthPerGlass = angleDifference / CGFloat(NoOfGlasses) //then multiply out by the actual glasses drunk let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle //2 - draw the outer arc let outlinePath = UIBezierPath(arcCenter: center, radius: bounds.width/2 - 2.5, startAngle: startAngle, endAngle: outlineEndAngle, clockwise: true) //3 - draw the inner arc outlinePath.addArcWithCenter(center, radius: bounds.width/2 - arcWidth + 2.5, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false) //4 - close the path outlinePath.closePath() outlineColor.setStroke() outlinePath.lineWidth = 5.0 outlinePath.stroke() } }
mit
d15eda2896b621ab1fe1e55456ff6249
27.25
79
0.554706
4.855469
false
false
false
false
baberthal/SwiftCoreExt
CoreExtensionsTests/RegexSpec.swift
1
2723
import Quick import Nimble import CoreExtensions class RegexSpec: QuickSpec { override func spec() { describe("Regex standard initialization", { var regex: Regex! describe("init(pattern: String)", { beforeEach { regex = Regex(pattern: "hello") } it("can instantiate without error") { expect(regex.pattern).to(equal("hello")) } it("matches a pattern with .match()") { expect(regex.match("hello_there")).to(beTruthy()) } }) describe("init with options", { beforeEach { regex = Regex(pattern: "hello", options: NSRegularExpressionOptions.AnchorsMatchLines) } it("instantiates without error") { expect(regex.pattern).to(equal("hello")) expect(regex.options).to( equal(NSRegularExpressionOptions.AnchorsMatchLines) ) } }) }) describe("Regex string literal initialization", { var regex: Regex! beforeEach { regex = "hello" } it("inits without errors") { expect(regex.pattern).to(equal("hello")) } it("can match against a pattern") { expect(regex.match("hello, my friend")).to(beTrue()) } }) describe("various literal conversions", { it("can convert from unicode scalar") { let reg = Regex(unicodeScalarLiteral: "a") expect(reg).toNot(beNil()) expect(reg.pattern).to(equal("a")) } it("can convert from extended grapheme cluster") { let reg = Regex(extendedGraphemeClusterLiteral: "\u{65}") expect(reg).toNot(beNil()) expect(reg.pattern).to(equal("\u{65}")) } }) describe("the =~ operator", { describe("with a `normally` initialized Regex") { var regex: Regex! beforeEach { regex = Regex(pattern: "hello") } it("matches with the =~ operator") { let doesMatch = "hello, my friend" =~ regex expect(doesMatch).to(beTrue()) } } }) } }
mit
b87aef923e02c9ef45e00753abb9d6c4
31.416667
106
0.42747
5.88121
false
false
false
false
64characters/Telephone
UseCases/DefaultRingtonePlaybackUseCase.swift
1
1354
// // DefaultRingtonePlaybackUseCase.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public final class DefaultRingtonePlaybackUseCase: NSObject { public static let interval: Double = 4 public var isPlaying: Bool { return ringtone != nil } private let factory: RingtoneFactory private var ringtone: Ringtone? public init(factory: RingtoneFactory) { self.factory = factory } } extension DefaultRingtonePlaybackUseCase: RingtonePlaybackUseCase { public func start() throws { if ringtone == nil { ringtone = try factory.makeRingtone(interval: DefaultRingtonePlaybackUseCase.interval) } ringtone!.startPlaying() } public func stop() { ringtone?.stopPlaying() ringtone = nil } }
gpl-3.0
f7ce12df464873d75000288dfe64bf5f
29.727273
98
0.703402
4.567568
false
false
false
false
alessiobrozzi/firefox-ios
Client/Frontend/Home/ReaderPanel.swift
2
20458
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage import ReadingList import Shared import XCGLogger private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44) static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035) static let DeleteButtonTitleColor = UIColor.white static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1) static let MarkAsReadButtonTitleColor = UIColor.white static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenHeaderTextColor = UIColor.darkGray static let WelcomeScreenItemTextColor = UIColor.gray static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: UITableViewCell { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url: URL = URL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor updateAccessibilityLabel() } } let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = UIEdgeInsets.zero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = UIViewContentMode.scaleAspectFit readStatusImageView.snp.makeConstraints { (make) -> Void in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.centerY.equalTo(self.contentView) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) contentView.addSubview(hostnameLabel) titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor titleLabel.numberOfLines = 2 titleLabel.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.trailing.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec make.bottom.lessThanOrEqualTo(hostnameLabel.snp.top).priority(1000) } hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor hostnameLabel.numberOfLines = 1 hostnameLabel.snp.makeConstraints { (make) -> Void in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.leading.trailing.equalTo(self.titleLabel) } setupDynamicFonts() } func setupDynamicFonts() { titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight } override func prepareForReuse() { super.prepareForReuse() setupDynamicFonts() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return hostname.substring(from: hostname.characters.index(hostname.startIndex, offsetBy: prefix.characters.count)) } } return hostname } fileprivate func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, let title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string as AnyObject } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? var profile: Profile! fileprivate lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview() fileprivate var records: [ReadingListClientRecord]? init() { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReadingListPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReadingListPanel.notificationReceived(_:)), name: NotificationDynamicFontChanged, object: nil) } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.accessibilityIdentifier = "ReadingTable" tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.separatorInset = UIEdgeInsets.zero tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorColor = UIConstants.SeparatorColor tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() view.backgroundColor = UIConstants.PanelBackgroundColor if let result = profile.readingList?.getAvailableRecords(), result.isSuccess { records = result.successValue // If no records have been added yet, we display the empty state if records?.count == 0 { tableView.isScrollEnabled = false view.addSubview(emptyStateOverlayView) } } } deinit { NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged: refreshReadingList() break case NotificationDynamicFontChanged: if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverview() refreshReadingList() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count if let result = profile.readingList?.getAvailableRecords(), result.isSuccess { records = result.successValue if records?.count == 0 { tableView.isScrollEnabled = false if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) } } else { if prevNumberOfRecords == 0 { tableView.isScrollEnabled = true emptyStateOverlayView.removeFromSuperview() } } self.tableView.reloadData() } } fileprivate func createEmptyStateOverview() -> UIView { let overlayView = UIScrollView(frame: tableView.bounds) overlayView.backgroundColor = UIColor.white // Unknown why this does not work with autolayout overlayView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] let containerView = UIView() overlayView.addSubview(containerView) let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel")) containerView.addSubview(logoImageView) logoImageView.snp.makeConstraints { make in make.centerX.equalTo(containerView) make.centerY.lessThanOrEqualTo(overlayView.snp.centerY).priority(1000) // Sets proper top constraint for iPhone 6 in portait and iPads. make.centerY.equalTo(overlayView.snp.centerY).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView.snp.top).offset(50).priority(1000) } let welcomeLabel = UILabel() containerView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = NSTextAlignment.center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(containerView) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) make.top.equalTo(logoImageView.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) // Sets proper center constraint for iPhones in landscape. make.centerY.lessThanOrEqualTo(overlayView.snp.centerY).offset(-40).priority(1000) } let readerModeLabel = UILabel() containerView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readerModeLabel.numberOfLines = 0 readerModeLabel.snp.makeConstraints { make in make.top.equalTo(welcomeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) containerView.addSubview(readerModeImageView) readerModeImageView.snp.makeConstraints { make in make.centerY.equalTo(readerModeLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } let readingListLabel = UILabel() containerView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readingListLabel.numberOfLines = 0 readingListLabel.snp.makeConstraints { make in make.top.equalTo(readerModeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) make.bottom.equalTo(overlayView).offset(-20) // making AutoLayout compute the overlayView's contentSize } let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) containerView.addSubview(readingListImageView) readingListImageView.snp.makeConstraints { make in make.centerY.equalTo(readingListLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(logoImageView.snp.top) make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset) make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(overlayView) } return overlayView } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell if let record = records?[indexPath.row] { cell.title = record.title cell.url = URL(string: record.url)! cell.unread = record.unread } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { guard let record = records?[indexPath.row] else { return [] } let delete = UITableViewRowAction(style: .normal, title: ReadingListTableViewCellUX.DeleteButtonTitleText) { [weak self] action, index in self?.deleteItem(atIndex: index) } delete.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor let toggleText = record.unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText let unreadToggle = UITableViewRowAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (action, index) in self?.toggleItem(atIndex: index) } unreadToggle.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor return [unreadToggle, delete] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { // Mark the item as read profile.readingList?.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.bookmark homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType) } } fileprivate func deleteItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { if let result = profile.readingList?.deleteRecord(record), result.isSuccess { records?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) // reshow empty state if no records left if records?.count == 0 { view.addSubview(emptyStateOverlayView) } } } } fileprivate func toggleItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { if let result = profile.readingList?.updateRecord(record, unread: !record.unread), result.isSuccess { // TODO This is a bit odd because the success value of the update is an optional optional Record if let successValue = result.successValue, let updatedRecord = successValue { records?[indexPath.row] = updatedRecord tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } } } } }
mpl-2.0
334b39693fcfcb94f9aa4769aea2d600
45.495455
333
0.694105
5.762817
false
false
false
false
MakeSchool/TripPlanner
TripPlanner/UI/AddWayPointScene/AddWaypointViewController.swift
1
4111
// // AddTripViewController.swift // TripPlanner // // Created by Benjamin Encz on 7/22/15. // Copyright © 2015 Make School. All rights reserved. // import UIKit import ListKit import MapKit import Result //TODO: Show google logo as part of search class LocationResultTableViewCell: UITableViewCell, ListKitCellProtocol { var model: Place? { didSet { if let model = model { self.textLabel!.text = model.placeDescription } } } } class AddWaypointViewController: UIViewController { // MARK: IBOutlets @IBOutlet var tableView: UITableView! @IBOutlet var mapView: MKMapView! // MARK: Properties and Property Observers var errorHandler = DefaultErrorHandler() var session: NSURLSession = NSURLSession.sharedSession() var arrayDataSource: ArrayDataSource<LocationResultTableViewCell, Place>! var mapViewDecorator: LocationSearchMapViewDecorator! var locationSearch: LocationSearch var waypoint: Waypoint? var displayedLocation: PlaceWithLocation? { didSet { mapViewDecorator.displayedLocation = displayedLocation waypoint?.name = displayedLocation?.locationSearchEntry.placeDescription waypoint?.location = displayedLocation?.location } } required init?(coder aDecoder: NSCoder) { locationSearch = LocationSearch(urlSession: session) super.init(coder: aDecoder) } var locations: [Place] = [] { didSet { arrayDataSource.array = locations tableView.reloadData() } } var searchTerm: String? { didSet { if let searchTerm = searchTerm where !searchTerm.isEmpty { let urlSafeSerchTerm = URLEncodedString(searchTerm) locationSearch.findPlaces(urlSafeSerchTerm, callback: handleSearchResult) } else { locations = [] } } } // MARK: View Lifecycle override func viewDidLoad() { arrayDataSource = ArrayDataSource(array: locations, cellType:LocationResultTableViewCell.self) tableView.dataSource = arrayDataSource tableView.delegate = self mapViewDecorator = LocationSearchMapViewDecorator(mapView: mapView) } // MARK: API Callbacks func handleSearchResult(result: Result<Predictions, Reason>) -> Void { switch result { case let .Success(predictions): self.locations = predictions.predictions case .Failure(_): self.errorHandler.displayErrorMessage( NSLocalizedString("add_trip.cannot_complete_search", comment: "Error message: the search returned an error, sorry! Please try again later") ) } } func handleLocationDetailResult(result: Result<PlaceWithLocation, Reason>) -> Void { switch result { case let .Success(place): displayedLocation = place case .Failure(_): self.errorHandler.displayErrorMessage( NSLocalizedString("add_trip.cannot_retrieve_place_details", comment: "Error message: cannot retrieve information for this place, please choose another one.") ) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(indexPath, animated: true) } } } } // MARK: TableViewDataSource extension AddWaypointViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayDataSource.tableView(tableView, numberOfRowsInSection: section) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return arrayDataSource.tableView(tableView, cellForRowAtIndexPath: indexPath) } } // MARK: TableViewDelegate extension AddWaypointViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { locationSearch.detailsForPlace(arrayDataSource.array[indexPath.row], callback: handleLocationDetailResult) } } // MARK: SearchBarDelegate extension AddWaypointViewController: UISearchBarDelegate { func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { searchTerm = searchText } }
mit
9870cb1533b4f15efb87ef4f2f8f250a
27.748252
165
0.726521
4.975787
false
false
false
false
Eonil/HomeworkApp1
Modules/Monolith/CancellableBlockingIO/Sources/Channel.swift
3
1492
// // Channel.swift // dispatch_semaphore_test // // Created by Hoon H. on 11/7/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation /// Single-shot data transfer. struct Transfer<T> { let _s = Semaphore() var _v = nil as T? var _f = AtomicBoolSlot(false) mutating func signal(v:T) { assert(_f.value == false, "This is one-time use only object. Do not reuse this.") if _f.compareAndSwapBarrier(oldValue: false, newValue: true) { _v = v _s.signal() } } mutating func wait() -> T { _s.wait() assert(_v != nil) return _v! } } ///// Multi-shot data transfer using sigle semaphore. ///// Anyway this uses locking due to risk of parallel access to the value. //struct Channel<T> { // let _put = Semaphore() // let _took = Semaphore() // var _vals = [] as [T] // // init() { // _took.signal() // } // mutating func signal(v:T) { // _took.wait(); // _vals.append(v) // _put.signal() // } // mutating func wait() -> T { // _put.wait() // let v1 = _vals.removeAtIndex(0) // _took.signal() // return v1 // } //} /// Multi-shot data transfer using sigle semaphore. /// Anyway this uses locking due to risk of parallel access to the value. class Channel<T> { let _lock = NSLock() let _s = Semaphore() var _vals = [] as [T] func signal(v:T) { _lock.lock() _vals.append(v) _lock.unlock() _s.signal() } func wait() -> T { _s.wait() _lock.lock() let v1 = _vals.removeAtIndex(0) _lock.unlock() return v1 } }
mit
01d82ad5a6773419824574b42052d188
17.65
83
0.601206
2.478405
false
false
false
false
mathewsheets/SwiftLearningExercises
Exercise_13.playground/Sources/Container.swift
1
3860
import Foundation // the contract for the Container public protocol Container { associatedtype ItemType func add(item: ItemType) func remove(item: ItemType) -> ItemType? var count: Int { get } subscript(i: Int) -> ItemType { get } } // the class that can hold any data type but the element must be equatable public class Database<Element> where Element: Equatable { public var items: [Element] public init() { items = [Element]() } } extension Database: Container { public typealias ItemType = Element public func add(item: ItemType) { items.append(item) } public func remove(item: ItemType) -> ItemType? { let index = items.index { $0 == item } if index != nil { return items.remove(at: index!) } return nil } public var count: Int { return items.count } public subscript(i: Int) -> ItemType { return items[i] } } public class DataFinder { public init() { } func iterator<T>(items: [T], closure: (T) -> Void) { for index in 0..<items.count { closure(items[index]) } } public func each<T>(items: [T], closure: (T, Int) -> Void) { var index = 0; iterator(items: items) { (item) in closure(item, index) index += 1 } } public func all<T>(items: [T], closure: (T) -> Bool) -> Bool { var all = true iterator(items: items) { (item) -> Void in if all && !closure(item) { all = false } } return all } public func any<T>(items: [T], closure: (T) -> Bool) -> Bool { var any = false iterator(items: items) { (item) -> Void in if !any && closure(item) { any = true } } return any } public func indexOf<T>(items: [T], closure: (T) -> Bool) -> Int? { var index = -1 var found = false iterator(items: items) { (item) -> Void in if !found { if closure(item) { found = true } index += 1 } } return index == -1 || !found ? nil : index } public func contains<T>(items: [T], closure: (T) -> Bool) -> Bool { var found = false iterator(items: items) { (item) -> Void in if !found && closure(item) { found = true } } return found } public func filter<T>(items: [T], closure: (T) -> Bool) -> [T]? { var filter = [T]() iterator(items: items) { (item) -> Void in if closure(item) { filter.append(item) } } return !filter.isEmpty ? filter : nil } public func reject<T>(items: [T], closure: (T) -> Bool) -> [T]? { var keep = [T]() iterator(items: items) { (item) -> Void in if !closure(item) { keep.append(item) } } return !keep.isEmpty ? keep : nil } public func pluck<T>(items: [T], closure: (T) -> Any) -> [Any] { var plucked = [Any]() iterator(items: items) { plucked.append(closure($0)) } return plucked } }
mit
38d6ee4fcfbee642da80a6d21f7a3141
19.531915
74
0.419948
4.611708
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/UserRequestManager.swift
1
14339
// // UserRequestManager.swift // Yona // // Created by Ben Smith on 28/04/16. // Copyright © 2016 Yona. All rights reserved. // import Foundation //MARK: - User APIService class UserRequestManager{ var newUser: Users? let APIService = APIServiceManager.sharedInstance static let sharedInstance = UserRequestManager() fileprivate init() {} fileprivate func saveUserDetail(_ json: BodyDataDictionary) { do { let userData = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) let userDataString = String(data: userData, encoding: String.Encoding.utf8) UserDefaults.standard.set(userDataString, forKey: YonaConstants.nsUserDefaultsKeys.savedUser) } catch let jsonError { print(jsonError) } self.newUser = Users.init(userData: json) } func getSavedUserFromUserDefaults() -> Users { if let savedUser = UserDefaults.standard.object(forKey: YonaConstants.nsUserDefaultsKeys.savedUser), let user = convertToDictionary(text: savedUser as! String) { return Users.init(userData: user as BodyDataDictionary) } return Users.init(userData: [:]) } fileprivate func genericUserRequest(_ httpmethodParam: httpMethods, path: String, userRequestType: userRequestTypes, body: BodyDataDictionary?, onCompletion: @escaping APIUserResponse){ ///now post updated user data APIService.callRequestWithAPIServiceResponse(body, path: path, httpMethod: httpmethodParam, onCompletion: { success, json, error in if let json = json { guard success == true else { onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil) return } //only update our user body on get, post, update or confirm mobile number if userRequestType == userRequestTypes.getUser || userRequestType == userRequestTypes.postUser || userRequestType == userRequestTypes.updateUser || userRequestType == userRequestTypes.confirmMobile { self.saveUserDetail(json) } onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), self.newUser) } else { //response from request failed onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil) } }) } /** Posts a new user to the server, part of the create new user flow, give a body with all the details such as mobile number (that must be unique) and then respond with new user object - parameter body: BodyDataDictionary, pass in a user body like this, mobile must be unique: { "firstName": "Ben", "lastName": "Quin", "mobileNumber": "+3161333999999", "nickname": "RQ" } - parameter confirmCode: String? Confirm code required to post a new body if the user has lost the phone and is sent a confirm code to update their account - parameter onCompletion: APIUserResponse, Responds with the new user body and also server messages and success or fail */ func postUser(_ body: BodyDataDictionary, confirmCode: String?, onCompletion: @escaping APIUserResponse) { var path = YonaConstants.commands.users //not in user body need to hardcode //if user lost phone then we need to set a confirm code if let confirmCodeUnwrap = confirmCode { path = YonaConstants.commands.users + YonaConstants.commands.userRequestOverrideCode + confirmCodeUnwrap } genericUserRequest(httpMethods.post, path: path, userRequestType: userRequestTypes.postUser, body: body, onCompletion: onCompletion) } func postOpenAppEvent(_ user: Users, onCompletion: @escaping APIResponse) { let openAppEventLinkPath = user.devices.first(where: { $0.isRequestingDevice! }).map {$0.openAppEventLink} if let path = openAppEventLinkPath, let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, let appVersionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String { let bodyForOpenAppEvent = ["operatingSystem": "IOS", "appVersion": appVersion, "appVersionCode":appVersionCode] as BodyDataDictionary genericUserRequest(httpMethods.post, path: path!, userRequestType: userRequestTypes.postUser, body: bodyForOpenAppEvent, onCompletion: { (success, message, code, nil) in onCompletion(success, message, code) }) } else { //Failed to retrive details for open app event onCompletion(false, YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(describing: responseCodes.internalErrorCode)) } } /**users Updates the user by getting the current user, then passing in the edit link for that user with the new body of details to update - parameter body: BodyDataDictionary, pass in the body as below on how you want to update the user { "firstName": "Richard", "lastName": "Quin", "mobileNumber": "+31612345678", "nickname": "RQ" } - parameter onCompletion: APIUserResponse, Responds with the new user body and also server messages and success or fail */ func updateUser(_ body: BodyDataDictionary, onCompletion: @escaping APIUserResponse) { // NSLog("----------------------- YONA") // NSLog("----------------------- updateUser") // NSLog(" ") // NSLog(" ") // NSLog("self.newUser? %@",self.newUser!.firstName) if let editLink = self.newUser?.editLink { ///now post updated user data genericUserRequest(httpMethods.put, path: editLink, userRequestType: userRequestTypes.updateUser, body: body, onCompletion: onCompletion) } else { //Failed to retrive details for POST user details request onCompletion(false, YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(describing: responseCodes.ok200), nil) } } /** V.important method called every time we need to access the user specific API, using the selfLink stored in the Keychain we can access the users details and returne this in a DAO user object in the response. - parameter onCompletion: APIUserResponse, Responds with the new user body and also server messages and success or fail - parameter userRequestType: GetUserRequest, This can be allowed (so we will allow an API call to the User Request) or not allowed (we will not allow whoever is call ing this to call the API for get User, but just return the stored User body). This changes depending on where we call the get user in the code */ func getUser(_ userRequestType: GetUserRequest, onCompletion: @escaping APIUserResponse) { if var selfUserLink = KeychainManager.sharedInstance.getUserSelfLink(){ selfUserLink = correctUserFetchUrlIfNeeded(storedUserUrl: selfUserLink) if self.newUser == nil || UserDefaults.standard.bool(forKey: YonaConstants.nsUserDefaultsKeys.isBlocked) || userRequestType == GetUserRequest.allowed { //if blocked because of pinreset #if DEBUG print("***** Get User API call ******") #endif genericUserRequest(httpMethods.get, path: selfUserLink, userRequestType: userRequestTypes.getUser, body: nil, onCompletion: onCompletion) } else { DispatchQueue.main.async(execute: { onCompletion(true, YonaConstants.serverMessages.OK, String(describing: responseCodes.ok200), self.newUser) }) } } else { //Failed to retrive details for GET user details request onCompletion(false, YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(describing: responseCodes.internalErrorCode), nil) } } func correctUserFetchUrlIfNeeded(storedUserUrl: String) -> String { if getSavedUserFromUserDefaults().getSelfLink == nil { return storedUserUrl } return correctUserFetchUrlIfNeeded(userURLStr: getSavedUserFromUserDefaults().getSelfLink!, environmentBaseURLStr: EnvironmentManager.baseUrlString()!,storedUserUrlStr: storedUserUrl) } func correctUserFetchUrlIfNeeded(userURLStr:String, environmentBaseURLStr:String, storedUserUrlStr:String) -> String { let userURL = URL(string: userURLStr) let environmentBaseURL = URL(string: environmentBaseURLStr) if userURL?.scheme != environmentBaseURL?.scheme { let formattedURLString = userURL?.absoluteString.deletePrefix((userURL?.scheme)!) return environmentBaseURL!.scheme! + formattedURLString! } return storedUserUrlStr //return as there is no mess up of URLs which is cause of the issue YD-621 } /** Deletes the user, first get the user then use the edit link to delete the user - parameter onCompletion: APIResponse, returns success or fail of the method and server messages */ func deleteUser(_ onCompletion: @escaping APIResponse) { //get the get user link... if let editLink = self.newUser?.editLink { genericUserRequest(httpMethods.delete, path: editLink, userRequestType: userRequestTypes.deleteUser, body: nil, onCompletion: { (success, message, code, nil) in if success { KeychainManager.sharedInstance.clearKeyChain() } onCompletion(success, message, code) }) } else { //Failed to retrive details for delete user request onCompletion(false, YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(describing: responseCodes.internalErrorCode)) } } /** Resends the confirmation code that is sent to the user when they are required to confirm their account - parameter onCompletion: APIResponse, returns success or fail of the method and server messages */ func resendConfirmationCodeMobile(_ onCompletion: @escaping APIResponse) { if let selfUserLink = KeychainManager.sharedInstance.getUserSelfLink() { genericUserRequest(httpMethods.get, path: selfUserLink, userRequestType: userRequestTypes.getUser, body: nil) {(success, message, code, user) in if let resendConfirmationCodeMobileLink = user?.resendConfirmationCodeMobileLink{ self.genericUserRequest(httpMethods.post, path: resendConfirmationCodeMobileLink, userRequestType: userRequestTypes.resendMobileConfirmCode, body: nil, onCompletion: { (success, message, code, user) in onCompletion(success, message, code) }) } else { //Failed to retrive details for confirmation code resend request onCompletion(false, YonaConstants.serverMessages.FailedToRetrieveConfirmationCode, String(describing: responseCodes.internalErrorCode)) } } } } /** Called when the user is required to confirm their mobile number after signup, they are sent a text with the confimation code in which they have to enter, this code is then sent through in the body and then the request can be made to confirm this mobile, if the code is wrong the server sends back messages saying as much...they have 5 attempts, after which the app is locked - parameter body: BodyDataDictionary?, The body must take the form of this, the code is the confirmation code sent by text { "code": "1234" } - parameter onCompletion: APIResponse, returns success or fail of the method and server messages */ func confirmMobileNumber(_ body: BodyDataDictionary?, onCompletion: @escaping APIResponse) { if let confirmMobileLink = self.newUser?.confirmMobileNumberLink { genericUserRequest(httpMethods.post, path: confirmMobileLink, userRequestType: userRequestTypes.confirmMobile, body: body, onCompletion: { (success, message, code, user) in onCompletion(success, message, code) }) } else if let savedUser = UserDefaults.standard.object(forKey: YonaConstants.nsUserDefaultsKeys.savedUser) { let user = convertToDictionary(text: savedUser as! String) self.newUser = Users.init(userData: user! as BodyDataDictionary) if let confirmMobileLink = self.newUser?.confirmMobileNumberLink { genericUserRequest(httpMethods.post, path: confirmMobileLink , userRequestType: userRequestTypes.confirmMobile, body: body, onCompletion: { (success, message, code, user) in onCompletion(success, message, code) }) } }else { //Failed to retrive details for confirm mobile request onCompletion(false, YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(describing: responseCodes.internalErrorCode)) } } func getMobileConfigFile( _ onCompletion: @escaping APIMobileConfigResponse) { let mobileConfigFileURL = self.newUser?.devices.first(where: { $0.isRequestingDevice! }).map {$0.mobileConfigLink} if let mobileConfigURL = mobileConfigFileURL { APIServiceManager.sharedInstance.callRequestWithAPIMobileConfigResponse(nil, path: mobileConfigURL!, httpMethod: httpMethods.get, onCompletion: onCompletion) } } func convertToDictionary(text: String) -> [String: Any]? { if let data = text.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print(error.localizedDescription) } } return nil } }
mpl-2.0
dbcc81d91dd00b829d873eb7e65aa9fc
55.007813
379
0.670805
5.206245
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Library/Utils/Formula/Formula.swift
1
4926
// // Formula.swift // FoodAndFitness // // Created by Mylo Ho on 4/12/17. // Copyright © 2017 SuHoVan. All rights reserved. // import Foundation import UIKit enum ActiveTracking: Int { case walking case running case cycling static var count: Int { return self.cycling.rawValue + 1 } var title: String { switch self { case .running: return Strings.running case .cycling: return Strings.cycling case .walking: return Strings.walking } } static func active(title: String) -> ActiveTracking { switch title { case self.walking.title: return walking case self.running.title: return running case self.cycling.title: return cycling default: return walking } } var image: UIImage { switch self { case .running: return #imageLiteral(resourceName: "img_running") case .cycling: return #imageLiteral(resourceName: "img_cycling") case .walking: return #imageLiteral(resourceName: "img_walking") } } var icon: UIImage { switch self { case .running: return #imageLiteral(resourceName: "ic_running") case .cycling: return #imageLiteral(resourceName: "ic_cycling") case .walking: return #imageLiteral(resourceName: "ic_walking") } } } // MARK: - BMI Calculator func bmi(weight: Int, height: Int) -> Double { let result = Double(weight) * 10_000 / Double(height * height) return result } func status(bmi: Double, age: Int) -> String { switch age { default: switch bmi { case 0..<16: return Strings.severeThinness case 16..<17: return Strings.moderateThinness case 17..<18.5: return Strings.mildThinness case 18.5..<25: return Strings.normal case 25..<30: return Strings.overweight case 30..<35: return Strings.obeseClassI case 35..<40: return Strings.obeseClassII case 40..<200: return Strings.obeseClassIII default: return Strings.empty } } } // MARK: - BMR Calculator func bmr(weight: Int, height: Int, age: Int, gender: Gender) -> Double { let value = 10 * Double(weight) + 6.25 * Double(height) - 5 * Double(age) switch gender { case .male: return value + 5 case .female: return value - 161 } } // MARK: - Carbohydrates Calculator with 50% func carbs(calories: Double) -> Int { let grams = calories / 8 return Int(grams) } // MARK: - Protein Calculator with 20% func protein(calories: Double) -> Int { let grams = calories / 20 return Int(grams) } // MARK: - Fat Calculator with 30% func fat(calories: Double) -> Int { let grams = calories / 27 return Int(grams) } // MARK: - Met Calculator fileprivate func met(velocity: Double, active: ActiveTracking) -> Double { switch active { case .walking: return metWalking(velocity: velocity) case .running: return metRunning(velocity: velocity) case .cycling: return metCycling(velocity: velocity) } } fileprivate func metWalking(velocity: Double) -> Double { switch velocity { case 0..<3.2: return 2.0 case 3.2..<4: return 2.8 case 4..<4.5: return 3.0 case 4.5..<5.2: return 3.5 case 5.2..<5.6: return 4.3 case 5.6..<6.4: return 5.0 case 6.4..<7.2: return 7.0 case 7.2..<20: return 8.3 default: return 0 } } fileprivate func metRunning(velocity: Double) -> Double { switch velocity { case 0..<6.4: return 6 case 6.4..<8: return 8.3 case 8..<9.5: return 9.8 case 9.5..<11.3: return 11.0 case 11.3..<12: return 11.8 case 12..<14.5: return 12.8 case 14.5..<16: return 14.5 case 16..<17.7: return 16 case 17.7..<19.3: return 19.0 case 19.3..<20.9: return 19.8 case 20.9..<50: return 23.0 default: return 0 } } fileprivate func metCycling(velocity: Double) -> Double { switch velocity { case 0..<8.9: return 3.5 case 8.9..<16: return 4.0 case 16..<19.2: return 6.8 case 19.2..<22.4: return 8.0 case 22.4..<25.6: return 10.0 case 25.6..<32.2: return 12.0 case 32.2..<100: return 15.8 default: return 0 } } // MARK: - Calories Burn Calculator func caloriesBurned(bmr: Double, velocity: Double, active: ActiveTracking, duration: Double) -> Int { return Int((bmr / 24) * met(velocity: velocity, active: active) * duration) }
mit
4bba09d17bfb95f868793b2e8d9a9a0a
22.014019
101
0.558782
3.803089
false
false
false
false
ECP-CANDLE/Supervisor
workflows/common/ext/EQ-R/eqr/EQR.swift
5
1095
(void v) EQR_init_script(location L, string filename) { v = @location=L EQR_tcl_initR(filename); } (void v) EQR_stop(location L) { v = @location=L EQR_tcl_stop(); } EQR_delete_R(location L) { @location=L EQR_tcl_delete_R(); } (string result) EQR_get(location L) { result = @location=L EQR_tcl_get(); } (void v) EQR_put(location L, string data) { v = @location=L EQR_tcl_put(data); } (boolean b) EQR_is_initialized(location L) { b = @location=L EQR_tcl_is_initialized(); } pragma worktypedef resident_work; @dispatch=resident_work (void v) EQR_tcl_initR(string filename) "eqr" "0.1" [ "initR <<filename>>" ]; @dispatch=resident_work (void v) EQR_tcl_stop() "eqr" "0.1" [ "stopIt" ]; @dispatch=resident_work EQR_tcl_delete_R() "eqr" "0.1" [ "deleteR" ]; @dispatch=resident_work (string result) EQR_tcl_get() "eqr" "0.1" [ "set <<result>> [ OUT_get ]" ]; @dispatch=resident_work (void v) EQR_tcl_put(string data) "eqr" "0.1" [ "IN_put <<data>>" ]; @dispatch=resident_work (boolean result) EQR_tcl_is_initialized() "eqr" "0.1" [ "set <<result>> [ EQR_is_initialized ]" ];
mit
a7ddd8812850a7931e47d73bd5e60e32
16.109375
53
0.645662
2.365011
false
false
true
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/KnowledgeGroupsComponent/View Model/DefaultKnowledgeGroupsViewModelFactory.swift
1
1870
import EurofurenceModel import UIKit.UIImage public struct DefaultKnowledgeGroupsViewModelFactory: KnowledgeGroupsViewModelFactory { private class ViewModel: KnowledgeGroupsListViewModel, KnowledgeServiceObserver { private var groups = [KnowledgeGroup]() private var knowledgeGroups: [KnowledgeListGroupViewModel] = [] private var delegate: KnowledgeGroupsListViewModelDelegate? func knowledgeGroupsDidChange(to groups: [KnowledgeGroup]) { self.groups = groups knowledgeGroups = groups.map { (group) -> KnowledgeListGroupViewModel in KnowledgeListGroupViewModel( title: group.title, fontAwesomeCharacter: group.fontAwesomeCharacterAddress, groupDescription: group.groupDescription ) } delegate?.knowledgeGroupsViewModelsDidUpdate(to: knowledgeGroups) } func setDelegate(_ delegate: KnowledgeGroupsListViewModelDelegate) { self.delegate = delegate delegate.knowledgeGroupsViewModelsDidUpdate(to: knowledgeGroups) } func describeContentsOfKnowledgeItem(at index: Int, visitor: KnowledgeGroupsListViewModelVisitor) { let group = groups[index] if group.entries.count == 1 { let entry = group.entries[0] visitor.visit(entry.identifier) } else { visitor.visit(group.identifier) } } } private let service: KnowledgeService public init(service: KnowledgeService) { self.service = service } public func prepareViewModel(completionHandler: @escaping (KnowledgeGroupsListViewModel) -> Void) { let viewModel = ViewModel() service.add(viewModel) completionHandler(viewModel) } }
mit
862b892f7526c611baaceacd1861547b
33.62963
107
0.652406
5.880503
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/BaseTest/BaseTest/TestPage/DefaultView.swift
1
1761
// // DefaultView.swift // BaseTest // // Created by wuyp on 2017/6/27. // Copyright © 2017年 raymond. All rights reserved. // import UIKit class DefaultViewMananger: NSObject { class func start() { UITableView.swizzle_reloadData() } } private var key:Void? extension UITableView { public var isNeedDefaultNoDataView: Bool { get { if let isNeed = objc_getAssociatedObject(self, &key) { return (isNeed as! NSNumber).boolValue } return true } set(newValue) { objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc private func my_reloadData() { self.my_reloadData() if isNeedDefaultNoDataView && check() { self.addNoDataView() } } fileprivate class func swizzle_reloadData() { let original = class_getInstanceMethod(UITableView.self, #selector(UITableView.reloadData)) let custom = class_getInstanceMethod(UITableView.self, #selector(UITableView.my_reloadData)) method_exchangeImplementations(original!, custom!) } private func check() -> Bool { let sections = self.numberOfSections if sections == 0 { return true } for section in 0..<sections { if self.numberOfRows(inSection: section) > 0 { return false } } return true } } extension UITableView { fileprivate func addNoDataView() { let noDataView = UIView(frame: self.bounds) noDataView.backgroundColor = .red self.addSubview(noDataView) } }
apache-2.0
fe4a42873d8ea0e4468519a8a677fa27
23.082192
100
0.576223
4.869806
false
false
false
false
mbernson/HomeControl.iOS
HomeControl/Features/Dashboard/DashboardPickerTableViewController.swift
1
3397
// // DashboardPickerTableViewController.swift // HomeControl // // Created by Mathijs Bernson on 04/05/16. // Copyright © 2016 Duckson. All rights reserved. // import UIKit import Promissum class DashboardPickerTableViewController: UITableViewController { fileprivate let promiseSource = PromiseSource<Dashboard, Void>() var promise: Promise<Dashboard, Void> { return promiseSource.promise } 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() } @IBAction func cancelButtonPressed(_ sender: AnyObject) { promiseSource.reject() dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Incomplete implementation, return the number of sections // return 0 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete implementation, return the number of rows // return 0 // } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
087bbfad3f5b15810063fedfe9c92b9f
31.037736
156
0.728799
5.091454
false
false
false
false
brave/browser-ios
Shared/TimeConstants.swift
2
5960
/* 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 public typealias Timestamp = UInt64 public typealias MicrosecondTimestamp = UInt64 public let ThreeWeeksInSeconds = 3 * 7 * 24 * 60 * 60 public let OneMonthInMilliseconds = 30 * OneDayInMilliseconds public let OneWeekInMilliseconds = 7 * OneDayInMilliseconds public let OneDayInMilliseconds = 24 * OneHourInMilliseconds public let OneHourInMilliseconds = 60 * OneMinuteInMilliseconds public let OneMinuteInMilliseconds = 60 * OneSecondInMilliseconds public let OneSecondInMilliseconds: UInt64 = 1000 extension Timestamp { public static func uptimeInMilliseconds() -> Timestamp { return Timestamp(DispatchTime.now().uptimeNanoseconds) / 1000000 } } extension Date { public static func now() -> Timestamp { return UInt64(1000 * Date().timeIntervalSince1970) } public static func nowNumber() -> NSNumber { return NSNumber(value: now() as UInt64) } public static func nowMicroseconds() -> MicrosecondTimestamp { return UInt64(1000000 * Date().timeIntervalSince1970) } public static func fromTimestamp(_ timestamp: Timestamp) -> Date { return Date(timeIntervalSince1970: Double(timestamp) / 1000) } public static func fromMicrosecondTimestamp(_ microsecondTimestamp: MicrosecondTimestamp) -> Date { return Date(timeIntervalSince1970: Double(microsecondTimestamp) / 1000000) } public func toTimestamp() -> Timestamp { return UInt64(self.timeIntervalSince1970 * 1000) } public func toRelativeTimeString() -> String { let now = Date() let units: NSCalendar.Unit = [NSCalendar.Unit.second, NSCalendar.Unit.minute, NSCalendar.Unit.day, NSCalendar.Unit.weekOfYear, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour] let components = (Calendar.current as NSCalendar).components(units, from: self, to: now, options: []) if components.year! > 0 { return String(format: DateFormatter.localizedString(from: self, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short)) } if components.month == 1 { return String(format: NSLocalizedString("more than a month ago", comment: "Relative date for dates older than a month and less than two months.")) } if components.month! > 1 { return String(format: DateFormatter.localizedString(from: self, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short)) } if components.weekOfYear! > 0 { return String(format: NSLocalizedString("more than a week ago", comment: "Description for a date more than a week ago, but less than a month ago.")) } if components.day == 1 { return String(format: NSLocalizedString("yesterday", comment: "Relative date for yesterday.")) } if components.day! > 1 { return String(format: NSLocalizedString("this week", comment: "Relative date for date in past week."), String(describing: components.day)) } if components.hour! > 0 || components.minute! > 0 { let absoluteTime = DateFormatter.localizedString(from: self, dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short) let format = NSLocalizedString("today at %@", comment: "Relative date for date older than a minute.") return String(format: format, absoluteTime) } return String(format: NSLocalizedString("just now", comment: "Relative time for a tab that was visited within the last few moments.")) } } let MaxTimestampAsDouble: Double = Double(UInt64.max) /** This is just like decimalSecondsStringToTimestamp, but it looks for values that seem to be * milliseconds and fixes them. That's necessary because Firefox for iOS <= 7.3 uploaded millis * when seconds were expected. */ public func someKindOfTimestampStringToTimestamp(_ input: String) -> Timestamp? { var double = 0.0 if Scanner(string: input).scanDouble(&double) { // This should never happen. Hah! if double.isNaN || double.isInfinite { return nil } // `double` will be either huge or negatively huge on overflow, and 0 on underflow. // We clamp to reasonable ranges. if double < 0 { return nil } if double >= MaxTimestampAsDouble { // Definitely not representable as a timestamp if the seconds are this large! return nil } if double > 1000000000000 { // Oh, this was in milliseconds. return Timestamp(double) } let millis = double * 1000 if millis >= MaxTimestampAsDouble { // Not representable as a timestamp. return nil } return Timestamp(millis) } return nil } public func decimalSecondsStringToTimestamp(_ input: String) -> Timestamp? { var double = 0.0 if Scanner(string: input).scanDouble(&double) { // This should never happen. Hah! if double.isNaN || double.isInfinite { return nil } // `double` will be either huge or negatively huge on overflow, and 0 on underflow. // We clamp to reasonable ranges. if double < 0 { return nil } let millis = double * 1000 if millis >= MaxTimestampAsDouble { // Not representable as a timestamp. return nil } return Timestamp(millis) } return nil } public func millisecondsToDecimalSeconds(_ input: Timestamp) -> String { let val: Double = Double(input) / 1000 return String(format: "%.2F", val) }
mpl-2.0
112006c0da43a9116089853e31aae1f2
35.564417
201
0.658725
4.829822
false
false
false
false
ChristianKienle/highway
Sources/HWKit/Command Helper/init/InitOptions.swift
1
1824
import Foundation import Arguments import Errors // highway init // highway init --type swift // highway init --type swift --create-project // highway init --type xcode public struct InitOptions { public enum ProjectType: String, RawRepresentable { case swift, xcode } public init(_ arguments: Arguments) throws { let all = arguments.all guard all.isEmpty == false else { self.init(projectType: .swift, shouldCreateProject: false) return } // We need at least two more options guard all.count >= 2 else { throw "Unknown configuration." } // First argument must be --type guard all.first == "--type" else { throw "Unknown configuration." } guard let projectType = ProjectType(rawValue: all[1]) else { throw "Unknown project type." } let shouldCreateProject = all.contains("--create-project") // creating xcode projects is not supported if projectType == .xcode && shouldCreateProject { throw "Creation of Xcode projects is not supported yet." } self.init(projectType: projectType, shouldCreateProject: shouldCreateProject) } public init(projectType: ProjectType, shouldCreateProject: Bool) { self.projectType = projectType self.shouldCreateProject = shouldCreateProject } // MARK: - Properties public var projectType: ProjectType = .xcode public var shouldCreateProject: Bool = false } extension InitOptions: Equatable { public static func ==(lhs: InitOptions, rhs: InitOptions) -> Bool { return lhs.projectType == rhs.projectType && lhs.shouldCreateProject == rhs.shouldCreateProject } }
mit
63c2ae1bb033224b155784c17613c145
30.448276
85
0.625548
5.094972
false
false
false
false
apple/swift
test/decl/protocol/existential_member_accesses_self_assoctype.swift
5
61013
// RUN: %target-typecheck-verify-swift -disable-availability-checking //===----------------------------------------------------------------------===// // Use of protocols with Self or associated type requirements //===----------------------------------------------------------------------===// struct Struct<T> { class Inner {} struct InnerGeneric<T> {} } class Class<T> {} protocol P1 { associatedtype Q // Methods func covariantSelf1() -> Self func covariantSelf2() -> Self? func covariantSelf3() -> Self.Type func covariantSelf4() -> (Self, Self) func covariantSelf5() -> Array<Self> func covariantSelf6() -> [String : Self] func covariantSelf7(_: (Self) -> Void) func covariantSelf8(_: (Self...) -> Void) func covariantSelfComplex(_: (Self.Type) -> Void, _: (Self.Type...) -> Void, _: (Array<Self>) -> Void, _: (Array<Array<Self>?>) -> Void, _: (() -> Self?) -> Void ) -> [String : () -> (Self, Self)] func covariantAssoc1() -> Q func covariantAssoc2() -> Q? func covariantAssoc3() -> Q.Type func covariantAssoc4() -> (Q, Q) func covariantAssoc5() -> Array<Q> func covariantAssoc6() -> [String : Q] func covariantAssoc7(_: (Q) -> Void) func covariantAssoc8(_: (Q...) -> Void) func covariantAssocComplex(_: (Q.Type) -> Void, _: (Q.Type...) -> Void, _: (Array<Q>) -> Void, _: (Array<Array<Q>?>) -> Void, _: (() -> Q?) -> Void ) -> [String : () -> (Q, Q)] func contravariantSelf1(_: Self?) func contravariantSelf2(_: () -> Self) func contravariantSelf3(_: Array<() -> Self>) func contravariantSelf4(_: [String : () -> Self]) func contravariantSelf5(_: () -> (Self, Self)) func contravariantSelf6(_: ((Self) -> Void) -> Void) func contravariantSelf7() -> (Self) -> Void func contravariantSelf8() -> Array<((Self) -> Void)?> func contravariantSelf9(_: [String : (() -> Self)?]) func contravariantSelf10() -> (Array<[String : Self??]>) -> Void func contravariantSelf11(_: Self.Type) func contravariantAssoc1(_: Q?) func contravariantAssoc2(_: () -> Q) func contravariantAssoc3(_: Array<() -> Q>) func contravariantAssoc4(_: [String : () -> Q]) func contravariantAssoc5(_: () -> (Q, Q)) func contravariantAssoc6(_: ((Q) -> Void) -> Void) func contravariantAssoc7() -> (Q) -> Void func contravariantAssoc8() -> Array<((Q) -> Void)?> func contravariantAssoc9(_: [String : (() -> Q)?]) func contravariantAssoc10() -> (Array<[String : Q??]>) -> Void func contravariantAssoc11(_: Q.Type) func invariantSelf1(_: inout Self) func invariantSelf2(_: (inout Self) -> Void) func invariantSelf3(_: inout Array<() -> Self>) func invariantSelf4(_: Struct<Self>) func invariantSelf5() -> Struct<Self> func invariantSelf6() -> Struct<Self>.Inner func invariantSelf7(_: (Struct<Self>) -> Void) func invariantSelf8(_: Struct<(Self) -> Void>) func invariantSelf9(_: Struct<() -> Self>) func invariantSelf10(_: any P1 & Class<Self>) func invariantSelf11() -> Struct<Self>.InnerGeneric<Void> func invariantAssoc1(_: inout Q) func invariantAssoc2(_: (inout Q) -> Void) func invariantAssoc3(_: inout Array<() -> Q>) func invariantAssoc4(_: Struct<Q>) func invariantAssoc5() -> Struct<Q> func invariantAssoc6() -> Struct<Q>.Inner func invariantAssoc7(_: (Struct<Q>) -> Void) func invariantAssoc8(_: Struct<(Q) -> Void>) func invariantAssoc9(_: Struct<() -> Q>) func invariantAssoc10(_: any P1 & Class<Q>) func invariantAssoc11() -> Struct<Q>.InnerGeneric<Void> // Properties var covariantSelfProp1: Self { get } var covariantSelfProp2: Self? { get } var covariantSelfProp3: Self.Type { get } var covariantSelfProp4: (Self, Self) { get } var covariantSelfProp5: Array<Self> { get } var covariantSelfProp6: [String : Self] { get } var covariantSelfProp7: ((Self) -> Void) -> Void { get } var covariantSelfProp8: ((Self...) -> Void) -> Void { get } var covariantSelfPropComplex: ((Self.Type) -> Void, (Self.Type...) -> Void, (Array<Self>) -> Void, (Array<Array<Self>?>) -> Void, (() -> Self?) -> Void ) -> [String : () -> (Self, Self)] { get } var covariantAssocProp1: Q { get } var covariantAssocProp2: Q? { get } var covariantAssocProp3: Q.Type { get } var covariantAssocProp4: (Q, Q) { get } var covariantAssocProp5: Array<Q> { get } var covariantAssocProp6: [String : Q] { get } var covariantAssocProp7: ((Q) -> Void) -> Void { get } var covariantAssocProp8: ((Q...) -> Void) -> Void { get } var covariantAssocPropComplex: ((Q.Type) -> Void, (Q.Type...) -> Void, (Array<Q>) -> Void, (Array<Array<Q>?>) -> Void, (() -> Q?) -> Void ) -> [String : () -> (Q, Q)] { get } var contravariantSelfProp1: (Self?) -> Void { get } var contravariantSelfProp2: (() -> Self) -> Void { get } var contravariantSelfProp3: (Array<() -> Self>) -> Void { get } var contravariantSelfProp4: ([String : () -> Self]) -> Void { get } var contravariantSelfProp5: (() -> (Self, Self)) -> Void { get } var contravariantSelfProp6: (((Self) -> Void) -> Void) -> Void { get } var contravariantSelfProp7: (Self) -> Void { get } var contravariantSelfProp8: Array<((Self) -> Void)?> { get } var contravariantSelfProp9: ([String : (() -> Self)?]) -> Void { get } var contravariantSelfProp10: (Array<[String : Self??]>) -> Void { get } var contravariantSelfProp11: (Self.Type) -> Void { get } var contravariantAssocProp1: (Q?) -> Void { get } var contravariantAssocProp2: (() -> Q) -> Void { get } var contravariantAssocProp3: (Array<() -> Q>) -> Void { get } var contravariantAssocProp4: ([String : () -> Q]) -> Void { get } var contravariantAssocProp5: (() -> (Q, Q)) -> Void { get } var contravariantAssocProp6: (((Q) -> Void) -> Void) -> Void { get } var contravariantAssocProp7: (Q) -> Void { get } var contravariantAssocProp8: Array<((Q) -> Void)?> { get } var contravariantAssocProp9: ([String : (() -> Q)?]) -> Void { get } var contravariantAssocProp10: (Array<[String : Q??]>) -> Void { get } var contravariantAssocProp11: (Q.Type) -> Void { get } var invariantSelfProp1: (inout Self) -> Void { get } var invariantSelfProp2: ((inout Self) -> Void) -> Void { get } var invariantSelfProp3: (inout Array<() -> Self>) -> Void { get } var invariantSelfProp4: (Struct<Self>) -> Void { get } var invariantSelfProp5: Struct<Self> { get } var invariantSelfProp6: Struct<Self>.Inner { get } var invariantSelfProp7: ((Struct<Self>) -> Void) -> Void { get } var invariantSelfProp8: (Struct<(Self) -> Void>) -> Void { get } var invariantSelfProp9: (Struct<() -> Self>) -> Void { get } var invariantSelfProp10: (any P1 & Class<Self>) -> Void { get } var invariantSelfProp11: Struct<Self>.InnerGeneric<Void> { get } var invariantAssocProp1: (inout Q) -> Void { get } var invariantAssocProp2: ((inout Q) -> Void) -> Void { get } var invariantAssocProp3: (inout Array<() -> Q>) -> Void { get } var invariantAssocProp4: (Struct<Q>) -> Void { get } var invariantAssocProp5: Struct<Q> { get } var invariantAssocProp6: Struct<Q>.Inner { get } var invariantAssocProp7: ((Struct<Q>) -> Void) { get } var invariantAssocProp8: (Struct<(Q) -> Void>) { get } var invariantAssocProp9: (Struct<() -> Q>) -> Void { get } var invariantAssocProp10: (any P1 & Class<Q>) -> Void { get } var invariantAssocProp11: Struct<Q>.InnerGeneric<Void> { get } // Subscripts subscript(covariantSelfSubscript1 _: Void) -> Self { get } subscript(covariantSelfSubscript2 _: Void) -> Self? { get } subscript(covariantSelfSubscript3 _: Void) -> Self.Type { get } subscript(covariantSelfSubscript4 _: Void) -> (Self, Self) { get } subscript(covariantSelfSubscript5 _: Void) -> Array<Self> { get } subscript(covariantSelfSubscript6 _: Void) -> [String : Self] { get } subscript(covariantSelfSubscript7 _: (Self) -> Void) -> Self { get } subscript(covariantSelfSubscript8 _: (Self...) -> Void) -> Self { get } subscript(covariantSelfSubscriptComplex _: (Self.Type) -> Void, _: (Self.Type...) -> Void, _: (Array<Self>) -> Void, _: (Array<Array<Self>?>) -> Void, _: (() -> Self?) -> Void ) -> [String : () -> (Self, Self)] { get } subscript(covariantAssocSubscript1 _: Void) -> Q { get } subscript(covariantAssocSubscript2 _: Void) -> Q? { get } subscript(covariantAssocSubscript3 _: Void) -> Q.Type { get } subscript(covariantAssocSubscript4 _: Void) -> (Q, Q) { get } subscript(covariantAssocSubscript5 _: Void) -> Array<Q> { get } subscript(covariantAssocSubscript6 _: Void) -> [String : Q] { get } subscript(covariantAssocSubscript7 _: (Q) -> Void) -> Q { get } subscript(covariantAssocSubscript8 _: (Q...) -> Void) -> Self { get } subscript(covariantAssocSubscriptComplex _: (Q.Type) -> Void, _: (Q.Type...) -> Void, _: (Array<Q>) -> Void, _: (Array<Array<Q>?>) -> Void, _: (() -> Q?) -> Void ) -> [String : () -> (Q, Q)] { get } subscript(contravariantSelfSubscript1 _: Self?) -> Void { get } subscript(contravariantSelfSubscript2 _: () -> Self) -> Void { get } subscript(contravariantSelfSubscript3 _: Array<() -> Self>) -> Void { get } subscript(contravariantSelfSubscript4 _: [String : () -> Self]) -> Void { get } subscript(contravariantSelfSubscript5 _: () -> (Self, Self)) -> Void { get } subscript(contravariantSelfSubscript6 _: ((Self) -> Void) -> Void) -> Void { get } subscript(contravariantSelfSubscript7 _: Void) -> (Self) -> Void { get } subscript(contravariantSelfSubscript8 _: Void) -> Array<((Self) -> Void)?> { get } subscript(contravariantSelfSubscript9 _: [String : (() -> Self)?]) -> Void { get } subscript(contravariantSelfSubscript10 _: Void) -> (Array<[String : Self??]>) -> Void { get } subscript(contravariantSelfSubscript11 _: Self.Type) -> Void { get } subscript(contravariantAssocSubscript1 _: Q?) -> Void { get } subscript(contravariantAssocSubscript2 _: () -> Q) -> Void { get } subscript(contravariantAssocSubscript3 _: Array<() -> Q>) -> Void { get } subscript(contravariantAssocSubscript4 _: [String : () -> Q]) -> Void { get } subscript(contravariantAssocSubscript5 _: () -> (Q, Q)) -> Void { get } subscript(contravariantAssocSubscript6 _: ((Q) -> Void) -> Void) -> Void { get } subscript(contravariantAssocSubscript7 _: Void) -> (Q) -> Void { get } subscript(contravariantAssocSubscript8 _: Void) -> Array<((Q) -> Void)?> { get } subscript(contravariantAssocSubscript9 _: [String : (() -> Q)?]) -> Void { get } subscript(contravariantAssocSubscript10 _: Void) -> (Array<[String : Q??]>) -> Void { get } subscript(contravariantAssocSubscript11 _: Q.Type) -> Void { get } subscript(invariantSelfSubscript1 _: Struct<Self>) -> Void { get } subscript(invariantSelfSubscript2 _: Void) -> Struct<Self> { get } subscript(invariantSelfSubscript3 _: Void) -> Struct<Self>.Inner { get } subscript(invariantSelfSubscript4 _: (Struct<Self>) -> Void) -> Void { get } subscript(invariantSelfSubscript5 _: Struct<(Self) -> Void>) -> Void { get } subscript(invariantSelfSubscript6 _: Struct<() -> Self>) -> Void { get } subscript(invariantSelfSubscript7 _: any P1 & Class<Self>) -> Void { get } subscript(invariantSelfSubscript8 _: Void) -> Struct<Self>.InnerGeneric<Void> { get } subscript(invariantAssocSubscript1 _: Struct<Q>) -> Void { get } subscript(invariantAssocSubscript2 _: Void) -> Struct<Q> { get } subscript(invariantAssocSubscript3 _: Void) -> Struct<Q>.Inner { get } subscript(invariantAssocSubscript4 _: (Struct<Q>) -> Void) -> Void { get } subscript(invariantAssocSubscript5 _: Struct<(Q) -> Void>) -> Void { get } subscript(invariantAssocSubscript6 _: Struct<() -> Q>) -> Void { get } subscript(invariantAssocSubscript7 _: any P1 & Class<Q>) -> Void { get } subscript(invariantAssocSubscript8 _: Void) -> Struct<Q>.InnerGeneric<Void> { get } } extension P1 { func opaqueResultTypeMethod() -> some P1 { self } var opaqueResultTypeProp: some P1 { self } subscript(opaqueResultTypeSubscript _: Bool) -> some P1 { self } } do { func testP1(arg: any P1) { let _: any P1 = arg.covariantSelf1() let _: (any P1)? = arg.covariantSelf2() let _: any P1.Type = arg.covariantSelf3() let _: (any P1, any P1) = arg.covariantSelf4() let _: Array<any P1> = arg.covariantSelf5() let _: [String : any P1] = arg.covariantSelf6() arg.covariantSelf7 { (_: any P1) in } arg.covariantSelf8 { (_: any P1...) in } let _: [String : () -> (any P1, any P1)] = arg.covariantSelfComplex( { (_: any P1.Type) in }, { (_: any P1.Type...) in }, { (_: Array<any P1>) in }, { (_: Array<Array<any P1>?>) in }, { (_: () -> (any P1)?) in } ) let _: Any = arg.covariantAssoc1() let _: Any? = arg.covariantAssoc2() let _: Any.Type = arg.covariantAssoc3() let _: (Any, Any) = arg.covariantAssoc4() let _: Array<Any> = arg.covariantAssoc5() let _: [String : Any] = arg.covariantAssoc6() arg.covariantAssoc7 { (_: Any) in } arg.covariantAssoc8 { (_: Any...) in } let _: [String : () -> (Any, Any)] = arg.covariantAssocComplex( { (_: Any.Type) in }, { (_: Any.Type...) in }, { (_: Array<Any>) in }, { (_: Array<Array<Any>?>) in }, { (_: () -> Any?) in } ) let _: any P1 = arg.covariantSelfProp1 let _: (any P1)? = arg.covariantSelfProp2 let _: any P1.Type = arg.covariantSelfProp3 let _: (any P1, any P1) = arg.covariantSelfProp4 let _: Array<any P1> = arg.covariantSelfProp5 let _: [String : any P1] = arg.covariantSelfProp6 let _: ((any P1) -> Void) -> Void = arg.covariantSelfProp7 let _: ((any P1...) -> Void) -> Void = arg.covariantSelfProp8 let _: ( (any P1.Type) -> Void, (any P1.Type...) -> Void, (Array<any P1>) -> Void, (Array<Array<any P1>?>) -> Void, (() -> (any P1)?) -> Void ) -> [String : () -> (any P1, any P1)] = arg.covariantSelfPropComplex let _: Any = arg.covariantAssocProp1 let _: Any? = arg.covariantAssocProp2 let _: Any.Type = arg.covariantAssocProp3 let _: (Any, Any) = arg.covariantAssocProp4 let _: Array<Any> = arg.covariantAssocProp5 let _: [String : Any] = arg.covariantAssocProp6 let _: ((Any) -> Void) -> Void = arg.covariantAssocProp7 let _: ((Any...) -> Void) -> Void = arg.covariantAssocProp8 let _: ( (Any.Type) -> Void, (Any.Type...) -> Void, (Array<Any>) -> Void, (Array<Array<Any>?>) -> Void, (() -> Any?) -> Void ) -> [String : () -> (Any, Any)] = arg.covariantAssocPropComplex let _: any P1 = arg[covariantSelfSubscript1: ()] let _: (any P1)? = arg[covariantSelfSubscript2: ()] let _: any P1.Type = arg[covariantSelfSubscript3: ()] let _: (any P1, any P1) = arg[covariantSelfSubscript4: ()] let _: Array<any P1> = arg[covariantSelfSubscript5: ()] let _: [String : any P1] = arg[covariantSelfSubscript6: ()] let _: any P1 = arg[covariantSelfSubscript7: { (_: any P1) in }] let _: any P1 = arg[covariantSelfSubscript8: { (_: any P1...) in }] let _: [String : () -> (any P1, any P1)] = arg[ covariantSelfSubscriptComplex: { (_: any P1.Type) in }, { (_: any P1.Type...) in }, { (_: Array<any P1>) in }, { (_: Array<Array<any P1>?>) in }, { (_: () -> (any P1)?) in } ] let _: Any = arg[covariantAssocSubscript1: ()] let _: Any? = arg[covariantAssocSubscript2: ()] let _: Any.Type = arg[covariantAssocSubscript3: ()] let _: (Any, Any) = arg[covariantAssocSubscript4: ()] let _: Array<Any> = arg[covariantAssocSubscript5: ()] let _: [String : Any] = arg[covariantAssocSubscript6: ()] let _: Any = arg[covariantAssocSubscript7: { (_: Any) in }] let _: Any = arg[covariantAssocSubscript8: { (_: Any...) in }] let _: [String : () -> (Any, Any)] = arg[ covariantAssocSubscriptComplex: { (_: Any.Type) in }, { (_: Any.Type...) in }, { (_: Array<Any>) in }, { (_: Array<Array<Any>?>) in }, { (_: () -> Any?) in } ] let _: any P1 = arg.opaqueResultTypeMethod() let _: any P1 = arg.opaqueResultTypeProp let _: any P1 = arg[opaqueResultTypeSubscript: true] arg.contravariantSelf1(0) // expected-error {{member 'contravariantSelf1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf2(0) // expected-error {{member 'contravariantSelf2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf3(0) // expected-error {{member 'contravariantSelf3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf4(0) // expected-error {{member 'contravariantSelf4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf5(0) // expected-error {{member 'contravariantSelf5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf6(0) // expected-error {{member 'contravariantSelf6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf7() // expected-error {{member 'contravariantSelf7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf8() // expected-error {{member 'contravariantSelf8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf9(0) // expected-error {{member 'contravariantSelf9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf10() // expected-error {{member 'contravariantSelf10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf11(0) // expected-error {{member 'contravariantSelf11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc1(0) // expected-error {{member 'contravariantAssoc1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc2(0) // expected-error {{member 'contravariantAssoc2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc3(0) // expected-error {{member 'contravariantAssoc3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc4(0) // expected-error {{member 'contravariantAssoc4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc5(0) // expected-error {{member 'contravariantAssoc5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc6(0) // expected-error {{member 'contravariantAssoc6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc7() // expected-error {{member 'contravariantAssoc7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc8() // expected-error {{member 'contravariantAssoc8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc9(0) // expected-error {{member 'contravariantAssoc9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc10() // expected-error {{member 'contravariantAssoc10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc11(0) // expected-error {{member 'contravariantAssoc11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf1(0) // expected-error {{member 'invariantSelf1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf2(0) // expected-error {{member 'invariantSelf2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf3(0) // expected-error {{member 'invariantSelf3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf4(0) // expected-error {{member 'invariantSelf4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf5() // expected-error {{member 'invariantSelf5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf6() // expected-error {{member 'invariantSelf6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf7(0) // expected-error {{member 'invariantSelf7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf8(0) // expected-error {{member 'invariantSelf8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf9(0) // expected-error {{member 'invariantSelf9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf10(0) // expected-error {{member 'invariantSelf10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf11() // expected-error {{member 'invariantSelf11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc1(0) // expected-error {{member 'invariantAssoc1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc2(0) // expected-error {{member 'invariantAssoc2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc3(0) // expected-error {{member 'invariantAssoc3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc4(0) // expected-error {{member 'invariantAssoc4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc5() // expected-error {{member 'invariantAssoc5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc6() // expected-error {{member 'invariantAssoc6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc7(0) // expected-error {{member 'invariantAssoc7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc8(0) // expected-error {{member 'invariantAssoc8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc9(0) // expected-error {{member 'invariantAssoc9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc10(0) // expected-error {{member 'invariantAssoc10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc11() // expected-error {{member 'invariantAssoc11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp1 // expected-error {{member 'contravariantSelfProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp2 // expected-error {{member 'contravariantSelfProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp3 // expected-error {{member 'contravariantSelfProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp4 // expected-error {{member 'contravariantSelfProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp5 // expected-error {{member 'contravariantSelfProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp6 // expected-error {{member 'contravariantSelfProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp7 // expected-error {{member 'contravariantSelfProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp8 // expected-error {{member 'contravariantSelfProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp9 // expected-error {{member 'contravariantSelfProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp10 // expected-error {{member 'contravariantSelfProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp11 // expected-error {{member 'contravariantSelfProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp1 // expected-error {{member 'contravariantAssocProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp2 // expected-error {{member 'contravariantAssocProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp3 // expected-error {{member 'contravariantAssocProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp4 // expected-error {{member 'contravariantAssocProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp5 // expected-error {{member 'contravariantAssocProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp6 // expected-error {{member 'contravariantAssocProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp7 // expected-error {{member 'contravariantAssocProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp8 // expected-error {{member 'contravariantAssocProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp9 // expected-error {{member 'contravariantAssocProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp10 // expected-error {{member 'contravariantAssocProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp11 // expected-error {{member 'contravariantAssocProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp1 // expected-error {{member 'invariantSelfProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp2 // expected-error {{member 'invariantSelfProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp3 // expected-error {{member 'invariantSelfProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp4 // expected-error {{member 'invariantSelfProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp5 // expected-error {{member 'invariantSelfProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp6 // expected-error {{member 'invariantSelfProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp7 // expected-error {{member 'invariantSelfProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp8 // expected-error {{member 'invariantSelfProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp9 // expected-error {{member 'invariantSelfProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp10 // expected-error {{member 'invariantSelfProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp11 // expected-error {{member 'invariantSelfProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp1 // expected-error {{member 'invariantAssocProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp2 // expected-error {{member 'invariantAssocProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp3 // expected-error {{member 'invariantAssocProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp4 // expected-error {{member 'invariantAssocProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp5 // expected-error {{member 'invariantAssocProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp6 // expected-error {{member 'invariantAssocProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp7 // expected-error {{member 'invariantAssocProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp8 // expected-error {{member 'invariantAssocProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp9 // expected-error {{member 'invariantAssocProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp10 // expected-error {{member 'invariantAssocProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp11 // expected-error {{member 'invariantAssocProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript2: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript3: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript7: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript9: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript10: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript11: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript2: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript3: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript7: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript9: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript10: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript11: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript2: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript3: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript7: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript2: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript3: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript7: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} } } protocol P1_TypeMemberOnInstanceAndViceVersa { static func static_covariantSelfMethod() -> Self static var static_covariantSelfProp: Self { get } static subscript(static_covariantSelfSubscript _: Void) -> Self { get } static func static_invariantSelfMethod() -> Struct<Self> static var static_invariantSelfProp: Struct<Self> { get } static subscript(static_invariantSelfSubscript _: Void) -> Struct<Self> { get } func covariantSelfMethod() -> Self func invariantSelfMethod() -> Struct<Self> var invariantSelfProp: Struct<Self> { get } subscript(invariantSelfSubscript _: Void) -> Struct<Self> { get } } do { // Test that invalid reference errors prevail over unsupported existential // member accesses. func test(protoMeta: (any P1_TypeMemberOnInstanceAndViceVersa).Type, existMeta: any P1_TypeMemberOnInstanceAndViceVersa.Type, instance: any P1_TypeMemberOnInstanceAndViceVersa) { // P1_TypeMemberOnInstanceAndViceVersa.Protocol protoMeta.static_invariantSelfMethod() // expected-error {{static member 'static_invariantSelfMethod' cannot be used on protocol metatype '(any P1_TypeMemberOnInstanceAndViceVersa).Type'}} protoMeta.static_invariantSelfProp // expected-error {{static member 'static_invariantSelfProp' cannot be used on protocol metatype '(any P1_TypeMemberOnInstanceAndViceVersa).Type'}} protoMeta[static_invariantSelfSubscript: ()] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P1_TypeMemberOnInstanceAndViceVersa).Type'}} _ = protoMeta.covariantSelfMethod // ok protoMeta.invariantSelfMethod // expected-error {{member 'invariantSelfMethod' cannot be used on value of type '(any P1_TypeMemberOnInstanceAndViceVersa).Type'; consider using a generic constraint instead}} protoMeta.invariantSelfProp // expected-error {{instance member 'invariantSelfProp' cannot be used on type 'any P1_TypeMemberOnInstanceAndViceVersa'}} protoMeta[invariantSelfSubscript: ()] // expected-error {{instance member 'subscript' cannot be used on type 'any P1_TypeMemberOnInstanceAndViceVersa'}} // P1_TypeMemberOnInstanceAndViceVersa.Type _ = existMeta.static_covariantSelfMethod // ok _ = existMeta.static_covariantSelfProp // ok _ = existMeta[static_covariantSelfSubscript: ()] // ok existMeta.static_invariantSelfMethod // expected-error {{member 'static_invariantSelfMethod' cannot be used on value of type 'any P1_TypeMemberOnInstanceAndViceVersa.Type'; consider using a generic constraint instead}} existMeta.static_invariantSelfProp // expected-error {{member 'static_invariantSelfProp' cannot be used on value of type 'any P1_TypeMemberOnInstanceAndViceVersa.Type'; consider using a generic constraint instead}} existMeta[static_invariantSelfSubscript: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1_TypeMemberOnInstanceAndViceVersa.Type'; consider using a generic constraint instead}} existMeta.invariantSelfMethod // expected-error {{instance member 'invariantSelfMethod' cannot be used on type 'P1_TypeMemberOnInstanceAndViceVersa'}} existMeta.invariantSelfProp // expected-error {{instance member 'invariantSelfProp' cannot be used on type 'P1_TypeMemberOnInstanceAndViceVersa'}} existMeta[invariantSelfSubscript: ()] // expected-error {{instance member 'subscript' cannot be used on type 'P1_TypeMemberOnInstanceAndViceVersa'}} // P1_TypeMemberOnInstanceAndViceVersa instance.static_invariantSelfMethod // expected-error {{static member 'static_invariantSelfMethod' cannot be used on instance of type 'any P1_TypeMemberOnInstanceAndViceVersa'}} instance.static_invariantSelfProp // expected-error {{static member 'static_invariantSelfProp' cannot be used on instance of type 'any P1_TypeMemberOnInstanceAndViceVersa'}} instance[static_invariantSelfSubscript: ()] // expected-error {{static member 'subscript' cannot be used on instance of type 'any P1_TypeMemberOnInstanceAndViceVersa'}} } } // A protocol member accessed with an existential value might have generic // constraints that require the ability to spell an opened archetype in order // to be satisfied. Such are // - superclass requirements, when the object is a non-'Self'-rooted type // parameter, and the subject is dependent on 'Self', e.g. U : G<Self.A> // - same-type requirements, when one side is dependent on 'Self', and the // other is a non-'Self'-rooted type parameter, e.g. U.Element == Self. // // Because opened archetypes are not part of the surface language, these // constraints render the member inaccessible. // // Note: 'Self'-rooted type parameters that are invalid in the context of the // existential base type are ignored -- the underlying requirement failure is // considered a more pressing issue. protocol UnfulfillableGenericRequirements { associatedtype A } extension UnfulfillableGenericRequirements { func method1() where A : Class<Self> {} func method2() where A: Sequence, A.Element == Self {} func method3<U>(_: U) -> U {} func method4<U>(_: U) where U : Class<Self.A> {} // expected-note@-1 3 {{where 'U' = 'Bool'}} func method5<U>(_: U) where U: Sequence, Self == U.Element {} // expected-note@-1 {{where 'U' = 'Bool'}} // expected-note@+1 2 {{where 'U' = 'Bool'}} func method6<U>(_: U) where U: UnfulfillableGenericRequirements, A: Sequence, A.Element: Sequence, U.A == A.Element.Element {} func method7<U>(_: U) where U: UnfulfillableGenericRequirements & Class<Self> {} func method8<U>(_: U) where U == Self.A {} } do { let exist: any UnfulfillableGenericRequirements exist.method1() // expected-error {{instance method 'method1()' requires that 'Self.A' inherit from 'Class<Self>'}} exist.method2() // expected-error@-1 {{instance method 'method2()' requires the types 'Self' and 'Self.A.Element' be equivalent}} // expected-error@-2 {{instance method 'method2()' requires that 'Self.A' conform to 'Sequence'}} _ = exist.method3(false) // ok exist.method4(false) // expected-error@-1 {{instance method 'method4' requires that 'Bool' inherit from 'Class<Self.A>'}} // expected-error@-2 {{member 'method4' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} exist.method5(false) // expected-error@-1 {{instance method 'method5' requires that 'Bool' conform to 'Sequence'}} // expected-error@-2 {{member 'method5' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} exist.method7(false) // expected-error@-1 {{instance method 'method7' requires that 'U' conform to 'UnfulfillableGenericRequirements'}} // expected-error@-2 {{member 'method7' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} exist.method8(false) // expected-error@-1 {{member 'method8' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} } // Make sure this also works in a generic context! struct G<X, Y, Z> { func doIt() { let exist: any UnfulfillableGenericRequirements exist.method8(false) // expected-error@-1 {{member 'method8' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} } } protocol UnfulfillableGenericRequirementsDerived1: UnfulfillableGenericRequirements where A == Bool {} protocol UnfulfillableGenericRequirementsDerived2: UnfulfillableGenericRequirements where A == Class<Self> {} do { // Test that 'Self' dependencies are computed relative to the base type. let exist1: any UnfulfillableGenericRequirementsDerived1 let exist2: any UnfulfillableGenericRequirementsDerived2 exist1.method4(false) // expected-error@-1 {{instance method 'method4' requires that 'Bool' inherit from 'Class<Self.A>}} exist2.method4(false) // expected-error@-1 {{member 'method4' cannot be used on value of type 'any UnfulfillableGenericRequirementsDerived2'; consider using a generic constraint instead}} // expected-error@-2 {{instance method 'method4' requires that 'Bool' inherit from 'Class<Self.A>'}} } protocol UnfulfillableGenericRequirementsDerived3: UnfulfillableGenericRequirements where A: Sequence, A.Element: Sequence {} do { // Test that 'Self'-rooted type parameters that are invalid in the context of // the existential base type are ignored. let exist1: any UnfulfillableGenericRequirements let exist2: any UnfulfillableGenericRequirementsDerived3 exist1.method6(false) // expected-error@-1 {{instance method 'method6' requires that 'Self.A.Element' conform to 'Sequence'}} // expected-error@-2 {{instance method 'method6' requires that 'Self.A' conform to 'Sequence'}} // expected-error@-3 {{instance method 'method6' requires that 'Bool' conform to 'UnfulfillableGenericRequirements'}} exist2.method6(false) // expected-error@-1 {{member 'method6' cannot be used on value of type 'any UnfulfillableGenericRequirementsDerived3'; consider using a generic constraint instead}} // expected-error@-2 {{instance method 'method6' requires that 'Bool' conform to 'UnfulfillableGenericRequirements'}} } // Test that we don't determine existential availability based on type // parameters that are invalid in the context of the existential base type -- // the requirement failure is a more pressing issue. protocol InvalidTypeParameters { associatedtype A } extension InvalidTypeParameters { func method1() -> A.A where A: InvalidTypeParameters {} func method2(_: A.A) where A: InvalidTypeParameters {} func method3(_: A.A, _: A) where A: InvalidTypeParameters {} } do { let exist: any InvalidTypeParameters exist.method1() // expected-error {{instance method 'method1()' requires that 'Self.A' conform to 'InvalidTypeParameters'}} exist.method2(false) // expected-error {{instance method 'method2' requires that 'Self.A' conform to 'InvalidTypeParameters'}} exist.method3(false, false) // expected-error {{instance method 'method3' requires that 'Self.A' conform to 'InvalidTypeParameters'}} // expected-error@-1 {{member 'method3' cannot be used on value of type 'any InvalidTypeParameters'; consider using a generic constraint instead}} } protocol GenericRequirementFailures { associatedtype A } extension GenericRequirementFailures where A == Never { func method1() {} func method2() -> Self {} func method3(_: A) {} } extension GenericRequirementFailures where A: GenericRequirementFailures { func method4() {} } do { let exist: any GenericRequirementFailures exist.method1() // expected-error {{referencing instance method 'method1()' on 'GenericRequirementFailures' requires the types 'Self.A' and 'Never' be equivalent}} exist.method2() // expected-error {{referencing instance method 'method2()' on 'GenericRequirementFailures' requires the types 'Self.A' and 'Never' be equivalent}} exist.method3(false) // expected-error {{referencing instance method 'method3' on 'GenericRequirementFailures' requires the types 'Self.A' and 'Never' be equivalent}} // expected-error@-1 {{member 'method3' cannot be used on value of type 'any GenericRequirementFailures'; consider using a generic constraint instead}} exist.method4() // expected-error {{referencing instance method 'method4()' on 'GenericRequirementFailures' requires that 'Self.A' conform to 'GenericRequirementFailures'}} } protocol GenericRequirementFailuresDerived: GenericRequirementFailures where A: GenericRequirementFailures {} do { let exist: any GenericRequirementFailuresDerived exist.method4() // ok } // Settable storage members with a 'Self' result type may not be used with an // existential base. protocol P2 { subscript() -> Self { get set } var prop: Self { get set } } func takesP2(p2: any P2) { _ = p2[] // expected-error@-1{{member 'subscript' cannot be used on value of type 'any P2'; consider using a generic constraint instead}} _ = p2.prop // expected-error@-1{{member 'prop' cannot be used on value of type 'any P2'; consider using a generic constraint instead}} } protocol MiscTestsProto { associatedtype R : IteratorProtocol, Sequence func getR() -> R associatedtype Assoc subscript() -> Assoc { get } var getAssoc: Assoc? { get } } do { func miscTests(_ arg: any MiscTestsProto) { var r: any Sequence & IteratorProtocol = arg.getR() r.makeIterator() // expected-error {{inferred result type 'any IteratorProtocol' requires explicit coercion due to loss of generic requirements}} {{19-19=as any IteratorProtocol}} r.next() // expected-warning {{result of call to 'next()' is unused}} r.nonexistent() // expected-error {{value of type 'any IteratorProtocol & Sequence' has no member 'nonexistent'}} arg[] // expected-warning {{expression of type 'Any' is unused}} arg.getAssoc // expected-warning {{expression of type 'Any?' is unused}} } } // Test that covariant erasure turns metatypes into existential metatypes. protocol CovariantMetatypes { associatedtype Q func covariantSelfMetatype1(_: (Self.Type.Type.Type) -> Void) func covariantSelfMetatype2() -> (Self.Type, Self.Type.Type) func covariantAssocMetatype1(_: (Q.Type.Type.Type) -> Void) func covariantAssocMetatype2() -> (Q.Type, Q.Type.Type) var covariantSelfMetatypeProp1: Self.Type.Type.Type { get } var covariantSelfMetatypeProp2: (Self.Type, Self.Type.Type) { get } var covariantAssocMetatypeProp1: Q.Type.Type.Type { get } var covariantAssocMetatypeProp2: (Q.Type, Q.Type.Type) { get } subscript(covariantSelfMetatypeSubscript1 _: (Self.Type.Type.Type) -> Void) -> Self.Type { get } subscript(covariantSelfMetatypeSubscript2 _: Void) -> (Self.Type, Self.Type.Type) { get } subscript(covariantAssocMetatypeSubscript1 _: (Q.Type.Type.Type) -> Void) -> Q.Type { get } subscript(covariantAssocMetatypeSubscript2 _: Void) -> (Q.Type, Q.Type.Type) { get } } do { func testCovariantMetatypes(arg: any CovariantMetatypes) { arg.covariantSelfMetatype1 { (_: any CovariantMetatypes.Type.Type.Type) in } let _: (any CovariantMetatypes.Type, any CovariantMetatypes.Type.Type) = arg.covariantSelfMetatype2() arg.covariantAssocMetatype1 { (_: Any.Type.Type.Type) in } let _: (Any.Type, Any.Type.Type) = arg.covariantAssocMetatype2() let _: any CovariantMetatypes.Type.Type.Type = arg.covariantSelfMetatypeProp1 let _: (any CovariantMetatypes.Type, any CovariantMetatypes.Type.Type) = arg.covariantSelfMetatypeProp2 let _: Any.Type.Type.Type = arg.covariantAssocMetatypeProp1 let _: (Any.Type, Any.Type.Type) = arg.covariantAssocMetatypeProp2 let _: any CovariantMetatypes.Type = arg[covariantSelfMetatypeSubscript1: { (_: any CovariantMetatypes.Type.Type.Type) in }] let _: (any CovariantMetatypes.Type, any CovariantMetatypes.Type.Type) = arg[covariantSelfMetatypeSubscript2: ()] let _: Any.Type = arg[covariantAssocMetatypeSubscript1: { (_: Any.Type.Type.Type) in }] let _: (Any.Type, Any.Type.Type) = arg[covariantAssocMetatypeSubscript2: ()] } } // Test that a reference to a 'Self'-rooted dependent member type does not // affect the ability to reference a protocol member on an existential when // it is *fully* concrete. protocol ConcreteAssocTypes { associatedtype A1 where A1 == Struct<Self> associatedtype A2 where A2 == (Bool, Self) associatedtype A3 where A3 == any Class<A4> & ConcreteAssocTypes associatedtype A4 func method1(_: A1) func method2() -> Struct<A2> func method3(_: A3) var property1: A1 { get } var property2: A2 { get } var property3: A3 { get } subscript(subscript1 _: A3) -> Bool { get } subscript(subscript2 _: Bool) -> A1 { get } subscript(subscript3 _: A2) -> Bool { get } associatedtype A5 where A5 == Bool associatedtype A6 where A6 == any ConcreteAssocTypes associatedtype A7 where A7 == A8.A5 associatedtype A8: ConcreteAssocTypes func method4(_: Struct<A5>, _: A6.Type, _: () -> A5) -> any Class<Struct<A7>.Inner> & ConcreteAssocTypes var property4: (Struct<A5>, A6.Type, () -> A5) -> any Class<Struct<A7>.Inner> & ConcreteAssocTypes { get } subscript(subscript4 _: Struct<A5>, _: A6.Type, _: () -> A5) -> any Class<Struct<A7>.Inner> & ConcreteAssocTypes { get } } do { func test(arg: any ConcreteAssocTypes) { _ = arg.method1 // expected-error {{member 'method1' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg.method2 // expected-error {{member 'method2' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg.method3 // expected-error {{member 'method3' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg.property1 // expected-error {{member 'property1' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} // Covariant 'Self' erasure works in conjunction with concrete associated types. let _: (Bool, any ConcreteAssocTypes) = arg.property2 // ok _ = arg.property3 // expected-error {{member 'property3' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg[subscript1: false] // expected-error {{member 'subscript' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg[subscript2: false] // expected-error {{member 'subscript' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg[subscript3: false] // expected-error {{member 'subscript' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} let _: ( Struct<Bool>, (any ConcreteAssocTypes).Type, () -> Bool ) -> any Class<Struct<Bool>.Inner> & ConcreteAssocTypes = arg.method4 let _: ( Struct<Bool>, (any ConcreteAssocTypes).Type, () -> Bool ) -> any Class<Struct<Bool>.Inner> & ConcreteAssocTypes = arg.property4 let _: any Class<Struct<Bool>.Inner> & ConcreteAssocTypes = arg[ subscript4: Struct<Bool>(), (any ConcreteAssocTypes).self, { true } ] } } protocol ConcreteAssocTypeComposition1 { associatedtype A func method(_: A) } protocol ConcreteAssocTypeComposition2 where A == Bool { associatedtype A } do { let exist: any ConcreteAssocTypeComposition1 & ConcreteAssocTypeComposition2 exist.method(true) // ok } // Edge case: an associated type can be resolved through a class conformance. class Class1Simple: ConcreteAssocTypeThroughClass { typealias A = Bool } class Class1Generic<A>: ConcreteAssocTypeThroughClass { } protocol ConcreteAssocTypeThroughClass { associatedtype A } protocol ConcreteAssocTypeThroughClassRefined: ConcreteAssocTypeThroughClass { func method(_: A) } extension ConcreteAssocTypeThroughClassRefined { func test(arg1: any ConcreteAssocTypeThroughClassRefined & Class1Generic<Self>, arg2: any ConcreteAssocTypeThroughClassRefined & Class1Simple) { arg1.method(self) // ok arg2.method(true) // ok } } protocol ConcreteAssocTypeCollision1 where A == Bool { associatedtype A func method(_: A) } protocol ConcreteAssocTypeCollision2 where A == Never { associatedtype A } do { let exist: any ConcreteAssocTypeCollision1 & ConcreteAssocTypeCollision2 // FIXME: Should 'A' be ambiguous here? exist.method(true) } class BadConformanceClass: CompositionBrokenClassConformance_a {} // expected-error@-1 {{type 'BadConformanceClass' does not conform to protocol 'CompositionBrokenClassConformance_a'}} protocol CompositionBrokenClassConformance_a { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} } protocol CompositionBrokenClassConformance_b: CompositionBrokenClassConformance_a { func method(_: A) } do { // FIXME: Should GenericSignature::getConcreteType return the null type instead // of the error type here for Self.A, despite the broken conformance? let exist: any CompositionBrokenClassConformance_b & BadConformanceClass exist.method(false) // expected-error {{type of expression is ambiguous without more context}} } /// Covariant Associated Type Erasure class Class2Base {} class Class2Derived<T>: Class2Base {} protocol CovariantAssocTypeErasure { associatedtype A1 associatedtype A2: AnyObject associatedtype A3: CovariantAssocTypeErasure associatedtype A4: Class2Base associatedtype A5: Class2Derived<Self> associatedtype A6: CovariantAssocTypeErasure & Class2Base associatedtype A7: Class2Derived<Self> & CovariantAssocTypeErasure associatedtype B1 where B1 == Optional<A1> associatedtype B2 where B2 == (A2, Bool) associatedtype B3 where B3 == A3.Type associatedtype B4 where B4 == Array<A4> associatedtype B5 where B5 == Dictionary<String, A5> func method1() -> A1 func method2() -> A2 func method3() -> A3 func method4() -> A4 func method5() -> A5 func method6() -> A6 func method7() -> A7 func method8() -> B1 func method9() -> B2 func method10() -> B3 func method11() -> B4 func method12() -> B5 } protocol CovariantAssocTypeErasureDerived: CovariantAssocTypeErasure where A1: CovariantAssocTypeErasureDerived, A2: Class2Base, A3: CovariantAssocTypeErasureDerived, A4: CovariantAssocTypeErasureDerived, A5: CovariantAssocTypeErasureDerived, A6: CovariantAssocTypeErasureDerived, A7: Sequence {} do { let exist: any CovariantAssocTypeErasure let _: Any = exist.method1() let _: AnyObject = exist.method2() let _: any CovariantAssocTypeErasure = exist.method3() let _: Class2Base = exist.method4() let _: Class2Base = exist.method5() let _: any Class2Base & CovariantAssocTypeErasure = exist.method6() let _: any Class2Base & CovariantAssocTypeErasure = exist.method7() let _: Any? = exist.method8() let _: (AnyObject, Bool) = exist.method9() let _: any CovariantAssocTypeErasure.Type = exist.method10() let _: Array<Class2Base> = exist.method11() let _: Dictionary<String, Class2Base> = exist.method12() } do { let exist: any CovariantAssocTypeErasureDerived let _: any CovariantAssocTypeErasureDerived = exist.method1() let _: Class2Base = exist.method2() let _: any CovariantAssocTypeErasureDerived = exist.method3() let _: any Class2Base & CovariantAssocTypeErasureDerived = exist.method4() let _: any Class2Base & CovariantAssocTypeErasureDerived = exist.method5() let _: any Class2Base & CovariantAssocTypeErasureDerived = exist.method6() let _: any Class2Base & CovariantAssocTypeErasure & Sequence = exist.method7() let _: (any CovariantAssocTypeErasureDerived)? = exist.method8() let _: (Class2Base, Bool) = exist.method9() let _: any CovariantAssocTypeErasureDerived.Type = exist.method10() let _: Array<any Class2Base & CovariantAssocTypeErasureDerived> = exist.method11() let _: Dictionary<String, any Class2Base & CovariantAssocTypeErasureDerived> = exist.method12() }
apache-2.0
d35500977fa0518b28dfb20c4f23c3ad
63.632415
222
0.706718
3.926696
false
false
false
false
TsinHzl/GoodCodes
exampleForAnimation-master/exampleForAnimation/WaterWare/YWWaterWaveView.swift
1
3889
// // YWSingleWaterWaveView.swift // exampleForAnimation // // Created by 姚巍 on 16/12/18. // Copyright © 2016年 姚巍. All rights reserved. // import UIKit class YWWaterWaveView: UIView { lazy var waveDisplaylink = CADisplayLink() lazy var firstWaveLayer = CAShapeLayer() lazy var secondWaveLayer = CAShapeLayer() var firstWaveColor: UIColor? /// 水纹振幅 var waveA: CGFloat = 10 /// 水纹周期 var waveW: CGFloat = 1/30.0; /// 位移 var offsetX: CGFloat = 0 /// 当前波浪高度Y var currentK: CGFloat = 0 /// 水纹速度 var waveSpeed: CGFloat = 0 /// 水纹路宽度 var waterWaveWidth: CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear layer.masksToBounds = true setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { // 波浪宽 waterWaveWidth = bounds.size.width // 波浪颜色 firstWaveColor = UIColor.green // 波浪速度 waveSpeed = 0.4 / CGFloat(M_PI) // 设置闭环的颜色 firstWaveLayer.fillColor = UIColor.init(colorLiteralRed: 73/255.0, green: 142/255.0, blue: 178/255.0, alpha: 0.5).cgColor // 设置边缘线的颜色 // firstWaveLayer.strokeColor = UIColor.blue.cgColor firstWaveLayer.strokeStart = 0.0 firstWaveLayer.strokeEnd = 0.8 // 设置闭环的颜色 secondWaveLayer.fillColor = UIColor.init(colorLiteralRed: 73/255.0, green: 142/255.0, blue: 178/255.0, alpha: 0.5).cgColor // 设置边缘线的颜色 // secondWaveLayer.strokeColor = UIColor.blue.cgColor secondWaveLayer.strokeStart = 0.0 secondWaveLayer.strokeEnd = 0.8 layer.addSublayer(firstWaveLayer) layer.addSublayer(secondWaveLayer) // 设置波浪流动速度 waveSpeed = 0.05 // 设置振幅 waveA = 8 // 设置周期 waveW = 2 * CGFloat(M_PI) / bounds.size.width // 设置波浪纵向位置 currentK = bounds.size.height / 2 //屏幕居中 waveDisplaylink = CADisplayLink(target: self, selector: #selector(getCurrentWave)) waveDisplaylink.add(to: RunLoop.current, forMode: .commonModes) } @objc private func getCurrentWave(disPlayLink: CADisplayLink) { // 实时位移 offsetX += waveSpeed setCurrentFirstWaveLayerPath() } private func setCurrentFirstWaveLayerPath() { // 创建一个路径 let path = CGMutablePath() var y = currentK path.move(to: CGPoint(x: 0, y: y)) for i in 0...Int(waterWaveWidth) { y = waveA * sin(waveW * CGFloat(i) + offsetX) + currentK path.addLine(to: CGPoint(x: CGFloat(i), y: y)) } path.addLine(to: CGPoint(x: waterWaveWidth, y: bounds.size.height)) path.addLine(to: CGPoint(x: 0, y: bounds.size.height)) path.closeSubpath() firstWaveLayer.path = path // 创建一个路径 let path2 = CGMutablePath() var y2 = currentK path2.move(to: CGPoint(x: 0, y: y)) for i in 0...Int(waterWaveWidth) { y2 = waveA * sin(waveW * CGFloat(i) + offsetX - waterWaveWidth/2 ) + currentK path2.addLine(to: CGPoint(x: CGFloat(i), y: y2)) } path2.addLine(to: CGPoint(x: waterWaveWidth, y: bounds.size.height)) path2.addLine(to: CGPoint(x: 0, y: bounds.size.height)) path2.closeSubpath() secondWaveLayer.path = path2 } deinit { waveDisplaylink.invalidate() } }
mit
bb3d6f96ec8e4b29153679f7684ba6b5
27.80315
130
0.581465
3.740286
false
false
false
false
IamAlchemist/DemoDynamicCollectionView
DemoDynamicCollectionView/NewtownianCell.swift
1
631
// // NewtownianCell.swift // DemoDynamicCollectionView // // Created by Wizard Li on 1/6/16. // Copyright © 2016 morgenworks. All rights reserved. // import UIKit class NewtownianCell : UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! override func prepareForReuse() { super.prepareForReuse() imageView.image = nil } func configWithImageName(imageName : String){ imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true backgroundColor = UIColor.orangeColor() imageView.image = UIImage(named: imageName) } }
mit
57d388b5ecdd28ca52fe831fe0d56e91
23.230769
54
0.673016
4.666667
false
false
false
false
ja-mes/experiments
iOS/Whats the Weather/Whats the Weather/AppDelegate.swift
1
6117
// // AppDelegate.swift // Whats the Weather // // Created by James Brown on 8/6/16. // Copyright © 2016 James Brown. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // 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.example.Whats_the_Weather" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() 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("Whats_the_Weather", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns 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 let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // 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 as NSError let wrappedError = 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 \(wrappedError), \(wrappedError.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 var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // 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. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
c1898ad9ced25fb151bec8a50c097ab9
54.099099
291
0.719588
5.886429
false
false
false
false
CharlesVu/Smart-iPad
MKHome/Settings/TrainJourneySettingsViewController.swift
1
2457
// // TrainJourneySettingsViewController.swift // MKHome // // Created by charles on 06/01/2017. // Copyright © 2017 charles. All rights reserved. // import Foundation import UIKit class TrainJourneySettingsViewController: UIViewController { @IBOutlet var trainJourneyTableView: UITableView? fileprivate let userSettings = UserSettings.sharedInstance fileprivate let appSettings = NationalRail.AppData.sharedInstance override func viewWillAppear(_ animated: Bool) { trainJourneyTableView?.reloadData() } } extension TrainJourneySettingsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userSettings.rail.getJourneys().count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let journey = userSettings.rail.getJourneys()[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "journeyCell")! if let source = appSettings.stationMap[journey.originCRS], let destination = appSettings.stationMap[journey.destinationCRS] { let attributedSource = NSMutableAttributedString(string: source.stationName, attributes: [NSAttributedString.Key.foregroundColor: UIColor(named: "normalText")!]) let attributedDestination = NSAttributedString(string: destination.stationName, attributes: [NSAttributedString.Key.foregroundColor: UIColor(named: "normalText")!]) attributedSource.append(NSAttributedString(string: " → ", attributes: [NSAttributedString.Key.foregroundColor: UIColor(named: "alternativeText")!])) attributedSource.append(attributedDestination) cell.textLabel?.attributedText = attributedSource } return cell } } extension TrainJourneySettingsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } @objc(tableView:commitEditingStyle:forRowAtIndexPath:) func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCell.EditingStyle.delete) { let journey = userSettings.rail.getJourneys()[indexPath.row] userSettings.rail.removeJourney(journey) tableView.reloadData() } } }
mit
fcad99b5beb6751dde5b56c03b13754b
41.310345
176
0.734719
5.32321
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Classtable/Model/ArrangeModel.swift
1
983
// // ArrangeModel.swift // WePeiYang // // Created by Qin Yubo on 16/5/8. // Copyright © 2016年 Qin Yubo. All rights reserved. // import UIKit import ObjectMapper class ArrangeModel: NSObject, Mappable { var week = "" var day = 0 var start = 0 var end = 0 var room = "" required init?(_ map: Map) { } func mapping(map: Map) { let transform = TransformOf<Int, String>(fromJSON: { (value: String?) -> Int? in // transform value from String? to Int? return Int(value!) }, toJSON: { (value: Int?) -> String? in // transform value from Int? to String? if let value = value { return String(value) } return nil }) week <- map["week"] day <- (map["day"], transform) start <- (map["start"], transform) end <- (map["end"], transform) room <- map["room"] } }
mit
3010045176a57d081a56ee098f1ebeae
21.790698
88
0.50102
4.117647
false
false
false
false
hooman/swift
test/DebugInfo/inlined-generics-basic.swift
3
6081
// SIL. // RUN: %target-swift-frontend -parse-as-library -module-name A \ // RUN: -Xllvm -sil-print-debuginfo %s -g -O -o - -emit-sil \ // RUN: | %FileCheck %s --check-prefix=SIL // IR. // RUN: %target-swift-frontend -parse-as-library -module-name A \ // RUN: %s -g -O -o - -emit-ir \ // RUN: | %FileCheck %s --check-prefix=IR import StdlibUnittest @inline(never) func yes() -> Bool { return true } #sourceLocation(file: "use.swift", line: 1) @inline(never) func use<V>(_ v: V) { _blackHole(v) } #sourceLocation(file: "h.swift", line: 1) @inline(__always) func h<U>(_ u: U) { yes() use(u) } #sourceLocation(file: "g.swift", line: 1) @inline(__always) func g<T>(_ t: T) { if (yes()) { h(t) } } // SIL: sil_scope [[F:.*]] { {{.*}}parent @$s1A1CC1fyyqd__lF // SIL: sil_scope [[F1G:.*]] { loc "f.swift":2:5 parent [[F]] } // SIL: sil_scope [[F1G1:.*]] { loc "g.swift":2:3 {{.*}}inlined_at [[F1G]] } // SIL: sil_scope [[F1G3:.*]] { loc "g.swift":3:5 {{.*}}inlined_at [[F1G]] } // SIL: sil_scope [[F1G3H:.*]] { loc "h.swift":1:24 // SIL-SAME: parent @{{.*}}1h{{.*}} inlined_at [[F1G3]] } #sourceLocation(file: "C.swift", line: 1) public class C<R> { let r : R init(_ _r: R) { r = _r } // SIL-LABEL: // C.f<A>(_:) // IR-LABEL: define {{.*}} @"$s1A1CC1fyyqd__lF" #sourceLocation(file: "f.swift", line: 1) public func f<S>(_ s: S) { // SIL: debug_value_addr %0 : $*S, let, name "s", argno 1,{{.*}} scope [[F]] // SIL: function_ref {{.*}}yes{{.*}} scope [[F1G1]] // SIL: function_ref {{.*}}use{{.*}} scope [[F1G3H]] // IR: dbg.value(metadata %swift.type* %S, metadata ![[MD_1_0:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[S:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[GS_T:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[GS_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 2) g(s) // Jump-threading removes the basic block containing debug_value // "t" before the second call to `g(r)`. When this happens, the // ref_element_addr in that removed block is left with a single // debug_value use, so they are both deleted. This means we have // no debug value for "t" in the call to `g(r)`. // dbg.value({{.*}}, metadata ![[GR_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GR_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 3) g(r) // IR: dbg.value({{.*}}, metadata ![[GRS_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GRS_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 4) g((r, s)) // Note to maintainers: the relative order of the constant dbg.values here // seem to flip back and forth. // IR: dbg.value({{.*}}, metadata ![[GI_U:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GI_T:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 5) g(Int(0)) // IR: dbg.value({{.*}}, metadata ![[GB_U:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GB_T:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 6) g(false) } } // SIL-LABEL: } // end sil function '$s1A1CC1fyyqd__lF' // IR-LABEL: ret void // IR: ![[BOOL:[0-9]+]] = !DICompositeType({{.*}}name: "Bool" // IR: ![[LET_BOOL:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[BOOL]]) // IR: ![[INT:[0-9]+]] = !DICompositeType({{.*}}name: "Int" // IR: ![[LET_INT:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[INT]]) // IR: ![[TAU_0_0:[0-9]+]] = {{.*}}DW_TAG_structure_type, name: "$sxD", // IR: ![[LET_TAU_0_0:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[TAU_0_0]]) // IR: ![[TAU_1_0:[0-9]+]] = {{.*}}DW_TAG_structure_type, name: "$sqd__D", // IR: ![[MD_1_0]] = !DILocalVariable(name: "$\CF\84_1_0" // IR: ![[S]] = !DILocalVariable(name: "s", {{.*}} type: ![[LET_TAU_1_0:[0-9]+]] // IR: ![[LET_TAU_1_0]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[TAU_1_0]]) // IR: ![[GS_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GS_T:[0-9]+]], {{.*}} type: ![[LET_TAU_1_0]]) // IR: ![[SP_GS_T]] = {{.*}}linkageName: "$s1A1gyyxlFqd___Ti5" // IR: ![[GS_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GS_U:[0-9]+]], {{.*}} type: ![[LET_TAU_1_0]]) // IR: ![[SP_GS_U]] = {{.*}}linkageName: "$s1A1hyyxlFqd___Ti5" // Debug info for this variable is removed. See the note above the call to g(r). // ![[GR_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GR_T:[0-9]+]], {{.*}}type: ![[LET_TAU_0_0]]) // S has the same generic parameter numbering s T and U. // ![[SP_GR_T]] = {{.*}}linkageName: "$s1A1gyyxlF" // IR: ![[GR_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GR_U:[0-9]+]], {{.*}}type: ![[LET_TAU_0_0]]) // IR: ![[SP_GR_U]] = {{.*}}linkageName: "$s1A1hyyxlF" // IR: ![[GRS_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GRS_T:[0-9]+]], {{.*}}type: ![[LET_TUPLE:[0-9]+]] // IR: ![[SP_GRS_T]] = {{.*}}linkageName: "$s1A1gyyxlFx_qd__t_Ti5" // IR: ![[LET_TUPLE]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[TUPLE:[0-9]+]]) // IR: ![[TUPLE]] = {{.*}}DW_TAG_structure_type, name: "$sx_qd__tD" // IR: ![[GRS_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GRS_U:[0-9]+]], {{.*}}type: ![[LET_TUPLE]] // IR: ![[SP_GRS_U]] = {{.*}}linkageName: "$s1A1hyyxlFx_qd__t_Ti5" // IR-DAG: ![[GI_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GI_G:[0-9]+]], {{.*}}type: ![[LET_INT]]) // IR-DAG: ![[SP_GI_G]] = {{.*}}linkageName: "$s1A1gyyxlFSi_Tg5" // IR-DAG: ![[GI_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GI_U:[0-9]+]], {{.*}}type: ![[LET_INT]]) // IR-DAG: ![[SP_GI_U]] = {{.*}}linkageName: "$s1A1hyyxlFSi_TG5" // IR-DAG: ![[GB_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GB_G:[0-9]+]], {{.*}}type: ![[LET_BOOL]]) // IR-DAG: ![[SP_GB_G]] = {{.*}}linkageName: "$s1A1gyyxlFSb_Tg5" // IR-DAG: ![[GB_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GB_U:[0-9]+]], {{.*}}type: ![[LET_BOOL]]) // IR-DAG: ![[SP_GB_U]] = {{.*}}linkageName: "$s1A1hyyxlFSb_TG5"
apache-2.0
0e206085bcd4c9164cc7baa01337b625
47.648
117
0.527051
2.672967
false
false
false
false
hironytic/FormulaCalc
FormulaCalc/View/Item/ItemViewController.swift
1
3614
// // ItemViewController.swift // FormulaCalc // // Copyright (c) 2016, 2017 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import RxSwift import RxCocoa public class ItemViewController: UITableViewController { private var _disposeBag: DisposeBag? public var viewModel: IItemViewModel? @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var formulaLabel: UILabel! @IBOutlet weak var visibleSwitch: UISwitch! @IBOutlet weak var formatLabel: UILabel! public override func viewWillAppear(_ animated: Bool) { bindViewModel() } public override func viewDidDisappear(_ animated: Bool) { _disposeBag = nil } private func bindViewModel() { _disposeBag = nil guard let viewModel = viewModel else { return } let disposeBag = DisposeBag() viewModel.message .bind(to: transitioner) .disposed(by: disposeBag) viewModel.name .bind(to: nameLabel.rx.text.avoidsEmpty) .disposed(by: disposeBag) viewModel.type .bind(to: typeLabel.rx.text.avoidsEmpty) .disposed(by: disposeBag) viewModel.formula .bind(to: formulaLabel.rx.text.avoidsEmpty) .disposed(by: disposeBag) viewModel.visible .bind(to: visibleSwitch.rx.isOn) .disposed(by: disposeBag) viewModel.format .bind(to: formatLabel.rx.text.avoidsEmpty) .disposed(by: disposeBag) itemSelectedAt(section: 0, row: 0) .bind(to: viewModel.onSelectName) .disposed(by: disposeBag) itemSelectedAt(section: 0, row: 1) .bind(to: viewModel.onSelectType) .disposed(by: disposeBag) itemSelectedAt(section: 1, row: 0) .bind(to: viewModel.onSelectFormula) .disposed(by: disposeBag) visibleSwitch.rx.isOn .bind(to: viewModel.onChangeVisible) .disposed(by: disposeBag) itemSelectedAt(section: 2, row: 1) .bind(to: viewModel.onSelectFormat) .disposed(by: disposeBag) _disposeBag = disposeBag } private func itemSelectedAt(section: Int, row: Int) -> Observable<Void> { return tableView.rx.itemSelected .filter { $0.section == section && $0.row == row } .map { _ -> Void in } } }
mit
11b23dad5156840c8fe3d4ca6a4d7be4
33.09434
80
0.644438
4.627401
false
false
false
false
lorentey/swift
stdlib/private/OSLog/OSLogNSObjectType.swift
3
4577
//===----------------- OSLogNSObjectType.swift ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// // This file defines extensions for interpolating NSObject into a OSLogMesage. // It defines `appendInterpolation` function for NSObject type. It also defines // extensions for generating an os_log format string for NSObjects (using the // format specifier %@) and for serializing NSObject into the argument buffer // passed to os_log ABIs. // // The `appendInterpolation` function defined in this file accept formatting // and privacy options along with the interpolated expression as shown below: // // "\(x, privacy: .public\)" import ObjectiveC extension OSLogInterpolation { /// Define interpolation for expressions of type NSObject. /// - Parameters: /// - argumentObject: the interpolated expression of type NSObject, which is autoclosured. /// - privacy: a privacy qualifier which is either private or public. Default is private. /// TODO: create a specifier to denote auto-inferred privacy level and make it default. @_semantics("constant_evaluable") @inlinable @_optimize(none) public mutating func appendInterpolation( _ argumentObject: @autoclosure @escaping () -> NSObject, privacy: Privacy = .private ) { guard argumentCount < maxOSLogArgumentCount else { return } let isPrivateArgument = isPrivate(privacy) formatString += getNSObjectFormatSpecifier(isPrivateArgument) addNSObjectHeaders(isPrivateArgument) arguments.append(argumentObject) argumentCount += 1 } /// Update preamble and append argument headers based on the parameters of /// the interpolation. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func addNSObjectHeaders(_ isPrivate: Bool) { // Append argument header. let header = getArgumentHeader(isPrivate: isPrivate, type: .object) arguments.append(header) // Append number of bytes needed to serialize the argument. let byteCount = pointerSizeInBytes() arguments.append(UInt8(byteCount)) // Increment total byte size by the number of bytes needed for this // argument, which is the sum of the byte size of the argument and // two bytes needed for the headers. totalBytesForSerializingArguments += byteCount + 2 preamble = getUpdatedPreamble(isPrivate: isPrivate, isScalar: false) } /// Construct an os_log format specifier from the given parameters. /// This function must be constant evaluable and all its arguments /// must be known at compile time. @inlinable @_semantics("constant_evaluable") @_effects(readonly) @_optimize(none) internal func getNSObjectFormatSpecifier(_ isPrivate: Bool) -> String { // TODO: create a specifier to denote auto-inferred privacy. return isPrivate ? "%{private}@" : "%{public}@" } } extension OSLogArguments { /// Append an (autoclosured) interpolated expression of type NSObject, passed to /// `OSLogMessage.appendInterpolation`, to the array of closures tracked /// by this instance. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func append(_ value: @escaping () -> NSObject) { argumentClosures.append({ (position, _) in serialize(value(), at: &position) }) } } /// Serialize an NSObject pointer at the buffer location pointed by /// `bufferPosition`. @inlinable @_alwaysEmitIntoClient @inline(__always) internal func serialize( _ object: NSObject, at bufferPosition: inout ByteBufferPointer ) { let byteCount = pointerSizeInBytes(); let dest = UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount) // Get the address of this NSObject as an UnsafeRawPointer. let objectAddress = Unmanaged.passUnretained(object).toOpaque() // Copy the address into the destination buffer. Note that the input NSObject // is an interpolated expression and is guaranteed to be alive until the // os_log ABI call is completed by the implementation. Therefore, passing // this address to the os_log ABI is safe. withUnsafeBytes(of: objectAddress) { dest.copyMemory(from: $0) } bufferPosition += byteCount }
apache-2.0
8802ae3f4a9ad2c6e546d837e04d434d
37.788136
93
0.714005
4.777662
false
false
false
false
Lasithih/LIHQRScanner
Pod/Classes/LIHQRScanner.swift
1
3760
// // LIHQRSCanner.swift // Perx // // Created by Lasith Hettiarachchi on 1/11/16. // Copyright © 2016 Lasith Hettiarachchi. All rights reserved. // import Foundation import AVFoundation import UIKit @objc public protocol LIHQRScannerDelegate { optional func qrDetected(qrString: String?, error: NSError?) } public class LIHQRScanner: NSObject, AVCaptureMetadataOutputObjectsDelegate { private var captureSession:AVCaptureSession? private var videoPreviewLayer:AVCaptureVideoPreviewLayer? public var delegate: LIHQRScannerDelegate? public func initialize(videoContainer avLayer: UIView) { let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) var error:NSError? let input: AnyObject! do { input = try AVCaptureDeviceInput(device: captureDevice) } catch let error1 as NSError { error = error1 input = nil } if (error != nil) { NSLog("\(error?.localizedDescription)") return } captureSession = AVCaptureSession() captureSession?.addInput(input as! AVCaptureInput) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = avLayer.layer.bounds if let preLayer = videoPreviewLayer { avLayer.layer.addSublayer(preLayer) } } public func startSession(completion: (()->())?) { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { self.captureSession?.startRunning() dispatch_async(dispatch_get_main_queue()) { completion?() } } } public func stopSession() { self.captureSession?.stopRunning() } //MARK: - MetadataObjectsDelegate public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { // Check if the metadataObjects array is not nil and it contains at least one object. if metadataObjects == nil || metadataObjects.count == 0 { self.delegate?.qrDetected?(nil, error: nil) return } // Get the metadata object. if let metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject { if metadataObj.type == AVMetadataObjectTypeQRCode { // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds if metadataObj.stringValue != nil { self.delegate?.qrDetected?(metadataObj.stringValue, error: nil) } else { self.delegate?.qrDetected?(nil, error: nil) } } else { self.delegate?.qrDetected?(nil, error: nil) } } else { self.delegate?.qrDetected?(nil, error: nil) } } }
mit
f230ec18f551a8d90dcf2bf29504e1a5
30.864407
169
0.591381
5.995215
false
false
false
false
colemancda/NetworkObjects
Source/RequestMessage.swift
1
7670
// // RequestMessage.swift // NetworkObjects // // Created by Alsey Coleman Miller on 9/3/15. // Copyright © 2015 ColemanCDA. All rights reserved. // import SwiftFoundation import CoreModel public struct RequestMessage: JSONEncodable, JSONParametrizedDecodable { public var request: Request public var metadata: [String: String] public init(_ request: Request, metadata: [String: String] = [:]) { self.request = request self.metadata = metadata } } // MARK: - JSON private extension RequestMessage { private enum JSONKey: String { case RequestType case Metadata case Entity case ResourceID case Values case FetchRequest case FunctionName case FunctionParameters } } public extension RequestMessage { /// Initializes a request message from JSON. /// /// The specified model will be used for value conversion. /// Created request message is assumed to be valid according to the ```model``` provided. public init?(JSONValue: JSON.Value, parameters: Model) { let model = parameters guard let jsonObject = JSONValue.objectValue, let entityName = jsonObject[JSONKey.Entity.rawValue]?.rawValue as? String, let requestTypeString = jsonObject[JSONKey.RequestType.rawValue]?.rawValue as? String, let requestType = RequestType(rawValue: requestTypeString), let metadata = jsonObject[JSONKey.Metadata.rawValue]?.rawValue as? [String: String], let entity = model[entityName] else { return nil } self.metadata = metadata switch requestType { case .Get: guard let resourceID = jsonObject[JSONKey.ResourceID.rawValue]?.rawValue as? String else { return nil } let resource = Resource(entityName, resourceID) self.request = Request.Get(resource) case .Edit: guard let resourceID = jsonObject[JSONKey.ResourceID.rawValue]?.rawValue as? String else { return nil } let resource = Resource(entityName, resourceID) guard let valuesJSON = jsonObject[JSONKey.Values.rawValue]?.objectValue, let values = entity.convert(valuesJSON) else { return nil } self.request = Request.Edit(resource, values) case .Delete: guard let resourceID = jsonObject[JSONKey.ResourceID.rawValue]?.rawValue as? String else { return nil } let resource = Resource(entityName, resourceID) self.request = Request.Delete(resource) case .Create: let values: ValuesObject? if let valuesJSON = jsonObject[JSONKey.Values.rawValue] { guard let valuesJSONObject = valuesJSON.objectValue, let convertedValues = entity.convert(valuesJSONObject) else { return nil } values = convertedValues } else { values = nil } self.request = Request.Create(entityName, values) case .Search: guard let fetchRequestJSON = jsonObject[JSONKey.FetchRequest.rawValue], let fetchRequest = FetchRequest(JSONValue: fetchRequestJSON, parameters: (entityName, entity)) else { return nil } self.request = Request.Search(fetchRequest) case .Function: guard let resourceID = jsonObject[JSONKey.ResourceID.rawValue]?.rawValue as? String else { return nil } let resource = Resource(entityName, resourceID) guard let functionName = jsonObject[JSONKey.FunctionName.rawValue]?.rawValue as? String else { return nil } let functionParameters: JSONObject? if let functionParametersJSON = jsonObject[JSONKey.FunctionParameters.rawValue] { guard let functionParametersJSONObject = functionParametersJSON.objectValue else { return nil } functionParameters = functionParametersJSONObject } else { functionParameters = nil } self.request = Request.Function(resource, functionName, functionParameters) } } public func toJSON() -> JSON.Value { var jsonObject = JSONObject() let metaDataJSONObject: JSONObject = { var jsonObject = JSONObject() for (key, value) in self.metadata { jsonObject[key] = JSON.Value.String(value) } return jsonObject }() jsonObject[JSONKey.Metadata.rawValue] = JSON.Value.Object(metaDataJSONObject) jsonObject[JSONKey.RequestType.rawValue] = JSON.Value.String(self.request.type.rawValue) switch self.request { case let .Get(resource): jsonObject[JSONKey.Entity.rawValue] = JSON.Value.String(resource.entityName) jsonObject[JSONKey.ResourceID.rawValue] = JSON.Value.String(resource.resourceID) case let .Edit(resource, values): jsonObject[JSONKey.Entity.rawValue] = JSON.Value.String(resource.entityName) jsonObject[JSONKey.ResourceID.rawValue] = JSON.Value.String(resource.resourceID) let valuesJSON = JSON.fromValues(values) jsonObject[JSONKey.Values.rawValue] = JSON.Value.Object(valuesJSON) case let .Delete(resource): jsonObject[JSONKey.Entity.rawValue] = JSON.Value.String(resource.entityName) jsonObject[JSONKey.ResourceID.rawValue] = JSON.Value.String(resource.resourceID) case let .Create(entityName, values): jsonObject[JSONKey.Entity.rawValue] = JSON.Value.String(entityName) if let values = values { let valuesJSON = JSON.fromValues(values) jsonObject[JSONKey.Values.rawValue] = JSON.Value.Object(valuesJSON) } case let .Search(fetchRequest): let fetchRequestJSON = fetchRequest.toJSON() jsonObject[JSONKey.Entity.rawValue] = JSON.Value.String(fetchRequest.entityName) jsonObject[JSONKey.FetchRequest.rawValue] = fetchRequestJSON case let .Function(resource, functionName, functionParametersJSON): jsonObject[JSONKey.Entity.rawValue] = JSON.Value.String(resource.entityName) jsonObject[JSONKey.ResourceID.rawValue] = JSON.Value.String(resource.resourceID) jsonObject[JSONKey.FunctionName.rawValue] = JSON.Value.String(functionName) if let functionParametersJSON = functionParametersJSON { jsonObject[JSONKey.FunctionParameters.rawValue] = JSON.Value.Object(functionParametersJSON) } } return JSON.Value.Object(jsonObject) } }
mit
d4462e32bb7c8db7db8cfc3757625d94
34.345622
111
0.568783
5.787925
false
false
false
false
Urinx/SomeCodes
iOS/CloudIMTest/CloudIMTest/ChatListViewController.swift
1
4352
// // ViewController.swift // CloudIMTest // // Created by Eular on 10/7/15. // Copyright © 2015 Eular. All rights reserved. // import UIKit class ChatListViewController: RCConversationListViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if !NSUserDefaults.standardUserDefaults().boolForKey("isLogined") { NSNotificationCenter.defaultCenter().addObserver(self, selector:"hasLogined:", name: hasLoginedNotification, object: nil) self.presentViewController(LoginViewController(), animated: false, completion: nil) } else { self.connectServer() } } func hasLogined(notification: NSNotification) { self.connectServer() } func connectServer() { let weixinUser = NSUserDefaults.standardUserDefaults().objectForKey("weixinUser") var userId = weixinUser?.objectForKey("openid") as! String let name = weixinUser?.objectForKey("nickname") as! String let portrait = weixinUser?.objectForKey("headimgurl") as! String var token = "" if userId == WeixinId { token = WeiToken } else { token = TestToken userId = TestId } RCIM.sharedRCIM().initWithAppKey(RCIMAppKey) RCIM.sharedRCIM().connectWithToken(token, success: { (_) -> Void in print("连接成功") let currentUser = RCUserInfo(userId: userId, name: name, portrait: portrait) RCIMClient.sharedRCIMClient().currentUserInfo = currentUser dispatch_async(dispatch_get_main_queue(), { () -> Void in self.setDisplayConversationTypes([ RCConversationType.ConversationType_APPSERVICE.rawValue, RCConversationType.ConversationType_CHATROOM.rawValue, RCConversationType.ConversationType_CUSTOMERSERVICE.rawValue, RCConversationType.ConversationType_DISCUSSION.rawValue, RCConversationType.ConversationType_GROUP.rawValue, RCConversationType.ConversationType_PRIVATE.rawValue, RCConversationType.ConversationType_PUBLICSERVICE.rawValue, RCConversationType.ConversationType_SYSTEM.rawValue ]) self.refreshConversationTableViewIfNeeded() }) }, error: { (code: RCConnectErrorCode) -> Void in print("连接失败: \(code)") }) { () -> Void in print("Token错误,或失效") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.refreshConversationTableViewIfNeeded() self.tabBarController?.tabBar.hidden = false } override func onSelectedTableRow(conversationModelType: RCConversationModelType, conversationModel model: RCConversationModel!, atIndexPath indexPath: NSIndexPath!) { let chatVC = RCConversationViewController() chatVC.targetId = model.targetId chatVC.userName = model.conversationTitle chatVC.conversationType = .ConversationType_PRIVATE chatVC.title = model.conversationTitle self.navigationController?.pushViewController(chatVC, animated: true) self.tabBarController?.tabBar.hidden = true } @IBAction func popOver(sender: UIBarButtonItem) { guard var frame = sender.valueForKey("view")?.frame else { return } frame.origin.y += 30 KxMenu.showMenuInView(self.view, fromRect: frame, menuItems: [ KxMenuItem("发起群聊", image: UIImage(named: "contacts_add_newmessage"), target: self, action: nil), KxMenuItem("添加朋友", image: UIImage(named: "contacts_add_friend"), target: self, action: nil), KxMenuItem("扫一扫", image: UIImage(named: "contacts_add_scan"), target: self, action: nil), KxMenuItem("收钱", image: UIImage(named: "contacts_add_money"), target: self, action: nil) ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
7faea7653665904ee8583086757064c3
40.718447
170
0.634396
4.984919
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Compiler/Compiler.swift
1
56660
// // Code.swift // LispKit // // Created by Matthias Zenger on 03/02/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import NumberKit /// /// Class `Compiler` provides a framework for compiling LispKit expressions. Static method /// `compile` invokes the compiler in a given environment and returns a `Code` object /// which encapsulates the generated code. /// public final class Compiler { /// Context in which this compiler is running public unowned let context: Context /// Set to the current syntax name internal var syntaxSym: Symbol? = nil /// Environment in which expressions should be compiled internal private(set) var env: Env /// Meta-environment in which macro expressions are evaluated internal let rulesEnv: Env /// Checkpointer for attaching information to help optimize the code in the second /// compilation phase. internal let checkpointer: Checkpointer /// Capture list private var captures: CaptureGroup! /// Current number of local values/variables internal var numLocals: Int = 0 /// Maximum number of local values/variables private var maxLocals: Int = 0 /// List of arguments private var arguments: BindingGroup? /// Constant pool private var constants: Exprs = [] /// List of code fragments private var fragments: Fragments = [] /// Instruction sequence private var instructions: Instructions = [] /// Directory of the current source file internal private(set) var sourceDirectory: String /// Parent compiler (needed since `Compiler` objects are nested, e.g. if nested /// functions get compiled) public var parent: Compiler? { return self.captures.parent?.owner } /// Initializes a compiler object from the given context, environments, and checkpointer. private init(in env: Env, and rulesEnv: Env, usingCheckpointer cp: Checkpointer) { self.context = env.environment!.context self.env = env self.rulesEnv = rulesEnv self.checkpointer = cp self.arguments = nil self.sourceDirectory = env.environment!.context.fileHandler.currentDirectoryPath self.captures = CaptureGroup(owner: self, parent: env.bindingGroup?.owner.captures) } /// Compiles the given expression `expr` in the environment `env` and the rules environment /// `rulesEnv`. If `optimize` is set to true, the compiler will be invoked twice. The /// information collected in the first phase will be used to optimize the code in the second /// phase. public static func compile(expr: Expr, in env: Env, and rulesEnv: Env? = nil, optimize: Bool = false, inDirectory: String? = nil) throws -> Code { let checkpointer = Checkpointer() var compiler = Compiler(in: env, and: rulesEnv ?? env, usingCheckpointer: checkpointer) if let dir = inDirectory { compiler.sourceDirectory = dir } try compiler.compileBody(expr) if optimize { // log(checkpointer.description) checkpointer.reset() compiler = Compiler(in: env, and: rulesEnv ?? env, usingCheckpointer: checkpointer) if let dir = inDirectory { compiler.sourceDirectory = dir } try compiler.compileBody(expr) // log(checkpointer.description) } return compiler.bundle() } /// Expands the given expression `expr` in the environment `env` and the rules environment /// `rulesEnv` at the outermost expression. If the outermost expression does not refer to a /// macro, the function returns `nil` public static func macroExpand(expr: Expr, in env: Env, and rulesEnv: Env? = nil, inDirectory: String? = nil) throws -> Expr? { let compiler = Compiler(in: env, and: rulesEnv ?? env, usingCheckpointer: Checkpointer()) if let dir = inDirectory { compiler.sourceDirectory = dir } return try compiler.macroExpand(expr, in: env) } /// Compiles the given list of arguments and returns the corresponding binding group as well /// as the remaining argument list private func collectArguments(_ arglist: Expr) -> (BindingGroup, Expr) { let arguments = BindingGroup(owner: self, parent: self.env) var next = arglist loop: while case .pair(let arg, let cdr) = next { switch arg { case .symbol(let sym): arguments.allocBindingFor(sym) default: break loop } next = cdr } return (arguments, next) } /// Compiles the given body of a function `expr` (or expression, if this compiler is not /// used to compile a function). /// When an `optionals` formal list of parameters is provided, the formals are matched /// against a list on the stack. The matching happens in the context of `optenv`. If /// `optenv` is not provided, the matching happens in the context of the environment /// constructed on top of `self.env`. /// When `localDefine` is set to true, local definitions are allowed. private func compileBody(_ expr: Expr, optionals: Expr? = nil, optenv: Env? = nil, localDefine: Bool = false) throws { if expr.isNull { self.emit(.pushVoid) self.emit(.return) } else { // Reserve instruction for reserving local variables let reserveLocalIp = self.emitPlaceholder() // Turn arguments into local variables if let arguments = self.arguments { for sym in arguments.symbols { if let sym = sym, let binding = arguments.bindingFor(sym) , !binding.isValue { self.emit(.makeVariableArgument(binding.index)) } } } // Compile body if let optionals = optionals { let initialLocals = self.numLocals let group = try self.compileOptionalBindings(optionals, in: self.env, optenv: optenv) let res = try self.compileSeq(expr, in: Env(group), inTailPos: true, localDefine: localDefine) if !self.finalizeBindings(group, exit: res, initialLocals: initialLocals) { self.emit(.return) } } else { if !(try compileSeq(expr, in: self.env, inTailPos: true, localDefine: localDefine)) { self.emit(.return) } } // Insert instruction to reserve local variables if self.maxLocals > self.arguments?.count ?? 0 { let n = self.maxLocals - (self.arguments?.count ?? 0) if optionals != nil { self.patch(.allocBelow(n), at: reserveLocalIp) } else { self.patch(.alloc(n), at: reserveLocalIp) } } } // Checkpoint argument mutability self.arguments?.finalize() } /// Allocates a new local value/variable. public func nextLocalIndex() -> Int { self.numLocals += 1 if self.numLocals > self.maxLocals { self.maxLocals = self.numLocals } return self.numLocals - 1 } /// Removes the last instruction from the instruction sequence. @discardableResult public func removeLastInstr() -> Int { self.instructions.removeLast() return self.instructions.count - 1 } /// Appends the given instruction to the instruction sequence. @discardableResult public func emit(_ instr: Instruction) -> Int { self.instructions.append(instr) return self.instructions.count - 1 } /// Replaces the instruction at the position `at` with the instruction `instr`. public func patch(_ instr: Instruction, at: Int) { self.instructions[at] = instr } /// Appends a placeholder instruction to the instruction sequence. @discardableResult public func emitPlaceholder() -> Int { return self.emit(.noOp) } /// Injects the name of a closure in form of an index into the constant pool into the /// `.makeClosure` operation. public func patchMakeClosure(_ nameIdx: Int) { guard let instr = self.instructions.last else { return } switch instr { case .makeClosure(-1, let n, let index): self.instructions[self.instructions.count - 1] = .makeClosure(nameIdx, n, index) case .pushProcedure(let i): guard nameIdx >= 0 && nameIdx < self.constants.count, case .symbol(let sym) = self.constants[nameIdx] else { return } if i >= 0 && i < self.constants.count, case .procedure(let proc) = self.constants[i], let newproc = proc.renamed(to: sym.description) { self.constants[i] = .procedure(newproc) } default: return } } /// Injects the name of a closure into the `.makeClosure` operation. public func patchMakeClosure(_ sym: Symbol) { guard let instr = self.instructions.last else { return } switch instr { case .makeClosure(-1, let n, let index): let nameIdx = self.registerConstant(.symbol(sym)) self.instructions[self.instructions.count - 1] = .makeClosure(nameIdx, n, index) case .pushProcedure(let i): if i >= 0 && i < self.constants.count, case .procedure(let proc) = self.constants[i], let newproc = proc.renamed(to: sym.description) { self.constants[i] = .procedure(newproc) } default: return } } /// Calls a procedure on the stack with `n` arguments. Uses a tail call if `tail` is set /// to true. public func call(_ n: Int, inTailPos tail: Bool) -> Bool { if tail { self.emit(.tailCall(n)) return true } else { self.emit(.call(n)) return false } } /// Computes the offset between the next instruction and the given instruction pointer `ip`. public func offsetToNext(_ ip: Int) -> Int { return self.instructions.count - ip } /// Pushes the given expression onto the stack. public func pushConstant(_ expr: Expr) { self.emit(.pushConstant(self.registerConstant(expr))) } /// Pushes the given procedure onto the stack. public func pushProcedure(_ proc: Procedure) { self.emit(.pushProcedure(self.registerConstant(.procedure(proc)))) } /// Attaches the given expression to the constant pool and returns the index into the constant /// pool. `registerConstant` makes sure that expressions are not added twice. public func registerConstant(_ expr: Expr) -> Int { for i in self.constants.indices { if eqExpr(expr, self.constants[i]) { return i } } self.constants.append(expr.datum) return self.constants.count - 1 } /// Push the value of the given symbol in the given environment onto the stack. public func pushValueOf(_ sym: Symbol, in env: Env) throws { switch self.pushLocalValueOf(sym, in: env) { case .success: break // Nothing to do case .globalLookupRequired(let lexicalSym, let environment): let locRef = self.forceDefinedLocationRef(for: lexicalSym, in: environment) if case .immutableImport(let loc) = locRef { let value = self.context.heap.locations[loc] if value.isUndef { self.emit(.pushGlobal(locRef.location!)) } else { try self.pushValue(value) } } else { self.emit(.pushGlobal(locRef.location!)) } case .macroExpansionRequired(_): throw RuntimeError.eval(.illegalKeywordUsage, .symbol(sym)) } } /// Result type of `pushLocalValueOf` method. public enum LocalLookupResult { /// `Success` indicates that a local value/variable was successfully pushed onto the stack case success /// `MacroExpansionRequired(proc)` indicates that the binding refers to a macro and the /// compiler needs to expand the expression with the macro expander procedure `proc`. case macroExpansionRequired(Procedure) /// `GlobalLookupRequired(gsym, genv)` indicates that a suitable binding wasn't found in the /// local environment and thus a lookup in the global environment `genv` needs to be made. /// Note that `gsym` and `sym` do not necessarily need to be the same due to the way how /// hygienic macro expansion is implemented. case globalLookupRequired(Symbol, Environment) } /// Pushes the value/variable bound to symbol `sym` in the local environment `env`. If this /// wasn't possible, the method returns an instruction on how to proceed. private func pushLocalValueOf(_ sym: Symbol, in env: Env) -> LocalLookupResult { var env = env // Iterate through the local binding groups until `sym` is found while case .local(let group) = env { if let binding = group.bindingFor(sym) { if case .macro(let proc) = binding.kind { return .macroExpansionRequired(proc) } else if group.owner === self { if binding.isValue { self.emit(.pushLocal(binding.index)) } else { self.emit(.pushLocalValue(binding.index)) } } else { let capturedIndex = self.captures.capture(binding, from: group) if binding.isValue { self.emit(.pushCaptured(capturedIndex)) } else { self.emit(.pushCapturedValue(capturedIndex)) } } return .success } env = group.parent } // If `sym` wasn't found, look into the lexical environment if let (lexicalSym, lexicalEnv) = sym.lexical { // If the lexical environment is a global environment, return that a global lookup is needed if case .global(_) = lexicalEnv { return .globalLookupRequired(sym, env.environment!) } // Find the new lexical symbol in the new lexcial environment let res = self.pushLocalValueOf(lexicalSym, in: lexicalEnv) // If this didn't succeed, return that a global lookup is needed guard case .globalLookupRequired(_, _) = res else { return res } } // Return global scope return .globalLookupRequired(sym, env.environment!) } /// Checks if the symbol `sym` is bound in the local environment `env`. private func lookupLocalValueOf(_ sym: Symbol, in env: Env) -> LocalLookupResult { var env = env // Iterate through the local binding groups until `sym` is found while case .local(let group) = env { if let binding = group.bindingFor(sym) { if case .macro(let proc) = binding.kind { return .macroExpansionRequired(proc) } return .success } env = group.parent } // If `sym` wasn't found, look into the lexical environment if let (lexicalSym, lexicalEnv) = sym.lexical { // If the lexical environment is a global environment, return that a global lookup is needed if case .global(_) = lexicalEnv { return .globalLookupRequired(sym, env.environment!) } // Find the new lexical symbol in the new lexcial environment let res = self.lookupLocalValueOf(lexicalSym, in: lexicalEnv) // If this didn't succeed, return that a global lookup is needed guard case .globalLookupRequired(_, _) = res else { return res } } // Return global scope return .globalLookupRequired(sym, env.environment!) } /// Generates instructions to push the given expression onto the stack. public func pushValue(_ value: Expr) throws { let expr = value.datum switch expr { case .undef, .uninit(_): self.emit(.pushUndef) case .void: self.emit(.pushVoid) case .eof: self.emit(.pushEof) case .null: self.emit(.pushNull) case .true: self.emit(.pushTrue) case .false: self.emit(.pushFalse) case .fixnum(let num): self.emit(.pushFixnum(num)) case .bignum(let num): self.emit(.pushBignum(num)) case .rational(.fixnum(let n), .fixnum(let d)): self.emit(.pushRat(Rational(n, d))) case .rational(.bignum(let n), .bignum(let d)): self.emit(.pushBigrat(Rational(n, d))) case .rational(_, _): preconditionFailure("incorrectly encoded rational number") case .flonum(let num): self.emit(.pushFlonum(num)) case .complex(let num): self.emit(.pushComplex(num.value)) case .char(let char): self.emit(.pushChar(char)) case .symbol(_), .string(_), .bytes(_), .pair(_, _), .box(_), .mpair(_), .array(_), .vector(_), .record(_), .table(_), .promise(_), .procedure(_), .env(_), .port(_), .object(_), .tagged(_, _), .error(_): self.pushConstant(expr) case .special(_): throw RuntimeError.eval(.illegalKeywordUsage, expr) case .values(_): preconditionFailure("cannot push multiple values onto stack") case .syntax(_, _): preconditionFailure("cannot push syntax onto stack") } } /// Pushes the given list of expressions `expr` onto the stack. This method returns the /// number of expressions whose result has been stored on the stack. public func pushValues(_ expr: Expr) throws -> Int { var n = 0 var next = expr while case .pair(let car, let cdr) = next { try self.pushValue(car) n += 1 next = cdr } guard next.isNull else { throw RuntimeError.type(expr, expected: [.properListType]) } return n } /// Bind symbol `sym` to the value on top of the stack in environment `env`. public func setValueOf(_ sym: Symbol, in env: Env) { switch self.setLocalValueOf(sym, in: env) { case .success: break; // Nothing to do case .globalLookupRequired(let lexicalSym, let environment): let loc = self.forceDefinedLocationRef(for: lexicalSym, in: environment).location! self.emit(.setGlobal(loc)) case .macroExpansionRequired(_): preconditionFailure("setting bindings should never trigger macro expansion") } } /// Bind symbol `sym` to the value on top of the stack assuming `lenv` is a local /// environment (i.e. the bindings are located on the stack). If this /// wasn't possible, the method returns an instruction on how to proceed. private func setLocalValueOf(_ sym: Symbol, in lenv: Env) -> LocalLookupResult { var env = lenv // Iterate through the local binding groups until `sym` is found while case .local(let group) = env { if let binding = group.bindingFor(sym) { if group.owner === self { self.emit(.setLocalValue(binding.index)) } else { self.emit(.setCapturedValue(self.captures.capture(binding, from: group))) } binding.wasMutated() return .success } env = group.parent } // If `sym` wasn't found, look into the lexical environment if let (lexicalSym, lexicalEnv) = sym.lexical { // If the lexical environment is a global environment, return that a global lookup is needed if case .global(_) = lexicalEnv { return .globalLookupRequired(sym, env.environment!) } // Find the new lexical symbol in the new lexcial environment let res = self.setLocalValueOf(lexicalSym, in: lexicalEnv) // If this didn't succeed, return that a global lookup is needed guard case .globalLookupRequired(_, _) = res else { return res } } return .globalLookupRequired(sym, env.environment!) } private func locationRef(for sym: Symbol, in environment: Environment) -> Environment.LocationRef { var environment = environment var res = environment.locationRef(for: sym) var sym = sym while case .undefined = res, let (lexicalSym, lexicalEnv) = sym.lexical { sym = lexicalSym environment = lexicalEnv.environment! res = environment.locationRef(for: sym) } return res } private func forceDefinedLocationRef(for sym: Symbol, in environment: Environment) -> Environment.LocationRef { var environment = environment var res = environment.locationRef(for: sym) var sym = sym while case .undefined = res, let (lexicalSym, lexicalEnv) = sym.lexical { sym = lexicalSym environment = lexicalEnv.environment! res = environment.locationRef(for: sym) } if case .undefined = res { return environment.forceDefinedLocationRef(for: sym) } return res } private func value(of sym: Symbol, in environment: Environment) -> Expr? { var environment = environment var res = environment[sym] var sym = sym while res == nil, let (lexicalSym, lexicalEnv) = sym.lexical { sym = lexicalSym environment = lexicalEnv.environment! res = environment[sym] } return res } /// Expand expression `expr` in environment `env`. private func expand(_ expr: Expr, in env: Env) throws -> Expr? { switch expr { case .pair(.symbol(let sym), let cdr): let cp = self.checkpointer.checkpoint() switch self.lookupLocalValueOf(sym, in: env) { case .success: return nil case .globalLookupRequired(let lexicalSym, let environment): if let value = self.checkpointer.fromGlobalEnv(cp) ?? value(of: lexicalSym, in: environment) { self.checkpointer.associate(.fromGlobalEnv(value), with: cp) switch value { case .special(let special): switch special.kind { case .primitive(_): return nil case .macro(let transformer): let expanded = try self.checkpointer.expansion(cp) ?? self.context.evaluator.machine.apply(.procedure(transformer), to: .pair(cdr, .null)) self.checkpointer.associate(.expansion(expanded), with: cp) // log("expanded = \(expanded)") return expanded } default: return nil } } else { return nil } case .macroExpansionRequired(let transformer): let expanded = try self.context.evaluator.machine.apply(.procedure(transformer), to: .pair(cdr, .null)) // log("expanded = \(expanded)") return expanded } default: return nil } } /// Expand expression `expr` in environment `env`. private func expand(_ expr: Expr, in env: Env, into: inout Exprs, depth: Int = 20) throws { guard depth > 0 else { into.append(expr) return } if case .pair(.symbol(let fun), let embedded) = expr, fun.root == self.context.symbols.begin, env.isImmutable(fun) { var lst = embedded while case .pair(let e, let next) = lst { try self.expand(e, in: env, into: &into, depth: depth) lst = next } } else if let expanded = try self.expand(expr, in: env) { try self.expand(expanded, in: env, into: &into, depth: depth - 1) } else { into.append(expr) } } /// Expand expression `expr` in environment `env`. public func macroExpand(_ expr: Expr, in env: Env) throws -> Expr? { switch expr { case .pair(.symbol(let sym), let cdr): switch self.lookupLocalValueOf(sym, in: env) { case .success: return nil case .globalLookupRequired(let lexicalSym, let environment): if case .special(let special) = self.value(of: lexicalSym, in: environment) { switch special.kind { case .primitive(_): return nil case .macro(let transformer): return try self.context.evaluator.machine.apply(.procedure(transformer), to: .pair(cdr, .null)) } } return nil case .macroExpansionRequired(let transformer): return try self.context.evaluator.machine.apply(.procedure(transformer), to: .pair(cdr, .null)) } default: return nil } } /// Compile expression `expr` in environment `env`. Parameter `tail` specifies if `expr` /// is located in a tail position. This allows compile to generate code with tail calls. @discardableResult public func compile(_ expr: Expr, in env: Env, inTailPos tail: Bool) throws -> Bool { let cp = self.checkpointer.checkpoint() switch expr { case .null: throw RuntimeError.eval(.executeEmptyList) case .symbol(let sym): try self.pushValueOf(sym, in: env) case .pair(.symbol(let sym), let cdr): let pushFrameIp = self.emit(.makeFrame) // Try to push the function if locally defined switch self.pushLocalValueOf(sym, in: env) { case .success: break // Nothing to do case .globalLookupRequired(let lexicalSym, let environment): // Is there a special compiler plugin for this global binding, or is this a // keyword/special form)? if let value = self.checkpointer.fromGlobalEnv(cp) ?? self.value(of: lexicalSym, in: environment) { self.checkpointer.associate(.fromGlobalEnv(value), with: cp) switch value { case .procedure(let proc): if case .primitive(_, _, .some(let formCompiler)) = proc.kind, self.checkpointer.systemDefined(cp) || environment.isImmutable(lexicalSym) { self.checkpointer.associate(.systemDefined, with: cp) self.removeLastInstr() return try formCompiler(self, expr, env, tail) } case .special(let special): self.removeLastInstr() switch special.kind { case .primitive(let formCompiler): return try formCompiler(self, expr, env, tail) case .macro(let transformer): let expanded = try self.checkpointer.expansion(cp) ?? self.context.evaluator.machine.apply(.procedure(transformer), to: .pair(cdr, .null)) self.checkpointer.associate(.expansion(expanded), with: cp) // log("expanded = \(expanded)") return try self.compile(expanded, in: env, inTailPos: tail) } default: break // Compile as normal global function call } } // Push function from global binding let locRef = self.forceDefinedLocationRef(for: lexicalSym, in: environment) if case .immutableImport(let loc) = locRef { let value = self.context.heap.locations[loc] if value.isUndef { self.emit(.pushGlobal(loc)) } else { try self.pushValue(value) } } else { self.emit(.pushGlobal(locRef.location!)) } case .macroExpansionRequired(let transformer): let expanded = try self.context.evaluator.machine.apply(.procedure(transformer), to: .pair(cdr, .null)) // log("expanded = \(expanded)") return try self.compile(expanded, in: env, inTailPos: tail) } // Push arguments and call function if self.call(try self.compileExprs(cdr, in: env), inTailPos: tail) { // Remove MakeFrame if this was a tail call self.patch(.noOp, at: pushFrameIp) return true } case .pair(.procedure(let proc), let cdr): let pushFrameIp = self.emit(.makeFrame) // Push function try self.pushValue(.procedure(proc)) // Push arguments let n = proc == self.context.evaluator.loader ? try self.pushValues(cdr) : try self.compileExprs(cdr, in: env) // Call procedure if self.call(n, inTailPos: tail) { // Remove MakeFrame if this was a tail call self.patch(.noOp, at: pushFrameIp) return true } case .pair(let car, let cdr): let pushFrameIp = self.emit(.makeFrame) // Push function try self.compile(car, in: env, inTailPos: false) // Push arguments and call function if self.call(try self.compileExprs(cdr, in: env), inTailPos: tail) { // Remove MakeFrame if this was a tail call self.patch(.noOp, at: pushFrameIp) return true } default: try self.pushValue(expr) } return false } /// Compile the given list of expressions `expr` in environment `env` and push each result /// onto the stack. This method returns the number of expressions that were evaluated and /// whose result has been stored on the stack. public func compileExprs(_ expr: Expr, in env: Env) throws -> Int { var n = 0 var next = expr while case .pair(let car, let cdr) = next { try self.compile(car, in: env, inTailPos: false) n += 1 next = cdr } guard next.isNull else { throw RuntimeError.type(expr, expected: [.properListType]) } return n } /// Returns `nil` if `sym` does not refer to any definition special form. Returns `true` if /// `sym` refers to special form `define`. Returns `false` if `sym` refers to special form /// `defineValues`. private func refersToDefine(_ sym: Symbol, in env: Env) -> Bool? { // This is the old logic; kept it here as a fallback if `define` is not available via the // corresponding virtual machine if self.context.evaluator.defineSpecial == nil { let root = sym.root if env.isImmutable(sym) { if root == self.context.symbols.define { return true } else if root == self.context.symbols.defineValues { return false } } return nil // This is the correct logic that determines if `sym` refers to a definition special // form or not } else { switch self.lookupLocalValueOf(sym, in: env) { case .globalLookupRequired(let glob, let environment): if let expr = self.value(of: glob, in: environment), case .special(let special) = expr { if special == self.context.evaluator.defineSpecial { return true } else if special == self.context.evaluator.defineValuesSpecial { return false } } fallthrough default: return nil } } } /// Compile the sequence of expressions `expr` in environment `env`. Parameter `tail` /// specifies if `expr` is located in a tail position. This allows the compiler to generate /// code with tail calls. @discardableResult public func compileSeq(_ expr: Expr, in env: Env, inTailPos tail: Bool, localDefine: Bool = true, inDirectory: String? = nil) throws -> Bool { // Return void for empty sequences guard !expr.isNull else { self.emit(.pushVoid) return false } // Override the source directory if the code comes from a different file let oldDir = self.sourceDirectory if let dir = inDirectory { self.sourceDirectory = dir } defer { self.sourceDirectory = oldDir } // Partially expand expressions in the sequence var next = expr var exprs = Exprs() while case .pair(let car, let cdr) = next { if localDefine { try self.expand(car, in: env, into: &exprs) } else { exprs.append(car) } next = cdr } // Throw error if the sequence is not a proper list guard next.isNull else { throw RuntimeError.type(expr, expected: [.properListType]) } // Identify internal definitions var i = 0 var bindings = Exprs() if localDefine { loop: while i < exprs.count { guard case .pair(.symbol(let fun), let binding) = exprs[i], let isDefine = self.refersToDefine(fun, in: env) else { break loop } // Distinguish value definitions from function definitions if isDefine { switch binding { case .pair(.symbol(let sym), .pair(let def, .null)): bindings.append(.pair(.pair(.symbol(sym), .null), .pair(def, .null))) case .pair(.pair(.symbol(let sym), let args), let def): bindings.append( .pair(.pair(.symbol(sym), .null), .pair(.pair(.symbol(Symbol(self.context.symbols.lambda, env.global)), .pair(args, def)), .null))) default: break loop } // Handle multi-value definitions } else { switch binding { case .pair(.null, .pair(let def, .null)): bindings.append(.pair(.null, .pair(def, .null))) case .pair(.pair(.symbol(let sym), let more), .pair(let def, .null)): bindings.append(.pair(.pair(.symbol(sym), more), .pair(def, .null))) default: break loop } } i += 1 } } // Compile the sequence var exit = false if i == 0 { // Compilation with no internal definitions while i < exprs.count { if i > 0 { self.emit(.pop) } exit = try self.compile(exprs[i], in: env, inTailPos: tail && (i == exprs.count - 1)) i += 1 } return exit } else { // Compilation with internal definitions let initialLocals = self.numLocals let group = try self.compileMultiBindings(.makeList(bindings), in: env, atomic: true, predef: true) let lenv = Env(group) var first = true while i < exprs.count { if !first { self.emit(.pop) } exit = try self.compile(exprs[i], in: lenv, inTailPos: tail && (i == exprs.count - 1)) first = false i += 1 } // Push void in case there is no non-define expression left if first { self.emit(.pushVoid) } return self.finalizeBindings(group, exit: exit, initialLocals: initialLocals) } } /// Compiles the given binding list of the form /// ```((ident init) ...)``` /// and returns a `BindingGroup` with information about the established local bindings. public func compileBindings(_ bindingList: Expr, in lenv: Env, atomic: Bool, predef: Bool, postset: Bool = false) throws -> BindingGroup { let group = BindingGroup(owner: self, parent: lenv) let env = atomic && !predef ? lenv : .local(group) var bindings = bindingList if predef || postset { while case .pair(.pair(.symbol(let sym), _), let rest) = bindings { let binding = group.allocBindingFor(sym) // This is a hack for now; we need to make sure forward references work, e.g. in // lambda expressions. A way to do this is to allocate variables for all bindings that // are predefined. binding.wasMutated() self.emit(.pushUndef) self.emit(binding.isValue ? .setLocal(binding.index) : .makeLocalVariable(binding.index)) bindings = rest } bindings = bindingList } var definitions: [Definition] = [] var prevIndex = -1 while case .pair(let binding, let rest) = bindings { guard case .pair(.symbol(let sym), .pair(let expr, .null)) = binding else { throw RuntimeError.eval(.malformedBinding, binding, bindingList) } try self.compile(expr, in: env, inTailPos: false) self.patchMakeClosure(sym) let binding = group.allocBindingFor(sym) guard !atomic || (predef && !postset) || binding.index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } if postset { definitions.append(binding) } else if binding.isValue { self.emit(.setLocal(binding.index)) } else if predef { self.emit(.setLocalValue(binding.index)) } else { self.emit(.makeLocalVariable(binding.index)) } prevIndex = binding.index bindings = rest } guard bindings.isNull else { throw RuntimeError.eval(.malformedBindings, bindingList) } for binding in definitions.reversed() { if binding.isValue { self.emit(.setLocal(binding.index)) } else { self.emit(.setLocalValue(binding.index)) } } return group } /// Compiles the given binding list of the form /// ```(((ident ...) init) ...)``` /// and returns a `BindingGroup` with information about the established local bindings. public func compileMultiBindings(_ bindingList: Expr, in lenv: Env, atomic: Bool, predef: Bool = false) throws -> BindingGroup { let group = BindingGroup(owner: self, parent: lenv) let env = atomic && !predef ? lenv : .local(group) var bindings = bindingList if predef { while case .pair(.pair(let variables, _), let rest) = bindings { var vars = variables while case .pair(.symbol(let sym), let more) = vars { let binding = group.allocBindingFor(sym) // This is a hack for now; we need to make sure forward references work, e.g. in // lambda expressions. A way to do this is to allocate variables for all bindings that // are predefined. binding.wasMutated() self.emit(.pushUndef) self.emit(binding.isValue ? .setLocal(binding.index) : .makeLocalVariable(binding.index)) vars = more } bindings = rest } bindings = bindingList } var prevIndex = -1 while case .pair(let binding, let rest) = bindings { guard case .pair(let variables, .pair(let expr, .null)) = binding else { throw RuntimeError.eval(.malformedBinding, binding, bindingList) } try self.compile(expr, in: env, inTailPos: false) var vars = variables var syms = [Symbol]() while case .pair(.symbol(let sym), let rest) = vars { syms.append(sym) vars = rest } switch vars { case .null: if syms.count == 1 { self.patchMakeClosure(syms[0]) } else { self.emit(.unpack(syms.count, false)) } case .symbol(let sym): self.emit(.unpack(syms.count, true)) let binding = group.allocBindingFor(sym) if binding.isValue { self.emit(.setLocal(binding.index)) } else if predef { self.emit(.setLocalValue(binding.index)) } else { self.emit(.makeLocalVariable(binding.index)) } prevIndex = binding.index default: throw RuntimeError.eval(.malformedBinding, binding, bindingList) } for sym in syms.reversed() { let binding = group.allocBindingFor(sym) guard predef || binding.index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } if binding.isValue { self.emit(.setLocal(binding.index)) } else if predef { self.emit(.setLocalValue(binding.index)) } else { self.emit(.makeLocalVariable(binding.index)) } prevIndex = binding.index } bindings = rest } guard bindings.isNull else { throw RuntimeError.eval(.malformedBindings, bindingList) } return group } func compileOptionalBindings(_ bindingList: Expr, in lenv: Env, optenv: Env?) throws -> BindingGroup { let group = BindingGroup(owner: self, parent: lenv) let env = optenv ?? .local(group) var bindings = bindingList var prevIndex = -1 while case .pair(.symbol(let sym), let rest) = bindings { self.emit(.decons) let binding = group.allocBindingFor(sym) guard binding.index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } if binding.isValue { self.emit(.setLocal(binding.index)) } else { self.emit(.makeLocalVariable(binding.index)) } prevIndex = binding.index bindings = rest } while case .pair(let binding, let rest) = bindings { guard case .pair(.symbol(let sym), .pair(let expr, .null)) = binding else { throw RuntimeError.eval(.malformedBinding, binding, bindingList) } self.emit(.dup) self.emit(.isNull) let branchIfIp = self.emitPlaceholder() self.emit(.decons) let branchIp = self.emitPlaceholder() self.patch(.branchIf(self.offsetToNext(branchIfIp)), at: branchIfIp) try self.compile(expr, in: env, inTailPos: false) self.patch(.branch(self.offsetToNext(branchIp)), at: branchIp) let binding = group.allocBindingFor(sym) guard binding.index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } if binding.isValue { self.emit(.setLocal(binding.index)) } else { self.emit(.makeLocalVariable(binding.index)) } prevIndex = binding.index bindings = rest } switch bindings { case .null: self.emit(.failIfNotNull) case .symbol(let sym): let binding = group.allocBindingFor(sym) guard binding.index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } if binding.isValue { self.emit(.setLocal(binding.index)) } else { self.emit(.makeLocalVariable(binding.index)) } default: throw RuntimeError.eval(.malformedBindings, bindingList) } return group } /// This function should be used for finalizing the compilation of blocks with local /// bindings. It finalizes the binding group and resets the local bindings so that the /// garbage collector can deallocate the objects that are not used anymore. public func finalizeBindings(_ group: BindingGroup, exit: Bool, initialLocals: Int) -> Bool { group.finalize() if !exit && self.numLocals > initialLocals { self.emit(.reset(initialLocals, self.numLocals - initialLocals)) } self.numLocals = initialLocals return exit } /// Binds a list of keywords to macro transformers in the given local environment `lenv`. /// If `recursive` is set to true, the macro transformers are evaluated in an environment that /// includes their own definition. public func compileMacros(_ bindingList: Expr, in lenv: Env, recursive: Bool) throws -> BindingGroup { var numMacros = 0 let group = BindingGroup(owner: self, parent: lenv, nextIndex: { numMacros += 1 return numMacros - 1 }) let env = recursive ? Env(group) : lenv var bindings = bindingList while case .pair(let binding, let rest) = bindings { guard case .pair(.symbol(let sym), .pair(let transformer, .null)) = binding else { throw RuntimeError.eval(.malformedBinding, binding, bindingList) } let procExpr = try self.context.evaluator.machine.compileAndEval(expr: transformer, in: env.syntacticalEnv, usingRulesEnv: env) guard case .procedure(let proc) = procExpr else { throw RuntimeError.eval(.malformedTransformer, transformer) //FIXME: Find better error message } guard group.bindingFor(sym) == nil else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } group.defineMacro(sym, proc: proc) bindings = rest } guard bindings.isNull else { throw RuntimeError.eval(.malformedBindings, bindingList) } return group } /// Compiles a closure consisting of a list of formal arguments `arglist`, a list of /// expressions `body`, and a local environment `env`. It puts the closure on top of the /// stack. /// When `optionals` is set to true, optional parameters are supported. /// When `atomic` is set to true, defaults of optional parameters are evaluated in `env`. /// When `tagged` is set to true, it is assumed a tag is on the stack and this tag is stored /// in the resulting closure. /// When `continuation` is set to true, the resulting closure is represented as a continuation. public func compileLambda(_ nameIdx: Int?, _ arglist: Expr, _ body: Expr, _ env: Env, optionals: Bool = false, atomic: Bool = true, tagged: Bool = false, continuation: Bool = false) throws { // Create closure compiler as child of the current compiler let closureCompiler = Compiler(in: env, and: env, usingCheckpointer: self.checkpointer) // Compile arguments let (arguments, next) = closureCompiler.collectArguments(arglist) switch next { case .null: // Handle arguments closureCompiler.emit(.assertArgCount(arguments.count)) closureCompiler.arguments = arguments closureCompiler.env = .local(arguments) // Compile body try closureCompiler.compileBody(body, localDefine: true) case .symbol(let sym): // Handle arguments if arguments.count > 0 { closureCompiler.emit(.assertMinArgCount(arguments.count)) } closureCompiler.emit(.collectRest(arguments.count)) arguments.allocBindingFor(sym) closureCompiler.arguments = arguments closureCompiler.env = .local(arguments) // Compile body try closureCompiler.compileBody(body, localDefine: true) case .pair(.pair(.symbol(_), _), _): // Handle arguments if arguments.count > 0 { closureCompiler.emit(.assertMinArgCount(arguments.count)) } closureCompiler.emit(.collectRest(arguments.count)) closureCompiler.arguments = arguments closureCompiler.env = .local(arguments) // Compile body try closureCompiler.compileBody(body, optionals: next, optenv: atomic ? env : nil, localDefine: true) default: throw RuntimeError.eval(.malformedArgumentList, arglist) } // Link compiled closure in the current compiler let codeIndex = self.fragments.count let code = closureCompiler.bundle() // Try to create procedure statically and store in constant pool if !tagged && !continuation && closureCompiler.captures.count == 0 { let type: Procedure.ClosureType if let idx = nameIdx, case .symbol(let sym) = self.constants[idx] { type = .named(sym.description) } else { type = .anonymous } self.pushProcedure(Procedure(type, [], code)) } else { // Store code fragment self.fragments.append(code) // Generate code for pushing captured bindings onto the stack for def in closureCompiler.captures.definitions { if let def = def, let capture = closureCompiler.captures.captureFor(def) { if capture.origin.owner === self { self.emit(.pushLocal(def.index)) } else { self.emit(.pushCaptured(self.captures.capture(def, from: capture.origin))) } } } // Return captured binding count and index of compiled closure if tagged { self.emit(.makeTaggedClosure(nameIdx ?? (continuation ? -2 : -1), closureCompiler.captures.count, codeIndex)) } else { self.emit(.makeClosure(nameIdx ?? (continuation ? -2 : -1), closureCompiler.captures.count, codeIndex)) } } } /// Compiles a closure consisting of a list of formal arguments `arglist`, a list of /// expressions `body`, and a local environment `env`. It puts the closure on top of the /// stack. public func compileCaseLambda(_ nameIdx: Int?, _ cases: Expr, _ env: Env, tagged: Bool = false) throws { // Create closure compiler as child of the current compiler let closureCompiler = Compiler(in: env, and: env, usingCheckpointer: self.checkpointer) // Iterate through all cases var current = cases loop: while case .pair(.pair(let args, let body), let nextCase) = current { // Reset compiler closureCompiler.env = env closureCompiler.numLocals = 0 closureCompiler.maxLocals = 0 closureCompiler.arguments = nil // Compile arguments let (arguments, next) = closureCompiler.collectArguments(args) var exactIp = -1 var minIp = -1 let numArgs = arguments.count switch next { case .null: exactIp = closureCompiler.emitPlaceholder() case .symbol(let sym): if arguments.count > 0 { minIp = closureCompiler.emitPlaceholder() } closureCompiler.emit(.collectRest(arguments.count)) arguments.allocBindingFor(sym) default: throw RuntimeError.eval(.malformedArgumentList, args) } closureCompiler.arguments = arguments closureCompiler.env = .local(arguments) // Compile body try closureCompiler.compileBody(body) // Fix jumps if exactIp >= 0 { closureCompiler.patch( .branchIfArgMismatch(numArgs, closureCompiler.offsetToNext(exactIp)), at: exactIp) } else if minIp >= 0 { closureCompiler.patch( .branchIfMinArgMismatch(numArgs, closureCompiler.offsetToNext(minIp)), at: minIp) } else { break loop } // Move to next case current = nextCase } // Compile final "else" case switch current { case .pair(.pair(_, _), _): break // early exit case .null: closureCompiler.emit(.noMatchingArgCount) default: throw RuntimeError.eval(.malformedCaseLambda, current) } // Link compiled closure in the current compiler let codeIndex = self.fragments.count let code = closureCompiler.bundle() // Try to create procedure statically and store in constant pool if !tagged && closureCompiler.captures.count == 0 { let type: Procedure.ClosureType if let idx = nameIdx, case .symbol(let sym) = self.constants[idx] { type = .named(sym.description) } else { type = .anonymous } self.pushProcedure(Procedure(type, [], code)) } else { // Store code fragment self.fragments.append(code) // Generate code for pushing captured bindings onto the stack for def in closureCompiler.captures.definitions { if let def = def, let capture = closureCompiler.captures.captureFor(def) { if capture.origin.owner === self { self.emit(.pushLocal(def.index)) } else { self.emit(.pushCaptured(self.captures.capture(def, from: capture.origin))) } } } // Return captured binding count and index of compiled closure if tagged { self.emit(.makeTaggedClosure(nameIdx ?? -1, closureCompiler.captures.count, codeIndex)) } else { self.emit(.makeClosure(nameIdx ?? -1, closureCompiler.captures.count, codeIndex)) } } } /// Bundles the code generated by this compiler into a `Code` object. public func bundle() -> Code { // Performce peephole optimization self.optimize() // Create code object return Code(self.instructions, self.constants, self.fragments) } /// This is just a placeholder for now. Will add a peephole optimizer eventually. For now, /// only NOOPs are removed. private func optimize() { var instrIndex: [Int] = [] var numInstr: Int = 0 for instr in self.instructions { instrIndex.append(numInstr) if case .noOp = instr { continue } numInstr += 1 } var ip = 0 while ip < self.instructions.count { switch self.instructions[ip] { case .branch(let offset): switch self.instructions[ip + offset] { case .tailCall(let n): self.instructions[ip] = .tailCall(n) case .return: self.instructions[ip] = .return case .branch(let offset2): self.instructions[ip] = .branch(instrIndex[ip + offset + offset2] - instrIndex[ip]) default: self.instructions[ip] = .branch(instrIndex[ip + offset] - instrIndex[ip]) } case .branchIf(let offset): self.instructions[ip] = .branchIf(instrIndex[ip + offset] - instrIndex[ip]) case .branchIfNot(let offset): self.instructions[ip] = .branchIfNot(instrIndex[ip + offset] - instrIndex[ip]) case .keepOrBranchIfNot(let offset): self.instructions[ip] = .keepOrBranchIfNot(instrIndex[ip + offset] - instrIndex[ip]) case .branchIfArgMismatch(let n, let offset): self.instructions[ip] = .branchIfArgMismatch(n, instrIndex[ip + offset] - instrIndex[ip]) case .branchIfMinArgMismatch(let n, let offset): self.instructions[ip] = .branchIfMinArgMismatch(n, instrIndex[ip + offset] - instrIndex[ip]) case .or(let offset): self.instructions[ip] = .or(instrIndex[ip + offset] - instrIndex[ip]) case .and(let offset): self.instructions[ip] = .and(instrIndex[ip + offset] - instrIndex[ip]) default: break } ip += 1 } ip = 0 while ip < self.instructions.count { if case .noOp = self.instructions[ip] { self.instructions.remove(at: ip) } else { ip += 1 } } } }
apache-2.0
be59151c9edad5c244e1ef8eefb3ecb7
37.88744
102
0.590656
4.448379
false
false
false
false
msahins/myTV
SwiftRadio/RadioStation.swift
1
1760
import UIKit //***************************************************************** // Radio Station //***************************************************************** // Class inherits from NSObject so that you may easily add features // i.e. Saving favorite stations to CoreData, etc class RadioStation: NSObject { var stationName : String var stationStreamURL: String var stationImageURL : String var stationDesc : String var stationLongDesc : String init(name: String, streamURL: String, imageURL: String, desc: String, longDesc: String) { self.stationName = name self.stationStreamURL = streamURL self.stationImageURL = imageURL self.stationDesc = desc self.stationLongDesc = longDesc } // Convenience init without longDesc convenience init(name: String, streamURL: String, imageURL: String, desc: String) { self.init(name: name, streamURL: streamURL, imageURL: imageURL, desc: desc, longDesc: "") } //***************************************************************** // MARK: - JSON Parsing into object //***************************************************************** class func parseStation(stationJSON: JSON) -> (RadioStation) { let name = stationJSON["name"].string ?? "" let streamURL = stationJSON["streamURL"].string ?? "" let imageURL = stationJSON["imageURL"].string ?? "" let desc = stationJSON["desc"].string ?? "" let longDesc = stationJSON["longDesc"].string ?? "" let station = RadioStation(name: name, streamURL: streamURL, imageURL: imageURL, desc: desc, longDesc: longDesc) return station } }
mit
05b3c38be774fe451708e0e17f4fee5d
35.666667
120
0.534091
5.333333
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/Kuery/Sources/Kuery/Operator.swift
1
9374
// // Operators.swift // Kuery // // Created by Kishikawa Katsumi on 2017/06/14. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import Foundation import CoreData // MARK: Logical Operators public func && <ManagedObject>(lhs: BasicPredicate<ManagedObject>, rhs: BasicPredicate<ManagedObject>) -> AndPredicate<ManagedObject> { return AndPredicate(left: lhs, right: rhs) } public func || <ManagedObject>(lhs: BasicPredicate<ManagedObject>, rhs: BasicPredicate<ManagedObject>) -> OrPredicate<ManagedObject> { return OrPredicate(left: lhs, right: rhs) } public prefix func ! <ManagedObject>(predicate: BasicPredicate<ManagedObject>) -> NotPredicate<ManagedObject> { return NotPredicate(original: predicate) } // MARK: String public func == <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, String?>, rhs: String) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSString]) } public func != <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, String?>, rhs: String) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSString]) } public func ~= <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, String?>, rhs: String) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K LIKE %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSString]) } public func << <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, String?>, rhs: [String]) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K IN %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSArray]) } // MARK: Bool public func == <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Bool>, rhs: Bool) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSNumber]) } public func != <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Bool>, rhs: Bool) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSNumber]) } public func << <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Bool>, rhs: [Bool]) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K IN %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSArray]) } // MARK: URL public func == <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, URL?>, rhs: URL) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSURL]) } public func != <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, URL?>, rhs: URL) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSURL]) } public func << <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, URL?>, rhs: [URL]) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K IN %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSArray]) } // MARK: UUID public func == <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, UUID?>, rhs: UUID) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSUUID]) } public func != <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, UUID?>, rhs: UUID) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSUUID]) } public func << <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, UUID?>, rhs: [UUID]) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K IN %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSArray]) } // MARK: Object public func == <ManagedObject: NSManagedObject, RelationObject: NSManagedObject>(lhs: KeyPath<ManagedObject, RelationObject?>, rhs: RelationObject) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs]) } public func != <ManagedObject: NSManagedObject, RelationObject: NSManagedObject>(lhs: KeyPath<ManagedObject, RelationObject?>, rhs: RelationObject) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs]) } public func << <ManagedObject: NSManagedObject, RelationObject: NSManagedObject>(lhs: KeyPath<ManagedObject, RelationObject?>, rhs: [RelationObject]) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K IN %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSArray]) } // MARK: Numeric public func < <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: Property) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K < %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as! NSNumber]) } public func > <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: Property) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K > %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as! NSNumber]) } public func <= <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: Property) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K <= %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as! NSNumber]) } public func >= <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: Property) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K >= %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as! NSNumber]) } public func == <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: Property) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as! NSNumber]) } public func != <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: Property) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as! NSNumber]) } public func << <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: [Property]) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K IN %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSArray]) } public func << <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: ClosedRange<Property>) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K BETWEEN %@", arguments: [lhs._kvcKeyPathString! as NSString, [rhs.lowerBound, rhs.upperBound] as NSArray]) } public func << <ManagedObject: NSManagedObject, Property: Numeric>(lhs: KeyPath<ManagedObject, Property>, rhs: CountableClosedRange<Property>) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K BETWEEN %@", arguments: [lhs._kvcKeyPathString! as NSString, [rhs.lowerBound, rhs.upperBound] as NSArray]) } // MARK: Date public func < <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Date?>, rhs: Date) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K < %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSDate]) } public func > <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Date?>, rhs: Date) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K > %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSDate]) } public func <= <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Date?>, rhs: Date) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K <= %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSDate]) } public func >= <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Date?>, rhs: Date) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K >= %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSDate]) } public func == <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Date?>, rhs: Date) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K == %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSDate]) } public func != <ManagedObject: NSManagedObject>(lhs: KeyPath<ManagedObject, Date?>, rhs: Date) -> BasicPredicate<ManagedObject> { return BasicPredicate<ManagedObject>(format: "%K != %@", arguments: [lhs._kvcKeyPathString! as NSString, rhs as NSDate]) }
mit
c2f1a9e5781637f8a39b83931c4962de
56.858025
184
0.739144
4.444286
false
false
false
false
resmio/TastyTomato
TastyTomato/Code/Extensions/Public/CGRect/CGRect (LeftRightTopBottomCenter).swift
1
2081
// // CGRect (LeftRightTopBottomCenter).swift // TastyTomato // // Created by Jan Nash on 7/28/16. // Copyright © 2016 resmio. All rights reserved. // import UIKit // MARK: // Public public extension CGRect { var left: CGFloat { get { return self._left } set(newLeft) { self._left = newLeft } } var right: CGFloat { get { return self._right } set(newRight) { self._right = newRight } } var top: CGFloat { get { return self._top } set(newTop) { self._top = newTop } } var bottom: CGFloat { get { return self._bottom } set(newBottom) { self._bottom = newBottom } } var center: CGPoint { get { return self._center } set(newCenter) { self._center = newCenter } } } // MARK: // Private private extension CGRect { var _left: CGFloat { get { return self.origin.x } set(newLeft) { self.origin.x = newLeft } } var _right: CGFloat { get { return self.left + self.width } set(newRight) { self.origin.x += newRight - self.right } } var _top: CGFloat { get { return self.origin.y } set(newTop) { self.origin.y = newTop } } var _bottom: CGFloat { get { return self.origin.y + self.height } set(newBottom) { self.origin.y += newBottom - self.bottom } } var _center: CGPoint { get { let x: CGFloat = self.midX let y: CGFloat = self.midY return CGPoint(x: x, y: y) } set(newCenter) { self.left += newCenter.x - self.center.x self.top += newCenter.y - self.center.y } } }
mit
65ca557caab701585129f32021d7ec01
17.909091
52
0.438462
4.135189
false
false
false
false
DerLobi/Depressed
Depressed?/Model/Question.swift
1
2842
import ResearchKit /// A question the user answers. public struct Question { /// The identifier of the question. public let identifier: QuestionIdentifier /// A headline summing up the question. public let title: String /// the complete text of the question. public let text: String /// An `ORKStep` representation, suitable to use with a `ORKTask`. public var step: ORKQuestionStep { let step = ORKQuestionStep(identifier: identifier.rawValue, title: title, question: text, answer: ORKTextChoiceAnswerFormat.phq9Format) step.isOptional = false return step } /// Creates a new `Question` from a `QuestionIdentifier`. /// /// - parameter identifier: a question identifier. /// /// - returns: A newly initialized Question. public init(identifier: QuestionIdentifier) { self.identifier = identifier switch identifier { case .losingInterest: title = NSLocalizedString("question_title_losing_interest", comment: "") text = NSLocalizedString("question_text_losing_interest", comment: "") case .feelingDepressed: title = NSLocalizedString("question_title_feeling_depressed", comment: "") text = NSLocalizedString("question_text_feeling_depressed", comment: "") case .troubleSleeping: title = NSLocalizedString("question_title_trouble_sleeping", comment: "") text = NSLocalizedString("question_text_trouble_sleeping", comment: "") case .feelingTired: title = NSLocalizedString("question_title_feeling_tired", comment: "") text = NSLocalizedString("question_text_feeling_tired", comment: "") case .poorAppetite: title = NSLocalizedString("question_title_poor_appetite", comment: "") text = NSLocalizedString("question_text_poor_appetite", comment: "") case .lowSelfEsteem: title = NSLocalizedString("question_title_low_self_esteem", comment: "") text = NSLocalizedString("question_text_low_self_esteem", comment: "") case .troubleConcentrating: title = NSLocalizedString("question_title_trouble_concentrating", comment: "") text = NSLocalizedString("question_text_trouble_concentrating", comment: "") case .slowOrFast: title = NSLocalizedString("question_title_slow_or_fast", comment: "") text = NSLocalizedString("question_text_slow_or_fast", comment: "") case .feelingSuicidal: title = NSLocalizedString("question_title_feeling_suicidal", comment: "") text = NSLocalizedString("question_text_feeling_suicidal", comment: "") } } }
mit
c788678db0f14619d5fb1983ed9741ff
42.060606
90
0.627023
4.682043
false
false
false
false
coffee-cup/solis
SunriseSunset/TimeFormatters.swift
1
3066
// // TimeFormatters.swift // SunriseSunset // // Created by Jake Runzer on 2016-06-19. // Copyright © 2016 Puddllee. All rights reserved. // import Foundation enum TimeFormat { case hour24 case hour12 case delta var description: String { switch(self) { case .hour24: return "HH:mm" case .hour12: return "h:mm a" case .delta: return "delta" } } } class TimeFormatters { static func timeFormatter(_ format: String, timeZone: TimeZone) -> DateFormatter { let timeFormatter = DateFormatter() timeFormatter.timeZone = timeZone timeFormatter.dateFormat = format return timeFormatter } // Create single instance of date formatter for each time zone // When time zone changes, create new date formatter static var formatter12hInstance = TimeFormatters.timeFormatter(TimeFormat.hour12.description, timeZone: TimeZone.ReferenceType.local) class func formatter12h(_ timeZone: TimeZone) -> DateFormatter { return formatter12hInstance.timeZone == timeZone ? formatter12hInstance : timeFormatter(TimeFormat.hour12.description, timeZone: timeZone) } static var formatter24hInstance = TimeFormatters.timeFormatter(TimeFormat.hour24.description, timeZone: TimeZone.ReferenceType.local) class func formatter24h(_ timeZone: TimeZone) -> DateFormatter { return formatter24hInstance.timeZone == timeZone ? formatter24hInstance : timeFormatter(TimeFormat.hour24.description, timeZone: timeZone) } static func currentFormatter(_ timeZone: TimeZone) -> DateFormatter? { let timeFormat = Defaults.timeFormat if timeFormat == TimeFormat.hour12.description { return formatter12h(timeZone) } else if timeFormat == TimeFormat.hour24.description { return formatter24h(timeZone) } return nil } static func currentFormattedString(_ time: Date, timeZone: TimeZone) -> String { var text = "" let timeOffset = time.addingTimeInterval(0) // may have to change let hours = timeOffset.getHoursToNow() let minutes = timeOffset.getMinutesToNow() let hourMinutes = abs(minutes - (hours * 60)) let inPast = timeOffset.timeIntervalSinceNow < 0 if Defaults.delta { text += inPast ? "- " : "+ " if hours != 0 { text += "\(hours)h" } if hours != 0 && hourMinutes != 0 { text += " " } if hourMinutes != 0 { text += "\(hourMinutes)m" } if hours == 0 && hourMinutes == 0 { text = "--" } } else { if let formatter = currentFormatter(timeZone) { text = formatter.string(from: time) text = text.replacingOccurrences(of: "AM", with: "am") text = text.replacingOccurrences(of: "PM", with: "pm") } } return text } }
mit
800eb6dcfdafba3c410538ca3ae797eb
33.829545
146
0.606852
4.708141
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/RxSwift/RxSwift/RxSwift/Disposables/CompositeDisposable.swift
2
2749
// // CompositeDisposable.swift // Rx // // Created by Krunoslav Zaher on 2/20/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation public class CompositeDisposable : DisposeBase, Disposable { public typealias BagKey = Bag<Disposable>.KeyType typealias State = ( disposables: RxMutableBox<Bag<Disposable>>!, disposed: Bool ) var lock: Lock = Lock() var state: State = ( disposables: RxMutableBox(Bag()), disposed: false ) public override init() { } public init(_ disposable1: Disposable, _ disposable2: Disposable) { let bag = state.disposables bag.value.put(disposable1) bag.value.put(disposable2) } public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { let bag = state.disposables bag.value.put(disposable1) bag.value.put(disposable2) bag.value.put(disposable3) } public init(disposables: [Disposable]) { let bag = state.disposables for disposable in disposables { bag.value.put(disposable) } } public func addDisposable(disposable: Disposable) -> BagKey? { // this should be let // bucause of compiler bug it's var let key = self.lock.calculateLocked { oldState -> BagKey? in if state.disposed { return nil } else { let key = state.disposables.value.put(disposable) return key } } if key == nil { disposable.dispose() } return key } public var count: Int { get { return self.lock.calculateLocked { self.state.disposables.value.count } } } public func removeDisposable(disposeKey: BagKey) { let disposable = self.lock.calculateLocked { Void -> Disposable? in return state.disposables.value.removeKey(disposeKey) } if let disposable = disposable { disposable.dispose() } } public func dispose() { let oldDisposables = self.lock.calculateLocked { Void -> [Disposable] in if state.disposed { return [] } let disposables = state.disposables var allValues = disposables.value.all state.disposed = true state.disposables = nil return allValues } for d in oldDisposables { d.dispose() } } }
mit
1b6955bfb2fc698c066243fb96c989a7
24.462963
98
0.536923
5.071956
false
false
false
false
aranasaurus/minutes-app
minutes/code/common/DataStore.swift
1
973
// // DataStore.swift // Minutes // // Created by Ryan Arana on 11/12/16. // Copyright © 2016 Aranasaurus. All rights reserved. // import Foundation protocol Storable: NSCoding { static var pluralName: String { get } } class DataStore<DataType: Storable> { let storageURL: URL var data: [DataType] = [] init(storageURL: URL? = nil) { self.storageURL = storageURL ?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) .first! .appendingPathComponent(DataType.pluralName) self.load() } @discardableResult func save() -> Bool { return NSKeyedArchiver.archiveRootObject(data, toFile: storageURL.path) } @discardableResult func load() -> [DataType]? { let loadedData = NSKeyedUnarchiver.unarchiveObject(withFile: storageURL.path) as? [DataType] data = loadedData ?? [] return loadedData == nil ? nil : data } }
mit
70eacc47da914a1c4dfa4b85724ef10c
24.578947
100
0.630658
4.281938
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/HomeSplash/MHomeSplashDescr.swift
1
2439
import UIKit class MHomeSplashDescr:MHomeSplashProtocol { let attributedString:NSAttributedString let kVerticalMargin:CGFloat = 30 let kMarginHorizontal:CGFloat = 10 private(set) var reusableIdentifier:String private let verticalMargin2:CGFloat private let marginHorizontal2:CGFloat private let drawingOptions:NSStringDrawingOptions private let kMaxHeight:CGFloat = 600 init(model:MHomeOptions) { reusableIdentifier = VHomeSplashCellDescr.reusableIdentifier marginHorizontal2 = kMarginHorizontal + kMarginHorizontal verticalMargin2 = kVerticalMargin + kVerticalMargin drawingOptions = NSStringDrawingOptions([ NSStringDrawingOptions.usesFontLeading, NSStringDrawingOptions.usesLineFragmentOrigin]) guard let title:String = model.title, let descr:String = model.descr else { attributedString = NSAttributedString() return } let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:22), NSForegroundColorAttributeName:UIColor.white] let attributesDescr:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:16), NSForegroundColorAttributeName:UIColor.white] let stringTitle:NSAttributedString = NSAttributedString( string:title, attributes:attributesTitle) let stringDescr:NSAttributedString = NSAttributedString( string:descr, attributes:attributesDescr) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringDescr) attributedString = mutableString } //MARK: splash protocol func cellHeightFor(width:CGFloat) -> CGFloat { let usableWidth:CGFloat = width - marginHorizontal2 let maxSize:CGSize = CGSize(width:usableWidth, height:kMaxHeight) let boundingRects:CGRect = attributedString.boundingRect( with:maxSize, options:drawingOptions, context:nil) let height:CGFloat = ceil(boundingRects.size.height) let heightMargin:CGFloat = height + verticalMargin2 return heightMargin } }
mit
e705a10fd4ced702a1f84add4512e8fa
33.352113
81
0.658877
6.082294
false
false
false
false
SmallElephant/FEAlgorithm-Swift
11-GoldenInterview/11-GoldenInterview/Other/Operator.swift
1
1525
// // Operator.swift // 11-GoldenInterview // // Created by keso on 2017/5/28. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Operator { func negate(a:Int) -> Int { var num:Int = a var result:Int = 0 let base:Int = num < 0 ? 1 : -1 while num != 0 { result += base num += base } return result } func minus(a:Int,b:Int) -> Int { return a + negate(a: b) } func multiply(a:Int,b:Int) -> Int { if a < b { return multiply(a:b,b:a) } var sum:Int = 0 for _ in 0..<abs(a: b) { sum += a } if b < 0 { sum = negate(a: sum) } return sum } func abs(a:Int) -> Int { if a < 0 { return negate(a:a) } else { return a } } func divide(a:Int,b:Int) -> Int? { if b == 0 { return nil } let numA:Int = abs(a: a) let numB:Int = abs(a: b) var result:Int = 0 var num:Int = 0 while (numB + num) < numA { num += numB result += 1 } if (a > 0 && b > 0) || (a < 0 && b < 0) { return result } else { return negate(a: result) } } }
mit
9932989b3156c53875d04080ee1cbe55
16.905882
55
0.363338
3.843434
false
false
false
false
PerfectExamples/Perfect-Authentication-Demo
Sources/PageHandlers.swift
1
1062
// // PageHandlers.swift // Perfect-Authentication // // Created by Jonathan Guthrie on 2017-01-18. // // import PerfectMustache import PerfectHTTP public struct MustacheHandler: MustachePageHandler { var context: [String: Any] public func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) { contxt.extendValues(with: context) do { contxt.webResponse.setHeader(.contentType, value: "text/html") try contxt.requestCompleted(withCollector: collector) } catch { let response = contxt.webResponse response.status = .internalServerError response.appendBody(string: "\(error)") response.completed() } } public init(context: [String: Any] = [String: Any]()) { self.context = context } } extension HTTPResponse { public func render(template: String, context: [String: Any] = [String: Any]()) { mustacheRequest(request: self.request, response: self, handler: MustacheHandler(context: context), templatePath: request.documentRoot + "/\(template).mustache") } }
apache-2.0
ac5b7b8aff0f0913f10a5bf97a04bf41
27.702703
162
0.741996
3.861818
false
false
false
false
seungprk/PenguinJump
PenguinJump/PenguinJump/StartMenuNode.swift
1
9022
// // StartMenuNode.swift // PenguinJump // // Created by Seung Park on 5/30/16. // Copyright © 2016 De Anza. All rights reserved. // import SpriteKit class StartMenuNode: SKNode { let title = SKSpriteNode(texture: nil) var playButton : SKLabelNode! var highScoreButton : SimpleButton! var aboutButton : SimpleButton! var settingsButton : SimpleButton! var wardrobeButton : SKSpriteNode! init(frame: CGRect) { super.init() // Main Title title.position = CGPointZero title.position.y += frame.height / 3 title.zPosition = 10000 let titleLabel = SKLabelNode(text: "PENGUIN") titleLabel.fontName = "Helvetica Neue Condensed Black" titleLabel.fontSize = 80 titleLabel.position = CGPointZero let subtitleLabel = SKLabelNode(text: "JUMP") subtitleLabel.fontName = "Helvetica Neue Condensed Black" subtitleLabel.fontSize = 122 subtitleLabel.position = CGPointZero subtitleLabel.position.y -= subtitleLabel.frame.height // Button "Play" playButton = SKLabelNode(text: "Play") playButton.name = "playButton" playButton.fontName = "Helvetica Neue Condensed Black" playButton.fontSize = 60 playButton.fontColor = SKColor(red: 35/255, green: 134/255, blue: 221/255, alpha: 1.0) playButton.position = CGPointZero playButton.position.y -= frame.height * 0.20 playButton.zPosition = 10000 let shrinkDown = SKAction.scaleTo(0.95, duration: 0.1) let bumpUp = SKAction.scaleTo(1.05, duration: 0.1) let bumpDown = SKAction.scaleTo(1.0, duration: 0.1) let bumpWait = SKAction.waitForDuration(2.0) let bump = SKAction.sequence([shrinkDown, bumpUp, bumpDown, bumpWait]) playButton.runAction(SKAction.repeatActionForever(bump)) // Button "Settings" settingsButton = SimpleButton(text: "Settings") settingsButton.name = "settingsButton" settingsButton.position = CGPointZero settingsButton.position.y = playButton.position.y - playButton.frame.height settingsButton.zPosition = 10000 // Button "High Scores" highScoreButton = SimpleButton(text: "High Scores") highScoreButton.name = "highScoreButton" highScoreButton.position = CGPointZero highScoreButton.position.y = settingsButton.position.y - playButton.frame.height highScoreButton.zPosition = 10000 // Button "About" aboutButton = SimpleButton(text: "About") aboutButton.name = "aboutButton" aboutButton.position = CGPointZero aboutButton.position.y = highScoreButton.position.y - playButton.frame.height aboutButton.zPosition = 10000 // Button "Wardrobe" wardrobeButton = SKSpriteNode(texture: SKTexture(image: UIImage(named: "wardrobe_icon")!)) wardrobeButton.name = "wardrobeButton" wardrobeButton.position.x += playButton.frame.width wardrobeButton.position.y -= frame.height * 0.175 wardrobeButton.zPosition = 10000 // Add to screen title.addChild(titleLabel) title.addChild(subtitleLabel) addChild(title) addChild(playButton) addChild(settingsButton) addChild(highScoreButton) addChild(aboutButton) addChild(wardrobeButton) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let parentScene = scene as! GameScene for touch in touches { let positionInScene = touch.locationInNode(self) let touchedNodes = self.nodesAtPoint(positionInScene) for touchedNode in touchedNodes { if let name = touchedNode.name { if name == "playButton" { let titleUp = SKAction.moveBy(CGVector(dx: 0, dy: 400), duration: 1.0) titleUp.timingMode = .EaseIn title.runAction(titleUp, completion: { self.title.removeFromParent() }) let playButtonDown = SKAction.moveBy(CGVector(dx: 0, dy: -300), duration: 1.0) playButtonDown.timingMode = .EaseIn playButton.runAction(playButtonDown, completion: { self.playButton.removeFromParent() }) settingsButton.runAction(playButtonDown, completion: { self.settingsButton.removeFromParent() }) highScoreButton.runAction(playButtonDown, completion: { self.highScoreButton.removeFromParent() }) aboutButton.runAction(playButtonDown, completion: { self.aboutButton.removeFromParent() }) wardrobeButton.runAction(playButtonDown, completion: { self.wardrobeButton.removeFromParent() }) parentScene.beginGame() if parentScene.gameData.soundEffectsOn == true { parentScene.buttonPressSound?.play() } } if name == "highScoreButton" { highScoreButton.buttonPress(parentScene.gameData.soundEffectsOn) } if name == "settingsButton" { settingsButton.buttonPress(parentScene.gameData.soundEffectsOn) } if name == "aboutButton" { aboutButton.buttonPress(parentScene.gameData.soundEffectsOn) } } } } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let positionInScene = touch.locationInNode(self) let touchedNodes = self.nodesAtPoint(positionInScene) for touchedNode in touchedNodes { if let name = touchedNode.name { if name == "highScoreButton" { if highScoreButton.pressed == true { highScoreButton.buttonRelease() let scoreScene = ScoreScene(size: scene!.size) let parentScene = scene as! GameScene scoreScene.score = parentScene.intScore let transition = SKTransition.moveInWithDirection(.Up, duration: 0.5) scoreScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(scoreScene, transition: transition) } } if name == "settingsButton" { if settingsButton.pressed == true { settingsButton.buttonRelease() let settingsScene = SettingsScene(size: scene!.size) settingsScene.backgroundMusic = (scene as! GameScene).backgroundMusic let transition = SKTransition.moveInWithDirection(.Up, duration: 0.5) settingsScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(settingsScene, transition: transition) } } if name == "aboutButton" { if aboutButton.pressed == true { aboutButton.buttonRelease() let aboutScene = AboutScene(size: scene!.size) let transition = SKTransition.moveInWithDirection(.Up, duration: 0.5) aboutScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(aboutScene, transition: transition) } } if name == "wardrobeButton" { let wardrobeScene = ItemSelectionScene(size: scene!.size) let transition = SKTransition.moveInWithDirection(.Up, duration: 0.5) self.scene!.view?.presentScene(wardrobeScene, transition: transition) } } } } highScoreButton.buttonRelease() settingsButton.buttonRelease() aboutButton.buttonRelease() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-2-clause
e50a81becfd9d1bd38baaf8d8e3508e5
43.438424
102
0.547389
5.54797
false
false
false
false
VladislavJevremovic/Exchange-Rates-NBS
Exchange Rates NBS/Controller/InfoViewController.swift
1
5211
// // InfoViewController.swift // Exchange Rates NBS // // Created by Vladislav Jevremovic on 4/4/15. // Copyright (c) 2015 Vladislav Jevremovic. All rights reserved. // import UIKit class InfoViewController: UITableViewController { typealias AppLink = (title: String, url: String, imageUrl: String) var appLinks = [AppLink]() override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("vcInfoTitle", comment: "vcInfoTitle") self.tableView.backgroundColor = Constants.CustomColor.TableBackgroundColor self.clearsSelectionOnViewWillAppear = true } // MARK: - Table View Data Source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 2 case 1: return appLinks.count default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return NSLocalizedString("aboutText", comment: "aboutText") case 1: return NSLocalizedString("otherAppsText", comment: "otherAppsText") default: return "" } } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 44.0 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView { let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 30.0)) label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 13.0) label.textAlignment = .center label.textColor = Constants.CustomColor.TableFooterColor switch section { case 0: label.text = NSLocalizedString("aboutFooterText", comment: "aboutFooterText") default: label.text = NSLocalizedString("otherAppsFooterText", comment: "otherAppsFooterText") } return label } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let CellIdentifier1 = "Cell1" let CellIdentifier2 = "Cell2" let CellIdentifier3 = "AppLinkCell" let accessoryView = UIImageView(image: UIImage(named: "disclosure")) accessoryView.frame = CGRect(x: 0, y: 0, width: 16, height: 16) switch (indexPath.section, indexPath.row) { case (0, 0): let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier1, for: indexPath) cell.textLabel?.text = NSLocalizedString("versionText", comment: "versionText") cell.detailTextLabel?.text = versionString() cell.backgroundColor = Constants.CustomColor.TableCellColor return cell case (0, 1): let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier2, for: indexPath) cell.textLabel?.text = NSLocalizedString("authorText", comment: "authorText") cell.detailTextLabel?.text = "Vladislav Jevremović" cell.backgroundColor = Constants.CustomColor.TableCellColor cell.accessoryView = accessoryView return cell case (1, _): let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier3, for: indexPath) cell.textLabel?.text = appLinks[indexPath.row].title if let url = URL(string: appLinks[indexPath.row].imageUrl), let data = try? Data(contentsOf: url) { cell.imageView?.image = UIImage(data: data) } cell.backgroundColor = Constants.CustomColor.TableCellColor return cell default: break } return UITableViewCell() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath.section, indexPath.row) { case (0, 1): if let url = URL(string: "http://vladislavjevremovic.com") { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } case (1, _): if let url = URL(string: appLinks[indexPath.row].url) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } default: break } } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } // MARK: - Private Methods func versionString() -> String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String } }
mit
91ff3a1c14a73c93879f10781581c94c
34.931034
112
0.624376
5.014437
false
false
false
false
Friend-LGA/LGSideMenuController
Demo/_shared_files/SideMenuController/RightViewController/RightViewController.swift
1
9479
// // RightViewController.swift // LGSideMenuControllerDemo // import Foundation import UIKit private let cellIdentifier = "cell" private let tableViewInset: CGFloat = 44.0 * 2.0 private let cellHeight: CGFloat = 100.0 class RightViewController: UITableViewController { private var type: DemoType? private let sections: [[SideViewCellItem]] = [ [.close, .openLeft], [.changeRootVC], [.pushVC(title: "1"), .pushVC(title: "2"), .pushVC(title: "3"), .pushVC(title: "4"), .pushVC(title: "5"), .pushVC(title: "6"), .pushVC(title: "7"), .pushVC(title: "8"), .pushVC(title: "9"), .pushVC(title: "10")] ] init(type: DemoType) { self.type = type super.init(style: .grouped) } required init?(coder: NSCoder) { super.init(coder: coder) } // For Storyboard Demo func setup(type: DemoType) { self.type = type } // MARK: - Lifecycle - override func viewDidLoad() { super.viewDidLoad() struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.viewDidLoad(), counter: \(Counter.count)") // For iOS < 11.0 use this property to avoid artefacts if necessary // automaticallyAdjustsScrollViewInsets = false tableView.register(RightViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.separatorStyle = .none tableView.contentInset = UIEdgeInsets(top: tableViewInset, left: 0.0, bottom: tableViewInset, right: 0.0) tableView.showsVerticalScrollIndicator = false tableView.backgroundColor = .clear tableView.contentInsetAdjustmentBehavior = .never tableView.contentOffset = CGPoint(x: 0.0, y: -tableViewInset) } // MARK: - Status Bar - override var prefersStatusBarHidden: Bool { switch type?.demoRow { case .statusBarHidden, .statusBarOnlyRoot: return true default: return false } } override var preferredStatusBarStyle: UIStatusBarStyle { guard let type = type else { return .default } switch type.demoRow { case .statusBarDifferentStyles: if isLightTheme() { return .lightContent } else { if #available(iOS 13.0, *) { return .darkContent } else { return .default } } case .statusBarNoBackground: if type.presentationStyle.shouldRootViewScale { return .lightContent } fallthrough default: return .default } } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } // MARK: - UITableViewDataSource - override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RightViewCell let item = sections[indexPath.section][indexPath.row] cell.textLabel!.text = item.description cell.textLabel!.font = UIFont.boldSystemFont(ofSize: { if case .pushVC = item { return 32.0 } return 16.0 }()) cell.separatorView.isHidden = (indexPath.row == sections[indexPath.section].count - 1) return cell } // MARK: - UITableViewDelegate - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let sideMenuController = self.sideMenuController else { return } let item = sections[indexPath.section][indexPath.row] func getNavigationController() -> UINavigationController { if type?.demoRow == .usageInsideNavigationController { return sideMenuController.parent as! RootNavigationController } else if type?.demoRow == .usageAsContainerForTabBarController { let tabBarController = sideMenuController.rootViewController as! RootTabBarController return tabBarController.selectedViewController as! RootNavigationController } else { return sideMenuController.rootViewController as! RootNavigationController } } switch item { case .close: sideMenuController.hideRightView(animated: true) case .openLeft: sideMenuController.showLeftView(animated: true) case .changeRootVC: let viewController = RootViewController(imageName: getBackgroundImageNameRandom()) if type?.demoRow == .usageInsideNavigationController { sideMenuController.rootViewController = viewController UIView.transition(with: sideMenuController.rootViewWrapperView!, duration: sideMenuController.rightViewAnimationDuration, options: [.transitionCrossDissolve], animations: nil) } else { let navigationController = getNavigationController() navigationController.setViewControllers([viewController], animated: false) UIView.transition(with: navigationController.view, duration: sideMenuController.rightViewAnimationDuration, options: [.transitionCrossDissolve], animations: nil) } sideMenuController.hideRightView(animated: true) case .pushVC(let title): let viewController = RootViewControllerWithTextLabel(title: title, imageName: getBackgroundImageNameRandom()) if type?.demoRow == .usageInsideNavigationController { sideMenuController.rootViewController = viewController UIView.transition(with: sideMenuController.rootViewWrapperView!, duration: sideMenuController.rightViewAnimationDuration, options: [.transitionCrossDissolve], animations: nil) } else { let navigationController = getNavigationController() navigationController.pushViewController(viewController, animated: true) } sideMenuController.hideRightView(animated: true) default: return } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let item = sections[indexPath.section][indexPath.row] if case .pushVC = item { return cellHeight } return cellHeight * 0.75 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0.0 } return cellHeight * 0.75 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return nil } return RightViewCellHeaderView() } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } // MARK: - Logging - deinit { struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.deinit(), counter: \(Counter.count)") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.viewWillAppear(\(animated)), counter: \(Counter.count)") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.viewDidAppear(\(animated)), counter: \(Counter.count)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.viewWillDisappear(\(animated)), counter: \(Counter.count)") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.viewDidDisappear(\(animated)), counter: \(Counter.count)") } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() struct Counter { static var count = 0 } Counter.count += 1 print("RightViewController.viewWillLayoutSubviews(), counter: \(Counter.count)") } }
mit
ea2ed5a36e92040050bcbbc99797bdf9
34.501873
114
0.605655
5.638905
false
false
false
false
apple/swift-syntax
Tests/SwiftParserTest/translated/IdentifiersTests.swift
1
4535
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// // This test file has been translated from swift/test/Parse/identifiers.swift import XCTest final class IdentifiersTests: XCTestCase { func testIdentifiers1() { AssertParse( """ func my_print<T>(_ t: T) {} """ ) } func testIdentifiers2() { AssertParse( #""" class 你好 { class שלום { class வணக்கம் { class Γειά { class func привет() { my_print("hello") } } } } } """# ) } func testIdentifiers3() { AssertParse( """ 你好.שלום.வணக்கம்.Γειά.привет() """ ) } func testIdentifiers4() { AssertParse( """ // Identifiers cannot start with combining chars. _ = .́duh() """ ) } func testIdentifiers5() { AssertParse( """ // Combining characters can be used within identifiers. func s̈pin̈al_tap̈() {} """ ) } func testIdentifiers6() { AssertParse( """ // Private-use characters aren't valid in Swift source. () """, diagnostics: [ // TODO: Old parser expected error on line 2: invalid character in source file, Fix-It replacements: 1 - 4 = ' ' ] ) } func testIdentifiers7() { AssertParse( """ // Placeholders are recognized as identifiers but with error. func <#some name#>() {} """, diagnostics: [ // TODO: Old parser expected error on line 2: editor placeholder in source file ] ) } func testIdentifiers8a() { AssertParse( """ // Keywords as identifiers class 1️⃣switch {} """, diagnostics: [ DiagnosticSpec(message: "keyword 'switch' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]), ], fixedSource: """ // Keywords as identifiers class `switch` {} """ ) } func testIdentifiers8b() { AssertParse( """ struct Self {} """, diagnostics: [ // TODO: Old parser expected error on line 3: keyword 'Self' cannot be used as an identifier here // TODO: Old parser expected note on line 3: if this name is unavoidable, use backticks to escape it, Fix-It replacements: 8 - 12 = '`Self`' ] ) } func testIdentifiers8c() { AssertParse( """ protocol 1️⃣enum {} """, diagnostics: [ DiagnosticSpec(message: "keyword 'enum' cannot be used as an identifier here"), ] ) } func testIdentifiers8d() { AssertParse( """ protocol test { associatedtype 1️⃣public } func 2️⃣_(_ x: Int) {} """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "keyword 'public' cannot be used as an identifier here"), DiagnosticSpec(locationMarker: "2️⃣", message: "'_' cannot be used as an identifier here"), ] ) } func testIdentifiers9() { AssertParse( """ // SIL keywords are tokenized as normal identifiers in non-SIL mode. _ = undef _ = sil _ = sil_stage _ = sil_vtable _ = sil_global _ = sil_witness_table _ = sil_default_witness_table _ = sil_coverage_map _ = sil_scope """ ) } func testIdentifiers10() { AssertParse( """ // https://github.com/apple/swift/issues/57542 // Make sure we do not parse the '_' on the newline as being part of the 'variable' identifier on the line before. """ ) } func testIdentifiers11() { AssertParse( """ @propertyWrapper struct Wrapper { var wrappedValue = 0 } """ ) } func testIdentifiers12() { AssertParse( """ func localScope() { @Wrapper var variable _ = 0 } """ ) } }
apache-2.0
8df2bf1477dfd97774b973feff177cce
21.774359
158
0.527134
4.221483
false
true
false
false
jmgc/swift
test/Concurrency/async_let_isolation.swift
1
1303
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency // REQUIRES: concurrency actor class MyActor { let immutable: Int = 17 var text: [String] = [] func synchronous() -> String { text.first ?? "nothing" } // expected-note 2 {{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} func asynchronous() async -> String { synchronous() } func testAsyncLetIsolation() async { async let x = self.synchronous() // expected-error @-1{{actor-isolated instance method 'synchronous()' is unsafe to reference in code that may execute concurrently}} async let y = await self.asynchronous() async let z = synchronous() // expected-error @-1{{actor-isolated instance method 'synchronous()' is unsafe to reference in code that may execute concurrently}} var localText = text // expected-note{{var declared here}} async let w = localText.removeLast() // expected-warning@-1{{local var 'localText' is unsafe to reference in code that may execute concurrently}} _ = await x _ = await y _ = await z _ = await w } } func outside() async { let a = MyActor() async let x = a.synchronous() // okay, await is implicit async let y = await a.synchronous() _ = await x _ = await y }
apache-2.0
248f6006f856a8cb6f3ee9ca8cdca7a7
34.216216
184
0.683807
4.25817
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCUI/Email/KYCConfirmEmailController.swift
1
4839
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import PlatformUIKit import RxSwift import ToolKit class KYCConfirmEmailController: KYCBaseViewController, BottomButtonContainerView, ProgressableView { // MARK: - ProgressableView @IBOutlet var progressView: UIProgressView! var barColor: UIColor = .green var startingValue: Float = 0.2 // MARK: BottomButtonContainerView var originalBottomButtonConstraint: CGFloat! var optionalOffset: CGFloat = 0 @IBOutlet var layoutConstraintBottomButton: NSLayoutConstraint! // MARK: IBOutlets @IBOutlet private var labelHeader: UILabel! @IBOutlet private var labelSubHeader: UILabel! @IBOutlet private var validationTextFieldEmail: ValidationTextField! @IBOutlet private var buttonDidntGetEmail: PrimaryButtonContainer! @IBOutlet private var primaryButton: PrimaryButtonContainer! // MARK: Private Properties private lazy var presenter: VerifyEmailPresenter = VerifyEmailPresenter(view: self) // MARK: Properties var email: String = "" { didSet { guard isViewLoaded else { return } validationTextFieldEmail.text = email } } // MARK: Factory override class func make(with coordinator: KYCRouter) -> KYCConfirmEmailController { let controller = makeFromStoryboard(in: .module) controller.router = coordinator controller.pageType = .confirmEmail return controller } // MARK: - UIViewController Lifecycle Methods deinit { cleanUp() } override func viewDidLoad() { super.viewDidLoad() labelHeader.text = LocalizationConstants.KYC.checkYourInbox labelSubHeader.text = LocalizationConstants.KYC.confirmEmailExplanation validationTextFieldEmail.text = email validationTextFieldEmail.isEnabled = false validationTextFieldEmail.accessibilityIdentifier = "kyc.email_field" // swiftlint:disable line_length let attributedTitle = NSMutableAttributedString(string: LocalizationConstants.KYC.didntGetTheEmail + " " + LocalizationConstants.KYC.sendAgain) attributedTitle.addForegroundColor(buttonDidntGetEmail.buttonTitleColor, to: LocalizationConstants.KYC.didntGetTheEmail) attributedTitle.addForegroundColor(#colorLiteral(red: 0.06274509804, green: 0.6784313725, blue: 0.8941176471, alpha: 1), to: LocalizationConstants.KYC.sendAgain) buttonDidntGetEmail.attributedTitle = attributedTitle buttonDidntGetEmail.primaryButtonFont = 2 buttonDidntGetEmail.activityIndicatorStyle = .medium buttonDidntGetEmail.actionBlock = { [unowned self] in self.sendVerificationEmail() } primaryButton.title = LocalizationConstants.KYC.openEmailApp primaryButton.actionBlock = { [unowned self] in self.primaryButtonTapped() } originalBottomButtonConstraint = layoutConstraintBottomButton.constant setupProgressView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setUpBottomButtonContainerView() presenter.waitForEmailConfirmation() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) presenter.cancel() } // MARK: - Actions private func sendVerificationEmail() { guard email.isEmail else { return } presenter.sendVerificationEmail(to: email) } private func primaryButtonTapped() { UIApplication.shared.openMailApplication() } } extension KYCConfirmEmailController: EmailConfirmationInterface { func updateLoadingViewVisibility(_ visibility: Visibility) { buttonDidntGetEmail.isLoading = visibility.isHidden == false } func sendEmailVerificationSuccess() { let origTitle = buttonDidntGetEmail.title let origColor = buttonDidntGetEmail.buttonTitleColor buttonDidntGetEmail.title = LocalizationConstants.KYC.emailSent buttonDidntGetEmail.buttonTitleColor = UIColor.green DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in guard let strongSelf = self else { return } strongSelf.buttonDidntGetEmail.title = origTitle strongSelf.buttonDidntGetEmail.buttonTitleColor = origColor } } func showError(message: String) { AlertViewPresenter.shared.standardError(message: message, in: self) } func hideLoadingView() { buttonDidntGetEmail.isLoading = false } func emailVerifiedSuccess() { Logger.shared.info("Email is verified.") router.handle(event: .nextPageFromPageType(pageType, nil)) } }
lgpl-3.0
fc91dc7fb11ea1218b8617e1292a8b25
33.070423
169
0.70711
5.157783
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Metadata/Sources/MetadataKit/Models/Entry/Payloads/EthereumEntryPayload.swift
1
4938
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct EthereumEntryPayload: MetadataNodeEntry, Hashable { public struct Ethereum: Codable, Hashable { public struct Account: Codable, Hashable { public enum CodingKeys: String, CodingKey { case address = "addr" case archived case correct case label } public let address: String public let archived: Bool public let correct: Bool public let label: String public init( address: String, archived: Bool, correct: Bool, label: String ) { self.address = address self.archived = archived self.correct = correct self.label = label } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) address = try container.decode(String.self, forKey: .address) archived = try container.decodeIfPresent(Bool.self, forKey: .archived) ?? false correct = try container.decodeIfPresent(Bool.self, forKey: .correct) ?? true label = try container.decode(String.self, forKey: .label) } } public struct ERC20: Codable, Hashable { public enum CodingKeys: String, CodingKey { case contract case hasSeen = "has_seen" case label case txNotes = "tx_notes" } public let contract: String public let hasSeen: Bool public let label: String public let txNotes: [String: String] public init( contract: String, hasSeen: Bool, label: String, txNotes: [String: String] ) { self.contract = contract self.hasSeen = hasSeen self.label = label self.txNotes = txNotes } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) contract = try container.decode(String.self, forKey: .contract) hasSeen = try container.decodeIfPresent(Bool.self, forKey: .hasSeen) ?? false label = try container.decode(String.self, forKey: .label) txNotes = try container.decodeIfPresent([String: String].self, forKey: .txNotes) ?? [:] } } public enum CodingKeys: String, CodingKey { case accounts case defaultAccountIndex = "default_account_idx" case erc20 case hasSeen = "has_seen" case lastTxTimestamp = "last_tx_timestamp" case transactionNotes = "tx_notes" } public let accounts: [Account] public let defaultAccountIndex: Int public let erc20: [String: ERC20]? public let hasSeen: Bool public let lastTxTimestamp: Int? public let transactionNotes: [String: String] public init( accounts: [Account], defaultAccountIndex: Int, erc20: [String: ERC20]?, hasSeen: Bool, lastTxTimestamp: Int?, transactionNotes: [String: String] ) { self.accounts = accounts self.defaultAccountIndex = defaultAccountIndex self.erc20 = erc20 self.hasSeen = hasSeen self.lastTxTimestamp = lastTxTimestamp self.transactionNotes = transactionNotes } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) accounts = try container.decode([Account].self, forKey: .accounts) defaultAccountIndex = try container.decodeIfPresent(Int.self, forKey: .defaultAccountIndex) ?? 0 erc20 = try container.decodeIfPresent([String: ERC20].self, forKey: .erc20) ?? [:] hasSeen = try container.decode(Bool.self, forKey: .hasSeen) lastTxTimestamp = try container.decodeIfPresent(Int.self, forKey: .lastTxTimestamp) transactionNotes = try container.decodeIfPresent([String: String].self, forKey: .transactionNotes) ?? [:] } } public enum CodingKeys: String, CodingKey { case ethereum } public static let type: EntryType = .ethereum public let ethereum: Ethereum? public init(ethereum: Ethereum) { self.ethereum = ethereum } } // MARK: - Internal, should only be used in testing - extension EthereumEntryPayload { init(ethereum: Ethereum?) { self.ethereum = ethereum } }
lgpl-3.0
fa0a60000009cc5f240bfb4e1b7cc306
34.014184
117
0.564715
5.068789
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftSoup/Selector.swift
4
12999
// // Selector.swift // SwiftSoup // // Created by Nabil Chatbi on 21/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation /** * CSS-like element selector, that finds elements matching a query. * * <h2>Selector syntax</h2> * <p> * A selector is a chain of simple selectors, separated by combinators. Selectors are <b>case insensitive</b> (including against * elements, attributes, and attribute values). * </p> * <p> * The universal selector (*) is implicit when no element selector is supplied (i.e. {@code *.header} and {@code .header} * is equivalent). * </p> * <table summary=""> * <tr><th align="left">Pattern</th><th align="left">Matches</th><th align="left">Example</th></tr> * <tr><td><code>*</code></td><td>any element</td><td><code>*</code></td></tr> * <tr><td><code>tag</code></td><td>elements with the given tag name</td><td><code>div</code></td></tr> * <tr><td><code>*|E</code></td><td>elements of type E in any namespace <i>ns</i></td><td><code>*|name</code> finds <code>&lt;fb:name&gt;</code> elements</td></tr> * <tr><td><code>ns|E</code></td><td>elements of type E in the namespace <i>ns</i></td><td><code>fb|name</code> finds <code>&lt;fb:name&gt;</code> elements</td></tr> * <tr><td><code>#id</code></td><td>elements with attribute ID of "id"</td><td><code>div#wrap</code>, <code>#logo</code></td></tr> * <tr><td><code>.class</code></td><td>elements with a class name of "class"</td><td><code>div.left</code>, <code>.result</code></td></tr> * <tr><td><code>[attr]</code></td><td>elements with an attribute named "attr" (with any value)</td><td><code>a[href]</code>, <code>[title]</code></td></tr> * <tr><td><code>[^attrPrefix]</code></td><td>elements with an attribute name starting with "attrPrefix". Use to find elements with HTML5 datasets</td><td><code>[^data-]</code>, <code>div[^data-]</code></td></tr> * <tr><td><code>[attr=val]</code></td><td>elements with an attribute named "attr", and value equal to "val"</td><td><code>img[width=500]</code>, <code>a[rel=nofollow]</code></td></tr> * <tr><td><code>[attr=&quot;val&quot;]</code></td><td>elements with an attribute named "attr", and value equal to "val"</td><td><code>span[hello="Cleveland"][goodbye="Columbus"]</code>, <code>a[rel=&quot;nofollow&quot;]</code></td></tr> * <tr><td><code>[attr^=valPrefix]</code></td><td>elements with an attribute named "attr", and value starting with "valPrefix"</td><td><code>a[href^=http:]</code></td></tr> * <tr><td><code>[attr$=valSuffix]</code></td><td>elements with an attribute named "attr", and value ending with "valSuffix"</td><td><code>img[src$=.png]</code></td></tr> * <tr><td><code>[attr*=valContaining]</code></td><td>elements with an attribute named "attr", and value containing "valContaining"</td><td><code>a[href*=/search/]</code></td></tr> * <tr><td><code>[attr~=<em>regex</em>]</code></td><td>elements with an attribute named "attr", and value matching the regular expression</td><td><code>img[src~=(?i)\\.(png|jpe?g)]</code></td></tr> * <tr><td></td><td>The above may be combined in any order</td><td><code>div.header[title]</code></td></tr> * <tr><td><td colspan="3"><h3>Combinators</h3></td></tr> * <tr><td><code>E F</code></td><td>an F element descended from an E element</td><td><code>div a</code>, <code>.logo h1</code></td></tr> * <tr><td><code>E {@literal >} F</code></td><td>an F direct child of E</td><td><code>ol {@literal >} li</code></td></tr> * <tr><td><code>E + F</code></td><td>an F element immediately preceded by sibling E</td><td><code>li + li</code>, <code>div.head + div</code></td></tr> * <tr><td><code>E ~ F</code></td><td>an F element preceded by sibling E</td><td><code>h1 ~ p</code></td></tr> * <tr><td><code>E, F, G</code></td><td>all matching elements E, F, or G</td><td><code>a[href], div, h3</code></td></tr> * <tr><td><td colspan="3"><h3>Pseudo selectors</h3></td></tr> * <tr><td><code>:lt(<em>n</em>)</code></td><td>elements whose sibling index is less than <em>n</em></td><td><code>td:lt(3)</code> finds the first 3 cells of each row</td></tr> * <tr><td><code>:gt(<em>n</em>)</code></td><td>elements whose sibling index is greater than <em>n</em></td><td><code>td:gt(1)</code> finds cells after skipping the first two</td></tr> * <tr><td><code>:eq(<em>n</em>)</code></td><td>elements whose sibling index is equal to <em>n</em></td><td><code>td:eq(0)</code> finds the first cell of each row</td></tr> * <tr><td><code>:has(<em>selector</em>)</code></td><td>elements that contains at least one element matching the <em>selector</em></td><td><code>div:has(p)</code> finds divs that contain p elements </td></tr> * <tr><td><code>:not(<em>selector</em>)</code></td><td>elements that do not match the <em>selector</em>. See also {@link Elements#not(String)}</td><td><code>div:not(.logo)</code> finds all divs that do not have the "logo" class.<p><code>div:not(:has(div))</code> finds divs that do not contain divs.</p></td></tr> * <tr><td><code>:contains(<em>text</em>)</code></td><td>elements that contains the specified text. The search is case insensitive. The text may appear in the found element, or any of its descendants.</td><td><code>p:contains(jsoup)</code> finds p elements containing the text "jsoup".</td></tr> * <tr><td><code>:matches(<em>regex</em>)</code></td><td>elements whose text matches the specified regular expression. The text may appear in the found element, or any of its descendants.</td><td><code>td:matches(\\d+)</code> finds table cells containing digits. <code>div:matches((?i)login)</code> finds divs containing the text, case insensitively.</td></tr> * <tr><td><code>:containsOwn(<em>text</em>)</code></td><td>elements that directly contain the specified text. The search is case insensitive. The text must appear in the found element, not any of its descendants.</td><td><code>p:containsOwn(jsoup)</code> finds p elements with own text "jsoup".</td></tr> * <tr><td><code>:matchesOwn(<em>regex</em>)</code></td><td>elements whose own text matches the specified regular expression. The text must appear in the found element, not any of its descendants.</td><td><code>td:matchesOwn(\\d+)</code> finds table cells directly containing digits. <code>div:matchesOwn((?i)login)</code> finds divs containing the text, case insensitively.</td></tr> * <tr><td></td><td>The above may be combined in any order and with other selectors</td><td><code>.light:contains(name):eq(0)</code></td></tr> * <tr><td colspan="3"><h3>Structural pseudo selectors</h3></td></tr> * <tr><td><code>:root</code></td><td>The element that is the root of the document. In HTML, this is the <code>html</code> element</td><td><code>:root</code></td></tr> * <tr><td><code>:nth-child(<em>a</em>n+<em>b</em>)</code></td><td><p>elements that have <code><em>a</em>n+<em>b</em>-1</code> siblings <b>before</b> it in the document tree, for any positive integer or zero value of <code>n</code>, and has a parent element. For values of <code>a</code> and <code>b</code> greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the <em>b</em>th element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The <code>a</code> and <code>b</code> values must be integers (positive, negative, or zero). The index of the first child of an element is 1.</p> * In addition to this, <code>:nth-child()</code> can take <code>odd</code> and <code>even</code> as arguments instead. <code>odd</code> has the same signification as <code>2n+1</code>, and <code>even</code> has the same signification as <code>2n</code>.</td><td><code>tr:nth-child(2n+1)</code> finds every odd row of a table. <code>:nth-child(10n-1)</code> the 9th, 19th, 29th, etc, element. <code>li:nth-child(5)</code> the 5h li</td></tr> * <tr><td><code>:nth-last-child(<em>a</em>n+<em>b</em>)</code></td><td>elements that have <code><em>a</em>n+<em>b</em>-1</code> siblings <b>after</b> it in the document tree. Otherwise like <code>:nth-child()</code></td><td><code>tr:nth-last-child(-n+2)</code> the last two rows of a table</td></tr> * <tr><td><code>:nth-of-type(<em>a</em>n+<em>b</em>)</code></td><td>pseudo-class notation represents an element that has <code><em>a</em>n+<em>b</em>-1</code> siblings with the same expanded element name <em>before</em> it in the document tree, for any zero or positive integer value of n, and has a parent element</td><td><code>img:nth-of-type(2n+1)</code></td></tr> * <tr><td><code>:nth-last-of-type(<em>a</em>n+<em>b</em>)</code></td><td>pseudo-class notation represents an element that has <code><em>a</em>n+<em>b</em>-1</code> siblings with the same expanded element name <em>after</em> it in the document tree, for any zero or positive integer value of n, and has a parent element</td><td><code>img:nth-last-of-type(2n+1)</code></td></tr> * <tr><td><code>:first-child</code></td><td>elements that are the first child of some other element.</td><td><code>div {@literal >} p:first-child</code></td></tr> * <tr><td><code>:last-child</code></td><td>elements that are the last child of some other element.</td><td><code>ol {@literal >} li:last-child</code></td></tr> * <tr><td><code>:first-of-type</code></td><td>elements that are the first sibling of its type in the list of children of its parent element</td><td><code>dl dt:first-of-type</code></td></tr> * <tr><td><code>:last-of-type</code></td><td>elements that are the last sibling of its type in the list of children of its parent element</td><td><code>tr {@literal >} td:last-of-type</code></td></tr> * <tr><td><code>:only-child</code></td><td>elements that have a parent element and whose parent element hasve no other element children</td><td></td></tr> * <tr><td><code>:only-of-type</code></td><td> an element that has a parent element and whose parent element has no other element children with the same expanded element name</td><td></td></tr> * <tr><td><code>:empty</code></td><td>elements that have no children at all</td><td></td></tr> * </table> * * @see Element#select(String) */ open class Selector { private let evaluator: Evaluator private let root: Element private init(_ query: String, _ root: Element)throws { let query = query.trim() try Validate.notEmpty(string: query) self.evaluator = try QueryParser.parse(query) self.root = root } private init(_ evaluator: Evaluator, _ root: Element) { self.evaluator = evaluator self.root = root } /** * Find elements matching selector. * * @param query CSS selector * @param root root element to descend into * @return matching elements, empty if none * @throws Selector.SelectorParseException (unchecked) on an invalid CSS query. */ public static func select(_ query: String, _ root: Element)throws->Elements { return try Selector(query, root).select() } /** * Find elements matching selector. * * @param evaluator CSS selector * @param root root element to descend into * @return matching elements, empty if none */ public static func select(_ evaluator: Evaluator, _ root: Element)throws->Elements { return try Selector(evaluator, root).select() } /** * Find elements matching selector. * * @param query CSS selector * @param roots root elements to descend into * @return matching elements, empty if none */ public static func select(_ query: String, _ roots: Array<Element>)throws->Elements { try Validate.notEmpty(string: query) let evaluator: Evaluator = try QueryParser.parse(query) var elements: Array<Element> = Array<Element>() var seenElements: Array<Element> = Array<Element>() // dedupe elements by identity, not equality for root: Element in roots { let found: Elements = try select(evaluator, root) for el: Element in found.array() { if (!seenElements.contains(el)) { elements.append(el) seenElements.append(el) } } } return Elements(elements) } private func select()throws->Elements { return try Collector.collect(evaluator, root) } // exclude set. package open so that Elements can implement .not() selector. static func filterOut(_ elements: Array<Element>, _ outs: Array<Element>) -> Elements { let output: Elements = Elements() for el: Element in elements { var found: Bool = false for out: Element in outs { if (el.equals(out)) { found = true break } } if (!found) { output.add(el) } } return output } }
mit
cd2b7b2171761c2449a0eb2427457de8
78.742331
795
0.650869
3.2898
false
false
false
false
krevis/MIDIApps
Applications/SysExLibrarian/PreferencesWindowController.swift
1
9484
/* Copyright (c) 2002-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Cocoa class PreferencesWindowController: GeneralWindowController { static let shared = PreferencesWindowController() init() { super.init(window: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var windowNibName: NSNib.Name? { return "Preferences" } // Allow bindings in the nib to get to the app's updater @objc var updater: SPUUpdater? { (NSApp.delegate as? AppController)?.updaterController?.updater } override func windowDidLoad() { super.windowDidLoad() // Make sure the "General" tab is showing, just in case it was changed in the nib tabView.selectTabViewItem(withIdentifier: "general") } func windowWillClose(_ notification: Notification) { if isSysExSpeedTabViewItem(tabView.selectedTabViewItem) { sysExSpeedController.willHide() } } // MARK: Actions @IBAction override func showWindow(_ sender: Any?) { _ = window // Make sure the window gets loaded before we do anything else synchronizeControls() if isSysExSpeedTabViewItem(tabView.selectedTabViewItem) { sysExSpeedController.willShow() } super.showWindow(sender) } @IBAction func changeSizeFormat(_ sender: Any?) { guard let control = sender as? NSControl, let cell = control.selectedCell() else { return } let boolValue = cell.tag == 1 UserDefaults.standard.set(boolValue, forKey: MainWindowController.abbreviateSizesInLibraryPreferenceKey) NotificationCenter.default.post(name: .displayPreferenceChanged, object: nil) } @IBAction func changeDoubleClickToSendMessages(_ sender: Any?) { guard let control = sender as? NSControl else { return } let boolValue = control.integerValue > 0 UserDefaults.standard.set(boolValue, forKey: MainWindowController.doubleClickToSendPreferenceKey) NotificationCenter.default.post(name: .doubleClickToSendPreferenceChanged, object: nil) } @IBAction func changeSysExFolder(_ sender: Any?) { let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true openPanel.canChooseFiles = false openPanel.allowsMultipleSelection = false openPanel.directoryURL = NSURL(fileURLWithPath: Library.shared.fileDirectoryPath, isDirectory: true) as URL openPanel.beginSheetModal(for: window!) { result in if result == .OK && openPanel.urls.count == 1, let url = openPanel.urls.first { Library.shared.fileDirectoryPath = url.path self.synchronizeControls() } } } @IBAction func changeReadTimeOut(_ sender: Any?) { guard let control = sender as? NSControl else { return } UserDefaults.standard.set(control.integerValue, forKey: MIDIController.sysExReadTimeOutPreferenceKey) synchronizeReadTimeOutField() NotificationCenter.default.post(name: .sysExReceivePreferenceChanged, object: nil) } @IBAction func changeIntervalBetweenSentMessages(_ sender: Any?) { guard let control = sender as? NSControl else { return } UserDefaults.standard.set(control.integerValue, forKey: MIDIController.timeBetweenSentSysExPreferenceKey) synchronizeIntervalBetweenSentMessagesField() NotificationCenter.default.post(name: .sysExSendPreferenceChanged, object: nil) } @IBAction func listenForProgramChanges(_ sender: Any?) { guard let control = sender as? NSControl else { return } let boolValue = control.integerValue > 0 UserDefaults.standard.set(boolValue, forKey: MIDIController.listenForProgramChangesPreferenceKey) NotificationCenter.default.post(name: .listenForProgramChangesPreferenceChanged, object: nil) } @IBAction func interruptOnProgramChange(_ sender: Any?) { guard let control = sender as? NSControl else { return } let boolValue = control.integerValue > 0 UserDefaults.standard.set(boolValue, forKey: MIDIController.interruptOnProgramChangePreferenceKey) // no need for a notification to be posted; relevant code looks up this value each time } @IBAction func programChangeBaseIndex(_ sender: Any?) { guard let control = sender as? NSControl, let cell = control.selectedCell() else { return } UserDefaults.standard.set(cell.tag, forKey: MIDIController.programChangeBaseIndexPreferenceKey) NotificationCenter.default.post(name: .programChangeBaseIndexPreferenceChanged, object: nil) } // MARK: Private @IBOutlet private var sizeFormatMatrix: NSMatrix! @IBOutlet private var sysExFolderPathField: NSTextField! @IBOutlet private var sysExReadTimeOutSlider: NSSlider! @IBOutlet private var sysExReadTimeOutField: NSTextField! @IBOutlet private var sysExIntervalBetweenSentMessagesSlider: NSSlider! @IBOutlet private var sysExIntervalBetweenSentMessagesField: NSTextField! @IBOutlet private var tabView: NSTabView! @IBOutlet private var doubleClickToSendMessagesButton: NSButton! @IBOutlet private var listenForProgramChangesButton: NSButton! @IBOutlet private var interruptOnProgramChangeButton: NSButton! @IBOutlet private var programChangeBaseIndexMatrix: NSMatrix! @IBOutlet private var sysExSpeedController: SysExSpeedController! } extension PreferencesWindowController: NSTabViewDelegate { func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { if isSysExSpeedTabViewItem(tabView.selectedTabViewItem) { sysExSpeedController.willHide() } if isSysExSpeedTabViewItem(tabViewItem) { sysExSpeedController.willShow() } } } extension PreferencesWindowController /* Private */ { private func isSysExSpeedTabViewItem(_ tabViewItem: NSTabViewItem?) -> Bool { guard let identifier = tabViewItem?.identifier as? String else { return false } return identifier == "speed" } private func synchronizeControls() { let defaults = UserDefaults.standard sizeFormatMatrix.selectCell(withTag: defaults.bool(forKey: MainWindowController.abbreviateSizesInLibraryPreferenceKey) ? 1 : 0) doubleClickToSendMessagesButton.integerValue = defaults.bool(forKey: MainWindowController.doubleClickToSendPreferenceKey) ? 1 : 0 sysExFolderPathField.stringValue = Library.shared.fileDirectoryPath sysExReadTimeOutSlider.integerValue = defaults.integer(forKey: MIDIController.sysExReadTimeOutPreferenceKey) listenForProgramChangesButton.integerValue = defaults.bool(forKey: MIDIController.listenForProgramChangesPreferenceKey) ? 1 : 0 interruptOnProgramChangeButton.integerValue = defaults.bool(forKey: MIDIController.interruptOnProgramChangePreferenceKey) ? 1 : 0 programChangeBaseIndexMatrix.selectCell(withTag: defaults.integer(forKey: MIDIController.programChangeBaseIndexPreferenceKey)) synchronizeReadTimeOutField() sysExIntervalBetweenSentMessagesSlider.integerValue = defaults.integer(forKey: MIDIController.timeBetweenSentSysExPreferenceKey) synchronizeIntervalBetweenSentMessagesField() } private func synchronizeReadTimeOutField() { sysExReadTimeOutField.stringValue = formatMilliseconds(UserDefaults.standard.integer(forKey: MIDIController.sysExReadTimeOutPreferenceKey)) } private func synchronizeIntervalBetweenSentMessagesField() { sysExIntervalBetweenSentMessagesField.stringValue = formatMilliseconds(UserDefaults.standard.integer(forKey: MIDIController.timeBetweenSentSysExPreferenceKey)) } private static var millisecondsFormat = NSLocalizedString("%ld milliseconds", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "format for milliseconds") private static var oneSecondString = NSLocalizedString("1 second", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "string for one second exactly") private static var oneSecondOrMoreFormat = NSLocalizedString("%#.3g seconds", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "one second or more (formatting of milliseconds)") private func formatMilliseconds(_ msec: Int) -> String { if msec > 1000 { return String.localizedStringWithFormat(Self.oneSecondOrMoreFormat, Double(msec) / 1000.0) } else if msec == 1000 { return Self.oneSecondString } else { return String.localizedStringWithFormat(Self.millisecondsFormat, msec) } } } extension Notification.Name { static let displayPreferenceChanged = Notification.Name("SSEDisplayPreferenceChangedNotification") static let doubleClickToSendPreferenceChanged = Notification.Name("SSEDoubleClickToSendPreferenceChangedNotification") static let sysExSendPreferenceChanged = Notification.Name("SSESysExSendPreferenceChangedNotification") static let sysExReceivePreferenceChanged = Notification.Name("SSESysExReceivePreferenceChangedNotification") static let listenForProgramChangesPreferenceChanged = Notification.Name("SSEListenForProgramChangesPreferenceChangedNotification") }
bsd-3-clause
fd65d21b82411e5dc6e3b3b8398201ba
44.596154
191
0.736925
4.98371
false
false
false
false
sgrinich/BeatsByKenApp
BeatsByKen/BeatsByKen/TestSessionViewController.swift
1
48388
// // MainSettingsView.swift // BeatsByKen // /*Copyright (c) 2015 Stephen Grinich 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 import CoreBluetooth import CoreData class TestSessionViewController: UIViewController, CSVControllerDelegate, UITextFieldDelegate{ var count = 10 @IBOutlet weak var participantNumberTextField: UITextField! @IBOutlet weak var sessionNumberTextField: UITextField! @IBOutlet weak var modelLabel: UILabel! @IBOutlet weak var startTimeLabel: UILabel! @IBOutlet weak var endTimeLabel: UILabel! @IBOutlet weak var beatCountLabel: UILabel! @IBOutlet weak var startTrialButton: UIButton! // @IBOutlet weak var newSessionButton: UIButton! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var durationButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var bpmLabel: UILabel! @IBOutlet weak var trialStatusLabel: UILabel! @IBOutlet weak var pre1: TrialButton! @IBOutlet weak var pre2: TrialButton! @IBOutlet weak var pre3: TrialButton! @IBOutlet weak var pre4: TrialButton! @IBOutlet weak var post1: TrialButton! @IBOutlet weak var post2: TrialButton! @IBOutlet weak var post3: TrialButton! @IBOutlet weak var post4: TrialButton! @IBOutlet weak var exer1: TrialButton! @IBOutlet weak var exer2: TrialButton! @IBOutlet weak var exer3: TrialButton! @IBOutlet weak var exer4: TrialButton! @IBOutlet weak var countdownLabel: UILabel! var started: Bool? var firstTouch: Bool? var isTrialRunning: Bool? var shouldBPMAlert: Bool? var trialTime: Int? var seconds: Int = 0; var startTime = NSTimeInterval() var globalTimer = NSTimer() var trialTimer = NSTimer() var countdownTimer = NSTimer() var beatDisplayTimer: NSTimer? = nil var bpmDisplayTimer: NSTimer? = nil var trialRunning : String = "none"; var session = Session() let noTrialColor = UIColor(red: 204/255, green: 204/255, blue: 204/255, alpha: 1) // var testTrialArray = [Session]() var duration = NSNumber() //The place where our data comes from var BTPeripherals = BTConnectorTwo.sharedBTInstance.getAvailablePeripherals() let dropboxSyncService = (UIApplication.sharedApplication().delegate as! AppDelegate).dropboxSyncService var fileName = String() var timeStamp = String() var settings = [NSManagedObject]() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext func controller(controller: CSVController, didExport: Bool) { // println("controller function in testSessionViewController called") session = Session(); resetToNewSession(); // println("just called resetTonewSession in controller function") trialStatusLabel.text = "No Trial Running" startTimeLabel.text = "N/A" endTimeLabel.text = "N/A" } override func viewDidLoad() { super.viewDidLoad() self.participantNumberTextField.delegate = self; self.sessionNumberTextField.delegate = self; self.title = "Trial"; started = false; firstTouch = false; isTrialRunning = false; // newSessionButton.addTarget(self, action: "newSessionAction:", forControlEvents: UIControlEvents.TouchUpInside); // startTrialButton.setTitle("Start Trial", forState: UIControlState.Normal); startTrialButton.layer.cornerRadius = 15; // newSessionButton.layer.cornerRadius = 15; cancelButton.layer.cornerRadius = 15; pre1.layer.cornerRadius = pre1.layer.frame.height / 2; pre2.layer.cornerRadius = pre2.layer.frame.height / 2; pre3.layer.cornerRadius = pre3.layer.frame.height / 2; pre4.layer.cornerRadius = pre4.layer.frame.height / 2; post1.layer.cornerRadius = post1.layer.frame.height / 2; post2.layer.cornerRadius = post2.layer.frame.height / 2; post3.layer.cornerRadius = post3.layer.frame.height / 2; post4.layer.cornerRadius = post4.layer.frame.height / 2; exer1.layer.cornerRadius = exer1.layer.frame.height / 2; exer2.layer.cornerRadius = exer2.layer.frame.height / 2; exer3.layer.cornerRadius = exer3.layer.frame.height / 2; exer4.layer.cornerRadius = exer4.layer.frame.height / 2; doneButton.layer.cornerRadius = 15; durationButton.layer.cornerRadius = 15; self.beatDisplayTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:"updateBPMLabel", userInfo: nil, repeats: true); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); self.navigationController?.navigationBarHidden = true setTrialTimes(); self.modelLabel.text = BTConnectorTwo.sharedBTInstance.getCurrentPeripheral(); } func updateBeatLabel() { if(started == true){ startTrialButton.setTitle(String(BTConnectorTwo.sharedBTInstance.getBeatCount()), forState: UIControlState.Normal); } } func newSessionAction(sender:UIButton!) { if(sessionIsDone(session) == false){ displaySessionNotFinished(); } else{ // testTrialArray.append(session); session = Session(); resetToNewSession(); //session.resetAllTrials(); } } @IBAction func startstopButtonTouched(sender: UIButton) { if(participantNumberTextField.text == "" || sessionNumberTextField.text == ""){ if(participantNumberTextField.text == ""){ displayNeedParticipantNumber(); } if(sessionNumberTextField.text == ""){ displayNeedSessionNumber(); } } else if(BTConnectorTwo.sharedBTInstance.getCurrentPeripheral() == "None"){ displayHRMNotConnected(); self.modelLabel.text = BTConnectorTwo.sharedBTInstance.getCurrentPeripheral(); } else{ // we use firstTouch because we want a running counter starting at the first touch of the start button but don't want to mess with that ever again if(firstTouch == false){ //if no trial has been selected if(trialRunning == "none"){ displayNeedTrial(); } else{ BTConnectorTwo.sharedBTInstance.resetBeatCount(); trialStatusLabel.text = trialRunning + " is running."; endTimeLabel.text = "N/A"; setTimeFromSelected(); countdownLabel.text = toString(trialTime!); self.trialTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "trialTimerCount", userInfo: nil, repeats: true); self.globalTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true); self.startTime = NSDate.timeIntervalSinceReferenceDate(); count = trialTime! - 1 self.countdownTimer.invalidate() self.countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateCowntdown"), userInfo: nil, repeats: true) firstTouch = true; } } if(started == false){ self.trialTimer.invalidate(); // if no trial has been selected if(trialRunning == "none"){ displayNeedTrial(); } // if a trial has been selected else{ BTConnectorTwo.sharedBTInstance.resetBeatCount(); trialStatusLabel.text = trialRunning + " is running."; endTimeLabel.text = "N/A"; setTimeFromSelected(); countdownLabel.text = toString(trialTime!); self.trialTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "trialTimerCount", userInfo: nil, repeats: true); self.beatDisplayTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector:"updateBeatLabel", userInfo: nil, repeats: true) count = trialTime! - 1 println("Count: " ) println(count) self.countdownTimer.invalidate() self.countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateCowntdown"), userInfo: nil, repeats: true) startTimeLabel.text = stringFromTimeInterval((NSDate.timeIntervalSinceReferenceDate() - startTime)) as String; started = true; } } } } func updateCowntdown() { if(count > 0) { countdownLabel.text = String(count) count = count - 1 } else{ countdownLabel.text = "0" } } func updateTime() { timerLabel.text = stringFromTimeInterval((NSDate.timeIntervalSinceReferenceDate() - startTime)) as String; } func updateBPMLabel(){ if(BTConnectorTwo.sharedBTInstance.getBPM() == 0){ bpmLabel.text = "0"; if(started == true && shouldBPMAlert == true){ bpmZeroAlert() shouldBPMAlert = false } } else{ bpmLabel.text = String(BTConnectorTwo.sharedBTInstance.getBPM()); } if(BTConnectorTwo.sharedBTInstance.getCurrentPeripheral() == "None"){ // displayHRMNotConnected(); self.modelLabel.text = "NO HR MONITOR"; } } func trialTimerCount(){ seconds++; if(seconds == trialTime){ endTimeLabel.text = stringFromTimeInterval((NSDate.timeIntervalSinceReferenceDate() - startTime)) as String; //create object here var trial = Trial(); trial.startTime = startTimeLabel.text trial.endTime = endTimeLabel.text; trial.type = trialRunning; trial.beatCount = startTrialButton.titleLabel!.text; trial.session = sessionNumberTextField.text; trial.participantID = participantNumberTextField.text; setTrialForSession(trial, session: session); startTrialButton.setTitle("Start", forState: UIControlState.Normal); started = false; trialStatusLabel.text = trialRunning + " is finished."; setFinishedTrialGray(); setTrialAlreadyDone(); BTConnectorTwo.sharedBTInstance.resetBeatCount(); seconds = 0; trialTimer.invalidate(); trialRunning = "none"; } } func stringFromTimeInterval(interval:NSTimeInterval) -> NSString { var ti = NSInteger(interval) var ms = Int((interval % 1) * 100) var seconds = ti % 60 var minutes = (ti / 60) % 60 return NSString(format: "%0.2d:%0.2d.%0.2d",minutes,seconds,ms) } @IBAction func pre1(sender: TrialButton) { if(started == false){ if(pre1.trialAlreadyDone == true){ displayTrialAlreadyDone("Pre-1"); } else{ trialRunning = "Pre-1"; setNonGreenColors(trialRunning); pre1.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func pre2(sender: TrialButton) { if(started == false){ if(pre2.trialAlreadyDone == true){ displayTrialAlreadyDone("Pre-2"); } else{ trialRunning = "Pre-2"; setNonGreenColors(trialRunning); pre2.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func pre3(sender: TrialButton) { if(started == false){ if(pre3.trialAlreadyDone == true){ displayTrialAlreadyDone("Pre-3"); } else{ trialRunning = "Pre-3"; setNonGreenColors(trialRunning); pre3.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func pre4(sender: TrialButton) { if(started == false){ if(pre4.trialAlreadyDone == true){ displayTrialAlreadyDone("Pre-4"); } else{ trialRunning = "Pre-4"; setNonGreenColors(trialRunning); pre4.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func post1(sender: TrialButton) { if(started == false){ if(post1.trialAlreadyDone == true){ displayTrialAlreadyDone("Post-1"); } else{ trialRunning = "Post-1"; setNonGreenColors(trialRunning); post1.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func post2(sender: TrialButton) { if(started == false){ if(post2.trialAlreadyDone == true){ displayTrialAlreadyDone("Post-2"); } else{ trialRunning = "Post-2"; setNonGreenColors(trialRunning); post2.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func post3(sender: TrialButton) { if(started == false){ if(post3.trialAlreadyDone == true){ displayTrialAlreadyDone("Post-3"); } else{ trialRunning = "Post-3"; setNonGreenColors(trialRunning); post3.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func post4(sender: TrialButton) { if(started == false){ if(post4.trialAlreadyDone == true){ displayTrialAlreadyDone("Post-4"); } else{ trialRunning = "Post-4"; setNonGreenColors(trialRunning); post4.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func exer1(sender: TrialButton) { if(started == false){ if(exer1.trialAlreadyDone == true){ displayTrialAlreadyDone("Exer-1"); } else{ trialRunning = "Exer-1"; setNonGreenColors(trialRunning); exer1.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func exer2(sender: TrialButton) { if(started == false){ if(exer2.trialAlreadyDone == true){ displayTrialAlreadyDone("Exer-2"); } else{ trialRunning = "Exer-2"; setNonGreenColors(trialRunning); exer2.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func exer3(sender: TrialButton) { if(started == false){ if(exer3.trialAlreadyDone == true){ displayTrialAlreadyDone("Exer-3"); } else{ trialRunning = "Exer-3"; setNonGreenColors(trialRunning); exer3.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func exer4(sender: TrialButton) { if(started == false){ if(exer4.trialAlreadyDone == true){ displayTrialAlreadyDone("Exer-4"); } else{ trialRunning = "Exer-4"; setNonGreenColors(trialRunning); exer4.backgroundColor = UIColor.greenColor(); shouldBPMAlert = true; } } else{ displayTrialAlreadyRunning(); } } @IBAction func cancelButton(sender: UIButton) { let cancelAlertController = UIAlertController(title: "Cancel?", message: "Are you sure you would like to cancel this trial?", preferredStyle: UIAlertControllerStyle.Alert) cancelAlertController.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in if(self.started == true){ self.trialTimer.invalidate(); self.trialStatusLabel.text = self.trialRunning + " canceled."; self.startTimeLabel.text = "Canceled"; self.endTimeLabel.text = "Canceled"; self.startTrialButton.setTitle("Start", forState: UIControlState.Normal); self.started = false; self.seconds = 0; self.countdownLabel.text = "0"; self.countdownTimer.invalidate(); } else{ self.displayNoNeedToCancel(); } })) cancelAlertController.addAction(UIAlertAction(title: "No", style: .Default, handler: { (action: UIAlertAction!) in })) self.presentViewController(cancelAlertController, animated: true, completion: nil) } @IBAction func doneButton(sender: UIButton) { print("done button pressed"); if(sessionIsDone(session) == false){ displaySessionNotFinished(); } else{ if(dropboxSyncService.isLinked() == false){ displayDropboxProblem(); } else{ var testTrialArray = [Session]() testTrialArray.append(session); // session = Session(); // resetToNewSession(); let csvViewController = self.storyboard!.instantiateViewControllerWithIdentifier("CSVController") as! CSVController; csvViewController.trialArray = testTrialArray; csvViewController.delegate = self; // let navController = UINavigationController(rootViewController: csvViewController) // Creating a navigation controller with resultController at the root of the navigation stack. // self.presentViewController(navController, animated: true, completion: nil) // // let date = NSDate() // let calendar = NSCalendar.currentCalendar() // let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date) // let dateFormatter = NSDateFormatter() // dateFormatter.dateFormat = "dd-MM-yy_hh:mm:ss" // var timeStamp = dateFormatter.stringFromDate(date); // // // fileName = testTrialArray[0].pre1Trial.participantID! + "." + testTrialArray[0].pre1Trial.session! + "_" + String(timeStamp) + ".csv"; // // self.navigationController!.pushViewController(csvViewController, animated: true) self.presentViewController(csvViewController, animated: true, completion: nil) } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "pushCSVController"{ let vc = segue.destinationViewController as! CSVController print("is this even working"); } } func displayDropboxProblem(){ let alertController = UIAlertController(title: "Wait", message: "Please connect to your dropbox account before going forward"+fileName, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func bpmZeroAlert(){ let alertController = UIAlertController(title: "Wait", message: "BPM is detected zero. Check your heart rate monitor. You may want to redo this trial.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayNoNeedToCancel(){ let alertController = UIAlertController(title: "Wait", message: "No trial is running. There is nothing to cancel.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayNeedTrial(){ let alertController = UIAlertController(title: "Wait", message: "You need to select a trial to run first. Select from Pre, Post, or Exer. ", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayNeedParticipantNumber(){ let alertController = UIAlertController(title: "Wait", message: "Please enter a Participant Number before getting started", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayNeedSessionNumber(){ let alertController = UIAlertController(title: "Wait", message: "Please enter a Session Number before getting started", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displaySessionNotFinished(){ let alertController = UIAlertController(title: "Wait!", message: "Your session is not yet finished. Please complete all trials before moving on.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayHRMNotConnected(){ let alertController = UIAlertController(title: "Wait!", message: "You must connect to a Heart Rate Monitoring device before testing. Please connect in Settings.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayTrialAlreadyRunning(){ let alertController = UIAlertController(title: "Wait!", message: "There is already a trail in progress. Please wait for it to complete before starting another.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func displayTrialAlreadyDone(trialSelected: String){ let alertController = UIAlertController(title: "Wait!", message: "You've already ran this trial. Would you like to redo it?", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Redo", style: .Default, handler: { (action: UIAlertAction!) in self.setRedoTrialColor(trialSelected) self.setRedoTrial() })) alertController.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in println("Handle Cancel Logic here") })) self.presentViewController(alertController, animated: true, completion: nil) } func setTrialTimes() { let settingsFields = ["Pre-1", "Pre-2", "Pre-3", "Pre-4", "Post-1", "Post-2", "Post-3", "Post-4", "Exer-1", "Exer-2", "Exer-3", "Exer-4"] var index = Int() // If no trial settings have been saved, create default settings with duration of 30 seconds for index = 0; index<settingsFields.count; index++ { if (!SessionTable.checkInManagedObjectContext(managedObjectContext!, participantID: 5000, sessionID: 5000, tableViewRow: index)) { duration = 20; if(settingsFields[index] == "Pre-1"){ duration = 39; } if(settingsFields[index] == "Pre-2"){ duration = 32; } if(settingsFields[index] == "Pre-3"){ duration = 45; } if(settingsFields[index] == "Pre-4"){ duration = 25; } if(settingsFields[index] == "Post-1"){ duration = 32; } if(settingsFields[index] == "Post-2"){ duration = 39; } if(settingsFields[index] == "Post-3"){ duration = 25; } if(settingsFields[index] == "Post-4"){ duration = 45; } if(settingsFields[index] == "Exer-1"){ duration = 25; } if(settingsFields[index] == "Exer-2"){ duration = 45; } if(settingsFields[index] == "Exer-3"){ duration = 32; } if(settingsFields[index] == "Exer-4"){ duration = 39; } let newSettings = SessionTable.createTrialSettingInManagedObjectContext(managedObjectContext!, heartbeatCount: 0, trialDuration: duration, startTime: "", endTime: "", trialType: settingsFields[index], participantID: 5000, sessionID: 5000, tableViewRow: index) } } loadTrialSettings() var str = "" if let v = settings[0].valueForKey("trialDuration") as? Int { str = "\(v)" } pre1.trialTime = str.toInt(); if let v = settings[1].valueForKey("trialDuration") as? Int { str = "\(v)" } pre2.trialTime = str.toInt(); if let v = settings[2].valueForKey("trialDuration") as? Int { str = "\(v)" } pre3.trialTime = str.toInt(); if let v = settings[3].valueForKey("trialDuration") as? Int { str = "\(v)" } pre4.trialTime = str.toInt(); if let v = settings[4].valueForKey("trialDuration") as? Int { str = "\(v)" } post1.trialTime = str.toInt(); if let v = settings[5].valueForKey("trialDuration") as? Int { str = "\(v)" } post2.trialTime = str.toInt(); if let v = settings[6].valueForKey("trialDuration") as? Int { str = "\(v)" } post3.trialTime = str.toInt(); if let v = settings[7].valueForKey("trialDuration") as? Int { str = "\(v)" } post4.trialTime = str.toInt(); if let v = settings[8].valueForKey("trialDuration") as? Int { str = "\(v)" } exer1.trialTime = str.toInt(); if let v = settings[9].valueForKey("trialDuration") as? Int { str = "\(v)" } exer2.trialTime = str.toInt(); if let v = settings[10].valueForKey("trialDuration") as? Int { str = "\(v)" } exer3.trialTime = str.toInt(); if let v = settings[11].valueForKey("trialDuration") as? Int { str = "\(v)" } exer4.trialTime = str.toInt(); } func loadTrialSettings() { if let temp = SessionTable.getCurrentSettings(managedObjectContext!, participantID: 5000, sessionID: 5000) { settings = temp print("got some sort of settings"); } else { println("no settings...") } } func setTimeFromSelected(){ if(trialRunning == "Pre-1"){ trialTime = pre1.trialTime; } if(trialRunning == "Pre-2"){ trialTime = pre2.trialTime; } if(trialRunning == "Pre-3"){ trialTime = pre3.trialTime; } if(trialRunning == "Pre-4"){ trialTime = pre4.trialTime; } if(trialRunning == "Post-1"){ trialTime = post1.trialTime; } if(trialRunning == "Post-2"){ trialTime = post2.trialTime; } if(trialRunning == "Post-3"){ trialTime = post3.trialTime; } if(trialRunning == "Post-4"){ trialTime = post4.trialTime; } if(trialRunning == "Exer-1"){ trialTime = exer1.trialTime; } if(trialRunning == "Exer-2"){ trialTime = exer2.trialTime; } if(trialRunning == "Exer-3"){ trialTime = exer3.trialTime; } if(trialRunning == "Exer-4"){ trialTime = exer4.trialTime; } } func setFinishedTrialGray(){ if(trialRunning == "Pre-1"){ pre1.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Pre-2"){ pre2.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Pre-3"){ pre3.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Pre-4"){ pre4.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Post-1"){ post1.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Post-2"){ post2.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Post-3"){ post3.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Post-4"){ post4.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Exer-1"){ exer1.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Exer-2"){ exer2.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Exer-3"){ exer3.backgroundColor = UIColor.darkGrayColor(); } if(trialRunning == "Exer-4"){ exer4.backgroundColor = UIColor.darkGrayColor(); } } func setTrialAlreadyDone(){ if(trialRunning == "Pre-1"){ pre1.trialAlreadyDone = true; } if(trialRunning == "Pre-2"){ pre2.trialAlreadyDone = true; } if(trialRunning == "Pre-3"){ pre3.trialAlreadyDone = true; } if(trialRunning == "Pre-4"){ pre4.trialAlreadyDone = true; } if(trialRunning == "Post-1"){ post1.trialAlreadyDone = true; } if(trialRunning == "Post-2"){ post2.trialAlreadyDone = true; } if(trialRunning == "Post-3"){ post3.trialAlreadyDone = true; } if(trialRunning == "Post-4"){ post4.trialAlreadyDone = true; } if(trialRunning == "Exer-1"){ exer1.trialAlreadyDone = true; } if(trialRunning == "Exer-2"){ exer2.trialAlreadyDone = true; } if(trialRunning == "Exer-3"){ exer3.trialAlreadyDone = true; } if(trialRunning == "Exer-4"){ exer4.trialAlreadyDone = true; } } func setRedoTrial(){ shouldBPMAlert = true; if(trialRunning == "Pre-1"){ pre1.redoTrial = true; trialRunning = "Pre-1"; setNonGreenColors(trialRunning); pre1.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Pre-2"){ pre2.redoTrial = true; trialRunning = "Pre-2"; setNonGreenColors(trialRunning); pre2.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Pre-3"){ pre3.redoTrial = true; trialRunning = "Pre-3"; setNonGreenColors(trialRunning); pre3.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Pre-4"){ pre4.redoTrial = true; trialRunning = "Pre-4"; setNonGreenColors(trialRunning); pre4.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Post-1"){ post1.redoTrial = true; trialRunning = "Post-1"; setNonGreenColors(trialRunning); post1.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Post-2"){ post2.redoTrial = true; trialRunning = "Post-2"; setNonGreenColors(trialRunning); post2.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Post-3"){ post3.redoTrial = true; trialRunning = "Post-3"; setNonGreenColors(trialRunning); post3.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Post-4"){ post4.redoTrial = true; trialRunning = "Post-4"; setNonGreenColors(trialRunning); post4.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Exer-1"){ exer1.redoTrial = true; trialRunning = "Exer-1"; setNonGreenColors(trialRunning); exer1.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Exer-2"){ exer2.redoTrial = true; trialRunning = "Exer-2"; setNonGreenColors(trialRunning); exer2.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Exer-3"){ exer3.redoTrial = true; trialRunning = "Exer-3"; setNonGreenColors(trialRunning); exer3.backgroundColor = UIColor.greenColor(); } if(trialRunning == "Exer-4"){ exer4.redoTrial = true; trialRunning = "Exer-4"; setNonGreenColors(trialRunning); exer4.backgroundColor = UIColor.greenColor(); } } func setRedoTrialColor(trialSelected: String){ if(trialSelected == "Pre-1"){ setNonGreenColors(trialRunning); pre1.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Pre-2"){ setNonGreenColors(trialRunning); pre2.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Pre-3"){ setNonGreenColors(trialRunning); pre3.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Pre-4"){ setNonGreenColors(trialRunning); pre4.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Post-1"){ setNonGreenColors(trialRunning); post1.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Post-2"){ setNonGreenColors(trialRunning); post2.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Post-3"){ setNonGreenColors(trialRunning); post3.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Post-4"){ setNonGreenColors(trialRunning); post4.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Exer-1"){ setNonGreenColors(trialRunning); exer1.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Exer-2"){ setNonGreenColors(trialRunning); exer2.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Exer-3"){ setNonGreenColors(trialRunning); exer3.backgroundColor = UIColor.greenColor(); } if(trialSelected == "Exer-4"){ setNonGreenColors(trialRunning); exer4.backgroundColor = UIColor.greenColor(); } trialRunning = trialSelected; } func setNonGreenColors(trialRunning: String){ if(pre1.trialAlreadyDone == true){ pre1.backgroundColor = UIColor.darkGrayColor(); } else{ pre1.backgroundColor = noTrialColor; } if(pre2.trialAlreadyDone == true){ pre2.backgroundColor = UIColor.darkGrayColor(); } else{ pre2.backgroundColor = noTrialColor; } if(pre3.trialAlreadyDone == true){ pre3.backgroundColor = UIColor.darkGrayColor(); } else{ pre3.backgroundColor = noTrialColor; } if(pre4.trialAlreadyDone == true){ pre4.backgroundColor = UIColor.darkGrayColor(); } else{ pre4.backgroundColor = noTrialColor; } if(post1.trialAlreadyDone == true){ post1.backgroundColor = UIColor.darkGrayColor(); } else{ post1.backgroundColor = noTrialColor; } if(post2.trialAlreadyDone == true){ post2.backgroundColor = UIColor.darkGrayColor(); } else{ post2.backgroundColor = noTrialColor; } if(post3.trialAlreadyDone == true){ post3.backgroundColor = UIColor.darkGrayColor(); } else{ post3.backgroundColor = noTrialColor; } if(post4.trialAlreadyDone == true){ post4.backgroundColor = UIColor.darkGrayColor(); } else{ post4.backgroundColor = noTrialColor; } if(exer1.trialAlreadyDone == true){ exer1.backgroundColor = UIColor.darkGrayColor(); } else{ exer1.backgroundColor = noTrialColor; } if(exer2.trialAlreadyDone == true){ exer2.backgroundColor = UIColor.darkGrayColor(); } else{ exer2.backgroundColor = noTrialColor; } if(exer3.trialAlreadyDone == true){ exer3.backgroundColor = UIColor.darkGrayColor(); } else{ exer3.backgroundColor = noTrialColor; } if(exer4.trialAlreadyDone == true){ exer4.backgroundColor = UIColor.darkGrayColor(); } else{ exer4.backgroundColor = noTrialColor; } } func setTrialForSession(trial: Trial, session: Session){ if(trial.type == "Pre-1"){ session.pre1Trial = trial; } if(trial.type == "Pre-2"){ session.pre2Trial = trial; } if(trial.type == "Pre-3"){ session.pre3Trial = trial; } if(trial.type == "Pre-4"){ session.pre4Trial = trial; } if(trial.type == "Post-1"){ session.post1Trial = trial; } if(trial.type == "Post-2"){ session.post2Trial = trial; } if(trial.type == "Post-3"){ session.post3Trial = trial; } if(trial.type == "Post-4"){ session.post4Trial = trial; } if(trial.type == "Exer-1"){ session.exer1Trial = trial; } if(trial.type == "Exer-2"){ session.exer2Trial = trial; } if(trial.type == "Exer-3"){ session.exer3Trial = trial; } if(trial.type == "Exer-4"){ session.exer4Trial = trial; } } func sessionIsDone(session: Session) -> Bool{ if(session.pre1Trial.endTime == nil){ return false; } if(session.pre2Trial.endTime == nil){ return false; } if(session.pre3Trial.endTime == nil){ return false; } if(session.pre4Trial.endTime == nil){ return false; } if(session.post1Trial.endTime == nil){ return false; } if(session.post2Trial.endTime == nil){ return false; } if(session.post3Trial.endTime == nil){ return false; } if(session.post4Trial.endTime == nil){ return false; } if(session.exer1Trial.endTime == nil){ return false; } if(session.exer2Trial.endTime == nil){ return false; } if(session.exer3Trial.endTime == nil){ return false; } if(session.exer4Trial.endTime == nil){ return false; } return true; } func resetToNewSession(){ println("resetting to a new session") // var testTrialArray = [Session]() // this makes it so we never have more than one instance of each pre, post, exer. Was confused about this earlier. If we want multiple session in the csv // at the end, erase this line self.globalTimer.invalidate(); timerLabel.text = "00:00.00"; sessionNumberTextField.text = ""; firstTouch = false; trialRunning = "none"; firstTouch = false; pre1.backgroundColor = noTrialColor; pre2.backgroundColor = noTrialColor; pre3.backgroundColor = noTrialColor; pre4.backgroundColor = noTrialColor; post1.backgroundColor = noTrialColor; post2.backgroundColor = noTrialColor; post3.backgroundColor = noTrialColor; post4.backgroundColor = noTrialColor; exer1.backgroundColor = noTrialColor; exer2.backgroundColor = noTrialColor; exer3.backgroundColor = noTrialColor; exer4.backgroundColor = noTrialColor; pre1.trialAlreadyDone = false; pre2.trialAlreadyDone = false; pre3.trialAlreadyDone = false; pre4.trialAlreadyDone = false; post1.trialAlreadyDone = false; post2.trialAlreadyDone = false; post3.trialAlreadyDone = false; post4.trialAlreadyDone = false; exer1.trialAlreadyDone = false; exer2.trialAlreadyDone = false; exer3.trialAlreadyDone = false; exer4.trialAlreadyDone = false; pre1.redoTrial = false; pre2.redoTrial = false; pre3.redoTrial = false; pre4.redoTrial = false; post1.redoTrial = false; post2.redoTrial = false; post3.redoTrial = false; post4.redoTrial = false; exer1.redoTrial = false; exer2.redoTrial = false; exer3.redoTrial = false; exer4.redoTrial = false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4bb2b87ee78431a3fd93a1f5d9603e35
30.77216
275
0.540444
4.957279
false
false
false
false
lorentey/swift
test/attr/attr_ibaction.swift
24
6332
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop @IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}} var iboutlet_global: Int var iboutlet_accessor: Int { @IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{3-13=}} get { return 42 } } @IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}} class IBOutletClassTy {} @IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}} struct IBStructTy {} @IBAction // expected-error {{only instance methods can be declared @IBAction}} {{1-11=}} func IBFunction() -> () {} class IBActionWrapperTy { @IBAction func click(_: AnyObject) -> () {} // no-warning func outer(_: AnyObject) -> () { @IBAction // expected-error {{only instance methods can be declared @IBAction}} {{5-15=}} func inner(_: AnyObject) -> () {} } @IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{3-13=}} var value : Void = () @IBAction func process(x: AnyObject) -> Int {} // expected-error {{methods declared @IBAction must not return a value}} // @IBAction does /not/ semantically imply @objc. @IBAction // expected-note {{attribute already specified here}} @IBAction // expected-error {{duplicate attribute}} func doMagic(_: AnyObject) -> () {} @IBAction @objc func moreMagic(_: AnyObject) -> () {} // no-warning @objc @IBAction func evenMoreMagic(_: AnyObject) -> () {} // no-warning } struct S { } enum E { } protocol P1 { } protocol P2 { } protocol CP1 : class { } protocol CP2 : class { } @objc protocol OP1 { } @objc protocol OP2 { } // Teach the compiler that String is @objc-friendly without importing // Foundation. extension String: _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> AnyObject { fatalError() } public static func _forceBridgeFromObjectiveC(_ x: AnyObject, result: inout String?) { fatalError() } public static func _conditionallyBridgeFromObjectiveC(_ x: AnyObject, result: inout String?) -> Bool { fatalError() } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject? ) -> String { fatalError() } } // Check which argument types @IBAction can take. @objc class X { // Class type @IBAction func action1(_: X) {} @IBAction func action2(_: X?) {} @IBAction func action3(_: X!) {} // AnyObject @IBAction func action4(_: AnyObject) {} @IBAction func action5(_: AnyObject?) {} @IBAction func action6(_: AnyObject!) {} // Any @IBAction func action4a(_: Any) {} @IBAction func action5a(_: Any?) {} @IBAction func action6a(_: Any!) {} // Protocol types @IBAction func action7(_: P1) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} expected-note{{protocol-constrained type containing protocol 'P1' cannot be represented in Objective-C}} @IBAction func action8(_: CP1) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} expected-note{{protocol-constrained type containing protocol 'CP1' cannot be represented in Objective-C}} @IBAction func action9(_: OP1) {} @IBAction func action10(_: P1?) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action11(_: CP1?) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action12(_: OP1?) {} @IBAction func action13(_: P1!) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action14(_: CP1!) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action15(_: OP1!) {} // Class metatype @IBAction func action15b(_: X.Type) {} @IBAction func action16(_: X.Type?) {} @IBAction func action17(_: X.Type!) {} // AnyClass @IBAction func action18(_: AnyClass) {} @IBAction func action19(_: AnyClass?) {} @IBAction func action20(_: AnyClass!) {} // Protocol types @IBAction func action21(_: P1.Type) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action22(_: CP1.Type) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action23(_: OP1.Type) {} @IBAction func action24(_: P1.Type?) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action25(_: CP1.Type?) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action26(_: OP1.Type?) {} @IBAction func action27(_: P1.Type!) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action28(_: CP1.Type!) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action29(_: OP1.Type!) {} // Structs representable in Objective-C @IBAction func action32(_: Int) {} @IBAction func action33(_: Int?) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} @IBAction func action34(_: String) {} @IBAction func action35(_: String?) {} // Other bad cases @IBAction func action30(_: S) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}} @IBAction func action31(_: E) {} // expected-error{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} expected-note{{non-'@objc' enums cannot be represented in Objective-C}} init() { } }
apache-2.0
57d4ce9c879915d65e361e6c70f52b0a
48.46875
267
0.703885
4.163051
false
false
false
false
GMSLabs/Hyber-SDK-iOS
Example/Hyber/DeviceTableViewController.swift
1
5528
// // DeviceTableViewController.swift // Hyber // // Created by Taras on 12/12/16. // Copyright © 2016 Incuube. All rights reserved. // import UIKit import Hyber import RealmSwift class DeviceTableViewController: UITableViewController { var deviceList: Results<Device>! @IBAction func logoutAction(_ sender: Any) { Hyber.LogOut() } @IBOutlet var deviceListsTableView: UITableView! func readAndUpdateUI() { let realm = try! Realm() deviceList = realm.objects(Device.self) self.deviceListsTableView.setEditing(false, animated: true) self.deviceListsTableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() firtLoadView() deviceListsTableView.es_addPullToRefresh { [weak self] in self?.loadDeviceList() } } func firtLoadView() { if UserDefaults.standard.object(forKey: "firtsLoadDevice") == nil { loadDeviceList() UserDefaults.standard.set("loaded", forKey: "firtsLoadDevice") UserDefaults.standard.synchronize() } else { readAndUpdateUI() } } func loadDeviceList() { Hyber.getDeviceList(completionHandler: { (success) -> Void in if success { self.readAndUpdateUI() self.deviceListsTableView.es_stopPullToRefresh(completion: true) } else { self.deviceListsTableView.es_stopPullToRefresh(completion: false) self.getErrorAlert() } }) } override func viewDidAppear(_ animated: Bool) { super.viewWillAppear(true) } //MARK: - TABLE VIEW Controller override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let lists = deviceList { return lists.count } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCell", for: indexPath) as? DeviceTableViewCell if (cell != nil) { let list = self.deviceList[indexPath.row] cell?.DeviceName.text = list.value(forKey: "deviceName") as! String? cell?.deviceId.text = list.value(forKey: "deviceId") as! String? let ios = "ios" let type = list.value(forKey: "osType") as! String? if type == ios { cell?.osTypeImage.image = UIImage(named: "iosIcon") } else { cell?.osTypeImage.image = UIImage(named: "androidIcon") } cell?.osVersion.text = list.value(forKey: "osVersion") as! String? let phone = "phone" let typeDevice = list.value(forKey: "deviceType") as! String? if typeDevice == phone { cell?.deviceTypeImage.image = UIImage(named: "iPhone") } else { cell?.deviceTypeImage.image = UIImage(named: "tablet") } cell?.updateDevice.text = list.value(forKey:"updatedAt") as! String? DispatchQueue.main.async { let active = list.value(forKey: "isActive") as! Bool? if active == true { cell?.currentDevice.isHidden = false } else { cell?.currentDevice.isHidden = true } } } return cell! } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let alertController = UIAlertController(title: "ATTENTION", message: "You are sure to delete device?", preferredStyle: .alert) let devices = deviceList[indexPath.row] let confirmAction = UIAlertAction(title: "Delete", style: .destructive) { (_) in Hyber.revokeDevice(deviceId:[devices.value(forKey: "deviceId") as Any] , completionHandler: { (success) -> Void in if success { } else { Hyber.getDeviceList(completionHandler:{(success) -> Void in if success{ self.deviceListsTableView.reloadData() } }) } }) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in } alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } } //MARK: - Data Function func getErrorAlert() { let alertController = UIAlertController(title: "Network error", message: "Something wrong. Please try later", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Ok", style: .cancel) { (_) in } alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } }
apache-2.0
ba8980877531e8640a506c9035b6b236
34.203822
141
0.559255
5.194549
false
false
false
false
AndrewBennet/readinglist
ReadingList/ViewControllers/Add/ReviewBulkBooks.swift
1
1977
import Foundation import CoreData import UIKit final class ReviewBulkBooks: UITableViewController { var books = [Book]() var context: NSManagedObjectContext! override func viewDidLoad() { super.viewDidLoad() assert(!books.isEmpty, "ReviewBulkBooks loaded without any assigned books") tableView.register(BookTableViewCell.self) navigationItem.title = "Review \(books.count) \("Book".pluralising(books.count))" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(save)) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { assert(section == 0) return books.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(BookTableViewCell.self, for: indexPath) cell.configureFrom(books[indexPath.row]) cell.selectionStyle = .none return cell } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { return UISwipeActionsConfiguration(actions: [ UIContextualAction(style: .destructive, title: "Delete") { _, _, _ in self.books.remove(at: indexPath.row).delete() self.tableView.deleteRows(at: [indexPath], with: .automatic) if self.books.isEmpty { self.navigationController?.popViewController(animated: true) } } ]) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 92 } @objc func save() { context.saveAndLogIfErrored() dismiss(animated: true) } }
gpl-3.0
46a94f752c11e78babe5387a5430b223
34.945455
151
0.661608
5.216359
false
true
false
false
stefan-vainberg/SlidingImagePuzzle
SlidingImagePuzzle/SlidingImagePuzzle/UserAlbumCollectionViewDataSource.swift
1
6515
// // UserAlbumCollectionViewDataSource.swift // SlidingImagePuzzle // // Created by Stefan Vainberg on 10/26/14. // Copyright (c) 2014 Stefan. All rights reserved. // import Foundation import UIKit import Photos import Photos import AssetsLibrary class UserAlbumCollectionViewDataSource : NSObject, UICollectionViewDataSource { let maxNumCachedImages = 30 var imagesToDisplay:[UIImage]? var imagesToDisplayIdentifiers:[NSString]? var fullSizeImages:[UIImage]? var reloadMethod:((NSIndexPath) -> Void)? var imagesAssociativeDictionary:[NSString:UIImage]? var imagesLRUArray:[String]? var albumID:String? init(albumIdentifier:String) { super.init() self.Initialize(albumIdentifier) } func Initialize(albumIdentifier:String) -> Void { self.imagesToDisplay = [] self.fullSizeImages = [] self.imagesAssociativeDictionary = [:] self.imagesLRUArray = [] self.albumID = albumIdentifier self.imagesToDisplayIdentifiers = [] } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(AlbumImageCollectionViewCell.reuseIdentifier(), forIndexPath: indexPath) as AlbumImageCollectionViewCell let imageID = self.imagesToDisplayIdentifiers![indexPath.row] if let image = self.imagesAssociativeDictionary![imageID] { cell.updateCell(image) /* if (cell.contentView.subviews.count > 0) { for subview in cell.contentView.subviews { subview.removeFromSuperview() } } let imageView = UIImageView(image: image) imageView.clipsToBounds = true imageView.layer.cornerRadius = 3.0 imageView.layer.borderColor = UIColor.blackColor().CGColor imageView.layer.borderWidth = 0.5 cell.contentView.addSubview(imageView) */ } else { cell.clearCell() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), { () -> Void in objc_sync_enter(self) self.FetchImageForIndexPath(indexPath, assetID: imageID) objc_sync_exit(self) }) } return cell as UICollectionViewCell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.imagesToDisplayIdentifiers!.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } // HELPERS func FetchImageForIndexPath(indexPath:NSIndexPath, assetID:String) -> Void { let startDate = NSDate() if let images = PHAsset.fetchAssetsWithLocalIdentifiers([assetID], options: nil) { if (images.count > 0) { let imageAsset: PHAsset = images.objectAtIndex(0) as PHAsset self.ConsumeAssetImage(imageAsset, indexPath: indexPath) } } } func ConsumeAssetImage(imageAsset:PHAsset, indexPath:NSIndexPath) -> Void { let requestOptions = PHImageRequestOptions() requestOptions.version = PHImageRequestOptionsVersion.Current PHImageManager.defaultManager().requestImageDataForAsset(imageAsset, options: requestOptions) { (result, metadata, orientation, _) -> Void in autoreleasepool{ if (result == nil || result.length > 10000000) { // strange bug gives me 500 megs of image data sometimes. Could be that an asset is improperly marked as an image when it is in fact a video return } let imageFromData = UIImage(data: result) if (imageFromData == nil) { return } if (self.imagesLRUArray!.count > self.maxNumCachedImages) { if let assetToPurgeId = self.imagesLRUArray!.last { self.imagesLRUArray!.removeLast() self.imagesAssociativeDictionary!.removeValueForKey(assetToPurgeId) } } let properlyRotateImage = UIImage(CGImage: imageFromData!.CGImage, scale: 1.0, orientation: orientation) let scaledImage = properlyRotateImage self.imagesAssociativeDictionary![imageAsset.localIdentifier] = scaledImage self.imagesLRUArray!.insert(imageAsset.localIdentifier, atIndex: 0) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.reloadMethod!(indexPath) }) } } } func clipImageToFitCollectionCell(image: UIImage) -> UIImage { let heightWidthDiff = abs(image.size.width - image.size.height) let clipRect = CGRectMake(0, 0, image.size.width > image.size.height ? image.size.width - heightWidthDiff : image.size.width, image.size.height > image.size.width ? image.size.height - heightWidthDiff : image.size.height) var croppedImage = CGImageCreateWithImageInRect(image.CGImage, clipRect) let returnImage = UIImage(CGImage: croppedImage)! croppedImage = nil return returnImage } func scaleImageToFitCollectionCell(image: UIImage) -> UIImage { let collectionViewCellSize = CGSizeMake(50, 50) // we need to figure out the appropriate amount to scale down let scaleDownWidthFactor = ceil(image.size.width / collectionViewCellSize.width) let scaleDownHeightFactor = ceil(image.size.height / collectionViewCellSize.height) let finalScaleDownFactor = max(scaleDownWidthFactor, scaleDownHeightFactor) UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width / finalScaleDownFactor, image.size.height / finalScaleDownFactor), false, 0.0) image.drawInRect(CGRectMake(0, 0, image.size.width / finalScaleDownFactor, image.size.height / finalScaleDownFactor)) let returnImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() println("\(returnImage.size)") return returnImage } }
cc0-1.0
4d00d056298a3a00822edfb1f8e69ca8
38.731707
229
0.633615
5.266774
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/ViewControllers/MediaMessageView.swift
1
14166
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import MediaPlayer import YYImage import SignalServiceKit @objc public enum MediaMessageViewMode: UInt { case large case small case attachmentApproval } @objc public class MediaMessageView: UIView, OWSAudioPlayerDelegate { // MARK: Properties @objc public let mode: MediaMessageViewMode @objc public let attachment: SignalAttachment @objc public var audioPlayer: OWSAudioPlayer? @objc public var audioPlayButton: UIButton? @objc public var videoPlayButton: UIImageView? @objc public var audioProgressSeconds: CGFloat = 0 @objc public var audioDurationSeconds: CGFloat = 0 @objc public var contentView: UIView? // MARK: Initializers @available(*, unavailable, message:"use other constructor instead.") required public init?(coder aDecoder: NSCoder) { notImplemented() } // Currently we only use one mode (AttachmentApproval), so we could simplify this class, but it's kind // of nice that it's written in a flexible way in case we'd want to use it elsewhere again in the future. @objc public required init(attachment: SignalAttachment, mode: MediaMessageViewMode) { assert(!attachment.hasError) self.attachment = attachment self.mode = mode super.init(frame: CGRect.zero) createViews() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Create Views private func createViews() { if attachment.isAnimatedImage { createAnimatedPreview() } else if attachment.isImage { createImagePreview() } else if attachment.isVideo { createVideoPreview() } else if attachment.isAudio { createAudioPreview() } else { createGenericPreview() } } private func wrapViewsInVerticalStack(subviews: [UIView]) -> UIView { assert(subviews.count > 0) let stackView = UIView() var lastView: UIView? for subview in subviews { stackView.addSubview(subview) subview.autoHCenterInSuperview() if lastView == nil { subview.autoPinEdge(toSuperviewEdge: .top) } else { subview.autoPinEdge(.top, to: .bottom, of: lastView!, withOffset: stackSpacing()) } lastView = subview } lastView?.autoPinEdge(toSuperviewEdge: .bottom) return stackView } private func stackSpacing() -> CGFloat { switch mode { case .large, .attachmentApproval: return CGFloat(10) case .small: return CGFloat(5) } } private func createAudioPreview() { guard let dataUrl = attachment.dataUrl else { createGenericPreview() return } audioPlayer = OWSAudioPlayer(mediaUrl: dataUrl, audioBehavior: .playback, delegate: self) var subviews = [UIView]() let audioPlayButton = UIButton() self.audioPlayButton = audioPlayButton setAudioIconToPlay() audioPlayButton.imageView?.layer.minificationFilter = .trilinear audioPlayButton.imageView?.layer.magnificationFilter = .trilinear audioPlayButton.addTarget(self, action: #selector(audioPlayButtonPressed), for: .touchUpInside) let buttonSize = createHeroViewSize() audioPlayButton.autoSetDimension(.width, toSize: buttonSize) audioPlayButton.autoSetDimension(.height, toSize: buttonSize) subviews.append(audioPlayButton) let fileNameLabel = createFileNameLabel() if let fileNameLabel = fileNameLabel { subviews.append(fileNameLabel) } let fileSizeLabel = createFileSizeLabel() subviews.append(fileSizeLabel) let stackView = wrapViewsInVerticalStack(subviews: subviews) self.addSubview(stackView) fileNameLabel?.autoPinWidthToSuperview(withMargin: 32) // We want to center the stackView in it's superview while also ensuring // it's superview is big enough to contain it. stackView.autoPinWidthToSuperview() stackView.autoVCenterInSuperview() NSLayoutConstraint.autoSetPriority(UILayoutPriority.defaultLow) { stackView.autoPinHeightToSuperview() } stackView.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual) stackView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual) } private func createAnimatedPreview() { guard attachment.isValidImage else { createGenericPreview() return } guard let dataUrl = attachment.dataUrl else { createGenericPreview() return } guard let image = YYImage(contentsOfFile: dataUrl.path) else { createGenericPreview() return } guard image.size.width > 0 && image.size.height > 0 else { createGenericPreview() return } let animatedImageView = YYAnimatedImageView() animatedImageView.image = image let aspectRatio = image.size.width / image.size.height addSubviewWithScaleAspectFitLayout(view: animatedImageView, aspectRatio: aspectRatio) contentView = animatedImageView } private func addSubviewWithScaleAspectFitLayout(view: UIView, aspectRatio: CGFloat) { self.addSubview(view) // This emulates the behavior of contentMode = .scaleAspectFit using // iOS auto layout constraints. // // This allows ConversationInputToolbar to place the "cancel" button // in the upper-right hand corner of the preview content. view.autoCenterInSuperview() view.autoPin(toAspectRatio: aspectRatio) view.autoMatch(.width, to: .width, of: self, withMultiplier: 1.0, relation: .lessThanOrEqual) view.autoMatch(.height, to: .height, of: self, withMultiplier: 1.0, relation: .lessThanOrEqual) } private func createImagePreview() { guard attachment.isValidImage else { createGenericPreview() return } guard let image = attachment.image() else { createGenericPreview() return } guard image.size.width > 0 && image.size.height > 0 else { createGenericPreview() return } let imageView = UIImageView(image: image) imageView.layer.minificationFilter = .trilinear imageView.layer.magnificationFilter = .trilinear let aspectRatio = image.size.width / image.size.height addSubviewWithScaleAspectFitLayout(view: imageView, aspectRatio: aspectRatio) contentView = imageView } private func createVideoPreview() { guard attachment.isValidVideo else { createGenericPreview() return } guard let image = attachment.videoPreview() else { createGenericPreview() return } guard image.size.width > 0 && image.size.height > 0 else { createGenericPreview() return } let imageView = UIImageView(image: image) imageView.layer.minificationFilter = .trilinear imageView.layer.magnificationFilter = .trilinear let aspectRatio = image.size.width / image.size.height addSubviewWithScaleAspectFitLayout(view: imageView, aspectRatio: aspectRatio) contentView = imageView // attachment approval provides it's own play button to keep it // at the proper zoom scale. if mode != .attachmentApproval { let videoPlayIcon = UIImage(named: "play_button")! let videoPlayButton = UIImageView(image: videoPlayIcon) self.videoPlayButton = videoPlayButton videoPlayButton.contentMode = .scaleAspectFit self.addSubview(videoPlayButton) videoPlayButton.autoCenterInSuperview() } } private func createGenericPreview() { var subviews = [UIView]() let imageView = createHeroImageView(imageName: "file-thin-black-filled-large") subviews.append(imageView) let fileNameLabel = createFileNameLabel() if let fileNameLabel = fileNameLabel { subviews.append(fileNameLabel) } let fileSizeLabel = createFileSizeLabel() subviews.append(fileSizeLabel) let stackView = wrapViewsInVerticalStack(subviews: subviews) self.addSubview(stackView) fileNameLabel?.autoPinWidthToSuperview(withMargin: 32) // We want to center the stackView in it's superview while also ensuring // it's superview is big enough to contain it. stackView.autoPinWidthToSuperview() stackView.autoVCenterInSuperview() NSLayoutConstraint.autoSetPriority(UILayoutPriority.defaultLow) { stackView.autoPinHeightToSuperview() } stackView.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual) stackView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual) } private func createHeroViewSize() -> CGFloat { switch mode { case .large: return ScaleFromIPhone5To7Plus(175, 225) case .attachmentApproval: return ScaleFromIPhone5(100) case .small: return ScaleFromIPhone5To7Plus(80, 80) } } private func createHeroImageView(imageName: String) -> UIView { let imageSize = createHeroViewSize() let image = UIImage(named: imageName) assert(image != nil) let imageView = UIImageView(image: image) imageView.layer.minificationFilter = .trilinear imageView.layer.magnificationFilter = .trilinear imageView.layer.shadowColor = UIColor.black.cgColor let shadowScaling = 5.0 imageView.layer.shadowRadius = CGFloat(2.0 * shadowScaling) imageView.layer.shadowOpacity = 0.25 imageView.layer.shadowOffset = CGSize(width: 0.75 * shadowScaling, height: 0.75 * shadowScaling) imageView.autoSetDimension(.width, toSize: imageSize) imageView.autoSetDimension(.height, toSize: imageSize) return imageView } private func labelFont() -> UIFont { switch mode { case .large, .attachmentApproval: return UIFont.ows_regularFont(withSize: ScaleFromIPhone5To7Plus(18, 24)) case .small: return UIFont.ows_regularFont(withSize: ScaleFromIPhone5To7Plus(14, 14)) } } private var controlTintColor: UIColor { switch mode { case .small, .large: return UIColor.ows_materialBlue case .attachmentApproval: return UIColor.white } } private func formattedFileExtension() -> String? { guard let fileExtension = attachment.fileExtension else { return nil } return String(format: NSLocalizedString("ATTACHMENT_APPROVAL_FILE_EXTENSION_FORMAT", comment: "Format string for file extension label in call interstitial view"), fileExtension.uppercased()) } public func formattedFileName() -> String? { guard let sourceFilename = attachment.sourceFilename else { return nil } let filename = sourceFilename.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) guard filename.count > 0 else { return nil } return filename } private func createFileNameLabel() -> UIView? { let filename = formattedFileName() ?? formattedFileExtension() guard filename != nil else { return nil } let label = UILabel() label.text = filename label.textColor = controlTintColor label.font = labelFont() label.textAlignment = .center label.lineBreakMode = .byTruncatingMiddle return label } private func createFileSizeLabel() -> UIView { let label = UILabel() let fileSize = attachment.dataLength label.text = String(format: NSLocalizedString("ATTACHMENT_APPROVAL_FILE_SIZE_FORMAT", comment: "Format string for file size label in call interstitial view. Embeds: {{file size as 'N mb' or 'N kb'}}."), OWSFormat.formatFileSize(UInt(fileSize))) label.textColor = controlTintColor label.font = labelFont() label.textAlignment = .center return label } // MARK: - Event Handlers @objc func audioPlayButtonPressed(sender: UIButton) { audioPlayer?.togglePlayState() } // MARK: - OWSAudioPlayerDelegate @objc public var audioPlaybackState = AudioPlaybackState.stopped { didSet { AssertIsOnMainThread() ensureButtonState() } } private func ensureButtonState() { if audioPlaybackState == .playing { setAudioIconToPause() } else { setAudioIconToPlay() } } public func setAudioProgress(_ progress: CGFloat, duration: CGFloat) { audioProgressSeconds = progress audioDurationSeconds = duration } private func setAudioIconToPlay() { let image = UIImage(named: "audio_play_black_large")?.withRenderingMode(.alwaysTemplate) assert(image != nil) audioPlayButton?.setImage(image, for: .normal) audioPlayButton?.imageView?.tintColor = controlTintColor } private func setAudioIconToPause() { let image = UIImage(named: "audio_pause_black_large")?.withRenderingMode(.alwaysTemplate) assert(image != nil) audioPlayButton?.setImage(image, for: .normal) audioPlayButton?.imageView?.tintColor = controlTintColor } }
gpl-3.0
01f44945d0f4b6345eccbe02aac43a02
32.175644
169
0.639348
5.394516
false
false
false
false
xedin/swift
test/SourceKit/CompileNotifications/cursor-info.swift
2
643
// RUN: %sourcekitd-test -req=track-compiles == -req=cursor %s -offset=0 -- %s | %FileCheck %s -check-prefix=COMPILE_1 // COMPILE_1: { // COMPILE_1: key.notification: source.notification.compile-will-start, // COMPILE_1: key.filepath: "SOURCE_DIR{{.*}}cursor-info.swift", // COMPILE_1: key.compileid: [[CID1:".*"]] // COMPILE_1: } // COMPILE_1: { // COMPILE_1: key.notification: source.notification.compile-did-finish, // COMPILE_1: key.compileid: [[CID1]] // COMPILE_1: } // COMPILE_1: <empty cursor info; internal diagnostic: "Unable to resolve cursor info."> // COMPILE_1-NOT: compile-will-start // COMPILE_1-NOT: compile-did-finish
apache-2.0
859262b244b2ed08f4a04edf46ec5967
48.461538
118
0.679627
3.033019
false
true
false
false
davidvuong/ddfa-app
ios/Pods/GooglePlacePicker/Example/GooglePlacePickerDemos/ViewControllers/PlaceDetail/PlaceDetailTableViewDataSource.swift
4
12314
/* * Copyright 2016 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import GooglePlaces enum PlaceProperty: Int { case placeID case coordinate case openNowStatus case phoneNumber case website case formattedAddress case rating case priceLevel case types case attribution static func numberOfProperties() -> Int { return 10 } } /// The data source and delegate for the Place Detail |UITableView|. Beyond just displaying the /// details of the place, this class also manages the floating section title containing the place /// name and takes into account the presence of the back button if it's visible. class PlaceDetailTableViewDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { // MARK: - Properties private let place: GMSPlace private let blueCellIdentifier = "BlueCellIdentifier" private let extensionConstraint: NSLayoutConstraint private let noneText = NSLocalizedString("PlaceDetails.MissingValue", comment: "The value of a property which is missing") private let tableView: UITableView var compactHeader = false { didSet { if #available(iOS 9.0, *) { tableView.beginUpdates() updateNavigationBar() tableView.endUpdates() } else { // We'd really rather not call reloadData(), but on iOS 8.x begin/endUpdates tend to crash // for this particular tableView. tableView.reloadData() } } } var offsetNavigationTitle = false // MARK: Init/Deinit /// Create a |PlaceDetailTableViewDataSource| with the specified |GMSPlace| and constraint. /// /// - parameter place The |GMSPlace| to show details for. /// - parameter extensionConstraint The |NSLayoutConstraint| to update when scrolling so that /// the header view shrinks/grows to fill the gap between the map/photo and the details. /// - parameter tableView The UITableView for this data. init(place: GMSPlace, extensionConstraint: NSLayoutConstraint, tableView: UITableView) { self.place = place self.extensionConstraint = extensionConstraint self.tableView = tableView // Register the |UITableViewCell|s. tableView.register(PlaceAttributeCell.nib, forCellReuseIdentifier: PlaceAttributeCell.reuseIdentifier) tableView.register(PlaceNameHeader.nib, forHeaderFooterViewReuseIdentifier: PlaceNameHeader.reuseIdentifier) tableView.register(UITableViewCell.self, forCellReuseIdentifier: blueCellIdentifier) // Configure some other properties. tableView.estimatedRowHeight = 44 tableView.estimatedSectionHeaderHeight = 44 tableView.sectionHeaderHeight = UITableViewAutomaticDimension } // MARK: - Public Methods func updateNavigationTextOffset() { updateNavigationBar() } // MARK: - UITableView DataSource/Delegate func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return PlaceProperty.numberOfProperties() + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // The first cell is special, this is a small blue spacer we use to pad out the place name // header. if indexPath.item == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: blueCellIdentifier, for: indexPath) cell.backgroundColor = Colors.blue2 cell.selectionStyle = .none return cell } // For all the other cells use the same class. let untyped = tableView.dequeueReusableCell(withIdentifier: PlaceAttributeCell.reuseIdentifier, for: indexPath) let cell = untyped as! PlaceAttributeCell // Disable selection. cell.selectionStyle = .none // Set the relevant values. if let propertyType = PlaceProperty(rawValue: indexPath.item - 1) { cell.propertyName.text = propertyType.localizedDescription() cell.propertyIcon.image = propertyType.icon() switch propertyType { case .placeID: cell.propertyValue.text = place.placeID case .coordinate: let format = NSLocalizedString("Places.Property.Coordinate.Format", comment: "The format string for latitude, longitude") cell.propertyValue.text = String(format: format, place.coordinate.latitude, place.coordinate.longitude) case .openNowStatus: cell.propertyValue.text = text(for: place.openNowStatus) case .phoneNumber: cell.propertyValue.text = place.phoneNumber ?? noneText case .website: cell.propertyValue.text = place.website?.absoluteString ?? noneText case .formattedAddress: cell.propertyValue.text = place.formattedAddress ?? noneText case .rating: let rating = place.rating // As specified in the documentation for |GMSPlace|, a rating of 0.0 signifies that there // have not yet been any ratings for this location. if rating > 0 { cell.propertyValue.text = "\(rating)" } else { cell.propertyValue.text = noneText } case .priceLevel: cell.propertyValue.text = text(for: place.priceLevel) case .types: cell.propertyValue.text = place.types.joined(separator: ", ") case .attribution: if let attributions = place.attributions { cell.propertyValue.attributedText = attributions } else { cell.propertyValue.text = noneText } } } else { fatalError("Unexpected row index") } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return place.name } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: PlaceNameHeader.reuseIdentifier) let header = view as! PlaceNameHeader updateNavigationBar(header) return header } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // Our first cell has a fixed height, all the rest are automatic. if indexPath.item == 0 { return compactHeader ? 0 : 20 } else { return UITableViewAutomaticDimension } } func scrollViewDidScroll(_ scrollView: UIScrollView) { // Update the extensionConstraint and the navigation title offset when the tableView scrolls. extensionConstraint.constant = max(0, -scrollView.contentOffset.y) updateNavigationTextOffset() } // MARK: - Utilities /// Return the appropriate text string for the specified |GMSPlacesOpenNowStatus|. private func text(for status: GMSPlacesOpenNowStatus) -> String { switch status { case .no: return NSLocalizedString("Places.OpenNow.No", comment: "Closed/Open state for a closed location") case .yes: return NSLocalizedString("Places.OpenNow.Yes", comment: "Closed/Open state for an open location") case .unknown: return NSLocalizedString("Places.OpenNow.Unknown", comment: "Closed/Open state for when it is unknown") } } /// Return the appropriate text string for the specified |GMSPlacesPriceLevel|. private func text(for priceLevel: GMSPlacesPriceLevel) -> String { switch priceLevel { case .free: return NSLocalizedString("Places.PriceLevel.Free", comment: "Relative cost for a free location") case .cheap: return NSLocalizedString("Places.PriceLevel.Cheap", comment: "Relative cost for a cheap location") case .medium: return NSLocalizedString("Places.PriceLevel.Medium", comment: "Relative cost for a medium cost location") case .high: return NSLocalizedString("Places.PriceLevel.High", comment: "Relative cost for a high cost location") case .expensive: return NSLocalizedString("Places.PriceLevel.Expensive", comment: "Relative cost for an expensive location") case .unknown: return NSLocalizedString("Places.PriceLevel.Unknown", comment: "Relative cost for when it is unknown") } } private func updateNavigationBar() { // Grab the header. if let header = tableView.headerView(forSection: 0) as? PlaceNameHeader { updateNavigationBar(header) } } private func updateNavigationBar(_ header: PlaceNameHeader) { // Check to see if we should be offsetting the navigation title. if offsetNavigationTitle { // If so offset it by at most 36 pixels, relative to how much we've scrolled past 160px. let offset = max(0, min(36, tableView.contentOffset.y - 160)) header.leadingConstraint.constant = offset } else { // Otherwise don't offset. header.leadingConstraint.constant = 0 } // Update the compact status. header.compact = compactHeader } } extension PlaceProperty { func localizedDescription() -> String { switch self { case .placeID: return NSLocalizedString("Places.Property.PlaceID", comment: "Name for the Place ID property") case .coordinate: return NSLocalizedString("Places.Property.Coordinate", comment: "Name for the Coordinate property") case .openNowStatus: return NSLocalizedString("Places.Property.OpenNowStatus", comment: "Name for the Open now status property") case .phoneNumber: return NSLocalizedString("Places.Property.PhoneNumber", comment: "Name for the Phone number property") case .website: return NSLocalizedString("Places.Property.Website", comment: "Name for the Website property") case .formattedAddress: return NSLocalizedString("Places.Property.FormattedAddress", comment: "Name for the Formatted address property") case .rating: return NSLocalizedString("Places.Property.Rating", comment: "Name for the Rating property") case .priceLevel: return NSLocalizedString("Places.Property.PriceLevel", comment: "Name for the Price level property") case .types: return NSLocalizedString("Places.Property.Types", comment: "Name for the Types property") case .attribution: return NSLocalizedString("Places.Property.Attributions", comment: "Name for the Attributions property") } } func icon() -> UIImage? { switch self { case .placeID: return UIImage(named: "place_id") case .coordinate: return UIImage(named: "coordinate") case .openNowStatus: return UIImage(named: "open_now") case .phoneNumber: return UIImage(named: "phone_number") case .website: return UIImage(named: "website") case .formattedAddress: return UIImage(named: "address") case .rating: return UIImage(named: "rating") case .priceLevel: return UIImage(named: "price_level") case .types: return UIImage(named: "types") case .attribution: return UIImage(named: "attribution") } } }
mit
f2facdc65b126ae5b7172bf7e57f59f2
37.361371
99
0.656326
5.150146
false
false
false
false
ngageoint/mage-ios
Mage/CoreData/Attachment.swift
1
2565
// // Attachment.m // mage-ios-sdk // // Created by William Newman on 4/13/16. // Copyright © 2016 National Geospatial-Intelligence Agency. All rights reserved. // import CoreData @objc public class Attachment: NSManagedObject { public static func attachment(json: [AnyHashable : Any], order: Int? = 0, context: NSManagedObjectContext) -> Attachment? { let attachment = Attachment.mr_createEntity(in: context); attachment?.populate(json: json, order: order); return attachment; } public func populate(json: [AnyHashable : Any], order: Int? = 0) { self.remoteId = json[AttachmentKey.id.key] as? String self.contentType = json[AttachmentKey.contentType.key] as? String self.url = json[AttachmentKey.url.key] as? String self.name = json[AttachmentKey.name.key] as? String self.size = json[AttachmentKey.size.key] as? NSNumber self.observationFormId = json[AttachmentKey.observationFormId.key] as? String self.fieldName = json[AttachmentKey.fieldName.key] as? String if let order = order { self.order = NSNumber(value:order) } else { self.order = 0 } if let dirty = json[AttachmentKey.dirty.key] as? Bool { self.dirty = dirty; } else { self.dirty = false; } self.localPath = json[AttachmentKey.localPath.key] as? String if let lastModified = json[AttachmentKey.lastModified.key] as? String { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]; formatter.timeZone = TimeZone(secondsFromGMT: 0)!; self.lastModified = formatter.date(from: lastModified); } else { self.lastModified = Date(); } if let markedForDeletion = json[AttachmentKey.markedForDeletion.key] as? Bool { self.markedForDeletion = markedForDeletion; } else { self.markedForDeletion = false; } } @objc public func sourceURL(size: NSInteger) -> URL? { if let localPath = self.localPath, FileManager.default.fileExists(atPath: localPath) { return URL(fileURLWithPath: localPath); } else { let token = StoredPassword.retrieveStoredToken(); return URL(string: "\(self.url ?? "")?access_token=\(token ?? "")&size=\(size)") } } }
apache-2.0
0fab02b82e01d37fe696889406d8efec
39.0625
157
0.624805
4.360544
false
false
false
false
alecsechechel/Swift
LazyLoadTest/LazyLoadTest/UIApplication+NetworkIndicator.swift
4
610
// // UIApplication+NetworkIndicator.swift // InfiniteScrollViewDemoSwift // // Created by pronebird on 5/3/15. // Copyright (c) 2015 pronebird. All rights reserved. // import Foundation private var networkActivityCount = 0 extension UIApplication { func startNetworkActivity() { networkActivityCount++ networkActivityIndicatorVisible = true } func stopNetworkActivity() { if networkActivityCount < 1 { return; } if --networkActivityCount == 0 { networkActivityIndicatorVisible = false } } }
mit
2fdb67d22454704380e7c01edbb528c2
19.366667
54
0.629508
4.88
false
false
false
false
keyeMyria/edx-app-ios
Source/OEXRouter+Swift.swift
1
10727
// // OEXRouter+Swift.swift // edX // // Created by Akiva Leffert on 5/7/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation // The router is an indirection point for navigation throw our app. // New router logic should live here so it can be written in Swift. // We should gradually migrate the existing router class here and then // get rid of the objc version enum CourseHTMLBlockSubkind { case Base case Problem } enum CourseBlockDisplayType { case Unknown case Outline case Unit case Video case HTML(CourseHTMLBlockSubkind) } extension CourseBlock { var displayType : CourseBlockDisplayType { switch self.type { case .Unknown(_), .HTML: return multiDevice ? .HTML(.Base) : .Unknown case .Problem: return multiDevice ? .HTML(.Problem) : .Unknown case .Course: return .Outline case .Chapter: return .Outline case .Section: return .Outline case .Unit: return .Unit case .Video(_): return .Video } } } extension OEXRouter { func showCoursewareForCourseWithID(courseID : String, fromController controller : UIViewController) { showContainerForBlockWithID(nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller) } func unitControllerForCourseID(courseID : String, blockID : CourseBlockID?, initialChildID : CourseBlockID?) -> CourseContentPageViewController { let environment = CourseContentPageViewController.Environment(dataManager: self.environment.dataManager, router: self, styles : self.environment.styles) let contentPageController = CourseContentPageViewController(environment: environment, courseID: courseID, rootID: blockID, initialChildID: initialChildID) return contentPageController } func showContainerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, parentID : CourseBlockID?, courseID : CourseBlockID, fromController controller: UIViewController) { switch type { case .Outline: fallthrough case .Unit: let outlineController = controllerForBlockWithID(blockID, type: type, courseID: courseID) controller.navigationController?.pushViewController(outlineController, animated: true) case .HTML: fallthrough case .Video: fallthrough case .Unknown: let pageController = unitControllerForCourseID(courseID, blockID: parentID, initialChildID: blockID) if let delegate = controller as? CourseContentPageViewControllerDelegate { pageController.navigationDelegate = delegate } controller.navigationController?.pushViewController(pageController, animated: true) } } private func controllerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, courseID : String) -> UIViewController { switch type { case .Outline: let environment = CourseOutlineViewController.Environment(dataManager: self.environment.dataManager, reachability : InternetReachability(), router: self, styles : self.environment.styles, networkManager : self.environment.networkManager) let outlineController = CourseOutlineViewController(environment: environment, courseID: courseID, rootID: blockID) return outlineController case .Unit: return unitControllerForCourseID(courseID, blockID: blockID, initialChildID: nil) case .HTML: let environment = HTMLBlockViewController.Environment(config : self.environment.config, courseDataManager : self.environment.dataManager.courseDataManager, session : self.environment.session, styles : self.environment.styles) let controller = HTMLBlockViewController(blockID: blockID, courseID : courseID, environment : environment) return controller case .Video: let environment = VideoBlockViewController.Environment(courseDataManager: self.environment.dataManager.courseDataManager, interface : self.environment.interface, styles : self.environment.styles) let controller = VideoBlockViewController(environment: environment, blockID: blockID, courseID: courseID) return controller case .Unknown: let environment = CourseUnknownBlockViewController.Environment(dataManager : self.environment.dataManager, styles : self.environment.styles) let controller = CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment) return controller } } func controllerForBlock(block : CourseBlock, courseID : String) -> UIViewController { return controllerForBlockWithID(block.blockID, type: block.displayType, courseID: courseID) } func showFullScreenMessageViewControllerFromViewController(controller : UIViewController, message : String, bottomButtonTitle: String?) { let fullScreenViewController = FullScreenMessageViewController(message: message, bottomButtonTitle: bottomButtonTitle) controller.presentViewController(fullScreenViewController, animated: true, completion: nil) } func showDiscussionResponsesFromViewController(controller: UIViewController, courseID : String, item : DiscussionPostItem) { let environment = DiscussionResponsesViewController.Environment(networkManager: self.environment.networkManager, router: self, styles : self.environment.styles) let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil) let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController responsesViewController.environment = environment responsesViewController.courseID = courseID responsesViewController.postItem = item controller.navigationController?.pushViewController(responsesViewController, animated: true) } func showDiscussionCommentsFromViewController(controller: UIViewController, courseID : String, item : DiscussionResponseItem, closed : Bool) { let environment = DiscussionCommentsViewController.Environment( courseDataManager: self.environment.dataManager.courseDataManager, router: self, networkManager : self.environment.networkManager) let commentsVC = DiscussionCommentsViewController(environment: environment, courseID : courseID, responseItem: item, closed: closed) controller.navigationController?.pushViewController(commentsVC, animated: true) } func showDiscussionNewCommentFromController(controller: UIViewController, courseID : String, item: DiscussionItem) { let environment = DiscussionNewCommentViewController.Environment( courseDataManager: self.environment.dataManager.courseDataManager, networkManager: self.environment.networkManager, router: self) let newCommentViewController = DiscussionNewCommentViewController(environment: environment, courseID : courseID, item: item) let navigationController = UINavigationController(rootViewController: newCommentViewController) controller.presentViewController(navigationController, animated: true, completion: nil) } func showPostsFromController(controller : UIViewController, courseID : String, topic : DiscussionTopic) { let environment = PostsViewControllerEnvironment(networkManager: self.environment.networkManager, router: self, styles: self.environment.styles) let postsController = PostsViewController(environment: environment, courseID: courseID, topic: topic) controller.navigationController?.pushViewController(postsController, animated: true) } func showAllPostsFromController(controller : UIViewController, courseID : String, followedOnly following : Bool) { let environment = PostsViewControllerEnvironment(networkManager: self.environment.networkManager, router: self, styles: self.environment.styles) let postsController = PostsViewController(environment: environment, courseID: courseID, following : following) controller.navigationController?.pushViewController(postsController, animated: true) } func showPostsFromController(controller : UIViewController, courseID : String, queryString : String) { let environment = PostsViewControllerEnvironment(networkManager: self.environment.networkManager, router: self, styles: self.environment.styles) let postsController = PostsViewController(environment: environment, courseID: courseID, queryString : queryString) controller.navigationController?.pushViewController(postsController, animated: true) } func showDiscussionTopicsFromController(controller: UIViewController, courseID : String) { let environment = DiscussionTopicsViewController.Environment( config: self.environment.config, courseDataManager: self.environment.dataManager.courseDataManager, networkManager: self.environment.networkManager, router: self, styles : self.environment.styles ) let topicsController = DiscussionTopicsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(topicsController, animated: true) } func showDiscussionNewPostFromController(controller: UIViewController, courseID : String, initialTopic : DiscussionTopic?) { let environment = DiscussionNewPostViewController.Environment( courseDataManager : self.environment.dataManager.courseDataManager, networkManager: self.environment.networkManager, router: self) let newPostController = DiscussionNewPostViewController(environment: environment, courseID: courseID, selectedTopic: initialTopic) let navigationController = UINavigationController(rootViewController: newPostController) controller.presentViewController(navigationController, animated: true, completion: nil) } func showHandoutsFromController(controller : UIViewController, courseID : String) { let environment = CourseHandoutsViewController.Environment( dataManager : self.environment.dataManager, networkManager: self.environment.networkManager, styles: self.environment.styles) let handoutsViewController = CourseHandoutsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(handoutsViewController, animated: true) } }
apache-2.0
535ca641a08b5297abaa2851e143dbdf
56.672043
253
0.743265
5.979376
false
false
false
false
igordeoliveirasa/yolo-ios
mvt-ios/AppDelegate.swift
1
6797
// // AppDelegate.swift // mvt-ios // // Created by Igor de Oliveira Sa on 24/12/14. // Copyright (c) 2014 Igor de Oliveira Sa. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let SCHEME_FACEBOOK = "fb453476448077542" let SCHEME_GOOGLE = "com.igordeoliveira.mvt-ios" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { FBLoginView.self FBProfilePictureView.self return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { var wasHandled:Bool = false println(url.scheme) if url.scheme == SCHEME_FACEBOOK { wasHandled = FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication) } else if url.scheme == SCHEME_GOOGLE { wasHandled = GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation: annotation) } return wasHandled } 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.igordeoliveira.mvt_ios" 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("mvt_ios", 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("mvt_ios.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. let dict = NSMutableDictionary() 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() } } } }
mit
cf1d51c81a424c62e1caa072503f8fa6
51.689922
290
0.708989
5.557645
false
false
false
false
beryu/CustomizableActionSheet
Source/CustomizableActionSheet.swift
2
8806
// // CustomizableActionSheet.swift // CustomizableActionSheet // // Created by Ryuta Kibe on 2015/12/22. // Copyright 2015 blk. All rights reserved. // import UIKit @objc public enum CustomizableActionSheetItemType: Int { case button case view } // Can't define CustomizableActionSheetItem as struct because Obj-C can't see struct definition. public class CustomizableActionSheetItem: NSObject { // MARK: - Public properties public var type: CustomizableActionSheetItemType = .button public var height: CGFloat = CustomizableActionSheetItem.kDefaultHeight public static let kDefaultHeight: CGFloat = 44 // type = .View public var view: UIView? // type = .Button public var label: String? public var textColor: UIColor = UIColor(red: 0, green: 0.47, blue: 1.0, alpha: 1.0) public var backgroundColor: UIColor = UIColor.white public var font: UIFont? = nil public var selectAction: ((_ actionSheet: CustomizableActionSheet) -> Void)? = nil // MARK: - Private properties fileprivate var element: UIView? = nil public convenience init(type: CustomizableActionSheetItemType, height: CGFloat = CustomizableActionSheetItem.kDefaultHeight) { self.init() self.type = type self.height = height } } private class ActionSheetItemView: UIView { var subview: UIView? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setting() } override init(frame: CGRect) { super.init(frame: frame) self.setting() } init() { super.init(frame: CGRect.zero) self.setting() } func setting() { self.clipsToBounds = true } override func addSubview(_ view: UIView) { super.addSubview(view) self.subview = view } override func layoutSubviews() { super.layoutSubviews() if let subview = self.subview { subview.frame = self.bounds } } } @objc public enum CustomizableActionSheetPosition: Int { case bottom case top } public class CustomizableActionSheet: NSObject { // MARK: - Private properties private static var actionSheets = [CustomizableActionSheet]() private static let kMarginSide: CGFloat = 8 private static let kItemInterval: CGFloat = 8 private static let kMarginTop: CGFloat = 20 private var items: [CustomizableActionSheetItem]? private let maskView = UIView() private let itemContainerView = UIView() private var closeBlock: (() -> Void)? // MARK: - Public properties public var defaultCornerRadius: CGFloat = 4 public var position: CustomizableActionSheetPosition = .bottom public func showInView(_ targetView: UIView, items: [CustomizableActionSheetItem], closeBlock: (() -> Void)? = nil) { // Save instance to reaction until closing this sheet CustomizableActionSheet.actionSheets.append(self) let targetBounds = targetView.bounds // Save closeBlock self.closeBlock = closeBlock // mask view let maskViewTapGesture = UITapGestureRecognizer(target: self, action: #selector(CustomizableActionSheet.maskViewWasTapped)) self.maskView.addGestureRecognizer(maskViewTapGesture) self.maskView.frame = targetBounds self.maskView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) targetView.addSubview(self.maskView) // set items for subview in self.itemContainerView.subviews { subview.removeFromSuperview() } var currentPosition: CGFloat = 0 let safeAreaLeft: CGFloat let safeAreaWidth: CGFloat let safeAreaTop: CGFloat let safeAreaBottom: CGFloat if #available(iOS 11.0, *) { safeAreaLeft = targetView.safeAreaInsets.left safeAreaWidth = targetView.safeAreaLayoutGuide.layoutFrame.width safeAreaTop = targetView.safeAreaInsets.top safeAreaBottom = targetView.safeAreaInsets.bottom } else { safeAreaLeft = 0 safeAreaWidth = targetBounds.width safeAreaTop = CustomizableActionSheet.kMarginTop safeAreaBottom = 0 } var availableHeight = targetBounds.height - safeAreaTop - safeAreaBottom // Calculate height of items for item in items { availableHeight = availableHeight - item.height - CustomizableActionSheet.kItemInterval } for item in items { // Apply height of items if availableHeight < 0 { let reduceNum = min(item.height, -availableHeight) item.height -= reduceNum availableHeight += reduceNum if item.height <= 0 { availableHeight += CustomizableActionSheet.kItemInterval continue } } // Add views switch (item.type) { case .button: let button = UIButton() button.layer.cornerRadius = defaultCornerRadius button.frame = CGRect( x: CustomizableActionSheet.kMarginSide, y: currentPosition, width: safeAreaWidth - (CustomizableActionSheet.kMarginSide * 2), height: item.height) button.setTitle(item.label, for: UIControl.State()) button.backgroundColor = item.backgroundColor button.setTitleColor(item.textColor, for: UIControl.State()) if let font = item.font { button.titleLabel?.font = font } if let _ = item.selectAction { button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CustomizableActionSheet.buttonWasTapped(_:)))) } item.element = button self.itemContainerView.addSubview(button) currentPosition = currentPosition + item.height + CustomizableActionSheet.kItemInterval case .view: if let view = item.view { let containerView = ActionSheetItemView(frame: CGRect( x: CustomizableActionSheet.kMarginSide, y: currentPosition, width: safeAreaWidth - (CustomizableActionSheet.kMarginSide * 2), height: item.height)) containerView.layer.cornerRadius = defaultCornerRadius containerView.addSubview(view) view.frame = view.bounds self.itemContainerView.addSubview(containerView) item.element = view currentPosition = currentPosition + item.height + CustomizableActionSheet.kItemInterval } } } let positionX: CGFloat = safeAreaLeft var positionY: CGFloat = targetBounds.minY + targetBounds.height - currentPosition - safeAreaBottom var moveY: CGFloat = positionY if self.position == .top { positionY = CustomizableActionSheet.kItemInterval moveY = -currentPosition } self.itemContainerView.frame = CGRect( x: positionX, y: positionY, width: safeAreaWidth, height: currentPosition) self.items = items // Show animation self.maskView.alpha = 0 targetView.addSubview(self.itemContainerView) self.itemContainerView.transform = CGAffineTransform(translationX: 0, y: moveY) UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseOut, animations: { () -> Void in self.maskView.alpha = 1 self.itemContainerView.transform = CGAffineTransform.identity }, completion: nil) } public func dismiss() { guard let targetView = self.itemContainerView.superview else { return } // Hide animation self.maskView.alpha = 1 var moveY: CGFloat = targetView.bounds.height - self.itemContainerView.frame.origin.y if self.position == .top { moveY = -self.itemContainerView.frame.height } UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseOut, animations: { () -> Void in self.maskView.alpha = 0 self.itemContainerView.transform = CGAffineTransform(translationX: 0, y: moveY) }) { (result: Bool) -> Void in // Remove views self.itemContainerView.removeFromSuperview() self.maskView.removeFromSuperview() // Remove this instance for i in 0 ..< CustomizableActionSheet.actionSheets.count { if CustomizableActionSheet.actionSheets[i] == self { CustomizableActionSheet.actionSheets.remove(at: i) break } } self.closeBlock?() } } // MARK: - Private methods @objc private func maskViewWasTapped() { self.dismiss() } @objc private func buttonWasTapped(_ sender: AnyObject) { guard let items = self.items else { return } for item in items { guard let element = item.element, let gestureRecognizer = sender as? UITapGestureRecognizer else { continue } if element == gestureRecognizer.view { item.selectAction?(self) } } } }
mit
58717c77c566847177f7b639a92f619c
30.116608
139
0.677038
4.770314
false
false
false
false
podverse/podverse-ios
Podverse/SearchPodcast.swift
1
9258
// // SearchPodcast.swift // Podverse // // Created by Creon on 12/24/16. // Copyright © 2016 Podverse LLC. All rights reserved. // import Foundation import UIKit class SearchPodcast { var buzzScore: String? var categories: String? var description: String? var feedUrl: String? var hosts: String? var imageUrl: String? var lastEpisodeTitle: String? var lastPubDate: String? var network: String? var id: String? var searchEpisodes = [SearchEpisode]() var title: String? static func convertJSONToSearchPodcast (_ json: [String:Any]) -> SearchPodcast { let searchPodcast = SearchPodcast() if let id = json["id"] as? String { searchPodcast.id = id } if let title = json["title"] as? String { searchPodcast.title = title } if let categories = json["categories"] as? [String] { var categoryString = "" for category in categories { categoryString += category if category != categories.last { categoryString += ", " } } searchPodcast.categories = categoryString } if let imageUrl = json["imageUrl"] as? String { searchPodcast.imageUrl = imageUrl } if let author = json["author"] as? String { searchPodcast.hosts = author } if let lastPubDate = json["lastPubDate"] as? String { searchPodcast.lastPubDate = lastPubDate } if let lastEpisodeTitle = json["lastEpisodeTitle"] as? String { searchPodcast.lastEpisodeTitle = lastEpisodeTitle } if let episodes = json["episodes"] as? [[String:Any]] { for episode in episodes { let searchEpisode = SearchEpisode.convertJSONToSearchEpisode(episode) searchPodcast.searchEpisodes.append(searchEpisode) } } return searchPodcast } static func retrievePodcastFromServer(id: String?, completion: @escaping (_ podcast:SearchPodcast?) -> Void) { if let id = id { if let url = URL(string: BASE_URL + "api/podcasts?id=" + id) { var request = URLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in guard error == nil else { DispatchQueue.main.async { completion(nil) } return } if let data = data { do { var searchPodcast = SearchPodcast() if let podcastJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] { searchPodcast = convertJSONToSearchPodcast(podcastJSON) } DispatchQueue.main.async { completion(searchPodcast) } } catch { print("Error: " + error.localizedDescription) } } } task.resume() } } else { completion(nil) } } static func authorityFeedUrlForPodcast(id: String, completion: @escaping (_ podverseId: String?) -> Void) { if let url = URL(string: BASE_URL + "api/podcasts/authorityFeedUrl?id=" + id) { var request = URLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in guard error == nil else { print(error?.localizedDescription ?? "") DispatchQueue.main.async { completion(nil) } return } if let data = data, let urlString = String(data: data, encoding: .utf8) { DispatchQueue.main.async { completion(urlString) } } } task.resume() } } static func searchPodcastsByTitle(title: String, completion: @escaping (_ podcasts: [SearchPodcast]?) -> Void) { if let encodedTitle = title.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { if let url = URL(string: BASE_URL + "podcasts?title=" + encodedTitle) { var request = URLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in guard error == nil else { DispatchQueue.main.async { completion([]) } return } if let data = data { do { var searchPodcasts = [SearchPodcast]() if let podcastsJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] { for item in podcastsJSON { let searchPodcast = convertJSONToSearchPodcast(item) searchPodcasts.append(searchPodcast) } } DispatchQueue.main.async { completion(searchPodcasts) } } catch { print("Error: " + error.localizedDescription) DispatchQueue.main.async { completion([]) } } } } task.resume() } } } static func showSearchPodcastActions(searchPodcast: SearchPodcast, vc: UIViewController) { if let id = searchPodcast.id { let podcastActions = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if let _ = Podcast.podcastForId(id: id) { podcastActions.addAction(UIAlertAction(title: "Unsubscribe", style: .default, handler: { action in PVSubscriber.unsubscribeFromPodcast(podcastId: id, feedUrl: nil) })) } else if ParsingPodcasts.shared.hasMatchingId(podcastId: id) { podcastActions.addAction(UIAlertAction(title: "Unsubscribe", style: .default, handler: { action in PVSubscriber.unsubscribeFromPodcast(podcastId: id, feedUrl: nil) })) } else { podcastActions.addAction(UIAlertAction(title: "Subscribe", style: .default, handler: { action in self.authorityFeedUrlForPodcast(id: id) { feedUrl in if let feedUrl = feedUrl { PVSubscriber.subscribeToPodcast(podcastId: id, feedUrl: feedUrl) } } })) } podcastActions.addAction(UIAlertAction(title: "About", style: .default, handler: { action in vc.performSegue(withIdentifier: "Show Search Podcast", sender: "About") })) podcastActions.addAction(UIAlertAction(title: "Episodes", style: .default, handler: { action in vc.performSegue(withIdentifier: "Show Search Podcast", sender: "Episodes") })) podcastActions.addAction(UIAlertAction(title: "Clips", style: .default, handler: { action in vc.performSegue(withIdentifier: "Show Search Podcast", sender: "Clips") })) podcastActions.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) vc.present(podcastActions, animated: true, completion: nil) } } }
agpl-3.0
73c4469f670639fcb16ec9e8be027689
37.410788
148
0.4751
5.98384
false
false
false
false
alexanderedge/Toolbelt
Toolbelt/Toolbelt/AVURLAsset.swift
1
1854
// // AVURLAsset.swift // Toolbelt // // The MIT License (MIT) // // Copyright (c) 02/05/2015 Alexander G Edge // // 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 AVFoundation extension AVURLAsset { public class func posterImageFromAssetWithURL(_ url : URL!) throws -> Image { return try AVURLAsset(url: url, options: [AVURLAssetPreferPreciseDurationAndTimingKey : true]).posterImage() } public func posterImage() throws -> Image { let gen = AVAssetImageGenerator(asset: self) gen.appliesPreferredTrackTransform = true gen.requestedTimeToleranceBefore = kCMTimeZero gen.requestedTimeToleranceAfter = kCMTimeZero let cgImage = try gen.copyCGImage(at: kCMTimeZero, actualTime: nil) return Image(cgImage: cgImage); } }
mit
4de7046aa62ecaff84e92161e88e8e06
41.136364
116
0.727616
4.5
false
false
false
false
naoyashiga/CatsForInstagram
Nekobu/Media.swift
1
442
// // Media.swift // Nekobu // // Created by naoyashiga on 2015/08/15. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import Foundation struct Media { var type = "" var id = "" var lowResolutionImageURL: NSURL? var standardResolutionImageURL: NSURL? var lowResolutionBase64ImageString = "" var standardResolutionBase64ImageString = "" var webPageLinkString: String = "" var video: Video? }
mit
0d0db85aa7ddc9cc915b67fe17ad013e
21
56
0.679545
3.793103
false
false
false
false
chizcake/ReplayKitExample
ReplayKitExampleStarter/Carthage/Checkouts/CleanroomLogger/Sources/RotatingLogFileRecorder.swift
2
6759
// // RotatingLogFileRecorder.swift // CleanroomLogger // // Created by Evan Maloney on 5/14/15. // Copyright © 2015 Gilt Groupe. All rights reserved. // import Foundation /** A `LogRecorder` implementation that maintains a set of daily rotating log files, kept for a user-specified number of days. - important: A `RotatingLogFileRecorder` instance assumes full control over the log directory specified by its `directoryPath` property. Please see the initializer documentation for details. */ open class RotatingLogFileRecorder: LogRecorderBase { /** The number of days for which the receiver will retain log files before they're eligible for pruning. */ open let daysToKeep: Int /** The filesystem path to a directory where the log files will be stored. */ open let directoryPath: String private static let filenameFormatter: DateFormatter = { let fmt = DateFormatter() fmt.dateFormat = "yyyy-MM-dd'.log'" return fmt }() private var mostRecentLogTime: Date? private var currentFileRecorder: FileLogRecorder? /** Initializes a new `RotatingLogFileRecorder` instance. - warning: The `RotatingLogFileRecorder` expects to have full control over the contents of its `directoryPath`. Any file not recognized as an active log file will be deleted during the automatic pruning process, which may occur at any time. Therefore, be __extremely careful__ when constructing the value passed in as the `directoryPath`. - parameter daysToKeep: The number of days for which log files should be retained. - parameter directoryPath: The filesystem path of the directory where the log files will be stored. Please note the warning above regarding the `directoryPath`. - parameter formatters: An array of `LogFormatter`s to use for formatting log entries to be recorded by the receiver. Each formatter is consulted in sequence, and the formatted string returned by the first formatter to yield a non-`nil` value will be recorded. If every formatter returns `nil`, the log entry is silently ignored and not recorded. */ public init(daysToKeep: Int, directoryPath: String, formatters: [LogFormatter] = [ReadableLogFormatter()]) { self.daysToKeep = daysToKeep self.directoryPath = directoryPath super.init(formatters: formatters) } /** Returns a string representing the filename that will be used to store logs recorded on the given date. - parameter date: The `Date` for which the log file name is desired. - returns: The filename. */ open class func logFilename(forDate date: Date) -> String { return filenameFormatter.string(from: date) } private class func fileLogRecorder(_ date: Date, directoryPath: String, formatters: [LogFormatter]) -> FileLogRecorder? { let fileName = logFilename(forDate: date) let filePath = (directoryPath as NSString).appendingPathComponent(fileName) return FileLogRecorder(filePath: filePath, formatters: formatters) } private func fileLogRecorder(_ date: Date) -> FileLogRecorder? { return type(of: self).fileLogRecorder(date, directoryPath: directoryPath, formatters: formatters) } private func isDate(_ firstDate: Date, onSameDayAs secondDate: Date) -> Bool { let firstDateStr = type(of: self).logFilename(forDate: firstDate) let secondDateStr = type(of: self).logFilename(forDate: secondDate) return firstDateStr == secondDateStr } /** Attempts to create—if it does not already exist—the directory indicated by the `directoryPath` property. - throws: If the function fails to create a directory at `directoryPath`. */ open func createLogDirectory() throws { let url = URL(fileURLWithPath: directoryPath, isDirectory: true) try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } /** Called by the `LogReceptacle` to record the specified log message. - note: This function is only called if one of the `formatters` associated with the receiver returned a non-`nil` string for the given `LogEntry`. - parameter message: The message to record. - parameter entry: The `LogEntry` for which `message` was created. - parameter currentQueue: The GCD queue on which the function is being executed. - parameter synchronousMode: If `true`, the receiver should record the log entry synchronously and flush any buffers before returning. */ open override func record(message: String, for entry: LogEntry, currentQueue: DispatchQueue, synchronousMode: Bool) { if mostRecentLogTime == nil || !self.isDate(entry.timestamp as Date, onSameDayAs: mostRecentLogTime!) { prune() currentFileRecorder = fileLogRecorder(entry.timestamp) } mostRecentLogTime = entry.timestamp as Date currentFileRecorder?.record(message: message, for: entry, currentQueue: queue, synchronousMode: synchronousMode) } /** Deletes any expired log files (and any other detritus that may be hanging around inside our `directoryPath`). - warning: Any file within the `directoryPath` not recognized as an active log file will be deleted during pruning. */ open func prune() { // figure out what files we'd want to keep, then nuke everything else let cal = Calendar.current var date = Date() var filesToKeep = Set<String>() for _ in 0..<daysToKeep { let filename = type(of: self).logFilename(forDate: date) filesToKeep.insert(filename) date = cal.date(byAdding: .day, value: -1, to: date, wrappingComponents: true)! } do { let fileMgr = FileManager.default let filenames = try fileMgr.contentsOfDirectory(atPath: directoryPath) let pathsToRemove = filenames .filter { return !$0.hasPrefix(".") } .filter { return !filesToKeep.contains($0) } .map { return (self.directoryPath as NSString).appendingPathComponent($0) } for path in pathsToRemove { do { try fileMgr.removeItem(atPath: path) } catch { print("Error attempting to delete the unneeded file <\(path)>: \(error)") } } } catch { print("Error attempting to read directory at path <\(directoryPath)>: \(error)") } } }
mit
f7a8cf4770333f0a9f927046cbca33bd
35.117647
120
0.665976
4.901306
false
false
false
false
dcunited001/Spectra
Pod/Node/SceneGraph.swift
1
4366
// // SceneGraph.swift // Pods // // Created by David Conner on 10/11/15. // // // X3D documentation: http://www.web3d.org/specifications/X3dSchemaDocumentation3.3/x3d-3.3.html // X3D Cube Example: view-source:http://www.web3d.org/x3d/content/examples/Basic/DistributedInteractiveSimulation/TestCubeCanonical.xml // X3Dom efficient Binary Meshes: http://www.web3d.org/sites/default/files/presentations/Efficient%20Binary%20Meshes%20in%20X3DOM%20Refined/x3dom_Efficient-Binary-Meshes_behr.pdf // X3Dom docs: http://doc.x3dom.org/ // Xml3D basics: https://github.com/xml3d/xml3d.js/wiki/The-Basics-of-XML3D import Ono public class MeshData {} public class MeshDataMap {} public class NodeGroup {} public class SceneGraph { let nodeGenAttr = "spectra-node-gen" let nodeRefAttr = "spectra-node-ref" public var perspectives: [String: Perspectable] = [:] public var views: [String: WorldView] = [:] public var cameras: [String: Camable] = [:] public var nodes: [String: Node] = [:] public var nodeGroups: [String: NodeGroup] = [:] public var meshes: [String: Mesh] = [:] public var meshData: [String: MeshData] = [:] public var meshDataMap: [String: MeshDataMap] = [:] public var meshGenerators: [String: MeshGenerator] = [:] private var viewMonads: [String: (() -> WorldView)] = [:] //final? private var cameraMonads: [String: (() -> Camable)] = [:] //final? private var meshGeneratorMonads: [String: (([String: String]) -> MeshGenerator)] = [:] // resources // - buffers? (encodable data or buffer pools) // - inputs? // - textures? public init() { setDefaultMeshGeneratorMonads() } // public func loadXML(data: NSData) { // //TODO: scene graph data from xml into objects // } // public func createGeneratedNodes(generatorMap: [String:NodeGenerator], var nodeMap: SceneNodeMap) -> SceneNodeMap { // xml!.enumerateElementsWithCSS("mesh[\(nodeGenAttr)]", block: { (elem) -> Void in // let nodeGenName = elem.valueForAttribute(self.nodeGenAttr) as! String // let nodeId = elem.valueForAttribute("id") as! String // nodeMap[nodeId] = generatorMap[nodeGenName]!.generate() // }) // // return nodeMap // } // // public func createRefNodes(var nodeMap: SceneNodeMap) -> SceneNodeMap { // xml!.enumerateElementsWithCSS("mesh[\(nodeRefAttr)]", block: { (elem) -> Void in // let nodeRefName = elem.valueForAttribute(self.nodeRefAttr) as! String // let nodeId = elem.valueForAttribute("id") as! String // nodeMap[nodeId] = nodeMap[nodeRefName] // }) // // return nodeMap // } //TODO: going to try out these protocol monad lists on a few types // - so more complicated types can be instantiated via xml // - or (for view/camera) i may just want to follow the perspectiveArgs example public func registerViewMonad(key: String, monad: (() -> WorldView)) { viewMonads[key] = monad } public func getViewMonad(key: String) -> (() -> WorldView)? { return viewMonads[key] } public func registerCameraMonad(key: String, monad: (() -> Camable)) { cameraMonads[key] = monad } public func getCameraMonad(key: String) -> (() -> Camable)? { return cameraMonads[key] } public func registerMeshGeneratorMonad(key: String, monad: (([String: String]) -> MeshGenerator)) { meshGeneratorMonads[key] = monad } public func getMeshGeneratorMonad(key: String) -> (([String: String]) -> MeshGenerator)? { return meshGeneratorMonads[key] } private func setDefaultMeshGeneratorMonads() { registerMeshGeneratorMonad("basic_triangle") { (args) in return BasicTriangleGenerator(args: args) } registerMeshGeneratorMonad("quad") { (args) in return QuadGenerator(args: args) } registerMeshGeneratorMonad("cube") { (args) in return CubeGenerator(args: args) } registerMeshGeneratorMonad("cube") { (args) in return TetrahedronGenerator(args: args) } registerMeshGeneratorMonad("cube") { (args) in return OctahedronGenerator(args: args) } } }
mit
02f3b1a00d649f2c60101477cf564ddb
36.008475
178
0.632845
3.734816
false
false
false
false
shitoudev/v2ex
v2ex/v2ex.playground/Contents.swift
1
5070
//: Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" extension Double { var km: Double { return self * 1_000.0 } var m: Double { return self } func cm() -> Double { return self / 100.0 } } let oneInch = 25.4.km oneInch.m oneInch.cm() extension Int { func repetitions(task: () -> ()) { for i in 0..<self { task() } } } 3.repetitions{ println("Hello!") } protocol pro { init(someParameter:Int) var mustBeSettable: Int {get set} var fullName: String {get} func do_what() } class hello { } class hi : hello, pro { required init(someParameter: Int) { } var mustBeSettable: Int = 0 var fullName: String{ return "\(mustBeSettable)" } func do_what() { } } protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case On, Off mutating func toggle() { switch self{ case Off: self = On case On: self = Off } } } var lightSwitch = OnOffSwitch.On lightSwitch.toggle() protocol RandomNumberGenerator: class { func random() -> Double } class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) % m) return lastRandom / m } } class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6,generator: LinearCongruentialGenerator()) for _ in 1...5 { println("Random dice roll is \(d6.roll())") } protocol TextRepresentable { func asText() -> String } extension Dice : TextRepresentable { func asText() -> String { return "A \(sides)-sided dice" } } let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator()) println(d12.asText()) struct Hamster { var name: String func asText() -> String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} var hamster: TextRepresentable = Hamster(name: "Hamster!") hamster.asText() let things: [TextRepresentable] = [d12,hamster] for thing in things { thing.asText() if let dice = thing as? Dice { dice.sides } } // 协议合成 protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person(name: "mks", age: 21) wishHappyBirthday(birthdayPerson) // 可选协议 @objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } // 泛型 func swapTwoInts(inout a: Int, inout b: Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) println("someInt is now \(someInt), and anotherInt is now \(anotherInt)") func swapTwoValues<T>(inout a: T, inout b: T) { let temporaryA = a a = b b = temporaryA } swapTwoValues(&someInt, &anotherInt) struct IntStack { var items = [Int]() mutating func push(item: Int) { items.append(item) } mutating func pop() -> Int { return items.removeLast() } } struct Stack<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } } var stackItems = Stack(items: [1,2,3]) stackItems.pop() var arr = [Int:String]() for (index, value) in enumerate(arr) { } func foundIndex <T: Equatable>(array: [T], valueToFind: T) -> Int? { return nil } protocol Container { typealias ItemType mutating func append(item: ItemType) var count: Int { get } subscript(i: Int) -> ItemType { get } } struct IntsStack:Container { var items = [Int]() mutating func push(item: Int) { items.append(item) } mutating func pop() -> Int { return items.removeLast() } // Container typealias ItemType = Int mutating func append(item: Int) { items.append(item) } var count: Int { return items.count } subscript(i: Int) -> Int { return items[i] } } extension Array: Container{} // 元祖 let http200Status = (statusCode: 200, desc: "OK") let one: UInt16 = 0b00001111 let onef = ~one class A { let b: B init() { b = B() b.a = self } deinit { println("A deinit") } } class B { weak var a: A? = nil deinit { println("B deinit") } } var obj: A? = A() obj = nil
mit
f80960eb1eb833d3b0779837c6ef7306
17.898876
76
0.597305
3.638068
false
false
false
false
AngeloStavrow/Rewatch
Rewatch/UI/Helpers/PictureHelpers.swift
1
789
// // PictureHelpers.swift // Rewatch // // Created by Romain Pouclet on 2015-11-02. // Copyright © 2015 Perfectly-Cooked. All rights reserved. // import UIKit func convertToBlackAndWhite(image: UIImage) -> UIImage { let colorSpace = CGColorSpaceCreateDeviceGray() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue).rawValue let width = Int(image.size.width) let height = Int(image.size.height) let context = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, bitmapInfo) CGContextDrawImage(context, CGRect(origin: CGPointZero, size: image.size), image.CGImage) let ref = CGBitmapContextCreateImage(context) if let ref = CGImageCreateCopy(ref) { return UIImage(CGImage: ref) } return image }
mit
48db88b9217a49ec07a501b52e3b4e21
28.185185
93
0.713198
4.259459
false
false
false
false
steelwheels/KiwiControls
UnitTest/OSX/UTTerminal/PreferenceViewController.swift
1
765
/** * @file PreferenceViewController.swift * @brief Define PreferenceViewController class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiControls import CoconutData import CoconutShell import JavaScriptCore public class PreferenceViewController: KCPlaneViewController { private var mPreferenceView: KCTerminalPreferenceView? = nil public override func loadContext() -> KCView? { let termview = KCTerminalPreferenceView() mPreferenceView = termview return mPreferenceView } override public func viewWillAppear() { super.viewWillAppear() /* Update window title */ if let window = self.view.window { window.title = "Terminal Setting" } } override public func viewDidAppear() { super.viewDidAppear() } }
lgpl-2.1
689c6e689583d898a7757e123f5d85ee
20.857143
61
0.75817
4.047619
false
false
false
false
sonsongithub/numsw
Sources/numsw/Matrix/MatrixInvert.swift
1
2820
enum InvertError: Error { case IrregalValue(argument: Int) case SingularMatrix } #if os(iOS) || os(OSX) import Accelerate extension Matrix where T == Double { public func inverted() throws -> Matrix<Double> { precondition(rows == columns, "Matrix is not square.") var inMatrix: [Double] = self.elements var N: __CLPK_integer = __CLPK_integer( sqrt( Double( self.rows*self.columns ) ) ) var pivots: [__CLPK_integer] = [__CLPK_integer](repeating: 0, count: Int(N)) var workspace: [Double] = [Double](repeating: 0.0, count: Int(N)) var error: __CLPK_integer = 0 // LU decomposition dgetrf_(&N, &N, &inMatrix, &N, &pivots, &error) if error < 0 { throw InvertError.IrregalValue(argument: -Int(error)) } else if error > 0 { throw InvertError.SingularMatrix } // solve dgetri_(&N, &inMatrix, &N, &pivots, &workspace, &N, &error) if error < 0 { throw InvertError.IrregalValue(argument: -Int(error)) } else if error > 0 { throw InvertError.SingularMatrix } return Matrix<Double>(rows: rows, columns: columns, elements: inMatrix) } } extension Matrix where T == Float { public func inverted() throws -> Matrix<Float> { precondition(rows == columns, "Matrix is not square.") var inMatrix: [Float] = self.elements var N: __CLPK_integer = __CLPK_integer( sqrt( Double( self.rows*self.columns ) ) ) var pivots: [__CLPK_integer] = [__CLPK_integer](repeating: 0, count: Int(N)) var workspace: [Float] = [Float](repeating: 0.0, count: Int(N)) var error: __CLPK_integer = 0 // LU decomposition sgetrf_(&N, &N, &inMatrix, &N, &pivots, &error) if error < 0 { throw InvertError.IrregalValue(argument: -Int(error)) } else if error > 0 { throw InvertError.SingularMatrix } // solve sgetri_(&N, &inMatrix, &N, &pivots, &workspace, &N, &error) if error < 0 { throw InvertError.IrregalValue(argument: -Int(error)) } else if error > 0 { throw InvertError.SingularMatrix } return Matrix<Float>(rows: rows, columns: columns, elements: inMatrix) } } #endif
mit
0ae887f7d93d2ed319913a976440adee
36.105263
101
0.479433
4.266263
false
false
false
false
devpunk/cartesian
cartesian/View/Main/Parent/VParentBar.swift
1
5699
import UIKit class VParentBar:UIView { private weak var controller:CParent! private weak var buttonHome:VParentBarButton! private weak var buttonSettings:VParentBarButton! private weak var buttonGallery:VParentBarButton! private weak var layoutHomeLeft:NSLayoutConstraint! private let kBorderHeight:CGFloat = 1 private let kButtonsTop:CGFloat = 20 private let kButtonsWidth:CGFloat = 60 init(controller:CParent) { super.init(frame:CGRect.zero) backgroundColor = UIColor.white translatesAutoresizingMaskIntoConstraints = false self.controller = controller let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1)) let buttonHome:VParentBarButton = VParentBarButton( image:#imageLiteral(resourceName: "assetGenericDraw")) buttonHome.isSelected = true buttonHome.addTarget( self, action:#selector(actionHome(sender:)), for:UIControlEvents.touchUpInside) self.buttonHome = buttonHome let buttonSettings:VParentBarButton = VParentBarButton( image:#imageLiteral(resourceName: "assetGenericConfig")) buttonSettings.isSelected = false buttonSettings.addTarget( self, action:#selector(actionSettings(sender:)), for:UIControlEvents.touchUpInside) self.buttonSettings = buttonSettings let buttonGallery:VParentBarButton = VParentBarButton( image:#imageLiteral(resourceName: "assetGenericGallery")) buttonGallery.isSelected = false buttonGallery.addTarget( self, action:#selector(actionGallery(sender:)), for:UIControlEvents.touchUpInside) self.buttonGallery = buttonGallery addSubview(border) addSubview(buttonGallery) addSubview(buttonSettings) addSubview(buttonHome) NSLayoutConstraint.height( view:border, constant:kBorderHeight) NSLayoutConstraint.bottomToBottom( view:border, toView:self) NSLayoutConstraint.equalsHorizontal( view:border, toView:self) NSLayoutConstraint.topToTop( view:buttonHome, toView:self, constant:kButtonsTop) NSLayoutConstraint.bottomToBottom( view:buttonHome, toView:self) layoutHomeLeft = NSLayoutConstraint.leftToLeft( view:buttonHome, toView:self) NSLayoutConstraint.width( view:buttonHome, constant:kButtonsWidth) NSLayoutConstraint.topToTop( view:buttonSettings, toView:self, constant:kButtonsTop) NSLayoutConstraint.bottomToBottom( view:buttonSettings, toView:self) NSLayoutConstraint.leftToLeft( view:buttonSettings, toView:self) NSLayoutConstraint.width( view:buttonSettings, constant:kButtonsWidth) NSLayoutConstraint.topToTop( view:buttonGallery, toView:self, constant:kButtonsTop) NSLayoutConstraint.bottomToBottom( view:buttonGallery, toView:self) NSLayoutConstraint.rightToRight( view:buttonGallery, toView:self) NSLayoutConstraint.width( view:buttonGallery, constant:kButtonsWidth) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remainHome:CGFloat = width - kButtonsWidth let marginHome:CGFloat = remainHome / 2.0 layoutHomeLeft.constant = marginHome super.layoutSubviews() } //MARK: actions func actionHome(sender button:UIButton) { if !buttonHome.isSelected { let transition:CParent.TransitionHorizontal if buttonSettings.isSelected { transition = CParent.TransitionHorizontal.fromRight } else { transition = CParent.TransitionHorizontal.fromLeft } buttonHome.isSelected = true buttonSettings.isSelected = false buttonGallery.isSelected = false let controllerDraw:CDrawList = CDrawList() controller.slideTo( horizontal:transition, controller:controllerDraw) } } func actionSettings(sender button:UIButton) { if !buttonSettings.isSelected { buttonHome.isSelected = false buttonSettings.isSelected = true buttonGallery.isSelected = false let controllerSettings:CSettings = CSettings() controller.slideTo( horizontal:CParent.TransitionHorizontal.fromLeft, controller:controllerSettings) } } func actionGallery(sender button:UIButton) { if !buttonGallery.isSelected { buttonHome.isSelected = false buttonSettings.isSelected = false buttonGallery.isSelected = true let controllerGallery:CGallery = CGallery() controller.slideTo( horizontal:CParent.TransitionHorizontal.fromRight, controller:controllerGallery) } } }
mit
c0a32312607f79be58dd6231155fa770
30.142077
71
0.593087
6.037076
false
false
false
false
RajatDhasmana/rajat_appinventiv
ImageSearch/ImageSearch/ImageInfoModel.swift
1
1842
// // ImageInfoModel.swift // ImageSearch // // Created by Rajat Dhasmana on 21/02/17. // Copyright © 2017 appinventiv. All rights reserved. // import Foundation import SwiftyJSON struct ImageInfo { let id : String! var comments = 0 var downloads = 0 var favorites = 0 var likes = 0 var views = 0 var pageURL : String = "" var userImageURL : String = "" var webformatURL : String = "" var previewURL : String = "" init(withJSON json: JSON) { self.id = json["id"].stringValue self.comments = json["comments"].intValue self.downloads = json["downloads"].intValue self.favorites = json["favorites"].intValue self.likes = json["likes"].intValue self.views = json["views"].intValue self.pageURL = json["pageURL"].stringValue self.userImageURL = json["userImageURL"].stringValue self.webformatURL = json["webformatURL"].stringValue self.previewURL = json["previewURL"].stringValue } } // comments = 12; // downloads = 20875; // favorites = 80; // id = 1212400; // imageHeight = 2296; // imageWidth = 3514; // likes = 94; // pageURL = "https://pixabay.com/en/dog-water-run-movement-joy-1212400/"; // previewHeight = 97; // previewURL = "https://cdn.pixabay.com/photo/2016/02/20/17/05/dog-1212400_150.jpg"; // previewWidth = 150; // tags = "dog, water, run"; // type = photo; // user = howo; // userImageURL = "https://cdn.pixabay.com/user/2016/02/21/16-58-44-476_250x250.jpg"; // "user_id" = 1747689; // views = 30819; // webformatHeight = 418; // webformatURL = "https://pixabay.com/get/e837b00d2cf4013ed95c4518b7484096e67ee7d204b0154992f5c878aee9b1_640.jpg"; // webformatWidth = 640;
mit
589f170dd3b8c04aa70599d392acb055
26.477612
118
0.607279
3.384191
false
false
false
false
almakkyi/Weather
Weather/ViewController.swift
1
9460
// // ViewController.swift // Weather // // Created by Ibrahim Almakky on 16/11/2014. // Copyright (c) 2014 Ibrahim Almakky. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var mainWeatherImage: UIImageView! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var currentTempLabel: UILabel! @IBOutlet weak var weatherTable: UITableView! @IBOutlet weak var pageController: UIPageControl! @IBOutlet var left: UISwipeGestureRecognizer! @IBOutlet var right: UISwipeGestureRecognizer! var locations:[Location] = [] var weekDays:[String] = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] var mainWeatherIcons: [String: String] = ["01d": "sunny", "02d": "sunny_to_cloudy", "03d": "overcast", "04d": "overcast", "09d": "heavy_rain", "10d": "sun_rain", "11d": "thunder", "13d": "snowy", "50d": "fog", "01n": "full_moon", "02n": "overcast", "03n": "overcast", "04n": "overcast", "09n": "heavy_rain", "10n": "showers", "11n": "thunder", "13n": "snowy", "50n": "fog"] var weatehrInfo = [WeatherInfo]() var threads:Int = 0 var img = UIImage(named: "heavy_rain") var weekDay:Int = 0 var dayornight:Int = 1 // Refresh the weather var refreshControl:UIRefreshControl! lazy var managedObjectContext : NSManagedObjectContext? = { let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate if let managedObjectContext = appDelegate.managedObjectContext { return managedObjectContext } else { return nil } }() override func viewDidLoad() { super.viewDidLoad() self.getLocations() // Hide the content when the app starts until the data loads self.weatherTable.alpha = 0.0 self.mainWeatherImage.alpha = 0.0 self.currentTempLabel.alpha = 0.0 self.locationLabel.alpha = 0.0 // Adding gestures for swiping left and right self.view.addGestureRecognizer(self.right) self.view.addGestureRecognizer(self.left) // Page indicator self.pageController.numberOfPages = locations.count self.pageController.currentPage = 0 // set up the attributed text for the refresh control var refreshAttributedString = NSMutableAttributedString(string: "Pull To Refresh") refreshAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSRange(location: 0, length: refreshAttributedString.length)) // Settign up refresh self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(attributedString: refreshAttributedString) self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.weatherTable.addSubview(refreshControl) self.getWeather() self.getDay() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bg")!) var nib = UINib(nibName: "CustomTableViewCell", bundle: nil) weatherTable.registerNib(nib, forCellReuseIdentifier: "customCell") NSNotificationCenter.defaultCenter().addObserver(self, selector: "reload:", name: "reloadMain", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return weatehrInfo.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:CustomTableViewCell = self.weatherTable.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell cell.loadItem(weekDays[(weekDay + indexPath.row)%7], icon: weatehrInfo[indexPath.row].icon, maxTemp: weatehrInfo[indexPath.row].maxTemp, minTemp: weatehrInfo[indexPath.row].minTemp) return cell } @IBAction func swipeLeft(sender: UISwipeGestureRecognizer) { println("swipeLeft") if self.pageController.currentPage < self.pageController.numberOfPages - 1{ UIView.animateWithDuration(0.3, animations: { println("animate") self.weatherTable.alpha = 0.0 self.mainWeatherImage.alpha = 0.0 self.currentTempLabel.alpha = 0.0 self.locationLabel.alpha = 0.0 }, completion: { (value: Bool) in self.pageController.currentPage++ println("page: \(self.pageController.currentPage)") self.setMain() self.getWeather() }) } } @IBAction func swipeRight(sender: UISwipeGestureRecognizer) { println("swipeRight") if self.pageController.currentPage > 0 { UIView.animateWithDuration(0.3, animations: { println("animate") self.weatherTable.alpha = 0.0 self.mainWeatherImage.alpha = 0.0 self.currentTempLabel.alpha = 0.0 self.locationLabel.alpha = 0.0 }, completion: { (value: Bool) in self.pageController.currentPage-- println("page: \(self.pageController.currentPage)") self.setMain() self.getWeather() }) } } func getWeather() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.threads++ let location = "\(self.locations[self.pageController.currentPage].city),\(self.locations[self.pageController.currentPage].country)" Weather.getWeather(location, completion: {(result: Array<WeatherInfo>) in self.weatehrInfo = result dispatch_async(dispatch_get_main_queue(), { self.weatherTable.reloadData() self.threads-- if(self.threads == 0) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false self.setMain() } UIView.animateWithDuration(0.3, animations: { self.weatherTable.alpha = 1.0 self.mainWeatherImage.alpha = 1.0 self.currentTempLabel.alpha = 1.0 self.locationLabel.alpha = 1.0 }) }) }) } func getDay() { let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(NSCalendarUnit.CalendarUnitWeekday, fromDate: date) let weekday = components.weekday self.weekDay = weekday } func setMain() { self.locationLabel.text = locations[self.pageController.currentPage].city self.currentTempLabel.text = "\(self.weatehrInfo[self.pageController.currentPage].dayTemp)°" if (Array(weatehrInfo[0].iconCode)[Array(weatehrInfo[0].iconCode).count-1] == "d") { // println("Day") self.dayornight = 1 //self.view.backgroundColor = UIColor(patternImage: UIImage(named: "clearSky.jpg")!) } else if (Array(weatehrInfo[0].iconCode)[Array(weatehrInfo[0].iconCode).count-1] == "n") { // println("Night") self.dayornight = 0 //self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bg.png")!) } if let mainIconName = mainWeatherIcons.indexForKey(weatehrInfo[0].iconCode) { // println(mainWeatherIcons[mainIconName].1) self.mainWeatherImage.image = UIImage(named: "\(mainWeatherIcons[mainIconName].1)") } } func getLocations() { let fetchRequest = NSFetchRequest(entityName: "Location") if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Location] { self.locations = fetchResults println("locations.count=\(locations.count)") } } func reload(notification: NSNotification) { self.getLocations() // Hide the content when the app starts until the data loads self.weatherTable.alpha = 0.0 self.mainWeatherImage.alpha = 0.0 self.currentTempLabel.alpha = 0.0 self.locationLabel.alpha = 0.0 // Page indicator self.pageController.numberOfPages = locations.count self.pageController.currentPage = 0 self.getWeather() self.getDay() } func refresh(sender: AnyObject) { self.getWeather() self.getDay() self.refreshControl.endRefreshing() } /* // 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. } */ }
apache-2.0
24d10c28113de50f2abfb76f9fa22c83
39.423077
377
0.622159
4.843318
false
false
false
false