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
lzpfmh/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Group/AddParticipantViewController.swift
1
2183
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class AddParticipantViewController: ContactsContentViewController, ContactsContentViewControllerDelegate { init (gid: Int) { super.init() self.gid = gid self.delegate = self } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = localized("GroupAddParticipantTitle") navigationItem.leftBarButtonItem = UIBarButtonItem( title: localized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss") } func willAddContacts(controller: ContactsContentViewController, section: ACManagedSection) { section.custom { (r:ACCustomRow<ContactActionCell>) -> () in r.height = 56 r.closure = { (cell) -> () in cell.bind("ic_invite_user", actionTitle: NSLocalizedString("GroupAddParticipantUrl", comment: "Action Title")) } r.selectAction = { () -> Bool in self.navigateNext(InviteLinkViewController(gid: self.gid), removeCurrent: false) return false } } } func contactDidBind(controller: ContactsContentViewController, contact: ACContact, cell: ContactCell) { cell.bindDisabled(isAlreadyMember(contact.uid)) } func contactDidTap(controller: ContactsContentViewController, contact: ACContact) -> Bool { if !isAlreadyMember(contact.uid) { self.executeSafeOnlySuccess(Actor.inviteMemberCommandWithGid(jint(gid), withUid: jint(contact.uid))) { (val) -> () in self.dismiss() } } return true } func isAlreadyMember(uid: jint) -> Bool { let members: [ACGroupMember] = group.getMembersModel().get().toArray().toSwiftArray() for m in members { if m.uid == uid { return true } } return false } }
mit
dd1b9b927bb5f5dcea7ee4f6dc8ebe5a
31.58209
129
0.589098
4.972665
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Data Models/Weather Information Models/WeatherInformationDTO.swift
1
5579
// // WeatherDataDTO.swift // NearbyWeather // // Created by Erik Maximilian Martens on 14.04.17. // Copyright © 2017 Erik Maximilian Martens. All rights reserved. // import UIKit import CoreLocation /** * OWMWeatherDTO is used to parse the JSON response from the server * It is constructed in a way so that only the required information is parsed * This DTO therefore does not exactly mirror the server response */ struct WeatherInformationListDTO: Codable { var list: [WeatherInformationDTO] enum CodingKeys: String, CodingKey { case list } } struct WeatherInformationDTO: Codable, Equatable { struct CoordinatesDTO: Codable, Equatable { var latitude: Double? var longitude: Double? enum CodingKeys: String, CodingKey { case latitude = "lat" case longitude = "lon" } init(from decoder: Decoder) { let values = try? decoder.container(keyedBy: CodingKeys.self) latitude = try? values?.decodeIfPresent(Double.self, forKey: .latitude) longitude = try? values?.decodeIfPresent(Double.self, forKey: .longitude) } } struct WeatherConditionDTO: Codable, Equatable { var identifier: Int? var conditionName: String? var conditionDescription: String? var conditionIconCode: String? enum CodingKeys: String, CodingKey { case identifier = "id" case conditionName = "main" case conditionDescription = "description" case conditionIconCode = "icon" } init(from decoder: Decoder) { let values = try? decoder.container(keyedBy: CodingKeys.self) identifier = try? values?.decodeIfPresent(Int.self, forKey: .identifier) conditionName = try? values?.decodeIfPresent(String.self, forKey: .conditionName) conditionDescription = try? values?.decodeIfPresent(String.self, forKey: .conditionDescription) conditionIconCode = try? values?.decodeIfPresent(String.self, forKey: .conditionIconCode) } } struct AtmosphericInformationDTO: Codable, Equatable { var temperatureKelvin: Double? var pressurePsi: Double? var humidity: Double? enum CodingKeys: String, CodingKey { case temperatureKelvin = "temp" case pressurePsi = "pressure" case humidity } init(from decoder: Decoder) { let values = try? decoder.container(keyedBy: CodingKeys.self) temperatureKelvin = try? values?.decodeIfPresent(Double.self, forKey: .temperatureKelvin) pressurePsi = try? values?.decodeIfPresent(Double.self, forKey: .pressurePsi) humidity = try? values?.decodeIfPresent(Double.self, forKey: .humidity) } } struct WindInformationDTO: Codable, Equatable { var windspeed: Double? var degrees: Double? enum CodingKeys: String, CodingKey { case windspeed = "speed" case degrees = "deg" } init(from decoder: Decoder) { let values = try? decoder.container(keyedBy: CodingKeys.self) windspeed = try? values?.decodeIfPresent(Double.self, forKey: .windspeed) degrees = try? values?.decodeIfPresent(Double.self, forKey: .degrees) } } struct CloudCoverageDTO: Codable, Equatable { var coverage: Double? enum CodingKeys: String, CodingKey { case coverage = "all" } init(from decoder: Decoder) { let values = try? decoder.container(keyedBy: CodingKeys.self) coverage = try? values?.decodeIfPresent(Double.self, forKey: .coverage) } } struct DayTimeInformationDTO: Codable, Equatable { /// multi location weather data does not contain this information var sunrise: Double? var sunset: Double? enum CodingKeys: String, CodingKey { case sunrise case sunset } init(from decoder: Decoder) { let values = try? decoder.container(keyedBy: CodingKeys.self) sunrise = try? values?.decodeIfPresent(Double.self, forKey: .sunrise) sunset = try? values?.decodeIfPresent(Double.self, forKey: .sunset) } } var stationIdentifier: Int var stationName: String var coordinates: CoordinatesDTO var weatherCondition: [WeatherConditionDTO] var atmosphericInformation: AtmosphericInformationDTO var windInformation: WindInformationDTO var cloudCoverage: CloudCoverageDTO var dayTimeInformation: DayTimeInformationDTO enum CodingKeys: String, CodingKey { case stationIdentifier = "id" case stationName = "name" case coordinates = "coord" case weatherCondition = "weather" case atmosphericInformation = "main" case windInformation = "wind" case cloudCoverage = "clouds" case dayTimeInformation = "sys" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.stationIdentifier = try values.decode(Int.self, forKey: .stationIdentifier) self.stationName = try values.decode(String.self, forKey: .stationName) self.coordinates = try values.decode(CoordinatesDTO.self, forKey: .coordinates) self.weatherCondition = try values.decode([WeatherConditionDTO].self, forKey: .weatherCondition) self.atmosphericInformation = try values.decode(AtmosphericInformationDTO.self, forKey: .atmosphericInformation) self.windInformation = try values.decode(WindInformationDTO.self, forKey: .windInformation) self.cloudCoverage = try values.decode(CloudCoverageDTO.self, forKey: .cloudCoverage) self.dayTimeInformation = try values.decode(DayTimeInformationDTO.self, forKey: .dayTimeInformation) } }
mit
9c4109c52793c476fa5fcc88a27fa4db
31.811765
116
0.701506
4.568387
false
false
false
false
kemalenver/SwiftHackerRank
Algorithms/Strings.playground/Pages/Strings - Sherlock and Valid String.xcplaygroundpage/Contents.swift
1
1354
import Foundation var inputs = ["hfchdkkbfifgbgebfaahijchgeeeiagkadjfcbekbdaifchkjfejckbiiihegacfbchdihkgbkbddgaefhkdgccjejjaajgijdkd"] // YES func readLine() -> String? { let next = inputs.first inputs.removeFirst() return next } func checkPossible(input: String.UTF8View) -> Bool { var frequency = [Int](repeating: 0, count: 26) for character in input { let idx = Int(character - 97) frequency[idx] += 1 } var lowestFrequency = 0 var highestFrequency = 0 var changesMadeToLowest = 0 var changesMadeToHighest = 0 for i in 0..<26 { if frequency[i] != 0 { if frequency[i] < lowestFrequency { lowestFrequency = frequency[i] } if frequency[i] > highestFrequency { highestFrequency = frequency[i] } if frequency[i] > lowestFrequency { changesMadeToLowest += 1 } if frequency[i] < highestFrequency { changesMadeToHighest += 1 } } } return changesMadeToLowest <= 1 || changesMadeToHighest <= 1 } let input = readLine()!.utf8 if checkPossible(input: input) { print("YES") } else { print("NO") }
mit
0d8cbc2299a1da559cd971a249166578
20.492063
124
0.543575
4.298413
false
false
false
false
lijian5509/KnowLedgeSummarize
李健凡iOS知识总结 /ContactsFR-读取联系人/ContactsFR-读取联系人/ContactsViewController.swift
1
5140
// // ContactsViewController.swift // ContactsFR-读取联系人 // // Created by mini on 15/10/19. // Copyright © 2015年 mini. All rights reserved. // import UIKit import Contacts import ContactsUI class ContactsViewController: UITableViewController,CNContactPickerDelegate { var contacts = [CNContact]() override func viewDidLoad() { super.viewDidLoad() //设置右导航栏按钮 self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Show Picker", style:UIBarButtonItemStyle.Plain, target: self, action:"showPicker:") //获取通讯录数据信息 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in self.contacts = self.findContacts() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } } //获取通讯录数据信息 func findContacts() -> [CNContact] { let store = CNContactStore() //CNContactStore 是一个用来读取和保存联系人的新的类 //创建一个指定条件的请求,通过这个 query 的请求去获取某些结果。创建一个 CNContactFetchRequest ,我们可以通过设置 contact keys 的数组,来获取我们需要的结果。 let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactImageDataKey, CNContactPhoneNumbersKey] let fetchFRequest = CNContactFetchRequest(keysToFetch: keysToFetch) var contacts = [CNContact]() do { //从 CNContactStore 中遍历所有符合我们需求的联系人 try! store.enumerateContactsWithFetchRequest(fetchFRequest, usingBlock: { (let contact, let stop) -> Void in contacts.append(contact) }) } catch let error as NSError { print(error.localizedDescription) } return contacts } // ContactsUI 选择联系人 func showPicker(sender : UIBarButtonItem) { let contactPicker = CNContactPickerViewController() contactPicker.delegate = self contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey] self.presentViewController(contactPicker, animated: true, completion: nil) } // ContactsUI 选择后回调 func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) { let contact = contactProperty.contact let phoneNumber = contactProperty.value as! CNPhoneNumber print(contact.givenName) print(phoneNumber.stringValue) } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.Delete } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { self.contacts.removeAtIndex(indexPath.row) self.tableView .reloadData() }else { } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) let contact = contacts[indexPath.row] as CNContact cell.textLabel?.text = "\(contact.givenName) \(contact.familyName)" return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { let viewC = segue.destinationViewController as! ViewController if let indexpath = self.tableView.indexPathForSelectedRow { let object = self.contacts[indexpath.row] viewC.contact = object } viewC.navigationItem.leftItemsSupplementBackButton = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
f948fdde4256f8f1eb585a9da86db60a
34.100719
157
0.657102
5.550626
false
false
false
false
AlphaJian/LarsonApp
LarsonApp/LarsonApp/View/MKButton/MKLayer.swift
2
7814
// // MKLayer.swift // MaterialKit // // Created by Le Van Nghia on 11/15/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit import QuartzCore public enum MKTimingFunction { case Linear case EaseIn case EaseOut case Custom(Float, Float, Float, Float) public var function: CAMediaTimingFunction { switch self { case .Linear: return CAMediaTimingFunction(name: "linear") case .EaseIn: return CAMediaTimingFunction(name: "easeIn") case .EaseOut: return CAMediaTimingFunction(name: "easeOut") case .Custom(let cpx1, let cpy1, let cpx2, let cpy2): return CAMediaTimingFunction(controlPoints: cpx1, cpy1, cpx2, cpy2) } } } public enum MKRippleLocation { case Center case Left case Right case TapLocation } public class MKLayer { private var superLayer: CALayer! private let rippleLayer = CALayer() private let backgroundLayer = CALayer() private let maskLayer = CAShapeLayer() public var rippleLocation: MKRippleLocation = .TapLocation { didSet { let origin: CGPoint? let sw = superLayer.bounds.width let sh = superLayer.bounds.height switch rippleLocation { case .Center: origin = CGPoint(x: sw/2, y: sh/2) case .Left: origin = CGPoint(x: sw*0.25, y: sh/2) case .Right: origin = CGPoint(x: sw*0.75, y: sh/2) default: origin = nil } if let origin = origin { setCircleLayerLocationAt(center: origin) } } } public var ripplePercent: Float = 0.9 { didSet { if ripplePercent > 0 { let sw = superLayer.bounds.width let sh = superLayer.bounds.height let circleSize = CGFloat(max(sw, sh)) * CGFloat(ripplePercent) let circleCornerRadius = circleSize/2 rippleLayer.cornerRadius = circleCornerRadius setCircleLayerLocationAt(center: CGPoint(x: sw/2, y: sh/2)) } } } public init(superLayer: CALayer) { self.superLayer = superLayer let sw = superLayer.bounds.width let sh = superLayer.bounds.height // background layer backgroundLayer.frame = superLayer.bounds backgroundLayer.opacity = 0.0 superLayer.addSublayer(backgroundLayer) // ripple layer let circleSize = CGFloat(max(sw, sh)) * CGFloat(ripplePercent) let rippleCornerRadius = circleSize/2 rippleLayer.opacity = 0.0 rippleLayer.cornerRadius = rippleCornerRadius setCircleLayerLocationAt(center: CGPoint(x: sw/2, y: sh/2)) backgroundLayer.addSublayer(rippleLayer) // mask layer setMaskLayerCornerRadius(cornerRadius: superLayer.cornerRadius) backgroundLayer.mask = maskLayer } public func superLayerDidResize() { CATransaction.begin() CATransaction.setDisableActions(true) backgroundLayer.frame = superLayer.bounds setMaskLayerCornerRadius(cornerRadius: superLayer.cornerRadius) CATransaction.commit() setCircleLayerLocationAt(center: CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2)) } public func enableOnlyCircleLayer() { backgroundLayer.removeFromSuperlayer() superLayer.addSublayer(rippleLayer) } public func setBackgroundLayerColor(color: UIColor) { backgroundLayer.backgroundColor = color.cgColor } public func setCircleLayerColor(color: UIColor) { rippleLayer.backgroundColor = color.cgColor } public func didChangeTapLocation(location: CGPoint) { if rippleLocation == .TapLocation { setCircleLayerLocationAt(center: location) } } public func setMaskLayerCornerRadius(cornerRadius: CGFloat) { maskLayer.path = UIBezierPath(roundedRect: backgroundLayer.bounds, cornerRadius: cornerRadius).cgPath } public func enableMask(enable: Bool = true) { backgroundLayer.mask = enable ? maskLayer : nil } public func setBackgroundLayerCornerRadius(cornerRadius: CGFloat) { backgroundLayer.cornerRadius = cornerRadius } private func setCircleLayerLocationAt(center: CGPoint) { let bounds = superLayer.bounds let width = bounds.width let height = bounds.height let subSize = CGFloat(max(width, height)) * CGFloat(ripplePercent) let subX = center.x - subSize/2 let subY = center.y - subSize/2 // disable animation when changing layer frame CATransaction.begin() CATransaction.setDisableActions(true) rippleLayer.cornerRadius = subSize / 2 rippleLayer.frame = CGRect(x: subX, y: subY, width: subSize, height: subSize) CATransaction.commit() } // MARK - Animation public func animateScaleForCircleLayer(fromScale: Float, toScale: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { let rippleLayerAnim = CABasicAnimation(keyPath: "transform.scale") rippleLayerAnim.fromValue = fromScale rippleLayerAnim.toValue = toScale let opacityAnim = CABasicAnimation(keyPath: "opacity") opacityAnim.fromValue = 1.0 opacityAnim.toValue = 0.0 let groupAnim = CAAnimationGroup() groupAnim.duration = duration groupAnim.timingFunction = timingFunction.function groupAnim.isRemovedOnCompletion = false groupAnim.fillMode = kCAFillModeForwards groupAnim.animations = [rippleLayerAnim, opacityAnim] rippleLayer.add(groupAnim, forKey: nil) } public func animateAlphaForBackgroundLayer(timingFunction: MKTimingFunction, duration: CFTimeInterval) { let backgroundLayerAnim = CABasicAnimation(keyPath: "opacity") backgroundLayerAnim.fromValue = 1.0 backgroundLayerAnim.toValue = 0.0 backgroundLayerAnim.duration = duration backgroundLayerAnim.timingFunction = timingFunction.function backgroundLayer.add(backgroundLayerAnim, forKey: nil) } public func animateSuperLayerShadow(fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { animateShadowForLayer(layer: superLayer, fromRadius: fromRadius, toRadius: toRadius, fromOpacity: fromOpacity, toOpacity: toOpacity, timingFunction: timingFunction, duration: duration) } public func animateMaskLayerShadow() { } private func animateShadowForLayer(layer: CALayer, fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { let radiusAnimation = CABasicAnimation(keyPath: "shadowRadius") radiusAnimation.fromValue = fromRadius radiusAnimation.toValue = toRadius let opacityAnimation = CABasicAnimation(keyPath: "shadowOpacity") opacityAnimation.fromValue = fromOpacity opacityAnimation.toValue = toOpacity let groupAnimation = CAAnimationGroup() groupAnimation.duration = duration groupAnimation.timingFunction = timingFunction.function groupAnimation.isRemovedOnCompletion = false groupAnimation.fillMode = kCAFillModeForwards groupAnimation.animations = [radiusAnimation, opacityAnimation] layer.add(groupAnimation, forKey: nil) } public func removeAllAnimations() { self.backgroundLayer.removeAllAnimations() self.rippleLayer.removeAllAnimations() } }
apache-2.0
580011becadc44a68e2c144b7bff56f7
33.883929
194
0.666496
5.46816
false
false
false
false
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/MainWibo/Tools/Emoticon/FindEmoticon.swift
1
2496
// // FindEmoticon.swift // LHBWeibo // // Created by LHB on 16/8/30. // Copyright © 2016年 LHB. All rights reserved. // import UIKit class FindEmoticon: NSObject { // MARK:- 设计单例对象 static let shareIntance : FindEmoticon = FindEmoticon() // MARK:- 表情属性 private lazy var manager : EmoticonManager = EmoticonManager() // 查找属性字符串的方法 func findAttrString(statusText : String?, font : UIFont) -> NSMutableAttributedString? { // 0.如果statusText没有值,则直接返回nil guard let statusText = statusText else { return nil } // 1.创建匹配规则 let pattern = "\\[.*?\\]" // 匹配表情 // 2.创建正则表达式对象 guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return nil } // 3.开始匹配 let results = regex.matchesInString(statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count)) // 4.获取结果 let attrMStr = NSMutableAttributedString(string: statusText) for var i = results.count - 1; i >= 0; i -= 1 {//i-- // 4.0.获取结果 let result = results[i] // 4.1.获取chs let chs = (statusText as NSString).substringWithRange(result.range) // 4.2.根据chs,获取图片的路径 guard let pngPath = findPngPath(chs) else { return nil } // 4.3.创建属性字符串 let attachment = NSTextAttachment() attachment.image = UIImage(contentsOfFile: pngPath) attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight) let attrImageStr = NSAttributedString(attachment: attachment) // 4.4.将属性字符串替换到来源的文字位置 attrMStr.replaceCharactersInRange(result.range, withAttributedString: attrImageStr) } // 返回结果 return attrMStr } private func findPngPath(chs : String) -> String? { for package in manager.packages { for emoticon in package.emoticons { if emoticon.chs == chs { return emoticon.pngPath } } } return nil } }
apache-2.0
881c8ab1c5757310b75fdec13c99e88c
29.197368
134
0.543791
4.645749
false
false
false
false
wordlessj/Bamboo
Source/Auto/Expression/Group.swift
1
2331
// // Group.swift // Bamboo // // Copyright (c) 2017 Javier Zhang (https://wordlessj.github.io/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation var shouldActivate = true class ConstraintStack { static let shared = ConstraintStack() private var constraints = [[NSLayoutConstraint]]() func push() { constraints.append([NSLayoutConstraint]()) } func pop() -> [NSLayoutConstraint] { return constraints.removeLast() } func append(_ constraint: NSLayoutConstraint) { for index in constraints.indices { constraints[index].append(constraint) } } } /// Group constraints created in the closure. /// When nested, the outer function will return constraints including the ones created in inner functions. /// /// - parameters: /// - activated: Should activate constraints, defaults to `true`. /// - constraints: Create constraints. /// - returns: Constraints created in the closure. @discardableResult public func group(activated: Bool = true, constraints: () -> ()) -> [NSLayoutConstraint] { let oldActivate = shouldActivate shouldActivate = activated ConstraintStack.shared.push() constraints() shouldActivate = oldActivate return ConstraintStack.shared.pop() }
mit
9fc6db49bc2f95696591fb0f7a376f0f
34.861538
106
0.717289
4.552734
false
false
false
false
wagnersouz4/replay
Replay/ReplayTests/Models/IntroContentTests.swift
1
2074
// // IntroContentTests.swift // Replay // // Created by Wagner Souza on 30/03/17. // Copyright © 2017 Wagner Souza. All rights reserved. // import Quick import Nimble @testable import Replay class IntroContentTests: QuickSpec { override func spec() { it("should create a movie as a IntroContent from a JSON") { let id = 1 let title = "Movie ABC" let posterPath = "/image1.jpg" let movieData: [String: Any] = ["id": id, "poster_path": posterPath, "title": title] guard let content = IntroContent(json: movieData) else { return fail() } expect(content.contentId) == id expect(content.description) == title expect(content.imagePath) == posterPath } it("should create a celebrity as a IntroContent from a JSON") { let id = 2 let name = "Elijah Wood" let profilePath = "/profile.jpg" let celebrityData: [String: Any] = ["id": id, "name": name, "profile_path": profilePath] guard let content = IntroContent(json: celebrityData) else { return fail() } expect(content.contentId) == id expect(content.description) == name expect(content.imagePath) == profilePath } it("should create a tv-show as a IntroContent form a JSON") { let id = 3 let name = "Lucifer" let posterPath = "/poster.jpg" let showData: [String: Any] = ["id": id, "name": name, "poster_path": posterPath] guard let content = IntroContent(json: showData) else { return fail() } expect(content.contentId) == id expect(content.description) == name expect(content.imagePath) == posterPath } } }
mit
8299c5b3dfd6695c728df4c2e4f1d3e4
31.904762
88
0.502653
4.877647
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Array/400_NthDigit.swift
1
938
// // 400_NthDigit.swift // LeetcodeSwift // // Created by yansong li on 2016-11-26. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:400 Nth Digit URL: https://leetcode.com/problems/nth-digit/ Space: O(lgN) Time: O(1) */ class NthDigit_Solution { func findNthDigit(_ n: Int) -> Int { // Firstly, find the len for that nth number. var len = 1 var count = 9 var remainedN = n var start = 1 while remainedN > len * count { remainedN -= len * count len = len + 1 count = count * 10 start = start * 10 } // Secondly, find the number the Nth digit belongs to. start += (remainedN - 1) / len let startString = String(start) // Thirdly, find the character the Nth digit of that finded number. let indexedCharacter = [Character](startString.characters)[(remainedN - 1) % len] return Int(String(indexedCharacter))! } }
mit
2ee2079618ec12decfa87410410c95e6
23.657895
85
0.631804
3.382671
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Redshift/Redshift_Error.swift
1
30812
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Redshift public struct RedshiftErrorType: AWSErrorType { enum Code: String { case accessToSnapshotDeniedFault = "AccessToSnapshotDenied" case authorizationAlreadyExistsFault = "AuthorizationAlreadyExists" case authorizationNotFoundFault = "AuthorizationNotFound" case authorizationQuotaExceededFault = "AuthorizationQuotaExceeded" case batchDeleteRequestSizeExceededFault = "BatchDeleteRequestSizeExceeded" case batchModifyClusterSnapshotsLimitExceededFault = "BatchModifyClusterSnapshotsLimitExceededFault" case bucketNotFoundFault = "BucketNotFoundFault" case clusterAlreadyExistsFault = "ClusterAlreadyExists" case clusterNotFoundFault = "ClusterNotFound" case clusterOnLatestRevisionFault = "ClusterOnLatestRevision" case clusterParameterGroupAlreadyExistsFault = "ClusterParameterGroupAlreadyExists" case clusterParameterGroupNotFoundFault = "ClusterParameterGroupNotFound" case clusterParameterGroupQuotaExceededFault = "ClusterParameterGroupQuotaExceeded" case clusterQuotaExceededFault = "ClusterQuotaExceeded" case clusterSecurityGroupAlreadyExistsFault = "ClusterSecurityGroupAlreadyExists" case clusterSecurityGroupNotFoundFault = "ClusterSecurityGroupNotFound" case clusterSecurityGroupQuotaExceededFault = "QuotaExceeded.ClusterSecurityGroup" case clusterSnapshotAlreadyExistsFault = "ClusterSnapshotAlreadyExists" case clusterSnapshotNotFoundFault = "ClusterSnapshotNotFound" case clusterSnapshotQuotaExceededFault = "ClusterSnapshotQuotaExceeded" case clusterSubnetGroupAlreadyExistsFault = "ClusterSubnetGroupAlreadyExists" case clusterSubnetGroupNotFoundFault = "ClusterSubnetGroupNotFoundFault" case clusterSubnetGroupQuotaExceededFault = "ClusterSubnetGroupQuotaExceeded" case clusterSubnetQuotaExceededFault = "ClusterSubnetQuotaExceededFault" case copyToRegionDisabledFault = "CopyToRegionDisabledFault" case dependentServiceRequestThrottlingFault = "DependentServiceRequestThrottlingFault" case dependentServiceUnavailableFault = "DependentServiceUnavailableFault" case eventSubscriptionQuotaExceededFault = "EventSubscriptionQuotaExceeded" case hsmClientCertificateAlreadyExistsFault = "HsmClientCertificateAlreadyExistsFault" case hsmClientCertificateNotFoundFault = "HsmClientCertificateNotFoundFault" case hsmClientCertificateQuotaExceededFault = "HsmClientCertificateQuotaExceededFault" case hsmConfigurationAlreadyExistsFault = "HsmConfigurationAlreadyExistsFault" case hsmConfigurationNotFoundFault = "HsmConfigurationNotFoundFault" case hsmConfigurationQuotaExceededFault = "HsmConfigurationQuotaExceededFault" case inProgressTableRestoreQuotaExceededFault = "InProgressTableRestoreQuotaExceededFault" case incompatibleOrderableOptions = "IncompatibleOrderableOptions" case insufficientClusterCapacityFault = "InsufficientClusterCapacity" case insufficientS3BucketPolicyFault = "InsufficientS3BucketPolicyFault" case invalidClusterParameterGroupStateFault = "InvalidClusterParameterGroupState" case invalidClusterSecurityGroupStateFault = "InvalidClusterSecurityGroupState" case invalidClusterSnapshotScheduleStateFault = "InvalidClusterSnapshotScheduleState" case invalidClusterSnapshotStateFault = "InvalidClusterSnapshotState" case invalidClusterStateFault = "InvalidClusterState" case invalidClusterSubnetGroupStateFault = "InvalidClusterSubnetGroupStateFault" case invalidClusterSubnetStateFault = "InvalidClusterSubnetStateFault" case invalidClusterTrackFault = "InvalidClusterTrack" case invalidElasticIpFault = "InvalidElasticIpFault" case invalidHsmClientCertificateStateFault = "InvalidHsmClientCertificateStateFault" case invalidHsmConfigurationStateFault = "InvalidHsmConfigurationStateFault" case invalidReservedNodeStateFault = "InvalidReservedNodeState" case invalidRestoreFault = "InvalidRestore" case invalidRetentionPeriodFault = "InvalidRetentionPeriodFault" case invalidS3BucketNameFault = "InvalidS3BucketNameFault" case invalidS3KeyPrefixFault = "InvalidS3KeyPrefixFault" case invalidScheduleFault = "InvalidSchedule" case invalidScheduledActionFault = "InvalidScheduledAction" case invalidSnapshotCopyGrantStateFault = "InvalidSnapshotCopyGrantStateFault" case invalidSubnet = "InvalidSubnet" case invalidSubscriptionStateFault = "InvalidSubscriptionStateFault" case invalidTableRestoreArgumentFault = "InvalidTableRestoreArgument" case invalidTagFault = "InvalidTagFault" case invalidUsageLimitFault = "InvalidUsageLimit" case invalidVPCNetworkStateFault = "InvalidVPCNetworkStateFault" case limitExceededFault = "LimitExceededFault" case numberOfNodesPerClusterLimitExceededFault = "NumberOfNodesPerClusterLimitExceeded" case numberOfNodesQuotaExceededFault = "NumberOfNodesQuotaExceeded" case reservedNodeAlreadyExistsFault = "ReservedNodeAlreadyExists" case reservedNodeAlreadyMigratedFault = "ReservedNodeAlreadyMigrated" case reservedNodeNotFoundFault = "ReservedNodeNotFound" case reservedNodeOfferingNotFoundFault = "ReservedNodeOfferingNotFound" case reservedNodeQuotaExceededFault = "ReservedNodeQuotaExceeded" case resizeNotFoundFault = "ResizeNotFound" case resourceNotFoundFault = "ResourceNotFoundFault" case sNSInvalidTopicFault = "SNSInvalidTopic" case sNSNoAuthorizationFault = "SNSNoAuthorization" case sNSTopicArnNotFoundFault = "SNSTopicArnNotFound" case scheduleDefinitionTypeUnsupportedFault = "ScheduleDefinitionTypeUnsupported" case scheduledActionAlreadyExistsFault = "ScheduledActionAlreadyExists" case scheduledActionNotFoundFault = "ScheduledActionNotFound" case scheduledActionQuotaExceededFault = "ScheduledActionQuotaExceeded" case scheduledActionTypeUnsupportedFault = "ScheduledActionTypeUnsupported" case snapshotCopyAlreadyDisabledFault = "SnapshotCopyAlreadyDisabledFault" case snapshotCopyAlreadyEnabledFault = "SnapshotCopyAlreadyEnabledFault" case snapshotCopyDisabledFault = "SnapshotCopyDisabledFault" case snapshotCopyGrantAlreadyExistsFault = "SnapshotCopyGrantAlreadyExistsFault" case snapshotCopyGrantNotFoundFault = "SnapshotCopyGrantNotFoundFault" case snapshotCopyGrantQuotaExceededFault = "SnapshotCopyGrantQuotaExceededFault" case snapshotScheduleAlreadyExistsFault = "SnapshotScheduleAlreadyExists" case snapshotScheduleNotFoundFault = "SnapshotScheduleNotFound" case snapshotScheduleQuotaExceededFault = "SnapshotScheduleQuotaExceeded" case snapshotScheduleUpdateInProgressFault = "SnapshotScheduleUpdateInProgress" case sourceNotFoundFault = "SourceNotFound" case subnetAlreadyInUse = "SubnetAlreadyInUse" case subscriptionAlreadyExistFault = "SubscriptionAlreadyExist" case subscriptionCategoryNotFoundFault = "SubscriptionCategoryNotFound" case subscriptionEventIdNotFoundFault = "SubscriptionEventIdNotFound" case subscriptionNotFoundFault = "SubscriptionNotFound" case subscriptionSeverityNotFoundFault = "SubscriptionSeverityNotFound" case tableLimitExceededFault = "TableLimitExceeded" case tableRestoreNotFoundFault = "TableRestoreNotFoundFault" case tagLimitExceededFault = "TagLimitExceededFault" case unauthorizedOperation = "UnauthorizedOperation" case unknownSnapshotCopyRegionFault = "UnknownSnapshotCopyRegionFault" case unsupportedOperationFault = "UnsupportedOperation" case unsupportedOptionFault = "UnsupportedOptionFault" case usageLimitAlreadyExistsFault = "UsageLimitAlreadyExists" case usageLimitNotFoundFault = "UsageLimitNotFound" } private let error: Code public let context: AWSErrorContext? /// initialize Redshift public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The owner of the specified snapshot has not authorized your account to access the snapshot. public static var accessToSnapshotDeniedFault: Self { .init(.accessToSnapshotDeniedFault) } /// The specified CIDR block or EC2 security group is already authorized for the specified cluster security group. public static var authorizationAlreadyExistsFault: Self { .init(.authorizationAlreadyExistsFault) } /// The specified CIDR IP range or EC2 security group is not authorized for the specified cluster security group. public static var authorizationNotFoundFault: Self { .init(.authorizationNotFoundFault) } /// The authorization quota for the cluster security group has been reached. public static var authorizationQuotaExceededFault: Self { .init(.authorizationQuotaExceededFault) } /// The maximum number for a batch delete of snapshots has been reached. The limit is 100. public static var batchDeleteRequestSizeExceededFault: Self { .init(.batchDeleteRequestSizeExceededFault) } /// The maximum number for snapshot identifiers has been reached. The limit is 100. public static var batchModifyClusterSnapshotsLimitExceededFault: Self { .init(.batchModifyClusterSnapshotsLimitExceededFault) } /// Could not find the specified S3 bucket. public static var bucketNotFoundFault: Self { .init(.bucketNotFoundFault) } /// The account already has a cluster with the given identifier. public static var clusterAlreadyExistsFault: Self { .init(.clusterAlreadyExistsFault) } /// The ClusterIdentifier parameter does not refer to an existing cluster. public static var clusterNotFoundFault: Self { .init(.clusterNotFoundFault) } /// Cluster is already on the latest database revision. public static var clusterOnLatestRevisionFault: Self { .init(.clusterOnLatestRevisionFault) } /// A cluster parameter group with the same name already exists. public static var clusterParameterGroupAlreadyExistsFault: Self { .init(.clusterParameterGroupAlreadyExistsFault) } /// The parameter group name does not refer to an existing parameter group. public static var clusterParameterGroupNotFoundFault: Self { .init(.clusterParameterGroupNotFoundFault) } /// The request would result in the user exceeding the allowed number of cluster parameter groups. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var clusterParameterGroupQuotaExceededFault: Self { .init(.clusterParameterGroupQuotaExceededFault) } /// The request would exceed the allowed number of cluster instances for this account. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var clusterQuotaExceededFault: Self { .init(.clusterQuotaExceededFault) } /// A cluster security group with the same name already exists. public static var clusterSecurityGroupAlreadyExistsFault: Self { .init(.clusterSecurityGroupAlreadyExistsFault) } /// The cluster security group name does not refer to an existing cluster security group. public static var clusterSecurityGroupNotFoundFault: Self { .init(.clusterSecurityGroupNotFoundFault) } /// The request would result in the user exceeding the allowed number of cluster security groups. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var clusterSecurityGroupQuotaExceededFault: Self { .init(.clusterSecurityGroupQuotaExceededFault) } /// The value specified as a snapshot identifier is already used by an existing snapshot. public static var clusterSnapshotAlreadyExistsFault: Self { .init(.clusterSnapshotAlreadyExistsFault) } /// The snapshot identifier does not refer to an existing cluster snapshot. public static var clusterSnapshotNotFoundFault: Self { .init(.clusterSnapshotNotFoundFault) } /// The request would result in the user exceeding the allowed number of cluster snapshots. public static var clusterSnapshotQuotaExceededFault: Self { .init(.clusterSnapshotQuotaExceededFault) } /// A ClusterSubnetGroupName is already used by an existing cluster subnet group. public static var clusterSubnetGroupAlreadyExistsFault: Self { .init(.clusterSubnetGroupAlreadyExistsFault) } /// The cluster subnet group name does not refer to an existing cluster subnet group. public static var clusterSubnetGroupNotFoundFault: Self { .init(.clusterSubnetGroupNotFoundFault) } /// The request would result in user exceeding the allowed number of cluster subnet groups. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var clusterSubnetGroupQuotaExceededFault: Self { .init(.clusterSubnetGroupQuotaExceededFault) } /// The request would result in user exceeding the allowed number of subnets in a cluster subnet groups. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var clusterSubnetQuotaExceededFault: Self { .init(.clusterSubnetQuotaExceededFault) } /// Cross-region snapshot copy was temporarily disabled. Try your request again. public static var copyToRegionDisabledFault: Self { .init(.copyToRegionDisabledFault) } /// The request cannot be completed because a dependent service is throttling requests made by Amazon Redshift on your behalf. Wait and retry the request. public static var dependentServiceRequestThrottlingFault: Self { .init(.dependentServiceRequestThrottlingFault) } /// Your request cannot be completed because a dependent internal service is temporarily unavailable. Wait 30 to 60 seconds and try again. public static var dependentServiceUnavailableFault: Self { .init(.dependentServiceUnavailableFault) } /// The request would exceed the allowed number of event subscriptions for this account. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var eventSubscriptionQuotaExceededFault: Self { .init(.eventSubscriptionQuotaExceededFault) } /// There is already an existing Amazon Redshift HSM client certificate with the specified identifier. public static var hsmClientCertificateAlreadyExistsFault: Self { .init(.hsmClientCertificateAlreadyExistsFault) } /// There is no Amazon Redshift HSM client certificate with the specified identifier. public static var hsmClientCertificateNotFoundFault: Self { .init(.hsmClientCertificateNotFoundFault) } /// The quota for HSM client certificates has been reached. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var hsmClientCertificateQuotaExceededFault: Self { .init(.hsmClientCertificateQuotaExceededFault) } /// There is already an existing Amazon Redshift HSM configuration with the specified identifier. public static var hsmConfigurationAlreadyExistsFault: Self { .init(.hsmConfigurationAlreadyExistsFault) } /// There is no Amazon Redshift HSM configuration with the specified identifier. public static var hsmConfigurationNotFoundFault: Self { .init(.hsmConfigurationNotFoundFault) } /// The quota for HSM configurations has been reached. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var hsmConfigurationQuotaExceededFault: Self { .init(.hsmConfigurationQuotaExceededFault) } /// You have exceeded the allowed number of table restore requests. Wait for your current table restore requests to complete before making a new request. public static var inProgressTableRestoreQuotaExceededFault: Self { .init(.inProgressTableRestoreQuotaExceededFault) } /// The specified options are incompatible. public static var incompatibleOrderableOptions: Self { .init(.incompatibleOrderableOptions) } /// The number of nodes specified exceeds the allotted capacity of the cluster. public static var insufficientClusterCapacityFault: Self { .init(.insufficientClusterCapacityFault) } /// The cluster does not have read bucket or put object permissions on the S3 bucket specified when enabling logging. public static var insufficientS3BucketPolicyFault: Self { .init(.insufficientS3BucketPolicyFault) } /// The cluster parameter group action can not be completed because another task is in progress that involves the parameter group. Wait a few moments and try the operation again. public static var invalidClusterParameterGroupStateFault: Self { .init(.invalidClusterParameterGroupStateFault) } /// The state of the cluster security group is not available. public static var invalidClusterSecurityGroupStateFault: Self { .init(.invalidClusterSecurityGroupStateFault) } /// The cluster snapshot schedule state is not valid. public static var invalidClusterSnapshotScheduleStateFault: Self { .init(.invalidClusterSnapshotScheduleStateFault) } /// The specified cluster snapshot is not in the available state, or other accounts are authorized to access the snapshot. public static var invalidClusterSnapshotStateFault: Self { .init(.invalidClusterSnapshotStateFault) } /// The specified cluster is not in the available state. public static var invalidClusterStateFault: Self { .init(.invalidClusterStateFault) } /// The cluster subnet group cannot be deleted because it is in use. public static var invalidClusterSubnetGroupStateFault: Self { .init(.invalidClusterSubnetGroupStateFault) } /// The state of the subnet is invalid. public static var invalidClusterSubnetStateFault: Self { .init(.invalidClusterSubnetStateFault) } /// The provided cluster track name is not valid. public static var invalidClusterTrackFault: Self { .init(.invalidClusterTrackFault) } /// The Elastic IP (EIP) is invalid or cannot be found. public static var invalidElasticIpFault: Self { .init(.invalidElasticIpFault) } /// The specified HSM client certificate is not in the available state, or it is still in use by one or more Amazon Redshift clusters. public static var invalidHsmClientCertificateStateFault: Self { .init(.invalidHsmClientCertificateStateFault) } /// The specified HSM configuration is not in the available state, or it is still in use by one or more Amazon Redshift clusters. public static var invalidHsmConfigurationStateFault: Self { .init(.invalidHsmConfigurationStateFault) } /// Indicates that the Reserved Node being exchanged is not in an active state. public static var invalidReservedNodeStateFault: Self { .init(.invalidReservedNodeStateFault) } /// The restore is invalid. public static var invalidRestoreFault: Self { .init(.invalidRestoreFault) } /// The retention period specified is either in the past or is not a valid value. The value must be either -1 or an integer between 1 and 3,653. public static var invalidRetentionPeriodFault: Self { .init(.invalidRetentionPeriodFault) } /// The S3 bucket name is invalid. For more information about naming rules, go to Bucket Restrictions and Limitations in the Amazon Simple Storage Service (S3) Developer Guide. public static var invalidS3BucketNameFault: Self { .init(.invalidS3BucketNameFault) } /// The string specified for the logging S3 key prefix does not comply with the documented constraints. public static var invalidS3KeyPrefixFault: Self { .init(.invalidS3KeyPrefixFault) } /// The schedule you submitted isn't valid. public static var invalidScheduleFault: Self { .init(.invalidScheduleFault) } /// The scheduled action is not valid. public static var invalidScheduledActionFault: Self { .init(.invalidScheduledActionFault) } /// The snapshot copy grant can't be deleted because it is used by one or more clusters. public static var invalidSnapshotCopyGrantStateFault: Self { .init(.invalidSnapshotCopyGrantStateFault) } /// The requested subnet is not valid, or not all of the subnets are in the same VPC. public static var invalidSubnet: Self { .init(.invalidSubnet) } /// The subscription request is invalid because it is a duplicate request. This subscription request is already in progress. public static var invalidSubscriptionStateFault: Self { .init(.invalidSubscriptionStateFault) } /// The value specified for the sourceDatabaseName, sourceSchemaName, or sourceTableName parameter, or a combination of these, doesn't exist in the snapshot. public static var invalidTableRestoreArgumentFault: Self { .init(.invalidTableRestoreArgumentFault) } /// The tag is invalid. public static var invalidTagFault: Self { .init(.invalidTagFault) } /// The usage limit is not valid. public static var invalidUsageLimitFault: Self { .init(.invalidUsageLimitFault) } /// The cluster subnet group does not cover all Availability Zones. public static var invalidVPCNetworkStateFault: Self { .init(.invalidVPCNetworkStateFault) } /// The encryption key has exceeded its grant limit in AWS KMS. public static var limitExceededFault: Self { .init(.limitExceededFault) } /// The operation would exceed the number of nodes allowed for a cluster. public static var numberOfNodesPerClusterLimitExceededFault: Self { .init(.numberOfNodesPerClusterLimitExceededFault) } /// The operation would exceed the number of nodes allotted to the account. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var numberOfNodesQuotaExceededFault: Self { .init(.numberOfNodesQuotaExceededFault) } /// User already has a reservation with the given identifier. public static var reservedNodeAlreadyExistsFault: Self { .init(.reservedNodeAlreadyExistsFault) } /// Indicates that the reserved node has already been exchanged. public static var reservedNodeAlreadyMigratedFault: Self { .init(.reservedNodeAlreadyMigratedFault) } /// The specified reserved compute node not found. public static var reservedNodeNotFoundFault: Self { .init(.reservedNodeNotFoundFault) } /// Specified offering does not exist. public static var reservedNodeOfferingNotFoundFault: Self { .init(.reservedNodeOfferingNotFoundFault) } /// Request would exceed the user's compute node quota. For information about increasing your quota, go to Limits in Amazon Redshift in the Amazon Redshift Cluster Management Guide. public static var reservedNodeQuotaExceededFault: Self { .init(.reservedNodeQuotaExceededFault) } /// A resize operation for the specified cluster is not found. public static var resizeNotFoundFault: Self { .init(.resizeNotFoundFault) } /// The resource could not be found. public static var resourceNotFoundFault: Self { .init(.resourceNotFoundFault) } /// Amazon SNS has responded that there is a problem with the specified Amazon SNS topic. public static var sNSInvalidTopicFault: Self { .init(.sNSInvalidTopicFault) } /// You do not have permission to publish to the specified Amazon SNS topic. public static var sNSNoAuthorizationFault: Self { .init(.sNSNoAuthorizationFault) } /// An Amazon SNS topic with the specified Amazon Resource Name (ARN) does not exist. public static var sNSTopicArnNotFoundFault: Self { .init(.sNSTopicArnNotFoundFault) } /// The definition you submitted is not supported. public static var scheduleDefinitionTypeUnsupportedFault: Self { .init(.scheduleDefinitionTypeUnsupportedFault) } /// The scheduled action already exists. public static var scheduledActionAlreadyExistsFault: Self { .init(.scheduledActionAlreadyExistsFault) } /// The scheduled action cannot be found. public static var scheduledActionNotFoundFault: Self { .init(.scheduledActionNotFoundFault) } /// The quota for scheduled actions exceeded. public static var scheduledActionQuotaExceededFault: Self { .init(.scheduledActionQuotaExceededFault) } /// The action type specified for a scheduled action is not supported. public static var scheduledActionTypeUnsupportedFault: Self { .init(.scheduledActionTypeUnsupportedFault) } /// The cluster already has cross-region snapshot copy disabled. public static var snapshotCopyAlreadyDisabledFault: Self { .init(.snapshotCopyAlreadyDisabledFault) } /// The cluster already has cross-region snapshot copy enabled. public static var snapshotCopyAlreadyEnabledFault: Self { .init(.snapshotCopyAlreadyEnabledFault) } /// Cross-region snapshot copy was temporarily disabled. Try your request again. public static var snapshotCopyDisabledFault: Self { .init(.snapshotCopyDisabledFault) } /// The snapshot copy grant can't be created because a grant with the same name already exists. public static var snapshotCopyGrantAlreadyExistsFault: Self { .init(.snapshotCopyGrantAlreadyExistsFault) } /// The specified snapshot copy grant can't be found. Make sure that the name is typed correctly and that the grant exists in the destination region. public static var snapshotCopyGrantNotFoundFault: Self { .init(.snapshotCopyGrantNotFoundFault) } /// The AWS account has exceeded the maximum number of snapshot copy grants in this region. public static var snapshotCopyGrantQuotaExceededFault: Self { .init(.snapshotCopyGrantQuotaExceededFault) } /// The specified snapshot schedule already exists. public static var snapshotScheduleAlreadyExistsFault: Self { .init(.snapshotScheduleAlreadyExistsFault) } /// We could not find the specified snapshot schedule. public static var snapshotScheduleNotFoundFault: Self { .init(.snapshotScheduleNotFoundFault) } /// You have exceeded the quota of snapshot schedules. public static var snapshotScheduleQuotaExceededFault: Self { .init(.snapshotScheduleQuotaExceededFault) } /// The specified snapshot schedule is already being updated. public static var snapshotScheduleUpdateInProgressFault: Self { .init(.snapshotScheduleUpdateInProgressFault) } /// The specified Amazon Redshift event source could not be found. public static var sourceNotFoundFault: Self { .init(.sourceNotFoundFault) } /// A specified subnet is already in use by another cluster. public static var subnetAlreadyInUse: Self { .init(.subnetAlreadyInUse) } /// There is already an existing event notification subscription with the specified name. public static var subscriptionAlreadyExistFault: Self { .init(.subscriptionAlreadyExistFault) } /// The value specified for the event category was not one of the allowed values, or it specified a category that does not apply to the specified source type. The allowed values are Configuration, Management, Monitoring, and Security. public static var subscriptionCategoryNotFoundFault: Self { .init(.subscriptionCategoryNotFoundFault) } /// An Amazon Redshift event with the specified event ID does not exist. public static var subscriptionEventIdNotFoundFault: Self { .init(.subscriptionEventIdNotFoundFault) } /// An Amazon Redshift event notification subscription with the specified name does not exist. public static var subscriptionNotFoundFault: Self { .init(.subscriptionNotFoundFault) } /// The value specified for the event severity was not one of the allowed values, or it specified a severity that does not apply to the specified source type. The allowed values are ERROR and INFO. public static var subscriptionSeverityNotFoundFault: Self { .init(.subscriptionSeverityNotFoundFault) } /// The number of tables in the cluster exceeds the limit for the requested new cluster node type. public static var tableLimitExceededFault: Self { .init(.tableLimitExceededFault) } /// The specified TableRestoreRequestId value was not found. public static var tableRestoreNotFoundFault: Self { .init(.tableRestoreNotFoundFault) } /// You have exceeded the number of tags allowed. public static var tagLimitExceededFault: Self { .init(.tagLimitExceededFault) } /// Your account is not authorized to perform the requested operation. public static var unauthorizedOperation: Self { .init(.unauthorizedOperation) } /// The specified region is incorrect or does not exist. public static var unknownSnapshotCopyRegionFault: Self { .init(.unknownSnapshotCopyRegionFault) } /// The requested operation isn't supported. public static var unsupportedOperationFault: Self { .init(.unsupportedOperationFault) } /// A request option was specified that is not supported. public static var unsupportedOptionFault: Self { .init(.unsupportedOptionFault) } /// The usage limit already exists. public static var usageLimitAlreadyExistsFault: Self { .init(.usageLimitAlreadyExistsFault) } /// The usage limit identifier can't be found. public static var usageLimitNotFoundFault: Self { .init(.usageLimitNotFoundFault) } } extension RedshiftErrorType: Equatable { public static func == (lhs: RedshiftErrorType, rhs: RedshiftErrorType) -> Bool { lhs.error == rhs.error } } extension RedshiftErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
e080b19f49a9da807cd0e18a428c5618
81.165333
238
0.779307
5.842245
false
true
false
false
austinzheng/swift
test/NameBinding/named_lazy_member_loading_protocol_mirroring.swift
20
1051
// REQUIRES: objc_interop // REQUIRES: OS=macosx // RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post // // Prime module cache // RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -typecheck %s // // Check that named-lazy-member-loading reduces the number of Decls deserialized // RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -disable-named-lazy-member-loading -stats-output-dir %t/stats-pre %s // RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -stats-output-dir %t/stats-post %s import NamedLazyMembers public func foo(d: MirroringDoer) { let _ = MirroringDoer.mirroredBaseClassMethod() let _ = MirroringDoer.mirroredDerivedClassMethod() let _ = d.mirroredBaseInstanceMethod() let _ = d.mirroredDerivedInstanceMethod() } public func foo(d: DerivedFromMirroringDoer) { let _ = MirroringDoer.mirroredBaseClassMethod() let _ = MirroringDoer.mirroredDerivedClassMethod() let _ = d.mirroredBaseInstanceMethod() let _ = d.mirroredDerivedInstanceMethod() }
apache-2.0
b443507ad0926fca4208abdc0a10fe2a
39.423077
140
0.745956
3.526846
false
false
false
false
ReneB/Signals
SignalsTests/SingalQueueTests.swift
1
3979
// // SignalsTests.swift // SignalsTests // // Created by Tuomas Artman on 16.10.2014. // Copyright (c) 2014 Tuomas Artman. All rights reserved. // import UIKit import XCTest class SignalQueueTests: XCTestCase { var emitter:SignalEmitter = SignalEmitter(); override func setUp() { super.setUp() emitter = SignalEmitter() } override func tearDown() { super.tearDown() } func testBasicFiring() { let expectation = expectationWithDescription("queuedDispatch") emitter.onInt.listen(self, callback: { (argument) in XCTAssertEqual(argument, 1, "Last data catched") expectation.fulfill() }).queueAndDelayBy(0.1) emitter.onInt.fire(1); waitForExpectationsWithTimeout(0.15, handler: nil) } func testDispatchQueueing() { let expectation = expectationWithDescription("queuedDispatch") emitter.onInt.listen(self, callback: { (argument) in XCTAssertEqual(argument, 3, "Last data catched") expectation.fulfill() }).queueAndDelayBy(0.1) emitter.onInt.fire(1); emitter.onInt.fire(2); emitter.onInt.fire(3); waitForExpectationsWithTimeout(0.15, handler: nil) } func testNoQueueTimeFiring() { let expectation = expectationWithDescription("queuedDispatch") emitter.onInt.listen(self, callback: { (argument) in XCTAssertEqual(argument, 3, "Last data catched") expectation.fulfill() }).queueAndDelayBy(0.0) emitter.onInt.fire(1); emitter.onInt.fire(2); emitter.onInt.fire(3); waitForExpectationsWithTimeout(0.05, handler: nil) } func testConditionalListening() { let expectation = expectationWithDescription("queuedDispatch") emitter.onIntAndString.listen(self, callback: { (argument1, argument2) -> Void in XCTAssertEqual(argument1, 2, "argument1 catched") XCTAssertEqual(argument2, "test2", "argument2 catched") expectation.fulfill() }).queueAndDelayBy(0.01).filter { $0 == 2 && $1 == "test2" } emitter.onIntAndString.fire((intArgument:1, stringArgument:"test")) emitter.onIntAndString.fire((intArgument:1, stringArgument:"test2")) emitter.onIntAndString.fire((intArgument:2, stringArgument:"test2")) emitter.onIntAndString.fire((intArgument:1, stringArgument:"test3")) waitForExpectationsWithTimeout(0.02, handler: nil) } func testCancellingListeners() { let expectation = expectationWithDescription("queuedDispatch") let listener = emitter.onIntAndString.listen(self, callback: { (argument1, argument2) -> Void in XCTFail("Listener should have been canceled") }).queueAndDelayBy(0.01) emitter.onIntAndString.fire((intArgument:1, stringArgument:"test")) emitter.onIntAndString.fire((intArgument:1, stringArgument:"test")) listener.cancel() dispatch_after( dispatch_time(DISPATCH_TIME_NOW, Int64(0.05 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { // Cancelled listener didn't dispatch expectation.fulfill() } waitForExpectationsWithTimeout(0.1, handler: nil) } func testListeningNoData() { let expectation = expectationWithDescription("queuedDispatch") var dispatchCount = 0 emitter.onNoParams.listen(self, callback: { () -> Void in dispatchCount++ XCTAssertEqual(dispatchCount, 1, "Dispatched only once") expectation.fulfill() }).queueAndDelayBy(0.01) emitter.onNoParams.fire() emitter.onNoParams.fire() emitter.onNoParams.fire() waitForExpectationsWithTimeout(0.05, handler: nil) } }
mit
f859a500113600570587105e228c3a45
32.158333
122
0.623021
4.930607
false
true
false
false
GreenCom-Networks/ios-charts
Charts/Classes/Renderers/ChartLegendRenderer.swift
2
15548
// // ChartLegendRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ChartLegendRenderer: ChartRendererBase { /// the legend object this renderer renders public var legend: ChartLegend? public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?) { super.init(viewPortHandler: viewPortHandler) self.legend = legend } /// Prepares the legend and calculates all needed forms, labels and colors. public func computeLegend(data: ChartData) { guard let legend = legend else { return } if (!legend.isLegendCustom) { var labels = [String?]() var colors = [NSUIColor?]() // loop for building up the colors and labels used in the legend for i in 0..<data.dataSetCount { let dataSet = data.getDataSetByIndex(i)! var clrs: [NSUIColor] = dataSet.colors let entryCount = dataSet.entryCount // if we have a barchart with stacked bars if (dataSet is IBarChartDataSet && (dataSet as! IBarChartDataSet).isStacked) { let bds = dataSet as! IBarChartDataSet var sLabels = bds.stackLabels for j in 0..<min(clrs.count, bds.stackSize) { labels.append(sLabels[j % sLabels.count]) colors.append(clrs[j]) } if (bds.label != nil) { // add the legend description label colors.append(nil) labels.append(bds.label) } } else if (dataSet is IPieChartDataSet) { var xVals = data.xVals let pds = dataSet as! IPieChartDataSet for j in 0..<min(clrs.count, entryCount, xVals.count) { labels.append(xVals[j]) colors.append(clrs[j]) } if (pds.label != nil) { // add the legend description label colors.append(nil) labels.append(pds.label) } } else if (dataSet is ICandleChartDataSet && (dataSet as! ICandleChartDataSet).decreasingColor != nil) { colors.append((dataSet as! ICandleChartDataSet).decreasingColor) colors.append((dataSet as! ICandleChartDataSet).increasingColor) labels.append(nil) labels.append(dataSet.label) } else { // all others for j in 0..<min(clrs.count, entryCount) { // if multiple colors are set for a DataSet, group them if (j < clrs.count - 1 && j < entryCount - 1) { labels.append(nil) } else { // add label to the last entry labels.append(dataSet.label) } colors.append(clrs[j]) } } } legend.colors = colors + legend._extraColors legend.labels = labels + legend._extraLabels } // calculate all dimensions of the legend legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler) } public func renderLegend(context context: CGContext) { guard let legend = legend else { return } if !legend.enabled { return } let labelFont = legend.font let labelTextColor = legend.textColor let labelLineHeight = labelFont.lineHeight let formYOffset = labelLineHeight / 2.0 var labels = legend.labels var colors = legend.colors let formSize = legend.formSize let formToTextSpace = legend.formToTextSpace let xEntrySpace = legend.xEntrySpace let direction = legend.direction // space between the entries let stackSpace = legend.stackSpace let yoffset = legend.yOffset let xoffset = legend.xOffset let legendPosition = legend.position switch (legendPosition) { case .BelowChartLeft, .BelowChartRight, .BelowChartCenter, .AboveChartLeft, .AboveChartRight, .AboveChartCenter: let contentWidth: CGFloat = viewPortHandler.contentWidth var originPosX: CGFloat if (legendPosition == .BelowChartLeft || legendPosition == .AboveChartLeft) { originPosX = viewPortHandler.contentLeft + xoffset if (direction == .RightToLeft) { originPosX += legend.neededWidth } } else if (legendPosition == .BelowChartRight || legendPosition == .AboveChartRight) { originPosX = viewPortHandler.contentRight - xoffset if (direction == .LeftToRight) { originPosX -= legend.neededWidth } } else // .BelowChartCenter || .AboveChartCenter { originPosX = viewPortHandler.contentLeft + contentWidth / 2.0 } var calculatedLineSizes = legend.calculatedLineSizes var calculatedLabelSizes = legend.calculatedLabelSizes var calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints var posX: CGFloat = originPosX var posY: CGFloat if (legendPosition == .AboveChartLeft || legendPosition == .AboveChartRight || legendPosition == .AboveChartCenter) { posY = yoffset } else { posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight } var lineIndex: Int = 0 for i in 0..<labels.count { if (i < calculatedLabelBreakPoints.count && calculatedLabelBreakPoints[i]) { posX = originPosX posY += labelLineHeight } if (posX == originPosX && (legendPosition == .BelowChartCenter || legendPosition == .AboveChartCenter) && lineIndex < calculatedLineSizes.count) { posX += (direction == .RightToLeft ? calculatedLineSizes[lineIndex].width : -calculatedLineSizes[lineIndex].width) / 2.0 lineIndex += 1 } let drawingForm = colors[i] != nil let isStacked = labels[i] == nil // grouped forms have null labels if (drawingForm) { if (direction == .RightToLeft) { posX -= formSize } drawForm(context: context, x: posX, y: posY + formYOffset, colorIndex: i, legend: legend) if (direction == .LeftToRight) { posX += formSize } } if (!isStacked) { if (drawingForm) { posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace } if (direction == .RightToLeft) { posX -= calculatedLabelSizes[i].width } drawLabel(context: context, x: posX, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) if (direction == .LeftToRight) { posX += calculatedLabelSizes[i].width } posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace } else { posX += direction == .RightToLeft ? -stackSpace : stackSpace } } case .PiechartCenter, .RightOfChart, .RightOfChartCenter, .RightOfChartInside, .LeftOfChart, .LeftOfChartCenter, .LeftOfChartInside: // contains the stacked legend size in pixels var stack = CGFloat(0.0) var wasStacked = false var posX: CGFloat = 0.0, posY: CGFloat = 0.0 if (legendPosition == .PiechartCenter) { posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -legend.textWidthMax / 2.0 : legend.textWidthMax / 2.0) posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset } else { let isRightAligned = legendPosition == .RightOfChart || legendPosition == .RightOfChartCenter || legendPosition == .RightOfChartInside if (isRightAligned) { posX = viewPortHandler.chartWidth - xoffset if (direction == .LeftToRight) { posX -= legend.textWidthMax } } else { posX = xoffset if (direction == .RightToLeft) { posX += legend.textWidthMax } } switch legendPosition { case .RightOfChart, .LeftOfChart: posY = viewPortHandler.contentTop + yoffset case .RightOfChartCenter, .LeftOfChartCenter: posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 default: // case .RightOfChartInside, .LeftOfChartInside posY = viewPortHandler.contentTop + yoffset } } for i in 0..<labels.count { let drawingForm = colors[i] != nil var x = posX if (drawingForm) { if (direction == .LeftToRight) { x += stack } else { x -= formSize - stack } drawForm(context: context, x: x, y: posY + formYOffset, colorIndex: i, legend: legend) if (direction == .LeftToRight) { x += formSize } } if (labels[i] != nil) { if (drawingForm && !wasStacked) { x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace } else if (wasStacked) { x = posX } if (direction == .RightToLeft) { x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width } if (!wasStacked) { drawLabel(context: context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } else { posY += labelLineHeight drawLabel(context: context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } // make a step down posY += labelLineHeight stack = 0.0 } else { stack += formSize + stackSpace wasStacked = true } } } } private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) /// Draws the Legend-form at the given position with the color at the given index. public func drawForm(context context: CGContext, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend) { guard let formColor = legend.colors[colorIndex] where formColor != NSUIColor.clearColor() else { return } let formsize = legend.formSize CGContextSaveGState(context) defer { CGContextRestoreGState(context) } switch (legend.form) { case .Circle: CGContextSetFillColorWithColor(context, formColor.CGColor) CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) case .Square: CGContextSetFillColorWithColor(context, formColor.CGColor) CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) case .Line: CGContextSetLineWidth(context, legend.formLineWidth) CGContextSetStrokeColorWithColor(context, formColor.CGColor) _formLineSegmentsBuffer[0].x = x _formLineSegmentsBuffer[0].y = y _formLineSegmentsBuffer[1].x = x + formsize _formLineSegmentsBuffer[1].y = y CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2) } } /// Draws the provided label at the given position. public func drawLabel(context context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor) { ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]) } }
apache-2.0
8fb1f563469b76eeea78456cf03c1ac1
34.993056
184
0.457872
6.505439
false
false
false
false
efeconirulez/daily-affirmation
Daily Affirmation/Models/Options.swift
1
4125
// // Options.swift // Daily Affirmation // // Created by Efe Helvacı on 28.10.2017. // Copyright © 2017 efehelvaci. All rights reserved. // import Foundation fileprivate let defaults = UserDefaults.standard extension Notification.Name { static let OptionsUpdate = Notification.Name("OptionsUpdate") } enum NotificationPermissionStatus { case Authorized case NotAuthorized case NotDetermined } struct NotificationTime { let hour: Int let minute: Int init(hour: Int = 7, minute: Int = 30) { self.hour = hour self.minute = minute } } struct Options { struct OptionsStoreKeys { static let DidNotificationTimeManuallySet = "notificationTimeManuallySet" static let NotificationHour = "notificationHour" static let NotificationMinute = "notificationMinute" static let IsTextToSpeechDisabled = "textToSpeechDisabled" static let ApplicationLaunchCount = "ApplicationLaunchCount" } var notificationTime: NotificationTime { didSet { defaults.set(true, forKey: OptionsStoreKeys.DidNotificationTimeManuallySet) defaults.set(notificationTime.hour, forKey: OptionsStoreKeys.NotificationHour) defaults.set(notificationTime.minute, forKey: OptionsStoreKeys.NotificationMinute) defaults.synchronize() AppDelegate.setDailyNotifications(hour: notificationTime.hour, minute: notificationTime.minute) } } var isTextToSpeechEnabled: Bool { didSet { defaults.set(!isTextToSpeechEnabled, forKey: OptionsStoreKeys.IsTextToSpeechDisabled) } } var notificationPermissionStatus: NotificationPermissionStatus? var applicationLaunchCount: Int { didSet { defaults.set(applicationLaunchCount, forKey: OptionsStoreKeys.ApplicationLaunchCount) } } } extension Options { static public var shared: Options = { let didNotificationTimeManuallySet = defaults.bool(forKey: OptionsStoreKeys.DidNotificationTimeManuallySet) var notificationTime: NotificationTime if didNotificationTimeManuallySet { let notificationHour = defaults.integer(forKey: OptionsStoreKeys.NotificationHour) let notificationMinute = defaults.integer(forKey: OptionsStoreKeys.NotificationMinute) notificationTime = NotificationTime(hour: notificationHour, minute: notificationMinute) } else { notificationTime = NotificationTime() } let isTextToSpeechEnabled = !defaults.bool(forKey: OptionsStoreKeys.IsTextToSpeechDisabled) let applicationLaunchCount = defaults.integer(forKey: OptionsStoreKeys.ApplicationLaunchCount) let options = Options(notificationTime: notificationTime, isTextToSpeechEnabled: isTextToSpeechEnabled, notificationPermissionStatus: nil, applicationLaunchCount: applicationLaunchCount) return options }() static public func setNotificationTime(_ time: NotificationTime) { Options.shared.notificationTime = time } static public func setNotificationPermission(_ permisson: NotificationPermissionStatus) { Options.shared.notificationPermissionStatus = permisson NotificationCenter.default.post(name: Notification.Name.OptionsUpdate, object: nil) } static public func setTextToSpeech(_ isEnabled: Bool) { Options.shared.isTextToSpeechEnabled = isEnabled } static public func increaseApplicationLaunchCount() { Options.shared.applicationLaunchCount += 1 } static public func shouldDisplayRatePrompt() -> Bool { let launchCount = Options.shared.applicationLaunchCount if launchCount > 0 && (launchCount == 6 || launchCount % 20 == 0) { return true } return false } }
apache-2.0
7f64919aa63420dd7a169a1d6ceb6343
31.722222
115
0.66699
5.906877
false
false
false
false
tardieu/swift
benchmark/single-source/BitCount.swift
10
1205
//===--- BitCount.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of Swift bit count. // and mask operator. // rdar://problem/22151678 import Foundation import TestsUtils func countBitSet(_ num: Int) -> Int { let bits = MemoryLayout<Int>.size * 8 var cnt: Int = 0 var mask: Int = 1 for _ in 0...bits { if num & mask != 0 { cnt += 1 } mask <<= 1 } return cnt } @inline(never) public func run_BitCount(_ N: Int) { for _ in 1...100*N { // Check some results. CheckResults(countBitSet(1) == 1, "Incorrect results in BitCount.") CheckResults(countBitSet(2) == 1, "Incorrect results in BitCount.") CheckResults(countBitSet(2457) == 6, "Incorrect results in BitCount.") } }
apache-2.0
6556a04dd111b74e45d52ef79a1c8561
29.125
80
0.591701
4.213287
false
false
false
false
kenada/advent-of-code
tests/2015/Day_1_Tests.swift
1
3007
// // Day_1_Tests.swift // Advent of Code 2015 // // Copyright © 2015–2016 Randy Eckenrode // // 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. // @testable import Advent_of_Code_2015 import XCTest class Day_1_Tests: XCTestCase { typealias InstructionsCases = (instructions: String, expectedFloor: Floor, expectedBasementPosition: Int?) let cases: [InstructionsCases] = [ (instructions: "(())", expectedFloor: 0, expectedBasementPosition: nil), (instructions: "()()", expectedFloor: 0, expectedBasementPosition: nil), (instructions: "(((", expectedFloor: 3, expectedBasementPosition: nil), (instructions: "(()(()(", expectedFloor: 3, expectedBasementPosition: nil), (instructions: "))(((((", expectedFloor: 3, expectedBasementPosition: 1), (instructions: "())", expectedFloor: -1, expectedBasementPosition: 3), (instructions: "))(", expectedFloor: -1, expectedBasementPosition: 1), (instructions: ")))", expectedFloor: -3, expectedBasementPosition: 1), (instructions: ")())())", expectedFloor: -3, expectedBasementPosition: 1) ] func testFloorInstructions() { cases.forEach { testCase in let directions = from(string: testCase.instructions) let floor = followed(directions: directions, until: .finished) XCTAssert(floor == testCase.expectedFloor, "floor: \(String(describing: floor)) == expected \(String(describing: testCase.expectedFloor))") } } func testFloorPosition() { cases.forEach { testCase in let directions = from(string: testCase.instructions) let position = followed(directions: directions, until: .enteredBasement) XCTAssert(position == testCase.expectedBasementPosition, "position: \(String(describing: position)) == expected: \(String(describing: testCase.expectedBasementPosition))") } } }
mit
10cfc934ae46d8df31d7b73b5dccdc4e
45.9375
136
0.686085
4.876623
false
true
false
false
minimoog/filters
filters/RGBChannelGaussianBlur.swift
1
2956
// // RGBChannelGaussianBlur.swift // filters // // Created by Toni Jovanoski on 2/8/17. // Copyright © 2017 Antonie Jovanoski. All rights reserved. // import Foundation import CoreImage class RGBChannelGaussianBlur: CIFilter { var inputImage: CIImage? var inputRedRadius: CGFloat = 2 var inputGreenRadius: CGFloat = 4 var inputBlueRadius: CGFloat = 8 let rgbChannelCompositing = RGBChannelCompositing() override func setDefaults() { inputRedRadius = 2 inputGreenRadius = 4 inputBlueRadius = 8 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "RGB Channel Gaussian Blur", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputRedRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 2, kCIAttributeDisplayName: "Red Radius", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputGreenRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 4, kCIAttributeDisplayName: "Green Radius", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputBlueRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 8, kCIAttributeDisplayName: "Blue Radius", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar] ] } override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let red = inputImage.applyingFilter("CIGaussianBlur", withInputParameters: [kCIInputRadiusKey: inputRedRadius]).cropping(to: inputImage.extent) let green = inputImage.applyingFilter("CIGaussianBlur", withInputParameters: [kCIInputRadiusKey: inputGreenRadius]).cropping(to: inputImage.extent) let blue = inputImage.applyingFilter("CIGaussianBlur", withInputParameters: [kCIInputRadiusKey: inputBlueRadius]).cropping(to: inputImage.extent) rgbChannelCompositing.inputRedImage = red rgbChannelCompositing.inputGreenImage = green rgbChannelCompositing.inputBlueImage = blue return rgbChannelCompositing.outputImage } }
mit
02a9755436262774b84e0efc83f49a3b
35.481481
155
0.618613
6.234177
false
false
false
false
andrashatvani/bcHealth
bcHealth/TrackTableViewController.swift
1
3571
import UIKit class TrackTableViewController: UITableViewController { var completeTracks: [Track] = [] var incompleteTracks: [Track] = [] 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 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return completeTracks.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:TrackTableViewCell = tableView.dequeueReusableCell(withIdentifier: "TrackTableViewCell", for: indexPath) as! TrackTableViewCell let track: Track = completeTracks[indexPath.row] cell.city.text = track.city cell.date.text = Parser.dateFormatter.string(from: track.date!) cell.averageSpeed.text = String(describing: track.averageSpeed!) cell.speedUnit.text = track.speedUnit cell.distance.text = String(describing: track.distance!) cell.distanceUnit.text = track.distanceUnit cell.time.text = String(describing: track.time!) cell.timeUnit.text = track.timeUnit return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
282bf38d8419ee2d8a33cd78914b63fa
36.989362
144
0.679922
5.213139
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/MaxLodPixels.swift
1
1125
// // MaxLodPixels.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML MaxLodPixels /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="maxLodPixels" type="double" default="-1.0"/> public class MaxLodPixels:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue { public static var elementName: String = "maxLodPixels" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Lod : v.value.maxLodPixels = self default: break } } } } public var value: Double = -1.0 public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = Double(contents)! self.parent = parent return parent } }
mit
ce84ff6ceecdeb33d7402b9f6f214ddc
28.666667
84
0.611423
3.869565
false
false
false
false
Limon-O-O/Lego
Modules/Mediator_Profile/Example/Tests/Tests.swift
1
1166
// https://github.com/Quick/Quick import Quick import Nimble import Mediator_Profile class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
36b0647f43a385152095a44d0e496ced
22.2
60
0.360345
5.52381
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/ViewControllers/Stickers/StickerSharingViewController.swift
1
3319
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation @objc public class StickerSharingViewController: SelectThreadViewController { // MARK: Dependencies private var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } var linkPreviewManager: OWSLinkPreviewManager { return SSKEnvironment.shared.linkPreviewManager } // MARK: - private let stickerPackInfo: StickerPackInfo init(stickerPackInfo: StickerPackInfo) { self.stickerPackInfo = stickerPackInfo super.init(nibName: nil, bundle: nil) self.selectThreadViewDelegate = self } required public init(coder: NSCoder) { notImplemented() } public override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = NSLocalizedString("STICKERS_PACK_SHARE_VIEW_TITLE", comment: "Title of the 'share sticker pack' view.") navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(didPressCloseButton)) } @objc public class func shareStickerPack(_ stickerPackInfo: StickerPackInfo, from fromViewController: UIViewController) { AssertIsOnMainThread() let view = StickerSharingViewController(stickerPackInfo: stickerPackInfo) let modal = OWSNavigationController(rootViewController: view) fromViewController.present(modal, animated: true) } private func shareTo(thread: TSThread) { AssertIsOnMainThread() let packUrl = stickerPackInfo.shareUrl() // Try to include a link preview of the sticker pack. linkPreviewManager.tryToBuildPreviewInfo(previewUrl: packUrl) .done { (linkPreviewDraft) in self.shareAndDismiss(thread: thread, packUrl: packUrl, linkPreviewDraft: linkPreviewDraft) }.catch { error in owsFailDebug("Could not build link preview: \(error)") self.shareAndDismiss(thread: thread, packUrl: packUrl, linkPreviewDraft: nil) } .retainUntilComplete() } private func shareAndDismiss(thread: TSThread, packUrl: String, linkPreviewDraft: OWSLinkPreviewDraft?) { AssertIsOnMainThread() databaseStorage.read { transaction in ThreadUtil.enqueueMessage(withText: packUrl, in: thread, quotedReplyModel: nil, linkPreviewDraft: linkPreviewDraft, transaction: transaction) } self.dismiss(animated: true) } // MARK: Helpers @objc private func didPressCloseButton(sender: UIButton) { Logger.info("") self.dismiss(animated: true) } } // MARK: - extension StickerSharingViewController: SelectThreadViewControllerDelegate { public func threadWasSelected(_ thread: TSThread) { shareTo(thread: thread) } public func canSelectBlockedContact() -> Bool { return false } public func createHeader(with searchBar: UISearchBar) -> UIView? { return nil } }
gpl-3.0
791044c67418e4703e6818e65bd364fe
28.900901
153
0.633625
5.732297
false
false
false
false
adelinofaria/Buildasaur
Buildasaur/ManualBotManagementViewController.swift
2
4658
// // ManualBotManagementViewController.swift // Buildasaur // // Created by Honza Dvorsky on 15/03/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import AppKit import BuildaGitServer import BuildaUtils import XcodeServerSDK class ManualBotManagementViewController: NSViewController { var syncer: HDGitHubXCBotSyncer! let storageManager: StorageManager = StorageManager.sharedInstance @IBOutlet weak var nameTextField: NSTextField! @IBOutlet weak var branchComboBox: NSComboBox! @IBOutlet weak var branchActivityIndicator: NSProgressIndicator! @IBOutlet weak var templateComboBox: NSComboBox! @IBOutlet weak var creatingActivityIndicator: NSProgressIndicator! override func viewDidLoad() { super.viewDidLoad() assert(self.syncer != nil, "We need a syncer here") let names = self.storageManager.buildTemplates.map({ $0.name! }) self.templateComboBox.addItemsWithObjectValues(names) } override func viewWillAppear() { super.viewWillAppear() self.fetchBranches { (branches, error) -> () in if let error = error { UIUtils.showAlertWithError(error) } } } func fetchBranches(completion: ([Branch]?, NSError?) -> ()) { self.branchActivityIndicator.startAnimation(nil) let repoName = self.syncer.localSource.githubRepoName()! self.syncer.github.getBranchesOfRepo(repoName, completion: { (branches, error) -> () in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.branchComboBox.removeAllItems() if let branches = branches { let names = branches.map { $0.name } self.branchComboBox.addItemsWithObjectValues(names) } completion(branches, error) self.branchActivityIndicator.stopAnimation(nil) }) }) } func pullBotName() -> String? { let name = self.nameTextField.stringValue if count(name) == 0 { UIUtils.showAlertWithText("Please specify the bot's name") return nil } return name } func pullBranchName() -> String? { if let branch = self.branchComboBox.objectValueOfSelectedItem as? String where count(branch) > 0 { return branch } UIUtils.showAlertWithText("Please specify a valid branch") return nil } func pullTemplate() -> BuildTemplate? { let index = self.templateComboBox.indexOfSelectedItem if index > -1 { let template = self.storageManager.buildTemplates[index] return template } UIUtils.showAlertWithText("Please specify a valid build template") return nil } func createBot() { if let name = self.pullBotName(), let branch = self.pullBranchName(), let template = self.pullTemplate() { let project = self.syncer.localSource let xcodeServer = self.syncer.xcodeServer self.creatingActivityIndicator.startAnimation(nil) XcodeServerSyncerUtils.createBotFromBuildTemplate(name, template: template, project: project, branch: branch, scheduleOverride: nil, xcodeServer: xcodeServer, completion: { (bot, error) -> () in self.creatingActivityIndicator.stopAnimation(nil) if let error = error { UIUtils.showAlertWithError(error) } else if let bot = bot { let text = "Successfully created bot \(bot.name) for branch \(bot.configuration.sourceControlBlueprint.branch)" UIUtils.showAlertWithText(text, style: nil, completion: { (resp) -> () in self.dismissController(nil) }) } else { //should never get here UIUtils.showAlertWithText("Unexpected error, please report this!") } }) } else { Log.error("Failed to satisfy some bot dependencies, ignoring...") } } @IBAction func cancelTapped(sender: AnyObject) { self.dismissController(nil) } @IBAction func createTapped(sender: AnyObject) { self.createBot() } }
mit
93e6d88204d5b3296857bbf51b07f48c
32.035461
206
0.58158
5.598558
false
false
false
false
onekiloparsec/SwiftAA
Sources/SwiftAA/AstronomicalCoordinates.swift
2
20185
// // Coordinates.swift // SwiftAA // // Created by Cédric Foellmi on 19/07/16. // MIT Licence. See LICENCE file. // import Foundation import ObjCAA /// Struct to encapsulate amount of proper motion in equatorial reference. public struct ProperMotion { /// The annual delta in right ascension public let deltaRightAscension: Second /// The annual delta in declination public let deltaDeclination: ArcSecond } /// The coordinates of an object in the equatorial system, based on Earth equator. public struct EquatorialCoordinates: CustomStringConvertible { /// The right ascension public let rightAscension: Hour /// The declination public let declination: Degree /// The epoch of the coordinates. public let epoch: Epoch /// The reference equinox. public let equinox: Equinox /// Convenience accessor for the right ascension public var alpha: Hour { return rightAscension } /// Convenience accessor of the declination public var delta: Degree { return declination } /// Creates an EquatorialCoordinates instance. /// /// - Parameters: /// - rightAscension: The right ascension value /// - declination: The declination value /// - epoch: The optional epoch, default to J2000.0. /// - equinox: The optional equinox, default to standard equinox J2000.0. public init(rightAscension: Hour, declination: Degree, epoch: Epoch = .J2000, equinox: Equinox = .standardJ2000) { self.rightAscension = rightAscension self.declination = declination self.epoch = epoch self.equinox = equinox } /// Creates an EquatorialCoordinates instance. /// /// - Parameters: /// - alpha: The alpha (R.A.) value /// - delta: The delta (Dec.) value /// - epoch: The optional epoch value, default to J2000.0. It is not called 'epsilon' to avoid confusion with equinox. /// - equinox: The optional equinox, default to standard equinox J2000.0. public init(alpha: Hour, delta: Degree, epoch: Epoch = .J2000, equinox: Equinox = .standardJ2000) { self.init(rightAscension: alpha, declination: delta, epoch: epoch, equinox: equinox) } /// Transform the coordinates to the ecliptic (celestial) system, at same epoch and for the same equinox. /// /// During the transformation, the mean obliquity of the ecliptic of the date (epoch) is used. Recall that the /// obliquity of the ecliptic is the inclination of Earth's rotation axis, or the angle between equator and /// the ecliptic, that is, the Earth orbital plane. 'Mean' here means that nutation is not taken into account. /// /// - Returns: A new EclipticCoordinates object. public func makeEclipticCoordinates() -> EclipticCoordinates { let eclipticObliquity = KPCAANutation_MeanObliquityOfEcliptic(self.epoch.julianDay.value) let components = KPCAACoordinateTransformation_Equatorial2Ecliptic(self.rightAscension.value, self.declination.value, eclipticObliquity) return EclipticCoordinates(lambda: Degree(components.X), beta: Degree(components.Y), epoch: self.epoch, equinox: self.equinox) } /// The galactic (Milky Way) North Pole equatorial coordinates. /// /// These coordinates have been fixed conventionally and must be considered as expect for the equinox B1950. /// They have been defined by the International Astronomical Union in 1959. The origin /// of the galactic longitude is the point (in western Sagittarius) of the galactic equator /// which is 33º distant from the ascending node (in western Aquila) of the galactic equator /// with the equator of B1950.0. See AA p.94. /// /// - Returns: A new EquatorialCoordinates instance. public static func adoptedGalacticNorthPole() -> EquatorialCoordinates { return EquatorialCoordinates(alpha: Hour(.plus, 12, 49, 0.0), delta: Degree(27.4), epoch: .B1950, equinox: .standardB1950) } /// Transform the coordinates to the galactic system, at same epoch and for the same equinox. /// /// - Returns: A new galactic coordinates instance. public func makeGalacticCoordinates() -> GalacticCoordinates { let components = KPCAACoordinateTransformation_Equatorial2Galactic(self.rightAscension.value, self.declination.value) return GalacticCoordinates(l: Degree(components.X), b: Degree(components.Y), epoch: self.epoch, equinox: self.equinox) } /// Transforms the coordinates into horizontal (local) ones for a given observer location. /// /// - Parameters: /// - location: The geographic location of the observer. /// - julianDay: The julian day of observation. /// - Returns: A new horizontal coordinates instance. public func makeHorizontalCoordinates(for location: GeographicCoordinates, at julianDay: JulianDay) -> HorizontalCoordinates { let lha = (julianDay.meanLocalSiderealTime(longitude: location.longitude) - rightAscension).reduced let components = KPCAACoordinateTransformation_Equatorial2Horizontal(lha.value, self.declination.value, location.latitude.value) return HorizontalCoordinates(azimuth: Degree(components.X), altitude: Degree(components.Y), geographicCoordinates: location, julianDay: julianDay) } /// Returns new EquatorialCoordinates precessed to the given epoch. /// /// - Parameter newEquinox: The new equinox to precess to. /// - Returns: A new EquatorialCoordinates instance. public func precessedCoordinates(to newEquinox: Equinox) -> EquatorialCoordinates { let components = KPCAAPrecession_PrecessEquatorial(self.rightAscension.value, self.declination.value, self.equinox.julianDay.value, newEquinox.julianDay.value) return EquatorialCoordinates(alpha: Hour(components.X), delta: Degree(components.Y), epoch: self.epoch, equinox: newEquinox) } /// Returns new EquatorialCoordinates shifted to the new epoch by the given proper motion. /// /// - Parameters: /// - newEpoch: The new epoch of coordinates. /// - properMotion: The amount of proper motion /// - Returns: A new EquatorialCoordinates instance. public func shiftedCoordinates(to newEpoch: Epoch, with properMotion: ProperMotion) -> EquatorialCoordinates { let deltaJDinJulianYears = (newEpoch.julianDay.value - self.epoch.julianDay.value) / JulianYear.value let shiftAlpha = Second(properMotion.deltaRightAscension.value * deltaJDinJulianYears) let shiftDelta = ArcSecond(properMotion.deltaDeclination.value * deltaJDinJulianYears) return EquatorialCoordinates(alpha: self.alpha + shiftAlpha.inHours, delta: self.delta + shiftDelta.inDegrees, epoch: newEpoch, equinox: self.equinox) } /// Returns the angular separation between two equatorial coordinates. /// /// - Parameter otherCoordinates: The other coordinates to consider. /// - Returns: A angle value, between the two coordinates. public func angularSeparation(with otherCoordinates: EquatorialCoordinates) -> Degree { return Degree(KPCAAAngularSeparation_Separation(self.alpha.value, self.delta.value, otherCoordinates.alpha.value, otherCoordinates.delta.value)) } /// Returns the position angle relative to other coordinates. /// /// - Parameter otherCoordinates: The other coordinates. /// - Returns: The position angle between the two coordinates. public func positionAngle(relativeTo otherCoordinates: EquatorialCoordinates) -> Degree { return Degree(KPCAAAngularSeparation_PositionAngle(self.alpha.value, self.delta.value, otherCoordinates.alpha.value, otherCoordinates.delta.value)) } /// Return new ecliptic coordinates corrected for the annual aberration of the Earth. It must be used for star coordinates, not planets. /// See AA, p149. /// /// - parameter julianDay: The julian day for which the aberration is computed. /// - parameter highPrecision: If `false`, the Ron-Vondrák algorithm is used. See AA p.153. If `true`, the newer VSOP87 theory is used. /// /// - returns: Corected ecliptic coordinates of the star. public func correctedForAnnualAberration(julianDay: JulianDay, highPrecision: Bool = true) -> EquatorialCoordinates { let diff = KPCAAAberration_EquatorialAberration(self.alpha.value, self.delta.value, julianDay.value, highPrecision) return EquatorialCoordinates(alpha: Hour(self.alpha.value+diff.X), delta: Degree(self.delta.value+diff.Y), epoch: self.epoch) } /// Description of EquatorialCoordinates public var description: String { return String(format: "α=%@, δ=%@ (epoch %@, equinox %@)", alpha.description, delta.description, epoch.description, equinox.description) } } // MARK: - /// The coordinates in the ecliptic (a.k.a. celestial) system, based on solar-system planets orbital planes. public struct EclipticCoordinates: CustomStringConvertible { /// The celestial longitude public let celestialLongitude: Degree /// The celestial latitude public let celestialLatitude: Degree /// The epoch of the coordinates. public let epoch: Epoch /// The reference equinox. public let equinox: Equinox /// A convenience accessor for the celestial longitude public var lambda: Degree { return celestialLongitude } /// A convenience accessor for the celestial latitude public var beta: Degree { return celestialLatitude } /// Creates a new EclipticCoordinates instance. /// /// - Parameters: /// - celestialLongitude: The celestial longitude value /// - celestialLatitude: The celestial latitude value /// - epoch: The optional epoch value, default to J2000.0 /// - equinox: The optional equinox, default to standard equinox J2000.0. public init(celestialLongitude: Degree, celestialLatitude: Degree, epoch: Epoch = .J2000, equinox: Equinox = .standardJ2000) { self.celestialLongitude = celestialLongitude self.celestialLatitude = celestialLatitude self.epoch = epoch self.equinox = equinox } /// Creates a new EclipticCoordinates instance. /// /// - Parameters: /// - lambda: The longitude value. /// - beta: The latitude value /// - epoch: The optional epoch value, default to J2000.0. It is not called 'epsilon' to avoid confusion with equinox. /// - equinox: The optional equinox, default to standard equinox J2000.0. public init(lambda: Degree, beta: Degree, epoch: Epoch = .J2000, equinox: Equinox = .standardJ2000) { self.init(celestialLongitude: lambda, celestialLatitude: beta, epoch: epoch, equinox: equinox) } /// Returns equatorial coordinates corresponding to the current ecliptic ones. /// /// - Returns: A new equatorial coordinates instance. public func makeEquatorialCoordinates() -> EquatorialCoordinates { let eclipticObliquity = KPCAANutation_MeanObliquityOfEcliptic(self.epoch.julianDay.value) let components = KPCAACoordinateTransformation_Ecliptic2Equatorial(self.celestialLongitude.value, self.celestialLatitude.value, eclipticObliquity) return EquatorialCoordinates(alpha: Hour(components.X), delta: Degree(components.Y), epoch: self.epoch) } /// Returns apparent equatorial coordinates corresponding to the current ecliptic ones. /// /// - Returns: A new equatorial coordinates instance public func makeApparentEquatorialCoordinates() -> EquatorialCoordinates { let eclipticObliquity = KPCAANutation_TrueObliquityOfEcliptic(self.epoch.julianDay.value) let components = KPCAACoordinateTransformation_Ecliptic2Equatorial(self.celestialLongitude.value, self.celestialLatitude.value, eclipticObliquity) return EquatorialCoordinates(alpha: Hour(components.X), delta: Degree(components.Y), epoch: self.epoch) } /// Returns EclipticCoordinates precessed to a new given epoch. /// /// - Parameter newEpoch: The new epoch to precess to. /// - Returns: A new EclipticCoordinates instance public func precessedCoordinates(to newEpoch: Epoch) -> EclipticCoordinates { let components = KPCAAPrecession_PrecessEcliptic(self.celestialLongitude.value, self.celestialLatitude.value, self.epoch.julianDay.value, newEpoch.julianDay.value) return EclipticCoordinates(lambda: Degree(components.X), beta: Degree(components.Y), epoch: newEpoch) } /// Return new ecliptic coordinates corrected for the annual aberration of the Earth. It must be used for star coordinates, not planets. /// See AA, p149. /// /// - parameter julianDay: The julian day for which the aberration is computed. /// - parameter highPrecision: If `false`, the Ron-Vondrák algorithm is used. See AA p.153. If `true`, the newer VSOP87 theory is used.OSun /// /// - returns: Corected ecliptic coordinates of the star. public func correctedForAnnualAberration(julianDay: JulianDay, highPrecision: Bool = true) -> EclipticCoordinates { let diff = KPCAAAberration_EclipticAberration(self.lambda.value, self.beta.value, julianDay.value, highPrecision) return EclipticCoordinates(lambda: Degree(self.lambda.value+diff.X), beta: Degree(self.beta.value+diff.Y), epoch: self.epoch) } /// Description of EclipticCoordinates public var description: String { return String(format: "λ=%@, β=%@ (epoch %@, equinox %@)", lambda.description, beta.description, epoch.description, equinox.description) } } // MARK: - /// The coordinates of an object in the Milky Way galactic system. public struct GalacticCoordinates: CustomStringConvertible { /// The galactic longitude public let galacticLongitude: Degree /// The galactic latitude public let galacticLatitude: Degree /// The epoch of the coordinates public let epoch: Epoch /// The reference equinox. public let equinox: Equinox /// A convenience accessor for the galactic longitude public var l: Degree { return galacticLongitude } /// A convenience accessor for the galactic latitude public var b: Degree { return galacticLatitude } /// Creates a new GalacticCoordinates instance. /// /// - Parameters: /// - galacticLongitude: The galactic longitude /// - galacticLatitude: The galactic latitude /// - epoch: The epoch of coordinates. Default is B1950.0 /// - equinox: The optional equinox, default to standard equinox J2000.0. public init(galacticLongitude: Degree, galacticLatitude: Degree, epoch: Epoch = .J2000, equinox: Equinox = .standardJ2000) { self.galacticLongitude = galacticLongitude self.galacticLatitude = galacticLatitude self.epoch = epoch self.equinox = equinox } /// Creates a new GalacticCoordinates instance. /// /// - Parameters: /// - l: The galactic longitude /// - b: The galactic latitude /// - epoch: The epoch of coordinates. Default is B1950.0 public init(l: Degree, b: Degree, epoch: Epoch = .J2000, equinox: Equinox = .standardJ2000) { self.init(galacticLongitude: l, galacticLatitude: b, epoch: epoch, equinox: equinox) } /// Returns the equatorial coordinates corresponding to the current galactic one. /// Careful: the epoch should necessarily be that of the galactic coordinates which is always B1950.0. /// /// - Returns: A new EquatorialCoordinates object. public func makeEquatorialCoordinates() -> EquatorialCoordinates { let components = KPCAACoordinateTransformation_Galactic2Equatorial(self.galacticLongitude.value, self.galacticLatitude.value) return EquatorialCoordinates(alpha: Hour(components.X), delta: Degree(components.Y), epoch: self.epoch) } /// Description of GalacticCoordinates public var description: String { return String(format: "l=%@, b=%@ (epoch %@, equinox %@)", l.description, b.description, epoch.description, equinox.description) } } // MARK: - /// The coordinates of an object as seen from an observer location on Earth. public struct HorizontalCoordinates: CustomStringConvertible { /// The azimuth, westward from the South see AA. p91 public let azimuth: Degree /// The altitude public let altitude: Degree /// The location on Earth public let geographicCoordinates: GeographicCoordinates /// The julian day public let julianDay: JulianDay /// The azimuth angle, starting from the North. public var northBasedAzimuth: Degree { return (azimuth + 180).reduced } /// Creates a new HorizontalCoordinates instance. /// /// - Parameters: /// - azimuth: The azimuth value. /// - altitude: The altitude value /// - geographicCoordinates: The location on Earth. public init(azimuth: Degree, altitude: Degree, geographicCoordinates: GeographicCoordinates, julianDay: JulianDay) { self.azimuth = azimuth self.altitude = altitude self.geographicCoordinates = geographicCoordinates self.julianDay = julianDay } /// Returns the equivalent Equatorial coordinates for the given Julian Day. /// /// - Parameters: /// - julianDay: The julian day at which the coordinates are returned. /// - epoch: The optional epoch value, default to J2000.0 /// - Returns: A new EquatorialCoordinates object. public func makeEquatorialCoordinates(julianDay: JulianDay, epoch: Epoch = .J2000) -> EquatorialCoordinates? { let components = KPCAACoordinateTransformation_Horizontal2Equatorial(self.azimuth.value, self.altitude.value, self.geographicCoordinates.latitude.value) let lst = julianDay.meanLocalSiderealTime(longitude: geographicCoordinates.longitude) return EquatorialCoordinates(alpha: Hour(lst.value - components.X).reduced, delta: Degree(components.Y), epoch: epoch) } /// Returns the angular separation between two horizontal coordinates. /// /// - Parameter otherCoordinates: The other coordinates to consider. /// - Returns: A angle value, between the two coordinates. public func angularSeparation(with otherCoordinates: HorizontalCoordinates) -> Degree { // note: we actually use AA method for *equatorial* coordinates separation (works fine for horizontal coordinates) return Degree(KPCAAAngularSeparation_Separation(self.azimuth.inHours.value, self.altitude.value, otherCoordinates.azimuth.inHours.value, otherCoordinates.altitude.value)) } public var description: String { return String(format: "A=%@, h=%@", azimuth.description, altitude.description) } }
mit
b071bfcc29d3ca0714e0fc39d478b9c5
49.69598
154
0.663726
5.149821
false
false
false
false
IngmarStein/swift
test/Parse/init_deinit.swift
1
3453
// RUN: %target-parse-verify-swift struct FooStructConstructorA { init // expected-error {{expected '('}} } struct FooStructConstructorB { init() // expected-error {{initializer requires a body}} } struct FooStructConstructorC { init {} // expected-error {{expected '('}}{{8-8=() }} } struct FooStructDeinitializerA { deinit // expected-error {{expected '{' for deinitializer}} } struct FooStructDeinitializerB { deinit // expected-error {{expected '{' for deinitializer}} } struct FooStructDeinitializerC { deinit {} // expected-error {{deinitializers may only be declared within a class}} } class FooClassDeinitializerA { deinit(a : Int) {} // expected-error{{no parameter clause allowed on deinitializer}}{{9-18=}} } class FooClassDeinitializerB { deinit { } } init {} // expected-error {{initializers may only be declared within a type}} expected-error {{expected '('}} {{6-6=() }} init() // expected-error {{initializers may only be declared within a type}} init() {} // expected-error {{initializers may only be declared within a type}} deinit {} // expected-error {{deinitializers may only be declared within a class}} deinit // expected-error {{expected '{' for deinitializer}} deinit {} // expected-error {{deinitializers may only be declared within a class}} struct BarStruct { init() {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension BarStruct { init(x : Int) {} // When/if we allow 'var' in extensions, then we should also allow dtors deinit {} // expected-error {{deinitializers may only be declared within a class}} } enum BarUnion { init() {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension BarUnion { init(x : Int) {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } class BarClass { init() {} deinit {} } extension BarClass { convenience init(x : Int) { self.init() } deinit {} // expected-error {{deinitializers may only be declared within a class}} } protocol BarProtocol { init() {} // expected-error {{protocol initializers may not have bodies}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension BarProtocol { init(x : Int) {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } func fooFunc() { init() {} // expected-error {{initializers may only be declared within a type}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } func barFunc() { var x : () = { () -> () in init() {} // expected-error {{initializers may only be declared within a type}} return } () var y : () = { () -> () in deinit {} // expected-error {{deinitializers may only be declared within a class}} return } () } // SR-852 class Aaron { init(x: Int) {} convenience init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} {{24-24=self.}} } class Theodosia: Aaron { init() { init(x: 2) // expected-error {{missing 'super.' at initializer invocation}} {{5-5=super.}} } } struct AaronStruct { init(x: Int) {} init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} {{12-12=self.}} } enum AaronEnum: Int { case A = 1 init(x: Int) { init(rawValue: x)! } // expected-error {{missing 'self.' at initializer invocation}} {{18-18=self.}} }
apache-2.0
a9a528f64765f92dc9ba73d73762d087
27.073171
121
0.670721
3.91941
false
false
false
false
Tiryoh/HelloSwift
Math.swift
1
274
// // Math // // Created by Tiryoh on 11/03/15. import Foundation print("3 + 6 = \(3 + 6)") print("12 - 4 = \(12 - 4)") print("7 * 3 = \(7 * 3)") print("8 / 3 = \(8 / 3)") print("8 % 3 = \(8 % 3)") print("3 + 5 * 2 = \(3 + 5 * 2)") print("(3 + 5) * 2 = \((3 + 5) * 2)")
mit
0aafd9102fae7394e0e6e57557772084
18.571429
37
0.408759
2.245902
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Main/View/PageTitlesView.swift
1
6070
// // PageTitlesView.swift // DYZB // // Created by xiudou on 16/9/16. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit // MARK:- 协议 protocol PageTitlesViewDelegate : class { func pageTitlesView(_ pageTitlesView:PageTitlesView, index : Int) } // MARK:- 常量 private let scrollLineH : CGFloat = 2 private let colorNormal : (CGFloat, CGFloat ,CGFloat) = (85 ,85 ,85) private let colorSelected : (CGFloat, CGFloat ,CGFloat) = (255 ,128 ,0) class PageTitlesView: UIView { // MARK:- 定义属性 fileprivate var titles : [String] fileprivate var currentIndex : Int = 0 weak var delegate : PageTitlesViewDelegate? // MARK:- 懒加载 /// scrollView fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() /// 底部的线 fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray return bottomLine }() /// 底部滚动的横条 fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor(r: colorSelected.0, g: colorSelected.1, b: colorSelected.2) return scrollLine }() /// 标题数组 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() // MARK:- 构造函数(override init) init(frame: CGRect,titles:[String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 初始化UI extension PageTitlesView{ fileprivate func setupUI(){ // 添加 scrollView addSubview(scrollView) scrollView.frame = self.bounds // 添加label setupTitleLabels() // 设置底部线和滑块 setupBottomLineAndScrollLine() } /** 设置label尺寸和位置 */ fileprivate func setupTitleLabels(){ let label_W = sScreenW / CGFloat(titles.count) let label_Y :CGFloat = 0 let label_H :CGFloat = frame.size.height - scrollLineH for (index,title) in titles.enumerated(){ let label = UILabel() titleLabels.append(label) scrollView .addSubview(label) // 设置属性 label.tag = index label.text = title label.textColor = UIColor(r: colorNormal.0, g: colorNormal.1, b: colorNormal.2) label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 17) // 设置尺寸 let label_X :CGFloat = CGFloat(index) * label_W label.frame = CGRect(x: label_X, y: label_Y, width: label_W, height: label_H) // 开启用户交互 label.isUserInteractionEnabled = true // 创建手势 let tap = UITapGestureRecognizer(target: self, action: #selector(PageTitlesView.tapGestureRecognizer(_:))) label.addGestureRecognizer(tap) } } fileprivate func setupBottomLineAndScrollLine(){ // 底部的线 scrollView.addSubview(bottomLine) bottomLine.frame = CGRect(x: 0, y: frame.size.height - scrollLineH, width: sScreenW, height: scrollLineH) guard let label = titleLabels.first else {return} label.textColor = UIColor(r: colorSelected.0, g: colorSelected.1, b: colorSelected.2) // 底部的滑块 addSubview(scrollLine) scrollLine.frame = CGRect(x: label.frame.origin.x, y: label.frame.size.height, width: label.frame.size.width, height: scrollLineH) } } // MARK:- 监听label点击事件 extension PageTitlesView{ @objc fileprivate func tapGestureRecognizer(_ tap : UIGestureRecognizer){ // as后面更上? 因为如果是! 就不可以用guard guard let label = tap.view as? UILabel else {return} // 之前的label let oldLabel = titleLabels[currentIndex] oldLabel.textColor = UIColor(r: colorNormal.0, g: colorNormal.1, b: colorNormal.2) // 让点击的label变色 label.textColor = UIColor(r: colorSelected.0, g: colorSelected.1, b: colorSelected.2) currentIndex = label.tag // 让滑块滚动 let scrollLine_X = CGFloat(currentIndex) * label.frame.size.width UIView.animate(withDuration: 0.2, animations: {[weak self] () -> Void in self?.scrollLine.frame.origin.x = scrollLine_X }) // 通知代理 delegate?.pageTitlesView(self, index: currentIndex) } } extension PageTitlesView{ func setPageTitlesView(_ progress: CGFloat, originalIndex: Int, targetIndex: Int) { // 原来的label let originalLabel = titleLabels[originalIndex] // 目标label let targetLabel = titleLabels[targetIndex] // 滑块 let moveRange = targetLabel.frame.origin.x - originalLabel.frame.origin.x let moveX = moveRange * progress scrollLine.frame.origin.x = originalLabel.frame.origin.x + moveX // 颜色变化的区间 let rangeColor = (colorSelected.0 - colorNormal.0,colorSelected.1 - colorNormal.1,colorSelected.2 - colorNormal.2) // 改变label的颜色 originalLabel.textColor = UIColor(r: colorSelected.0 - rangeColor.0 * progress, g: colorSelected.1 - rangeColor.1 * progress, b: colorSelected.2 - rangeColor.2 * progress) targetLabel.textColor = UIColor(r: rangeColor.0 * progress + colorNormal.0, g: rangeColor.1 * progress + colorNormal.1, b: rangeColor.2 * progress + colorNormal.2) currentIndex = targetIndex } }
mit
a9918335abfe39b18b784ebdd6d6aa88
31.374302
181
0.61346
4.581028
false
false
false
false
P0ed/FireTek
Source/Scenes/Space/SpaceScene.swift
1
1682
import SpriteKit import Fx final class SpaceScene: Scene { private var engine: SpaceEngine! private var world: SKNode! private var lastUpdate = 0 as CFTimeInterval private let hidController = HIDController() let hud = HUDNode() static func create() -> SpaceScene { let scene = SpaceScene(fileNamed: "SpaceScene")! scene.scaleMode = .aspectFit return scene } override func didMove(to view: SKView) { super.didMove(to: view) backgroundColor = SKColor(red: 0.01, green: 0.02, blue: 0.06, alpha: 1) let camera = SKCameraNode() camera.position = CGPoint(x: 128, y: 128) addChild(camera) self.camera = camera world = SKNode() addChild(world) SoundsFabric.preheat() engine = SpaceEngine(SpaceEngine.Model( scene: self, inputController: InputController(hidController.eventsController) )) camera.addChild(hud) hud.zPosition = 1000 hud.layout(size: size) } // func renderTileMap(_ level: PlanetLevel) { // let tileSize = 64 // level.tileMap.forEach { position, tile in // let node = SKSpriteNode(color: tile.color, size: CGSize(width: tileSize, height: tileSize)) // node.position = CGPoint(x: position.x * tileSize, y: position.y * tileSize) // node.anchorPoint = .zero // world.addChild(node) // } // } override func update(_ currentTime: TimeInterval) { if lastUpdate != 0 { while currentTime - lastUpdate > SpaceEngine.timeStep { lastUpdate += SpaceEngine.timeStep engine.simulate() } } else { lastUpdate = currentTime } } override func didFinishUpdate() { engine.didFinishUpdate() } override func keyDown(with event: NSEvent) {} override func keyUp(with event: NSEvent) {} }
mit
55eb0b46874c6a8c6aed5f7b421b5c20
22.690141
96
0.697979
3.391129
false
false
false
false
MukeshKumarS/Swift
test/SILGen/partial_apply_super.swift
1
6078
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -use-native-super-method -emit-silgen -parse-as-library -I %t %s | FileCheck %s import resilient_class public class Parent { public init() {} public func method() {} public final func finalMethod() {} public class func classMethod() {} public final class func finalClassMethod() {} } public class GenericParent<A> { let a: A public init(a: A) { self.a = a } public func method() {} public final func finalMethod() {} public class func classMethod() {} public final class func finalClassMethod() {} } class Child : Parent { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super5Child6methodfT_T_ : $@convention(method) (@guaranteed Child) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF15resilient_class5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $Child, #Parent.method!1 : Parent -> () -> () , $@convention(method) (@guaranteed Parent) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@guaranteed Parent) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super5Child11classMethodfT_T_ : $@convention(thin) (@thick Child.Type) -> () { // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF15resilient_class5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick Child.Type, #Parent.classMethod!1 : Parent.Type -> () -> () , $@convention(thin) (@thick Parent.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } // CHECK-LABEL: sil hidden @_TFC19partial_apply_super5Child20callFinalSuperMethodfT_T_ : $@convention(method) (@guaranteed Child) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF15resilient_class5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC19partial_apply_super6Parent11finalMethodFT_T_ : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> () // CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[APPLIED_SELF]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () func callFinalSuperMethod() { doFoo(super.finalMethod) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super5Child25callFinalSuperClassMethodfT_T_ : $@convention(thin) (@thick Child.Type) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF15resilient_class5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TZFC19partial_apply_super6Parent16finalClassMethodFT_T_ : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> () // CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[APPLIED_SELF]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () class func callFinalSuperClassMethod() { doFoo(super.finalClassMethod) } } class GenericChild<A> : GenericParent<A> { override init(a: A) { super.init(a: a) } // CHECK-LABEL: sil hidden @_TFC19partial_apply_super12GenericChild6methodfT_T_ : $@convention(method) <A> (@guaranteed GenericChild<A>) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF15resilient_class5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $GenericChild<A> to $GenericParent<A> // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $GenericChild<A>, #GenericParent.method!1 : <A> GenericParent<A> -> () -> () , $@convention(method) <τ_0_0> (@guaranteed GenericParent<τ_0_0>) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed GenericParent<τ_0_0>) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super12GenericChild11classMethodfT_T_ : $@convention(thin) <A> (@thick GenericChild<A>.Type) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF15resilient_class5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChild<A>.Type to $@thick GenericParent<A>.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChild<A>.Type, #GenericParent.classMethod!1 : <A> GenericParent<A>.Type -> () -> () , $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply %4<A>(%3) : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> () // CHECK: apply %2(%5) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } }
apache-2.0
39190bc740625b7bd5df09a756169d3e
64.978261
225
0.625041
3.326027
false
false
false
false
TheMindStudios/WheelPicker
WheelPicker/Classes/WheelPickerCollectionViewLayout.swift
1
4460
// // WheelPickerCollectionViewLayout.swift // WheelPicker // // Created by Dima on 17.02.17. // Copyright © 2017 Dima. All rights reserved. // import UIKit public protocol WheelPickerLayoutDelegate: class { func pickerViewStyle(for layout: WheelPickerCollectionViewLayout) -> WheelPickerStyle } open class WheelPickerCollectionViewLayout : UICollectionViewFlowLayout { open weak var delegate: WheelPickerLayoutDelegate? fileprivate var width = CGFloat(0.0) fileprivate var height = CGFloat(0.0) fileprivate var midX = CGFloat(0.0) fileprivate var midY = CGFloat(0.0) fileprivate var maxAngle = CGFloat(0.0) override open func prepare() { let visibleRect = CGRect(origin: collectionView?.contentOffset ?? CGPoint.zero, size: collectionView?.bounds.size ?? CGSize.zero) midX = visibleRect.midX midY = visibleRect.midY width = visibleRect.width/2 height = visibleRect.height/2 maxAngle = CGFloat(Double.pi / 2) } override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let attributes = super.layoutAttributesForItem(at: indexPath) , let style = delegate?.pickerViewStyle(for: self) { switch style { case .styleFlat: return attributes case .style3D: switch scrollDirection { case .horizontal: let distance = attributes.frame.midX - midX let currentAngle = maxAngle * distance / width / CGFloat(Double.pi / 2.0) var transform = CATransform3DIdentity transform = CATransform3DTranslate(transform, -distance, 0.0, -width) transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0) transform = CATransform3DTranslate(transform, 0, 0, width) if abs(currentAngle) < maxAngle { attributes.transform3D = transform attributes.alpha = 1.0 } else { attributes.alpha = 0.0 } case .vertical: let distance = attributes.frame.midY - midY let currentAngle = maxAngle * distance / height / CGFloat(Double.pi / 2) var transform = CATransform3DIdentity transform = CATransform3DTranslate(transform, 0, -distance, 0) transform = CATransform3DRotate(transform, currentAngle, 1, 0, 0) transform = CATransform3DTranslate(transform, 0, distance, 0) if abs(currentAngle) < maxAngle / 2 { attributes.transform3D = transform attributes.alpha = 1.0 } else { attributes.alpha = 0.0 } } return attributes } } return nil } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if let style = delegate?.pickerViewStyle(for: self) { switch style { case .styleFlat: return super.layoutAttributesForElements(in: rect) case .style3D: var attributes = [UICollectionViewLayoutAttributes]() if let indexs = collectionView?.numberOfItems(inSection: 0), (collectionView?.numberOfSections)! > 0 { for index in 0 ..< indexs { let indexPath = IndexPath(item: index, section: 0) if let attribut = self.layoutAttributesForItem(at: indexPath) { attributes.append(attribut) } else { attributes.append(UICollectionViewLayoutAttributes()) } } } return attributes } } return nil } }
mit
96112457ef4f27beab08f8e84dc563f8
37.111111
138
0.532631
5.921647
false
false
false
false
1170197998/SinaWeibo
SFWeiBo/SFWeiBo/Classes/Newfeature/NewfeatureCollectionViewController.swift
1
5742
// // NewfeatureCollectionViewController.swift // SFWeiBo // // Created by mac on 16/4/9. // Copyright © 2016年 ShaoFeng. All rights reserved. // //在Swift中private修饰的变量或者方法,只能在在本文件中可以访问,若本文件中有多个类,那么别的类也可以访问这个变量或者方法 import UIKit //重用标识 private let reuseIdentifier = "reuseIdentifier" class NewfeatureCollectionViewController: UICollectionViewController { //页面个数 private let pageCount = 4 //布局对象(自定义布局) private var layout: UICollectionViewFlowLayout = NewfeatureLayout() init() { super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() //注册一个cell collectionView?.registerClass(NewfearureCell.self, forCellWithReuseIdentifier: reuseIdentifier) } } //MARK: - UICollectionDataSource extension NewfeatureCollectionViewController { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageCount } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { //获取cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewfearureCell //设置cell数据 // cell.backgroundColor = UIColor.redColor() cell.imageIndex = indexPath.item return cell } //MARK: - 完全显示一个cell后调用 override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { //拿到当前显示cell对应的索引 let path = collectionView.indexPathsForVisibleItems().last! if path.item == (pageCount - 1) { //拿到当前索引对应的cell let cell = collectionView.cellForItemAtIndexPath(path) as! NewfearureCell //让cell执行按钮动画 cell.starButtonAnimation() } } } //MARK: - Swift中一个文件可以定义多个类 //MARK: 自定义collectionViewCell //如果当前类需要监听按钮的点击事件,那么当前类不能是私有的(private) class NewfearureCell: UICollectionViewCell { //保存图片索引 private var imageIndex:Int? { didSet { //根据页码创建图片名字 iconView.image = UIImage(named: "new_feature_\(imageIndex! + 1)") if imageIndex == 3 { starButton.hidden = false starButtonAnimation() } else { starButton.hidden = true } } } //MARK: - 按钮动画 func starButtonAnimation() { //执行动画 //初始大小为0,并且不可点击 starButton.transform = CGAffineTransformMakeScale(0.0, 0.0) starButton.userInteractionEnabled = false UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in //清空变形 self.starButton.transform = CGAffineTransformIdentity },completion: { (_) -> Void in self.starButton.userInteractionEnabled = true }) } override init(frame: CGRect) { super.init(frame: frame) //初始化UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { //添加子控件到contentView contentView.addSubview(iconView) contentView.addSubview(starButton) //布局子控件位置(填充屏幕) iconView.Fill(contentView) starButton.AlignInner(type: AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160)) } //MARK: 懒加载 private lazy var iconView = UIImageView() private lazy var starButton:UIButton = { let button = UIButton() button.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted) button.addTarget(self, action: #selector(NewfearureCell.starButtonClick), forControlEvents: UIControlEvents.TouchUpInside) return button }() func starButtonClick() { //进入微博 NSNotificationCenter.defaultCenter().postNotificationName(SFSwitchRootViewController, object: true) } } //MARK: - 继承UICollectionViewFlowLayout,自定义布局 private class NewfeatureLayout: UICollectionViewFlowLayout { //重写系统准备布局的方法 //这个方法在返回多少行的方法之后,在返回cell的方法之前调用 override func prepareLayout() { //设置layout布局 itemSize = UIScreen.mainScreen().bounds.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.Horizontal //设置其他属性 collectionView?.showsHorizontalScrollIndicator = false collectionView?.bounces = false collectionView?.pagingEnabled = true } }
apache-2.0
6ecff1de318cbce914c45a0b35338013
31.04321
177
0.649971
5.16004
false
false
false
false
thanegill/RxSwift
RxTests/Event+Equatable.swift
11
1278
// // Event+Equatable.swift // Rx // // Created by Krunoslav Zaher on 12/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift /** Compares two events. They are equal if they are both the same member of `Event` enumeration. In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code) and their string representations are equal. */ public func == <Element: Equatable>(lhs: Event<Element>, rhs: Event<Element>) -> Bool { switch (lhs, rhs) { case (.Completed, .Completed): return true case (.Error(let e1), .Error(let e2)): // if the references are equal, then it's the same object if let lhsObject = lhs as? AnyObject, rhsObject = rhs as? AnyObject where lhsObject === rhsObject { return true } #if os(Linux) return "\(e1)" == "\(e2)" #else let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code && "\(e1)" == "\(e2)" #endif case (.Next(let v1), .Next(let v2)): return v1 == v2 default: return false } }
mit
db83099d42e87e8ebfb5457586e7082d
29.404762
125
0.595928
3.905199
false
false
false
false
pascaljette/GearRadarChart
GearRadarChart/GearRadarChartExample/GKRadarGraphModel.swift
1
6476
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // 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 GearRadarChart /// Model containing the data necessary to display the radar graph view controller. struct GKRadarGraphModel { // // MARK: Randomization // private static let allowedColors = [UIColor.red, UIColor.black, UIColor.blue, UIColor.purple, UIColor.cyan, UIColor.yellow, UIColor.orange, UIColor.green, UIColor.magenta, UIColor.brown] private static let randomParameterMaxLength: UInt32 = 8 private static let allowedDecorations: [GKRadarGraphView.Serie.DecorationType] = [ .square(8.0), .circle(6.0), .diamond(8.0) ] private static func randomAlphaNumericString(length: Int) -> String { let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let allowedCharsCount = UInt32(allowedChars.characters.count) var randomString = "" for _ in 0..<length { let randomNum = Int(arc4random_uniform(allowedCharsCount)) let randomIndex = allowedChars.index(allowedChars.startIndex, offsetBy: randomNum) let newCharacter = allowedChars[randomIndex] randomString += String(newCharacter) } return randomString } static var random: GKRadarGraphModel { var model = GKRadarGraphModel() // Randomize parameters. let numberOfParameters = arc4random_uniform(10) + 3 model.parameters = (1...numberOfParameters).map { _ in let name = randomAlphaNumericString(length: Int(arc4random_uniform(randomParameterMaxLength) + 1)) return GKRadarGraphView.Parameter(name: name) } // Randomize series. var randomizedAllowedColors = GKRadarGraphModel.allowedColors.shuffled() let numberOfSeries = arc4random_uniform(UInt32(allowedColors.count)) + 1 model.series = (1...numberOfSeries).map { _ in var serie = GKRadarGraphView.Serie() let color = randomizedAllowedColors.popLast()! serie.strokeColor = color serie.strokeWidth = 4.0 serie.fillMode = .solid(color.withAlphaComponent(0.7)) serie.decoration = allowedDecorations.shuffled().first! serie.percentageValues = (1...numberOfParameters).map { _ in return CGFloat(arc4random_uniform(100)) / 100 } return serie } return model } static var defaultModel: GKRadarGraphModel { var model = GKRadarGraphModel() let hpParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "HP") let mpParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "MP") let strengthParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "STR") let defenseParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "DF") let magicParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "MGC") model.parameters = [hpParameter, mpParameter, strengthParameter, defenseParameter, magicParameter] // We only support gradients for a single serie radar graph var firstSerie = GKRadarGraphView.Serie() firstSerie.strokeColor = UIColor.blue firstSerie.strokeWidth = 4.0 firstSerie.name = "blue" let firstFillColor: UIColor = UIColor(red: 0.1, green: 0.1, blue: 0.7, alpha: 0.7) firstSerie.fillMode = .solid(firstFillColor) firstSerie.percentageValues = [0.9, 0.5, 0.6, 0.2, 0.9] firstSerie.decoration = .square(8.0) var secondSerie = GKRadarGraphView.Serie() secondSerie.strokeColor = UIColor.green secondSerie.strokeWidth = 4.0 secondSerie.name = "green" let secondFillColor: UIColor = UIColor(red: 0.1, green: 0.7, blue: 0.1, alpha: 0.7) secondSerie.fillMode = .solid(secondFillColor) secondSerie.percentageValues = [0.9, 0.1, 0.2, 0.9, 0.3] secondSerie.decoration = .circle(6.0) var thirdSerie = GKRadarGraphView.Serie() thirdSerie.strokeColor = UIColor.red thirdSerie.strokeWidth = 4.0 thirdSerie.name = "red" let thirdSerieFillColor: UIColor = UIColor(red: 0.7, green: 0.1, blue: 0.1, alpha: 0.7) thirdSerie.fillMode = .solid(thirdSerieFillColor) thirdSerie.percentageValues = [0.5, 0.9, 0.5, 0.5, 0.6] thirdSerie.decoration = .diamond(8.0) model.series = [firstSerie, secondSerie, thirdSerie] return model } // // MARK: Stored properties // /// Array of parameters for the plot. var parameters: [GKRadarGraphView.Parameter] = [] /// Series representing the data in the plot. var series: [GKRadarGraphView.Serie] = [] }
mit
cdcc6ea36ab0bfad6f8492d32f6d82e0
39.987342
110
0.622607
4.935976
false
false
false
false
Oyvindkg/swiftydb
Pod/Classes/SwiftyDB+Asynchronous.swift
1
3655
// // SwiftyDB+Asynchronous.swift // SwiftyDB // // Created by Øyvind Grimnes on 13/01/16. // import TinySQLite /** Support asynchronous queries */ extension SwiftyDB { /** A global, concurrent queue with default priority */ private var queue: dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) } // MARK: - Asynchronous database operations /** Asynchronously add object to the database - parameter object: object to be added to the database - parameter update: indicates whether the record should be updated if already present */ public func asyncAddObject <S: Storable> (object: S, update: Bool = true, withCompletionHandler completionHandler: ((Result<Bool>)->Void)? = nil) { asyncAddObjects([object], update: update, withCompletionHandler: completionHandler) } /** Asynchronously add objects to the database - parameter objects: objects to be added to the database - parameter update: indicates whether the record should be updated if already present */ public func asyncAddObjects <S: Storable> (objects: [S], update: Bool = true, withCompletionHandler completionHandler: ((Result<Bool>)->Void)? = nil) { dispatch_async(queue) { [weak self] () -> Void in guard self != nil else { return } completionHandler?(self!.addObjects(objects)) } } /** Asynchronous retrieval of data for a specified type, matching a filter, from the database - parameter filters: dictionary containing the filters identifying objects to be retrieved - parameter type: type of the objects to be retrieved */ public func asyncDataForType <S: Storable> (type: S.Type, matchingFilter filter: Filter? = nil, withCompletionHandler completionHandler: ((Result<[[String: Value?]]>)->Void)) { dispatch_async(queue) { [weak self] () -> Void in guard self != nil else { return } completionHandler(self!.dataForType(type, matchingFilter: filter)) } } /** Asynchronously remove objects of a specified type, matching a filter, from the database - parameter filters: dictionary containing the filters identifying objects to be deleted - parameter type: type of the objects to be deleted */ public func asyncDeleteObjectsForType (type: Storable.Type, matchingFilter filter: Filter? = nil, withCompletionHandler completionHandler: ((Result<Bool>)->Void)? = nil) { dispatch_async(queue) { [weak self] () -> Void in guard self != nil else { return } completionHandler?(self!.deleteObjectsForType(type, matchingFilter: filter)) } } } extension SwiftyDB { // MARK: - Asynchronous dynamic initialization /** Asynchronous retrieval of objects of a specified type, matching a set of filters, from the database - parameter filters: dictionary containing the filters identifying objects to be retrieved - parameter type: type of the objects to be retrieved */ public func asyncObjectsForType <D where D: Storable, D: NSObject> (type: D.Type, matchingFilter filter: Filter? = nil, withCompletionHandler completionHandler: ((Result<[D]>)->Void)) { dispatch_async(queue) { [unowned self] () -> Void in completionHandler(self.objectsForType(type, matchingFilter: filter)) } } }
mit
c7cca606d77ac56435e27d050058c870
35.188119
189
0.63711
5.082058
false
false
false
false
hemmerling/codingdojo
src/game_of_life/swift_coderetreat_socramob_2016-01/Cell.swift
1
939
// // Cell.swift // CodeRetreat // // Created by Andreas Bauer on 13.02.16. // Copyright © 2016 Andreas Bauer. All rights reserved. // import UIKit enum CellState { case ALIVE case DEAD } class Cell: NSObject { var neighbours: Int = 0 var state = CellState.ALIVE func nextGeneration() -> Cell { let cell = Cell() switch neighbours { case 2: switch state { case .ALIVE: cell.state = .ALIVE case .DEAD: cell.state = .DEAD } case 3: cell.state = .ALIVE default: cell.state = .DEAD } return cell // if neighbours == 0 { // let cell = Cell() // cell.state = .DEAD // return cell // } else { // let cell = Cell() // cell.state = .ALIVE // return cell // } } }
apache-2.0
2928a8f3f258510b40a78a013e06b47f
18.957447
56
0.460554
4.043103
false
false
false
false
Wolox/wolmo-core-ios
WolmoCore/Extensions/UIKit/UIView/Gradient.swift
1
7245
// // Gradient.swift // WolmoCore // // Created by Daniela Riesgo on 10/12/17. // Copyright © 2017 Wolox. All rights reserved. // import Foundation /** Represents the posible directions of a gradient in a view. */ public enum GradientDirection { /// Sets the gradient's direction from left to right. case leftToRight /// Sets the gradient's direction from right to left. case rightToLeft /// Sets the gradient's direction from top to bottom. case topToBottom /// Sets the gradient's direction from bottom to top. case bottomToTop /// Sets the gradient's direction from top left to bottom right. case topLeftToBottomRight /// Sets the gradient's direction from bottom right to top left. case bottomRightToTopLeft /// Sets the gradient's direction from top right to bottom left. case topRightToBottomLeft /// Sets the gradient's direction from bottom left to top right. case bottomLeftToTopRight } fileprivate extension GradientDirection { var startPoint: CGPoint { switch self { case .leftToRight: return CGPoint(x: 0, y: 0.5) case .rightToLeft: return CGPoint(x: 1, y: 0.5) case .topToBottom: return CGPoint(x: 0.5, y: 0) case .bottomToTop: return CGPoint(x: 0.5, y: 1) case .topLeftToBottomRight: return CGPoint(x: 0, y: 0) case .bottomRightToTopLeft: return CGPoint(x: 1, y: 1) case .topRightToBottomLeft: return CGPoint(x: 1, y: 0) case .bottomLeftToTopRight: return CGPoint(x: 0, y: 1) } } var endPoint: CGPoint { switch self { case .leftToRight: return CGPoint(x: 1, y: 0.5) case .rightToLeft: return CGPoint(x: 0, y: 0.5) case .topToBottom: return CGPoint(x: 0.5, y: 1) case .bottomToTop: return CGPoint(x: 0.5, y: 0) case .topLeftToBottomRight: return CGPoint(x: 1, y: 1) case .bottomRightToTopLeft: return CGPoint(x: 0, y: 0) case .topRightToBottomLeft: return CGPoint(x: 0, y: 1) case .bottomLeftToTopRight: return CGPoint(x: 1, y: 0) } } } /** Represents a color that takes place ina gradient that can be applied to a view. It has a UIColor and a location which indicates where that color should be placed in the gradient. */ public struct GradientColor { /// Color to use in gradient. public let color: UIColor /** Location where to place color inside the gradient. Number between 0 and 1 (inclusive). */ public let location: Float /** Initializes an inmutable GradientColor. - parameter color: UIColor to use. - parameter location: Locations of the center of the color through out the gradient. A location is any possible number between 0 and 1, being 0 the start of the gradient and 1 the end of the gradient in the direction specified. - warning: If the location isn't between 0 and 1 (inclusive) the init will fail. */ public init?(color: UIColor, location: Float) { if location < 0 || location > 1 { return nil } self.color = color self.location = location } } /** Represents a gradient that can be applied to a view. It can have many colors distributed in many ways and directions. - note: There can only be one gradient at a time in a view. */ public struct ViewGradient { /// Direction of the gradient. public let direction: GradientDirection /// GradientColors involved in the order involved. public let colors: [GradientColor] fileprivate let layer: CAGradientLayer /** Initializes an inmutable ViewGradient. - parameter colors: Array of GradientColors to be used. - parameter direction: Direction in which the gradient should develop. */ public init(colors: [GradientColor], direction: GradientDirection) { self.colors = colors.sorted { g1, g2 in g1.location < g2.location } self.direction = direction layer = CAGradientLayer() layer.anchorPoint = .zero layer.colors = self.colors.map { $0.color.cgColor } layer.locations = self.colors.map { NSNumber(value: $0.location) } layer.startPoint = direction.startPoint layer.endPoint = direction.endPoint } /** Initializes an inmutable ViewGradient. - parameter colors: Array of UIColors in the order in which to place them. They will be evenly separated. - parameter direction: Direction in which the gradient should develop. */ public init(colors: [UIColor], direction: GradientDirection) { let locations = calculateLocations(for: colors.count) let gradientColors = colors.enumerated().map { (index, color) in GradientColor(color: color, location: locations[index].floatValue)! } self.init(colors: gradientColors, direction: direction) } } private func calculateLocations(for numberOfColors: Int) -> [NSNumber] { var locs: [NSNumber] = [] let colorProportion = 1.0 / Double(numberOfColors - 1) for i in 0...numberOfColors { let location = Double(i) * colorProportion locs.append(NSNumber(value: location)) } return locs } public extension UIView { /** ViewGradient applied currently to the view. A view can only have one gradient at a time. When setting this property to a new gradient, the old one will be removed, and when set to .none the current one will be removed. The gradient will always have the same direction in relation to the view's orientation at a certain time. The gradient will always acommodate to the view's change in size or orientation. - warning: To avoid memory leak and crashes, you should set the `gradient` to .none before deallocating the view. */ var gradient: ViewGradient? { get { return getGradient() } set { if gradient != nil { removeGradient() } if let grad = newValue { apply(gradient: grad) } } } private func apply(gradient: ViewGradient) { let gradientLayer = gradient.layer gradientLayer.bounds = bounds layer.insertSublayer(gradientLayer, at: 0) setAssociatedObject(self, key: &ViewGradientKey, value: gradient as ViewGradient?) let observer = observe(\.bounds) { object, _ in gradientLayer.bounds = object.bounds } setAssociatedObject(self, key: &ViewGradientObserverKey, value: observer as NSKeyValueObservation?) } private func removeGradient() { if let gradient = getGradient() { gradient.layer.removeFromSuperlayer() setAssociatedObject(self, key: &ViewGradientKey, value: ViewGradient?.none) setAssociatedObject(self, key: &ViewGradientObserverKey, value: NSKeyValueObservation?.none) } } private func getGradient() -> ViewGradient? { return getAssociatedObject(self, key: &ViewGradientKey) } } private var ViewGradientKey: UInt8 = 1 private var ViewGradientObserverKey: UInt8 = 2
mit
1df44b827b6b2e1f975f78616d1b4bab
34.509804
121
0.652954
4.536005
false
false
false
false
daferpi/p5App
p5App/p5App/AppDelegate.swift
1
3317
// // AppDelegate.swift // p5App // // Created by Abel Fernandez on 20/05/2017. // Copyright © 2017 Daferpi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
258397cbe1dde83c02a7e496abd1e2b0
53.360656
285
0.76146
6.198131
false
false
false
false
zenangst/Faker
Source/Generators/Lorem.swift
1
1400
import Foundation public class Lorem: Generator { public func word() -> String { return generate("lorem.words") } public func words(amount: Int = 3) -> String { var words: [String] = [] for _ in 0..<amount { words.append(word()) } return " ".join(words) } public func character() -> String { return characters(amount: 1) } public func characters(amount: Int = 255) -> String { var chars = "" if amount > 0 { for _ in 0..<amount { let char = Character(UnicodeScalar(arc4random() % (122-97) + 97)) chars.append(char) } } return chars } public func sentence(wordsAmount: Int = 4) -> String { var sentence = words(amount: wordsAmount) + "." sentence.replaceRange(sentence.startIndex...sentence.startIndex, with: String(sentence[sentence.startIndex]).capitalizedString) return sentence } public func sentences(amount: Int = 3) -> String { var sentences: [String] = [] for _ in 0..<amount { sentences.append(sentence()) } return " ".join(sentences) } public func paragraph(sentencesAmount: Int = 3) -> String { return sentences(amount: sentencesAmount) } public func paragraphs(amount: Int = 3) -> String { var paragraphs: [String] = [] for _ in 0..<amount { paragraphs.append(paragraph()) } return "\n".join(paragraphs) } }
mit
321cbab77144ca2ec4030a4dc1adc6f8
21.222222
131
0.61
3.943662
false
false
false
false
mrazam110/MRSelectCountry
MRSelectCountry/MRSelectCountry/MRSelectCountry.swift
1
1777
// // MRSelectCountry.swift // MRSelectCountry // // Created by Muhammad Raza on 21/08/2017. // Copyright © 2017 Muhammad Raza. All rights reserved. // import UIKit public class MRSelectCountry: NSObject { public static func getMRSelectCountryController(delegate: MRSelectCountryDelegate? = nil) -> MRSelectCountryTableViewController { let bundle = Bundle(identifier: "org.cocoapods.MRSelectCountry") let storyboard = UIStoryboard(name: "MRSelectCountry", bundle: bundle) let controller = storyboard.instantiateViewController(withIdentifier: "MRSelectCountryTableViewController") as! MRSelectCountryTableViewController controller.delegate = delegate return controller } public static func getCountries() -> [MRCountry] { var countries = [MRCountry]() let bundle = Bundle(identifier: "org.cocoapods.MRSelectCountry") if let path = bundle?.url(forResource: "countries", withExtension: "json") { do { let jsonData = try Data(contentsOf: path, options: .mappedIfSafe) do { if let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? NSArray { for arrData in jsonResult { let country = MRCountry(json: arrData as! [String: Any]) countries.append(country) } } } catch let error as NSError { print("Error: \(error)") } } catch let error as NSError { print("Error: \(error)") } } return countries } }
mit
8a1cbdfc9f791f5e3be40d115aaa2de7
38.466667
158
0.593468
5.447853
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift
13
2219
// // Multicast.swift // Rx // // Created by Krunoslav Zaher on 2/27/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class MulticastSink<S: SubjectType, O: ObserverType>: Sink<O>, ObserverType { typealias Element = O.E typealias ResultType = Element typealias MutlicastType = Multicast<S, O.E> let parent: MutlicastType init(parent: MutlicastType, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { do { let subject = try parent.subjectSelector() let connectable = ConnectableObservable(source: self.parent.source, subject: subject) let observable = try self.parent.selector(connectable) let subscription = observable.subscribeSafe(self) let connection = connectable.connect() return BinaryDisposable(subscription, connection) } catch let e { observer?.on(.Error(e)) self.dispose() return NopDisposable.instance } } func on(event: Event<ResultType>) { observer?.on(event) switch event { case .Next: break case .Error, .Completed: self.dispose() } } } class Multicast<S: SubjectType, R>: Producer<R> { typealias SubjectSelectorType = () throws -> S typealias SelectorType = (Observable<S.E>) throws -> Observable<R> let source: Observable<S.SubjectObserverType.E> let subjectSelector: SubjectSelectorType let selector: SelectorType init(source: Observable<S.SubjectObserverType.E>, subjectSelector: SubjectSelectorType, selector: SelectorType) { self.source = source self.subjectSelector = subjectSelector self.selector = selector } override func run<O: ObserverType where O.E == R>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
8da32bc82d4805c57af9975730154e57
30.267606
133
0.617846
4.537832
false
false
false
false
prot3ct/Ventio
Ventio/Ventio/AppDelegate.swift
1
5071
// // AppDelegate.swift // Ventio // // Created by prot3ct on 3/31/17. // Copyright © 2017 Georgi Karaboichev. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = .lightContent if UserDefaults.standard.contains(key: "username") { self.window = UIWindow(frame: UIScreen.main.bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard.instantiateViewController(withIdentifier: "eventsTableViewController") self.window?.rootViewController = initialViewController self.window?.makeKeyAndVisible() } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "Ventio") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
3abfb0b09c068c18d07b6ef4189d4795
47.285714
285
0.678304
5.861272
false
false
false
false
OscarSwanros/swift
test/SILGen/nested_generics.swift
1
14790
// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen -parse-as-library %s | %FileCheck %s // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null // TODO: // - test generated SIL -- mostly we're just testing mangling here // - class_method calls // - witness_method calls // - inner generic parameters on protocol requirements // - generic parameter list on method in nested type // - types nested inside unconstrained extensions of generic types protocol Pizza : class { associatedtype Topping } protocol HotDog { associatedtype Condiment } protocol CuredMeat {} // Generic nested inside generic struct Lunch<T : Pizza> where T.Topping : CuredMeat { struct Dinner<U : HotDog> where U.Condiment == Deli<Pepper>.Mustard { let firstCourse: T let secondCourse: U? var leftovers: T var transformation: (T) -> U func coolCombination(t: T.Topping, u: U.Condiment) { func nestedGeneric<X, Y>(x: X, y: Y) -> (X, Y) { return (x, y) } _ = nestedGeneric(x: t, y: u) } } } // CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> () // CHECK-LABEL: // nestedGeneric #1 <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(x: A2, y: B2) -> (A2, B2) in nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil private @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF0A7GenericL_qd0___qd0_0_tqd0__1x_qd0_0_1ytAA5PizzaRzAA6HotDogRd__AA9CuredMeatAHRQAP9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y) // CHECK-LABEL: // nested_generics.Lunch.Dinner.init(firstCourse: A, secondCourse: Swift.Optional<A1>, leftovers: A, transformation: (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1> // CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerVAEyx_qd__Gx11firstCourse_qd__Sg06secondF0x9leftoversqd__xc14transformationtcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_owned (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U> // Non-generic nested inside generic class Deli<Spices> : CuredMeat { class Pepperoni : CuredMeat {} struct Sausage : CuredMeat {} enum Mustard { case Yellow case Dijon case DeliStyle(Spices) } } // CHECK-LABEL: // nested_generics.Deli.Pepperoni.init() -> nested_generics.Deli<A>.Pepperoni // CHECK-LABEL: sil hidden @_T015nested_generics4DeliC9PepperoniCAEyx_Gycfc : $@convention(method) <Spices> (@owned Deli<Spices>.Pepperoni) -> @owned Deli<Spices>.Pepperoni // Typealiases referencing outer generic parameters struct Pizzas<Spices> { class NewYork : Pizza { typealias Topping = Deli<Spices>.Pepperoni } class DeepDish : Pizza { typealias Topping = Deli<Spices>.Sausage } } class HotDogs { struct Bratwurst : HotDog { typealias Condiment = Deli<Pepper>.Mustard } struct American : HotDog { typealias Condiment = Deli<Pepper>.Mustard } } // Local type in extension of type in another module extension String { func foo() { // CHECK-LABEL: // init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()<A> in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> () // CHECK-LABEL: sil private @_T0SS15nested_genericsE3fooyyF6CheeseL_VADyxGx8material_tcfC struct Cheese<Milk> { let material: Milk } let _ = Cheese(material: "cow") } } // Local type in extension of type in same module extension HotDogs { func applyRelish() { // CHECK-LABEL: // init(material: A) -> Relish #1 in nested_generics.HotDogs.applyRelish() -> ()<A> in Relish #1 in nested_generics.HotDogs.applyRelish() -> () // CHECK-LABEL: sil private @_T015nested_generics7HotDogsC11applyRelishyyF0F0L_VAFyxGx8material_tcfC struct Relish<Material> { let material: Material } let _ = Relish(material: "pickles") } } struct Pepper {} struct ChiliFlakes {} // CHECK-LABEL: // nested_generics.eatDinnerGeneric<A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(d: inout nested_generics.Lunch<A>.Dinner<B>, t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics16eatDinnerGenericyAA5LunchV0D0Vyx_q_Gz1d_7ToppingQz1tAA4DeliC7MustardOyAA6PepperV_G1utAA5PizzaRzAA6HotDogR_AA9CuredMeatAJRQAR9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> () func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // Overloading concrete function with different bound generic arguments in parent type // CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAA6PepperV_G1utF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> () func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, t: Deli<ChiliFlakes>.Pepperoni, u: Deli<Pepper>.Mustard) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_owned (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_owned (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@unowned nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIexxr_AhLIexxd_TR : $@convention(thin) (@owned Pizzas<ChiliFlakes>.NewYork, @owned @callee_owned (@owned Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American // CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAL_G1utF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> () func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, t: Deli<Pepper>.Pepperoni, u: Deli<Pepper>.Mustard) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIexxr_AhLIexxd_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @owned @callee_owned (@owned Pizzas<Pepper>.NewYork) -> @out HotDogs.American) -> HotDogs.American // CHECK-LABEL: // closure #1 (nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> nested_generics.HotDogs.American in nested_generics.calls() -> () // CHECK-LABEL: sil private @_T015nested_generics5callsyyFAA7HotDogsC8AmericanVAA6PizzasV7NewYorkCyAA6PepperV_GcfU_ : $@convention(thin) (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American func calls() { let firstCourse = Pizzas<Pepper>.NewYork() let secondCourse = HotDogs.American() var dinner = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>( firstCourse: firstCourse, secondCourse: secondCourse, leftovers: firstCourse, transformation: { _ in HotDogs.American() }) let topping = Deli<Pepper>.Pepperoni() let condiment1 = Deli<Pepper>.Mustard.Dijon let condiment2 = Deli<Pepper>.Mustard.DeliStyle(Pepper()) eatDinnerGeneric(d: &dinner, t: topping, u: condiment1) eatDinnerConcrete(d: &dinner, t: topping, u: condiment2) } protocol ProtocolWithGenericRequirement { associatedtype T associatedtype U func method<V>(t: T, u: U, v: V) -> (T, U, V) } class OuterRing<T> { class InnerRing<U> : ProtocolWithGenericRequirement { func method<V>(t: T, u: U, v: V) -> (T, U, V) { return (t, u, v) } } } class SubclassOfInner<T, U> : OuterRing<T>.InnerRing<U> { override func method<V>(t: T, u: U, v: V) -> (T, U, V) { return super.method(t: t, u: u, v: v) } } // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @escaping @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIexxd_AhLIexxr_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @owned @callee_owned (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American // CHECK-LABEL: sil private [transparent] [thunk] @_T015nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementA2aGP6method1TQz_1UQzqd__tAK1t_AM1uqd__1vtlFTW : $@convention(witness_method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) { // CHECK: bb0([[T:%[0-9]+]] : @trivial $*τ_0_0, [[U:%[0-9]+]] : @trivial $*τ_1_0, [[V:%[0-9]+]] : @trivial $*τ_2_0, [[TOut:%[0-9]+]] : @trivial $*τ_0_0, [[UOut:%[0-9]+]] : @trivial $*τ_1_0, [[VOut:%[0-9]+]] : @trivial $*τ_2_0, [[SELF:%[0-9]+]] : @trivial $*OuterRing<τ_0_0>.InnerRing<τ_1_0>): // CHECK: [[SELF_COPY:%[0-9]+]] = alloc_stack $OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: copy_addr [[SELF]] to [initialization] [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: [[SELF_COPY_VAL:%[0-9]+]] = load [take] [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: [[BORROWED_SELF_COPY_VAL:%.*]] = begin_borrow [[SELF_COPY_VAL]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) // CHECK: apply [[METHOD]]<τ_0_0, τ_1_0, τ_2_0>([[T]], [[U]], [[V]], [[TOut]], [[UOut]], [[VOut]], [[BORROWED_SELF_COPY_VAL]]) : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: end_borrow [[BORROWED_SELF_COPY_VAL]] from [[SELF_COPY_VAL]] // CHECK: destroy_value [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: dealloc_stack [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: return [[RESULT]] : $() // CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Pepperoni: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Sausage: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Deli<Spices>: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.NewYork: Pizza module nested_generics { // CHECK: associated_type Topping: Deli<Spices>.Pepperoni // CHECK: } // CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.DeepDish: Pizza module nested_generics { // CHECK: associated_type Topping: Deli<Spices>.Sausage // CHECK: } // CHECK: sil_witness_table hidden HotDogs.Bratwurst: HotDog module nested_generics { // CHECK: associated_type Condiment: Deli<Pepper>.Mustard // CHECK: } // CHECK: sil_witness_table hidden HotDogs.American: HotDog module nested_generics { // CHECK: associated_type Condiment: Deli<Pepper>.Mustard // CHECK: }
apache-2.0
8d1b9dec228f5cc259da0f0a69bb8353
54.6
403
0.707344
3.23753
false
false
false
false
jdbateman/VirtualTourist
VirtualTourist/PhotoAlbumViewController.swift
1
17035
/*! @header PhotoAlbumViewController.swift VirtualTourist The PhotoAlbumViewController class displays a MapView containing a single annotation (refered to as a pin), and a collection of images in a UICollectionView. The controller supports the following functionality: - The controller dowloads images through the Flickr api based on the geo coordinates of the pin. - The New Collection button deletes all existing images associated with a pin and downloads a new set of images from Flickr. - Select an image to mark it for delete. This toggles the "New Collection" button to a "Remove Selected Pictures" button. - Delete images by selecting the "Remove Selected Pictures" button. This toggles the "Remove Selected Pictures" button back to "New Collection". - Select the Done button to change interaction back to AddPin mode. @author John Bateman. Created on 9/19/15 @copyright Copyright (c) 2015 John Bateman. All rights reserved. */ import UIKit import CoreData import MapKit class PhotoAlbumViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, flickrDelegate, NSFetchedResultsControllerDelegate { var activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50)) as UIActivityIndicatorView private let sectionInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0) /* the map at the top of the view */ @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var noImagesLabel: UILabel! var newCollectionButton: UIBarButtonItem? = nil let flickr = Flickr() /* The pin to be displayed on the map. Should be set by the source view controller. */ var pin:Pin? // The selected indexes array keeps all of the indexPaths for cells that are "selected". The array is // used inside cellForItemAtIndexPath to lower the alpha of selected cells. var selectedIndexes = [NSIndexPath]() // These arrays are used to track insertions, deletions, and updates to the collection view. var insertedIndexPaths: [NSIndexPath]! var deletedIndexPaths: [NSIndexPath]! var updatedIndexPaths: [NSIndexPath]! override func viewDidLoad() { super.viewDidLoad() // Initialize the fetchResultsController from the core data store. fetchPhotos() // set the UICollectionView data source and delegate self.collectionView.dataSource = self self.collectionView.delegate = self // set the Flickr delegate flickr.delegate = self // set the NSFetchedResultsControllerDelegate fetchedResultsController.delegate = self if let pin = pin { showPinOnMap(pin) } // configure the toolbar items let flexButtonLeft = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) newCollectionButton = UIBarButtonItem(title: "New Collection", style: .Plain, target: self, action: "onNewCollectionButtonTap") let flexButtonRight = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) self.setToolbarItems([flexButtonLeft, newCollectionButton!, flexButtonRight], animated: true) // enable display of the navigation controller's toolbar self.navigationController?.setToolbarHidden(false, animated: true) // Initialize flickrPhotos from flickr if the current pin did not contain any photos. if let pin = pin { // enable the New Collection button newCollectionButton!.enabled = true // Note: I removed the following resetPhotos() call, now that Photo.initPhotosFrom:forPin: is called when the pin is dropped. // If the count is zero, the user can select the New Collection button to fetch more images. // Fetch images from flickr if there are none associated with the currently selected pin. // if pin.photos.count == 0 { // resetPhotos() // } } } override func viewDidDisappear(animated: Bool) { fetchedResultsController.delegate = nil } /* @brief Search flickr for images by gps coordinates. Create a Photo object for each set of image meta returned. Insert each into the shared Core Data context. @discussion The data is returned from the Flickr object as an array of dictionaries, where each dictionary contains metadata for a particular image. The data does not contain the actual image data, but instead a url identifying the location of the image. */ func resetPhotos() { self.startActivityIndicator() // disable the New Collection button until the images are downloaded from flickr. newCollectionButton!.enabled = false if let pin = self.pin { self.flickr.searchPhotosBy2DCoordinates(pin) { success, error, imageMetadata in if success == true { // Create a Photo instance for each image metadata dictionary in imageMetadata. Associate each Photo with the pin. Photo.initPhotosFrom(imageMetadata, forPin: pin) // halt the activity indicator self.stopActivityIndicator() // enable the New Collection button. self.newCollectionButton!.enabled = true // force the cells to update now that the images have been downloaded dispatch_async(dispatch_get_main_queue()) { //self.view.setNeedsDisplay() self.collectionView.reloadData() } } else { // halt the activity indicator self.stopActivityIndicator() // Report error to user. (extract info from NSError userInfo dictionary.) if let error = error { let errorString = error.localizedDescription var errorTitle = "Error" switch error.code { case VTError.ErrorCodes.JSON_PARSE_ERROR.rawValue: errorTitle = "Flickr Response Error" case VTError.ErrorCodes.FLICKR_REQUEST_ERROR.rawValue: errorTitle = "Flickr API Error" default: errorTitle = "Error" } VTAlert(viewController:self).displayErrorAlertView("error_title", message: error.localizedDescription) } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: buttons func onNewCollectionButtonTap() { // remove all photos associated with this pin in core data store if let pin = pin { for photo in pin.photos { photo.deletePhoto(false) } CoreDataStackManager.sharedInstance().saveContext() } // fetch a new set of images resetPhotos() } // MARK: UICollectionViewDataSource protocol func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo let count = sectionInfo.numberOfObjects if count > 0 { self.noImagesLabel.hidden = true self.collectionView.hidden = false } else { self.noImagesLabel.hidden = false self.collectionView.hidden = true } return count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoAlbumCellID", forIndexPath: indexPath) as! PhotoAlbumCell self.configureCell(cell, atIndexPath: indexPath) return cell } // MARK: UICollectionViewDelegate protocol func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // remove the Photo object from the core data store. let photo = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Photo photo.deletePhoto(true) // force the cells to update now that the image has been downloaded self.collectionView.reloadData() } // MARK: - Core Data /* core data managed object context */ lazy var sharedContext: NSManagedObjectContext = { return CoreDataStackManager.sharedInstance().managedObjectContext! }() // MARK: - Fetched results controller lazy var fetchedResultsController: NSFetchedResultsController = { // Create the fetch request let fetchRequest = NSFetchRequest(entityName: Photo.entityName) // Define the predicate (filter) for the query. if let pin = self.pin { fetchRequest.predicate = NSPredicate(format: "pin == %@", pin) } else { println("self.pin == nil in PhotoAlbumViewController") } // Add a sort descriptor to enforce a sort order on the results. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] // Create the Fetched Results Controller let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) // Return the fetched results controller. It will be the value of the lazy variable return fetchedResultsController } () /* Perform a fetch of Photo objects to update the fetchedResultsController with the current data from the core data store. */ func fetchPhotos() { var error: NSError? = nil fetchedResultsController.performFetch(&error) if let error = error { VTAlert(viewController:self).displayErrorAlertView("Error retrieving photos", message: "Unresolved error in fetchedResultsController.performFetch \(error), \(error.userInfo)") } } // MARK: NSFetchedResultsControllerDelegate // Any change to Core Data causes these delegate methods to be called. // Initialize arrays of index paths which identify objects that will need to be changed. func controllerWillChangeContent(controller: NSFetchedResultsController) { insertedIndexPaths = [NSIndexPath]() deletedIndexPaths = [NSIndexPath]() updatedIndexPaths = [NSIndexPath]() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { // Our project does not use sections. So we can ignore these invocations. } // Save the index path of each object that is added, deleted, or updated as the change is identified by Core Data. func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type{ case .Insert: // A new Photo has been added to Core Data. Save the "newIndexPath" parameter so the cell can be added later. insertedIndexPaths.append(newIndexPath!) break case .Delete: // A Photo has been deleted from Core Data. Save the "indexPath" parameter so the corresponding cell can be removed later. deletedIndexPaths.append(indexPath!) break case .Update: // A change was made to an existing object in Core Data. // (For example, when an images is downloaded from Flickr in the Virtual Tourist app) updatedIndexPaths.append(indexPath!) break case .Move: break default: break } } // Do an update of all changes in the current batch. func controllerDidChangeContent(controller: NSFetchedResultsController) { collectionView.performBatchUpdates({() -> Void in // added for indexPath in self.insertedIndexPaths { self.collectionView.insertItemsAtIndexPaths([indexPath]) } // deleted for indexPath in self.deletedIndexPaths { self.collectionView.deleteItemsAtIndexPaths([indexPath]) } // updated for indexPath in self.updatedIndexPaths { self.collectionView.reloadItemsAtIndexPaths([indexPath]) } }, completion: nil) } // MARK: helper functions /* Display the specified pin on the MKMapView. This function sets the span. */ func showPinOnMap(pin: Pin) { // Add the annotation to a local array of annotations. var annotations = [MKPointAnnotation]() annotations.append(pin.annotation) // Add the annotation(s) to the map. self.mapView.addAnnotations(annotations) // set the mapview span let span = MKCoordinateSpanMake(0.15, 0.15) self.mapView.region.span = span // Center the map on the coordinate(s). self.mapView.setCenterCoordinate(pin.coordinate, animated: false) // Tell the OS that the mapView needs to be refreshed. self.mapView.setNeedsDisplay() } /* show activity indicator */ func startActivityIndicator() { activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge view.addSubview(activityIndicator) activityIndicator.startAnimating() } /* hide acitivity indicator */ func stopActivityIndicator() { dispatch_async(dispatch_get_main_queue()) { self.activityIndicator.stopAnimating() } } /* Set the cell image. */ func configureCell(cell: PhotoAlbumCell, atIndexPath indexPath: NSIndexPath) { cell.startActivityIndicator() let photo = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Photo // set placeholder image cell.imageView.image = UIImage(named: "placeholder.jpg") // Acquire the image from the Photo object. photo.getImage( { success, error, image in if success { dispatch_async(dispatch_get_main_queue()) { cell.stopActivityIndicator() cell.imageView.image = image } } else { cell.stopActivityIndicator() } }) } } extension String { func toDouble() -> Double? { return NSNumberFormatter().numberFromString(self)?.doubleValue } } /* Set the layout of the UICollectionView cells. */ extension PhotoAlbumViewController : UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { // calculate the cell size let nCells = 4 let nSpaces = nCells - 1 let widthSpaces: CGFloat = (4 * sectionInsets.left) + (4 * sectionInsets.right) let cellWidth = (collectionView.frame.size.width - widthSpaces ) / 4 return CGSize(width: cellWidth, height: cellWidth) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return sectionInsets } } extension PhotoAlbumViewController : flickrDelegate { // Flickr reports the number of images that will be downloaded. func numberOfPhotosToReturn(flickr: Flickr, count: Int) { println("flickrDelegate protocol reports \(count) images will be downloaded.") } }
mit
d59a41692a4de7c074719672fc310e01
39.656325
258
0.641444
5.912877
false
false
false
false
codefellows/sea-b29-iOS
Sample Projects/Week 2/PhotoFilters/PhotoFilters/Thumbnail.swift
1
981
// // Thumbnail.swift // PhotoFilters // // Created by Bradley Johnson on 1/13/15. // Copyright (c) 2015 BPJ. All rights reserved. // import UIKit class Thumbnail { var originalImage : UIImage? var filteredImage : UIImage? var filterName : String var imageQueue : NSOperationQueue var gpuContext : CIContext init( filterName : String, operationQueue : NSOperationQueue, context : CIContext) { self.filterName = filterName self.imageQueue = operationQueue self.gpuContext = context } func generateFilteredImage() { let startImage = CIImage(image: self.originalImage) let filter = CIFilter(name: self.filterName) filter.setDefaults() filter.setValue(startImage, forKey: kCIInputImageKey) let result = filter.valueForKey(kCIOutputImageKey) as CIImage let extent = result.extent() let imageRef = self.gpuContext.createCGImage(result, fromRect: extent) self.filteredImage = UIImage(CGImage: imageRef) } }
mit
45fd9402bfc07784c6da2573d6198c25
25.513514
86
0.718654
4.36
false
false
false
false
thulefog/AutoFrameLayout
AutoFrameLayout/DataLayer/DataProvider.swift
1
1812
// // DataProvider.swift // // Created by John Matthew Weston in February 2015. // Source Code - Copyright © 2015 John Matthew Weston but published as open source under MIT License. // import Foundation class DataProvider : IDataProvider { var json: JSON! var count: Int! var hydrated: Bool! var ElementCount:Int { return count } var Hydrated:Bool { return hydrated; } func ElementAtIndex(index: Int) -> String { if( index < count ) { let result = (json["SimpleStore"][index]["Instance"]) let formattedResult = result.string log( "instance \(result)") return formattedResult! } else { return "" } } init() { Populate() } func Populate() -> Bool { count = 0 if let file = NSBundle(forClass:AppDelegate.self).pathForResource("SimpleStore", ofType: "json") { let data = NSData(contentsOfFile: file)! json = JSON(data:data) for (_, _): (String, JSON) in json { log( "index \(index) " ) } //traverse the data set and log to sanity check for (index, subJson): (String, JSON) in json["SimpleStore"] { let instance = subJson["Instance"].string; let description = subJson["Description"].string; log( "index \(index) Instance \(instance) | Description \(description)" ) count!++ } //test: instance zero log( "instance \(json["SimpleStore"][0]["Instance"]) ") } hydrated = true return hydrated } }
mit
93a3f9f696aaf2a03e8e63297206364f
23.486486
106
0.500828
4.816489
false
false
false
false
rushabh55/NaviTag-iOS
iOS/SwiftExample/CameraViewController.swift
1
9897
import UIKit import CoreLocation import Foundation import MobileCoreServices class CameraViewController: UIViewController, CLLocationManagerDelegate, UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate, UIScrollViewDelegate { @IBOutlet weak var blurSlider: UISlider! @IBOutlet var backgroundImage:UIImageView? @IBOutlet weak var imageControl: UIImageView! @IBOutlet weak var pickButton: UIButton! @IBOutlet weak var hintView: UITextField! @IBOutlet weak var radioButton: UISegmentedControl! @IBOutlet weak var mangleButton: UIButton! let scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds) var cameraUI:UIImagePickerController = UIImagePickerController() var locationManager: CLLocationManager! var myLong: Double = 0.0 var myLat: Double = 0.0 override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() scrollView.addSubview(self.view) scrollView.contentSize = self.view.bounds.size scrollView.delegate = self scrollView.indicatorStyle = .White } func zoomUpdate() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var keyName = String() func getFilterName() -> String{ let rand = arc4random() let dict = ["CIVignette", "CISepiaTone","CIVignetteEffect", "CIBloom", "CIBoxBlur", "CIGaussianBlur", "CIMaskedVariableBlur","CIEdgeWork", "CIMotionBlur", "CIComicEffect"] let c = UInt32(dict.count) var i = Int(rand % c) var res = dict[i] // debugPrint(res) switch i { case 1, 2, 3, 0: keyName = "inputIntensity" case 4, 5,6,7, 8: keyName = "inputRadius" default: keyName = "" } if res == "" { return getFilterName() } return res } //pragma mark - Vie func scrollViewDidScroll(scrollView: UIScrollView){ /* Gets called when user scrolls or drags */ scrollView.alpha = 0.50 } func scrollViewDidEndDecelerating(scrollView: UIScrollView){ /* Gets called only after scrolling */ scrollView.alpha = 1 } func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool){ scrollView.alpha = 1 } // MARK: - CoreLocation Delegate Methods func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { locationManager.stopUpdatingLocation() if ((error) != nil) { print(error) } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var str: String switch(status){ case .NotDetermined: str = "NotDetermined" case .Restricted: str = "Restricted" case .Denied: str = "Denied" case .Authorized: str = "Authorized" case .AuthorizedWhenInUse: str = "AuthorizedWhenInUse" } println("locationManager auth status changed, \(str)") if( status == .Authorized || status == .AuthorizedWhenInUse ) { locationManager.startUpdatingLocation() println("startUpdatingLocation") } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { println("found \(locations.count) placemarks.") if( locations.count > 0 ){ let location = locations[0] as CLLocation; locationManager.stopUpdatingLocation() //self.L1 = location myLong = location.coordinate.latitude myLat = location.coordinate.longitude println("location updated, lat:\(location.coordinate.latitude), lon:\(location.coordinate.longitude), stop updating.") } } @IBAction func cameraShow() { self.presentCamera() } @IBAction func onAddHuntDone(sender: AnyObject) { // http://rushg.me/TreasureHunt/hunt.php?q=addHunt&name=first&image=&hint&coordinates=VARCHAR&created_user=int&count_finish_users=int var bodyData = "q=addHunt&hint=" + hintView.text + self.myLat.description + "," + self.myLong.description let URL: NSURL = NSURL(string: "http://rushg.me/TreasureHunt/hunt.php?")! let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL) request.HTTPMethod = "POST" request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding); NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in // debugPrint(NSString(data: data, encoding: NSUTF8StringEncoding)) } } func mimeTypeForPath(path: String) -> String { let pathExtension = path.pathExtension if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { return mimetype as NSString } } return "application/octet-stream"; } func createBodyWithParameters(request : NSMutableURLRequest) -> NSData { let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy" let contentType = "multipart/form-data; boundary=\(boundary)" request.setValue(contentType, forHTTPHeaderField:"Content-Type") var body = NSMutableData(); let tempData = NSMutableData() let fileName = imageControl.image let parameterName = "userfile" var imageData :NSData = UIImageJPEGRepresentation(fileName, 1.0); let mimeType = "application/octet-stream" tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : "" let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n" tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!) tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) tempData.appendData(imageData) tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(tempData) body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) return body } func presentCamera() { cameraUI = UIImagePickerController() cameraUI.delegate = self cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary //camera cameraUI.mediaTypes = [kUTTypeImage] cameraUI.allowsEditing = false self.presentViewController(cameraUI, animated: true, completion: nil) } @IBOutlet weak var staticTextView: UITextField! //pragma mark- Image @IBAction func onEditBegin(sender: AnyObject) { staticTextView.text = "Show your name" } @IBOutlet weak var navigationControl: UINavigationItem! func imagePickerControllerDidCancel(picker:UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker:UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary) { // var mediaType:NSString = info.objectForKey(UIImagePickerControllerEditedImage) as NSString var imageToSave:UIImage imageToSave = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage imageControl.image = imageToSave pickButton.hidden = true mangleButton.hidden = false blurSlider.hidden = false mangleButton.highlighted = true UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil) self.savedImage() self.dismissViewControllerAnimated(true, completion: nil) } func savedImage() { var alert:UIAlertView = UIAlertView() alert.title = "Saved!" alert.message = "Now hit the Magic Wand to see the Magic" alert.delegate = self alert.addButtonWithTitle("Awesome") alert.show() } @IBAction func onMangleClick(sender: AnyObject) { let beginImage = CIImage(image: imageControl.image) let name = getFilterName() let filter = CIFilter(name: name) if filter == nil { onMangleClick(sender) return } filter.setValue(beginImage, forKey: kCIInputImageKey) var val = blurSlider.value if keyName == "" { } else { filter.setValue(val, forKey: keyName) } let newImage = UIImage(CIImage: filter.outputImage) imageControl.image = newImage blurSlider.hidden = true mangleButton.hidden = true } func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) { NSLog("Did dismiss button: %d", buttonIndex) // self.presentCamera() } }
apache-2.0
c2218c2c9a27406689a5a0ee3159c753
33.971731
181
0.639184
5.378804
false
false
false
false
uptech/Constraid
Sources/Constraid/CupByMargin.swift
1
7126
// We don't conditional import AppKit like normal here because AppKit Autolayout doesn't support // the margin attributes that UIKit does. And of course this file isn't included in the MacOS // build target. #if os(iOS) import UIKit /** Constrains the object's leading, top, and bottom edges to be equal to the leadingMargin, topMargin, and bottomMargin edges of `itemB` - parameter itemA: The `item` you want to constrain in relation to another object - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leadingMargin, topMargin, and bottomMargin of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority these constraints use when being evaluated against other constraints - returns: Constraint collection containing the generated constraints */ public func cup(_ itemA: Constraid.View, byLeadingMarginOf itemB: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired ) -> Constraid.ConstraintCollection { itemA.translatesAutoresizingMaskIntoConstraints = false let collection = Constraid.ConstraintCollection([ NSLayoutConstraint(item: itemA, attribute: .top, relatedBy: .equal, toItem: itemB, attribute: .topMargin, multiplier: multiplier, constant: inset, priority: priority), NSLayoutConstraint(item: itemA, attribute: .leading, relatedBy: .equal, toItem: itemB, attribute: .leadingMargin, multiplier: multiplier, constant: inset, priority: priority), NSLayoutConstraint(item: itemA, attribute: .bottom, relatedBy: .equal, toItem: itemB, attribute: .bottomMargin, multiplier: multiplier, constant: (-1.0 * inset), priority: priority) ]) return collection } /** Constrains the object's trailing, top, and bottom edges to be equal to the trailingMargin, topMargin, and bottomMargin of `itemB` - parameter itemA: The `item` you want to constrain in relation to another object - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to trailingMargin, topMargin, and bottomMargin of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority these constraints use when being evaluated against other constraints - returns: Constraint collection containing the generated constraints */ public func cup(_ itemA: Constraid.View, byTrailingMarginOf itemB: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired ) -> Constraid.ConstraintCollection { itemA.translatesAutoresizingMaskIntoConstraints = false let collection = Constraid.ConstraintCollection([ NSLayoutConstraint(item: itemA, attribute: .top, relatedBy: .equal, toItem: itemB, attribute: .topMargin, multiplier: multiplier, constant: inset, priority: priority), NSLayoutConstraint(item: itemA, attribute: .trailing, relatedBy: .equal, toItem: itemB, attribute: .trailingMargin, multiplier: multiplier, constant: (-1.0 * inset), priority: priority), NSLayoutConstraint(item: itemA, attribute: .bottom, relatedBy: .equal, toItem: itemB, attribute: .bottomMargin, multiplier: multiplier, constant: (-1.0 * inset), priority: priority) ]) return collection } /** Constrains the object's leading, top, and trailing edges to be equal to the leadingMargin, topMargin, and trailingMargin edges of `itemB` - parameter itemA: The `item` you want to constrain in relation to another object - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leadingMargin, topMargin, and trailingMargin of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority these constraints use when being evaluated against other constraints - returns: Constraint collection containing the generated constraints */ public func cup(_ itemA: Constraid.View, byTopMarginOf itemB: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired ) -> Constraid.ConstraintCollection { itemA.translatesAutoresizingMaskIntoConstraints = false let collection = Constraid.ConstraintCollection([ NSLayoutConstraint(item: itemA, attribute: .leading, relatedBy: .equal, toItem: itemB, attribute: .leadingMargin, multiplier: multiplier, constant: inset, priority: priority), NSLayoutConstraint(item: itemA, attribute: .top, relatedBy: .equal, toItem: itemB, attribute: .topMargin, multiplier: multiplier, constant: inset, priority: priority), NSLayoutConstraint(item: itemA, attribute: .trailing, relatedBy: .equal, toItem: itemB, attribute: .trailingMargin, multiplier: multiplier, constant: (-1.0 * inset), priority: priority), ]) return collection } /** Constrains the object's leading, bottom, and trailing edges to be equal to the leadingMargin, bottomMargin, and trailingMargin of `itemB` - parameter itemA: The `item` you want to constrain in relation to another object - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leadingMargin, bottomMargin, and trailingMargin of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority these constraints use when being evaluated against other constraints - returns: Constraint collection containing the generated constraints */ public func cup(_ itemA: Constraid.View, byBottomMarginOf itemB: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired ) -> Constraid.ConstraintCollection { itemA.translatesAutoresizingMaskIntoConstraints = false let collection = Constraid.ConstraintCollection([ NSLayoutConstraint(item: itemA, attribute: .leading, relatedBy: .equal, toItem: itemB, attribute: .leadingMargin, multiplier: multiplier, constant: inset, priority: priority), NSLayoutConstraint(item: itemA, attribute: .bottom, relatedBy: .equal, toItem: itemB, attribute: .bottomMargin, multiplier: multiplier, constant: (-1.0 * inset), priority: priority), NSLayoutConstraint(item: itemA, attribute: .trailing, relatedBy: .equal, toItem: itemB, attribute: .trailingMargin, multiplier: multiplier, constant: (-1.0 * inset), priority: priority), ]) return collection } #endif
mit
555e1fa2f60612e5c7106ff256704824
56.467742
194
0.752175
5.057488
false
false
false
false
eduarenas80/MarvelClient
Source/Entities/Series.swift
2
3140
// // Series.swift // MarvelClient // // Copyright (c) 2016 Eduardo Arenas <[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 Foundation import SwiftyJSON public struct Series: Entity { public let id: Int public let title: String public let seriesDescription: String public let resourceURI: String public let urls: [Url] public let startYear: Int public let endYear: Int public let rating: String public let modified: NSDate? public let thumbnail: Image public let comics: ResourceList<ComicSummary> public let stories: ResourceList<StorySummary> public let events: ResourceList<EventSummary> public let characters: ResourceList<CharacterSummary> public let creators: ResourceList<CreatorSummary> public let next: SeriesSummary? public let previous: SeriesSummary? public init(json: JSON) { self.id = json["id"].int! self.title = json["title"].string! self.seriesDescription = json["description"].string! self.resourceURI = json["resourceURI"].string! self.urls = json["urls"].array!.map { Url(json: $0) } self.startYear = json["startYear"].int! self.endYear = json["endYear"].int! self.rating = json["rating"].string! self.modified = json["modified"].dateTime self.thumbnail = Image(json: json["thumbnail"]) self.comics = ResourceList<ComicSummary>(json: json["comics"]) self.stories = ResourceList<StorySummary>(json: json["stories"]) self.events = ResourceList<EventSummary>(json: json["series"]) self.characters = ResourceList<CharacterSummary>(json: json["characters"]) self.creators = ResourceList<CreatorSummary>(json: json["creators"]) self.next = json["next"].type != .Null ? SeriesSummary(json: json["next"]) : nil self.previous = json["previous"].type != .Null ? SeriesSummary(json: json["previous"]) : nil } } public struct SeriesSummary: EntitySummary { public let resourceURI: String public let name: String public init(json: JSON) { self.resourceURI = json["resourceURI"].string! self.name = json["name"].string! } }
mit
478f1be589b7181054dd7f4f2a650476
38.746835
96
0.724204
4.186667
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/Settings/AccountSettingsTableViewCell.swift
1
2712
// // AccountSettingsTableViewCell.swift // Avalon-Print // // Created by Roman Mizin on 7/2/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit class AccountSettingsTableViewCell: UITableViewCell { var icon: UIImageView = { var icon = UIImageView() icon.translatesAutoresizingMaskIntoConstraints = false icon.contentMode = .scaleAspectFit return icon }() var title: UILabel = { var title = UILabel() title.translatesAutoresizingMaskIntoConstraints = false title.font = UIFont.systemFont(ofSize: 18) title.textColor = ThemeManager.currentTheme().generalTitleColor return title }() let separator: UIView = { let separator = UIView() separator.translatesAutoresizingMaskIntoConstraints = false separator.backgroundColor = UIColor.clear return separator }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) setColor() contentView.addSubview(icon) icon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true icon.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16).isActive = true icon.widthAnchor.constraint(equalToConstant: 30).isActive = true icon.heightAnchor.constraint(equalToConstant: 30).isActive = true contentView.addSubview(title) title.centerYAnchor.constraint(equalTo: icon.centerYAnchor, constant: 0).isActive = true title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 15).isActive = true title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true title.heightAnchor.constraint(equalToConstant: 30).isActive = true addSubview(separator) separator.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true separator.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true separator.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -15).isActive = true separator.heightAnchor.constraint(equalToConstant: 0.4).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setColor() { backgroundColor = .clear accessoryView?.backgroundColor = .clear title.backgroundColor = .clear icon.backgroundColor = .clear title.textColor = ThemeManager.currentTheme().generalTitleColor selectionColor = ThemeManager.currentTheme().cellSelectionColor } override func prepareForReuse() { super.prepareForReuse() setColor() } }
gpl-3.0
329861bd2eec9b9f297f89f5d07e2289
33.75641
103
0.739948
5.095865
false
false
false
false
alexanderjarvis/PeerKit
PeerKit/Session.swift
1
2560
// // Session.swift // CardsAgainst // // Created by JP Simard on 11/3/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import Foundation import MultipeerConnectivity public protocol SessionDelegate { func connecting(myPeerID: MCPeerID, toPeer peer: MCPeerID) func connected(myPeerID: MCPeerID, toPeer peer: MCPeerID) func disconnected(myPeerID: MCPeerID, fromPeer peer: MCPeerID) func receivedData(myPeerID: MCPeerID, data: NSData, fromPeer peer: MCPeerID) func finishReceivingResource(myPeerID: MCPeerID, resourceName: String, fromPeer peer: MCPeerID, atURL localURL: NSURL) } public class Session: NSObject, MCSessionDelegate { public private(set) var myPeerID: MCPeerID var delegate: SessionDelegate? public private(set) var mcSession: MCSession public init(displayName: String, delegate: SessionDelegate? = nil) { myPeerID = MCPeerID(displayName: displayName) self.delegate = delegate mcSession = MCSession(peer: myPeerID) super.init() mcSession.delegate = self } public func disconnect() { self.delegate = nil mcSession.delegate = nil mcSession.disconnect() } // MARK: MCSessionDelegate public func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) { switch state { case .Connecting: delegate?.connecting(myPeerID, toPeer: peerID) case .Connected: delegate?.connected(myPeerID, toPeer: peerID) case .NotConnected: delegate?.disconnected(myPeerID, fromPeer: peerID) } } public func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) { delegate?.receivedData(myPeerID, data: data, fromPeer: peerID) } public func session(session: MCSession!, didReceiveStream stream: NSInputStream!, withName streamName: String!, fromPeer peerID: MCPeerID!) { // unused } public func session(session: MCSession!, didStartReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) { // unused } public func session(session: MCSession!, didFinishReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, atURL localURL: NSURL!, withError error: NSError!) { if (error == nil) { delegate?.finishReceivingResource(myPeerID, resourceName: resourceName, fromPeer: peerID, atURL: localURL) } } }
mit
b6fa3bccfce0cd22cfc3658204b4a8e4
36.101449
183
0.689844
5.150905
false
false
false
false
RocketChat/Rocket.Chat.iOS
Pods/RocketChatViewController/Composer/Classes/Library/ComposerLocalizable.swift
1
952
// // ComposerLocalizable.swift // DifferenceKit // // Created by Matheus Cardoso on 11/20/18. // import Foundation enum ComposerLocalizableKey: String { case textViewPlaceholder = "composer.textview.placeholder" case editingViewTitle = "composer.editingview.title" case swipeIndicatorViewTitle = "composer.recordaudioview.swipe" // Accessibility case sendButtonLabel = "composer.sendButton.label" case micButtonLabel = "composer.micButton.label" case addButtonLabel = "composer.addButton.label" } protocol ComposerLocalizable { static func localized(_ key: ComposerLocalizableKey) -> String } extension ComposerLocalizable { static func localized(_ key: ComposerLocalizableKey) -> String { return NSLocalizedString( key.rawValue, tableName: "Localizable", bundle: Bundle(for: ComposerView.self), value: "", comment: "" ) } }
mit
72f84849bba221ac459148424f9728a0
25.444444
68
0.684874
4.666667
false
false
false
false
tehprofessor/SwiftyFORM
Example/Custom/CustomViewController.swift
1
1356
// MIT license. Copyright (c) 2015 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class CustomViewController: FormViewController { override func populate(builder: FormBuilder) { builder.navigationTitle = "Custom cells" builder.toolbarMode = .Simple builder.demo_showInfo("Demonstration of\ncustom cells using\nCustomFormItem") builder += SectionHeaderTitleFormItem().title("World news") let loaderItem0 = CustomFormItem() loaderItem0.createCell = { return try LoadingCell.createCell() } builder += loaderItem0 builder += SectionHeaderTitleFormItem().title("Technology news") let loaderItem1 = CustomFormItem() loaderItem1.createCell = { return try LoadingCell.createCell() } builder += loaderItem1 builder += SectionHeaderTitleFormItem().title("Game news") let loaderItem2 = CustomFormItem() loaderItem2.createCell = { return try LoadingCell.createCell() } builder += loaderItem2 builder += SectionHeaderTitleFormItem().title("Fashion news") let loaderItem3 = CustomFormItem() loaderItem3.createCell = { return try LoadingCell.createCell() } builder += loaderItem3 builder += SectionHeaderTitleFormItem().title("Biz news") let loaderItem4 = CustomFormItem() loaderItem4.createCell = { return try LoadingCell.createCell() } builder += loaderItem4 } }
mit
ac4a4bac99c64c66460ef072f0f5f81d
27.25
79
0.741888
4.360129
false
false
false
false
simplicitylab/electronics-experiments
Eddy and his stones/mobile apps/SimpleIOSEddystone/Pods/Eddystone/Pod/Classes/UidFrame.swift
1
1239
// // UidFrame.swift // Pods // // Created by Tanner Nelson on 8/24/15. // // import UIKit class UidFrame: Frame { var namespace: String var instance: String var uid: String { get { return namespace + instance } } init(namespace: String, instance: String) { self.namespace = namespace self.instance = instance super.init() } override class func frameWithBytes(bytes: [Byte]) -> UidFrame? { var namespace = "" var instance = "" for (offset, byte) in bytes.enumerate() { var hex = String(byte, radix: 16) if hex.characters.count == 1 { hex = "0" + hex } switch offset { case 2...11: namespace += hex case 12...17: instance += hex default: break } } if namespace.characters.count == 20 && instance.characters.count == 12 { return UidFrame(namespace: namespace, instance: instance) } else { log("Invalid UID frame") } return nil } }
gpl-2.0
aff237262406946279b5e52bd7a0a775
20.362069
80
0.464891
4.821012
false
false
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/00175-swift-parser-parseexprlist.swift
1
3567
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g func a<d>() -> [c{ enum b { case c } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func j(d: h) -> <k>(() -> k) -> h { return { n n "\(} c i<k : i> { } y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) func p<p>() -> (p, p -> p) -> p { l c l.l = { } { p) { (e: o, h:o) -> e }) } j(k(m, k(2, 3))) func l(p: j) -> <n>(() -> n func ^(a: Boolean, Bool) -> Bool { return !(a) } func b((Any, e))(e: (Any) -> <d>(()-> d) -> f protocol A { func c()l k { func l() -> g { m "" } } class C: k, A { j func l()q c() -> g { m "" } } func e<r where r: A, r: k>(n: r) { n.c() } protocol A { typealias h } c k<r : A> { p f: r p p: r.h } protocol C l.e() } } class o { typealias l = l func h<j>() -> (j, j -> j) -> j { var f: ({ (c: e, f: e -> e) -> return f(c) }(k, i) let o: e = { c, g return f(c) }(l) -> m) -> p>, e> } class n<j : n> struct A<T> { let a: [(T, () -> ())] = [] } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } protocol A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> St} func i<l : d where l.f == c> (n: l) { } i(e()) d> Bool { e !(f) } b protocol f : b { func b ) func n<w>() -> (w, w -> w) -> w { o m o.q = { } { w) { k } } protocol n { class func q() } class o: n{ class func q {} func p(e: Int = x) { } let c = p c() func r<o: y, s q n<s> ==(r(t)) protocol p : p { } protocol p { class func c() } class e: p { class func c() { } } (e() u p).v.c() k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) { i) import Foundation class q<k>: c a(b: Int = 0) { } let c = a c() func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? { for (mx : e?) in c { struct c<d: Sequence, b where Optional<b> == d.Iterator.Element> enum S<T> { case C(T, () -> ()) } struct A<T> { let a: [(T, () - == g> { } protocol g { typealias f typealias e } struct c<h : g> : g { typealias f = h typealias e = a<c<h>, f> a) func a<b:a protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } func g<h>() -> (h, h -> h) -> h { f f: ((h, h -> h) -> h)! j f } protocol f { class func j() } struct i { f d: f.i func j() { d.j() } } class g { typealias f = f } func g(f: Int = k) { } let i = g struct l<e : Sequence> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k func f<e>() -> (e, e -> e) -> e { e b e.c = { } { e) { f } } protocol f { class func c() } class e: f{ class func c protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F func g<T where T.E == F>(f: B<T>) } struct D : C { typealias F = Int func g<T where T.E == F>(f: B<T>) { } }
apache-2.0
5c7e7b45a1c19eb8c83b482614a6e631
14.309013
87
0.436501
2.360688
false
false
false
false
dn-m/Collections
CollectionsTests/DictionaryTypeTests.swift
1
5191
// // DictionaryTypeTests.swift // Collections // // Created by James Bean on 12/23/16. // // import XCTest import Collections class DictionaryTypeTests: XCTestCase { func testSafelyAppendToExisting() { var dict = [0: [0,1,2]] dict.safelyAppend(3, toArrayWith: 0) XCTAssertEqual(dict[0]!, [0,1,2,3]) } func testSafelyAppendToNotYetExisting() { var dict = [0: [0,1,2]] dict.safelyAppend(0, toArrayWith: 1) XCTAssertEqual(dict[1]!, [0]) } func testSafelyAppendContentsToExisting() { var dict = [0: [0,1,2]] dict.safelyAppendContents(of: [3,4,5], toArrayWith: 0) XCTAssertEqual(dict[0]!, [0,1,2,3,4,5]) } func testSafelyAppendContentsToNotYetExtant() { var dict = [0: [0,1,2]] dict.safelyAppendContents(of: [0,1,2], toArrayWith: 1) XCTAssertEqual(dict[1]!, [0,1,2]) } func testSafelyAndUniquelyAppendValuePreexisting() { var dict = [0: [0,1,2]] dict.safelyAndUniquelyAppend(1, toArrayWith: 1) XCTAssertEqual(dict[0]!, [0,1,2]) } func testSafelyAndUniquelyAppendValueNotExtant() { var dict = [0: [0,1,2]] dict.safelyAndUniquelyAppend(3, toArrayWith: 0) XCTAssertEqual(dict[0]!, [0,1,2,3]) } func testEnsureArrayTypeValueForKeyPreexisting() { var dict = [0: [0], 1: [1], 2: [2]] dict.ensureValue(for: 0) XCTAssertEqual(dict[1]!, [1]) } func testEnsureArrayTypeValueForKeyNotYetExtant() { var dict = [0: [0], 1: [1], 2: [2]] dict.ensureValue(for: 3) XCTAssertEqual(dict[3]!, []) } func testEnsureDictionaryTypeValuePreexisting() { var dict = [0: [0: 0]] dict.ensureValue(for: 0) XCTAssertNotNil(dict[0]) } func testEnsureDictionaryTypeValueNotYetExtant() { var dict = [0: [0: 0]] dict.ensureValue(for: 1) XCTAssertNotNil(dict[1]) } func testUpdateValueForKeyPathThrowsAllIllFormed() { var dict = ["parent": ["child": 0]] XCTAssertThrowsError(try dict.update(1, keyPath: [1,2])) } func testEnsureValueForKeyPathIllFormedBadTypes() { var dict: Dictionary<String, Dictionary<Int, Any>> = [:] XCTAssertThrowsError(try dict.update("value", keyPath: [1, "root"])) } func testEnsureValueForKeyPathIllFormedBadKeyPathCount() { var dict: Dictionary<String, Dictionary<Int, Any>> = [:] XCTAssertThrowsError(try dict.update("value", keyPath: [1])) } func testUpdateValueForKeyPathThrowsRootIllFormed() { var dict = ["parent": ["child": 0]] XCTAssertThrowsError(try dict.update(1, keyPath: ["parent", 0])) } func testUpdateValueForKeyPathThrowsNestedIllFormed() { var dict = ["parent": ["child": 0]] XCTAssertThrowsError(try dict.update(1, keyPath: [1, "child"])) } func testUpdateValueForKeyPathStringKeys() { var dict = ["parent": ["child": 0]] try! dict.update(1, keyPath: "parent.child") XCTAssertEqual(dict["parent"]!["child"], 1) } func testUpdateValueForKeyPathHeterogeneousKeys() { var dict = ["0": [1: 2.0]] try! dict.update(2.1, keyPath: ["0", 1]) XCTAssertEqual(dict["0"]![1], 2.1) } func testMergeNewDictOvercomesOriginal() { var a = ["1": 1, "2": 2, "3": 3] let b = ["1": 0 ,"2": 1, "3": 2] a.merge(with: b) XCTAssertEqual(a,b) } func testMergedNewDictOvercomesOriginal() { let a = ["1": 1, "2": 2, "3": 3] let b = ["1": 0 ,"2": 1, "3": 2] let result = a.merged(with: b) let expected = b XCTAssertEqual(result, expected) } func testMergeNestedDict() { var a = ["1": ["a": 0], "2": ["b": 1], "3": ["c": 2]] let b = ["1": ["a": 2], "2": ["b": 1], "3": ["c": 0]] a.merge(with: b) for (key, subDict) in a { XCTAssertEqual(subDict, b[key]!) } } func testMergedNestedDict() { let a = ["1": ["a": 0], "2": ["b": 1], "3": ["c": 2]] let b = ["1": ["a": 2], "2": ["b": 1], "3": ["c": 0]] let result = a.merged(with: b) let expected = b for (key, subDict) in result { XCTAssertEqual(subDict, expected[key]!) } } func testDictionaryInitWithArrays() { let xs = [0,1,2,3,4] let ys = ["a","b","c","d","e"] let dict = Dictionary(xs,ys) XCTAssertEqual(dict[0], "a") XCTAssertEqual(dict[4], "e") } func testDictionaryInitWithArrayOfTuples() { let keysAndValues = [(1, "one"), (2, "two"), (3, "three")] _ = Dictionary(keysAndValues) } func testSortedDictionaryInitWithArraysSorted() { let xs = [0,3,4,1,2] let ys = ["a","d","e","b","c"] let dict = SortedDictionary(xs,ys) XCTAssertEqual(dict[0], "a") XCTAssertEqual(dict[4], "e") } func testEqualitySimple() { let stringByInt = [1: "one", 2: "two", 3: "three"] XCTAssert(stringByInt == [1: "one", 2: "two", 3: "three"]) } }
mit
186eaae90a402ca332dfa7d714767608
23.144186
76
0.550954
3.5628
false
true
false
false
tkremenek/swift
benchmark/single-source/DevirtualizeProtocolComposition.swift
12
1294
//===--- DevirtualizeProtocolComposition.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 // //===----------------------------------------------------------------------===// import TestsUtils public let DevirtualizeProtocolComposition = [ BenchmarkInfo(name: "DevirtualizeProtocolComposition", runFunction: run_DevirtualizeProtocolComposition, tags: [.validation, .api]), ] protocol Pingable { func ping() -> Int; func pong() -> Int} public class Game<T> { func length() -> Int { return 10 } } public class PingPong: Game<String> { } extension PingPong : Pingable { func ping() -> Int { return 1 } func pong() -> Int { return 2 } } func playGame<T>(_ x: Game<T> & Pingable) -> Int { var sum = 0 for _ in 0..<x.length() { sum += x.ping() + x.pong() } return sum } @inline(never) public func run_DevirtualizeProtocolComposition(N: Int) { for _ in 0..<N * 20_000 { blackHole(playGame(PingPong())) } }
apache-2.0
e7409ac1b220d81442451f2ad9817b43
27.755556
134
0.619011
4.094937
false
false
false
false
jeffcollier/FirebaseSwiftExample
FirebaseSwiftExample/Extensions.swift
1
2002
// // Utilities.swift // FirebaseSwiftExample // // Created by Collier, Jeff on 1/7/17. // Copyright © 2017 Collierosity, LLC. All rights reserved. // import Foundation import UIKit // Add these attributes to InterfaceBuilder under Attributes Inspector such as for a TextField // Otherwise, the attributes would be required on the User-Defined Attributes and some don't work // For example, borderColor requires cgColor @IBDesignable extension UIView { @IBInspectable var borderColor:UIColor? { set { layer.borderColor = newValue!.cgColor } get { if let color = layer.borderColor { return UIColor(cgColor:color) } else { return nil } } } @IBInspectable var borderWidth:CGFloat { set { layer.borderWidth = newValue } get { return layer.borderWidth } } @IBInspectable var cornerRadius:CGFloat { set { layer.cornerRadius = newValue clipsToBounds = newValue > 0 } get { return layer.cornerRadius } } } extension UIImage { func scaleAndCrop(withAspect: Bool, to: Int) -> UIImage? { // Scale down the image to avoid wasting unnnecesary storage and network capacity let size = CGSize(width: to, height: to) let scale = max(size.width/self.size.width, size.height/self.size.height) let width = self.size.width * scale let height = self.size.height * scale let x = (size.width - width) / CGFloat(2) let y = (size.height - height) / CGFloat(2) let scaledRect = CGRect(x: x, y: y, width: width, height: height) UIGraphicsBeginImageContextWithOptions(size, false, 0) self.draw(in: scaledRect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } }
mit
7fe1b9b3cafb84dfaf1569aa7b518fba
27.585714
97
0.605697
4.621247
false
false
false
false
VladiMihaylenko/omim
iphone/Maps/Core/Subscriptions/SubscriptionManager.swift
1
7022
@objc protocol SubscriptionManagerListener: AnyObject { func didFailToSubscribe(_ subscription: ISubscription, error: Error?) func didSubsribe(_ subscription: ISubscription) func didFailToValidate(_ subscription: ISubscription, error: Error?) func didDefer(_ subscription: ISubscription) func validationError() } class SubscriptionManager: NSObject { typealias SuscriptionsCompletion = ([ISubscription]?, Error?) -> Void typealias RestorationCompletion = (MWMValidationResult) -> Void @objc static var shared: SubscriptionManager = { return SubscriptionManager() }() private let paymentQueue = SKPaymentQueue.default() private var productsRequest: SKProductsRequest? private var subscriptionsComplection: SuscriptionsCompletion? private var products: [String: SKProduct]? private var pendingSubscription: ISubscription? private var listeners = NSHashTable<SubscriptionManagerListener>.weakObjects() private var restorationCallback: RestorationCompletion? override private init() { super.init() paymentQueue.add(self) } deinit { paymentQueue.remove(self) } @objc static func canMakePayments() -> Bool { return SKPaymentQueue.canMakePayments() } @objc func getAvailableSubscriptions(_ completion: @escaping SuscriptionsCompletion){ subscriptionsComplection = completion productsRequest = SKProductsRequest(productIdentifiers: Set(Subscription.productIds)) productsRequest!.delegate = self productsRequest!.start() } @objc func subscribe(to subscription: ISubscription) { pendingSubscription = subscription guard let product = products?[subscription.productId] else { return } paymentQueue.add(SKPayment(product: product)) } @objc func addListener(_ listener: SubscriptionManagerListener) { listeners.add(listener) } @objc func removeListener(_ listener: SubscriptionManagerListener) { listeners.remove(listener) } @objc func validate() { validate(false) } @objc func restore(_ callback: @escaping RestorationCompletion) { restorationCallback = callback validate(true) } private func validate(_ refreshReceipt: Bool) { MWMPurchaseManager.shared() .validateReceipt(MWMPurchaseManager.adsRemovalServerId(), refreshReceipt: refreshReceipt) { (_, validationResult) in self.logEvents(validationResult) if validationResult == .valid || validationResult == .notValid { MWMPurchaseManager.shared().setAdsDisabled(validationResult == .valid) self.paymentQueue.transactions .filter { Subscription.productIds.contains($0.payment.productIdentifier) && ($0.transactionState == .purchased || $0.transactionState == .restored) } .forEach { self.paymentQueue.finishTransaction($0) } } self.restorationCallback?(validationResult) self.restorationCallback = nil } } private func logEvents(_ validationResult: MWMValidationResult) { switch validationResult { case .valid: Statistics.logEvent(kStatInappValidationSuccess) Statistics.logEvent(kStatInappProductDelivered, withParameters: [kStatVendor : MWMPurchaseManager.adsRemovalVendorId()]) case .notValid: Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 0]) case .serverError: Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 2]) case .authError: Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 1]) } } } extension SubscriptionManager: SKProductsRequestDelegate { func request(_ request: SKRequest, didFailWithError error: Error) { Statistics.logEvent(kStatInappPaymentError, withParameters: [kStatError : error.localizedDescription]) subscriptionsComplection?(nil, error) subscriptionsComplection = nil productsRequest = nil } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { guard response.products.count == 3 else { subscriptionsComplection?(nil, NSError(domain: "mapsme.subscriptions", code: -1, userInfo: nil)) subscriptionsComplection = nil productsRequest = nil return } let subscriptions = response.products.map { Subscription($0) } .sorted { $0.period.rawValue > $1.period.rawValue } products = Dictionary(uniqueKeysWithValues: response.products.map { ($0.productIdentifier, $0) }) subscriptionsComplection?(subscriptions, nil) subscriptionsComplection = nil productsRequest = nil } } extension SubscriptionManager: SKPaymentTransactionObserver { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { let subscriptionTransactions = transactions.filter { Subscription.productIds.contains($0.payment.productIdentifier) } subscriptionTransactions .filter { $0.transactionState == .failed } .forEach { processFailed($0, error: $0.error) } if subscriptionTransactions.contains(where: { $0.transactionState == .purchased || $0.transactionState == .restored }) { subscriptionTransactions .filter { $0.transactionState == .purchased } .forEach { processPurchased($0) } subscriptionTransactions .filter { $0.transactionState == .restored } .forEach { processRestored($0) } validate(false) } subscriptionTransactions .filter { $0.transactionState == .deferred } .forEach { processDeferred($0) } } private func processDeferred(_ transaction: SKPaymentTransaction) { if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { listeners.allObjects.forEach { $0.didDefer(ps) } } } private func processPurchased(_ transaction: SKPaymentTransaction) { MWMPurchaseManager.shared().setAdsDisabled(true) paymentQueue.finishTransaction(transaction) if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { Statistics.logEvent(kStatInappPaymentSuccess) listeners.allObjects.forEach { $0.didSubsribe(ps) } } } private func processRestored(_ transaction: SKPaymentTransaction) { MWMPurchaseManager.shared().setAdsDisabled(true) paymentQueue.finishTransaction(transaction) if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { listeners.allObjects.forEach { $0.didSubsribe(ps) } } } private func processFailed(_ transaction: SKPaymentTransaction, error: Error?) { paymentQueue.finishTransaction(transaction) if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { Statistics.logEvent(kStatInappPaymentError, withParameters: [kStatError : error?.localizedDescription ?? ""]) listeners.allObjects.forEach { $0.didFailToSubscribe(ps, error: error) } } } }
apache-2.0
0b2fd4fc1c159f956e82285edf47546b
37.371585
104
0.724722
5.335866
false
false
false
false
cemolcay/MusicTheory
Sources/MusicTheory/Accidental.swift
1
7058
// // Enharmonics.swift // MusicTheory // // Created by Cem Olcay on 21.06.2018. // Copyright © 2018 cemolcay. All rights reserved. // // https://github.com/cemolcay/MusicTheory // import Foundation /// Returns a new accidental by adding up two accidentals in the equation. /// /// - Parameters: /// - lhs: Left hand side of the equation. /// - rhs: Right hand side of the equation. /// - Returns: Returns the sum of two accidentals. public func + (lhs: Accidental, rhs: Accidental) -> Accidental { return Accidental(integerLiteral: lhs.rawValue + rhs.rawValue) } /// Returns a new accidental by substracting two accidentals in the equation. /// /// - Parameters: /// - lhs: Left hand side of the equation. /// - rhs: Right hand side of the equation. /// - Returns: Returns the difference of two accidentals. public func - (lhs: Accidental, rhs: Accidental) -> Accidental { return Accidental(integerLiteral: lhs.rawValue - rhs.rawValue) } /// Returns a new accidental by adding up an int to the accidental in the equation. /// /// - Parameters: /// - lhs: Left hand side of the equation. /// - rhs: Right hand side of the equation. /// - Returns: Returns the sum of two accidentals. public func + (lhs: Accidental, rhs: Int) -> Accidental { return Accidental(integerLiteral: lhs.rawValue + rhs) } /// Returns a new accidental by substracting an int from the accidental in the equation. /// /// - Parameters: /// - lhs: Left hand side of the equation. /// - rhs: Right hand side of the equation. /// - Returns: Returns the difference of two accidentals. public func - (lhs: Accidental, rhs: Int) -> Accidental { return Accidental(integerLiteral: lhs.rawValue - rhs) } /// Multiples an accidental with a multiplier. /// /// - Parameters: /// - lhs: Accidental you want to multiply. /// - rhs: Multiplier. /// - Returns: Returns a multiplied acceident. public func * (lhs: Accidental, rhs: Int) -> Accidental { return Accidental(integerLiteral: lhs.rawValue * rhs) } /// Divides an accidental with a multiplier /// /// - Parameters: /// - lhs: Accidental you want to divide. /// - rhs: Multiplier. /// - Returns: Returns a divided accidental. public func / (lhs: Accidental, rhs: Int) -> Accidental { return Accidental(integerLiteral: lhs.rawValue / rhs) } /// Checks if the two accidental is identical in terms of their halfstep values. /// /// - Parameters: /// - lhs: Left hand side of the equation. /// - rhs: Right hand side of the equation. /// - Returns: Returns true if two accidentalals is identical. public func == (lhs: Accidental, rhs: Accidental) -> Bool { return lhs.rawValue == rhs.rawValue } /// Checks if the two accidental is exactly identical. /// /// - Parameters: /// - lhs: Left hand side of the equation. /// - rhs: Right hand side of the equation. /// - Returns: Returns true if two accidentalals is identical. public func === (lhs: Accidental, rhs: Accidental) -> Bool { switch (lhs, rhs) { case (.natural, .natural): return true case let (.sharps(a), .sharps(b)): return a == b case let (.flats(a), .flats(b)): return a == b default: return false } } /// The enum used for calculating values of the `Key`s and `Pitche`s. public enum Accidental: Codable, Equatable, Hashable, RawRepresentable, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral, CustomStringConvertible { /// No accidental. case natural /// Reduces the `Key` or `Pitch` value amount of halfsteps. case flats(amount: Int) /// Increases the `Key` or `Pitch` value amount of halfsteps. case sharps(amount: Int) /// Reduces the `Key` or `Pitch` value one halfstep below. public static let flat: Accidental = .flats(amount: 1) /// Increases the `Key` or `Pitch` value one halfstep above. public static let sharp: Accidental = .sharps(amount: 1) /// Reduces the `Key` or `Pitch` value amount two halfsteps below. public static let doubleFlat: Accidental = .flats(amount: 2) /// Increases the `Key` or `Pitch` value two halfsteps above. public static let doubleSharp: Accidental = .sharps(amount: 2) /// A flag for `description` function that determines if it should use double sharp and double flat symbols. /// It's useful to set it false where the fonts do not support that symbols. Defaults true. public static var shouldUseDoubleFlatAndDoubleSharpNotation = true // MARK: RawRepresentable public typealias RawValue = Int /// Value of the accidental in terms of halfsteps. public var rawValue: Int { switch self { case .natural: return 0 case let .flats(amount): return -amount case let .sharps(amount): return amount } } /// Initilizes the accidental with an integer that represents the halfstep amount. /// /// - Parameter rawValue: Halfstep value of the accidental. Zero if natural, above zero if sharp, below zero if flat. public init?(rawValue: Accidental.RawValue) { if rawValue == 0 { self = .natural } else if rawValue > 0 { self = .sharps(amount: rawValue) } else { self = .flats(amount: -rawValue) } } // MARK: ExpressibleByIntegerLiteral public typealias IntegerLiteralType = Int /// Initilizes the accidental with an integer literal value. /// /// - Parameter value: Halfstep value of the accidental. Zero if natural, above zero if sharp, below zero if flat. public init(integerLiteral value: Accidental.IntegerLiteralType) { self = Accidental(rawValue: value) ?? .natural } // MARK: ExpressibleByStringLiteral public typealias StringLiteralType = String public init(stringLiteral value: Accidental.StringLiteralType) { var sum = 0 for i in 0 ..< value.count { switch value[value.index(value.startIndex, offsetBy: i)] { case "#", "♯": sum += 1 case "b", "♭": sum -= 1 default: break } } self = Accidental(rawValue: sum) ?? .natural } // MARK: CustomStringConvertible /// Returns the notation string of the accidental. public var notation: String { if case .natural = self { return "♮" } return description } /// Returns the notation string of the accidental. Returns empty string if accidental is natural. public var description: String { switch self { case .natural: return "" case let .flats(amount): switch amount { case 0: return Accidental.natural.description case 1: return "♭" case 2 where Accidental.shouldUseDoubleFlatAndDoubleSharpNotation: return "𝄫" default: return amount > 0 ? (0 ..< amount).map({ _ in Accidental.flats(amount: 1).description }).joined() : "" } case let .sharps(amount): switch amount { case 0: return Accidental.natural.description case 1: return "♯" case 2 where Accidental.shouldUseDoubleFlatAndDoubleSharpNotation: return "𝄪" default: return amount > 0 ? (0 ..< amount).map({ _ in Accidental.sharps(amount: 1).description }).joined() : "" } } } }
mit
851dfe84e88d1c4c30d1b5e5bd0adae9
31.901869
154
0.676324
4.095986
false
false
false
false
ProjectDent/ARKit-CoreLocation
Sources/ARKit-CoreLocation/Extensions/SCNNode+Extensions.swift
1
2644
// // SCNNode+Extensions.swift // ARKit+CoreLocation // // Created by Andrew Hart on 09/07/2017. // Copyright © 2017 Project Dent. All rights reserved. // import SceneKit extension SCNNode { /// Overlapping nodes require unique renderingOrder values to avoid flicker /// This method will select random values if you don't care which node is in front of the other, /// or you can specify a particular z-order value /// Note: rendering order will be changed later based on distance from camera func removeFlicker (withRenderingOrder renderingOrder: Int = Int.random(in: 1..<Int.max)) { self.renderingOrder = renderingOrder if let geom = geometry { geom.materials.forEach { $0.readsFromDepthBuffer = false } } } /// Returns a node similar to the one displayed when an `ARSCNView`'s `.debugOptions` includes `.showWorldOrigin` class func axesNode(quiverLength: CGFloat, quiverThickness: CGFloat) -> SCNNode { let quiverThickness = (quiverLength / 50.0) * quiverThickness let chamferRadius = quiverThickness / 2.0 let xQuiverBox = SCNBox(width: quiverLength, height: quiverThickness, length: quiverThickness, chamferRadius: chamferRadius) xQuiverBox.firstMaterial?.diffuse.contents = UIColor.red let xQuiverNode = SCNNode(geometry: xQuiverBox) xQuiverNode.position = SCNVector3Make(Float(quiverLength / 2.0), 0.0, 0.0) let yQuiverBox = SCNBox(width: quiverThickness, height: quiverLength, length: quiverThickness, chamferRadius: chamferRadius) yQuiverBox.firstMaterial?.diffuse.contents = UIColor.green let yQuiverNode = SCNNode(geometry: yQuiverBox) yQuiverNode.position = SCNVector3Make(0.0, Float(quiverLength / 2.0), 0.0) let zQuiverBox = SCNBox(width: quiverThickness, height: quiverThickness, length: quiverLength, chamferRadius: chamferRadius) zQuiverBox.firstMaterial?.diffuse.contents = UIColor.blue let zQuiverNode = SCNNode(geometry: zQuiverBox) zQuiverNode.position = SCNVector3Make(0.0, 0.0, Float(quiverLength / 2.0)) let quiverNode = SCNNode() quiverNode.addChildNode(xQuiverNode) quiverNode.addChildNode(yQuiverNode) quiverNode.addChildNode(zQuiverNode) quiverNode.name = "Axes" return quiverNode } }
mit
e737bb73a36bd86e9e7a72d0a4994408
43.79661
117
0.631101
4.996219
false
false
false
false
dabing1022/DBMetaballLoading
DBMetaballLoading/ViewController.swift
1
6856
// // ViewController.swift // // Copyright (c) 2016 ChildhoodAndy (http://dabing1022.github.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class ViewController: UIViewController { @IBOutlet weak var loadingView: DBMetaballLoadingView! @IBOutlet weak var styleLabel: UILabel! @IBOutlet weak var styleSwitcher: UISwitch! @IBOutlet weak var fillColorLabel: UILabel! @IBOutlet weak var fillColorSlider: UISlider! @IBOutlet weak var strokeColorLabel: UILabel! @IBOutlet weak var strokeColorSlider: UISlider! @IBOutlet weak var ballRadiusLabel: UILabel! @IBOutlet weak var ballRadiusSlider: UISlider! @IBOutlet weak var maxDistanceLabel: UILabel! @IBOutlet weak var maxDistanceSlider: UISlider! @IBOutlet weak var mvLabel: UILabel! @IBOutlet weak var mvSlider: UISlider! @IBOutlet weak var handleLenRateLabel: UILabel! @IBOutlet weak var handleLenRateSlider: UISlider! @IBOutlet weak var spacingLabel: UILabel! @IBOutlet weak var spacingSlider: UISlider! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 0.0, green: 26.0 / 255.0, blue: 42.0 / 255.0, alpha: 1.0) self.title = "DBMetaballLoading" strokeColorSlider.value = 0.0 changeStrokeColor(strokeColorSlider) fillColorSlider.value = 0.0 changeFillColor(fillColorSlider) changeBallRadius(ballRadiusSlider) changeMaxDistance(maxDistanceSlider) changeMv(mvSlider) changeHandleLenRate(handleLenRateSlider) changeSpacing(spacingSlider) } @IBAction func switchLoadingViewStyle(_ sender: UISwitch) { if sender.isOn { styleLabel.text = "loadingStyle: Fill" loadingView.loadingStyle = .Fill } else { styleLabel.text = "loadingStyle: Stroke" loadingView.loadingStyle = .Stroke } } @IBAction func changeFillColor(_ sender: UISlider) { styleSwitcher.setOn(true, animated: true) switchLoadingViewStyle(styleSwitcher) fillColorLabel.textColor = _colorByIndex(index: NSInteger(sender.value)) loadingView.fillColor = fillColorLabel.textColor sender.minimumTrackTintColor = fillColorLabel.textColor sender.thumbTintColor = fillColorLabel.textColor } @IBAction func changeStrokeColor(_ sender: UISlider) { styleSwitcher.setOn(false, animated: true) switchLoadingViewStyle(styleSwitcher) strokeColorLabel.textColor = _colorByIndex(index: NSInteger(sender.value)) loadingView.strokeColor = strokeColorLabel.textColor sender.minimumTrackTintColor = strokeColorLabel.textColor sender.thumbTintColor = strokeColorLabel.textColor } @IBAction func changeBallRadius(_ sender: UISlider) { ballRadiusLabel.text = String(format: "ballRadius %.2f", sender.value) loadingView.ballRadius = CGFloat(sender.value) loadingView.resetAnimation() maxDistanceSlider.minimumValue = ballRadiusSlider.minimumValue * 4 maxDistanceSlider.maximumValue = ballRadiusSlider.maximumValue * 4 } @IBAction func changeMaxDistance(_ sender: UISlider) { maxDistanceLabel.text = String(format: "maxDistance %.2f", sender.value) loadingView.maxDistance = CGFloat(sender.value) loadingView.resetAnimation() } @IBAction func changeMv(_ sender: UISlider) { styleSwitcher.setOn(false, animated: true) switchLoadingViewStyle(styleSwitcher) mvLabel.text = String(format: "curveAngle: %.2f", sender.value) loadingView.curveAngle = CGFloat(sender.value) loadingView.resetAnimation() } @IBAction func changeHandleLenRate(_ sender: UISlider) { styleSwitcher.setOn(false, animated: true) switchLoadingViewStyle(styleSwitcher) handleLenRateLabel.text = String(format: "hanleLenRate: %.2f", sender.value) loadingView.handleLenRate = CGFloat(sender.value) loadingView.resetAnimation() } @IBAction func changeSpacing(_ sender: UISlider) { spacingLabel.text = String(format: "spacing: %.2f", sender.value) loadingView.spacing = CGFloat(sender.value) loadingView.resetAnimation() } @IBAction func resetConfig(sender: UIButton) { strokeColorSlider.value = 0.0 changeStrokeColor(strokeColorSlider) fillColorSlider.value = 0.0 changeFillColor(fillColorSlider) ballRadiusSlider.value = Float(DefaultConfig.radius) changeBallRadius(ballRadiusSlider) maxDistanceSlider.value = Float(DefaultConfig.maxDistance) changeMaxDistance(maxDistanceSlider) mvSlider.value = Float(DefaultConfig.curveAngle) changeMv(mvSlider) handleLenRateSlider.value = Float(DefaultConfig.handleLenRate) changeHandleLenRate(handleLenRateSlider) spacingSlider.value = Float(DefaultConfig.spacing) changeSpacing(spacingSlider) } func _colorByIndex(index: NSInteger) -> UIColor { var color = UIColor.black switch index { case 0: color = UIColor.orange break case 1: color = UIColor.yellow break case 2: color = UIColor.green break case 3: color = UIColor.cyan break case 4: color = UIColor.red break default: color = UIColor.blue } return color } }
mit
65756123bb3c07bcfd24e3cfac1713cc
34.523316
106
0.667007
4.925287
false
false
false
false
pinterest/tulsi
src/TulsiGeneratorTests/BazelSettingsProviderTests.swift
1
1888
// Copyright 2018 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import TulsiGenerator class BazelSettingsProviderTests: XCTestCase { let bazel = "/path/to/bazel" let bazelExecRoot = "__MOCK_EXEC_ROOT__" let features = Set<BazelSettingFeature>() let buildRuleEntries = Set<RuleEntry>() let bazelSettingsProvider = BazelSettingsProvider(universalFlags: BazelFlags()) func testBazelBuildSettingsProviderForWatchOS() { let options = TulsiOptionSet() let settings = bazelSettingsProvider.buildSettings( bazel: bazel, bazelExecRoot: bazelExecRoot, options: options, features: features, buildRuleEntries: buildRuleEntries) let expectedFlag = "--watchos_cpus=armv7k,arm64_32" let expectedIdentifiers = Set(["watchos_armv7k", "watchos_arm64_32", "ios_arm64", "ios_arm64e"]) // Check that both watchos flags are set for both architectures. for (identifier, flags) in settings.platformConfigurationFlags { if expectedIdentifiers.contains(identifier) { XCTAssert( flags.contains(expectedFlag), "\(expectedFlag) flag was not set for \(identifier).") } else { XCTAssert( !flags.contains(expectedFlag), "\(expectedFlag) flag was unexpectedly set for \(identifier).") } } } }
apache-2.0
bdd803ae9d3882fc8830a24f7e06f06f
36.76
100
0.710805
4.411215
false
true
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/VASTTests/PBMVastLoaderTestWrapperPlusInline.swift
1
11762
/*   Copyright 2018-2021 Prebid.org, 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 XCTest @testable import PrebidMobile class PBMVastLoaderTestWrapperPlusInline: XCTestCase { var didFetchInline:XCTestExpectation! var vastRequestSuccessfulExpectation:XCTestExpectation! var vastServerResponse: PBMAdRequestResponseVAST? override func setUp() { self.continueAfterFailure = true MockServer.shared.reset() } override func tearDown() { MockServer.shared.reset() self.didFetchInline = nil self.vastRequestSuccessfulExpectation = nil } func testRequest() { self.didFetchInline = self.expectation(description: "Expected ServerConnection to hit foo.com/inline") self.vastRequestSuccessfulExpectation = self.expectation(description: "vastRequestSuccessfulExpectation #1") let conn = UtilitiesForTesting.createConnectionForMockedTest() //////////////////////////// //Mock a server at "foo.com" //////////////////////////// MockServer.shared.reset() let ruleInline = MockServerRule(urlNeedle: "foo.com/inline/vast", mimeType: MockServerMimeType.XML.rawValue, connectionID: conn.internalID, fileName: "document_with_one_inline_ad.xml") ruleInline.mockServerReceivedRequestHandler = { (urlRequest:URLRequest) in Log.info("didFetchInline.fulfill()") self.didFetchInline.fulfill() } MockServer.shared.resetRules([ruleInline]) //Handle 404's MockServer.shared.notFoundRule.mockServerReceivedRequestHandler = { (urlRequest:URLRequest) in XCTFail("Unexpected request for \(urlRequest)") } ////////////////////////////////////////////////////////////////////////////////// //Make an ServerConnection and redirect its network requests to the Mock Server ////////////////////////////////////////////////////////////////////////////////// let adConfiguration = AdConfiguration() let adLoadManager = MockPBMAdLoadManagerVAST(bid: RawWinningBidFabricator.makeWinningBid(price: 0.1, bidder: "bidder", cacheID: "cache-id"), connection:conn, adConfiguration: adConfiguration) adLoadManager.mock_requestCompletedSuccess = { response in self.vastServerResponse = response self.vastRequestSuccessfulExpectation.fulfill() } adLoadManager.mock_requestCompletedFailure = { error in XCTFail(error.localizedDescription) } let requester = PBMAdRequesterVAST(serverConnection:conn, adConfiguration: adConfiguration) requester.adLoadManager = adLoadManager if let data = UtilitiesForTesting.loadFileAsDataFromBundle("document_with_one_wrapper_ad.xml") { requester.buildAdsArray(data) } self.waitForExpectations(timeout: 2) guard let response = self.vastServerResponse else { XCTFail() return } check(response) let inlineVastRequestSuccessfulExpectation = self.expectation(description: "Expected Inline VAST Load to be successful") let modelMaker = PBMCreativeModelCollectionMakerVAST(serverConnection:conn, adConfiguration: adConfiguration) modelMaker.makeModels(response, successCallback: { models in let createModelCount = 2 // For video interstitials with End Card, count is 2. Includes all companions. XCTAssertEqual(models.count, createModelCount) inlineVastRequestSuccessfulExpectation.fulfill() }, failureCallback: { error in inlineVastRequestSuccessfulExpectation.fulfill() XCTFail(error.localizedDescription) }) self.waitForExpectations(timeout: 10, handler: nil) } // MARK: - Check result func check(_ response: NSObject) { guard let vastResponse = response as? PBMAdRequestResponseVAST else { XCTFail() return } guard let ads = vastResponse.ads else { XCTFail() return } //There should be 1 ad. //An Ad can be either inline or wrapper; this should be inline. if (ads.count != 1) { XCTFail("Expected 1 ad, got \(ads.count)") return } let ad = ads.first! PBMAssertEq(ad.adSystem, "Inline AdSystem") PBMAssertEq(ad.adSystemVersion, "1.0") PBMAssertEq(ad.errorURIs, ["http://myErrorURL/AdError"]) PBMAssertEq(ad.impressionURIs, ["http://myTrackingURL/inline/impression", "http://myTrackingURL/inline/anotherImpression", "http://myTrackingURL/wrapper/impression", "http://myTrackingURL/wrapper/anotherImpression"]) //There should be 3 creatives: //a Linear Creative //a Companion ad Creative composed of two companions (an image and an iframe) //And a NonlinearAds Creative composed of two Nonlinear ads (an image and an iframe) PBMAssertEq(ad.creatives.count, 3) //Creative 1 - Linear let pbmVastCreativeLinear = ad.creatives[0] as! PBMVastCreativeLinear PBMAssertEq(pbmVastCreativeLinear.AdId, "601364") PBMAssertEq(pbmVastCreativeLinear.id, "6012") PBMAssertEq(pbmVastCreativeLinear.sequence, 1) PBMAssertEq(pbmVastCreativeLinear.duration, 6) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["creativeView"], ["http://myTrackingURL/inline/creativeView", "http://myTrackingURL/wrapper/creativeView"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["start"], ["http://myTrackingURL/inline/start1", "http://myTrackingURL/inline/start2", "http://myTrackingURL/wrapper/start1", "http://myTrackingURL/wrapper/start2"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["midpoint"], ["http://myTrackingURL/inline/midpoint", "http://myTrackingURL/wrapper/midpoint"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["firstQuartile"], ["http://myTrackingURL/inline/firstQuartile", "http://myTrackingURL/wrapper/firstQuartile"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["thirdQuartile"], ["http://myTrackingURL/inline/thirdQuartile", "http://myTrackingURL/wrapper/thirdQuartile"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["complete"], ["http://myTrackingURL/inline/complete", "http://myTrackingURL/wrapper/complete"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["mute"], ["http://myTrackingURL/inline/mute", "http://myTrackingURL/wrapper/mute"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["unmute"], ["http://myTrackingURL/inline/unmute", "http://myTrackingURL/wrapper/unmute"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["pause"], ["http://myTrackingURL/inline/pause", "http://myTrackingURL/wrapper/pause"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["rewind"], ["http://myTrackingURL/inline/rewind", "http://myTrackingURL/wrapper/rewind"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["resume"], ["http://myTrackingURL/inline/resume", "http://myTrackingURL/wrapper/resume"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["fullscreen"], ["http://myTrackingURL/inline/fullscreen", "http://myTrackingURL/wrapper/fullscreen"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["expand"], ["http://myTrackingURL/inline/expand", "http://myTrackingURL/wrapper/expand"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["collapse"], ["http://myTrackingURL/inline/collapse", "http://myTrackingURL/wrapper/collapse"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["acceptInvitation"], ["http://myTrackingURL/inline/acceptInvitation", "http://myTrackingURL/wrapper/acceptInvitation"]) PBMAssertEq(pbmVastCreativeLinear.vastTrackingEvents.trackingEvents["close"], ["http://myTrackingURL/inline/close", "http://myTrackingURL/wrapper/close"]) PBMAssertEq(pbmVastCreativeLinear.adParameters, "params=for&request=gohere") PBMAssertEq(pbmVastCreativeLinear.clickThroughURI, "http://www.openx.com") PBMAssertEq(pbmVastCreativeLinear.clickTrackingURIs, ["http://myTrackingURL/inline/click1", "http://myTrackingURL/inline/click2", "http://myTrackingURL/inline/custom1", "http://myTrackingURL/inline/custom2", "http://myTrackingURL/wrapper/click1", "http://myTrackingURL/wrapper/click2", "http://myTrackingURL/wrapper/custom1", "http://myTrackingURL/wrapper/custom2"]) PBMAssertEq(pbmVastCreativeLinear.mediaFiles.count, 1) let mediaFile = pbmVastCreativeLinear.mediaFiles.firstObject as! PBMVastMediaFile PBMAssertEq(mediaFile.id, "firstFile") PBMAssertEq(mediaFile.streamingDeliver, false) PBMAssertEq(mediaFile.type, "video/mp4") PBMAssertEq(mediaFile.bitrate, 500) PBMAssertEq(mediaFile.width, 400) PBMAssertEq(mediaFile.height, 300) PBMAssertEq(mediaFile.scalable, true) PBMAssertEq(mediaFile.maintainAspectRatio, true) PBMAssertEq(mediaFile.apiFramework, "VPAID") PBMAssertEq(mediaFile.mediaURI, "http://get_video_file") //Creative 2 - CompanionAds let pbmVastCreativeCompanionAds = ad.creatives[1] as! PBMVastCreativeCompanionAds PBMAssertEq(pbmVastCreativeCompanionAds.companions.count, 2) //First Companion let pbmVastCreativeCompanionAdsCompanion = pbmVastCreativeCompanionAds.companions[0] as! PBMVastCreativeCompanionAdsCompanion PBMAssertEq(pbmVastCreativeCompanionAdsCompanion.companionIdentifier, "big_box") PBMAssertEq(pbmVastCreativeCompanionAdsCompanion.width, 300) PBMAssertEq(pbmVastCreativeCompanionAdsCompanion.height, 250) //Should we support expandedWidth="600" expandedHeight="500" apiFramework="VPAID" ?? PBMAssertEq(pbmVastCreativeCompanionAdsCompanion.resource, "http://demo.tremormedia.com/proddev/vast/Blistex1.jpg") //TODO: change from "staticResource" to "jpeg" or something? PBMAssertEq(pbmVastCreativeCompanionAdsCompanion.resourceType, PBMVastResourceType.staticResource) let trackingEvents = pbmVastCreativeCompanionAdsCompanion.trackingEvents.trackingEvents PBMAssertEq(trackingEvents.count, 2) PBMAssertEq(trackingEvents["creativeView"], ["http://myTrackingURL/inline/firstCompanionCreativeView"]) PBMAssertEq(trackingEvents["creativeViewFromWrapper"], ["http://myTrackingURL/wrapper/firstCompanionCreativeView"]) PBMAssertEq(pbmVastCreativeCompanionAdsCompanion.clickThroughURI, "http://www.openx.com") } }
apache-2.0
503c9fd7c52a51661c4f44eccf27d11f
54.691943
374
0.691345
5.420203
false
false
false
false
C4Framework/C4iOS
C4/UI/View+Render.swift
2
2719
// Copyright © 2014 C4 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: The above copyright // notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import UIKit public extension View { /// Creates a flattened image of the receiver and its subviews / layers. /// - returns: A new Image @objc public func render() -> Image? { guard let l = layer else { print("Could not retrieve layer for current object: \(self)") return nil } UIGraphicsBeginImageContextWithOptions(CGSize(size), false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext()! l.render(in: context) let uiimage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Image(uiimage: uiimage!) } } public extension Shape { /// Creates a flattened image of the receiver and its subviews / layers. /// This override takes into consideration the lineWidth of the receiver. /// - returns: A new Image public override func render() -> Image? { var s = CGSize(size) var inset: CGFloat = 0 if let alpha = strokeColor?.alpha, alpha > 0.0 && lineWidth > 0 { inset = CGFloat(lineWidth/2.0) s = CGRect(frame).insetBy(dx: -inset, dy: -inset).size } let scale = CGFloat(UIScreen.main.scale) UIGraphicsBeginImageContextWithOptions(s, false, scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: CGFloat(-bounds.origin.x)+inset, y: CGFloat(-bounds.origin.y)+inset) shapeLayer.render(in: context) let uiimage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Image(uiimage: uiimage!) } }
mit
6b3dc1691a69316650d32beedabf08dd
43.557377
99
0.695364
4.84492
false
false
false
false
wieseljonas/Koloda
Pod/Classes/KolodaView/KolodaView.swift
1
21236
// // KolodaView.swift // TinderCardsSwift // // Created by Eugene Andreyev on 4/24/15. // Copyright (c) 2015 Eugene Andreyev. All rights reserved. // import UIKit import pop public enum SwipeResultDirection { case None case Left case Right } //Default values private let defaultCountOfVisibleCards = 3 private let backgroundCardsTopMargin: CGFloat = 4.0 private let backgroundCardsScalePercent: CGFloat = 0.95 private let backgroundCardsLeftMargin: CGFloat = 8.0 private let backgroundCardFrameAnimationDuration: NSTimeInterval = 0.2 //Opacity values private let defaultAlphaValueOpaque: CGFloat = 1.0 private let defaultAlphaValueTransparent: CGFloat = 0.0 private let defaultAlphaValueSemiTransparent: CGFloat = 0.7 //Animations constants private let revertCardAnimationName = "revertCardAlphaAnimation" private let revertCardAnimationDuration: NSTimeInterval = 1.0 private let revertCardAnimationToValue: CGFloat = 1.0 private let revertCardAnimationFromValue: CGFloat = 0.0 private let kolodaAppearScaleAnimationName = "kolodaAppearScaleAnimation" private let kolodaAppearScaleAnimationFromValue = CGPoint(x: 0.1, y: 0.1) private let kolodaAppearScaleAnimationToValue = CGPoint(x: 1.0, y: 1.0) private let kolodaAppearScaleAnimationDuration: NSTimeInterval = 0.8 private let kolodaAppearAlphaAnimationName = "kolodaAppearAlphaAnimation" private let kolodaAppearAlphaAnimationFromValue: CGFloat = 0.0 private let kolodaAppearAlphaAnimationToValue: CGFloat = 1.0 private let kolodaAppearAlphaAnimationDuration: NSTimeInterval = 0.8 public protocol KolodaViewDataSource:class { func kolodaNumberOfCards(koloda: KolodaView) -> UInt func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView? } public protocol KolodaViewDelegate:class { func kolodaDidSwipedCardAtIndex(koloda: KolodaView,index: UInt, direction: SwipeResultDirection) func kolodaDidRunOutOfCards(koloda: KolodaView) func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt) func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool func kolodaBackgroundCardAnimation(koloda: KolodaView) -> POPPropertyAnimation? } public class KolodaView: UIView, DraggableCardDelegate { public weak var dataSource: KolodaViewDataSource! { didSet { setupDeck() } } public weak var delegate: KolodaViewDelegate? private(set) public var currentCardNumber = 0 private(set) public var countOfCards = 0 public var countOfVisibleCards = defaultCountOfVisibleCards private var visibleCards = [DraggableCardView]() private var animating = false private var configured = false public var alphaValueOpaque: CGFloat = defaultAlphaValueOpaque public var alphaValueTransparent: CGFloat = defaultAlphaValueTransparent public var alphaValueSemiTransparent: CGFloat = defaultAlphaValueSemiTransparent //MARK: Lifecycle required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! configure() } override init(frame: CGRect) { super.init(frame: frame) configure() } deinit { unsubsribeFromNotifications() } override public func layoutSubviews() { super.layoutSubviews() if !self.configured { if self.visibleCards.isEmpty { reloadData() } else { layoutDeck() } self.configured = true } } //MARK: Configurations private func subscribeForNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "layoutDeck", name: UIDeviceOrientationDidChangeNotification, object: nil) } private func unsubsribeFromNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } private func configure() { subscribeForNotifications() } private func setupDeck() { countOfCards = Int(dataSource!.kolodaNumberOfCards(self)) if countOfCards - currentCardNumber > 0 { let countOfNeededCards = min(countOfVisibleCards, countOfCards - currentCardNumber) for index in 0..<countOfNeededCards { if let nextCardContentView = dataSource?.kolodaViewForCardAtIndex(self, index: UInt(index)) { let nextCardView = DraggableCardView(frame: frameForCardAtIndex(UInt(index))) nextCardView.delegate = self nextCardView.alpha = index == 0 ? alphaValueOpaque : alphaValueSemiTransparent nextCardView.userInteractionEnabled = index == 0 let overlayView = overlayViewForCardAtIndex(UInt(index)) nextCardView.configure(nextCardContentView, overlayView: overlayView) visibleCards.append(nextCardView) index == 0 ? addSubview(nextCardView) : insertSubview(nextCardView, belowSubview: visibleCards[index - 1]) } } } } public func layoutDeck() { for (index, card) in self.visibleCards.enumerate() { card.frame = frameForCardAtIndex(UInt(index)) } } //MARK: Frames public func frameForCardAtIndex(index: UInt) -> CGRect { let bottomOffset:CGFloat = 0 let topOffset = backgroundCardsTopMargin * CGFloat(self.countOfVisibleCards - 1) let xOffset = backgroundCardsLeftMargin * CGFloat(index) let scalePercent = backgroundCardsScalePercent let width = CGRectGetWidth(self.frame) * pow(scalePercent, CGFloat(index)) let height = (CGRectGetHeight(self.frame) - bottomOffset - topOffset) * pow(scalePercent, CGFloat(index)) let multiplier: CGFloat = index > 0 ? 1.0 : 0.0 let previousCardFrame = index > 0 ? frameForCardAtIndex(max(index - 1, 0)) : CGRectZero let yOffset = (CGRectGetHeight(previousCardFrame) - height + previousCardFrame.origin.y + backgroundCardsTopMargin) * multiplier let frame = CGRect(x: xOffset, y: yOffset, width: width, height: height) return frame } private func moveOtherCardsWithFinishPercent(percent: CGFloat) { if visibleCards.count > 1 { for index in 1..<visibleCards.count { let previousCardFrame = frameForCardAtIndex(UInt(index - 1)) var frame = frameForCardAtIndex(UInt(index)) let distanceToMoveY: CGFloat = (frame.origin.y - previousCardFrame.origin.y) * (percent / 100) frame.origin.y -= distanceToMoveY let distanceToMoveX: CGFloat = (previousCardFrame.origin.x - frame.origin.x) * (percent / 100) frame.origin.x += distanceToMoveX let widthScale = (previousCardFrame.size.width - frame.size.width) * (percent / 100) let heightScale = (previousCardFrame.size.height - frame.size.height) * (percent / 100) frame.size.width += widthScale frame.size.height += heightScale let card = visibleCards[index] card.pop_removeAllAnimations() card.frame = frame card.layoutIfNeeded() //For fully visible next card, when moving top card if let shouldTransparentize = delegate?.kolodaShouldTransparentizeNextCard(self) where shouldTransparentize == true { if index == 1 { card.alpha = alphaValueOpaque } } } } } //MARK: Animations public func applyAppearAnimation() { userInteractionEnabled = false animating = true let kolodaAppearScaleAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) kolodaAppearScaleAnimation.beginTime = CACurrentMediaTime() + cardSwipeActionAnimationDuration kolodaAppearScaleAnimation.duration = kolodaAppearScaleAnimationDuration kolodaAppearScaleAnimation.fromValue = NSValue(CGPoint: kolodaAppearScaleAnimationFromValue) kolodaAppearScaleAnimation.toValue = NSValue(CGPoint: kolodaAppearScaleAnimationToValue) kolodaAppearScaleAnimation.completionBlock = { (_, _) in self.userInteractionEnabled = true self.animating = false } let kolodaAppearAlphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) kolodaAppearAlphaAnimation.beginTime = CACurrentMediaTime() + cardSwipeActionAnimationDuration kolodaAppearAlphaAnimation.fromValue = NSNumber(float: Float(kolodaAppearAlphaAnimationFromValue)) kolodaAppearAlphaAnimation.toValue = NSNumber(float: Float(kolodaAppearAlphaAnimationToValue)) kolodaAppearAlphaAnimation.duration = kolodaAppearAlphaAnimationDuration pop_addAnimation(kolodaAppearAlphaAnimation, forKey: kolodaAppearAlphaAnimationName) pop_addAnimation(kolodaAppearScaleAnimation, forKey: kolodaAppearScaleAnimationName) } func applyRevertAnimation(card: DraggableCardView) { animating = true let firstCardAppearAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) firstCardAppearAnimation.toValue = NSNumber(float: Float(revertCardAnimationToValue)) firstCardAppearAnimation.fromValue = NSNumber(float: Float(revertCardAnimationFromValue)) firstCardAppearAnimation.duration = revertCardAnimationDuration firstCardAppearAnimation.completionBlock = { (_, _) in self.animating = false } card.pop_addAnimation(firstCardAppearAnimation, forKey: revertCardAnimationName) } //MARK: DraggableCardDelegate func cardDraggedWithFinishPercent(card: DraggableCardView, percent: CGFloat) { animating = true if let shouldMove = delegate?.kolodaShouldMoveBackgroundCard(self) where shouldMove == true { self.moveOtherCardsWithFinishPercent(percent) } } func cardSwippedInDirection(card: DraggableCardView, direction: SwipeResultDirection) { swipedAction(direction) } func cardWasReset(card: DraggableCardView) { if visibleCards.count > 1 { UIView.animateWithDuration(backgroundCardFrameAnimationDuration, delay: 0.0, options: .CurveLinear, animations: { self.moveOtherCardsWithFinishPercent(0) }, completion: { _ in self.animating = false for index in 1..<self.visibleCards.count { let card = self.visibleCards[index] card.alpha = self.alphaValueSemiTransparent } }) } else { animating = false } } func cardTapped(card: DraggableCardView) { let index = currentCardNumber + visibleCards.indexOf(card)! delegate?.kolodaDidSelectCardAtIndex(self, index: UInt(index)) } //MARK: Private private func clear() { currentCardNumber = 0 for card in visibleCards { card.removeFromSuperview() } visibleCards.removeAll(keepCapacity: true) } private func overlayViewForCardAtIndex(index: UInt) -> OverlayView? { return dataSource.kolodaViewForCardOverlayAtIndex(self, index: index) } //MARK: Actions private func swipedAction(direction: SwipeResultDirection) { animating = true visibleCards.removeAtIndex(0) currentCardNumber++ let shownCardsCount = currentCardNumber + countOfVisibleCards if shownCardsCount - 1 < countOfCards { if let dataSource = self.dataSource { let lastCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(shownCardsCount - 1)) let lastCardOverlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(shownCardsCount - 1)) let lastCardFrame = frameForCardAtIndex(UInt(currentCardNumber + visibleCards.count)) let lastCardView = DraggableCardView(frame: lastCardFrame) lastCardView.hidden = true lastCardView.userInteractionEnabled = true lastCardView.configure(lastCardContentView, overlayView: lastCardOverlayView) lastCardView.delegate = self insertSubview(lastCardView, belowSubview: visibleCards.last!) visibleCards.append(lastCardView) } } if !visibleCards.isEmpty { for (index, currentCard) in visibleCards.enumerate() { var frameAnimation: POPPropertyAnimation if let delegateAnimation = delegate?.kolodaBackgroundCardAnimation(self) where delegateAnimation.property.name == kPOPViewFrame { frameAnimation = delegateAnimation } else { frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame) (frameAnimation as! POPBasicAnimation).duration = backgroundCardFrameAnimationDuration } let shouldTransparentize = delegate?.kolodaShouldTransparentizeNextCard(self) if index != 0 { currentCard.alpha = alphaValueSemiTransparent } else { frameAnimation.completionBlock = {(_, _) in self.visibleCards.last?.hidden = false self.animating = false self.delegate?.kolodaDidSwipedCardAtIndex(self, index: UInt(self.currentCardNumber - 1), direction: direction) if (shouldTransparentize == false) { currentCard.alpha = self.alphaValueOpaque } } if (shouldTransparentize == true) { currentCard.alpha = alphaValueOpaque } else { let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) alphaAnimation.toValue = alphaValueOpaque alphaAnimation.duration = backgroundCardFrameAnimationDuration currentCard.pop_addAnimation(alphaAnimation, forKey: "alpha") } } currentCard.userInteractionEnabled = index == 0 frameAnimation.toValue = NSValue(CGRect: frameForCardAtIndex(UInt(index))) currentCard.pop_addAnimation(frameAnimation, forKey: "frameAnimation") } } else { delegate?.kolodaDidSwipedCardAtIndex(self, index: UInt(currentCardNumber - 1), direction: direction) animating = false self.delegate?.kolodaDidRunOutOfCards(self) } } public func revertAction() { if currentCardNumber > 0 && animating == false { if countOfCards - currentCardNumber >= countOfVisibleCards { if let lastCard = visibleCards.last { lastCard.removeFromSuperview() visibleCards.removeLast() } } currentCardNumber-- if let dataSource = self.dataSource { let firstCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(currentCardNumber)) let firstCardOverlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(currentCardNumber)) let firstCardView = DraggableCardView() firstCardView.alpha = alphaValueTransparent firstCardView.configure(firstCardContentView, overlayView: firstCardOverlayView) firstCardView.delegate = self addSubview(firstCardView) visibleCards.insert(firstCardView, atIndex: 0) firstCardView.frame = frameForCardAtIndex(0) applyRevertAnimation(firstCardView) } for index in 1..<visibleCards.count { let currentCard = visibleCards[index] let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame) frameAnimation.duration = backgroundCardFrameAnimationDuration currentCard.alpha = alphaValueSemiTransparent frameAnimation.toValue = NSValue(CGRect: frameForCardAtIndex(UInt(index))) currentCard.userInteractionEnabled = false currentCard.pop_addAnimation(frameAnimation, forKey: "frameAnimation") } } } private func loadMissingCards(missingCardsCount: Int) { if missingCardsCount > 0 { let cardsToAdd = min(missingCardsCount, countOfCards - currentCardNumber) for index in 1...cardsToAdd { let nextCardIndex = countOfVisibleCards - cardsToAdd + index - 1 let nextCardView = DraggableCardView(frame: frameForCardAtIndex(UInt(index))) nextCardView.alpha = alphaValueSemiTransparent nextCardView.delegate = self visibleCards.append(nextCardView) insertSubview(nextCardView, belowSubview: visibleCards[index - 1]) } } reconfigureCards() } private func reconfigureCards() { for index in 0..<visibleCards.count { if let dataSource = self.dataSource { let currentCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(currentCardNumber + index)) let overlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(currentCardNumber + index)) let currentCard = visibleCards[index] currentCard.configure(currentCardContentView, overlayView: overlayView) } } } public func reloadData() { countOfCards = Int(dataSource!.kolodaNumberOfCards(self)) let missingCards = min(countOfVisibleCards - visibleCards.count, countOfCards - (currentCardNumber + 1)) if countOfCards == 0 { return } if currentCardNumber == 0 { clear() } if countOfCards - (currentCardNumber + visibleCards.count) > 0 { if !visibleCards.isEmpty { loadMissingCards(missingCards) } else { setupDeck() layoutDeck() if let shouldApply = delegate?.kolodaShouldApplyAppearAnimation(self) where shouldApply == true { self.alpha = 0 applyAppearAnimation() } } } else { reconfigureCards() } } public func swipe(direction: SwipeResultDirection) { if (animating == false) { if let frontCard = visibleCards.first { animating = true if visibleCards.count > 1 { if let shouldTransparentize = delegate?.kolodaShouldTransparentizeNextCard(self) where shouldTransparentize == true { let nextCard = visibleCards[1] nextCard.alpha = alphaValueOpaque } } switch direction { case SwipeResultDirection.None: frontCard.swipeNone() case SwipeResultDirection.Left: frontCard.swipeLeft() case SwipeResultDirection.Right: frontCard.swipeRight() } } } } public func resetCurrentCardNumber() { clear() reloadData() } }
mit
133621a513370f24a6b337b7c68df353
38.325926
147
0.605105
6.324002
false
false
false
false
ericmarkmartin/Nightscouter2
Common/Stores/SitesDataSource.swift
1
7846
// // SitesDataSource.swift // Nightscouter // // Created by Peter Ina on 1/15/16. // Copyright © 2016 Nothingonline. All rights reserved. // import Foundation public enum DefaultKey: String, RawRepresentable { case sites, lastViewedSiteIndex, primarySiteUUID, lastDataUpdateDateFromPhone, updateData, action, error static var payloadPhoneUpdate: [String : String] { return [DefaultKey.action.rawValue: DefaultKey.updateData.rawValue] } static var payloadPhoneUpdateError: [String : String] { return [DefaultKey.action.rawValue: DefaultKey.error.rawValue] } } public class SitesDataSource: SiteStoreType { public static let sharedInstance = SitesDataSource() private init() { self.defaults = NSUserDefaults(suiteName: AppConfiguration.sharedApplicationGroupSuiteName ) ?? NSUserDefaults.standardUserDefaults() let watchConnectivityManager = WatchSessionManager.sharedManager watchConnectivityManager.store = self watchConnectivityManager.startSession() let iCloudManager = iCloudKeyValueStore() iCloudManager.store = self iCloudManager.startSession() self.sessionManagers = [watchConnectivityManager, iCloudManager] } private let defaults: NSUserDefaults private var sessionManagers: [SessionManagerType] = [] public var storageLocation: StorageLocation { return .LocalKeyValueStore } public var otherStorageLocations: SiteStoreType? public var sites: [Site] { if let loaded = loadData() { return loaded } return [] } public var lastViewedSiteIndex: Int { get { return defaults.objectForKey(DefaultKey.lastViewedSiteIndex.rawValue) as? Int ?? 0 } set { if lastViewedSiteIndex != newValue { saveData([DefaultKey.lastViewedSiteIndex.rawValue: newValue]) } } } public var primarySite: Site? { set{ if let site = newValue { saveData([DefaultKey.primarySiteUUID.rawValue: site.uuid.UUIDString]) } } get { if let uuidString = defaults.objectForKey(DefaultKey.primarySiteUUID.rawValue) as? String { return sites.filter { $0.uuid.UUIDString == uuidString }.first } else if let firstSite = sites.first { return firstSite } return nil } } // MARK: Array modification methods public func createSite(site: Site, atIndex index: Int?) -> Bool { var initial: [Site] = self.sites if initial.isEmpty { primarySite = site } if let index = index { initial.insert(site, atIndex: index) } else { initial.append(site) } let siteDict = initial.map { $0.encode() } saveData([DefaultKey.sites.rawValue: siteDict]) return initial.contains(site) } public func updateSite(site: Site) -> Bool { var initial = sites let success = initial.insertOrUpdate(site) let siteDict = initial.map { $0.encode() } saveData([DefaultKey.sites.rawValue: siteDict]) return success } public func deleteSite(site: Site) -> Bool { var initial = sites let success = initial.remove(site) AppConfiguration.keychain[site.uuid.UUIDString] = nil if site == lastViewedSite { lastViewedSiteIndex = 0 } if sites.isEmpty { lastViewedSiteIndex = 0 primarySite = nil } let siteDict = initial.map { $0.encode() } saveData([DefaultKey.sites.rawValue: siteDict]) return success } public func clearAllSites() -> Bool { var initial = sites initial.removeAll() saveData([DefaultKey.sites.rawValue: []]) return initial.isEmpty } public func handleApplicationContextPayload(payload: [String : AnyObject]) { if let sites = payload[DefaultKey.sites.rawValue] as? ArrayOfDictionaries { defaults.setObject(sites, forKey: DefaultKey.sites.rawValue) } else { print("No sites were found.") } if let lastViewedSiteIndex = payload[DefaultKey.lastViewedSiteIndex.rawValue] as? Int { self.lastViewedSiteIndex = lastViewedSiteIndex } else { print("No lastViewedIndex was found.") } if let uuidString = payload[DefaultKey.primarySiteUUID.rawValue] as? String { self.primarySite = sites.filter{ $0.uuid.UUIDString == uuidString }.first } else { print("No primarySiteUUID was found.") } #if os(watchOS) if let lastDataUpdateDateFromPhone = payload[DefaultKey.lastDataUpdateDateFromPhone.rawValue] as? NSDate { defaults.setObject(lastDataUpdateDateFromPhone,forKey: DefaultKey.lastDataUpdateDateFromPhone.rawValue) } #endif if let action = payload[DefaultKey.action.rawValue] as? String { if action == DefaultKey.updateData.rawValue { print("found an action: \(action)") for site in sites { #if os(iOS) dispatch_async(dispatch_get_main_queue()) { // let socket = NightscoutSocketIOClient(site: site) // socket.fetchConfigurationData().startWithNext { racSite in // // if let racSite = racSite { // // self.updateSite(racSite) // // } // } // socket.fetchSocketData().observeNext { racSite in // self.updateSite(racSite) // } } #endif } } else if action == DefaultKey.error.rawValue { print("Received an error.") } else { print("Did not find an action.") } } defaults.synchronize() NSNotificationCenter.defaultCenter().postNotificationName(DataUpdatedNotification, object: nil) } public func loadData() -> [Site]? { if let sites = defaults.arrayForKey(DefaultKey.sites.rawValue) as? ArrayOfDictionaries { return sites.flatMap { Site.decode($0) } } return [] } public func saveData(dictionary: [String: AnyObject]) -> (savedLocally: Bool, updatedApplicationContext: Bool) { var dictionaryToSend = dictionary var successfullSave: Bool = false for (key, object) in dictionaryToSend { defaults.setObject(object, forKey: key) } dictionaryToSend[DefaultKey.lastDataUpdateDateFromPhone.rawValue] = NSDate() successfullSave = defaults.synchronize() var successfullAppContextUpdate = true sessionManagers.forEach({ (manager: SessionManagerType ) -> () in do { try manager.updateApplicationContext(dictionaryToSend) } catch { successfullAppContextUpdate = false fatalError("Something didn't go right, create a fix.") } }) return (successfullSave, successfullAppContextUpdate) } }
mit
2e018d56274bb38066c098166efdc408
31.417355
141
0.563161
5.591589
false
false
false
false
y16ra/CookieCrunch
CookieCrunch/Swap.swift
1
750
// // Swap.swift // CookieCrunch // // Created by Ichimura Yuichi on 2015/08/01. // Copyright (c) 2015年 Ichimura Yuichi. All rights reserved. // import Foundation struct Swap: CustomStringConvertible, Hashable { let cookieA: Cookie let cookieB: Cookie init(cookieA: Cookie, cookieB: Cookie) { self.cookieA = cookieA self.cookieB = cookieB } var description: String { return "swap \(cookieA) with \(cookieB)" } var hashValue: Int { return cookieA.hashValue ^ cookieB.hashValue } } func ==(lhs: Swap, rhs: Swap) -> Bool { return (lhs.cookieA == rhs.cookieA && lhs.cookieB == rhs.cookieB) || (lhs.cookieB == rhs.cookieA && lhs.cookieA == rhs.cookieB) }
mit
6614f7a9f0862d2293b7e9618f7287af
22.375
72
0.620321
3.816327
false
false
false
false
SwiftAndroid/swift-jni
JNIObjects.swift
1
1144
import CJNI public extension JNI { public func AllocObject(targetClass: jclass) -> jobject { let env = self._env return env.memory.memory.AllocObject(env, targetClass) } public func NewObject(targetClass: jclass, _ methodID: jmethodID, _ args: jvalue...) -> jobject { return self.NewObjectA(targetClass, _ methodID: methodID, _ args: args) } @available(*, unavailable, message="CVaListPointer unavailable, use NewObject or NewObjectA") public func NewObjectV(targetClass: jclass, _ methodID: jmethodID, _ args: CVaListPointer) -> jobject { // let env = self._env // return env.memory.memory.NewObjectV(env, targetClass, methodID, args) return jobject() } public func NewObjectA(targetClass: jclass, _ methodID: jmethodID, _ args: [jvalue]) -> jobject { let env = self._env var mutableArgs = args return env.memory.memory.NewObjectA(env, targetClass, methodID, &mutableArgs) } public func GetObjectClass(obj: jobject) -> jclass? { let env = self._env let result = env.memory.memory.GetObjectClass(env, obj) return (result != nil) ? result : .None } }
apache-2.0
5919ef1d37bf30795a553ec008f74fde
33.666667
104
0.684441
3.864865
false
false
false
false
infinitetoken/Arcade
Sources/Protocols/Storable.swift
1
410
// // Storable.swift // Arcade // // Created by A.C. Wright Design on 10/30/17. // Copyright © 2017 A.C. Wright Design. All rights reserved. // import Foundation public func !=(lhs: Storable, rhs: Storable) -> Bool { return lhs.persistentId != rhs.persistentId } public func ==(lhs: Storable, rhs: Storable) -> Bool { return lhs.persistentId == rhs.persistentId } public protocol Storable: Viewable {}
mit
fe6fa1212736d9d0efbaf60270cfd034
28.214286
100
0.694377
3.619469
false
false
false
false
stephanmantler/SwiftyGPIO
Sources/SPI.swift
1
13388
/* SwiftyGPIO Copyright (c) 2016 Umberto Raimondi Licensed under the MIT license, as follows: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.) */ #if os(Linux) import Glibc #else import Darwin.C #endif extension SwiftyGPIO { public static func hardwareSPIs(for board: SupportedBoard) -> [SPIInterface]? { switch board { case .CHIP: return [SPICHIP[0]!] case .RaspberryPiRev1: fallthrough case .RaspberryPiRev2: fallthrough case .RaspberryPiPlusZero: fallthrough case .RaspberryPi2: fallthrough case .RaspberryPi3: return [SPIRPI[0]!, SPIRPI[1]!] default: return nil } } } // MARK: - SPI Presets extension SwiftyGPIO { // RaspberryPis SPIs static let SPIRPI: [Int:SPIInterface] = [ 0: SysFSSPI(spiId:"0.0"), 1: SysFSSPI(spiId:"0.1") ] // CHIP SPIs // Supported but not readily available // See: https://bbs.nextthing.co/t/can-interface-spi-and-can-utils/18042/3 // https://bbs.nextthing.co/t/can-bus-mcp2515-via-spi-anyone/11388/2 static let SPICHIP: [Int:SPIInterface] = [ 0: SysFSSPI(spiId:"2.0") ] } // MARK: SPI public protocol SPIInterface { // Send data at the requested frequency (from 500Khz to 20 Mhz) func sendData(_ values: [UInt8], frequencyHz: UInt) // Send data at the default frequency func sendData(_ values: [UInt8]) // Send data and then receive a chunck of data at the requested frequency (from 500Khz to 20 Mhz) func sendDataAndRead(_ values: [UInt8], frequencyHz: UInt) -> [UInt8] // Send data and then receive a chunck of data at the default frequency func sendDataAndRead(_ values: [UInt8]) -> [UInt8] // Returns true if the SPIInterface is using a real SPI pin, false if performing bit-banging var isHardware: Bool { get } } /// Hardware SPI via SysFS public final class SysFSSPI: SPIInterface { struct spi_ioc_transfer { var tx_buf: UInt64 var rx_buf: UInt64 var len: UInt32 var speed_hz: UInt32 = 500000 var delay_usecs: UInt16 = 0 var bits_per_word: UInt8 = 8 let cs_change: UInt8 = 0 let tx_nbits: UInt8 = 0 let rx_nbits: UInt8 = 0 let pad: UInt16 = 0 } let spiId: String var mode: CInt = 0 var bits: UInt8 = 8 var speed: UInt32 = 500000 var delay: UInt16 = 0 public init(spiId: String) { self.spiId=spiId //TODO: Check if available? } public var isHardware = true public func sendData(_ values: [UInt8], frequencyHz: UInt = 500000) { if frequencyHz > 500000 { speed = UInt32(frequencyHz) } transferData(SPIBASEPATH+spiId, tx:values) } public func sendData(_ values: [UInt8]) { sendData(values, frequencyHz: 500000) } public func sendDataAndRead(_ values: [UInt8], frequencyHz: UInt = 500000) -> [UInt8] { if frequencyHz > 500000 { speed = UInt32(frequencyHz) } let rx = transferData(SPIBASEPATH+spiId, tx:values) return rx } public func sendDataAndRead(_ values: [UInt8]) -> [UInt8] { return sendDataAndRead(values, frequencyHz: 500000) } /// Write and read bits, will need a few dummy writes if you want only read @discardableResult private func transferData(_ path: String, tx: [UInt8]) -> [UInt8] { let rx: [UInt8] = [UInt8](repeating:0, count: tx.count) let fd = open(path, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } var tr = spi_ioc_transfer( tx_buf: UInt64( UInt(bitPattern: UnsafeMutablePointer(mutating: tx)) ), rx_buf: UInt64( UInt(bitPattern: UnsafeMutablePointer(mutating: rx)) ), len: UInt32(tx.count), speed_hz: speed, delay_usecs: delay, bits_per_word: bits) let r = ioctl(fd, SPI_IOC_MESSAGE1, &tr) if r < 1 { perror("Couldn't send spi message") abort() } close(fd) return rx } public func setMode(_ to: CInt) { mode = to let fd = open(SPIBASEPATH+spiId, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } let r = ioctl(fd, SPI_IOC_WR_MODE, &mode) if r == -1 { fatalError("Couldn't set spi mode") } close(fd) } public func getMode() -> CInt { let fd = open(SPIBASEPATH+spiId, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } let r = ioctl(fd, SPI_IOC_RD_MODE, &mode) if r == -1 { fatalError("Couldn't get spi mode") } close(fd) return mode } public func setBitsPerWord(_ to: UInt8) { bits = to let fd = open(SPIBASEPATH+spiId, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } let r = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits) if r == -1 { fatalError("Couldn't set bits per word") } close(fd) } public func getBitsPerWord() -> UInt8 { let fd = open(SPIBASEPATH+spiId, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } let r = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits) if r == -1 { fatalError("Couldn't get bits per word") } close(fd) return bits } public func setMaxSpeedHz(_ to: UInt32) { speed = to let fd = open(SPIBASEPATH+spiId, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } let r = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed) if r == -1 { fatalError("Couldn't set max speed hz") } close(fd) } public func getMaxSpeedHz() -> UInt32 { let fd = open(SPIBASEPATH+spiId, O_RDWR) guard fd > 0 else { fatalError("Couldn't open the SPI device") } let r = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed) if r == -1 { fatalError("Couldn't get max speed hz") } close(fd) return speed } } /// Bit-banging virtual SPI implementation, output only public final class VirtualSPI: SPIInterface { let mosiGPIO, misoGPIO, clockGPIO, csGPIO: GPIO public init(mosiGPIO: GPIO, misoGPIO: GPIO, clockGPIO: GPIO, csGPIO: GPIO) { self.mosiGPIO = mosiGPIO self.mosiGPIO.direction = .OUT self.mosiGPIO.value = 0 self.misoGPIO = misoGPIO self.misoGPIO.direction = .IN self.clockGPIO = clockGPIO self.clockGPIO.direction = .OUT self.clockGPIO.value = 0 self.csGPIO = csGPIO self.csGPIO.direction = .OUT self.csGPIO.value = 1 } public var isHardware = true public func sendData(_ values: [UInt8], frequencyHz: UInt = 500000) { let mmapped = mosiGPIO.isMemoryMapped() if mmapped { sendDataGPIOObj(values, frequencyHz: frequencyHz, read: false) } else { sendDataSysFSGPIO(values, frequencyHz: frequencyHz, read: false) } } public func sendData(_ values: [UInt8]) { sendData(values, frequencyHz: 0) } public func sendDataAndRead(_ values: [UInt8], frequencyHz: UInt = 500000) -> [UInt8] { let mmapped = mosiGPIO.isMemoryMapped() var rx = [UInt8]() if mmapped { rx = sendDataGPIOObj(values, frequencyHz: frequencyHz, read: true) } else { rx = sendDataSysFSGPIO(values, frequencyHz: frequencyHz, read: true) } return rx } public func sendDataAndRead(_ values: [UInt8]) -> [UInt8] { return sendDataAndRead(values, frequencyHz: 0) } @discardableResult private func sendDataGPIOObj(_ values: [UInt8], frequencyHz: UInt, read: Bool) -> [UInt8] { var rx: [UInt8] = [UInt8]() var bit: Int = 0 var rbit: UInt8 = 0 //Begin transmission cs=LOW csGPIO.value = 0 for value in values { rbit = 0 for i in 0...7 { bit = ((value & UInt8(1 << (7-i))) == 0) ? 0 : 1 mosiGPIO.value = bit clockGPIO.value = 1 if frequencyHz > 0 { let amount = UInt32(1_000_000/Double(frequencyHz)) // Calling usleep introduces significant delay, don't sleep for small values if amount > 50 { usleep(amount) } } clockGPIO.value = 0 if read { rbit |= ( UInt8(misoGPIO.value) << (7-UInt8(i)) ) } } if read { rx.append(rbit) } } //End transmission cs=HIGH csGPIO.value = 1 return rx } @discardableResult private func sendDataSysFSGPIO(_ values: [UInt8], frequencyHz: UInt, read: Bool) -> [UInt8] { var rx: [UInt8] = [UInt8]() let mosipath = GPIOBASEPATH+"gpio"+String(self.mosiGPIO.id)+"/value" let misopath = GPIOBASEPATH+"gpio"+String(self.misoGPIO.id)+"/value" let sclkpath = GPIOBASEPATH+"gpio"+String(self.clockGPIO.id)+"/value" let HIGH = "1" let LOW = "0" //Begin transmission cs=LOW csGPIO.value = 0 let fpmosi: UnsafeMutablePointer<FILE>! = fopen(mosipath, "w") let fpmiso: UnsafeMutablePointer<FILE>! = fopen(misopath, "r") let fpsclk: UnsafeMutablePointer<FILE>! = fopen(sclkpath, "w") guard (fpmosi != nil)&&(fpsclk != nil) else { perror("Error while opening gpio") abort() } setvbuf(fpmosi, nil, _IONBF, 0) setvbuf(fpmiso, nil, _IONBF, 0) setvbuf(fpsclk, nil, _IONBF, 0) var bit: String = LOW var rbit: UInt8 = 0 for value in values { rbit = 0 for i in 0...7 { bit = ((value & UInt8(1 << (7-i))) == 0) ? LOW : HIGH writeToFP(fpmosi, value:bit) writeToFP(fpsclk, value:HIGH) if frequencyHz > 0 { let amount = UInt32(1_000_000/Double(frequencyHz)) // Calling usleep introduces significant delay, don't sleep for small values if amount > 50 { usleep(amount) } } writeToFP(fpsclk, value:LOW) if read { rbit |= ( readFromFP(fpmiso) << (7-UInt8(i)) ) } } if read { rx.append(rbit) } } fclose(fpmosi) fclose(fpmiso) fclose(fpsclk) //End transmission cs=HIGH csGPIO.value = 1 return rx } private func writeToFP(_ fp: UnsafeMutablePointer<FILE>, value: String) { let ret = fwrite(value, MemoryLayout<CChar>.stride, 1, fp) if ret<1 { if ferror(fp) != 0 { perror("Error while writing to file") abort() } } } private func readFromFP(_ fp: UnsafeMutablePointer<FILE>) -> UInt8 { var value: UInt8 = 0 let ret = fread(&value, MemoryLayout<CChar>.stride, 1, fp) if ret<1 { if ferror(fp) != 0 { perror("Error while reading from file") abort() } } return value } } // MARK: - SPI Constants internal let SPI_IOC_WR_MODE: UInt = 0x40016b01 internal let SPI_IOC_RD_MODE: UInt = 0x80016b01 internal let SPI_IOC_WR_BITS_PER_WORD: UInt = 0x40016b03 internal let SPI_IOC_RD_BITS_PER_WORD: UInt = 0x80016b03 internal let SPI_IOC_WR_MAX_SPEED_HZ: UInt = 0x40046b04 internal let SPI_IOC_RD_MAX_SPEED_HZ: UInt = 0x80046b04 internal let SPI_IOC_MESSAGE1: UInt = 0x40206b00 internal let SPIBASEPATH="/dev/spidev" // MARK: - Darwin / Xcode Support #if os(OSX) || os(iOS) private var O_SYNC: CInt { fatalError("Linux only") } #endif
mit
e500e8c59335c8f5f1699daecfc646dd
29.085393
101
0.567673
3.983338
false
false
false
false
stephentyrone/swift
test/Driver/Dependencies/fail-with-bad-deps-fine.swift
5
3292
/// main ==> depends-on-main | bad ==> depends-on-bad // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled main.swift // CHECK-FIRST: Handled bad.swift // CHECK-FIRST: Handled depends-on-main.swift // CHECK-FIRST: Handled depends-on-bad.swift // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-NONE %s // CHECK-NONE-NOT: Handled // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t // RUN: touch -t 201401240006 %t/bad.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s // CHECK-BUILD-ALL-NOT: warning // CHECK-BUILD-ALL: Handled bad.swift // CHECK-BUILD-ALL-DAG: Handled main.swift // CHECK-BUILD-ALL-DAG: Handled depends-on-main.swift // CHECK-BUILD-ALL-DAG: Handled depends-on-bad.swift // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t // RUN: touch -t 201401240007 %t/bad.swift %t/main.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-WITH-FAIL %s // RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps // CHECK-WITH-FAIL: Handled main.swift // CHECK-WITH-FAIL-NOT: Handled depends // CHECK-WITH-FAIL: Handled bad.swift // CHECK-WITH-FAIL-NOT: Handled depends // CHECK-RECORD-DAG: "./bad.swift": !private [ // CHECK-RECORD-DAG: "./main.swift": [ // CHECK-RECORD-DAG: "./depends-on-main.swift": !private [ // CHECK-RECORD-DAG: "./depends-on-bad.swift": [ // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies ./bad.swift ./main.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s
apache-2.0
5361d8453e79c6a010c6beb7c2bf2f21
64.84
379
0.71932
3.068034
false
false
false
false
Sadmansamee/quran-ios
Quran/ConnectionsPool.swift
1
1417
// // ConnectionsPool.swift // Quran // // Created by Mohamed Afifi on 10/30/16. // Copyright © 2016 Quran.com. All rights reserved. // import Foundation import SQLite import CSQLite final class ConnectionsPool { static var `default`: ConnectionsPool = ConnectionsPool() var pool: [String: (uses: Int, connection: Connection)] = [:] func getConnection(filePath: String) throws -> Connection { if let (uses, connection) = pool[filePath] { pool[filePath] = (uses + 1, connection) return connection } else { do { let connection = try Connection(filePath, readonly: false) pool[filePath] = (1, connection) return connection } catch { Crash.recordError(error, reason: "Cannot open connection to sqlite file '\(filePath)'.") throw PersistenceError.openDatabase(error) } } } func close(connection: Connection) { let filePath = String(cString: sqlite3_db_filename(connection.handle, nil)) if let (uses, connection) = pool[filePath] { if uses <= 1 { pool[filePath] = nil // remove it } else { pool[filePath] = (uses - 1, connection) } } else { CLog("Warning: Closing connection multiple times '\(filePath)'") } } }
mit
a6d04f0034e4a9fe5a75861c62115f47
29.12766
104
0.565678
4.582524
false
false
false
false
iOSTestApps/PhoneBattery
PhoneBattery/DeviceInformation.swift
1
924
// // DeviceInformation.swift // PhoneBattery // // Created by Marcel Voß on 29.07.15. // Copyright (c) 2015 Marcel Voss. All rights reserved. // import UIKit class DeviceInformation: NSObject { class func hardwareIdentifier() -> String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var hw_machine = [CChar](count: Int(size), repeatedValue: 0) sysctl(&name, 2, &hw_machine, &size, &name, 0) let hardware: String = String.fromCString(hw_machine)! return hardware } class func appIdentifiers() -> (String, String) { let shortString = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String let buildString = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String return (shortString, buildString) } }
mit
77290ce079949607d4ef8b5864a8fa0b
28.774194
104
0.624052
4.066079
false
false
false
false
StevenUpForever/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/SignalHandler.swift
2
1494
/** * 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 struct SignalInfo : EventReporterSubject { let signo: Int32 let name: String var jsonDescription: JSON { get { return JSON.dictionary([ "signo" : JSON.number(NSNumber(value: self.signo as Int32)), "name" : JSON.string(self.name), ]) }} var description: String { get { return "\(self.name) \(self.signo)" }} } let signalPairs: [SignalInfo] = [ SignalInfo(signo: SIGTERM, name: "SIGTERM"), SignalInfo(signo: SIGHUP, name: "SIGHUP"), SignalInfo(signo: SIGINT, name: "SIGINT") ] func ignoreSignal(_: Int32) {} class SignalHandler { let callback: (SignalInfo) -> Void var sources: [DispatchSource] = [] init(callback: @escaping (SignalInfo) -> Void) { self.callback = callback } func register() { self.sources = signalPairs.map { info in signal(info.signo, ignoreSignal) let source = DispatchSource.makeSignalSource(signal: info.signo, queue: DispatchQueue.main) source.setEventHandler { self.callback(info) } source.resume() return source as! DispatchSource } } func unregister() { for source in self.sources { source.cancel() } } }
bsd-3-clause
09fd24bbd70e1767f4d3e1a08d414a1c
23.491803
97
0.664659
3.772727
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/view model/TKUIHomeViewModel.swift
1
2803
// // TKUIHomeViewModel.swift // TripKitUI-iOS // // Created by Adrian Schönig on 19.12.19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import Foundation import MapKit import RxSwift import RxCocoa import TGCardViewController import TripKit class TKUIHomeViewModel { struct SearchInput { var searchInProgress: Driver<Bool> var searchText: Observable<(String, forced: Bool)> var itemSelected: Signal<Item> var itemAccessoryTapped: Signal<Item>? = nil var refresh: Signal<Void> = .never() var biasMapRect: Driver<MKMapRect> = .just(.null) } private(set) var componentViewModels: [TKUIHomeComponentViewModel]! init( componentViewModels: [TKUIHomeComponentViewModel], actionInput: Signal<TKUIHomeCard.ComponentAction>, searchInput: SearchInput ) { // When not searching self.componentViewModels = componentViewModels let fullContent = Self.fullContent(for: componentViewModels) let customizationFromDefaults = NotificationCenter.default.rx.notification(.TKUIHomeComponentsCustomized) .map { _ in } .startWith(()) .map { () -> [TKUIHomeCard.CustomizedItem] in let unsorted = componentViewModels.compactMap { component in component.customizerItem.map { TKUIHomeCard.CustomizedItem(fromUserDefaultsWithId: component.identity, item: $0) } } return TKUIHomeCard.sortedAsInDefaults(unsorted) } .share(replay: 1, scope: .whileConnected) let baseContent = Self.customizedContent(full: fullContent, customization: customizationFromDefaults) let componentNext = Self.buildNext( for: Signal.merge(componentViewModels.map(\.nextAction)), customization: customizationFromDefaults ) let actionNext = Self.buildNext( for: actionInput, customization: customizationFromDefaults ) // When searching let (searchContent, searchNext, searchError) = Self.searchContent(for: searchInput) // Combined let isSearching = searchInput.searchInProgress .startWith(false) .distinctUntilChanged() .asDriver(onErrorJustReturn: false) sections = Driver.combineLatest(baseContent, searchContent.startWith([]), isSearching) { $2 ? $1 : $0 } next = Signal.merge(componentNext, actionNext, searchNext) error = searchError } let sections: Driver<[Section]> let next: Signal<NextAction> let error: Signal<Error> } extension TKUIHomeViewModel.Section { init?(_ content: TKUIHomeComponentContent, identity: String) { guard let items = content.items else { return nil } self.identity = identity self.headerConfiguration = content.header self.items = items.map { .component($0) } } }
apache-2.0
9795fa17023f395949bedf268732a388
27.581633
126
0.696894
4.660566
false
false
false
false
gb-6k-house/YsSwift
Sources/Peacock/Utils/YSFont.swift
1
3340
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: 说明 ** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved ******************************************************************************/ import Foundation import UIKit @objc public enum YSFont: Int { /// (47) 重要数据 case t01 /// (31) 重要数据 case t02 /// (20) 导航栏和其他标题 case t03 /// (18) 次要标题和重要文字 case t04 /// (15) 一般正文 case t05 /// (13) 提示和辅助信息 case t06 /// (10) 提示和辅助信息 case t07 /// (16) case t08 case none static var fontCache: [Int: UIFont] = [NSInteger: UIFont]() var fontSize: CGFloat { get { var size: CGFloat = 0 switch self { case .t01: size = 47 case .t02: size = 31 case .t03: size = 20 case .t04: size = 17 case .t05: size = 15 case .t06: size = 12 case .t07: size = 10 case .t08: size = 16 default: size = 15 } return size } } public var font: UIFont { return self.mono } var boldFont: UIFont { let key = 20 + self.rawValue if let cacheFont = YSFont.fontCache[key] { return cacheFont } let font = UIFont.boldSystemFont(ofSize: self.fontSize) YSFont.fontCache[key] = font return font } var mono: UIFont { let key = 30 + self.rawValue if let cacheFont = YSFont.fontCache[key] { return cacheFont } guard let font = UIFont(name: "SimHei", size: self.fontSize) else { return UIFont.systemFont(ofSize: self.fontSize) } YSFont.fontCache[key] = font return font } var boldMono: UIFont { let key = 40 + self.rawValue if let cacheFont = YSFont.fontCache[key] { return cacheFont } // guard let font = UIFont(name: "HelveticaNeue-Bold", size: self.fontSize) else { // return self.font // } guard let font = UIFont(name: "Helvetica-Bold", size: self.fontSize) else { return self.font } YSFont.fontCache[key] = font return font } var lightMono: UIFont { let key = 50 + self.rawValue if let cacheFont = YSFont.fontCache[key] { return cacheFont } guard let font = UIFont(name: "HelveticaNeue-Light", size: self.fontSize) else { return self.font } // guard let font = UIFont(name: "Helvetica-Light", size: self.fontSize) else { // return self.font // } YSFont.fontCache[key] = font return font } } @objc class YSFontWrapper: NSObject { @objc func getFontSize(_ font: YSFont) -> CGFloat { return font.fontSize } @objc func getFont(_ font: YSFont) -> UIFont { return font.font } }
mit
039408f9f856291499f9d8597e11567c
20.711409
97
0.467697
4.377537
false
false
false
false
Raizlabs/Shift
Source/Shift/UIWindow+Screenshot.swift
1
3780
// // UIWindow+Screenshot.swift // Shift // // Created by Matthew Buckley on 12/10/15. // Copyright 2015 Raizlabs and other contributors // http://raizlabs.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 extension UIWindow { public class func screenshot() -> UIImage { // Generate image size depending on device orientation let imageSize: CGSize = UIScreen.mainScreen().bounds.size UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() // Draw view hierarchy drawWindow(inContext: context, imageSize: imageSize) // Grab rendered image let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } class func drawWindow(inContext context: CGContextRef?, imageSize: CGSize) -> Void { if let context = context { for window in UIApplication.sharedApplication().windows { // Save the current graphics state CGContextSaveGState(context) // draw view hierarchy or render if window.respondsToSelector(Selector("drawViewHierarchyInRect:")) { window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true) } else { window.layer.renderInContext(context) } CGContextRestoreGState(context) } } else { // Log an error message in case of failure debugPrint("unable to get current graphics context") } } class func rotateContext(context context: CGContextRef, imageSize: CGSize) -> Void { let pi_2 = CGFloat(M_PI_2) let pi = CGFloat(M_PI) switch UIApplication.sharedApplication().statusBarOrientation { case .LandscapeLeft: // Rotate graphics context 90 degrees clockwise CGContextRotateCTM(context, pi_2) // Move graphics context up CGContextTranslateCTM(context, 0, -imageSize.width) case .LandscapeRight: // Rotate graphics context 90 degrees counter-clockwise CGContextRotateCTM(context, -pi_2) // Move graphics context left CGContextTranslateCTM(context, -imageSize.height, 0) case .PortraitUpsideDown: // Rotate graphics context 180 degrees CGContextRotateCTM(context, pi) // Move graphics context left and up CGContextTranslateCTM(context, -imageSize.width, -imageSize.height) default: break } } }
mit
48b6a265f7e0ddcda31e4a0b5c9b1ebf
35
93
0.657937
5.316456
false
false
false
false
ryanspillsbury90/OmahaTutorial
ios/OmahaPokerTutorial/OmahaPokerTutorial/Util.swift
1
4154
// // Util.swift // OmahaPokerTutorial // // Created by Ryan Pillsbury on 6/7/15. // Copyright (c) 2015 koait. All rights reserved. // import Foundation import UIKit class Util { enum PRIORITY : Int { case SUPER_LOW = 0 case LOW = 1 case MEDIUM = 2 case HIGH = 3 case SUPER_HIGH = 4 } static func getQualityOfServiceByPriority(p: PRIORITY?) -> Int { if (p == nil) { return Int(QOS_CLASS_DEFAULT.rawValue); } switch (p!) { case .SUPER_LOW: return Int(QOS_CLASS_BACKGROUND.rawValue); case .LOW: return Int(QOS_CLASS_UTILITY.rawValue); case .MEDIUM: return Int(QOS_CLASS_DEFAULT.rawValue); case .HIGH: return Int(QOS_CLASS_USER_INITIATED.rawValue); case .SUPER_HIGH: return Int(QOS_CLASS_USER_INTERACTIVE.rawValue); default: return Int(QOS_CLASS_DEFAULT.rawValue); } } static func enqueue (task: () -> Void, priority: PRIORITY?) { let qos = getQualityOfServiceByPriority(priority) dispatch_async(dispatch_get_global_queue(qos, 0)) { task(); } } static func getRangesOfTagElementInString(attrStr: String, tag: String) -> Array<NSRange> { let inputLength = attrStr.characters.count var searchString = "<\(tag)>" var searchLength = searchString.characters.count var range = NSRange(location: 0, length: inputLength) var ranges: Array<NSRange> = [] while (range.location != NSNotFound) { range = (attrStr as NSString).rangeOfString(searchString, options: [], range: range) if (range.location != NSNotFound) { ranges.append(range); range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length)) } } searchString = "</\(tag)>" searchLength = searchString.characters.count range = NSRange(location: 0, length: inputLength) var endRanges: Array<NSRange> = [] while (range.location != NSNotFound) { range = (attrStr as NSString).rangeOfString(searchString, options: [], range: range) if (range.location != NSNotFound) { endRanges.append(range); range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length)) } } var tagRanges: Array<NSRange> = [] while ranges.count > 0 { for i in 0..<ranges.count { if i == ranges.count - 1 || ranges[i+1].location > endRanges[0].location { tagRanges.append(NSMakeRange(ranges[i].location, endRanges[0].location)); ranges.removeAtIndex(i); endRanges.removeAtIndex(0); break; } } } tagRanges.sortInPlace({return $0.location < $1.location}) return tagRanges; } static func transformGenericArray<T, G>(collection: Array<G>) -> Array<T> { var genCollection = Array<T>(); for g in collection { if let t = (g as? T) { genCollection.append(t); } } return genCollection; } } extension UIViewController { func addNoElementsAvailableView(subView: UIView, message: String) { let noPhotosView = UIView(frame: subView.frame); noPhotosView.backgroundColor = UIColor.blackColor(); noPhotosView.alpha = 0.75; let label = UILabel(frame: CGRectMake(20, 54, noPhotosView.frame.width - 40, 200 )); label.text = message; label.textAlignment = NSTextAlignment.Center; label.numberOfLines = 0; label.font = UIFont(name: "Avenir", size: 20); label.textColor = UIColor.whiteColor(); noPhotosView.addSubview(label); subView.addSubview(noPhotosView); } }
mit
b1bb029d245cf3b712db4c5e16919582
31.968254
127
0.559942
4.515217
false
false
false
false
jaften/calendar-Swift-2.0-
CVCalendar/CVCalendarWeekContentViewController.swift
2
19876
// // CVCalendarWeekContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVCalendarWeekContentViewController: CVCalendarContentViewController { private var weekViews: [Identifier : WeekView] private var monthViews: [Identifier : MonthView] public override init(calendarView: CalendarView, frame: CGRect) { weekViews = [Identifier : WeekView]() monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) initialLoad(NSDate()) } public init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) { weekViews = [Identifier : WeekView]() monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate) presentedMonthView.updateAppearance(bounds) initialLoad(presentedDate) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Load & Reload public func initialLoad(date: NSDate) { monthViews[Previous] = getPreviousMonth(presentedMonthView.date) monthViews[Presented] = presentedMonthView monthViews[Following] = getFollowingMonth(presentedMonthView.date) presentedMonthView.mapDayViews { dayView in if self.matchedDays(dayView.date, Date(date: date)) { self.insertWeekView(dayView.weekView, withIdentifier: self.Presented) self.calendarView.coordinator.flush() self.calendarView.touchController.receiveTouchOnDayView(dayView) dayView.circleView?.removeFromSuperview() } } if let presented = weekViews[Presented] { insertWeekView(getPreviousWeek(presented), withIdentifier: Previous) insertWeekView(getFollowingWeek(presented), withIdentifier: Following) } } public func reloadWeekViews() { for (identifier, weekView) in weekViews { weekView.frame.origin = CGPointMake(CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width, 0) weekView.removeFromSuperview() scrollView.addSubview(weekView) } } // MARK: - Insertion public func insertWeekView(weekView: WeekView, withIdentifier identifier: Identifier) { let index = CGFloat(indexOfIdentifier(identifier)) weekView.frame.origin = CGPointMake(scrollView.bounds.width * index, 0) weekViews[identifier] = weekView scrollView.addSubview(weekView) } public func replaceWeekView(weekView: WeekView, withIdentifier identifier: Identifier, animatable: Bool) { var weekViewFrame = weekView.frame weekViewFrame.origin.x = weekViewFrame.width * CGFloat(indexOfIdentifier(identifier)) weekView.frame = weekViewFrame weekViews[identifier] = weekView if animatable { scrollView.scrollRectToVisible(weekViewFrame, animated: false) } } // MARK: - Load management public func scrolledLeft() { if let presented = weekViews[Presented], let following = weekViews[Following] { if pageLoadingEnabled { pageLoadingEnabled = false weekViews[Previous]?.removeFromSuperview() replaceWeekView(presented, withIdentifier: Previous, animatable: false) replaceWeekView(following, withIdentifier: Presented, animatable: true) insertWeekView(getFollowingWeek(following), withIdentifier: Following) } } } public func scrolledRight() { if let presented = weekViews[Presented], let previous = weekViews[Previous] { if pageLoadingEnabled { pageLoadingEnabled = false weekViews[Following]?.removeFromSuperview() replaceWeekView(presented, withIdentifier: Following, animatable: false) replaceWeekView(previous, withIdentifier: Presented, animatable: true) insertWeekView(getPreviousWeek(previous), withIdentifier: Previous) } } } // MARK: - Override methods public override func updateFrames(rect: CGRect) { super.updateFrames(rect) for monthView in monthViews.values { monthView.reloadViewsWithRect(rect != CGRectZero ? rect : scrollView.bounds) } reloadWeekViews() if let presented = weekViews[Presented] { scrollView.scrollRectToVisible(presented.frame, animated: false) } } public override func performedDayViewSelection(dayView: DayView) { if dayView.isOut { if dayView.date.day > 20 { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate)) presentPreviousView(dayView) } else { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate)) presentNextView(dayView) } } } public override func presentPreviousView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = weekViews[Following], let presented = weekViews[Presented], let previous = weekViews[Previous] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnWeekView(presented, hidden: false) extra.frame.origin.x += self.scrollView.frame.width presented.frame.origin.x += self.scrollView.frame.width previous.frame.origin.x += self.scrollView.frame.width self.replaceWeekView(presented, withIdentifier: self.Following, animatable: false) self.replaceWeekView(previous, withIdentifier: self.Presented, animatable: false) }) { _ in extra.removeFromSuperview() self.insertWeekView(self.getPreviousWeek(previous), withIdentifier: self.Previous) self.updateSelection() self.presentationEnabled = true for weekView in self.weekViews.values { self.prepareTopMarkersOnWeekView(weekView, hidden: false) } } } } } public override func presentNextView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = weekViews[Previous], let presented = weekViews[Presented], let following = weekViews[Following] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnWeekView(presented, hidden: false) extra.frame.origin.x -= self.scrollView.frame.width presented.frame.origin.x -= self.scrollView.frame.width following.frame.origin.x -= self.scrollView.frame.width self.replaceWeekView(presented, withIdentifier: self.Previous, animatable: false) self.replaceWeekView(following, withIdentifier: self.Presented, animatable: false) }) { _ in extra.removeFromSuperview() self.insertWeekView(self.getFollowingWeek(following), withIdentifier: self.Following) self.updateSelection() self.presentationEnabled = true for weekView in self.weekViews.values { self.prepareTopMarkersOnWeekView(weekView, hidden: false) } } } } } public override func updateDayViews(hidden: Bool) { setDayOutViewsVisible(hidden) } private var togglingBlocked = false public override func togglePresentedDate(date: NSDate) { let presentedDate = Date(date: date) if let _/*presentedMonthView*/ = monthViews[Presented], let presentedWeekView = weekViews[Presented], let selectedDate = calendarView.coordinator.selectedDayView?.date { if !matchedDays(selectedDate, Date(date: date)) && !togglingBlocked { if !matchedWeeks(presentedDate, selectedDate) { togglingBlocked = true weekViews[Previous]?.removeFromSuperview() weekViews[Following]?.removeFromSuperview() let currentMonthView = MonthView(calendarView: calendarView, date: date) currentMonthView.updateAppearance(scrollView.bounds) monthViews[Presented] = currentMonthView monthViews[Previous] = getPreviousMonth(date) monthViews[Following] = getFollowingMonth(date) let currentDate = CVDate(date: date) calendarView.presentedDate = currentDate var currentWeekView: WeekView! currentMonthView.mapDayViews { dayView in if self.matchedDays(currentDate, dayView.date) { if let weekView = dayView.weekView { currentWeekView = weekView currentWeekView.alpha = 0 } } } insertWeekView(getPreviousWeek(currentWeekView), withIdentifier: Previous) insertWeekView(currentWeekView, withIdentifier: Presented) insertWeekView(getFollowingWeek(currentWeekView), withIdentifier: Following) UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { presentedWeekView.alpha = 0 currentWeekView.alpha = 1 }) { _ in presentedWeekView.removeFromSuperview() self.selectDayViewWithDay(currentDate.day, inWeekView: currentWeekView) self.togglingBlocked = false } } else { if let currentWeekView = weekViews[Presented] { selectDayViewWithDay(presentedDate.day, inWeekView: currentWeekView) } } } } } } // MARK: - WeekView management extension CVCalendarWeekContentViewController { public func getPreviousWeek(presentedWeekView: WeekView) -> WeekView { if let presentedMonthView = monthViews[Presented], let previousMonthView = monthViews[Previous] where presentedWeekView.monthView == presentedMonthView { for weekView in presentedMonthView.weekViews { if weekView.index == presentedWeekView.index - 1 { return weekView } } for weekView in previousMonthView.weekViews { if weekView.index == previousMonthView.weekViews.count - 1 { return weekView } } } else if let previousMonthView = monthViews[Previous] { monthViews[Following] = monthViews[Presented] monthViews[Presented] = monthViews[Previous] monthViews[Previous] = getPreviousMonth(previousMonthView.date) presentedMonthView = monthViews[Previous]! } return getPreviousWeek(presentedWeekView) } public func getFollowingWeek(presentedWeekView: WeekView) -> WeekView { if let presentedMonthView = monthViews[Presented], let followingMonthView = monthViews[Following] where presentedWeekView.monthView == presentedMonthView { for _/*weekView*/ in presentedMonthView.weekViews { for weekView in presentedMonthView.weekViews { if weekView.index == presentedWeekView.index + 1 { return weekView } } for weekView in followingMonthView.weekViews { if weekView.index == 0 { return weekView } } } } else if let followingMonthView = monthViews[Following] { monthViews[Previous] = monthViews[Presented] monthViews[Presented] = monthViews[Following] monthViews[Following] = getFollowingMonth(followingMonthView.date) presentedMonthView = monthViews[Following]! } return getFollowingWeek(presentedWeekView) } } // MARK: - MonthView management extension CVCalendarWeekContentViewController { public func getFollowingMonth(date: NSDate) -> MonthView { let calendarManager = calendarView.manager let firstDate = calendarManager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month += 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let monthView = MonthView(calendarView: calendarView, date: newDate) let frame = CGRectMake(0, 0, scrollView.bounds.width, scrollView.bounds.height) monthView.updateAppearance(frame) return monthView } public func getPreviousMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month -= 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let monthView = MonthView(calendarView: calendarView, date: newDate) let frame = CGRectMake(0, 0, scrollView.bounds.width, scrollView.bounds.height) monthView.updateAppearance(frame) return monthView } } // MARK: - Visual preparation extension CVCalendarWeekContentViewController { public func prepareTopMarkersOnWeekView(weekView: WeekView, hidden: Bool) { weekView.mapDayViews { dayView in dayView.topMarker?.hidden = hidden } } public func setDayOutViewsVisible(visible: Bool) { for monthView in monthViews.values { monthView.mapDayViews { dayView in if dayView.isOut { if !visible { dayView.alpha = 0 dayView.hidden = false } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { dayView.alpha = visible ? 0 : 1 }) { _ in if visible { dayView.alpha = 1 dayView.hidden = true dayView.userInteractionEnabled = false } else { dayView.userInteractionEnabled = true } } } } } } public func updateSelection() { let coordinator = calendarView.coordinator if let selected = coordinator.selectedDayView { for (index, monthView) in monthViews { if indexOfIdentifier(index) != 1 { monthView.mapDayViews { dayView in if dayView == selected { dayView.setDeselectedWithClearing(true) coordinator.dequeueDayView(dayView) } } } } } if let presentedWeekView = weekViews[Presented], let presentedMonthView = monthViews[Presented] { self.presentedMonthView = presentedMonthView calendarView.presentedDate = Date(date: presentedMonthView.date) var presentedDate: Date! for dayView in presentedWeekView.dayViews { if !dayView.isOut { presentedDate = dayView.date break } } if let selected = coordinator.selectedDayView where !matchedWeeks(selected.date, presentedDate) { let current = Date(date: NSDate()) if matchedWeeks(current, presentedDate) { selectDayViewWithDay(current.day, inWeekView: presentedWeekView) } else { selectDayViewWithDay(presentedDate.day, inWeekView: presentedWeekView) } } } } public func selectDayViewWithDay(day: Int, inWeekView weekView: WeekView) { let coordinator = calendarView.coordinator weekView.mapDayViews { dayView in if dayView.date.day == day && !dayView.isOut { if let selected = coordinator.selectedDayView where selected != dayView { self.calendarView.didSelectDayView(dayView) } coordinator.performDayViewSingleSelection(dayView) } } } } // MARK: - UIScrollViewDelegate extension CVCalendarWeekContentViewController { public func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.y != 0 { scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0) } let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1) if currentPage != page { currentPage = page } lastContentOffset = scrollView.contentOffset.x } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if let presented = weekViews[Presented] { prepareTopMarkersOnWeekView(presented, hidden: true) } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if pageChanged { switch direction { case .Left: scrolledLeft() case .Right: scrolledRight() default: break } } updateSelection() pageLoadingEnabled = true direction = .None } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { let rightBorder = scrollView.frame.width if scrollView.contentOffset.x <= rightBorder { direction = .Right } else { direction = .Left } } for weekView in self.weekViews.values { self.prepareTopMarkersOnWeekView(weekView, hidden: false) } } }
mit
7f470179b9916fa1714cb79e65579d68
39.815195
177
0.57909
6.399227
false
false
false
false
DeepLearningKit/DeepLearningKit
iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/MetalUtilityFunctions.swift
1
7993
// // MetalUtilFunctions.swift // MemkiteMetal // // Created by Amund Tveit on 24/11/15. // Copyright © 2015 memkite. All rights reserved. // import Foundation import Metal func createComplexNumbersArray(count: Int) -> [MetalComplexNumberType] { let zeroComplexNumber = MetalComplexNumberType() return [MetalComplexNumberType](count: count, repeatedValue: zeroComplexNumber) } func createFloatNumbersArray(count: Int) -> [Float] { return [Float](count: count, repeatedValue: 0.0) } func createFloatMetalBuffer(vector: [Float], let metalDevice:MTLDevice) -> MTLBuffer { var vector = vector let byteLength = vector.count*sizeof(Float) // future: MTLResourceStorageModePrivate return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } // TODO: could perhaps use generics to combine both functions below? func createComplexMetalBuffer(vector:[MetalComplexNumberType], let metalDevice:MTLDevice) -> MTLBuffer { var vector = vector let byteLength = vector.count*sizeof(MetalComplexNumberType) // or size of and actual 1st element object? return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createShaderParametersMetalBuffer(shaderParameters:MetalShaderParameters, metalDevice:MTLDevice) -> MTLBuffer { var shaderParameters = shaderParameters let byteLength = sizeof(MetalShaderParameters) return metalDevice.newBufferWithBytes(&shaderParameters, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createMatrixShaderParametersMetalBuffer(params: MetalMatrixVectorParameters, metalDevice: MTLDevice) -> MTLBuffer { var params = params let byteLength = sizeof(MetalMatrixVectorParameters) return metalDevice.newBufferWithBytes(&params, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createPoolingParametersMetalBuffer(params: MetalPoolingParameters, metalDevice: MTLDevice) -> MTLBuffer { var params = params let byteLength = sizeof(MetalPoolingParameters) return metalDevice.newBufferWithBytes(&params, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createConvolutionParametersMetalBuffer(params: MetalConvolutionParameters, metalDevice: MTLDevice) -> MTLBuffer { var params = params let byteLength = sizeof(MetalConvolutionParameters) return metalDevice.newBufferWithBytes(&params, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createTensorDimensionsVectorMetalBuffer(vector: [MetalTensorDimensions], metalDevice: MTLDevice) -> MTLBuffer { var vector = vector let byteLength = vector.count * sizeof(MetalTensorDimensions) return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func setupShaderInMetalPipeline(shaderName:String, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice) -> (shader:MTLFunction!, computePipelineState:MTLComputePipelineState!, computePipelineErrors:NSErrorPointer!) { let shader = metalDefaultLibrary.newFunctionWithName(shaderName) let computePipeLineDescriptor = MTLComputePipelineDescriptor() computePipeLineDescriptor.computeFunction = shader // var computePipelineErrors = NSErrorPointer() // let computePipelineState:MTLComputePipelineState = metalDevice.newComputePipelineStateWithFunction(shader!, completionHandler: {(}) let computePipelineErrors:NSErrorPointer = nil var computePipelineState:MTLComputePipelineState? = nil do { computePipelineState = try metalDevice.newComputePipelineStateWithFunction(shader!) } catch { print("catching..") } return (shader, computePipelineState, computePipelineErrors) } func createMetalBuffer(vector:[Float], metalDevice:MTLDevice) -> MTLBuffer { var vector = vector let byteLength = vector.count*sizeof(Float) return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func preLoadMetalShaders(metalDevice: MTLDevice, metalDefaultLibrary: MTLLibrary) { let shaders = ["avg_pool", "max_pool", "rectifier_linear", "convolution_layer", "im2col"] for shader in shaders { setupShaderInMetalPipeline(shader, metalDefaultLibrary: metalDefaultLibrary,metalDevice: metalDevice) // TODO: this returns stuff } } func createOrReuseFloatMetalBuffer(name:String, data: [Float], inout cache:[Dictionary<String,MTLBuffer>], layer_number:Int, metalDevice:MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { print("found key = \(name) in cache") result = tmpval } else { print("didnt find key = \(name) in cache") result = createFloatMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result // print("DEBUG: cache = \(cache)") } return result } func createOrReuseConvolutionParametersMetalBuffer(name:String, data: MetalConvolutionParameters, inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { print("found key = \(name) in cache") result = tmpval } else { print("didnt find key = \(name) in cache") result = createConvolutionParametersMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result } func createOrReuseTensorDimensionsVectorMetalBuffer(name:String, data:[MetalTensorDimensions],inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { print("found key = \(name) in cache") result = tmpval } else { print("didnt find key = \(name) in cache") result = createTensorDimensionsVectorMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result } // //let sizeParamMetalBuffer = createShaderParametersMetalBuffer(size_params, metalDevice: metalDevice) //let poolingParamMetalBuffer = createPoolingParametersMetalBuffer(pooling_params, metalDevice: metalDevice) func createOrReuseShaderParametersMetalBuffer(name:String, data:MetalShaderParameters,inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { // print("found key = \(name) in cache") result = tmpval } else { // print("didnt find key = \(name) in cache") result = createShaderParametersMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result } func createOrReusePoolingParametersMetalBuffer(name:String, data:MetalPoolingParameters,inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { // print("found key = \(name) in cache") result = tmpval } else { // print("didnt find key = \(name) in cache") result = createPoolingParametersMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result }
apache-2.0
57598235d0380ebd828c2cb5c2cff8c3
42.912088
162
0.715966
5.186243
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/TextFind.swift
1
18032
// // TextFind.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2017-02-02. // // --------------------------------------------------------------------------- // // © 2015-2022 1024jp // // 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 // // https://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 struct ReplacementItem { let string: String let range: NSRange } final class TextFind { enum Mode { case textual(options: String.CompareOptions, fullWord: Bool) // don't include .backwards to options case regularExpression(options: NSRegularExpression.Options, unescapesReplacement: Bool) } enum ReplacingFlag { case findProgress case foundCount(Int) case replacementProgress } enum `Error`: LocalizedError { case regularExpression(reason: String) case emptyFindString case emptyInSelectionSearch var errorDescription: String? { switch self { case .regularExpression: return "Invalid regular expression".localized case .emptyFindString: return "Empty find string".localized case .emptyInSelectionSearch: return "The option “in selection” is enabled, although nothing is selected.".localized } } var recoverySuggestion: String? { switch self { case .regularExpression(let reason): return reason case .emptyFindString: return "Input text to find.".localized case .emptyInSelectionSearch: return "Select the search scope in the document or turn off the “in selection” option.".localized } } } // MARK: Public Properties let mode: TextFind.Mode let findString: String let string: String let selectedRanges: [NSRange] let inSelection: Bool // MARK: Private Properties private let regex: NSRegularExpression? private let scopeRanges: [NSRange] private lazy var fullWordChecker = try! NSRegularExpression(pattern: "^\\b.+\\b$") // MARK: - // MARK: Lifecycle /// Return an initialized TextFind instance with the specified options. /// /// - Parameters: /// - string: The string to search. /// - findString: The string for which to search. /// - mode: The settable options for the text search. /// - inSelection: Whether find string only in selectedRanges. /// - selectedRanges: The selected ranges in the text view. /// - Throws: `TextFind.Error` init(for string: String, findString: String, mode: TextFind.Mode, inSelection: Bool = false, selectedRanges: [NSRange] = [NSRange()]) throws { assert(!selectedRanges.isEmpty) guard !findString.isEmpty else { throw TextFind.Error.emptyFindString } guard !inSelection || selectedRanges.contains(where: { !$0.isEmpty }) else { throw TextFind.Error.emptyInSelectionSearch } switch mode { case .textual(let options, _): assert(!options.contains(.backwards)) self.regex = nil case .regularExpression(let options, _): // replace `\v` with `\u000b` // -> Because NSRegularExpression cannot handle `\v` correctly. (2017-07 on macOS 10.12) // cf. https://github.com/coteditor/CotEditor/issues/713 let sanitizedFindString: String = findString.contains("\\v") ? findString.replacingOccurrences(of: "(?<!\\\\)\\\\v", with: "\\\\u000b", options: .regularExpression) : findString do { self.regex = try NSRegularExpression(pattern: sanitizedFindString, options: options) } catch { throw TextFind.Error.regularExpression(reason: error.localizedDescription) } } self.mode = mode self.string = string self.selectedRanges = selectedRanges self.findString = findString self.inSelection = inSelection self.scopeRanges = inSelection ? selectedRanges : [string.nsRange] } // MARK: Public Methods /// The number of capture groups in the regular expression. var numberOfCaptureGroups: Int { return self.regex?.numberOfCaptureGroups ?? 0 } /// Return the nearest match from the insertion point. /// /// - Parameters: /// - forward: Whether search forward from the insertion. /// - isWrap: Whetehr search wrap search around. /// - Returns: /// - range: The range of matched or nil if not found. /// - count: The total number of matches in the scopes. /// - wrapped: Whether the search was wrapped to find the result. func find(forward: Bool, isWrap: Bool) -> (range: NSRange?, count: Int, wrapped: Bool) { if self.inSelection { return self.findInSelection(forward: forward) } let selectedRange = self.selectedRanges.first! let startLocation = forward ? selectedRange.upperBound : selectedRange.location var forwardMatches: [NSRange] = [] // matches after the start location let forwardRange = NSRange(startLocation..<(self.string as NSString).length) self.enumerateMatchs(in: [forwardRange], using: { (matchedRange, _, _) in forwardMatches.append(matchedRange) }) var wrappedMatches: [NSRange] = [] // matches before the start location var intersectionMatches: [NSRange] = [] // matches including the start location self.enumerateMatchs(in: [(self.string as NSString).range], using: { (matchedRange, _, stop) in if matchedRange.location >= startLocation { stop = true return } if matchedRange.contains(startLocation) { intersectionMatches.append(matchedRange) } else { wrappedMatches.append(matchedRange) } }) var foundRange = forward ? forwardMatches.first : wrappedMatches.last // wrap search let isWrapped = (foundRange == nil && isWrap) if isWrapped { foundRange = forward ? (wrappedMatches + intersectionMatches).first : (intersectionMatches + forwardMatches).last } let count = forwardMatches.count + wrappedMatches.count + intersectionMatches.count return (foundRange, count, isWrapped) } /// Return a match in selection ranges. /// /// - Parameters: /// - forward: Whether search forward from the insertion. /// - Returns: /// - range: The range of matched or nil if not found. /// - count: The total number of matches in the scopes. /// - wrapped: Whether the search was wrapped to find the result. func findInSelection(forward: Bool) -> (range: NSRange?, count: Int, wrapped: Bool) { assert(self.inSelection) var matches: [NSRange] = [] self.enumerateMatchs(in: self.selectedRanges, using: { (matchedRange, _, _) in matches.append(matchedRange) }) let foundRange = forward ? matches.first : matches.last return (foundRange, matches.count, false) } /// Return ReplacementItem replacing matched string in selection. /// /// - Parameters: /// - replacementString: The string with which to replace. /// - Returns: The struct of a string to replace with and a range to replace if found. Otherwise, nil. func replace(with replacementString: String) -> ReplacementItem? { let string = self.string let selectedRange = self.selectedRanges.first! switch self.mode { case let .textual(options, fullWord): let matchedRange = (string as NSString).range(of: self.findString, options: options, range: selectedRange) guard matchedRange.location != NSNotFound else { return nil } guard !fullWord || self.isFullWord(range: matchedRange) else { return nil } return ReplacementItem(string: replacementString, range: matchedRange) case .regularExpression: let regex = self.regex! guard let match = regex.firstMatch(in: string, options: [.withTransparentBounds, .withoutAnchoringBounds], range: selectedRange) else { return nil } let template = self.replacementString(from: replacementString) let replacedString = regex.replacementString(for: match, in: string, offset: 0, template: template) return ReplacementItem(string: replacedString, range: match.range) } } /// Find all matches in the scopes. /// /// - Parameters: /// - block: The Block enumerates the matches. /// - matches: The array of matches including group matches. /// - stop: The Block can set the value to true to stop further processing of the array. func findAll(using block: (_ matches: [NSRange], _ stop: inout Bool) -> Void) { let numberOfGroups = self.numberOfCaptureGroups self.enumerateMatchs(in: self.scopeRanges, using: { (matchedRange: NSRange, match: NSTextCheckingResult?, stop) in var matches = [matchedRange] if let match = match, numberOfGroups > 0 { matches += (1...numberOfGroups).map { match.range(at: $0) } } block(matches, &stop) }) } /// Replace all matches in the scopes. /// /// - Parameters: /// - replacementString: The string with which to replace. /// - block: The Block enumerates the matches. /// - flag: The current state of the replacing progress. /// - stop: The Block can set the value to true to stop further processing of the array. /// - Returns: /// - replacementItems: ReplacementItem per selectedRange. /// - selectedRanges: New selections for textView only if the replacement is performed within selection. Otherwise, nil. func replaceAll(with replacementString: String, using block: @escaping (_ flag: ReplacingFlag, _ stop: inout Bool) -> Void) -> (replacementItems: [ReplacementItem], selectedRanges: [NSRange]?) { let replacementString = self.replacementString(from: replacementString) var replacementItems: [ReplacementItem] = [] var selectedRanges: [NSRange] = [] var ioStop = false // temporal container collecting replacements to process string per selection in `scopeCompletionHandler` block var items: [ReplacementItem] = [] self.enumerateMatchs(in: self.scopeRanges, using: { (matchedRange: NSRange, match: NSTextCheckingResult?, stop) in let replacedString: String = { guard let match = match, let regex = match.regularExpression else { return replacementString } return regex.replacementString(for: match, in: self.string, offset: 0, template: replacementString) }() items.append(ReplacementItem(string: replacedString, range: matchedRange)) block(.findProgress, &ioStop) stop = ioStop }, scopeCompletionHandler: { (scopeRange: NSRange) in block(.foundCount(items.count), &ioStop) let length: Int if items.isEmpty { length = scopeRange.length } else { // build replacementString let replacedString = NSMutableString(string: (self.string as NSString).substring(with: scopeRange)) for item in items.reversed() { block(.replacementProgress, &ioStop) if ioStop { return } // -> Do not convert to Range<Index>. It can fail when the range is smaller than String.Character. let substringRange = item.range.shifted(by: -scopeRange.location) replacedString.replaceCharacters(in: substringRange, with: item.string) } replacementItems.append(ReplacementItem(string: replacedString.copy() as! String, range: scopeRange)) length = replacedString.length } // build selectedRange let locationDelta = zip(selectedRanges, self.selectedRanges) .map { $0.0.length - $0.1.length } .reduce(scopeRange.location, +) let selectedRange = NSRange(location: locationDelta, length: length) selectedRanges.append(selectedRange) items.removeAll() }) return (replacementItems, self.inSelection ? selectedRanges : nil) } // MARK: Private Methods private typealias EnumerationBlock = ((_ matchedRange: NSRange, _ match: NSTextCheckingResult?, _ stop: inout Bool) -> Void) /// unescape given string for replacement string only if needed private func replacementString(from string: String) -> String { switch self.mode { case .regularExpression(_, let unescapes) where unescapes: return string.unescaped default: return string } } /// chack if the given range is a range of whole word private func isFullWord(range: NSRange) -> Bool { return self.fullWordChecker.firstMatch(in: self.string, options: .withTransparentBounds, range: range) != nil } /// enumerate matchs in string using current settings private func enumerateMatchs(in ranges: [NSRange], using block: (_ matchedRange: NSRange, _ match: NSTextCheckingResult?, _ stop: inout Bool) -> Void, scopeCompletionHandler: ((NSRange) -> Void) = { _ in }) { switch self.mode { case .textual: self.enumerateTextualMatchs(in: ranges, using: block, scopeCompletionHandler: scopeCompletionHandler) case .regularExpression: self.enumerateRegularExpressionMatchs(in: ranges, using: block, scopeCompletionHandler: scopeCompletionHandler) } } /// enumerate matchs in string using textual search private func enumerateTextualMatchs(in ranges: [NSRange], using block: (_ matchedRange: NSRange, _ match: NSTextCheckingResult?, _ stop: inout Bool) -> Void, scopeCompletionHandler: ((NSRange) -> Void) = { _ in }) { guard !self.string.isEmpty else { return } guard case let .textual(options, fullWord) = self.mode else { return assertionFailure() } let string = self.string as NSString for scopeRange in ranges { var searchRange = scopeRange while searchRange.location != NSNotFound { searchRange.length = string.length - searchRange.location let foundRange = string.range(of: self.findString, options: options, range: searchRange) guard foundRange.upperBound <= scopeRange.upperBound else { break } searchRange.location = foundRange.upperBound guard !fullWord || self.isFullWord(range: foundRange) else { continue } var stop = false block(foundRange, nil, &stop) guard !stop else { return } } scopeCompletionHandler(scopeRange) } } /// enumerate matchs in string using regular expression private func enumerateRegularExpressionMatchs(in ranges: [NSRange], using block: (_ matchedRange: NSRange, _ match: NSTextCheckingResult?, _ stop: inout Bool) -> Void, scopeCompletionHandler: ((NSRange) -> Void) = { _ in }) { guard !self.string.isEmpty else { return } let string = self.string let regex = self.regex! let options: NSRegularExpression.MatchingOptions = [.withTransparentBounds, .withoutAnchoringBounds] var cancelled = false for scopeRange in ranges { guard !cancelled else { return } regex.enumerateMatches(in: string, options: options, range: scopeRange) { (result, _, stop) in guard let result = result else { return } var ioStop = false block(result.range, result, &ioStop) if ioStop { stop.pointee = ObjCBool(ioStop) cancelled = true } } scopeCompletionHandler(scopeRange) } } }
apache-2.0
4af82be8d0e61f89a15432b8ca4f2d18
37.593148
229
0.58209
5.389653
false
false
false
false
practicalswift/swift
benchmark/single-source/RandomValues.swift
3
2418
//===--- RandomValues.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // // Benchmark generating lots of random values. Measures the performance of // the default random generator and the algorithms for generating integers // and floating-point values. // public let RandomValues = [ BenchmarkInfo(name: "RandomIntegersDef", runFunction: run_RandomIntegersDef, tags: [.api], legacyFactor: 100), BenchmarkInfo(name: "RandomIntegersLCG", runFunction: run_RandomIntegersLCG, tags: [.api]), BenchmarkInfo(name: "RandomDoubleDef", runFunction: run_RandomDoubleDef, tags: [.api], legacyFactor: 100), BenchmarkInfo(name: "RandomDoubleLCG", runFunction: run_RandomDoubleLCG, tags: [.api], legacyFactor: 2), ] /// A linear congruential PRNG. struct LCRNG: RandomNumberGenerator { private var state: UInt64 init(seed: Int) { state = UInt64(truncatingIfNeeded: seed) for _ in 0..<10 { _ = next() } } mutating func next() -> UInt64 { state = 2862933555777941757 &* state &+ 3037000493 return state } } @inline(never) public func run_RandomIntegersDef(_ N: Int) { for _ in 0 ..< N { var x = 0 for _ in 0 ..< 1_000 { x &+= Int.random(in: 0...10_000) } blackHole(x) } } @inline(never) public func run_RandomIntegersLCG(_ N: Int) { for _ in 0 ..< N { var x: Int64 = 0 var generator = LCRNG(seed: 0) for _ in 0 ..< 100_000 { x &+= Int64.random(in: 0...10_000, using: &generator) } CheckResults(x == 498214315) } } @inline(never) public func run_RandomDoubleDef(_ N: Int) { for _ in 0 ..< N { var x = 0.0 for _ in 0 ..< 1_000 { x += Double.random(in: -1000...1000) } blackHole(x) } } @inline(never) public func run_RandomDoubleLCG(_ N: Int) { for _ in 0 ..< N { var x = 0.0 var generator = LCRNG(seed: 0) for _ in 0 ..< 50_000 { x += Double.random(in: -1000...1000, using: &generator) } blackHole(x) } }
apache-2.0
2c89670ba2bf118de709b0f86a66f387
25.571429
80
0.60794
3.680365
false
false
false
false
MatthiasU/SwiftyBit
Sources/SwiftyBit/BitPosition.swift
1
11625
// // BitPosition.swift // SwiftyBit // // Created by Matthias Uttendorfer on 23/09/2016. // // //Apache License //Version 2.0, January 2004 //http://www.apache.org/licenses/ // //TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION // //1. Definitions. // //"License" shall mean the terms and conditions for use, reproduction, //and distribution as defined by Sections 1 through 9 of this document. // //"Licensor" shall mean the copyright owner or entity authorized by //the copyright owner that is granting the License. // //"Legal Entity" shall mean the union of the acting entity and all //other entities that control, are controlled by, or are under common //control with that entity. For the purposes of this definition, //"control" means (i) the power, direct or indirect, to cause the //direction or management of such entity, whether by contract or //otherwise, or (ii) ownership of fifty percent (50%) or more of the //outstanding shares, or (iii) beneficial ownership of such entity. // //"You" (or "Your") shall mean an individual or Legal Entity //exercising permissions granted by this License. // //"Source" form shall mean the preferred form for making modifications, //including but not limited to software source code, documentation //source, and configuration files. // //"Object" form shall mean any form resulting from mechanical //transformation or translation of a Source form, including but //not limited to compiled object code, generated documentation, //and conversions to other media types. // //"Work" shall mean the work of authorship, whether in Source or //Object form, made available under the License, as indicated by a //copyright notice that is included in or attached to the work //(an example is provided in the Appendix below). // //"Derivative Works" shall mean any work, whether in Source or Object //form, that is based on (or derived from) the Work and for which the //editorial revisions, annotations, elaborations, or other modifications //represent, as a whole, an original work of authorship. For the purposes //of this License, Derivative Works shall not include works that remain //separable from, or merely link (or bind by name) to the interfaces of, //the Work and Derivative Works thereof. // //"Contribution" shall mean any work of authorship, including //the original version of the Work and any modifications or additions //to that Work or Derivative Works thereof, that is intentionally //submitted to Licensor for inclusion in the Work by the copyright owner //or by an individual or Legal Entity authorized to submit on behalf of //the copyright owner. For the purposes of this definition, "submitted" //means any form of electronic, verbal, or written communication sent //to the Licensor or its representatives, including but not limited to //communication on electronic mailing lists, source code control systems, //and issue tracking systems that are managed by, or on behalf of, the //Licensor for the purpose of discussing and improving the Work, but //excluding communication that is conspicuously marked or otherwise //designated in writing by the copyright owner as "Not a Contribution." // //"Contributor" shall mean Licensor and any individual or Legal Entity //on behalf of whom a Contribution has been received by Licensor and //subsequently incorporated within the Work. // //2. Grant of Copyright License. Subject to the terms and conditions of //this License, each Contributor hereby grants to You a perpetual, //worldwide, non-exclusive, no-charge, royalty-free, irrevocable //copyright license to reproduce, prepare Derivative Works of, //publicly display, publicly perform, sublicense, and distribute the //Work and such Derivative Works in Source or Object form. // //3. Grant of Patent License. Subject to the terms and conditions of //this License, each Contributor hereby grants to You a perpetual, //worldwide, non-exclusive, no-charge, royalty-free, irrevocable //(except as stated in this section) patent license to make, have made, //use, offer to sell, sell, import, and otherwise transfer the Work, //where such license applies only to those patent claims licensable //by such Contributor that are necessarily infringed by their //Contribution(s) alone or by combination of their Contribution(s) //with the Work to which such Contribution(s) was submitted. If You //institute patent litigation against any entity (including a //cross-claim or counterclaim in a lawsuit) alleging that the Work //or a Contribution incorporated within the Work constitutes direct //or contributory patent infringement, then any patent licenses //granted to You under this License for that Work shall terminate //as of the date such litigation is filed. // //4. Redistribution. You may reproduce and distribute copies of the //Work or Derivative Works thereof in any medium, with or without //modifications, and in Source or Object form, provided that You //meet the following conditions: // //(a) You must give any other recipients of the Work or //Derivative Works a copy of this License; and // //(b) You must cause any modified files to carry prominent notices //stating that You changed the files; and // //(c) You must retain, in the Source form of any Derivative Works //that You distribute, all copyright, patent, trademark, and //attribution notices from the Source form of the Work, //excluding those notices that do not pertain to any part of //the Derivative Works; and // //(d) If the Work includes a "NOTICE" text file as part of its //distribution, then any Derivative Works that You distribute must //include a readable copy of the attribution notices contained //within such NOTICE file, excluding those notices that do not //pertain to any part of the Derivative Works, in at least one //of the following places: within a NOTICE text file distributed //as part of the Derivative Works; within the Source form or //documentation, if provided along with the Derivative Works; or, //within a display generated by the Derivative Works, if and //wherever such third-party notices normally appear. The contents //of the NOTICE file are for informational purposes only and //do not modify the License. You may add Your own attribution //notices within Derivative Works that You distribute, alongside //or as an addendum to the NOTICE text from the Work, provided //that such additional attribution notices cannot be construed //as modifying the License. // //You may add Your own copyright statement to Your modifications and //may provide additional or different license terms and conditions //for use, reproduction, or distribution of Your modifications, or //for any such Derivative Works as a whole, provided Your use, //reproduction, and distribution of the Work otherwise complies with //the conditions stated in this License. // //5. Submission of Contributions. Unless You explicitly state otherwise, //any Contribution intentionally submitted for inclusion in the Work //by You to the Licensor shall be under the terms and conditions of //this License, without any additional terms or conditions. //Notwithstanding the above, nothing herein shall supersede or modify //the terms of any separate license agreement you may have executed //with Licensor regarding such Contributions. // //6. Trademarks. This License does not grant permission to use the trade //names, trademarks, service marks, or product names of the Licensor, //except as required for reasonable and customary use in describing the //origin of the Work and reproducing the content of the NOTICE file. // //7. Disclaimer of Warranty. Unless required by applicable law or //agreed to in writing, Licensor provides the Work (and each //Contributor provides its Contributions) on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or //implied, including, without limitation, any warranties or conditions //of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A //PARTICULAR PURPOSE. You are solely responsible for determining the //appropriateness of using or redistributing the Work and assume any //risks associated with Your exercise of permissions under this License. // //8. Limitation of Liability. In no event and under no legal theory, //whether in tort (including negligence), contract, or otherwise, //unless required by applicable law (such as deliberate and grossly //negligent acts) or agreed to in writing, shall any Contributor be //liable to You for damages, including any direct, indirect, special, //incidental, or consequential damages of any character arising as a //result of this License or out of the use or inability to use the //Work (including but not limited to damages for loss of goodwill, //work stoppage, computer failure or malfunction, or any and all //other commercial damages or losses), even if such Contributor //has been advised of the possibility of such damages. // //9. Accepting Warranty or Additional Liability. While redistributing //the Work or Derivative Works thereof, You may choose to offer, //and charge a fee for, acceptance of support, warranty, indemnity, //or other liability obligations and/or rights consistent with this //License. However, in accepting such obligations, You may act only //on Your own behalf and on Your sole responsibility, not on behalf //of any other Contributor, and only if You agree to indemnify, //defend, and hold each Contributor harmless for any liability //incurred by, or claims asserted against, such Contributor by reason //of your accepting any such warranty or additional liability. // //END OF TERMS AND CONDITIONS // //APPENDIX: How to apply the Apache License to your work. // //To apply the Apache License to your work, attach the following //boilerplate notice, with the fields enclosed by brackets "{}" //replaced with your own identifying information. (Don't include //the brackets!) The text should be enclosed in the appropriate //comment syntax for the file format. We also recommend that a //file or class name and description of purpose be included on the //same "printed page" as the copyright notice for easier // identification within third-party archives. // //Copyright 2016 Matthias Uttendorfer // //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. internal struct BitPosition { /// Byte position of the bit private (set) var byte = Int() /// Bit position in the specific byte private (set) var bit = Int() /// Transforms a the position of a bit related to the 0 position into a Bit Position struct /// /// - parameter bitNumberDecimal: bit position in decimal with a origin of zero /// /// - returns: BitPosition structure of the decimal integer with origin of zero init(bitNumberDecimal: Int){ var octalRepString = String(bitNumberDecimal, radix: 8) let bitPos = octalRepString.last! self.bit = Int(String(bitPos))! octalRepString.removeLast() if octalRepString.isEmpty { self.byte = 0 } else { self.byte = Int(octalRepString)! } } }
apache-2.0
daf1e26a10cf170ac47cc69236349655
47.4375
95
0.764301
4.406748
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPUserProfileViewController.swift
1
16431
// // KPUserProfileViewController.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/4/26. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPUserProfileViewController: KPViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, KPTabViewDelegate { var dismissButton: KPBounceButton! var editButton: KPBounceButton! let tabTitles: [(title: String, key: String)] = [("已收藏", "favorites"), ("我去過", "visits"), ("已評分", "rates"), ("已評論", "reviews")] let statusContents:[(icon: UIImage, content: String)] = [(R.image.status_collect()!, "快來收藏你喜愛的店家吧!"), (R.image.status_location()!, "你有去過哪些店家呢?"), (R.image.status_star()!, "快給你喜愛的店家一些正面的評分吧!"), (R.image.status_comment()!, "快給你喜愛的店家一些正面的評論吧!")] lazy var userContainer: UIView = { let containerView = UIView() containerView.backgroundColor = KPColorPalette.KPBackgroundColor.mainColor_light return containerView }() lazy var userPhoto: UIImageView = { let imageView = UIImageView() imageView.backgroundColor = KPColorPalette.KPBackgroundColor.mainColor imageView.layer.borderWidth = 2.0 imageView.layer.borderColor = UIColor.white.cgColor imageView.layer.cornerRadius = 5.0 imageView.layer.masksToBounds = true imageView.image = R.image.demo_profile() imageView.contentMode = .scaleAspectFill return imageView }() lazy var userNameLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont (ofSize: 16.0) label.textColor = KPColorPalette.KPTextColor.whiteColor label.text = "我是一隻蟲" return label }() lazy var userCityLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12.0) label.textColor = KPColorPalette.KPTextColor.whiteColor label.text = "Taipei" return label }() lazy var userBioLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12.0) label.textColor = KPColorPalette.KPTextColor.whiteColor label.text = "被你看到這個隱藏的內容?!肯定有Bug,快回報給我們吧!" label.numberOfLines = 0 return label }() var tableViews: [UITableView] = [] var statusViews: [KPStatusView] = [] var displayDataModels: [[KPDataModel]] = [] var scrollView: UIScrollView! var scrollContainer: UIView! var tabView: KPTabView! var isAnimating: Bool = false { didSet { self.scrollView.isUserInteractionEnabled = !isAnimating } } var dataLoading: Bool = false var dataloaded: Bool = false override func viewDidLoad() { super.viewDidLoad() KPAnalyticManager.sendPageViewEvent(KPAnalyticsEventValue.page.profile_page) view.backgroundColor = UIColor.white navigationController?.navigationBar.topItem?.title = "個人資料" navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() dismissButton = KPBounceButton(frame: CGRect.zero, image: R.image.icon_close()!) dismissButton.widthAnchor.constraint(equalToConstant: 30).isActive = true dismissButton.heightAnchor.constraint(equalToConstant: 30).isActive = true dismissButton.contentEdgeInsets = UIEdgeInsetsMake(6, 0, 8, 14) dismissButton.tintColor = KPColorPalette.KPTextColor.whiteColor dismissButton.addTarget(self, action: #selector(KPInformationViewController.handleDismissButtonOnTapped), for: .touchUpInside) let barItem = UIBarButtonItem(customView: dismissButton) let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) negativeSpacer.width = -7 navigationItem.leftBarButtonItems = [negativeSpacer, barItem] editButton = KPBounceButton(frame: CGRect.zero, image: R.image.icon_edit()!) editButton.widthAnchor.constraint(equalToConstant: 30).isActive = true editButton.heightAnchor.constraint(equalToConstant: 30).isActive = true editButton.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5) editButton.tintColor = KPColorPalette.KPTextColor.whiteColor editButton.addTarget(self, action: #selector(KPUserProfileViewController.handleEditButtonOnTapped), for: .touchUpInside) let rightBarItem = UIBarButtonItem(customView: editButton) navigationItem.leftBarButtonItems = [negativeSpacer, barItem] navigationItem.rightBarButtonItems = [negativeSpacer, rightBarItem] view.addSubview(userContainer) userContainer.addConstraints(fromStringArray: ["V:|[$self]", "H:|[$self]|"]) userContainer.addSubview(userPhoto) userPhoto.addConstraints(fromStringArray: ["H:|-16-[$self(64)]", "V:|-16-[$self(64)]-16-|"]) userContainer.addSubview(userNameLabel) userNameLabel.addConstraints(fromStringArray: ["H:[$view0]-8-[$self]", "V:|-16-[$self]"], views: [userPhoto]) userContainer.addSubview(userCityLabel) userCityLabel.addConstraints(fromStringArray: ["H:[$view0]-8-[$self]", "V:[$view1]-2-[$self]"], views: [userPhoto, userNameLabel]) userContainer.addSubview(userBioLabel) userBioLabel.addConstraints(fromStringArray: ["H:[$view0]-8-[$self(150)]", "V:[$view1]-4-[$self]"], views: [userPhoto, userCityLabel]) tabView = KPTabView(titles: tabTitles.map {$0.title}) tabView.delegate = self view.addSubview(tabView) tabView.addConstraints(fromStringArray: ["H:|[$self]|", "V:[$view0][$self(44)]"], views: [userContainer]) scrollView = UIScrollView() scrollView.delegate = self scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false view.addSubview(scrollView) scrollView.addConstraints(fromStringArray: ["H:|[$self]|", "V:[$view0][$self]|"], views: [tabView]) scrollContainer = UIView() scrollView.addSubview(scrollContainer) scrollContainer.addConstraints(fromStringArray: ["H:|[$self]|", "V:|[$self]|"]) scrollContainer.addConstraintForHavingSameHeight(with: scrollView) for (index, _) in tabTitles.enumerated() { let tableView = UITableView() tableView.dataSource = self tableView.delegate = self tableView.tag = index tableView.separatorColor = UIColor.clear tableView.register(KPMainListTableViewCell.self, forCellReuseIdentifier: "cell") tableView.register(KPDefaultLoadingTableCell.self, forCellReuseIdentifier: "cell_loading") tableView.estimatedRowHeight = 80 scrollContainer.addSubview(tableView) tableView.addConstraint(from: "V:|[$self]|") tableView.addConstraintForHavingSameWidth(with: view) let statusView = KPStatusView.init(statusContents[index].icon, statusContents[index].content) statusView.isHidden = true scrollContainer.addSubview(statusView) statusView.addConstraint(from: "V:|-72-[$self]") statusView.addConstraint(forWidth: 220) statusView.addConstraintForCenterAligning(to: tableView, in: .horizontal) if tableViews.count > 0 { tableView.addConstraint(from: "H:[$view0][$self]", views: [tableViews[index-1]]) } else { tableView.addConstraint(from: "H:|[$self]") } tableViews.append(tableView) statusViews.append(statusView) displayDataModels.append([]) } tableViews.last!.addConstraint(from: "H:[$self]|") if let user = KPUserManager.sharedManager.currentUser { if let photoURL = URL(string: user.photoURL ?? "") { userPhoto.af_setImage(withURL: photoURL) } userNameLabel.text = user.displayName ?? "" userCityLabel.text = user.defaultLocation ?? "" userBioLabel.text = user.intro ?? "" for (index, tabTitle) in tabTitles.enumerated() { if let displayModel = KPUserManager.sharedManager.currentUser?.value(forKey: tabTitle.key) as? [KPDataModel] { tabView.tabs[index].setTitle("\(tabTitle.title) \(displayModel.count)", for: .normal) } } } view.bringSubview(toFront: tabView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let user = KPUserManager.sharedManager.currentUser { if let photoURL = URL(string: user.photoURL ?? "") { userPhoto.af_setImage(withURL: photoURL) } userNameLabel.text = user.displayName ?? "" userCityLabel.text = user.defaultLocation ?? "" userBioLabel.text = user.intro ?? "" } if !dataloaded { dataLoading = true for tableView in self.tableViews { tableView.reloadData() } DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.5) { for (index, tabTitle) in self.tabTitles.enumerated() { if let displayModel = KPUserManager.sharedManager.currentUser?.value(forKey: tabTitle.key) as? [KPDataModel] { self.displayDataModels[index] = displayModel DispatchQueue.main.async { UIView.animate(withDuration: 0.1, animations: { self.tableViews[index].alpha = (displayModel.count == 0) ? 0.0 : 1.0 self.statusViews[index].alpha = (displayModel.count != 0) ? 0.0 : 1.0 }, completion: { (_) in self.tableViews[index].isHidden = displayModel.count == 0 self.statusViews[index].isHidden = (displayModel.count != 0) }) } } else { self.displayDataModels[index] = [] DispatchQueue.main.async { UIView.animate(withDuration: 0.1, animations: { self.tableViews[index].alpha = 0.0 self.statusViews[index].alpha = 1.0 }, completion: { (_) in self.tableViews[index].isHidden = true self.statusViews[index].isHidden = false }) } } } self.dataLoading = false DispatchQueue.main.async { for tableView in self.tableViews { tableView.reloadData() } } } dataloaded = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func handleDismissButtonOnTapped() { self.appModalController()?.dismissControllerWithDefaultDuration() } func handleEditButtonOnTapped() { self.navigationController?.pushViewController(KPUserProfileEditorController(), animated: true) } func tabView(_: KPTabView, didSelectIndex index: Int) { isAnimating = true UIView.animate(withDuration: 0.25, animations: { self.scrollView.contentOffset = CGPoint(x: UIScreen.main.bounds.width*CGFloat(index), y: 0) }) { (complete) in self.isAnimating = false } } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataLoading ? 6 : self.displayDataModels[tableView.tag].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if !dataLoading { let cell = tableView.dequeueReusableCell(withIdentifier:"cell", for: indexPath) as! KPMainListTableViewCell cell.selectionStyle = .none cell.dataModel = self.displayDataModels[tableView.tag][indexPath.row] return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier:"cell_loading", for: indexPath) as! KPDefaultLoadingTableCell return cell } } // MARK: UITableView Delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { KPAnalyticManager.sendCellClickEvent(self.displayDataModels[tableView.tag][indexPath.row].name, self.displayDataModels[tableView.tag][indexPath.row].averageRate?.stringValue, KPAnalyticsEventValue.source.source_profile) let controller = KPInformationViewController() controller.informationDataModel = self.displayDataModels[tableView.tag][indexPath.row] controller.showBackButton = true self.navigationController?.pushViewController(controller, animated: true) for tableView in self.tableViews { if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: false) } } } // MARK: UIScrollView Delegate func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView is UITableView { return } if isAnimating { return } let screenWidth = UIScreen.main.bounds.width tabView.currentIndex = Int((scrollView.contentOffset.x+screenWidth/2)/screenWidth) } }
mit
cbaa27bc8663a5cd2db6688a4bce6ead
41.603675
138
0.53758
5.813754
false
false
false
false
qrush/kidsmash-mac
kidsmash/GameScene.swift
1
2182
import SpriteKit class GameScene: SKScene { var history: Array<String> = [] var currentZPosition: CGFloat = 1 lazy var background: SKSpriteNode = self.initialBackground() func initialBackground() -> SKSpriteNode { return SKSpriteNode(color: NSColor.whiteColor(), size: view!.window!.frame.size) } override func didMoveToView(view: SKView) { backgroundColor = NSColor.whiteColor() background.alpha = 0.1 background.position = CGPoint(x: background.frame.size.width / 2, y: background.frame.size.height / 2) colorizeBackground() addChild(background) view.window!.makeFirstResponder(self) } override func mouseMoved(theEvent: NSEvent) { let center = theEvent.locationInWindow addSmash(Smasher(point: NSPoint(x: center.x, y: center.y))) } override func keyDown(theEvent: NSEvent) { let characters = theEvent.characters if let _ = characters!.rangeOfString("[A-Za-z0-9]", options: .RegularExpressionSearch) { addLabel(characters!) } else if characters == " " { addSmash(Smasher(shape: .Face)) } } override func mouseDown(theEvent: NSEvent) { addSmash(Smasher(shape: .Face)) } private func colorizeBackground() { var action = SKAction.colorizeWithColor(Random.color(), colorBlendFactor: 1.0, duration: 15) background.runAction(action, completion: { self.colorizeBackground() }) } private func addSmash(smasher: Smasher) { let node = smasher.generateNode() node.zPosition = currentZPosition currentZPosition++ addChild(node) } private func addLabel(label: String) { history.append(label) let word = history.reduce("", +) if word == "quit" { NSApplication.sharedApplication().terminate(self) } else { addSmash(Smasher(label: label)) } if history.count > 3 { history.removeAtIndex(0) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
87c4d80b3f8bf4e840e43582132274d8
28.486486
110
0.62099
4.564854
false
false
false
false
mlmc03/SwiftFM-DroidFM
SwiftFM/SwiftFM/PersonDetailViewController.swift
1
2460
// // PersonDetailViewController.swift // SwiftFM // // Created by Mary Martinez on 1/11/16. // Copyright © 2016 MMartinez. All rights reserved. // import UIKit import MobileCoreServices class PersonDetailViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var people = [Person]() var person : Person? @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() } // MARK: - Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "savePersonDetail" { person = Person(name: nameTextField.text!, email: emailTextField.text!, photo: "") } } // MARK: - Table view override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { nameTextField.becomeFirstResponder() } else if indexPath.section == 1 { emailTextField.becomeFirstResponder() } else if indexPath.section == 2 { self.uploadImage() } } // MARK: - Image picker func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // set the image in the view let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage imageView.image = selectedImage // convert to NSData let imageData = UIImagePNGRepresentation(selectedImage) print(imageData!.length) self.dismissViewControllerAnimated(true, completion: nil) } func uploadImage() { // setup image picker let imagePickerController = UIImagePickerController() imagePickerController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePickerController.allowsEditing = false imagePickerController.delegate = self self.presentViewController(imagePickerController, animated: true, completion: nil) } }
apache-2.0
5dee46d2d4014a8ca5006177e6b3bd2f
33.633803
123
0.691745
5.953995
false
false
false
false
gustavoavena/BandecoUnicamp
BandecoUnicamp/MainViewController.swift
1
6150
// // MainViewController.swift // BandecoUnicamp // // Created by Gustavo Avena on 24/07/17. // Copyright © 2017 Gustavo Avena. All rights reserved. // import UIKit import StoreKit class MainViewController: GAITrackedViewController { let errorString = "Desculpe, não foi possível carregar o cardápio." weak var pageViewController: PageViewController! var lastRefreshed: Date = Date() func displayAlert() { let alert = UIAlertController(title: "", message: "", preferredStyle: .alert) // Change font of the title and message let titleFont:[String : AnyObject] = [ NSFontAttributeName : UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium) ] let messageFont:[String : AnyObject] = [ NSFontAttributeName : UIFont.systemFont(ofSize: 14) ] let attributedTitle = NSMutableAttributedString(string: "Bem vindo ao Bandex!", attributes: titleFont) let attributedMessage = NSMutableAttributedString(string: "Qual a sua preferência de cardápio?", attributes: messageFont) alert.setValue(attributedTitle, forKey: "attributedTitle") alert.setValue(attributedMessage, forKey: "attributedMessage") // Tradicional let action1 = UIAlertAction(title: "Tradicional", style: .default, handler: { (action) -> Void in UserDefaults(suiteName: "group.bandex.shared")!.set(false, forKey: "vegetariano") self.dietaMayHaveChanged() }) // Vegetariano let action2 = UIAlertAction(title: "Vegetariano", style: .default, handler: { (action) -> Void in UserDefaults(suiteName: "group.bandex.shared")!.set(true, forKey: "vegetariano") // self.typeSegmentedControl.selectedSegmentIndex = 1 self.dietaMayHaveChanged() }) alert.addAction(action1) alert.addAction(action2) self.present(alert, animated: true, completion: nil) } @available(iOS 10.3, *) fileprivate func askForReview() { let launchCount = UserDefaults.standard.integer(forKey: "launchCount") let didAskForReview = UserDefaults.standard.bool(forKey: "didAskForReview") if launchCount >= 5 && !didAskForReview { print("Asking for review...") // Ask for review SKStoreReviewController.requestReview() UserDefaults.standard.set(true, forKey: "didAskForReview") } else { print("Not asking for review") } } override func viewDidLoad() { super.viewDidLoad() print("Loading MainViewController...") let firstLaunchKeyString = "FirstLaunchHappened" if !UserDefaults.standard.bool(forKey: firstLaunchKeyString) { // TODO: Alerta com pergunta de dieta AQUI displayAlert() UserDefaults.standard.set(true, forKey: firstLaunchKeyString) } if #available(iOS 10.3, *) { askForReview() } pageViewController.vegetariano = UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: "vegetariano") } /// Checa se passaram 30min desde a ultima atualizacao para evitar requests desnecessarios que deixam o app lento. func checkIfNeedsRefreshing() { let INTERVALO_DE_RELOAD = 5 // em minutos let components = Calendar.current.dateComponents([.minute], from: lastRefreshed, to: Date()) if let minutes = components.minute, minutes > INTERVALO_DE_RELOAD || pageViewController.cardapios.count == 0 { print("Atualizando cardapios. Minutos desde ultima atualizacao: \(minutes).") // Faz request e atualiza cardapios. self.pageViewController.reloadCardapios() { success in if success { self.lastRefreshed = Date() } } } } func dietaMayHaveChanged() { // Coloquei esse if para ele nao ficar setando o atributo pageViewController.vegetariano sem necessidade, ja que esse atributo chama um metodo para reinstanciar todos os view controllers. if(UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: "vegetariano") != pageViewController.vegetariano) { pageViewController.vegetariano = UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: "vegetariano") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) dietaMayHaveChanged() checkIfNeedsRefreshing() self.screenName = "mainViewController" let name = "mainViewController" // The UA-XXXXX-Y tracker ID is loaded automatically from the // GoogleService-Info.plist by the `GGLContext` in the AppDelegate. // If you're copying this to an app just using Analytics, you'll // need to configure your tracking ID here. // [START screen_view_hit_swift] guard let tracker = GAI.sharedInstance().defaultTracker else { return } tracker.set(kGAIScreenName, value: name) guard let builder = GAIDictionaryBuilder.createScreenView() else { return } tracker.send(builder.build() as [NSObject : AnyObject]) // [END screen_view_hit_swift] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "embedPage" { let controller = segue.destination as! PageViewController self.pageViewController = controller } } }
mit
1b28ecc5f15c897f6a3fb243d262bb82
34.72093
195
0.617025
4.974899
false
false
false
false
jovito-royeca/Decktracker
ios/Pods/Eureka/Source/Rows/PickerRow.swift
6
2896
// // PickerRow.swift // Eureka // // Created by Martin Barreto on 2/23/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation //MARK: PickerCell public class PickerCell<T where T: Equatable> : Cell<T>, CellType, UIPickerViewDataSource, UIPickerViewDelegate{ public lazy var picker: UIPickerView = { [unowned self] in let picker = UIPickerView() picker.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(picker) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": picker])) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": picker])) return picker }() private var pickerRow : _PickerRow<T>? { return row as? _PickerRow<T> } public required init(style: UITableViewCellStyle, reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func setup() { super.setup() accessoryType = .None editingAccessoryType = .None picker.delegate = self picker.dataSource = self } deinit { picker.delegate = nil picker.dataSource = nil } public override func update(){ super.update() textLabel?.text = nil detailTextLabel?.text = nil picker.reloadAllComponents() if let selectedValue = pickerRow?.value, let index = pickerRow?.options.indexOf(selectedValue){ picker.selectRow(index, inComponent: 0, animated: true) } } public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerRow?.options.count ?? 0 } public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerRow?.displayValueFor?(pickerRow?.options[row]) } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if let picker = pickerRow where !picker.options.isEmpty { picker.value = picker.options[row] } } } //MARK: PickerRow public class _PickerRow<T where T: Equatable> : Row<T, PickerCell<T>>{ public var options = [T]() required public init(tag: String?) { super.init(tag: tag) } } /// A generic row where the user can pick an option from a picker view public final class PickerRow<T where T: Equatable>: _PickerRow<T>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
apache-2.0
c28dc38b6d40fafd0651e9f7ef9939fb
31.166667
163
0.652159
4.800995
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/Core/CoreData/GlobalMessageServiceCoreDataHelper.swift
1
9221
// // GlobalMessageServiceCoreDataHelper.swift // GMS Worldwide App // // Created by Vitalii Budnik on 1/25/16. // Copyright © 2016 Global Message Services AG. All rights reserved. // import Foundation import CoreData import UIKit /** Easy `CoreData`. */ public final class GlobalMessageServiceCoreDataHelper { /** Initializes instance with passed `modelName` and `fileName`. Adds observers of application state - parameter modelName: `String` with .xcdatamodeld filename (without extension) - parameter fileName: `String` with filename of created CoreData storage Returns initialized `self` */ private init(withModelName modelName: String, fileName: String) { self.modelName = modelName self.fileName = fileName NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(save), name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(save), name: UIApplicationWillTerminateNotification, object: nil) } /** Attempts to commit unsaved changes in `managedObjectContext`. Recursively for all `parentContext`'s. Public for application state observers */ @objc public func save() { saveContext() } /** Deinitializes `self`. Removes observers of application state */ deinit { NSNotificationCenter.defaultCenter().removeObserver( self, name: UIApplicationDidEnterBackgroundNotification, object: .None) NSNotificationCenter.defaultCenter().removeObserver( self, name: UIApplicationWillTerminateNotification, object: .None) } /// `String` with .xcdatamodeld filename (without extension). (read-only) private let modelName: String /// `String` with filename of created CoreData storage. (read-only) private let fileName: String // MARK: Core Data stack /// Application library directory `NSURL` private lazy var applicationLibraryDirectory: NSURL = { // The directory the application uses to store the Core Data store file. // This code uses a directory named "com.gms-worldwide.GMS_Worldwide" in the application's // documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.LibraryDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() /// The managed object model for the framework private lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the framework. This property is not optional. // It is a fatal error for the application not to be able to find and load its model. let bundle = GlobalMessageService.bundle let modelURL = bundle.URLForResource(modelName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() /// The persistent store coordinator for the framework private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the framework. 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.applicationLibraryDirectory.URLByAppendingPathComponent(fileName + ".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 // if error is NSError { // dict[NSUnderlyingErrorKey] = error // } let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) gmsLog.error("Unresolved error \(wrappedError), \(wrappedError.userInfo)") } return coordinator }() /// Returns the main managed object context for the framework (which is already bound /// to the persistent store coordinator for the framework.) /// Private property private lazy var mainManagedObjectContext: 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 }() /// Returns the main managed object context for the framework (which is already bound to the persistent /// store coordinator for the framework.) /// Private property private 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. var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.parentContext = mainManagedObjectContext return managedObjectContext }() } internal extension GlobalMessageServiceCoreDataHelper { /// `String` with .xcdatamodeld filename (without extension) private static var modelName: String = "GlobalMessageServicesInbox" /// `String` with filename of created CoreData storage private static var fileName: String = modelName /** Sets static `modelName` and `fileName` variables, used to initalize shared instance of `GlobalMessageServiceCoreDataHelper - parameter modelName: `String` with .xcdatamodeld filename (without extension) - parameter fileName: `String` with filename of created CoreData storage - warning: You should call this func before first access to `sharedInstance` property */ internal static func initializeSharedInstance(withModelName modelName: String, fileName: String) { GlobalMessageServiceCoreDataHelper.modelName = modelName GlobalMessageServiceCoreDataHelper.fileName = fileName } /** Generates new `NSManagedObjectContext` for current thread - returns: Newely generated `NSManagedObjectContext` for current thread */ internal func newManagedObjectContext() -> NSManagedObjectContext { let moc = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) moc.parentContext = managedObjectContext return moc } // Core Data Saving support /** Attempts to commit unsaved changes in `managedObjectContext`. Recursively for all `parentContext`'s */ internal func saveContext() { managedObjectContext.performBlockAndWait { if self.managedObjectContext.hasChanges { do { try self.managedObjectContext.saveRecursively() } catch { let nserror = error as NSError gmsLog.error("Unresolved error \(nserror), \(nserror.userInfo)") } } } } } // MARK: - Static extension GlobalMessageServiceCoreDataHelper { /// The shared `GlobalMessageServiceCoreDataHelper` object for the process. (read-only) private (set) static var sharedInstance: GlobalMessageServiceCoreDataHelper = { return GlobalMessageServiceCoreDataHelper(withModelName: modelName, fileName: fileName) }() /// The shared `GlobalMessageServiceCoreDataHelper` object for the process. (read-only) private static var mainManagedObjectContext: NSManagedObjectContext { return sharedInstance.mainManagedObjectContext } /// Returns the main managed object context for the framework /// (which is already bound to the persistent store coordinator for the framework.). (read-only) static var managedObjectContext: NSManagedObjectContext { return sharedInstance.managedObjectContext } /// The managed object model for the framework. (read-only) static var managedObjectModel: NSManagedObjectModel { return sharedInstance.managedObjectModel } /** Generates new `NSManagedObjectContext` for current thread - returns: Newely generated `NSManagedObjectContext` for current thread */ static func newManagedObjectContext() -> NSManagedObjectContext { return sharedInstance.newManagedObjectContext() } // MARK: Core Data Saving support /** Attempts to commit unsaved changes in `managedObjectContext`. Recursively for all `parentContext`'s */ static func saveContext() { sharedInstance.saveContext() } }
apache-2.0
1ce3042da7fa244a0a06d0a9641be805
37.902954
110
0.736334
5.67734
false
false
false
false
yangyu2010/DouYuZhiBo
DouYuZhiBo/DouYuZhiBo/Class/Home/Controller/HomeViewController.swift
1
2950
// // HomeViewController.swift // DouYuZhiBo // // Created by Young on 2017/2/14. // Copyright © 2017年 YuYang. All rights reserved. // import UIKit fileprivate let TitleViewH: CGFloat = 40 class HomeViewController: UIViewController { fileprivate lazy var titleView: YYTitleView = {[weak self] in let frame = CGRect(x: 0, y: kNavigationH, width: kScreenW, height: TitleViewH) let titleView = YYTitleView(frame: frame, titles: ["推荐","游戏","娱乐","趣玩"]) titleView.delegate = self return titleView }() fileprivate lazy var contentView: YYContentView = {[weak self] in let frame = CGRect(x: 0, y: kNavigationH + TitleViewH, width: kScreenW, height: kScreenH - kNavigationH - TitleViewH - kTabBarH) var subVcs = [UIViewController]() subVcs.append(RecommendViewController()) subVcs.append(GameViewController()) subVcs.append(AmusementViewController()) subVcs.append(FunnyViewController()) let contentView = YYContentView(frame: frame, subVcs: subVcs, parentVc: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } } // MARK: -设置UI相关 extension HomeViewController { fileprivate func setupUI() { // 0.设置nav不影响scroll 不然加的Label看不到 automaticallyAdjustsScrollViewInsets = false // 1.设置nav setupNavigationBar() // 2.添加titleView view.addSubview(titleView) // 3. view.addSubview(contentView) // contentView.delegate = self } fileprivate func setupNavigationBar() { // 1.左边的斗鱼图标 navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo", highImageName: "", size: CGSize.zero) // 2.右边的三个item let size = CGSize(width: 30, height: 30) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_clicked", size: size) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "image_my_history_clicked", size: size) navigationItem.rightBarButtonItems = [searchItem, qrcodeItem, historyItem] } } // MARK: -titleView代理 extension HomeViewController : YYTitleViewDelegate { func yyTitleViewScrollToIndex(index: Int) { contentView.scrollToIndex(index: index) } } // MARK: -contentView代理 extension HomeViewController : YYContentViewDelegate { func yyContentViewScroll(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { titleView.setTitleView(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
1ecebff0477e063f7a2184685cbf7c62
29.094737
137
0.658622
4.741294
false
false
false
false
luinily/hOme
hOme/UI/SelectDeviceCommandViewController.swift
1
2784
// // SelectDeviceCommandViewController.swift // hOme // // Created by Coldefy Yoann on 2016/03/20. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class SelectDeviceCommandViewController: UITableViewController, ApplicationUser { @IBOutlet var table: UITableView! private var _device: DeviceProtocol? private var _commands = [CommandProtocol]() private var _selectedCommand: CommandProtocol? private var _onCommandSelected: ((_ command: CommandProtocol) -> Void)? var selectedCommand: CommandProtocol? { get {return _selectedCommand} set(selectedCommand) { _selectedCommand = selectedCommand } } override func viewDidLoad() { table.delegate = self table.dataSource = self } override func willMove(toParentViewController parent: UIViewController?) { if let selectedCommand = _selectedCommand { _onCommandSelected?(selectedCommand) } } func setDevice(_ device: DeviceProtocol?, onOffCommandIncluded: Bool = true) { _device = device if let application = application, let device = device { if let commands = application.getCommandsOfDevice(deviceInternalName: device.internalName) { if onOffCommandIncluded { _commands = commands } else { _commands = commands.filter() { commandIncluded in return !(commandIncluded is OnOffCommand) } } } } } func setOnCommandSelected(_ onCommandSelected: @escaping (_ command: CommandProtocol) -> Void) { _onCommandSelected = onCommandSelected } //MARK: - Table Data Source //MARK: Sections override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Commands" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _commands.count } //MARK: Cells override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell? cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCommandSelectorCell") if let cell = cell as? SelectDeviceCommandCell { cell.command = _commands[(indexPath as NSIndexPath).row] cell.commandSelected = cell.command?.name == _selectedCommand?.name return cell } else { return UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell") } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return false } //MARK: - Table Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { _selectedCommand = _commands[(indexPath as NSIndexPath).row] tableView.reloadData() } }
mit
a705f3caaa07a9b6c9c6c4adfb073a57
27.96875
106
0.735707
4.226444
false
false
false
false
cpuu/OTT
OTT/ResultsTableViewController.swift
1
4343
// // ResultsTableViewController.swift // OTT // // Created by 박재유 on 2016. 6. 9.. // Copyright © 2016년 Troy Stribling. All rights reserved. // import UIKit import MapKit class ResultsTableViewController: UITableViewController { var mapItems: [MKMapItem]! var CellImages = [String]() override func viewDidLoad() { super.viewDidLoad() CellImages = ["Picture1.png", "Picture2.png", "Picture3.png", "Picture4.png", "Picture5.png", "Picture6.png", "Picture7.png", "Picture8.png"] // 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let routeViewController = segue.destinationViewController as! RouteViewController let indexPath = self.tableView.indexPathForSelectedRow! let row = indexPath.row routeViewController.destination = mapItems![row] } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mapItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier( "resultCell", forIndexPath: indexPath) as! ResultsTableCell // Configure the cell... let row = indexPath.row let item = mapItems[row] if ( row < 8){ cell.nameLabel.text = "도곡근린공원" cell.phoneLabel.text = "#아빠와 #등산 #우리가함께한시간 #힐링힐링" cell.takePicture.image = UIImage(named: CellImages[row]) } else{ cell.nameLabel.text = item.name cell.phoneLabel.text = item.phoneNumber cell.takePicture.image = UIImage(named: "Badge.png") } 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
5b96833214c93eb7c76e9c0ef70ac1df
33.304
158
0.649021
5.160048
false
false
false
false
lucaslouca/swipe-away-views
swipe/SwipeView.swift
1
3768
import UIKit enum DisappearDirection { case Left case Right } class SwipeView: UIView { var screenSize: CGRect! var panGestureRecognizer : UIPanGestureRecognizer! var originalPoint:CGPoint! override init(frame: CGRect){ super.init(frame : frame) screenSize = UIScreen.mainScreen().bounds self.backgroundColor = UIColor.greenColor() self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("swiped:")) self.addGestureRecognizer(panGestureRecognizer) loadStyle() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func loadStyle(){ self.layer.cornerRadius = 8 self.layer.shadowOffset = CGSizeMake(5.00, 5.00) self.layer.shadowRadius = 5 } func shouldShowShadow(show:Bool){ if (show) { self.layer.shadowOpacity = 0.5 } else { self.layer.shadowOpacity = 0.0 } } func swiped(gestureRecognizer: UIPanGestureRecognizer) { let xDistance:CGFloat = gestureRecognizer.translationInView(self).x let yDistance:CGFloat = gestureRecognizer.translationInView(self).y switch(gestureRecognizer.state){ case UIGestureRecognizerState.Began: self.originalPoint = self.center shouldShowShadow(true) case UIGestureRecognizerState.Changed: let rotationStrength:CGFloat = min((xDistance/320),1) let rotationAngel:CGFloat = (1.50*CGFloat(M_PI)*CGFloat(rotationStrength) / 15.00) let scaleStrength:CGFloat = 1.00 - CGFloat(fabsf(Float(rotationStrength))) / 4.00 let scale:CGFloat = max(scaleStrength, 0.93); self.center = CGPointMake(self.originalPoint.x + xDistance, self.originalPoint.y + yDistance) let transform:CGAffineTransform = CGAffineTransformMakeRotation(rotationAngel) let scaleTransform:CGAffineTransform = CGAffineTransformScale(transform, scale, scale) self.transform = scaleTransform self.backgroundColor = UIColor.redColor() case UIGestureRecognizerState.Ended: let hasMovedToFarLeft = CGRectGetMaxX(self.frame) < screenSize.width / 2 let hasMovedToFarRight = CGRectGetMinX(self.frame) > screenSize.width / 2 if (hasMovedToFarLeft) { removeViewFromParentWithAnimation(disappearDirection: .Left) } else if (hasMovedToFarRight) { removeViewFromParentWithAnimation(disappearDirection: .Right) } else { self.resetViewPositionAndTransformations() } default: break } } func resetViewPositionAndTransformations(){ UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: .CurveEaseInOut, animations: { self.center = self.originalPoint self.transform = CGAffineTransformMakeRotation(0) self.shouldShowShadow(false) }, completion: {success in }) } func removeViewFromParentWithAnimation(disappearDirection disappearDirection:DisappearDirection){ var animations:(()->Void)! switch disappearDirection { case .Left: animations = {self.center.x = -self.frame.width} case .Right: animations = {self.center.x = self.screenSize.width + self.frame.width} default: break } UIView.animateWithDuration(0.2, animations: animations , completion: {success in self.removeFromSuperview()}) } }
mit
27a1664860a087cf046bed180353010e
35.582524
148
0.633227
5.182944
false
false
false
false
appcodev/Let-Swift-Code
BeyondClass-Swift/BeyondClass-Swift/main.swift
1
14293
// // main.swift // BeyondClass-Swift // // Created by Chalermchon Samana on 6/6/14. // Copyright (c) 2014 Onzondev Innovation Co., Ltd. All rights reserved. // import Foundation println("Beyond Class!") //structures in swift //การสร้าง struct //struct MyPoint { // var x, y: Double // init(x:Double, y:Double){ // self.x = x // self.y = y // } //} // //struct MySize { // var width, height: Double //} //struct MyRect { // var origin: MyPoint // var size0: MySize // var area: Double { // return size.width*size.height // } // init(){ // self.origin = MyPoint(x:0, y:0) // self.size0 = MySize(width:0, height:0) // //area = self.size.width * self.size.height // } // // // //message of structure // func isBiggerThanRect(other: MyRect) -> Bool { // return self.area > other.area // } //} //var p = MyPoint(x:0.0, y:0.0) //println(p.x,p.y) //class MyWindow { // var frame: MyRect // // init(){ // // } //} /* //Stucture กับ Class ต่างกันอย่างไร 1. Structure ไม่สามารถมีการสืบทอดกับ Structure อื่นได้เหมือน Class 2. การเปลี่ยนแปลงค่า object โดยที่ object ของ Structure จะเปลี่ยนแปลงค่าโดยการ pass by value (ส่งไปแต่ค่า เปลี่ยนแปลงเฉพาะค่า ส่วนใหญ่จะเกี่ยวกับตัวเลข) object ของ Class จะเปลี่ยนแปลงค่าแบบ pass by reference (อ้างอิงตำแหน่งของหน่วยความจำที่สร้างออฟเจ็คนั้นๆ) */ //Constant and Variables: Reference Types /* //สร้าง frame ขึ้นมาอันนึง ละไว้นะ //สร้าง window let window = Window(frame: frame) window.title = "Hello!" //อันนี้เราสามารถเปลี่ยนค่าได้ ถึงแม้ว่า window ของเราจะประกาศเป็น constant ก็ตาม //แต่ เราไม่สามารถเปลี่ยนแปลงการอ้างอิงตัว window นี้ได้ เพราะเราประกาศเป็น constant นะ // window = Window(frame: frame2) //error: Cannot mutate a constant! */ //Constant and Variables: Value Types var point1 = Point(v: 0, h: 0) point1.v = 50 //point1 v=50 h=0 ... OK let point2 = Point(v:0, h:0) //point2.v = 50 // X //error: ไม่สามารถเปลี่ยนแปลงค่าของ constant ได้นะ //Mutating a Structure struct MyMuPoint { var x, y: Double //การสร้าง structure หากไม่มี ฟังก์ชั่น init แล้วจะต้องใส่พารามิเตอร์ทุกตัวที่เป็น property ของ struct ตัวนั้นให้หมด //แต่หากมี init() ในฟังก์ชั่นเราจะต้องเรียกใช้ self.x self.y (เรียกใช้ property ด้วย) เพื่อกำหนดค่าเริ่มต้นด้วย init(){ self.x = 0 self.y = 0 } init(x:Double, y:Double){ self.x = x self.y = y } //หากต้องการมี message ใน struct ที่ทำการเปลี่ยนแปลงค่าของ property จำเป็นต้องใส่คีย์เวิร์ด mutating ไว้ด้านหน้าด้วย mutating func moveToRightBy(dx: Double) { x += dx } } var p1 = MyMuPoint(x:20, y:10) println("1. p1 x:\(p1.x) y:\(p1.y)") p1.x = 40 p1.y = 50 println("2. p1 x:\(p1.x) y:\(p1.y)") p1.x += 20 println("3. p1 x:\(p1.x) y:\(p1.y)") p1.moveToRightBy(10) println("4. p1 x:\(p1.x) y:\(p1.y)") let p2 = MyMuPoint() //p2.x = 80 //error: can't assign to 'x' in 'p2' //p2.moveToRightBy(20) //Error: Immutable value of type 'MyMuPoint' only has mutating members named 'moveToRigthBy' //จะต้องเป็นตัวแปร MyMuPoint แบบเปลี่ยนแปลงค่าได้ (var) เท่านั้นจึงจะสามารถเรียกใช้งาน 'moveToRigthBy' ได้ //Enumeration: Raw Values //enum แบบกำหนดค่า enum Planet: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune //Raw Values 2 3 4 5 6 7 8 /* case Mercury = 11, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune //Raw Values 12 13 14 15 16 17 18 */ } let earthNum = Planet.Earth.toRaw() println(earthNum) //3 enum ControlCharacter: Character{ case Tab = "\t" case Linefeed = "\n" case CarriageReturn = "\r" } println("Go to Page\(ControlCharacter.Tab.toRaw())Let Swift\(ControlCharacter.Linefeed.toRaw())to Learn and Share about Swift Programming\(ControlCharacter.CarriageReturn.toRaw()):)") /* Go to Page Let Swift to Learn and Share about Swift Programming :) //tab จะไม่แสดงผลบน console แต่เมื่อก็อปปี้มาลงแล้วจะแสดงผลตามปกติ */ //การประกาศ enum นั้นสามารถประกาศได้โดยใส่ชื่อ enum ของเราและใส่ Type ไปด้วยว่าจะให้เป็นคลาสอะไร เช่น Int Character จะได้รู้ว่าสมาชิกจะเป็นชนิดอะไร //การเรียกใช้ค่าของสมาชิกแต่ละตัวจะต้องเรียกใช้ผ่าน .toRaw() //Enumeration //enum ที่จะใช้แต่ชื่อสมาชิก enum CompassPoint { case North, South, East, West } println("compass \(CompassPoint.North) \(CompassPoint.South) \(CompassPoint.East) \(CompassPoint.West)") //compass (Enum Value) (Enum Value) (Enum Value) (Enum Value) var direction = CompassPoint.North //change direction = .East //ตอนนี้ตัวแปร direction นั้นรู้แล้วว่าตนเองเป็น CompassPoint ดังนั้นเวลาจะเปลี่ยนเป็นตัวอื่นก็ใช้แค่ .East ก็พอ println("direction \(direction)") //direction (Enum Value) /* let label = UILabel() label.textAligment = .Right //อย่าง ตัวอย่างของการเซ็ตการจัดเรียงแนวของ label จะใส่แค่ .Right เท่านั้น */ //Enumerations: Associated Values /* enum ที่มีทั้งสมาชิกที่ไม่กำหนดค่าเข้าไป และสมาชิกที่สามารถกำหนดค่าได้ วืิธีการกำหนดค่า ให้เขียนชื่อสมาชิก(ชนิดของตัวแปรเข้าไป) เช่น Delayed(Int) เราสามารถกำหนดค่าเริ่มต้นให้กับ enum ได้โดยใช้ฟังก์ชั่น init เช่นเดียวกับ class และ structure เราสามารถมีตัวแปรที่เป็น property ของ enum ได้เช่นกัน ตัวอย่าง description: String * การเรียกใช้สมาชิกที่มีพารามิเตอร์ จำเป็นจะต้องประกาศตัวแปรของพารามิเตอร์ก่อนใช้งานด้วย เช่น case Delayed(let min): return "Delayed by \(min) minute" //เราประกาศ let min เพื่อให้สอดคล้องกับตอนประกาศสมาชิก Delayed(Int) */ enum TrainStatus { case OnTime, Delayed(Int) init() { self = OnTime } var description: String { switch self{ case OnTime: return "On Time" case Delayed(let minutes): return "Delayed by \(minutes) minute" } } } var trainStatus = TrainStatus() println("train \(trainStatus.description)") //train On Time trainStatus = .Delayed(5) println("tain!!! \(trainStatus.description)") //tain!!! Delayed by 5 minute //Nested Types //เราสามารถประกาศ enum ให้เป็น property ของคลาสได้ class Train { enum Status { case OnTime, Delayed(Int) init(){ self = OnTime } var description: String { switch self { case OnTime: return "on Time" case Delayed(let min): return "delay \(min) minute" } } } var status = Status() } let train = Train() var tDesc = train.status.description println("Train desc : \(tDesc)") //Train desc : on Time train.status = .Delayed(90) println("Train desc : \(tDesc)") //Train desc : on Time //สาเหตุที่ค่าของ status.description ไม่เปลี่ยนตามนั้นก็เพราะ enum เป็นการพาสค่าแบบ Value จึงจำเป็นต้องประกาศตัวแปรมารับค่าที่อัพเดทใหม่อีกครั้ง var newTDesc = train.status.description println("Train desc : \(newTDesc)") //Train desc : delay 90 minute //Extensions //like Category in Objective-C //ทำได้ทั้ง Class และ Struct //Extentsion กับ structure var pp1 = MyMuPoint(x:80, y:0) pp1.moveToRightBy(10) //pp1.moveToLeftTopBy(20, dy:10) //**จะเรียกใช้ moveToLeftTopBy ไม่ได้เพราะยังไม่ได้ประกาศ println("pp1 x \(pp1.x)") extension MyMuPoint { mutating func moveToLeftTopBy(dx:Double, dy:Double) { x -= dx y -= dy } } pp1.moveToLeftTopBy(20, dy:10) //**จะเรียกใช้ moveToLeftTopBy ได้เพราะประกาศเพิ่มในแบบ extension แล้ว println("pp1 x \(pp1.x)") //pp1 x 70.0 //จะประกาศตัวใหม่ก็ได้ var pp2 = MyMuPoint(x:10, y:20) pp2.moveToLeftTopBy(5, dy:10) println("pp2 x \(pp2.x)") //pp2 x 5.0 //Extension กับ enum var eCom1 = CompassPoint.North //println("com1 \(eCom1) \(eCom1.desc)") //** จะเรียกใช้ desc ไม่ได้เพราะไม่มีการประกาศอยู่ใน enum CompassPoint ก่อนหน้านี้ extension CompassPoint { var desc: String { switch self { case North: return "North" case South: return "South" case East: return "East" case West: return "West" } } } println("com1 \(eCom1) \(eCom1.desc)") //com1 (Enum Value) North //** สามารถเรียกใช้ได้ เนื่องจากเราประกาศตัวแปร desc เข้าไปแล้วใน extension //Extension กับ Int extension Int { func repetitions(task: ()->()) { for i in 0..self { task() } } } 5.repetitions { println("Five!") } /* Five! Five! Five! Five! Five! */ //A Non-Generic Stack Sturcture struct IntStack { var elements = Int[]() mutating func push(element: Int) { elements.append(element) } mutating func pop() -> Int { return elements.removeLast() } } /* จากตัวอย่าง เป็นการสร้าง struct ธรรมดาที่ทำตัวเป็น stack แต่ถ้าทำแบบนี้ จะใส่ค่า ได้เฉพาะชนิดตัวแปรนั้นๆ เท่านั้น จึงจำเป็นต้องทำให้เป็นแบบ Generic ถึงจะสามารถใส่ค่าได้หลายๆ ชนิด */ //A Generic Stack Sturcture struct Stack<T> { var elements = T[]() mutating func push(element: T) { elements.append(element) } mutating func pop() -> T { return elements.removeLast() } var description: String { return "elements: \(elements)" } } /* Generic จะใช้ <T> เป็นตัวบ่งบอกว่าสามารถใช้พารามิเตอร์ได้หลากหลายชนิด ที่เป็นชนืดเดียวกันเท่านั้น */ var intSck = Stack<Int>() intSck.push(90) intSck.push(22) intSck.push(88) println("int stack \(intSck.description)") //int stack elements: [90, 22, 88] let lastInt = intSck.pop() println("int stack last \(lastInt)") //int stack last 88 println("int stack \(intSck.description)") //int stack elements: [90, 22] var stringSck = Stack<String>() stringSck.push("Hello") stringSck.push("Let") stringSck.push("Swift") stringSck.push("Yaaa hoo") //!! stringSck.push(59) // คนละชนิดกับที่ประกาศเอาไว้จึงไม่สามารถใช้ได้ println("stack \(stringSck.description)") //stack elements: [Hello, Let, Swift, Yaaa hoo] let lastString = stringSck.pop() println("last \(lastString)") println("stack \(stringSck.description)") //last Yaaa hoo //stack elements: [Hello, Let, Swift]
apache-2.0
502fda51926f9655d3d89b8fa6c2b09f
23.965432
183
0.62882
2.64409
false
false
false
false
pgorzelany/PGChoiceViewController
PGChoiceViewController/SettingsTableViewController.swift
1
2976
// // SettingsTableViewController.swift // PGChoiceViewController // // Created by Piotr Gorzelany on 17/11/15. // Copyright © 2015 Piotr Gorzelany. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { @IBOutlet weak var sortOrderCell: UITableViewCell! @IBOutlet weak var sortByCell: UITableViewCell! @IBOutlet weak var studentCell: UITableViewCell! override func viewWillAppear(animated: Bool) { if let sortOrder = Settings.sortOrder?.description { sortOrderCell.detailTextLabel!.text = sortOrder } if let sortBy = Settings.sortBy?.description { sortByCell.detailTextLabel?.text = sortBy } if let student = Settings.student?.description { studentCell.detailTextLabel?.text = student } } let piotr = Student(name: "Piotr", surname: "Gorzelany") let john = Student(name: "John", surname: "Appleseed") override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard let selectedCell = tableView.cellForRowAtIndexPath(indexPath) else {return} let choiceController: UITableViewController if selectedCell == sortOrderCell { let sortOrderChoices: [SortOrder] = [.Ascending, .Descending] let currentSortOrderChoice = Settings.sortOrder choiceController = PGChoiceViewController(choices: sortOrderChoices, currentChoice: currentSortOrderChoice, choiceHandler: { (sortOrder) -> Void in Settings.sortOrder = sortOrder self.navigationController?.popViewControllerAnimated(true) }) } else if selectedCell == sortByCell { let sortByChoices: [SortBy] = [.Date, .Priority, .Title, .Progress, .Deadline] let currentSortByChoice = Settings.sortBy choiceController = PGChoiceViewController(choices: sortByChoices, currentChoice: currentSortByChoice, choiceHandler: { (sortBy) -> Void in Settings.sortBy = sortBy self.navigationController?.popViewControllerAnimated(true) }) } else { // Student cell let studentChoice = [piotr, john] let currentStudentChoice = Settings.student choiceController = PGChoiceViewController(choices: studentChoice, currentChoice: currentStudentChoice, choiceHandler: { (student) -> Void in Settings.student = student self.navigationController?.popViewControllerAnimated(true) }) } choiceController.title = selectedCell.textLabel?.text self.navigationController?.pushViewController(choiceController, animated: true) } }
mit
ab0bfc7aeb33338caca0073aabb3394e
35.280488
159
0.627563
5.844794
false
false
false
false
LarkNan/SXMWB
SXMWeibo/SXMWeibo/Classes/Home/StatusListModel.swift
1
2847
// // StatusListModel.swift // SXMWeibo // // Created by 申铭 on 2017/3/12. // Copyright © 2017年 shenming. All rights reserved. // import UIKit import SDWebImage class StatusListModel: NSObject { // 保存所有微博数据 var statuses: [StatusViewModel]? func loadData(lastStatus : Bool, finished: (models: [StatusViewModel]?, error: NSError?) -> ()) { var since_id = statuses?.first?.status.idstr ?? "0" var max_id = "0" if lastStatus { since_id = "0" max_id = statuses?.last?.status.idstr ?? "0" } NetworkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (array, error) -> () in if error != nil { finished(models: nil, error: error) return } // 将字典数组转换为模型数组 var models = [StatusViewModel]() for dict in array! { let status = StatusViewModel(status: Status(dict: dict)) models.append(status) } // 处理微博数据 if since_id != "0" { self.statuses = models + self.statuses! } else if max_id != "0" { self.statuses = self.statuses! + models } else { self.statuses = models } // 缓存微博所有配图 self.cachesImages(models, finished: finished) // self.refreshControl?.endRefreshing() // // // 显示刷新提醒 // self.showRefreshStatus(models.count) } } private func cachesImages(viewModels: [StatusViewModel], finished: (models: [StatusViewModel]?, error: NSError?) -> ()) { // 创建一个组 let group = dispatch_group_create() for viewModel in viewModels { guard let picurls = viewModel.thumbnail_pic else { continue } // 遍历配图数组下载图片 for url in picurls { // 将下载操作添加到组中 dispatch_group_enter(group) // 下载图片 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in SXMLog("图片下载完成") // 将当前下载操作从组中移除 dispatch_group_leave(group) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in SXMLog("全部图片下载完成"); finished(models: viewModels, error: nil) } } }
mit
1b0cf17db0928797d9f40bee7dfc7243
30.176471
179
0.491321
4.561102
false
false
false
false
CatchChat/Yep
YepKit/UserDefaults/YepUserDefaults.swift
1
15575
// // YepUserDefaults.swift // Yep // // Created by NIX on 15/3/17. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import CoreSpotlight import CoreLocation import RealmSwift private let v1AccessTokenKey = "v1AccessToken" private let userIDKey = "userID" private let nicknameKey = "nickname" private let introductionKey = "introduction" private let avatarURLStringKey = "avatarURLString" private let badgeKey = "badge" private let blogURLStringKey = "blogURLString" private let blogTitleKey = "blogTitle" private let pusherIDKey = "pusherID" private let adminKey = "admin" private let areaCodeKey = "areaCode" private let mobileKey = "mobile" private let discoveredUserSortStyleKey = "discoveredUserSortStyle" private let feedSortStyleKey = "feedSortStyle" private let latitudeShiftKey = "latitudeShift" private let longitudeShiftKey = "longitudeShift" private let userCoordinateLatitudeKey = "userCoordinateLatitude" private let userCoordinateLongitudeKey = "userCoordinateLongitude" private let userLocationNameKey = "userLocationName" private let syncedConversationsKey = "syncedConversations" private let appLaunchCountKey = "appLaunchCount" private let tabBarItemTextEnabledKey = "tabBarItemTextEnabled" public struct Listener<T>: Hashable { let name: String public typealias Action = T -> Void let action: Action public var hashValue: Int { return name.hashValue } } public func ==<T>(lhs: Listener<T>, rhs: Listener<T>) -> Bool { return lhs.name == rhs.name } final public class Listenable<T> { public var value: T { didSet { setterAction(value) for listener in listenerSet { listener.action(value) } } } public typealias SetterAction = T -> Void var setterAction: SetterAction var listenerSet = Set<Listener<T>>() public func bindListener(name: String, action: Listener<T>.Action) { let listener = Listener(name: name, action: action) listenerSet.insert(listener) } public func bindAndFireListener(name: String, action: Listener<T>.Action) { bindListener(name, action: action) action(value) } public func removeListenerWithName(name: String) { for listener in listenerSet { if listener.name == name { listenerSet.remove(listener) break } } } public func removeAllListeners() { listenerSet.removeAll(keepCapacity: false) } public init(_ v: T, setterAction action: SetterAction) { value = v setterAction = action } } final public class YepUserDefaults { static let defaults = NSUserDefaults(suiteName: Config.appGroupID)! public static let appLaunchCountThresholdForTabBarItemTextEnabled: Int = 30 public static var isLogined: Bool { if let _ = YepUserDefaults.v1AccessToken.value { return true } else { return false } } public static var isSyncedConversations: Bool { if let syncedConversations = YepUserDefaults.syncedConversations.value { return syncedConversations } else { return false } } public static var blogString: String? { if let blogURLString = YepUserDefaults.blogURLString.value { guard !blogURLString.isEmpty else { return nil } if let blogTitle = YepUserDefaults.blogTitle.value where !blogTitle.isEmpty { return blogTitle } else { return blogURLString } } return nil } public static var userCoordinate: CLLocationCoordinate2D? { guard let latitude = YepUserDefaults.userCoordinateLatitude.value, longitude = YepUserDefaults.userCoordinateLongitude.value else { return nil } return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } // MARK: ReLogin public class func cleanAllUserDefaults() { do { v1AccessToken.removeAllListeners() userID.removeAllListeners() nickname.removeAllListeners() introduction.removeAllListeners() avatarURLString.removeAllListeners() badge.removeAllListeners() blogURLString.removeAllListeners() blogTitle.removeAllListeners() pusherID.removeAllListeners() admin.removeAllListeners() areaCode.removeAllListeners() mobile.removeAllListeners() discoveredUserSortStyle.removeAllListeners() feedSortStyle.removeAllListeners() latitudeShift.removeAllListeners() longitudeShift.removeAllListeners() userCoordinateLatitude.removeAllListeners() userCoordinateLongitude.removeAllListeners() userLocationName.removeAllListeners() syncedConversations.removeAllListeners() appLaunchCount.removeAllListeners() tabBarItemTextEnabled.removeAllListeners() } do { // Manually reset YepUserDefaults.v1AccessToken.value = nil YepUserDefaults.userID.value = nil YepUserDefaults.nickname.value = nil YepUserDefaults.introduction.value = nil YepUserDefaults.badge.value = nil YepUserDefaults.blogURLString.value = nil YepUserDefaults.blogTitle.value = nil YepUserDefaults.pusherID.value = nil YepUserDefaults.admin.value = nil YepUserDefaults.areaCode.value = nil YepUserDefaults.mobile.value = nil YepUserDefaults.discoveredUserSortStyle.value = nil YepUserDefaults.feedSortStyle.value = nil // No reset Location related YepUserDefaults.syncedConversations.value = false YepUserDefaults.appLaunchCount.value = 0 YepUserDefaults.tabBarItemTextEnabled.value = nil defaults.synchronize() } /* // reset suite let dict = defaults.dictionaryRepresentation() dict.keys.forEach({ println("removeObjectForKey defaults key: \($0)") defaults.removeObjectForKey($0) }) defaults.synchronize() // reset standardUserDefaults let standardUserDefaults = NSUserDefaults.standardUserDefaults() standardUserDefaults.removePersistentDomainForName(NSBundle.mainBundle().bundleIdentifier!) standardUserDefaults.synchronize() */ } public class func maybeUserNeedRelogin(prerequisites prerequisites: () -> Bool, confirm: () -> Void) { guard v1AccessToken.value != nil else { return } CSSearchableIndex.defaultSearchableIndex().deleteAllSearchableItemsWithCompletionHandler(nil) guard prerequisites() else { return } cleanAllUserDefaults() confirm() } public static var v1AccessToken: Listenable<String?> = { let v1AccessToken = defaults.stringForKey(v1AccessTokenKey) return Listenable<String?>(v1AccessToken) { v1AccessToken in defaults.setObject(v1AccessToken, forKey: v1AccessTokenKey) Config.updatedAccessTokenAction?() } }() public static var userID: Listenable<String?> = { let userID = defaults.stringForKey(userIDKey) return Listenable<String?>(userID) { userID in defaults.setObject(userID, forKey: userIDKey) } }() public static var nickname: Listenable<String?> = { let nickname = defaults.stringForKey(nicknameKey) return Listenable<String?>(nickname) { nickname in defaults.setObject(nickname, forKey: nicknameKey) guard let realm = try? Realm() else { return } if let nickname = nickname, let me = meInRealm(realm) { let _ = try? realm.write { me.nickname = nickname } } } }() public static var introduction: Listenable<String?> = { let introduction = defaults.stringForKey(introductionKey) return Listenable<String?>(introduction) { introduction in defaults.setObject(introduction, forKey: introductionKey) guard let realm = try? Realm() else { return } if let introduction = introduction, let me = meInRealm(realm) { let _ = try? realm.write { me.introduction = introduction } } } }() public static var avatarURLString: Listenable<String?> = { let avatarURLString = defaults.stringForKey(avatarURLStringKey) return Listenable<String?>(avatarURLString) { avatarURLString in defaults.setObject(avatarURLString, forKey: avatarURLStringKey) guard let realm = try? Realm() else { return } if let avatarURLString = avatarURLString, let me = meInRealm(realm) { let _ = try? realm.write { me.avatarURLString = avatarURLString } } } }() public static var badge: Listenable<String?> = { let badge = defaults.stringForKey(badgeKey) return Listenable<String?>(badge) { badge in defaults.setObject(badge, forKey: badgeKey) guard let realm = try? Realm() else { return } if let badge = badge, let me = meInRealm(realm) { let _ = try? realm.write { me.badge = badge } } } }() public static var blogURLString: Listenable<String?> = { let blogURLString = defaults.stringForKey(blogURLStringKey) return Listenable<String?>(blogURLString) { blogURLString in defaults.setObject(blogURLString, forKey: blogURLStringKey) guard let realm = try? Realm() else { return } if let blogURLString = blogURLString, let me = meInRealm(realm) { let _ = try? realm.write { me.blogURLString = blogURLString } } } }() public static var blogTitle: Listenable<String?> = { let blogTitle = defaults.stringForKey(blogTitleKey) return Listenable<String?>(blogTitle) { blogTitle in defaults.setObject(blogTitle, forKey: blogTitleKey) guard let realm = try? Realm() else { return } if let blogTitle = blogTitle, let me = meInRealm(realm) { let _ = try? realm.write { me.blogTitle = blogTitle } } } }() public static var pusherID: Listenable<String?> = { let pusherID = defaults.stringForKey(pusherIDKey) return Listenable<String?>(pusherID) { pusherID in defaults.setObject(pusherID, forKey: pusherIDKey) // 注册推送的好时机 if let pusherID = pusherID { Config.updatedPusherIDAction?(pusherID: pusherID) } } }() public static var admin: Listenable<Bool?> = { let admin = defaults.boolForKey(adminKey) return Listenable<Bool?>(admin) { admin in defaults.setObject(admin, forKey: adminKey) } }() public static var areaCode: Listenable<String?> = { let areaCode = defaults.stringForKey(areaCodeKey) return Listenable<String?>(areaCode) { areaCode in defaults.setObject(areaCode, forKey: areaCodeKey) } }() public static var mobile: Listenable<String?> = { let mobile = defaults.stringForKey(mobileKey) return Listenable<String?>(mobile) { mobile in defaults.setObject(mobile, forKey: mobileKey) } }() public static var fullPhoneNumber: String? { if let areaCode = areaCode.value, mobile = mobile.value { return "+" + areaCode + " " + mobile } return nil } public static var discoveredUserSortStyle: Listenable<String?> = { let discoveredUserSortStyle = defaults.stringForKey(discoveredUserSortStyleKey) return Listenable<String?>(discoveredUserSortStyle) { discoveredUserSortStyle in defaults.setObject(discoveredUserSortStyle, forKey: discoveredUserSortStyleKey) } }() public static var feedSortStyle: Listenable<String?> = { let feedSortStyle = defaults.stringForKey(feedSortStyleKey) return Listenable<String?>(feedSortStyle) { feedSortStyle in defaults.setObject(feedSortStyle, forKey: feedSortStyleKey) } }() public static var latitudeShift: Listenable<Double?> = { let latitudeShift = defaults.doubleForKey(latitudeShiftKey) return Listenable<Double?>(latitudeShift) { latitudeShift in defaults.setObject(latitudeShift, forKey: latitudeShiftKey) } }() public static var longitudeShift: Listenable<Double?> = { let longitudeShift = defaults.doubleForKey(longitudeShiftKey) return Listenable<Double?>(longitudeShift) { longitudeShift in defaults.setObject(longitudeShift, forKey: longitudeShiftKey) } }() public static var userCoordinateLatitude: Listenable<Double?> = { let userCoordinateLatitude = defaults.doubleForKey(userCoordinateLatitudeKey) return Listenable<Double?>(userCoordinateLatitude) { userCoordinateLatitude in defaults.setObject(userCoordinateLatitude, forKey: userCoordinateLatitudeKey) } }() public static var userCoordinateLongitude: Listenable<Double?> = { let userCoordinateLongitude = defaults.doubleForKey(userCoordinateLongitudeKey) return Listenable<Double?>(userCoordinateLongitude) { userCoordinateLongitude in defaults.setObject(userCoordinateLongitude, forKey: userCoordinateLongitudeKey) } }() public static var userLocationName: Listenable<String?> = { let userLocationName = defaults.stringForKey(userLocationNameKey) return Listenable<String?>(userLocationName) { userLocationName in defaults.setObject(userLocationName, forKey: userLocationNameKey) } }() public static var syncedConversations: Listenable<Bool?> = { let syncedConversations = defaults.boolForKey(syncedConversationsKey) return Listenable<Bool?>(syncedConversations) { syncedConversations in defaults.setObject(syncedConversations, forKey: syncedConversationsKey) } }() public static var appLaunchCount: Listenable<Int> = { let appLaunchCount = defaults.integerForKey(appLaunchCountKey) ?? 0 return Listenable<Int>(appLaunchCount) { appLaunchCount in defaults.setObject(appLaunchCount, forKey: appLaunchCountKey) } }() public static var tabBarItemTextEnabled: Listenable<Bool?> = { let tabBarItemTextEnabled = defaults.objectForKey(tabBarItemTextEnabledKey) as? Bool return Listenable<Bool?>(tabBarItemTextEnabled) { tabBarItemTextEnabled in defaults.setObject(tabBarItemTextEnabled, forKey: tabBarItemTextEnabledKey) } }() }
mit
2b105df8137b5d7e10771c00c7ced442
30.491903
139
0.634248
5.552106
false
false
false
false
ifeherva/HSTracker
HSTracker/Logging/Game.swift
1
58991
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 13/02/16. */ import Foundation import RealmSwift import HearthMirror struct PlayingDeck { let id: String let name: String let hsDeckId: Int64? let playerClass: CardClass let heroId: String let cards: [Card] let isArena: Bool } /** * Game object represents the current state of the tracker */ class Game: NSObject, PowerEventHandler { /** * View controller of this game object */ #if DEBUG internal let windowManager = WindowManager() #else private let windowManager = WindowManager() #endif static let guiUpdateDelay: TimeInterval = 0.5 private let turnTimer: TurnTimer private var hearthstoneRunState: HearthstoneRunState { didSet { if hearthstoneRunState.isRunning { // delay update as game might not have a proper window DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1), execute: { [weak self] in self?.updateTrackers() }) } else { self.updateTrackers() } } } private var selfAppActive: Bool = true func setHearthstoneRunning(flag: Bool) { hearthstoneRunState.isRunning = flag } func setHearthstoneActived(flag: Bool) { hearthstoneRunState.isActive = flag } func setSelfActivated(flag: Bool) { self.selfAppActive = flag self.updateTrackers() } // MARK: - PowerEventHandler protocol func handleEntitiesChange(changed: [(old: Entity, new: Entity)]) { if let playerPair = changed.first(where: { $0.old.id == self.player.id }) { // TODO: player entity changed if let oldName = playerPair.old.name, let newName = playerPair.new.name, oldName != newName { print("Player entity name changed from \(oldName) to \(newName)") } else { // get added/removed tags let newTags = playerPair.new.tags.keys.filter { !playerPair.old.tags.keys.contains($0) } if newTags.contains(.mulligan_state) { print("Player new mulligan state: \(playerPair.new[.mulligan_state])") } } } } func add(entity: Entity) { if entities[entity.id] == .none { entities[entity.id] = entity } } func determinedPlayers() -> Bool { return player.id > 0 && opponent.id > 0 } private var guiNeedsUpdate = false private var guiUpdateResets = false private let _queue = DispatchQueue(label: "be.michotte.hstracker.guiupdate", attributes: []) private func _updateTrackers(notification: Notification) { self._updateTrackers() } private func _updateTrackers() { SizeHelper.hearthstoneWindow.reload() self.updatePlayerTracker(reset: guiUpdateResets) self.updateOpponentTracker(reset: guiUpdateResets) self.updateCardHud() self.updateTurnTimer() self.updateBoardStateTrackers() self.updateArenaHelper() self.updateSecretTracker() } // MARK: - GUI calls var shouldShowGUIElement: Bool { return // do not show gui while spectating !(Settings.dontTrackWhileSpectating && self.spectator) && // do not show gui while game is in background !((Settings.hideAllWhenGameInBackground || Settings.hideAllWhenGameInBackground) && !self.hearthstoneRunState.isActive) } func updateTrackers(reset: Bool = false) { self.guiNeedsUpdate = true self.guiUpdateResets = reset || self.guiUpdateResets } @objc fileprivate func updateOpponentTracker(reset: Bool = false) { DispatchQueue.main.async { [unowned(unsafe) self] in let tracker = self.windowManager.opponentTracker if Settings.showOpponentTracker && !(Settings.dontTrackWhileSpectating && self.spectator) && ((Settings.hideAllTrackersWhenNotInGame && !self.gameEnded) || (!Settings.hideAllTrackersWhenNotInGame) || self.selfAppActive ) && ((Settings.hideAllWhenGameInBackground && self.hearthstoneRunState.isActive) || !Settings.hideAllWhenGameInBackground || self.selfAppActive) { // update cards if self.gameEnded && Settings.clearTrackersOnGameEnd { tracker.update(cards: [], reset: reset) } else { tracker.update(cards: self.opponent.opponentCardList, reset: reset) } let gameStarted = !self.isInMenu && self.entities.count >= 67 tracker.updateCardCounter(deckCount: !gameStarted ? 30 : self.opponent.deckCount, handCount: !gameStarted ? 0 : self.opponent.handCount, hasCoin: self.opponent.hasCoin, gameStarted: gameStarted) tracker.showCthunCounter = self.showOpponentCthunCounter tracker.showSpellCounter = Settings.showOpponentSpell tracker.showDeathrattleCounter = Settings.showOpponentDeathrattle tracker.showGraveyard = Settings.showOpponentGraveyard tracker.showJadeCounter = self.showOpponentJadeCounter tracker.proxy = self.opponentCthunProxy tracker.nextJadeSize = self.opponentNextJadeGolem tracker.fatigueCounter = self.opponent.fatigue tracker.spellsPlayedCount = self.opponent.spellsPlayedCount tracker.deathrattlesPlayedCount = self.opponent.deathrattlesPlayedCount tracker.playerName = self.opponent.name tracker.graveyard = self.opponent.graveyard tracker.playerClassId = self.opponent.playerClassId tracker.currentFormat = self.currentFormat tracker.currentGameMode = self.currentGameMode tracker.matchInfo = self.matchInfo tracker.setWindowSizes() var rect: NSRect? if Settings.autoPositionTrackers && self.hearthstoneRunState.isRunning { rect = SizeHelper.opponentTrackerFrame() } else { rect = Settings.opponentTrackerFrame if rect == nil { let x = WindowManager.screenFrame.origin.x + 50 rect = NSRect(x: x, y: WindowManager.top + WindowManager.screenFrame.origin.y, width: WindowManager.cardWidth, height: WindowManager.top) } } tracker.hasValidFrame = true self.windowManager.show(controller: tracker, show: true, frame: rect, title: "Opponent tracker", overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: tracker, show: false) } } } @objc fileprivate func updatePlayerTracker(reset: Bool = false) { DispatchQueue.main.async { [unowned(unsafe) self] in let tracker = self.windowManager.playerTracker if Settings.showPlayerTracker && !(Settings.dontTrackWhileSpectating && self.spectator) && ( (Settings.hideAllTrackersWhenNotInGame && !self.gameEnded) || (!Settings.hideAllTrackersWhenNotInGame) || self.selfAppActive ) && ((Settings.hideAllWhenGameInBackground && self.hearthstoneRunState.isActive) || !Settings.hideAllWhenGameInBackground || self.selfAppActive) { // update cards tracker.update(cards: self.player.playerCardList, reset: reset) // update card counter values let gameStarted = !self.isInMenu && self.entities.count >= 67 tracker.updateCardCounter(deckCount: !gameStarted ? 30 : self.player.deckCount, handCount: !gameStarted ? 0 : self.player.handCount, hasCoin: self.player.hasCoin, gameStarted: gameStarted) tracker.showCthunCounter = self.showPlayerCthunCounter tracker.showSpellCounter = self.showPlayerSpellsCounter tracker.showDeathrattleCounter = self.showPlayerDeathrattleCounter tracker.showGraveyard = Settings.showPlayerGraveyard tracker.showJadeCounter = self.showPlayerJadeCounter tracker.proxy = self.playerCthunProxy tracker.nextJadeSize = self.playerNextJadeGolem tracker.fatigueCounter = self.player.fatigue tracker.spellsPlayedCount = self.player.spellsPlayedCount tracker.deathrattlesPlayedCount = self.player.deathrattlesPlayedCount if let currentDeck = self.currentDeck { if let deck = RealmHelper.getDeck(with: currentDeck.id) { tracker.recordTrackerMessage = StatsHelper .getDeckManagerRecordLabel(deck: deck, mode: .all) } tracker.playerName = currentDeck.name if !currentDeck.heroId.isEmpty { tracker.playerClassId = currentDeck.heroId } else { tracker.playerClassId = currentDeck.playerClass.defaultHeroCardId } } tracker.graveyard = self.player.graveyard tracker.currentFormat = self.currentFormat tracker.currentGameMode = self.currentGameMode tracker.matchInfo = self.matchInfo tracker.setWindowSizes() var rect: NSRect? if Settings.autoPositionTrackers && self.hearthstoneRunState.isRunning { rect = SizeHelper.playerTrackerFrame() } else { rect = Settings.playerTrackerFrame if rect == nil { let x = WindowManager.screenFrame.width - WindowManager.cardWidth + WindowManager.screenFrame.origin.x rect = NSRect(x: x, y: WindowManager.top + WindowManager.screenFrame.origin.y, width: WindowManager.cardWidth, height: WindowManager.top) } } tracker.hasValidFrame = true self.windowManager.show(controller: tracker, show: true, frame: rect, title: "Player tracker", overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: tracker, show: false) } } } func updateTurnTimer() { DispatchQueue.main.async { [unowned(unsafe) self] in if Settings.showTimer && !self.gameEnded && self.shouldShowGUIElement { var rect: NSRect? if Settings.autoPositionTrackers { rect = SizeHelper.timerHudFrame() } else { rect = Settings.timerHudFrame if rect == nil { rect = SizeHelper.timerHudFrame() } } if let timerHud = self.turnTimer.timerHud { timerHud.hasValidFrame = true self.windowManager.show(controller: timerHud, show: true, frame: rect, title: nil, overlay: self.hearthstoneRunState.isActive) } } else { if let timerHud = self.turnTimer.timerHud { self.windowManager.show(controller: timerHud, show: false) } } } } func updateSecretTracker(cards: [Card]) { DispatchQueue.main.async { [unowned(unsafe) self] in self.windowManager.secretTracker.set(cards: cards) self.windowManager.secretTracker.table?.reloadData() self.updateSecretTracker() } } func updateSecretTracker() { DispatchQueue.main.async { [unowned(unsafe) self] in let tracker = self.windowManager.secretTracker if Settings.showSecretHelper && !self.gameEnded && ((Settings.hideAllWhenGameInBackground && self.hearthstoneRunState.isActive) || !Settings.hideAllWhenGameInBackground) { if tracker.cards.count > 0 { tracker.table?.reloadData() self.windowManager.show(controller: tracker, show: true, frame: SizeHelper.secretTrackerFrame(height: tracker.frameHeight), title: nil, overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: tracker, show: false) } } else { self.windowManager.show(controller: tracker, show: false) } } } func updateCardHud() { DispatchQueue.main.async { [unowned(unsafe) self] in let tracker = self.windowManager.cardHudContainer if Settings.showCardHuds && self.shouldShowGUIElement { if !self.gameEnded { tracker.update(entities: self.opponent.hand, cardCount: self.opponent.handCount) self.windowManager.show(controller: tracker, show: true, frame: SizeHelper.cardHudContainerFrame(), title: nil, overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: tracker, show: false) } } else { self.windowManager.show(controller: tracker, show: false) } } } func updateBoardStateTrackers() { DispatchQueue.main.async { // board damage let board = BoardState(game: self) let playerBoardDamage = self.windowManager.playerBoardDamage let opponentBoardDamage = self.windowManager.opponentBoardDamage var rect: NSRect? if Settings.playerBoardDamage && self.shouldShowGUIElement { if !self.gameEnded { var heroPowerDmg = 0 if let heroPower = board.player.heroPower, self.player.currentMana >= heroPower.cost { heroPowerDmg = heroPower.damage // Garrison Commander = hero power * 2 if board.player.cards.first(where: { $0.cardId == "AT_080"}) != nil { heroPowerDmg *= 2 } } playerBoardDamage.update(attack: board.player.damage + heroPowerDmg) if Settings.autoPositionTrackers { rect = SizeHelper.playerBoardDamageFrame() } else { rect = Settings.playerBoardDamageFrame if rect == nil { rect = SizeHelper.playerBoardDamageFrame() } } playerBoardDamage.hasValidFrame = true self.windowManager.show(controller: playerBoardDamage, show: true, frame: rect, title: nil, overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: playerBoardDamage, show: false) } } else { self.windowManager.show(controller: playerBoardDamage, show: false) } if Settings.opponentBoardDamage && self.shouldShowGUIElement { if !self.gameEnded { var heroPowerDmg = 0 if let heroPower = board.opponent.heroPower { heroPowerDmg = heroPower.damage // Garrison Commander = hero power * 2 if board.opponent.cards.first(where: { $0.cardId == "AT_080"}) != nil { heroPowerDmg *= 2 } } opponentBoardDamage.update(attack: board.opponent.damage + heroPowerDmg) if Settings.autoPositionTrackers { rect = SizeHelper.opponentBoardDamageFrame() } else { rect = Settings.opponentBoardDamageFrame if rect == nil { rect = SizeHelper.opponentBoardDamageFrame() } } opponentBoardDamage.hasValidFrame = true self.windowManager.show(controller: opponentBoardDamage, show: true, frame: SizeHelper.opponentBoardDamageFrame(), title: nil, overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: opponentBoardDamage, show: false) } } else { self.windowManager.show(controller: opponentBoardDamage, show: false) } } } func updateArenaHelper() { DispatchQueue.main.async { let tracker = self.windowManager.arenaHelper if Settings.showArenaHelper && ArenaWatcher.isRunning() && !(Settings.dontTrackWhileSpectating && self.spectator) && self.windowManager.arenaHelper.cards.count == 3 && ((Settings.hideAllWhenGameInBackground && self.hearthstoneRunState.isActive) || !Settings.hideAllWhenGameInBackground ) { tracker.table?.reloadData() self.windowManager.show(controller: tracker, show: true, frame: SizeHelper.arenaHelperFrame(), title: nil, overlay: self.hearthstoneRunState.isActive) } else { self.windowManager.show(controller: tracker, show: false) } } } // MARK: - Vars var startTime: Date? var currentTurn = 0 var lastId = 0 var gameTriggerCount = 0 private var playerDeckAutodetected: Bool = false private var powerLog: [LogLine] = [] func add(powerLog: LogLine) { self.powerLog.append(powerLog) } var playedCards: [PlayedCard] = [] var proposedAttackerEntityId: Int = 0 var proposedDefenderEntityId: Int = 0 var player: Player! var opponent: Player! var currentMode: Mode? = .invalid var previousMode: Mode? = .invalid var gameResult: GameResult = .unknown var wasConceded: Bool = false private var _spectator: Bool = false var spectator: Bool { if self.gameEnded { return false } return _spectator } private var _currentGameMode: GameMode = .none var currentGameMode: GameMode { if spectator { return .spectator } if _currentGameMode == .none { _currentGameMode = GameMode(gameType: currentGameType) } return _currentGameMode } private var _currentGameType: GameType = .gt_unknown var currentGameType: GameType { if _currentGameType != .gt_unknown { return _currentGameType } if self.gameEnded { return .gt_unknown } if let gameType = MirrorHelper.getGameType(), let type = GameType(rawValue: gameType) { _currentGameType = type } return _currentGameType } private var _serverInfo: MirrorGameServerInfo? var serverInfo: MirrorGameServerInfo? { if _serverInfo == nil { _serverInfo = MirrorHelper.getGameServerInfo() } return _serverInfo } var entities: [Int: Entity] = [:] { didSet { // collect all elements that changed let newKeys = entities.keys let changedElements = Array(newKeys.filter { if let oldEntity = oldValue[$0] { return oldEntity != self.entities[$0] } return false }).map { (old: oldValue[$0]!, new: self.entities[$0]!) } self.handleEntitiesChange(changed: changedElements) } } var tmpEntities: [Entity] = [] var knownCardIds: [Int: [String]] = [:] var joustReveals = 0 var lastCardPlayed: Int? var gameEnded = true internal private(set) var currentDeck: PlayingDeck? var currentEntityHasCardId = false var playerUsedHeroPower = false private var hasCoin = false var currentEntityZone: Zone = .invalid var opponentUsedHeroPower = false var wasInProgress = false var setupDone = false var secretsManager: SecretsManager? var proposedAttacker = 0 var proposedDefender = 0 private var defendingEntity: Entity? private var attackingEntity: Entity? private var avengeDeathRattleCount = 0 private var awaitingAvenge = false var isInMenu = true private var handledGameEnd = false var enqueueTime = LogDate(date: Date.distantPast) private var lastTurnStart: [Int] = [0, 0] private var turnQueue: Set<PlayerTurn> = Set() fileprivate var lastGameStartTimestamp: LogDate = LogDate(date: Date.distantPast) private var _matchInfo: MatchInfo? var matchInfo: MatchInfo? { if _matchInfo != nil { return _matchInfo } if !self.gameEnded, let mInfo = MirrorHelper.getMatchInfo() { self._matchInfo = MatchInfo(info: mInfo) logger.info("\(String(describing: self._matchInfo?.localPlayer.name))" + " vs \(String(describing: self._matchInfo?.opposingPlayer.name))" + " matchInfo: \(String(describing: self._matchInfo))") if let minfo = self._matchInfo { self.player.name = minfo.localPlayer.name self.opponent.name = minfo.opposingPlayer.name self.player.id = minfo.localPlayer.playerId self.opponent.id = minfo.opposingPlayer.playerId self._currentGameType = minfo.gameType self.currentFormat = minfo.formatType } // request a mirror read so we have this data at the end of the game _ = self.serverInfo } return _matchInfo } var arenaInfo: ArenaInfo? { if let _arenaInfo = MirrorHelper.getArenaDeck() { return ArenaInfo(info: _arenaInfo) } return nil } var brawlInfo: BrawlInfo? { if let _brawlInfo = MirrorHelper.getBrawlInfo() { return BrawlInfo(info: _brawlInfo) } return nil } var playerEntity: Entity? { return entities.map { $0.1 }.first { $0[.player_id] == self.player.id } } var opponentEntity: Entity? { return entities.map { $0.1 }.first { $0.has(tag: .player_id) && !$0.isPlayer(eventHandler: self) } } var gameEntity: Entity? { return entities.map { $0.1 }.first { $0.name == "GameEntity" } } var isMinionInPlay: Bool { return entities.map { $0.1 }.first { $0.isInPlay && $0.isMinion } != nil } var isOpponentMinionInPlay: Bool { return entities.map { $0.1 } .first { $0.isInPlay && $0.isMinion && $0.isControlled(by: self.opponent.id) } != nil } var opponentMinionCount: Int { return entities.map { $0.1 } .filter { $0.isInPlay && $0.isMinion && $0.isControlled(by: self.opponent.id) }.count } var playerMinionCount: Int { return entities.map { $0.1 } .filter { $0.isInPlay && $0.isMinion && $0.isControlled(by: self.player.id) }.count } var opponentHandCount: Int { return entities.map { $0.1 } .filter { $0.isInHand && $0.isControlled(by: self.opponent.id) }.count } private(set) var currentFormat = Format(formatType: FormatType.ft_unknown) // MARK: - Lifecycle private var allTrackerUpdateObserver: NSObjectProtocol? init(hearthstoneRunState: HearthstoneRunState) { self.hearthstoneRunState = hearthstoneRunState turnTimer = TurnTimer(gui: windowManager.timerHud) super.init() player = Player(local: true, game: self) opponent = Player(local: false, game: self) secretsManager = SecretsManager(game: self) secretsManager?.onChanged = { [weak self] cards in self?.updateSecretTracker(cards: cards) } windowManager.startManager() windowManager.playerTracker.window?.delegate = self windowManager.opponentTracker.window?.delegate = self let center = NotificationCenter.default // events that should update the player tracker let playerTrackerUpdateEvents = [Settings.show_player_tracker, Settings.rarity_colors, Settings.remove_cards_from_deck, Settings.highlight_last_drawn, Settings.highlight_cards_in_hand, Settings.highlight_discarded, Settings.show_player_get, Settings.player_draw_chance, Settings.player_card_count, Settings.player_cthun_frame, Settings.player_yogg_frame, Settings.player_deathrattle_frame, Settings.show_win_loss_ratio, Settings.player_in_hand_color, Settings.show_deck_name, Settings.player_graveyard_details_frame, Settings.player_graveyard_frame] // events that should update the opponent's tracker let opponentTrackerUpdateEvents = [Settings.show_opponent_tracker, Settings.opponent_card_count, Settings.opponent_draw_chance, Settings.opponent_cthun_frame, Settings.opponent_yogg_frame, Settings.opponent_deathrattle_frame, Settings.show_opponent_class, Settings.opponent_graveyard_frame, Settings.opponent_graveyard_details_frame] // events that should update all trackers let allTrackerUpdateEvents = [Settings.rarity_colors, Events.reload_decks, Settings.window_locked, Settings.auto_position_trackers, Events.space_changed, Events.hearthstone_closed, Events.hearthstone_running, Events.hearthstone_active, Events.hearthstone_deactived, Settings.can_join_fullscreen, Settings.hide_all_trackers_when_not_in_game, Settings.hide_all_trackers_when_game_in_background, Settings.card_size, Settings.theme_token] for option in playerTrackerUpdateEvents { center.addObserver(self, selector: #selector(updatePlayerTracker), name: NSNotification.Name(rawValue: option), object: nil) } for option in opponentTrackerUpdateEvents { center.addObserver(self, selector: #selector(updateOpponentTracker), name: NSNotification.Name(rawValue: option), object: nil) } for option in allTrackerUpdateEvents { allTrackerUpdateObserver = center.addObserver(forName: NSNotification.Name(rawValue: option), object: nil, queue: OperationQueue.main, using: _updateTrackers) } // start gui updater thread _queue.async { while true { if self.guiNeedsUpdate { self.guiNeedsUpdate = false self._updateTrackers() self.guiUpdateResets = false } Thread.sleep(forTimeInterval: Game.guiUpdateDelay) } } } func reset() { logger.verbose("Reseting Game") currentTurn = 0 playedCards.removeAll() self.gameResult = .unknown self.wasConceded = false lastId = 0 gameTriggerCount = 0 _matchInfo = nil currentFormat = Format(formatType: FormatType.ft_unknown) _currentGameType = .gt_unknown _currentGameMode = .none _serverInfo = nil entities.removeAll() tmpEntities.removeAll() knownCardIds.removeAll() joustReveals = 0 lastCardPlayed = nil currentEntityHasCardId = false playerUsedHeroPower = false hasCoin = false currentEntityZone = .invalid opponentUsedHeroPower = false setupDone = false secretsManager?.reset() proposedAttacker = 0 proposedDefender = 0 defendingEntity = nil attackingEntity = nil avengeDeathRattleCount = 0 awaitingAvenge = false lastTurnStart = [0, 0] player.reset() if let currentdeck = self.currentDeck { player.playerClass = currentdeck.playerClass } opponent.reset() updateSecretTracker(cards: []) windowManager.hideGameTrackers() _spectator = false } func set(activeDeckId: String?, autoDetected: Bool) { Settings.activeDeck = activeDeckId self.playerDeckAutodetected = autoDetected if let id = activeDeckId, let deck = RealmHelper.getDeck(with: id) { set(activeDeck: deck) } else { currentDeck = nil player.playerClass = nil updateTrackers(reset: true) } } private func set(activeDeck deck: Deck) { var cards: [Card] = [] for deckCard in deck.cards { if let card = Cards.by(cardId: deckCard.id) { card.count = deckCard.count cards.append(card) } } currentDeck = PlayingDeck(id: deck.deckId, name: deck.name, hsDeckId: deck.hsDeckId.value, playerClass: deck.playerClass, heroId: deck.heroId, cards: cards.sortCardList(), isArena: deck.isArena ) player.playerClass = currentDeck?.playerClass updateTrackers(reset: true) } func removeActiveDeck() { currentDeck = nil Settings.activeDeck = nil updateTrackers(reset: true) } // MARK: - game state private var lastGameStart = Date.distantPast func gameStart(at timestamp: LogDate) { logger.info("currentGameMode: \(currentGameMode), isInMenu: \(isInMenu), " + "handledGameEnd: \(handledGameEnd), " + "lastGameStartTimestamp: \(lastGameStartTimestamp), " + "timestamp: \(timestamp)") if currentGameMode == .practice && !isInMenu && !handledGameEnd && lastGameStartTimestamp > LogDate(date: Date.distantPast) && timestamp > lastGameStartTimestamp { adventureRestart() return } lastGameStartTimestamp = timestamp if lastGameStart > Date.distantPast && (abs(lastGameStart.timeIntervalSinceNow) < 5) { // game already started return } ImageUtils.clearCache() reset() lastGameStart = Date() // remove every line before _last_ create game if let index = self.powerLog.reversed().index(where: { $0.line.contains("CREATE_GAME") }) { self.powerLog = self.powerLog.reversed()[...index].reversed() as [LogLine] } else { self.powerLog = [] } gameEnded = false isInMenu = false handledGameEnd = false logger.info("----- Game Started -----") AppHealth.instance.setHearthstoneGameRunning(flag: true) NotificationManager.showNotification(type: .gameStart) if Settings.showTimer { self.turnTimer.start() } // update spectator information _spectator = MirrorHelper.isSpectating() ?? false updateTrackers(reset: true) self.startTime = Date() } private func adventureRestart() { // The game end is not logged in PowerTaskList logger.info("Adventure was restarted. Simulating game end.") concede() loss() gameEnd() inMenu() } func gameEnd() { logger.info("----- Game End -----") AppHealth.instance.setHearthstoneGameRunning(flag: false) handleEndGame() secretsManager?.reset() updateTrackers(reset: true) windowManager.hideGameTrackers() turnTimer.stop() } func inMenu() { if isInMenu { return } logger.verbose("Game is now in menu") turnTimer.stop() isInMenu = true } private func generateEndgameStatistics() -> InternalGameStats? { let result = InternalGameStats() result.startTime = self.startTime ?? Date() result.endTime = Date() result.playerHero = currentDeck?.playerClass ?? player.playerClass ?? .neutral result.opponentHero = opponent.playerClass ?? .neutral result.wasConceded = self.wasConceded result.result = self.gameResult if let build = BuildDates.latestBuild { result.hearthstoneBuild = build.build } result.season = Database.currentSeason if let name = self.player.name { result.playerName = name } if let _player = self.entities.map({ $0.1 }).first(where: { $0.isPlayer(eventHandler: self) }) { result.coin = !_player.has(tag: .first_player) } if let name = self.opponent.name { result.opponentName = name } else if result.opponentHero != .neutral { result.opponentName = result.opponentHero.rawValue } result.turns = self.turnNumber() result.gameMode = self.currentGameMode result.format = self.currentFormat if let matchInfo = self.matchInfo, self.currentGameMode == .ranked { let wild = self.currentFormat == .wild result.rank = wild ? matchInfo.localPlayer.wildRank : matchInfo.localPlayer.standardRank result.opponentRank = wild ? matchInfo.opposingPlayer.wildRank : matchInfo.opposingPlayer.standardRank result.legendRank = wild ? matchInfo.localPlayer.wildLegendRank : matchInfo.localPlayer.standardLegendRank result.opponentLegendRank = wild ? matchInfo.opposingPlayer.wildLegendRank : matchInfo.opposingPlayer.standardLegendRank result.stars = wild ? matchInfo.localPlayer.wildStars : matchInfo.localPlayer.standardStars } else if self.currentGameMode == .arena { result.arenaLosses = self.arenaInfo?.losses ?? 0 result.arenaWins = self.arenaInfo?.wins ?? 0 } else if let brawlInfo = self.brawlInfo, self.currentGameMode == .brawl { result.brawlWins = brawlInfo.wins result.brawlLosses = brawlInfo.losses } result.gameType = self.currentGameType if let serverInfo = self.serverInfo { result.serverInfo = ServerInfo(info: serverInfo) } result.playerCardbackId = self.matchInfo?.localPlayer.cardBackId ?? 0 result.opponentCardbackId = self.matchInfo?.opposingPlayer.cardBackId ?? 0 result.friendlyPlayerId = self.matchInfo?.localPlayer.playerId ?? 0 result.scenarioId = self.matchInfo?.missionId ?? 0 result.brawlSeasonId = self.matchInfo?.brawlSeasonId ?? 0 result.rankedSeasonId = self.matchInfo?.rankedSeasonId ?? 0 result.hsDeckId = self.currentDeck?.hsDeckId self.player.revealedCards.filter({ $0.collectible }).forEach({ result.revealedCards.append($0) }) self.opponent.opponentCardList.filter({ !$0.isCreated }).forEach({ result.opponentCards.append($0) }) return result } func handleEndGame() { if self.handledGameEnd { logger.warning("HandleGameEnd was already called.") return } guard let currentGameStats = generateEndgameStatistics() else { logger.error("Error: could not generate endgame statistics") return } logger.verbose("currentGameStats: \(currentGameStats), " + "handledGameEnd: \(self.handledGameEnd)") self.handledGameEnd = true if self.currentGameMode == .spectator && currentGameStats.result == .none { logger.info("Game was spectator mode without a game result." + " Probably exited spectator mode early.") return } /*if Settings.promptNotes { let message = NSLocalizedString("Do you want to add some notes for this game ?", comment: "") let frame = NSRect(x: 0, y: 0, width: 300, height: 80) let input = NSTextView(frame: frame) if NSAlert.show(style: .informational, message: message, accessoryView: input, forceFront: true) { currentGameStats.note = input.string ?? "" } }*/ logger.verbose("End game: \(currentGameStats)") let stats = currentGameStats.toGameStats() if let currentDeck = self.currentDeck { if let deck = RealmHelper.getDeck(with: currentDeck.id) { RealmHelper.addStatistics(to: deck, stats: stats) if Settings.autoArchiveArenaDeck && self.currentGameMode == .arena && deck.isArena && deck.arenaFinished() { RealmHelper.set(deck: deck, active: false) } } } self.syncStats(logLines: self.powerLog, stats: currentGameStats) } private var logContainsGoldRewardState: Bool { return powerLog.filter({ $0.line.contains("tag=GOLD_REWARD_STATE value=1") }).count == 2 } private var logContainsStateComplete: Bool { return powerLog.any({ $0.line.contains("tag=STATE value=COMPLETE") }) } private func syncStats(logLines: [LogLine], stats: InternalGameStats) { guard currentGameMode != .practice && currentGameMode != .none && currentGameMode != .spectator else { logger.info("Game was in \(currentGameMode), don't send to third-party") return } if TrackOBotAPI.isLogged() && Settings.trackobotSynchronizeMatches { do { try TrackOBotAPI.postMatch(stat: stats, cards: playedCards) } catch { logger.error("Track-o-Bot error : \(error)") } } if Settings.hsReplaySynchronizeMatches && ( (stats.gameMode == .ranked && Settings.hsReplayUploadRankedMatches) || (stats.gameMode == .casual && Settings.hsReplayUploadCasualMatches) || (stats.gameMode == .arena && Settings.hsReplayUploadArenaMatches) || (stats.gameMode == .brawl && Settings.hsReplayUploadBrawlMatches) || (stats.gameMode == .practice && Settings.hsReplayUploadAdventureMatches) || (stats.gameMode == .friendly && Settings.hsReplayUploadFriendlyMatches) || (stats.gameMode == .spectator && Settings.hsReplayUploadFriendlyMatches)) { let (uploadMetaData, statId) = UploadMetaData.generate(stats: stats, deck: self.playerDeckAutodetected && self.currentDeck != nil ? self.currentDeck : nil ) HSReplayAPI.getUploadToken { _ in LogUploader.upload(logLines: logLines, metaData: (uploadMetaData, statId)) { result in if case UploadResult.successful(let replayId) = result { NotificationManager.showNotification(type: .hsReplayPush(replayId: replayId)) NotificationCenter.default .post(name: Notification.Name(rawValue: Events.reload_decks), object: nil) } else if case UploadResult.failed(let error) = result { NotificationManager.showNotification(type: .hsReplayUploadFailed(error: error)) } } } } } func turnNumber() -> Int { if !isMulliganDone() { return 0 } if let gameEntity = self.gameEntity { return (gameEntity[.turn] + 1) / 2 } return 0 } func turnsInPlayChange(entity: Entity, turn: Int) { guard let opponentEntity = opponentEntity else { return } if entity.isHero { let player: PlayerType = opponentEntity.isCurrentPlayer ? .opponent : .player if lastTurnStart[player.rawValue] >= turn { return } lastTurnStart[player.rawValue] = turn turnStart(player: player, turn: turn) return } secretsManager?.handleTurnsInPlayChange(entity: entity, turn: turn) } func turnStart(player: PlayerType, turn: Int) { if !isMulliganDone() { logger.info("--- Mulligan ---") } var turnNumber = turn if turnNumber == 0 { turnNumber += 1 } turnQueue.insert(PlayerTurn(player: player, turn: turn)) DispatchQueue.global().async { while !self.isMulliganDone() { Thread.sleep(forTimeInterval: 0.1) } while let playerTurn = self.turnQueue.popFirst() { self.handleTurnStart(playerTurn: playerTurn) } } } func handleTurnStart(playerTurn: PlayerTurn) { let player = playerTurn.player if Settings.fullGameLog { logger.info("Turn \(playerTurn.turn) start for player \(player) ") } if player == .player { handleThaurissanCostReduction() } if turnQueue.count > 0 { return } var timeout = -1 if player == .player && playerEntity!.has(tag: .timeout) { timeout = playerEntity![.timeout] } else if player == .opponent && opponentEntity!.has(tag: .timeout) { timeout = opponentEntity![.timeout] } turnTimer.startTurn(for: player, timeout: timeout) if player == .player && !isInMenu { NotificationManager.showNotification(type: .turnStart) } updateTrackers() } func concede() { logger.info("Game has been conceded : (") self.wasConceded = true } func win() { logger.info("You win ¯\\_(ツ) _ / ¯") self.gameResult = .win if self.wasConceded { NotificationManager.showNotification(type: .opponentConcede) } } func loss() { logger.info("You lose : (") self.gameResult = .loss } func tied() { logger.info("You lose : ( / game tied: (") self.gameResult = .draw } func isMulliganDone() -> Bool { let player = entities.map { $0.1 }.first { $0.isPlayer(eventHandler: self) } let opponent = entities.map { $0.1 } .first { $0.has(tag: .player_id) && !$0.isPlayer(eventHandler: self) } if let player = player, let opponent = opponent { return player[.mulligan_state] == Mulligan.done.rawValue && opponent[.mulligan_state] == Mulligan.done.rawValue } return false } func handleThaurissanCostReduction() { let thaurissans = opponent.board.filter({ $0.cardId == CardIds.Collectible.Neutral.EmperorThaurissan && !$0.has(tag: .silenced) }) if thaurissans.isEmpty { return } for impFavor in opponent.board .filter({ $0.cardId == CardIds.NonCollectible.Neutral.EmperorThaurissan_ImperialFavorEnchantment }) { if let entity = entities[impFavor[.attached]] { entity.info.costReduction += thaurissans.count } } } // MARK: - player func set(playerHero cardId: String) { if let card = Cards.hero(byId: cardId) { player.playerClass = card.playerClass player.playerClassId = cardId if Settings.fullGameLog { logger.info("Player class is \(card) ") } } } func set(playerName name: String) { player.name = name } func playerGet(entity: Entity, cardId: String?, turn: Int) { if cardId.isBlank { return } player.createInHand(entity: entity, turn: turn) updateTrackers() } func playerBackToHand(entity: Entity, cardId: String?, turn: Int) { if cardId.isBlank { return } updateTrackers() player.boardToHand(entity: entity, turn: turn) } func playerPlayToDeck(entity: Entity, cardId: String?, turn: Int) { if cardId.isBlank { return } player.boardToDeck(entity: entity, turn: turn) updateTrackers() } func playerPlay(entity: Entity, cardId: String?, turn: Int) { if cardId.isBlank { return } player.play(entity: entity, turn: turn) if let cardId = cardId, !cardId.isEmpty { playedCards.append(PlayedCard(player: .player, cardId: cardId, turn: turn)) } if entity.has(tag: .ritual) { // if this entity has the RITUAL tag, it will trigger some C'Thun change // we wait 300ms so the proxy have the time to be updated let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(300) DispatchQueue.main.asyncAfter(deadline: when) { [weak self] in self?.updateTrackers() } } secretsManager?.handleCardPlayed(entity: entity) updateTrackers() } func playerHandDiscard(entity: Entity, cardId: String?, turn: Int) { if cardId.isBlank { return } player.handDiscard(entity: entity, turn: turn) updateTrackers() } func playerSecretPlayed(entity: Entity, cardId: String?, turn: Int, fromZone: Zone) { if cardId.isBlank { return } if !entity.isSecret { if entity.isQuest { player.questPlayedFromHand(entity: entity, turn: turn) } return } switch fromZone { case .deck: player.secretPlayedFromDeck(entity: entity, turn: turn) case .hand: player.secretPlayedFromHand(entity: entity, turn: turn) secretsManager?.handleCardPlayed(entity: entity) default: player.createInSecret(entity: entity, turn: turn) return } updateTrackers() } func playerMulligan(entity: Entity, cardId: String?) { if cardId.isBlank { return } player.mulligan(entity: entity) updateTrackers() } func playerDraw(entity: Entity, cardId: String?, turn: Int) { if cardId.isBlank { return } if cardId == CardIds.NonCollectible.Neutral.TheCoin { playerGet(entity: entity, cardId: cardId, turn: turn) } else { player.draw(entity: entity, turn: turn) updateTrackers() } } func playerRemoveFromDeck(entity: Entity, turn: Int) { player.removeFromDeck(entity: entity, turn: turn) updateTrackers() } func playerDeckDiscard(entity: Entity, cardId: String?, turn: Int) { player.deckDiscard(entity: entity, turn: turn) updateTrackers() } func playerDeckToPlay(entity: Entity, cardId: String?, turn: Int) { player.deckToPlay(entity: entity, turn: turn) updateTrackers() } func playerPlayToGraveyard(entity: Entity, cardId: String?, turn: Int) { player.playToGraveyard(entity: entity, cardId: cardId, turn: turn) updateTrackers() } func playerJoust(entity: Entity, cardId: String?, turn: Int) { player.joustReveal(entity: entity, turn: turn) updateTrackers() } func playerGetToDeck(entity: Entity, cardId: String?, turn: Int) { player.createInDeck(entity: entity, turn: turn) updateTrackers() } func playerFatigue(value: Int) { if Settings.fullGameLog { logger.info("Player get \(value) fatigue") } player.fatigue = value updateTrackers() } func playerCreateInPlay(entity: Entity, cardId: String?, turn: Int) { player.createInPlay(entity: entity, turn: turn) } func playerStolen(entity: Entity, cardId: String?, turn: Int) { player.stolenByOpponent(entity: entity, turn: turn) opponent.stolenFromOpponent(entity: entity, turn: turn) if entity.isSecret { var heroClass: CardClass? var className = "\(entity[.class])" if !className.isBlank { className = className.lowercased() heroClass = CardClass(rawValue: className) if heroClass == .none { if let playerClass = opponent.playerClass { heroClass = playerClass } } } else { if let playerClass = opponent.playerClass { heroClass = playerClass } } guard heroClass != nil else { return } secretsManager?.newSecret(entity: entity) } } func playerRemoveFromPlay(entity: Entity, turn: Int) { player.removeFromPlay(entity: entity, turn: turn) } func playerCreateInSetAside(entity: Entity, turn: Int) { player.createInSetAside(entity: entity, turn: turn) } func playerHeroPower(cardId: String, turn: Int) { player.heroPower(turn: turn) if Settings.fullGameLog { logger.info("Player Hero Power \(cardId) \(turn) ") } secretsManager?.handleHeroPower() } // MARK: - Opponent actions func set(opponentHero cardId: String) { if let card = Cards.hero(byId: cardId) { opponent.playerClass = card.playerClass opponent.playerClassId = cardId updateTrackers() if Settings.fullGameLog { logger.info("Opponent class is \(card) ") } } } func set(opponentName name: String) { opponent.name = name updateTrackers() } func opponentGet(entity: Entity, turn: Int, id: Int) { if !isMulliganDone() && entity[.zone_position] == 5 { entity.cardId = CardIds.NonCollectible.Neutral.TheCoin } opponent.createInHand(entity: entity, turn: turn) updateTrackers() } func opponentPlayToHand(entity: Entity, cardId: String?, turn: Int, id: Int) { opponent.boardToHand(entity: entity, turn: turn) updateTrackers() } func opponentPlayToDeck(entity: Entity, cardId: String?, turn: Int) { opponent.boardToDeck(entity: entity, turn: turn) updateTrackers() } func opponentPlay(entity: Entity, cardId: String?, from: Int, turn: Int) { opponent.play(entity: entity, turn: turn) if let cardId = cardId, !cardId.isEmpty { playedCards.append(PlayedCard(player: .opponent, cardId: cardId, turn: turn)) } if entity.has(tag: .ritual) { // if this entity has the RITUAL tag, it will trigger some C'Thun change // we wait 300ms so the proxy have the time to be updated let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(300) DispatchQueue.main.asyncAfter(deadline: when) { [weak self] in self?.updateTrackers() } } updateTrackers() } func opponentHandDiscard(entity: Entity, cardId: String?, from: Int, turn: Int) { opponent.handDiscard(entity: entity, turn: turn) updateTrackers() } func opponentSecretPlayed(entity: Entity, cardId: String?, from: Int, turn: Int, fromZone: Zone, otherId: Int) { if !entity.isSecret { if entity.isQuest { opponent.questPlayedFromHand(entity: entity, turn: turn) } return } switch fromZone { case .deck: opponent.secretPlayedFromDeck(entity: entity, turn: turn) case .hand: opponent.secretPlayedFromHand(entity: entity, turn: turn) default: opponent.createInSecret(entity: entity, turn: turn) } var heroClass: CardClass? let className = "\(entity[.class])".lowercased() if let tagClass = TagClass(rawValue: entity[.class]) { heroClass = tagClass.cardClassValue } else if let _heroClass = CardClass(rawValue: className), !className.isBlank { heroClass = _heroClass } else if let playerClass = opponent.playerClass { heroClass = playerClass } if Settings.fullGameLog { logger.info("Secret played by \(entity[.class])" + " -> \(String(describing: heroClass)) " + "-> \(String(describing: opponent.playerClass))") } if heroClass != nil { secretsManager?.newSecret(entity: entity) } updateTrackers() } func opponentMulligan(entity: Entity, from: Int) { opponent.mulligan(entity: entity) updateTrackers() } func opponentDraw(entity: Entity, turn: Int) { opponent.draw(entity: entity, turn: turn) updateTrackers() } func opponentRemoveFromDeck(entity: Entity, turn: Int) { opponent.removeFromDeck(entity: entity, turn: turn) updateTrackers() } func opponentDeckDiscard(entity: Entity, cardId: String?, turn: Int) { opponent.deckDiscard(entity: entity, turn: turn) updateTrackers() } func opponentDeckToPlay(entity: Entity, cardId: String?, turn: Int) { opponent.deckToPlay(entity: entity, turn: turn) updateTrackers() } func opponentPlayToGraveyard(entity: Entity, cardId: String?, turn: Int, playersTurn: Bool) { opponent.playToGraveyard(entity: entity, cardId: cardId, turn: turn) if playersTurn && entity.isMinion { opponentMinionDeath(entity: entity, turn: turn) } updateTrackers() } func opponentJoust(entity: Entity, cardId: String?, turn: Int) { opponent.joustReveal(entity: entity, turn: turn) updateTrackers() } func opponentGetToDeck(entity: Entity, turn: Int) { opponent.createInDeck(entity: entity, turn: turn) updateTrackers() } func opponentSecretTrigger(entity: Entity, cardId: String?, turn: Int, otherId: Int) { if !entity.isSecret { return } opponent.secretTriggered(entity: entity, turn: turn) secretsManager?.removeSecret(entity: entity) } func opponentFatigue(value: Int) { opponent.fatigue = value updateTrackers() } func opponentCreateInPlay(entity: Entity, cardId: String?, turn: Int) { opponent.createInPlay(entity: entity, turn: turn) } func opponentStolen(entity: Entity, cardId: String?, turn: Int) { opponent.stolenByOpponent(entity: entity, turn: turn) player.stolenFromOpponent(entity: entity, turn: turn) if entity.isSecret { secretsManager?.removeSecret(entity: entity) } } func opponentRemoveFromPlay(entity: Entity, turn: Int) { player.removeFromPlay(entity: entity, turn: turn) } func opponentCreateInSetAside(entity: Entity, turn: Int) { opponent.createInSetAside(entity: entity, turn: turn) } func opponentHeroPower(cardId: String, turn: Int) { opponent.heroPower(turn: turn) if Settings.fullGameLog { logger.info("Opponent Hero Power \(cardId) \(turn) ") } updateTrackers() } // MARK: - Game actions func defending(entity: Entity?) { self.defendingEntity = entity if let attackingEntity = self.attackingEntity, let defendingEntity = self.defendingEntity, let entity = entity { if entity.isControlled(by: opponent.id) { secretsManager?.handleAttack(attacker: attackingEntity, defender: defendingEntity) } } } func attacking(entity: Entity?) { self.attackingEntity = entity if let attackingEntity = self.attackingEntity, let defendingEntity = self.defendingEntity, let entity = entity { if entity.isControlled(by: player.id) { secretsManager?.handleAttack(attacker: attackingEntity, defender: defendingEntity) } } } func playerMinionPlayed() { secretsManager?.handleMinionPlayed() } func opponentMinionDeath(entity: Entity, turn: Int) { secretsManager?.handleMinionDeath(entity: entity) } func opponentDamage(entity: Entity) { secretsManager?.handleOpponentDamage(entity: entity) } func opponentTurnStart(entity: Entity) { } // MARK: - Arena func setArenaOptions(cards: [Card]) { self.windowManager.arenaHelper.set(cards: cards) self.updateArenaHelper() } } // MARK: NSWindowDelegate functions extension Game: NSWindowDelegate { func windowDidResize(_ notification: Notification) { guard let window = notification.object as? NSWindow else { return } if window == self.windowManager.playerTracker.window { self.updatePlayerTracker(reset: false) onWindowMove(tracker: self.windowManager.playerTracker) } else if window == self.windowManager.opponentTracker.window { self.updateOpponentTracker(reset: false) onWindowMove(tracker: self.windowManager.opponentTracker) } } func windowDidMove(_ notification: Notification) { guard let window = notification.object as? NSWindow else { return } if window == self.windowManager.playerTracker.window { onWindowMove(tracker: self.windowManager.playerTracker) } else if window == self.windowManager.opponentTracker.window { onWindowMove(tracker: self.windowManager.opponentTracker) } } private func onWindowMove(tracker: Tracker) { if !tracker.isWindowLoaded || !tracker.hasValidFrame {return} if tracker.playerType == .player { Settings.playerTrackerFrame = tracker.window?.frame } else { Settings.opponentTrackerFrame = tracker.window?.frame } } }
mit
9bbc1a07c8f5bd4df4b79a71b1aa482b
34.11131
170
0.591537
4.816838
false
false
false
false
xu6148152/binea_project_for_ios
RatingControl/RatingControl/MealViewController.swift
1
3696
// // ViewController.swift // RatingControl // // Created by Binea Xu on 10/10/15. // Copyright © 2015 Binea Xu. All rights reserved. // import UIKit class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: Properties @IBOutlet weak var mTextField: UITextField! @IBOutlet weak var mealNameLabel: UILabel! var meal = Meal?() @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var ratingControl: RatingControl! override func viewDidLoad() { super.viewDidLoad() mTextField.delegate = self if let meal = meal { navigationItem.title = meal.name mTextField.text = meal.name photoImageView.image = meal.photo ratingControl.rating = meal.rating } checkValidName() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if saveButton == sender as! UIBarButtonItem { let name = mTextField.text ?? "" let photo = photoImageView.image let rating = ratingControl.rating meal = Meal(name: name, photo: photo, rating: rating) } } // MARK: Action @IBAction func setDefaultLabelText(sender: UIButton) { mealNameLabel.text = "Default Text" } @IBAction func editingChanged(sender: UITextField) { mealNameLabel.text = sender.text checkValidName() } @IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) { mTextField.resignFirstResponder() let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .PhotoLibrary imagePickerController.delegate = self presentViewController(imagePickerController, animated: true, completion: nil) } @IBAction func cancel(sender: UIBarButtonItem) { if presentingViewController is UINavigationController { dismissViewControllerAnimated(true, completion: nil) }else { navigationController?.popViewControllerAnimated(true) } } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { mTextField.resignFirstResponder() return true } func textFieldDidEndEditing(textField: UITextField) { checkValidName() mealNameLabel.text = textField.text } func textFieldDidBeginEditing(textField: UITextField) { saveButton.enabled = false } // MARK: UIImagePickerController delegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage photoImageView.image = selectedImage dismissViewControllerAnimated(true, completion: nil) } func checkValidName() { let text = mTextField.text ?? "" saveButton.enabled = !text.isEmpty } }
mit
05579551b5b255abfd0e19fbb0828d14
27.867188
130
0.646549
6.11755
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/common/base/GsExtensionString.swift
1
1946
// // GsExtensionString.swift // GitHubStar // // Created by midoks on 16/4/3. // Copyright © 2016年 midoks. All rights reserved. // import UIKit extension String { func textSize(font: UIFont, constrainedToSize size:CGSize) -> CGSize { let option = NSStringDrawingOptions.usesLineFragmentOrigin let attributes = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) let stringRect = self.boundingRect(with: size, options: option, attributes: attributes as? [String : AnyObject], context: nil) return stringRect.size } func textSize(font:UIFont, width:CGFloat) ->CGFloat { let option = NSStringDrawingOptions.usesLineFragmentOrigin let attributes = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) let rect = self.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: option,attributes: attributes as? [String : AnyObject], context: nil) return rect.size.height } func textSizeWithFont(font: UIFont, constrainedToSize size:CGSize) -> CGSize { var textSize:CGSize! if size.equalTo(CGSize.zero) { let attributes = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) textSize = self.size(attributes: attributes as? [String : AnyObject]) } else { //NSStringDrawingOptions.UsesLineFragmentOrigin || NSStringDrawingOptions.UsesFontLeading let option = NSStringDrawingOptions.usesLineFragmentOrigin let attributes = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) let stringRect = self.boundingRect(with: size, options: option, attributes: attributes as? [String : AnyObject], context: nil) textSize = stringRect.size } return textSize } }
apache-2.0
431323fdfea0e2d4c2177847c9130772
43.159091
184
0.671642
5.294278
false
false
false
false
kaideyi/KDYSample
SlideTabBar/SlideTabBar/SlideTabBarController/SlideTabController.swift
1
15831
// // SlideTabController.swift // SlideTabBar // // Created by mac on 17/2/20. // Copyright © 2017年 kaideyi.com. All rights reserved. // import UIKit protocol SlideConcig { } /// 滑块控制器 open class SlideTabController: UIViewController { public enum SlideTabBarStyle { case `default`(UIColor?, UIColor?, CGFloat?, CGFloat?, CGFloat?) case underline(UIColor?, CGFloat?, CGFloat?, Bool) case titleScale case coverTitle } // MARK: - Properties /// 滑动的类型 var style: SlideTabBarStyle? static let cellIdentifier = "slideCell" /// 标题字体大小 var titleFont: UIFont = .systemFont(ofSize: 15) /// 标题默认颜色 var titleNormalColor = UIColor.gray /// 标题选中颜色 var titleSelectColor = UIColor.gray /// 标题高度 public var titleHeight: CGFloat = 44.0 /// 标题宽度 var titleWidth: CGFloat = 0.0 /// 标题间距 public var titleMargin: CGFloat = 20.0 /// 下划线宽度 var underlineWidth: CGFloat = 0.0 /// 下划线高度 var underlineHieght: CGFloat = 3.0 /// 下划线颜色 var underlineColor: UIColor = .red /// 下划线是否与title等宽 var isEqualTitle: Bool = true /// 选中的下标 private var selectIndex: Int = 0 /// 最后一次的偏移量 var lastXOffset: CGFloat = 0 let kFrameWidth = UIScreen.main.bounds.width let kFrameHeight = UIScreen.main.bounds.height /// 标题的总数组 lazy var titleLabelsArray: NSMutableArray = { let array = NSMutableArray.init() return array }() /// 标题的总宽度 var titleWidthsArray: NSMutableArray = [] /// 全部的内容视图 lazy var contentBgView: UIView = { let contentBgView = UIView() contentBgView.frame = CGRect(x: 0, y: 64, width: self.view.width, height: self.view.height) self.view.addSubview(contentBgView) return contentBgView }() /// 顶部标题滚动视图 lazy var titleScrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 0, width: self.view.width, height: self.titleHeight) scrollView.backgroundColor = UIColor(white: 1, alpha: 0.6) scrollView.scrollsToTop = false scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false self.contentBgView.addSubview(scrollView) return scrollView }() /// 内容视图 lazy var collectionView: UICollectionView = { let layout = SlideFlowLayout() let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) let yPos = self.titleScrollView.frame.maxY let height = self.contentBgView.height - self.titleScrollView.height collectionView.frame = CGRect(x: 0, y: yPos, width: self.view.width, height: height) collectionView.scrollsToTop = false collectionView.bounces = false collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: cellIdentifier) collectionView.dataSource = self collectionView.delegate = self self.contentBgView.addSubview(collectionView) return collectionView }() /// 下划线视图 lazy var underlineView: UIView = { let underlineView = UIView() underlineView.backgroundColor = self.underlineColor self.titleScrollView.addSubview(underlineView) return underlineView }() // MARK: - Life Cycle override open func viewDidLoad() { super.viewDidLoad() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.automaticallyAdjustsScrollViewInsets = false collectionView.reloadData() setupTitleWidths() setupTitlesArray() } // MARK: - Public Methods /** * 设置顶部标题样式 */ public func setSlideSytle(_ slideStyle: SlideTabBarStyle) { style = slideStyle switch slideStyle { case .default(let color, let selColor, let font, let width, let height): setTitleDefaultStyle(color, selColor, font, width, height) case .underline(let color, let width, let height, let isEqual): setTitleUnderlineStyle(color, width, height, isEqual) case .titleScale: break case .coverTitle: break } } func setTitleDefaultStyle(_ norColor: UIColor?, _ selColor: UIColor?, _ font: CGFloat?, _ width: CGFloat?, _ height: CGFloat?) { if let norColor = norColor { titleNormalColor = norColor } if let selColor = selColor { titleSelectColor = selColor } if let font = font { titleFont = UIFont.systemFont(ofSize: font) } if let width = width { titleWidth = width } if let height = height { titleHeight = height } } func setTitleUnderlineStyle(_ color: UIColor?, _ width: CGFloat?, _ height: CGFloat?, _ isEqual: Bool = true) { if let color = color { underlineColor = color } if let height = height { underlineHieght = height } if !isEqual { // 不与title宽度相等 isEqualTitle = isEqual if let width = width { underlineWidth = width } } } func setTitleScaleStyle() { } func setTitleCoverStyle() { } // MARK: - Private Methods /** * 根据label字符串计算宽 */ private func getLableWidth(labelStr: String, font: UIFont) -> CGFloat { let statusLabelText = labelStr as NSString let size = CGSize(width: 800, height: 0) let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String: AnyObject], context:nil).size return strSize.width } /** * 初始化标题栏宽度 */ func setupTitleWidths() { // 标题总宽度 var totalWidth: CGFloat = 0 for controller in self.childViewControllers { let title = controller.title let width = getLableWidth(labelStr: title!, font: titleFont) totalWidth += width titleWidthsArray.add(width) } let marginCounts = self.childViewControllers.count + 1 let margin = (totalWidth > kFrameWidth) ? titleMargin : (kFrameWidth - totalWidth) / CGFloat(marginCounts) titleScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: margin) } /** * 初始化标题栏 */ func setupTitlesArray() { // 顶部标题frame var labelX: CGFloat = 0 let labelY: CGFloat = 0 var labelW = titleWidth let labelH = titleHeight for controller in self.childViewControllers { let index = self.childViewControllers.index(of: controller) // 顶部标题 let label = SlideTitleLabel() label.font = titleFont label.textColor = titleNormalColor label.text = controller.title label.tag = index! if titleWidth == 0 { labelW = titleWidthsArray[index!] as! CGFloat var tempLastLabel = UILabel() if titleLabelsArray.count == 0 { labelX = titleMargin } else { tempLastLabel = titleLabelsArray.lastObject as! UILabel labelX = titleMargin + tempLastLabel.frame.maxX } } else { labelX = CGFloat(index!) * titleWidth } label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickTitleAction(_:))) label.isUserInteractionEnabled = true label.addGestureRecognizer(tapGesture) // 默认选中第一个title if index == selectIndex { clickTitleAction(tapGesture) } // 存储到顶部标题数组 titleLabelsArray.add(label) titleScrollView.addSubview(label) } let lastLabel = titleLabelsArray.lastObject as! UILabel titleScrollView.contentSize = CGSize(width: lastLabel.frame.maxX, height: 0) let counts = self.childViewControllers.count collectionView.contentSize = CGSize(width: CGFloat(counts) * self.view.width, height: 0) } func setupUnderline(_ selLabel: UILabel) { let width = getLableWidth(labelStr: selLabel.text!, font: titleFont) // 设置下划线frame underlineView.y = titleHeight - underlineHieght underlineView.width = width underlineView.height = underlineHieght if !isEqualTitle { // 重置宽度 underlineView.width = underlineWidth } // 初始化时不做动画 if underlineView.x == 0 { underlineView.centerX = selLabel.centerX } else { UIView.animate(withDuration: 0.25) { self.underlineView.centerX = selLabel.centerX } } } // MARK: - Events Response /** * 点击标题事件 */ func clickTitleAction(_ sender: UITapGestureRecognizer) { let titleLabel = sender.view as! UILabel let index = titleLabel.tag let xOffset = CGFloat(index) * kFrameWidth collectionView.contentOffset = CGPoint(x: xOffset, y: 0) // 改变标题状态 titleStateSelecting(titleLabel, style: style!) // 记录索引和偏移量 selectIndex = index lastXOffset = xOffset } /** * 选中标题时更改样式 */ func titleStateSelecting(_ selLabel: UILabel, style: SlideTabBarStyle = .default(nil, nil, nil, nil, nil)) { selLabel.textColor = titleSelectColor for lable in titleLabelsArray { if selLabel == (lable as! UILabel) { continue } (lable as! UILabel).textColor = titleNormalColor } // 居中显示 setSeltitleToCenter(selLabel) switch style { case .underline(_, _, _, _): setupUnderline(selLabel) default: break } } /** * 设置选中标题居中 */ func setSeltitleToCenter(_ selLabel: UILabel) { var currentOffsetX = selLabel.center.x - kFrameWidth * 0.5 var maxOffsetX = titleScrollView.contentSize.width - kFrameWidth + titleMargin // 滚动不足半屏 if currentOffsetX < 0 { currentOffsetX = 0 } // 滚动区域不足一屏 if maxOffsetX < 0 { maxOffsetX = 0 } // 超过最大滚动区域 if currentOffsetX > maxOffsetX { currentOffsetX = maxOffsetX } titleScrollView.setContentOffset(CGPoint(x: currentOffsetX, y: 0), animated: true) } /** * 设置下划线动画 */ func setUnderlineAnimation(_ leftLabel: UILabel, _ rightLabel: UILabel, _ offset: CGFloat) { if isEqualTitle { // 普通样式 let centerDiff = rightLabel.x - leftLabel.x let offsetDiff = offset - lastXOffset let widthDiff = getLableWidth(labelStr: rightLabel.text!, font: titleFont) - getLableWidth(labelStr: leftLabel.text!, font: titleFont) // xPos和增长宽度的比例值 let xTransform = centerDiff * (offsetDiff / kFrameWidth) let updateWidth = widthDiff * (offsetDiff / kFrameWidth) underlineView.x += xTransform underlineView.width += updateWidth } else { // 优酷样式 let centerDiff = rightLabel.x - leftLabel.x let halfFrameW = kFrameWidth * 0.5 if offset <= halfFrameW { let newW = underlineWidth + offset * (centerDiff / halfFrameW ) underlineView.width = newW } else { let label = titleLabelsArray[0] as! UILabel underlineView.x = (offset - halfFrameW) * (centerDiff / halfFrameW) + label.centerX - 7.5 let width = underlineView.width - (offset - halfFrameW ) * (underlineView.width - underlineWidth) / halfFrameW underlineView.width = width } } } } // MARK: - extension SlideTabController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.childViewControllers.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SlideTabController.cellIdentifier, for: indexPath) let controller = self.childViewControllers[indexPath.item] as UIViewController controller.view.frame = CGRect(x: 0, y: 0, width: collectionView.width, height: collectionView.height) cell.contentView.addSubview(controller.view) return cell } } extension SlideTabController: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } } // MARK: - extension SlideTabController: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { let xOffset = scrollView.contentOffset.x let index = xOffset / kFrameWidth let leftLabel = titleLabelsArray[Int(index)] as! UILabel var rightLabel: UILabel? = nil // 最后一个标题后面没有 rightLabel if Int(index) < titleLabelsArray.count - 1 { rightLabel = titleLabelsArray[Int(index)+1] as? UILabel } // 先设置下划线动画 if let rightLabel = rightLabel { setUnderlineAnimation(leftLabel, rightLabel, xOffset) } // 再更新偏移量 lastXOffset = xOffset } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let xOffset = scrollView.contentOffset.x let index = xOffset / kFrameWidth // 选中标题 titleStateSelecting(titleLabelsArray[Int(index)] as! UILabel) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { } }
mit
8ec45bad42c47f82134100919199a1cd
29.359281
155
0.580408
5.321903
false
false
false
false