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
asp2insp/yowl
yowl/FiltersStore.swift
1
3415
// // FiltersStore.swift // yowl // // Created by Josiah Gaskin on 5/17/15. // Copyright (c) 2015 Josiah Gaskin. All rights reserved. // import Foundation // ID: filters class FiltersStore : Store { override func getInitialState() -> Immutable.State { return Immutable.toState(["otherFilters": [ "search": [ "param": "term", "value": "", "disabled": false, ], "sort": [ "param": "sort", "value": 0, "disabled": false, ], "radius": [ "param": "radius_filter", "value": 804, "disabled": true, ], "deals": [ "param": "deals_filter", "value": false, "disabled": false, ], "latlong": [ "param": "ll", "value": "37.785771,-122.406165", "disabled": false, ], ], "offset": 0]) } override func initialize() { self.on("setSearch", handler: { (state, searchTerm, action) -> Immutable.State in let newSearch = searchTerm as! String return state.setIn(["otherFilters", "search", "value"], withValue: Immutable.toState(newSearch)) }) self.on("setDeals", handler: { (state, deals, action) -> Immutable.State in let dealsBool = deals as! Int == 1 return state.setIn(["otherFilters", "deals", "value"], withValue: Immutable.toState(dealsBool)) }) self.on("setDistance", handler: { (state, distance, action) -> Immutable.State in var d : Int = -1 switch distance as! Int { case 0: d = 804 // 0.5 miles in meters case 1: d = 1608 // 1 miles in meters case 2: d = 3216 // 2 miles in meters case 3: d = 8040 // 5 miles in meters default: d = -1 } if d == -1 { return state.setIn(["otherFilters", "radius", "disabled"], withValue: Immutable.toState(true)) } return state.setIn(["otherFilters", "radius", "disabled"], withValue: Immutable.toState(false)).setIn(["otherFilters", "radius", "value"], withValue: Immutable.toState(d)) }) self.on("setSort", handler: { (state, sortType, action) -> Immutable.State in let sort = sortType as! Int return state.setIn(["otherFilters", "sort", "value"], withValue: Immutable.toState(sort)) }) self.on("setOffset", handler: { (state, offset, action) -> Immutable.State in let offsetInt = offset as! Int return state.setIn(["offset"], withValue: Immutable.toState(offsetInt)) }) } } let OFFSET = Getter(keyPath: ["filters", "offset"]) let QUERY = Getter(keyPath: ["filters", "otherFilters"], withFunc: { (args) -> Immutable.State in return args[0].reduce(Immutable.toState([:]), f: {(query, next) -> Immutable.State in let param = next.getIn(["param"]).toSwift() as! String let disabled = next.getIn(["disabled"]).toSwift() as! Bool if disabled { return query } return query.setIn([param], withValue: next.getIn(["value"])) }) })
mit
7fec25846aac07d7f8b6dd30f289bf4e
35.329787
183
0.505417
4.274093
false
false
false
false
dadederk/WeatherTV
Weather/Weather/Controllers/Extensions/String.swift
1
1064
// // String.swift // Weather // // Created by Daniel Devesa Derksen-Staats on 22/02/2016. // Copyright © 2016 Desfici. All rights reserved. // import Foundation extension String { mutating func appendPathComponent(pathComponent: String) { var appendingPathComponent = pathComponent let stringEndIndex = self.endIndex.advancedBy(-1) let pathComponentStartIndex = pathComponent.startIndex let separatorCharacter: Character = "/" self.removeCharacterIfExistsAtIndex(stringEndIndex, character: separatorCharacter) appendingPathComponent.removeCharacterIfExistsAtIndex(pathComponentStartIndex, character: separatorCharacter) self.append(separatorCharacter) self = self + appendingPathComponent } private mutating func removeCharacterIfExistsAtIndex(stringIndex: Index, character: Character) { if self[stringIndex] == character { self.removeAtIndex(stringIndex) } } }
apache-2.0
d776af50732e1c3fe337e54f43ce6ba9
31.212121
100
0.66698
5.423469
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01282-swift-nominaltypedecl-getdeclaredtypeincontext.swift
11
1857
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse s)) func ^(a: Boolean, Bool) -> Bool { return !(a) } f e) func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { class func i() } class d: f{ class func i {} enum S<T> { case C(T, () -> ()) } var x1 = 1 var f1: Int -> Int = { return $0 } let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in return f(x) }(x1, f1) let crashes: Int = { x, f in return f(x) }(x1, f1) class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) } } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e()) func c<d { enum c { func e var _ = e } } protocol A { } struct B : A { } struct C<D, E: A where D.C == E> { } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e pealias e = a<c<h>, d> } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } struct A<T> { let a: [(T, () -> ())] = [] } func a<T>() { enum b { case c } } func a(b: Int = 0) { } let c = a c
apache-2.0
9c2cab74566b1d66e3a490f469297051
13.622047
78
0.560043
2.386889
false
false
false
false
blumareks/iot-watson-swift
lab3/ios/WatsonIoTCreate2/WatsonIoTCreate2/ViewController.swift
2
6883
// // ViewController.swift // WatsonIoTCreate2 // // Created by Marek Sadowski on 11/23/16. // Copyright © 2016 Marek Sadowski. All rights reserved. // import UIKit import MQTTClient //STT import SpeechToTextV1 //TTS import TextToSpeechV1 //audio! import AVFoundation class ViewController: UIViewController { let ORG_ID = "<step 1. your_org_id>" let ioTHostBase = "messaging.internetofthings.ibmcloud.com" let C_ID = "a: <step 1. your_org_id>:RaspberryPiCreate2App" let DEV_TYPE = "RPi3" let DEV_ID = "RaspberryPi3iRobotCreate2" let BEEP_MSG = "1" //play beep let DOCK_MSG = "2" //dock let IOT_API_KEY = "<step 3. your_boilerplates_iot_apikey>" let IOT_AUTH_TOKEN = "<step 2. your_boilerplates_iot_token>" //STT + Weather + TTS @IBOutlet weak var speechToTextLabel: UILabel! @IBAction func micButtonTouchedDown(_ sender: Any) { NSLog("mic button pressed down - starting to listen") //STT - listen for the *forecast* command let usernameSTT = "STT user name from bluemix" let passwordSTT = "STT password from bluemix" let speechToText = SpeechToText(username: usernameSTT, password: passwordSTT) var settings = RecognitionSettings(contentType: .opus) settings.continuous = false settings.interimResults = false let failureSTT = {(error: Error) in print(error)} speechToText.recognizeMicrophone(settings: settings, failure: failureSTT) { results in print(results.bestTranscript) self.speechToTextLabel.text! = results.bestTranscript NSLog("stopping Mic") speechToText.stopRecognizeMicrophone() if (self.speechToTextLabel.text!.contains("forecast")){ NSLog("found forecast") //fetch weather data from Weather Company Data let weather = WeatherData() weather.getCurrentWeather() //print the weather forecast print(weather.getGolf()) sleep(1)// some time to get the result from Weather Company Data print(weather.getGolf()) let textToSay = weather.getGolf() //TTS - say the data let username = "TTS user name from bluemix" let password = "TTS password from bluemix" let textToSpeech = TextToSpeech(username: username, password: password) let failureTTS = { (error: Error) in print(error) } textToSpeech.synthesize(textToSay, voice: SynthesisVoice.us_Michael.rawValue, failure: failureTTS) { data in var audioPlayer: AVAudioPlayer // see note below audioPlayer = try! AVAudioPlayer(data: data) audioPlayer.prepareToPlay() audioPlayer.play() sleep(4) NSLog("end of tts") } } NSLog("end STT") } } override func viewDidLoad() { super.viewDidLoad() // 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. } @IBAction func buttonBeepPressed(_ sender: Any) { NSLog("button Beep pressed") //send a message to the Watson IoT Platform let iotfSession = MQTTSessionManager() if (iotfSession.state != MQTTSessionManagerState.connected) { let host = ORG_ID + "." + ioTHostBase let clientId = "a:" + ORG_ID + ":" + IOT_API_KEY let CMD_TOPIC = "iot-2/type/" + DEV_TYPE + "/id/" + DEV_ID + "/cmd/cmdapp/fmt/json" NSLog("current mqtt topic: " + CMD_TOPIC) iotfSession.connect( to: host, port: 1883, tls: false, keepalive: 30, clean: true, auth: true, user: IOT_API_KEY, pass: IOT_AUTH_TOKEN, will: false, willTopic: nil, willMsg: nil, willQos: MQTTQosLevel.atMostOnce, willRetainFlag: false, withClientId: clientId) // Wait for the session to connect while iotfSession.state != MQTTSessionManagerState.connected { NSLog("waiting for connect " + (iotfSession.state).hashValue.description) RunLoop.current.run(until: NSDate(timeIntervalSinceNow: 1) as Date) } NSLog("connected") iotfSession.send(BEEP_MSG.data(using: String.Encoding.utf8, allowLossyConversion: false), topic: CMD_TOPIC, qos: MQTTQosLevel.exactlyOnce, retain: false) NSLog("MQTT sent cmd BEEP") } } @IBAction func buttonDockPressed(_ sender: Any) { NSLog("button Dock pressed") //send a message to the Watson IoT Platform let iotfSession = MQTTSessionManager() if (iotfSession.state != MQTTSessionManagerState.connected) { let host = ORG_ID + "." + ioTHostBase let clientId = "a:" + ORG_ID + ":" + IOT_API_KEY let CMD_TOPIC = "iot-2/type/" + DEV_TYPE + "/id/" + DEV_ID + "/cmd/cmdapp/fmt/json" NSLog("current mqtt topic: " + CMD_TOPIC) iotfSession.connect( to: host, port: 1883, tls: false, keepalive: 30, clean: true, auth: true, user: IOT_API_KEY, pass: IOT_AUTH_TOKEN, will: false, willTopic: nil, willMsg: nil, willQos: MQTTQosLevel.atMostOnce, willRetainFlag: false, withClientId: clientId) // Wait for the session to connect while iotfSession.state != MQTTSessionManagerState.connected { NSLog("waiting for connect " + (iotfSession.state).hashValue.description) RunLoop.current.run(until: NSDate(timeIntervalSinceNow: 1) as Date) } NSLog("connected") iotfSession.send(DOCK_MSG.data(using: String.Encoding.utf8, allowLossyConversion: false), topic: CMD_TOPIC, qos: MQTTQosLevel.exactlyOnce, retain: false) NSLog("MQTT sent cmd DOCK") } } }
gpl-3.0
95cd9973d2dafc0955bcd3e5f2160abc
37.022099
124
0.541848
4.65
false
false
false
false
jbruce2112/cutlines
Cutlines/Controllers/SearchViewController.swift
1
5431
// // SearchViewController.swift // Cutlines // // Created by John on 1/30/17. // Copyright © 2017 Bruce32. All rights reserved. // import UIKit class SearchViewController: UITableViewController { // MARK: Properties var photoManager: PhotoManager! private var resultsViewController = SearchResultsViewController() private var recentSearches = [String]() private let recentSearchTermLimit = 5 private var lastSearchTerm: String? private let recentSearchesArchive: String = { let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! return cacheDir.appendingPathComponent("recentSearches.archive").path }() private var searchController: UISearchController! // MARK: Functions override func viewDidLoad() { super.viewDidLoad() definesPresentationContext = true searchController = UISearchController(searchResultsController: resultsViewController) searchController.searchResultsUpdater = resultsViewController searchController.dimsBackgroundDuringPresentation = false resultsViewController.photoManager = photoManager resultsViewController.searchController = searchController navigationItem.searchController = searchController navigationItem.searchController?.hidesNavigationBarDuringPresentation = false navigationItem.hidesSearchBarWhenScrolling = false tableView.cellLayoutMarginsFollowReadableWidth = true // Don't show empty cells tableView.tableFooterView = UIView() tableView.dataSource = self resultsViewController.searchController.delegate = self resultsViewController.searchTermDelegate = self recentSearches = loadRecent() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setTheme() // Since this viewController overlays us, // we need to call setTheme() on it as well resultsViewController.setTheme() } override func setTheme(_ theme: Theme) { super.setTheme(theme) searchController.searchBar.setTheme() // force the section headers to refresh tableView.reloadSections(IndexSet(integer: 0), with: .none) tableView.backgroundView = UIView() tableView.backgroundView?.setTheme() } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { tableView.reloadData() } func saveRecent() { NSKeyedArchiver.archiveRootObject(recentSearches, toFile: recentSearchesArchive) log("Recent searches saved") } // MARK: UITableViewDataSource functions override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return recentSearches.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) cell.textLabel!.text = recentSearches[indexPath.row] cell.setTheme() return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Recent Searches" : nil } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let view = view as? UITableViewHeaderFooterView else { return } view.backgroundView?.setTheme() let theme = Theme() view.backgroundView?.backgroundColor = theme.altBackgroundColor if theme.isNight { view.textLabel?.textColor = .white } } // MARK: UITableViewDelegate functions override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Trigger a search using the selected term searchController.isActive = true searchController.searchBar.text = recentSearches[indexPath.row] } // MARK: Private functions private func loadRecent() -> [String] { if let recent = NSKeyedUnarchiver.unarchiveObject(withFile: recentSearchesArchive) as? [String] { log("Previous search terms loaded from archive") return recent } else { log("Unable to load previous search terms, starting new") return [String]() } } } // MARK: UISearchControllerDelegate conformance extension SearchViewController: UISearchControllerDelegate { func willDismissSearchController(_ searchController: UISearchController) { tableView.reloadData() } } // MARK: SearchTermDelegate conformance extension SearchViewController: SearchTermDelegate { func didPerformSearch(withTerm searchTerm: String) { lastSearchTerm = searchTerm if searchTerm.trimmingCharacters(in: .whitespaces).isEmpty { return } // Kick off a save in a few seconds for this search term for the recent list DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) { // Cancel the save if we started another search by the time this ran if self.lastSearchTerm != searchTerm { log("Last search term \(self.lastSearchTerm ?? "nil") doesn't match pending save \(searchTerm)") return } // We're only storing a few terms - don't bother with duplicates if self.recentSearches.contains(searchTerm) { return } if self.recentSearches.count == self.recentSearchTermLimit { self.recentSearches.removeLast() } self.recentSearches.insert(searchTerm, at: 0) log("Added recent search term \(searchTerm)") } } }
mit
72a20953b94ddfaef261373cfcacd138
26.989691
125
0.747145
4.713542
false
false
false
false
xiaoyouPrince/WeiBo
WeiBo/WeiBo/Classes/Tools/Emotion/UITextView+Extension.swift
1
2842
// // UI+Extension.swift // WeiBo // // Created by 渠晓友 on 2017/6/12. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // import UIKit /// 封装UITextView插入和读取属性字符串的方法 extension UITextView { /// 获取TextView的AttributeString /// /// - Returns: <#return value description#> func getAttributeString() -> String { // 1.获取属性字符串 let attrStr = NSMutableAttributedString(attributedString: attributedText) // 2.遍历 attrStr 对原有的表情进行替换 let range = NSMakeRange(0, attrStr.length) attrStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in Dlog("\(String(describing: dict))" + "-----" + "(\(range.location),\(range.length))") if let attachment = dict[NSAttributedString.Key(rawValue: "NSAttachment")] as? EmotionAttchment { attrStr.replaceCharacters(in: range, with: attachment.chs!) } Dlog(attrStr.string) } return attrStr.string } func insertEmotionToTextView(emotion : Emotion) { Dlog(emotion) // 空表情 不行 if emotion.isEmpty { return } // 删除表情 if emotion.isRemove { deleteBackward() return } //emoji表情,直接插入 if (emotion.emojiCode != nil) { /** let textRange = selectedTextRange! replace(textRange, withText: emotion.emojiCode!) */ insertText(emotion.emojiCode!) return } // 普通表情(图文混排) // 1.设置attachment let attachment = EmotionAttchment() attachment.chs = emotion.chs attachment.image = UIImage(contentsOfFile: emotion.pngPath!) let font = self.font attachment.bounds = CGRect(x: 0, y: -4, width: (font?.lineHeight)!, height: (font?.lineHeight)!) // 2.通过attachMent生成待使用属性字符串 let attrImageStr = NSAttributedString(attachment: attachment) // 3.取得原textView内容获得原属性字符串 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 4.替换当前位置的属性字符串并重新赋值给textView let range = selectedRange attrMStr.replaceCharacters(in: range, with: attrImageStr) attributedText = attrMStr // 5.处理出现的遗留问题 self.font = font selectedRange = NSMakeRange(range.location + 1, range.length) } }
mit
a00f2f7d5b6d169c236c140c3064f1c6
26.072917
110
0.546364
4.725455
false
false
false
false
lucaslouca/swift-concurrency
app-ios/Fluxcapacitor/FXCSearchBar.swift
1
1271
// // FXCSearchBar.swift // Fluxcapacitor // // Created by Lucas Louca on 31/05/15. // Copyright (c) 2015 Lucas Louca. All rights reserved. // import UIKit @IBDesignable class FXCSearchBar: UISearchBar { @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var searchFieldBackgroundColor: UIColor = UIColor.clearColor() { didSet { let textField = self.valueForKey("searchField") as! UITextField textField.backgroundColor = searchFieldBackgroundColor } } @IBInspectable var searchFieldBorderWidth: CGFloat = 0 { didSet { let textField = self.valueForKey("searchField") as! UITextField textField.layer.borderWidth = searchFieldBorderWidth } } @IBInspectable var searchFieldBorderColor: UIColor = UIColor.clearColor() { didSet { let textField = self.valueForKey("searchField") as! UITextField textField.layer.borderColor = searchFieldBorderColor.CGColor } } }
mit
9a8f486000e655a76b700c1d36a16967
27.244444
83
0.632573
5.252066
false
false
false
false
Geor9eLau/WorkHelper
WorkoutHelper/InfoRecordView.swift
1
6855
// // InfoRecordView.swift // WorkoutHelper // // Created by George on 2017/2/13. // Copyright © 2017年 George. All rights reserved. // import UIKit import Toaster protocol InfoRecordViewDelegate { func recordDidFinished(weight: Double, repeats: Int) } class InfoRecordView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ public var delegate: InfoRecordViewDelegate? private var weight: Double = 0 private var repeats: Int = 0 private let backView: UIView = { let tmp = UIView(frame: UIScreen.main.bounds) tmp.backgroundColor = UIColor.black tmp.alpha = 0.6 return tmp }() private let weightRecordBackView: UIView = { let tmp = UIView(frame: CGRect(x: 50, y: 160, width: SCREEN_WIDTH - 100, height: 180)) tmp.backgroundColor = UIColor.white tmp.layer.cornerRadius = 10.0 return tmp }() private let repeatsRecordBackView: UIView = { let tmp = UIView(frame: CGRect(x: 50 + SCREEN_WIDTH, y: 160, width: SCREEN_WIDTH - 100, height: 160)) tmp.backgroundColor = UIColor.white tmp.layer.cornerRadius = 10.0 return tmp }() private let weightTitleLbl: UILabel = { let tmp = UILabel(frame: CGRect(x: 0, y: 20, width: SCREEN_WIDTH - 100, height: 30)) tmp.text = "How much weight" tmp.textAlignment = .center tmp.font = UIFont.systemFont(ofSize: 24) tmp.textColor = UIColor.black return tmp }() private let weightTf: UITextField = { let tmp = UITextField(frame: CGRect(x: (SCREEN_WIDTH - 100 - 50) / 2, y: 80, width: 50, height: 30)) tmp.borderStyle = .none tmp.keyboardType = .decimalPad tmp.textColor = UIColor.green tmp.font = UIFont.systemFont(ofSize: 20) return tmp }() private let weightUnitLbl: UILabel = { let tmp = UILabel(frame: CGRect(x: (SCREEN_WIDTH - 100 - 50) / 2 + 50, y: 80, width: 40, height: 30)) tmp.text = "kg" tmp.font = UIFont.systemFont(ofSize: 20) tmp.textColor = UIColor.black return tmp }() private let repeatsTitleLbl: UILabel = { let tmp = UILabel(frame: CGRect(x: 0, y: 20, width: SCREEN_WIDTH - 100, height: 30)) tmp.text = "How many repeats" tmp.textAlignment = .center tmp.font = UIFont.systemFont(ofSize: 24) tmp.textColor = UIColor.black return tmp }() private let repeatsTf: UITextField = { let tmp = UITextField(frame: CGRect(x: (SCREEN_WIDTH - 100 - 50) / 2, y: 80, width: 50, height: 30)) tmp.borderStyle = .none tmp.keyboardType = .numberPad tmp.textColor = UIColor.green tmp.font = UIFont.systemFont(ofSize: 20) return tmp }() private let repeatUnitLbl: UILabel = { let tmp = UILabel(frame: CGRect(x: (SCREEN_WIDTH - 100 - 50) / 2 + 50, y: 80, width: 90, height: 30)) tmp.text = "repeats" tmp.font = UIFont.systemFont(ofSize: 20) tmp.textColor = UIColor.black return tmp }() private lazy var nextBtn: UIButton = { let tmp = UIButton(frame: CGRect(x: SCREEN_WIDTH - 120, y: SCREEN_HEIGHT - 270, width: 100, height: 40)) tmp.setTitle("Next >>", for: .normal) tmp.layer.cornerRadius = 5.0 tmp.titleLabel?.font = UIFont.systemFont(ofSize: 16) tmp.backgroundColor = UIColor.blue tmp.addTarget(self, action: #selector(nextBtnDidClicked), for: .touchUpInside) return tmp }() private lazy var doneBtn: UIButton = { let tmp = UIButton(frame: CGRect(x: SCREEN_WIDTH - 120, y: SCREEN_HEIGHT - 270, width: 100, height: 40)) tmp.setTitle("Done !!", for: .normal) tmp.layer.cornerRadius = 5.0 tmp.titleLabel?.font = UIFont.systemFont(ofSize: 16) tmp.backgroundColor = UIColor.blue tmp.addTarget(self, action: #selector(doneBtnDidClicked), for: .touchUpInside) tmp.isHidden = true return tmp }() // MARK: - Public func show() { UIApplication.shared.keyWindow?.addSubview(self) self.weightTf.becomeFirstResponder() } // MARK: - Initialize override init(frame: CGRect) { super.init(frame: frame) addSubview(backView) addSubview(weightRecordBackView) weightRecordBackView.addSubview(weightTitleLbl) weightRecordBackView.addSubview(weightTf) weightRecordBackView.addSubview(weightUnitLbl) addSubview(repeatsRecordBackView) repeatsRecordBackView.addSubview(repeatsTitleLbl) repeatsRecordBackView.addSubview(repeatsTf) repeatsRecordBackView.addSubview(repeatUnitLbl) addSubview(nextBtn) addSubview(doneBtn) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Event Handlers @objc private func nextBtnDidClicked() { guard self.weightTf.text?.characters.count != 0 else { let toast = Toast(text: "Please enter the weight", delay: 0.1, duration: 0.5) toast.show() return } self.weight = Double(self.weightTf.text!)! UIView.animate(withDuration: 0.5, animations: {[weak self] in let originalFrame = self?.weightRecordBackView.frame self?.weightRecordBackView.frame = CGRect(x: CGFloat(Double((originalFrame?.origin.x)!) - SCREEN_WIDTH), y: CGFloat(Double((originalFrame?.origin.y)!)), width: (originalFrame?.size.width)!, height: (originalFrame?.size.height)!) self?.repeatsRecordBackView.frame = originalFrame! }) self.nextBtn.isHidden = true self.doneBtn.isHidden = false self.repeatsTf.becomeFirstResponder() } @objc private func doneBtnDidClicked() { guard self.repeatsTf.text?.characters.count != 0 else { let toast = Toast(text: "Please enter the repeats", delay: 0.1, duration: 0.5) toast.show() return } self.repeats = Int(self.repeatsTf.text!)! self.delegate?.recordDidFinished(weight: self.weight, repeats: self.repeats) self.removeFromSuperview() self.weightRecordBackView.frame = CGRect(x: 50, y: 160, width: SCREEN_WIDTH - 100, height: 160) self.repeatsRecordBackView.frame = CGRect(x: 50 + SCREEN_WIDTH, y: 160, width: SCREEN_WIDTH - 100, height: 160) self.nextBtn.isHidden = false self.doneBtn.isHidden = true self.repeatsTf.resignFirstResponder() } }
mit
3d859c1f244f96f644996b56564ccf45
35.446809
240
0.619381
4.152727
false
false
false
false
objcio/OptimizingCollections
Sources/BTree2.swift
1
11419
public struct BTree2<Element: Comparable> { fileprivate var root: Node public init(order: Int) { self.root = Node(order: order) } } extension BTree2 { public init() { let order = (cacheSize ?? 32768) / (4 * MemoryLayout<Element>.stride) self.init(order: Swift.max(16, order)) } } extension BTree2 { class Node { let order: Int var mutationCount: Int64 = 0 var elementCount: Int = 0 let elements: UnsafeMutablePointer<Element> var children: ContiguousArray<Node> = [] init(order: Int) { self.order = order self.elements = .allocate(capacity: order) } deinit { elements.deinitialize(count: elementCount) elements.deallocate(capacity: order) } } } extension BTree2 { public func forEach(_ body: (Element) throws -> Void) rethrows { try root.forEach(body) } } extension BTree2.Node { func forEach(_ body: (Element) throws -> Void) rethrows { if isLeaf { for i in 0 ..< elementCount { try body(elements[i]) } } else { for i in 0 ..< elementCount { try children[i].forEach(body) try body(elements[i]) } try children[elementCount].forEach(body) } } } extension BTree2.Node { internal func slot(of element: Element) -> (match: Bool, index: Int) { var start = 0 var end = elementCount while start < end { let mid = start + (end - start) / 2 if elements[mid] < element { start = mid + 1 } else { end = mid } } let match = start < elementCount && elements[start] == element return (match, start) } } extension BTree2 { public func contains(_ element: Element) -> Bool { return root.contains(element) } } extension BTree2.Node { func contains(_ element: Element) -> Bool { let slot = self.slot(of: element) if slot.match { return true } guard !children.isEmpty else { return false } return children[slot.index].contains(element) } } extension BTree2 { fileprivate mutating func makeRootUnique() -> Node { if isKnownUniquelyReferenced(&root) { return root } root = root.clone() return root } } extension BTree2.Node { func clone() -> BTree2<Element>.Node { let node = BTree2<Element>.Node(order: order) node.elementCount = self.elementCount node.elements.initialize(from: self.elements, count: self.elementCount) if !isLeaf { node.children.reserveCapacity(order + 1) node.children += self.children } return node } } extension BTree2.Node { func makeChildUnique(at slot: Int) -> BTree2<Element>.Node { guard !isKnownUniquelyReferenced(&children[slot]) else { return children[slot] } let clone = children[slot].clone() children[slot] = clone return clone } } extension BTree2.Node { var maxChildren: Int { return order } var minChildren: Int { return (maxChildren + 1) / 2 } var maxElements: Int { return maxChildren - 1 } var minElements: Int { return minChildren - 1 } var isLeaf: Bool { return children.isEmpty } var isTooLarge: Bool { return elementCount > maxElements } } extension BTree2 { struct Splinter { let separator: Element let node: Node } } extension BTree2.Node { func split() -> BTree2<Element>.Splinter { let count = self.elementCount let middle = count / 2 let separator = elements[middle] let node = BTree2<Element>.Node(order: self.order) let c = count - middle - 1 node.elements.moveInitialize(from: self.elements + middle + 1, count: c) node.elementCount = c self.elementCount = middle if !isLeaf { node.children.reserveCapacity(self.order + 1) node.children += self.children[middle + 1 ... count] self.children.removeSubrange(middle + 1 ... count) } return .init(separator: separator, node: node) } } extension BTree2.Node { fileprivate func _insertElement(_ element: Element, at slot: Int) { assert(slot >= 0 && slot <= elementCount) (elements + slot + 1).moveInitialize(from: elements + slot, count: elementCount - slot) (elements + slot).initialize(to: element) elementCount += 1 } } extension BTree2.Node { func insert(_ element: Element) -> (old: Element?, splinter: BTree2<Element>.Splinter?) { let slot = self.slot(of: element) if slot.match { // The element is already in the tree. return (self.elements[slot.index], nil) } mutationCount += 1 if self.isLeaf { _insertElement(element, at: slot.index) return (nil, self.isTooLarge ? self.split() : nil) } let (old, splinter) = makeChildUnique(at: slot.index).insert(element) guard let s = splinter else { return (old, nil) } _insertElement(s.separator, at: slot.index) self.children.insert(s.node, at: slot.index + 1) return (old, self.isTooLarge ? self.split() : nil) } } extension BTree2 { @discardableResult public mutating func insert(_ element: Element) -> (inserted: Bool, memberAfterInsert: Element) { let root = makeRootUnique() let (old, splinter) = root.insert(element) if let s = splinter { let root = BTree2<Element>.Node(order: root.order) root.elementCount = 1 root.elements.initialize(to: s.separator) root.children = [self.root, s.node] self.root = root } return (inserted: old == nil, memberAfterInsert: old ?? element) } } extension BTree2 { struct UnsafePathElement: Equatable { unowned(unsafe) let node: Node var slot: Int init(_ node: Node, _ slot: Int) { self.node = node self.slot = slot } var isLeaf: Bool { return node.isLeaf } var isAtEnd: Bool { return slot == node.elementCount } var value: Element? { guard slot < node.elementCount else { return nil } return node.elements[slot] } var child: Node { return node.children[slot] } static func ==(left: UnsafePathElement, right: UnsafePathElement) -> Bool { return left.node === right.node && left.slot == right.slot } } } extension BTree2 { public struct Index: Comparable { fileprivate weak var root: Node? fileprivate let mutationCount: Int64 fileprivate var path: [UnsafePathElement] fileprivate var current: UnsafePathElement init(startOf tree: BTree2) { self.root = tree.root self.mutationCount = tree.root.mutationCount self.path = [] self.current = UnsafePathElement(tree.root, 0) while !current.isLeaf { push(0) } } init(endOf tree: BTree2) { self.root = tree.root self.mutationCount = tree.root.mutationCount self.path = [] self.current = UnsafePathElement(tree.root, tree.root.elementCount) } } } extension BTree2.Index { fileprivate func validate(for root: BTree2<Element>.Node) { precondition(self.root === root) precondition(self.mutationCount == root.mutationCount) } fileprivate static func validate(_ left: BTree2<Element>.Index, _ right: BTree2<Element>.Index) { precondition(left.root === right.root) precondition(left.mutationCount == right.mutationCount) precondition(left.root != nil) precondition(left.mutationCount == left.root!.mutationCount) } } extension BTree2.Index { fileprivate mutating func push(_ slot: Int) { path.append(current) let child = current.node.children[current.slot] current = BTree2<Element>.UnsafePathElement(child, slot) } fileprivate mutating func pop() { current = self.path.removeLast() } } extension BTree2.Index { fileprivate mutating func formSuccessor() { precondition(!current.isAtEnd, "Cannot advance beyond endIndex") current.slot += 1 if current.isLeaf { while current.isAtEnd, current.node !== root { pop() } } else { while !current.isLeaf { push(0) } } } } extension BTree2.Index { fileprivate mutating func formPredecessor() { if current.isLeaf { while current.slot == 0, current.node !== root { pop() } precondition(current.slot > 0, "Cannot go below startIndex") current.slot -= 1 } else { while !current.isLeaf { let c = current.child push(c.isLeaf ? c.elementCount - 1 : c.elementCount) } } } } extension BTree2.Index { public static func ==(left: BTree2<Element>.Index, right: BTree2<Element>.Index) -> Bool { BTree2<Element>.Index.validate(left, right) return left.current == right.current } public static func <(left: BTree2<Element>.Index, right: BTree2<Element>.Index) -> Bool { BTree2<Element>.Index.validate(left, right) switch (left.current.value, right.current.value) { case let (a?, b?): return a < b case (nil, _): return false default: return true } } } extension BTree2: SortedSet { public var startIndex: Index { return Index(startOf: self) } public var endIndex: Index { return Index(endOf: self) } public subscript(index: Index) -> Element { get { index.validate(for: root) return index.current.value! } } public func formIndex(after i: inout Index) { i.validate(for: root) i.formSuccessor() } public func index(after i: Index) -> Index { i.validate(for: root) var i = i i.formSuccessor() return i } public func formIndex(before i: inout Index) { i.validate(for: root) i.formPredecessor() } public func index(before i: Index) -> Index { i.validate(for: root) var i = i i.formPredecessor() return i } } extension BTree2 { public var count: Int { return root.count } } extension BTree2.Node { var count: Int { return children.reduce(elementCount) { $0 + $1.count } } } extension BTree2 { public struct Iterator: IteratorProtocol { let tree: BTree2 var index: Index init(_ tree: BTree2) { self.tree = tree self.index = tree.startIndex } public mutating func next() -> Element? { guard let result = index.current.value else { return nil } index.formSuccessor() return result } } public func makeIterator() -> Iterator { return Iterator(self) } }
mit
34612b2aefeecd7ed67a835571a981c2
27.264851
101
0.573693
4.184317
false
false
false
false
phimage/MomXML
Sources/Model/MomEntity.swift
1
1257
// Created by Eric Marchand on 07/06/2017. // Copyright © 2017 Eric Marchand. All rights reserved. // import Foundation public struct MomEntity { public var name: String public var representedClassName: String public var syncable: Bool = true public var codeGenerationType: String public var userInfo = MomUserInfo() public var uniquenessConstraints: MomUniquenessConstraints? //TODO public var elementID: String? //TODO public var versionHashModifier: String? public init(name: String, representedClassName: String? = nil, codeGenerationType: String = "class") { self.name = name self.representedClassName = representedClassName ?? name self.codeGenerationType = codeGenerationType } public var attributes: [MomAttribute] = [] public var relationship: [MomRelationship] = [] public var fetchProperties: [MomFetchedProperty] = [] public var fetchIndexes: [MomFetchIndex] = [] // TODO MomCompoundIndex (deprecated) } extension MomEntity { var relationshipByName: [String: MomRelationship] { return relationship.dictionaryBy { $0.name } } var attributesByName: [String: MomAttribute] { return attributes.dictionaryBy { $0.name } } }
mit
6ff930c78077ee99ccf0d6c765c7298f
31.205128
106
0.705414
4.30137
false
false
false
false
ortizraf/macsoftwarecenter
Mac Application Store/ProductDetailController.swift
1
11351
// // ProductDetailController.swift // Mac Software Center // // Created by Rafael Ortiz. // Copyright © 2017 Nextneo. All rights reserved. // import Cocoa class ProductDetailController: NSViewController { var application : App = App() @IBOutlet weak var application_label_name: NSTextField! @IBOutlet weak var application_imageview_image: NSImageView! @IBOutlet weak var application_label_description: NSTextField! @IBOutlet weak var application_button_category: NSButton! @IBOutlet weak var application_label_last_update: NSTextField! @IBOutlet weak var application_label_version: NSTextField! @IBOutlet weak var application_button_organization: NSButton! @IBOutlet weak var application_button_website_link: NSButton! @IBOutlet weak var application_website_view: NSView! @IBOutlet weak var application_link: NSButton! @IBOutlet weak var application_option: NSPopUpButton! var taskName = String() var productId = Int() override func viewDidLoad() { super.viewDidLoad() trackingAreaButton() let dbApp = AppDB() if (taskName=="product" && productId>0){ self.application = dbApp.getAppById(id: productId as AnyObject) application_label_name.stringValue = (application.name)! if((application.url_image?.contains("http"))! && (application.url_image?.contains(".png"))!){ let url = URL(string: (application.url_image)!) let image = NSImage(byReferencing: url!) image.cacheMode = NSImage.CacheMode.always application_imageview_image.image=image } else { application_imageview_image.image = NSImage(named: (application.url_image)!) } if(!(application.description?.isEmpty)!){ application_label_description.stringValue = (application.description)! } application_button_category.title = (application.category?.name)! let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd, yyyy" application_label_last_update.stringValue = dateFormatter.string(from:application.last_update!) if(application.version != nil && !(application.version?.isEmpty)!){ application_label_version.stringValue = (application.version)! } else { application_label_version.stringValue = "Last version" } application_button_organization.isHidden = true application_button_organization.isEnabled = false if(application.organization != nil){ application_button_organization.isHidden = false application_button_organization.isEnabled = true application_button_organization.title = (application.organization?.name)! } if(application.website != nil && !(application.website?.isEmpty)!){ application_website_view.isHidden = false application_button_website_link.isHidden = false } } } @IBAction func clickActionToCategoryController(sender: AnyObject) { print("Button pressed Category ") actionToOrganizationController(taskName: "category") } @IBAction func clickActionToOrganizationController(sender: AnyObject) { print("click button Organization") actionToOrganizationController(taskName: "organization") } @IBAction func clickActionToWebsiteController(sender: AnyObject) { print("click button Website") NSWorkspace.shared.open(URL(string: application.website!)!) } func actionToOrganizationController(taskName: String) { self.view.wantsLayer = true let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil) let productViewController = mainStoryboard.instantiateController(withIdentifier: "productViewController") as! ProductController productViewController.taskName = taskName if(application.organization != nil){ productViewController.organizationId = (application.organization?.id)! } if(application.category != nil){ productViewController.categoryId = (application.category?.id)! } for view in self.view.subviews { view.removeFromSuperview() } self.insertChild(productViewController, at: 0) self.view.addSubview(productViewController.view) self.view.frame = productViewController.view.frame } @IBAction func btnDownload(sender: AnyObject){ print("Button pressed 👍 ") getDownload(downloadLink: (application.download_link)!, appName: (application.name)!) } @IBAction func selectOption(sender: AnyObject){ print("PopUp Button pressed 👍 ") let selectedNumber = sender.indexOfSelectedItem if(selectedNumber==0){ if let url = URL(string: (application.download_link)!), NSWorkspace.shared.open(url) { print("default browser was successfully opened") } } else if (selectedNumber==1) { let pasteBoard = NSPasteboard.general pasteBoard.clearContents() pasteBoard.setString((application.download_link)!, forType: .string) } } func getDownload(downloadLink: String, appName: String){ application_link.isEnabled = false application_link.title = "downloading..." let downloadUrl = NSURL(string: downloadLink) let downloadService = DownloadService(url: downloadUrl!) downloadService.downloadData(completion: { (data) in let fileDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0] let fileNameUrl = NSURL(fileURLWithPath: (downloadUrl?.absoluteString)!).lastPathComponent! var fileName = fileNameUrl.removingPercentEncoding if(self.application.file_format?.contains("zip"))!{ print("zip") fileName = appName+".zip" } else if(self.application.file_format?.contains("dmg"))!{ fileName = appName+".dmg" } else if(!(fileName?.contains(".dmg"))! && !(fileName?.contains(".zip"))! && !(fileName?.contains(".app"))!){ print("dmg") fileName = appName+".dmg" } let fileUrl = fileDirectory.appendingPathComponent(fileName!, isDirectory: false) try? data.write(to: fileUrl) let messageService = MessageService() messageService.showNotification(title: appName, informativeText: "Download completed successfully") self.application_link.title = "download" self.application_link.isEnabled = true }) } //tracking buttons func trackingAreaButton(){ let areaButtonCategory = NSTrackingArea.init(rect: application_button_category.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) application_button_category.addTrackingArea(areaButtonCategory) let areaButtonOrganization = NSTrackingArea.init(rect: application_button_organization.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) application_button_organization.addTrackingArea(areaButtonOrganization) let areaButtonWebsite = NSTrackingArea.init(rect: application_button_website_link.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) application_button_website_link.addTrackingArea(areaButtonWebsite) } override func mouseExited(with event: NSEvent) { print("Mouse Exited") let pstyle = NSMutableParagraphStyle() application_button_category.attributedTitle = NSAttributedString(string: application_button_category.title, attributes: [ NSAttributedString.Key.foregroundColor : NSColor.secondaryLabelColor, NSAttributedString.Key.paragraphStyle : pstyle, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 11), NSFontDescriptor.AttributeName.size: 11 ] as? [NSAttributedString.Key : Any]) application_button_organization.attributedTitle = NSAttributedString(string: application_button_organization.title, attributes: [ NSAttributedString.Key.foregroundColor : NSColor.secondaryLabelColor, NSAttributedString.Key.paragraphStyle : pstyle, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 11), NSFontDescriptor.AttributeName.size: 11 ] as? [NSAttributedString.Key : Any]) application_button_website_link.attributedTitle = NSAttributedString(string: application_button_website_link.title, attributes: [ NSAttributedString.Key.foregroundColor : NSColor.secondaryLabelColor, NSAttributedString.Key.paragraphStyle : pstyle, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 13), NSFontDescriptor.AttributeName.size: 13 ] as? [NSAttributedString.Key : Any]) } override func mouseEntered(with event: NSEvent) { print("Mouse Entered") let pstyle = NSMutableParagraphStyle() if(event.trackingArea?.rect.equalTo((application_button_category.trackingAreas.first?.rect)!))!{ application_button_category.attributedTitle = NSAttributedString(string: application_button_category.title, attributes: [ NSAttributedString.Key.foregroundColor : NSColor.linkColor, NSAttributedString.Key.paragraphStyle : pstyle, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 11), NSFontDescriptor.AttributeName.size: 11 ] as? [NSAttributedString.Key : Any]) } if(event.trackingArea?.rect.equalTo((application_button_organization.trackingAreas.first?.rect)!))!{ application_button_organization.attributedTitle = NSAttributedString(string: application_button_organization.title, attributes: [ NSAttributedString.Key.foregroundColor : NSColor.linkColor, NSAttributedString.Key.paragraphStyle : pstyle, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 11), NSFontDescriptor.AttributeName.size: 11 ] as? [NSAttributedString.Key : Any]) } if(event.trackingArea?.rect.equalTo((application_button_website_link.trackingAreas.first?.rect)!))!{ application_button_website_link.attributedTitle = NSAttributedString(string: application_button_website_link.title, attributes: [ NSAttributedString.Key.foregroundColor : NSColor.linkColor, NSAttributedString.Key.paragraphStyle : pstyle, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 13), NSFontDescriptor.AttributeName.size: 13, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue as AnyObject ] as? [NSAttributedString.Key : Any]) } } }
gpl-3.0
9b5b3ffd99f4d4110496a9b8846be1f2
47.686695
485
0.667225
5.278734
false
false
false
false
cornerstonecollege/401
olderFiles/401_2016_2/swift_examples/Tuples/Tuples/main.swift
1
553
// // main.swift // Tuples // // Created by Luiz on 2016-09-27. // Copyright © 2016 Ideia do Luiz. All rights reserved. // import Foundation let point = (5.5, 10.1) print(point.0) let point2 = (x: 7.5, y: 12.1) print("X: \(point2.x) Y:\(point2.y)") let (point2X, point2Y) = point2 print("Hey, I broke \(point2X) and \(point2Y) down") let (x, _) = point2 let arr = [26, 46, 56, 66] for element in arr { print("The element is \(element)") } for (index, element) in arr.enumerated() { print("The element at \(index) is \(element)") }
gpl-3.0
0e8e6a9950d5636c9094d15e125d506a
15.727273
56
0.612319
2.579439
false
false
false
false
hujiaweibujidao/Gank
Gank/Class/Home/AHHomeViewController.swift
2
8520
// // AHHomeViewController.swift // Gank // // Created by AHuaner on 2016/12/22. // Copyright © 2016年 CoderAhuan. All rights reserved. // import UIKit class AHHomeViewController: BaseViewController { // MARK: - property fileprivate var datasArray: [AHHomeGroupModel] = [AHHomeGroupModel]() fileprivate var lastSelectedIndex: Int = 0 fileprivate var lastDate: String = UserConfig.string(forKey: .lastDate) ?? "" // MARK: - control fileprivate lazy var headerView: AHHomeHeaderView = { let headerView = AHHomeHeaderView.headerView() headerView.frame = CGRect(x: 0, y: 0, width: kScreen_W, height: kScreen_H * 0.55) return headerView }() fileprivate lazy var tableView: UITableView = { let tabelView = UITableView(frame: CGRect(x: 0, y: 0, width: kScreen_W, height: kScreen_H), style: UITableViewStyle.grouped) tabelView.backgroundColor = UIColor.white tabelView.delegate = self tabelView.dataSource = self tabelView.contentInset.bottom = kBottomBarHeight tabelView.separatorStyle = .none tabelView.register(UITableViewCell.self, forCellReuseIdentifier: "homecell") tabelView.tableHeaderView = self.headerView return tabelView }() fileprivate lazy var navBar: AHNavBar = { let navBar = AHNavBar(frame: CGRect(x: 0, y: 0, width: kScreen_W, height: 64)) navBar.searchView.locationVC = self return navBar }() fileprivate lazy var loadingView: AHLoadingView = { let loadingView = AHLoadingView(frame: CGRect(x: 0, y: 0, width: kScreen_W, height: kScreen_H - kBottomBarHeight)) return loadingView }() // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.statusBarStyle = .lightContent self.navigationController?.setNavigationBarHidden(true, animated: animated) loadGankFromCache() sendRequest() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if (self.navigationController?.viewControllers.count)! > 1 { self.navigationController?.setNavigationBarHidden(false, animated: animated) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - event && methods fileprivate func setupUI() { view.addSubview(tableView) view.addSubview(navBar) self.automaticallyAdjustsScrollViewInsets = false NotificationCenter.default.addObserver(self, selector: #selector(tabBarSelector), name: NSNotification.Name.AHTabBarDidSelectNotification, object: nil) } fileprivate func sendRequest() { // 获取发过干货的日期 AHNewWork.loadDateRequest(success: { (result: Any) in guard let dateArray = result as? [String] else { return } guard let newestDate = dateArray.first else { return } let date = newestDate.replacingOccurrences(of: "-", with: "/") if self.lastDate == date { self.loadGankFromCache() return } self.loadGanks(WithDate: date) }) { (error: Error) in AHLog(error) self.loadGankFromCache() } } // 请求首页数据 fileprivate func loadGanks(WithDate date: String) { AHNewWork.loadHomeRequest(date: date, success: { (result: Any) in guard let datasArray = result as? [AHHomeGroupModel] else { return } self.loadingView.isHidden = true self.lastDate = date // UserDefaults.AHData.lastDate.store(value: date) UserConfig.set(date, forKey: .lastDate) self.datasArray = datasArray self.setupHeaderView() self.tableView.reloadData() }) { (error: Error) in self.loadGankFromCache() } } // 读取缓存的首页数据 fileprivate func loadGankFromCache() { guard let datas = NSKeyedUnarchiver.unarchiveObject(withFile: "homeGanks".cachesDir()) as? [AHHomeGroupModel] else { view.addSubview(loadingView) return } self.datasArray = datas self.setupHeaderView() if datas.count == 0 { view.addSubview(loadingView) return } self.tableView.reloadData() } fileprivate func setupHeaderView() { var newData = [AHHomeGroupModel]() for data in datasArray { if data.groupTitle == "福利" { guard let urlString = data.ganks.first?.url else { return } let url = urlString + "?/0/w/\(kScreen_H * 0.55)/h/\(kScreen_W)" headerView.imageView.yy_imageURL = URL(string: url) continue } newData.append(data) } datasArray = newData } func tabBarSelector() { if self.lastSelectedIndex == self.tabBarController!.selectedIndex && self.view.isShowingOnKeyWindow() { var offset = self.tableView.contentOffset offset.y = -self.tableView.contentInset.top; self.tableView.setContentOffset(offset, animated: true) } self.lastSelectedIndex = self.tabBarController!.selectedIndex } } // MARK: - UITableViewDelegate, UITableViewDataSource extension AHHomeViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return datasArray.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datasArray[section].ganks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellFromNib() as AHHomeCell cell.gankModel = datasArray[indexPath.section].ganks[indexPath.row] cell.indexPath = indexPath cell.moreButtonClickedClouse = { [unowned self] (indexPath: IndexPath) in let model = self.datasArray[indexPath.section].ganks[indexPath.row] model.isOpen = !model.isOpen self.tableView.reloadRows(at: [indexPath], with: .fade) } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let model = datasArray[indexPath.section].ganks[indexPath.row] return model.cellH } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerSection = AHHeaderSectionView.headerSectionView() headerSection.groupModel = datasArray[section] return headerSection } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.001 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let model = datasArray[indexPath.section].ganks[indexPath.row] let webView = AHHomeWebViewController() webView.urlString = model.url webView.gankModel = model webView.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(webView, animated: true) } } // MARK: - UIScrollViewDelegate extension AHHomeViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y let alpha = offsetY / (kScreen_H * 0.55 - kNavBarHeight) if offsetY > 0 { navBar.bgAlpha = alpha if offsetY >= kScreen_H * 0.55 - kNavBarHeight { self.navBar.showLongStyle() } } else { navBar.bgAlpha = 0.001 self.navBar.showShortStyle() } } }
mit
71e9eb28e1b6797d85680d44456b221c
33.55102
159
0.621146
4.988214
false
false
false
false
Intercambio/CloudService
CloudService/CloudService/URL.swift
1
1110
// // URL.swift // CloudService // // Created by Tobias Kräntzer on 02.02.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import Foundation extension URL { public func pathComponents(relativeTo baseURL: URL) -> [String]? { guard baseURL.scheme == scheme, baseURL.host == host, baseURL.user == user, baseURL.port == port else { return nil } let basePath = baseURL.pathComponents.count == 0 ? ["/"] : baseURL.pathComponents var path = pathComponents if path.starts(with: basePath) { path.removeFirst(basePath.count) return path } else { return nil } } public func makePath(relativeTo baseURL: URL) -> Path? { guard let components = pathComponents(relativeTo: baseURL) else { return nil } return Path(components: components) } public func appending(_ path: Path) -> URL { return appendingPathComponent(path.components.joined(separator: "/")) } }
gpl-3.0
afc57278012fc13227304c3ab6383364
25.357143
89
0.570009
4.710638
false
false
false
false
macc704/iKF
iKF/KFRegistrationViewController.swift
1
3294
// // KFRegistrationViewController.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-06-06. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit class KFRegistrationViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var host:String!; var registrations:Array<KFRegistration> = []; @IBOutlet var registrationCodeField : UITextField! @IBOutlet var registrationsPicker : UIPickerView! @IBOutlet weak var usernameLabel: UILabel! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() self.registrationsPicker.dataSource = self; self.registrationsPicker.delegate = self; self.navigationItem.title = "Welcome to " + host; self.usernameLabel.text = KFService.getInstance().currentUser.getFullName(); self.refreshRegistrations(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { self.navigationController!.setNavigationBarHidden(false, animated: animated); } override func viewWillDisappear(animated: Bool) { self.navigationController!.setNavigationBarHidden(true, animated: animated); } /* data source */ func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1; } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return registrations.count; } /* delegate */ func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{ let registration:KFRegistration = self.registrations[row]; return registration.community.name + " ( as " + registration.roleName + " )"; } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){ } @IBAction func enterButtonPressed(sender : AnyObject) { if(self.registrations.count <= 0){ KFAppUtils.showAlert("Error", msg: "No registration selected."); return; } let canvasViewController = KFCanvasViewController(); let row = self.registrationsPicker.selectedRowInComponent(0); canvasViewController.setKFRegistration(self.registrations[row]); self.presentViewController(canvasViewController, animated: true, completion: nil); } @IBAction func regsiterButtonPressed(sender : AnyObject) { let service = KFService.getInstance(); let res = service.registerCommunity(registrationCodeField.text); if(res == false){ KFAppUtils.showAlert("Error", msg: "Registration failed."); } self.refreshRegistrations(); } private func refreshRegistrations(){ let service = KFService.getInstance(); self.registrations = service.getRegistrations(); self.registrationsPicker.reloadAllComponents(); } }
gpl-2.0
5aaab9c9618296fe6fed0b4d5b864fa9
32.612245
108
0.672131
5.203791
false
false
false
false
Scorocode/scorocode-SDK-swift
todolist/Task.swift
1
502
// // Task.swift // todolist // // Created by Alexey Kuznetsov on 31/10/2016. // Copyright © 2016 ProfIT. All rights reserved. // import Foundation class Task { var id : String = "" var name : String = "" var isDone : Bool = false var isClose : Bool = false var comment : String = "" var bossComment : String = "" var detailed: String = "" var closeDate : Date = Date() var user : String = "" var username : String = "" init() { } }
mit
852099c180c17b1ec261a8ed44ce9912
18.269231
49
0.558882
3.795455
false
false
false
false
ksco/swift-algorithm-club-cn
Graph/Graph.playground/Pages/Adjacency Matrix.xcplaygroundpage/Contents.swift
1
3419
//: [Previous: Adjacency List](@previous) //: # Graph using an adjacency matrix //: //: In an adjacency matrix implementation, each vertex is given an index //: from `0..<V`, where `V` is the total number of vertices. The matrix is //: a 2D array, with each entry indicating if the corresponding two vertices //: are connected, and the weight of that edge. //: //: For example, if `matrix[3][5] = 4.6`, then vertex #3 is connected to //: vertex #5, with a weight of 4.6. Note that vertex #5 is not necessarily //: connected back to vertex #3 (that would be recorded in `matrix[5][3]`). public struct Vertex<T> { public var data: T private let index: Int } public struct Graph<T> { // If adjacencyMatrix[i][j] is not nil, then there is an edge from // vertex i to vertex j. private var adjacencyMatrix: [[Double?]] = [] // Adds a new vertex to the matrix. // Performance: possibly O(n^2) because of the resizing of the matrix. public mutating func createVertex(data: T) -> Vertex<T> { let vertex = Vertex(data: data, index: adjacencyMatrix.count) // Expand each existing row to the right one column. for i in 0..<adjacencyMatrix.count { adjacencyMatrix[i].append(nil) } // Add one new row at the bottom. let newRow = [Double?](count: adjacencyMatrix.count + 1, repeatedValue: nil) adjacencyMatrix.append(newRow) return vertex } // Creates a directed edge source -----> dest. public mutating func connect(sourceVertex: Vertex<T>, to destinationVertex: Vertex<T>, withWeight weight: Double = 0) { adjacencyMatrix[sourceVertex.index][destinationVertex.index] = weight } // Creates an undirected edge by making 2 directed edges: // some ----> other, and other ----> some. public mutating func connect(someVertex: Vertex<T>, symmetricallyWithVertex withVertex: Vertex<T>, withWeight weight: Double = 0) { adjacencyMatrix[someVertex.index][withVertex.index] = weight adjacencyMatrix[withVertex.index][someVertex.index] = weight } public func weightFrom(sourceVertex: Vertex<T>, toDestinationVertex: Vertex<T>) -> Double? { return adjacencyMatrix[sourceVertex.index][toDestinationVertex.index] } } //: ### Demo // Create the vertices var graph = Graph<Int>() let v1 = graph.createVertex(1) let v2 = graph.createVertex(2) let v3 = graph.createVertex(3) let v4 = graph.createVertex(4) let v5 = graph.createVertex(5) // Set up a cycle like so: // v5 // ^ // | (3.2) // | // v1 ---(1)---> v2 ---(1)---> v3 ---(4.5)---> v4 // ^ | // | V // ---------<-----------<---------(2.8)----<----| graph.connect(v1, to: v2, withWeight: 1.0) graph.connect(v2, to: v3, withWeight: 1.0) graph.connect(v3, to: v4, withWeight: 4.5) graph.connect(v4, to: v1, withWeight: 2.8) graph.connect(v2, to: v5, withWeight: 3.2) // Returns the weight of the edge from v1 to v2 (1.0) graph.weightFrom(v1, toDestinationVertex: v2) // Returns the weight of the edge from v1 to v3 (nil, since there is not an edge) graph.weightFrom(v1, toDestinationVertex: v3) // Returns the weight of the edge from v3 to v4 (4.5) graph.weightFrom(v3, toDestinationVertex: v4) // Returns the weight of the edge from v4 to v1 (2.8) graph.weightFrom(v4, toDestinationVertex: v1) print(graph.adjacencyMatrix)
mit
f1d288d764331fa2dc277e708172168f
33.535354
133
0.65019
3.460526
false
false
false
false
balazs630/Gross-Net-Calculator
GrossNetCalculator/Constants.swift
1
1119
// // Constants.swift // GrossNetCalculator // // Created by Horváth Balázs on 2017. 12. 10.. // Copyright © 2017. Horváth Balázs. All rights reserved. // import AppKit struct Constants { static let maxNumberOfTextFieldDigits = 9 } enum Key { static let gross = "gross" static let net = "net" } enum CurrencySign { static let forint = "Ft" static let dollar = "$" static let euro = "€" } extension UserDefaults { enum Key { static let isAppAlreadyLaunchedOnce = "isAppAlreadyLaunchedOnce" static let vatRate = "vatRate" static let currency = "currency" } } enum NotificationIdentifier { static let updateCurrencyLabels = NSNotification.Name("currencyLabelUpdaterNotification") static let updateTextFields = NSNotification.Name("textfieldUpdaterNotification") } extension NSStoryboard.Name { static let main = NSStoryboard.Name("Main") } extension NSStoryboard.SceneIdentifier { static let calculatorVC = NSStoryboard.SceneIdentifier("CalculatorVC") static let preferencesVC = NSStoryboard.SceneIdentifier("PreferencesVC") }
apache-2.0
101a7612ede0f1af9ef2c10414b1a7b5
23.173913
93
0.716727
4.34375
false
false
false
false
Yummypets/YPImagePicker
Source/Pages/Gallery/YPLibraryView.swift
1
6908
// // YPLibraryView.swift // YPImgePicker // // Created by Sacha Durand Saint Omer on 2015/11/14. // Copyright © 2015 Yummypets. All rights reserved. // import UIKit import Stevia import Photos internal final class YPLibraryView: UIView { // MARK: - Public vars internal let assetZoomableViewMinimalVisibleHeight: CGFloat = 50 internal var assetViewContainerConstraintTop: NSLayoutConstraint? internal let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical let v = UICollectionView(frame: .zero, collectionViewLayout: layout) v.backgroundColor = YPConfig.colors.libraryScreenBackgroundColor v.collectionViewLayout = layout v.showsHorizontalScrollIndicator = false v.alwaysBounceVertical = true return v }() internal lazy var assetViewContainer: YPAssetViewContainer = { let v = YPAssetViewContainer(frame: .zero, zoomableView: assetZoomableView) v.accessibilityIdentifier = "assetViewContainer" return v }() internal let assetZoomableView: YPAssetZoomableView = { let v = YPAssetZoomableView(frame: .zero) v.accessibilityIdentifier = "assetZoomableView" return v }() /// At the bottom there is a view that is visible when selected a limit of items with multiple selection internal let maxNumberWarningView: UIView = { let v = UIView() v.backgroundColor = .ypSecondarySystemBackground v.isHidden = true return v }() internal let maxNumberWarningLabel: UILabel = { let v = UILabel() v.font = YPConfig.fonts.libaryWarningFont return v }() // MARK: - Private vars private let line: UIView = { let v = UIView() v.backgroundColor = .ypSystemBackground return v }() /// When video is processing this bar appears private let progressView: UIProgressView = { let v = UIProgressView() v.progressViewStyle = .bar v.trackTintColor = YPConfig.colors.progressBarTrackColor v.progressTintColor = YPConfig.colors.progressBarCompletedColor ?? YPConfig.colors.tintColor v.isHidden = true v.isUserInteractionEnabled = false return v }() private let collectionContainerView: UIView = { let v = UIView() v.accessibilityIdentifier = "collectionContainerView" return v }() private var shouldShowLoader = false { didSet { DispatchQueue.main.async { self.assetViewContainer.squareCropButton.isEnabled = !self.shouldShowLoader self.assetViewContainer.multipleSelectionButton.isEnabled = !self.shouldShowLoader self.assetViewContainer.spinnerIsShown = self.shouldShowLoader self.shouldShowLoader ? self.hideOverlayView() : () } } } // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) setupLayout() clipsToBounds = true } required init?(coder: NSCoder) { super.init(coder: coder) fatalError("Only code layout.") } // MARK: - Public Methods // MARK: Overlay view func hideOverlayView() { assetViewContainer.itemOverlay?.alpha = 0 } // MARK: Loader and progress func fadeInLoader() { shouldShowLoader = true // Only show loader if full res image takes more than 0.5s to load. if #available(iOS 10.0, *) { Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { _ in if self.shouldShowLoader == true { UIView.animate(withDuration: 0.2) { self.assetViewContainer.spinnerView.alpha = 1 } } } } else { // Fallback on earlier versions UIView.animate(withDuration: 0.2) { self.assetViewContainer.spinnerView.alpha = 1 } } } func hideLoader() { shouldShowLoader = false assetViewContainer.spinnerView.alpha = 0 } func updateProgress(_ progress: Float) { progressView.isHidden = progress > 0.99 || progress == 0 progressView.progress = progress UIView.animate(withDuration: 0.1, animations: progressView.layoutIfNeeded) } // MARK: Crop Rect func currentCropRect() -> CGRect { let cropView = assetZoomableView let normalizedX = min(1, cropView.contentOffset.x &/ cropView.contentSize.width) let normalizedY = min(1, cropView.contentOffset.y &/ cropView.contentSize.height) let normalizedWidth = min(1, cropView.frame.width / cropView.contentSize.width) let normalizedHeight = min(1, cropView.frame.height / cropView.contentSize.height) return CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight) } // MARK: Curtain func refreshImageCurtainAlpha() { let imageCurtainAlpha = abs(assetViewContainerConstraintTop?.constant ?? 0) / (assetViewContainer.frame.height - assetZoomableViewMinimalVisibleHeight) assetViewContainer.curtain.alpha = imageCurtainAlpha } func cellSize() -> CGSize { var screenWidth: CGFloat = UIScreen.main.bounds.width if UIDevice.current.userInterfaceIdiom == .pad && YPImagePickerConfiguration.widthOniPad > 0 { screenWidth = YPImagePickerConfiguration.widthOniPad } let size = screenWidth / 4 * UIScreen.main.scale return CGSize(width: size, height: size) } // MARK: - Private Methods private func setupLayout() { subviews( collectionContainerView.subviews( collectionView ), line, assetViewContainer.subviews( assetZoomableView ), progressView, maxNumberWarningView.subviews( maxNumberWarningLabel ) ) collectionContainerView.fillContainer() collectionView.fillHorizontally().bottom(0) assetViewContainer.Bottom == line.Top line.height(1) line.fillHorizontally() assetViewContainer.top(0).fillHorizontally().heightEqualsWidth() self.assetViewContainerConstraintTop = assetViewContainer.topConstraint assetZoomableView.fillContainer().heightEqualsWidth() assetZoomableView.Bottom == collectionView.Top assetViewContainer.sendSubviewToBack(assetZoomableView) progressView.height(5).fillHorizontally() progressView.Bottom == line.Top |maxNumberWarningView|.bottom(0) maxNumberWarningView.Top == safeAreaLayoutGuide.Bottom - 40 maxNumberWarningLabel.centerHorizontally().top(11) } }
mit
cdd16908ed72deda9a5a4b9cda52efe6
32.857843
108
0.643695
5.067498
false
false
false
false
tspecht/SwiftLint
Source/SwiftLintFramework/Rules/FunctionBodyLengthRule.swift
1
3368
// // FunctionBodyLengthRule.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework import SwiftXPC public struct FunctionBodyLengthRule: ASTRule, ParameterizedRule { public init() {} public let identifier = "function_body_length" public let parameters = [ RuleParameter(severity: .VeryHigh, value: 500) ] public func validateFile(file: File) -> [StyleViolation] { return validateFile(file, dictionary: file.structure.dictionary) } public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] { return (dictionary["key.substructure"] as? XPCArray ?? []).flatMap { subItem in var violations = [StyleViolation]() if let subDict = subItem as? XPCDictionary, let kindString = subDict["key.kind"] as? String, let kind = flatMap(kindString, { SwiftDeclarationKind(rawValue: $0) }) { violations.extend(validateFile(file, dictionary: subDict)) violations.extend(validateFile(file, kind: kind, dictionary: subDict)) } return violations } } public func validateFile(file: File, kind: SwiftDeclarationKind, dictionary: XPCDictionary) -> [StyleViolation] { let functionKinds: [SwiftDeclarationKind] = [ .FunctionAccessorAddress, .FunctionAccessorDidset, .FunctionAccessorGetter, .FunctionAccessorMutableaddress, .FunctionAccessorSetter, .FunctionAccessorWillset, .FunctionConstructor, .FunctionDestructor, .FunctionFree, .FunctionMethodClass, .FunctionMethodInstance, .FunctionMethodStatic, .FunctionOperator, .FunctionSubscript ] if !contains(functionKinds, kind) { return [] } if let offset = flatMap(dictionary["key.offset"] as? Int64, { Int($0) }), let bodyOffset = flatMap(dictionary["key.bodyoffset"] as? Int64, { Int($0) }), let bodyLength = flatMap(dictionary["key.bodylength"] as? Int64, { Int($0) }) { let location = Location(file: file, offset: offset) let startLine = file.contents.lineAndCharacterForByteOffset(bodyOffset) let endLine = file.contents.lineAndCharacterForByteOffset(bodyOffset + bodyLength) for parameter in reverse(parameters) { if let startLine = startLine?.line, let endLine = endLine?.line where endLine - startLine > parameter.value { return [StyleViolation(type: .Length, location: location, severity: parameter.severity, reason: "Function body should be span 40 lines or less: currently spans " + "\(endLine - startLine) lines")] } } } return [] } public let example = RuleExample( ruleName: "Function Body Length Rule", ruleDescription: "This rule checks whether your function bodies are less than 40 lines.", nonTriggeringExamples: [], triggeringExamples: [], showExamples: false ) }
mit
bc646a92365c33d2f131379a4a8aa256
37.712644
99
0.600653
5.110774
false
false
false
false
RemyDCF/tpg-offline
tpg offline/Settings/SettingsTableViewController.swift
1
7410
// // SettingsTableViewController.swift // tpg offline // // Created by Rémy Da Costa Faro on 16/08/2017. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit import Alamofire import SafariServices import MessageUI #if !arch(i386) && !arch(x86_64) import NetworkExtension #endif class SettingsTableViewController: UITableViewController { var settings: [[Setting]] = [] var titles = [ Text.notifications, Text.application, Text.project ] override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: App.textColor] } if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, version != UserDefaults.standard.string(forKey: "lastVersion"), UserDefaults.standard.string(forKey: "lastVersion") != nil { self.performSegue(withIdentifier: "showNewFeatures", sender: self) } navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: App.textColor] // Notifications self.settings.append([ Setting(Text.pendingNotifications, icon: #imageLiteral(resourceName: "cel-bell"), action: { (_) in self.performSegue(withIdentifier: "showPendingNotifications", sender: self) }) ]) // Application self.settings.append([ Setting(Text.defaultTabOnStartup, icon: #imageLiteral(resourceName: "menuRounded"), action: { (_) in self.performSegue(withIdentifier: "showDefaultTab", sender: self) }), Setting(Text.reorderStops, icon: #imageLiteral(resourceName: "reorder"), action: { (_) in self.performSegue(withIdentifier: "showReorderStopsView", sender: self) }), Setting(Text.updateOfflineData, icon: #imageLiteral(resourceName: "download"), action: { (_) in App.log("Settings: Update Departures") self.performSegue(withIdentifier: "showUpdateDepartures", sender: self) }), Setting(Text.darkMode, icon: #imageLiteral(resourceName: "moon"), action: { (_) in self.performSegue(withIdentifier: "showDarkMode", sender: self) }), Setting(Text.privacy, icon: #imageLiteral(resourceName: "circuit"), action: { (_) in self.performSegue(withIdentifier: "showPrivacy", sender: self) }) ]) #if !arch(i386) && !arch(x86_64) self.settings[1].append(Setting(Text.connectWifi, icon: #imageLiteral(resourceName: "wifi"), action: { (_) in if #available(iOS 11.0, *) { let configuration = NEHotspotConfiguration(ssid: "tpg-freeWiFi") configuration.joinOnce = false NEHotspotConfigurationManager.shared.apply(configuration, completionHandler: { (error) in print(error ?? "") }) } else { print("How did you ended here ?") } })) #endif // The project self.settings.append([ Setting(Text.giveFeedback, icon: #imageLiteral(resourceName: "megaphone"), action: { ( _ ) in App.log("Settings: Give feedback") let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients(["[email protected]"]) mailComposerVC.setSubject(Text.tpgoffline) mailComposerVC.setMessageBody("", isHTML: false) if MFMailComposeViewController.canSendMail() { self.present(mailComposerVC, animated: true, completion: nil) } }), Setting(Text.lastFeatures, icon: #imageLiteral(resourceName: "flag"), action: { (_) in self.performSegue(withIdentifier: "showNewFeatures", sender: self) }), Setting(Text.credits, icon: #imageLiteral(resourceName: "crows"), action: { (_) in self.performSegue(withIdentifier: "showCredits", sender: self) }), Setting(Text.githubWebpage, icon: #imageLiteral(resourceName: "github"), action: { (_) in let vc = SFSafariViewController(url: URL(string: URL.github)!, entersReaderIfAvailable: false) if App.darkMode, #available(iOS 10.0, *) { vc.preferredBarTintColor = .black } vc.delegate = self self.present(vc, animated: true) }) ]) if App.darkMode { self.tableView.backgroundColor = .black self.navigationController?.navigationBar.barStyle = .black self.tableView.separatorColor = App.separatorColor } ColorModeManager.shared.addColorModeDelegate(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSections(in tableView: UITableView) -> Int { return self.settings.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.settings[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell", for: indexPath) let setting = self.settings[indexPath.section][indexPath.row] cell.textLabel?.text = setting.title cell.textLabel?.textColor = App.textColor cell.detailTextLabel?.text = "" cell.detailTextLabel?.textColor = App.textColor cell.backgroundColor = App.cellBackgroundColor cell.accessoryType = .disclosureIndicator cell.imageView?.image = setting.icon.maskWith(color: App.textColor) if App.darkMode { let selectedView = UIView() selectedView.backgroundColor = .black cell.selectedBackgroundView = selectedView } else { let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) cell.selectedBackgroundView = selectedView } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: true) let setting = self.settings[indexPath.section][indexPath.row] setting.action(setting) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return titles[section] } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return (section + 1) == tableView.numberOfSections ? Text.tpgofflineVersion : nil } deinit { ColorModeManager.shared.removeColorModeDelegate(self) } } extension SettingsTableViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { // swiftlint:disable:previous line_length controller.dismiss(animated: true, completion: nil) } } extension SettingsTableViewController: SFSafariViewControllerDelegate { func safariViewControllerDidFinish(_ controller: SFSafariViewController) { dismiss(animated: true) } }
mit
be6a5cf26405a9f9afe9ed8f7c30c126
35.131707
106
0.667612
4.938
false
false
false
false
DrabWeb/Keijiban
Keijiban/Keijiban/KJColoredTitleButton.swift
1
1436
// // KJColoredTitleButton.swift // Keijiban // // Created by Seth on 2016-06-06. // import Cocoa class KJColoredTitleButton: NSButton { /// The color for this button's title var titleColor : NSColor = NSColor.blackColor() { didSet { // Update the title color updateTitleColor(); } }; override var title : String { didSet { // Update the title color updateTitleColor(); } } /// Updates the title color for this button func updateTitleColor() { /// The paragraph style for the buttons title let titleParagraphStyle : NSMutableParagraphStyle = NSMutableParagraphStyle(); // Set the title alignment to the button's title alignment titleParagraphStyle.alignment = self.alignment; /// The attributes dictionary for the title attributed string let titleAttributesDictionary : [String:AnyObject]? = [NSForegroundColorAttributeName:self.titleColor, NSFontAttributeName:self.font!, NSParagraphStyleAttributeName:titleParagraphStyle]; /// The attributed string for the title let titleAttributedString : NSAttributedString = NSAttributedString(string: self.title, attributes: titleAttributesDictionary); // Set the title to the created attributed string self.attributedTitle = titleAttributedString; } }
gpl-3.0
7fd9d1b99a54903a67cdacb33a65e242
32.395349
194
0.655989
5.837398
false
false
false
false
radex/RxExperiments
viewmodels/GitHubSignupViewModel4.swift
1
3617
import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class GitHubSignupViewModel4 { // MARK: - Inputs struct Props { var username = "" var password = "" var repeatPassword = "" } // MARK: - Internal state private struct State { var usernameValidation: ValidationResult = .empty var signingIn = false } // MARK: - Outputs typealias Output = ( usernameValid: ValidationResult, passwordValid: ValidationResult, repeatPasswordValid: ValidationResult, signupEnabled: Bool, signingIn: Bool ) // MARK: - Initialize typealias Renderer = (Output) -> Void private let renderer: Renderer init(render: @escaping Renderer) { self.renderer = render rxSetup() } // MARK: - Logic private func rxSetup() { username_rx.asObservable() .distinctUntilChanged() .flatMapLatest { username in // those should all be [unowned self] or weak return self.validator.validateUsername(username) .observeOn(MainScheduler.instance) .catchErrorJustReturn(.failed(message: "Error contacting server")) } .subscribe(onNext: { self.state.usernameValidation = $0 }) .addDisposableTo(disposeBag) } private func outputState() -> Output { let usernameValidation = state.usernameValidation let passwordValidation = validator.validatePassword(props.password) let repeatPasswordValidation = validator.validateRepeatedPassword(props.password, repeatedPassword: props.repeatPassword) let signupEnabled = usernameValidation.isValid && passwordValidation.isValid && repeatPasswordValidation.isValid && !state.signingIn let signingIn = state.signingIn return (usernameValidation, passwordValidation, repeatPasswordValidation, signupEnabled, signingIn) } // MARK: - Actions func signIn() { state.signingIn = true API.signup(props.username, password: props.password) .observeOn(MainScheduler.instance) .catchErrorJustReturn(false) .subscribe(onNext: { [unowned self] signedIn in self.state.signingIn = false print("Signed in? \(signedIn)") }) .addDisposableTo(disposeBag) } // MARK: - Dependencies private let validator = GitHubDefaultValidationService.sharedValidationService private let API = GitHubDefaultAPI.sharedAPI private let wireframe = DefaultWireframe.sharedInstance // MARK: - Implementation var props = Props() { didSet { username_rx.value = props.username triggerOutput() } } private var state = State() { didSet { triggerOutput() } } private let username_rx = Variable("") // MARK: - Infrastructure private var disposeBag = DisposeBag() private var outputScheduled = false private func triggerOutput() { guard !outputScheduled else { return } DispatchQueue.main.async { [weak self] in guard let _self = self else { return } _self.outputScheduled = false _self.renderer(_self.outputState()) } outputScheduled = true } func end() { disposeBag = DisposeBag() } }
mit
54645f9033337ec4bdaf7546e8832865
27.03876
129
0.594692
5.374443
false
false
false
false
wantedly/ReactKit
ReactKitTests/OperationTests.swift
2
46340
// // OperationTests.swift // ReactKitTests // // Created by Yasuhiro Inami on 2015/04/04. // Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. // import ReactKit import SwiftTask import Async import XCTest class OperationTests: _TestCase { //-------------------------------------------------- // MARK: - Single Stream Operations //-------------------------------------------------- // MARK: transforming func testMap() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> map { (value: AnyObject?) -> String? in return (value as! String).uppercaseString } // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "HOGE") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "FUGA") expect.fulfill() } self.wait() } func testMap2() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> map2 { (oldValue: AnyObject??, newValue: AnyObject?) -> String? in let oldString = (oldValue as? String) ?? "empty" return "\(oldString) -> \(newValue as! String)" } // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "empty -> hoge") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "hoge -> fuga") expect.fulfill() } self.wait() } /// a.k.a `Rx.scan` func testMapAccumulate() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let stream = KVO.stream(obj1, "value") |> mapAccumulate([]) { accumulatedValue, newValue -> [String] in return accumulatedValue + [newValue as! String] } var result: [String]? // REACT stream ~> { result = $0 } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(result!, [ "hoge" ]) obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(result!, [ "hoge", "fuga" ]) expect.fulfill() } self.wait() } func testFlatMapMerge() { // NOTE: this is async test if !self.isAsync { return } let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> flatMap(.Merge) { (value: AnyObject?) -> Stream<AnyObject?> in // delay sending value for 0.01 sec return NSTimer.stream(timeInterval: 0.01, repeats: false) { _ in value } } // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "initial", "`obj2.value` should NOT be updated because `stream` is delayed.") // wait for "hoge" to arrive... Async.main(after: 0.1) { XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "hoge", "`obj2.value` should be updated because delayed `stream` message arrived.") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "hoge", "`obj2.value` should NOT be updated because `stream` is delayed.") } // wait for "fuga" to arrive... Async.main(after: 0.2 + SAFE_DELAY) { XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "fuga", "`obj2.value` should be updated because delayed `stream` message arrived.") expect.fulfill() } } self.wait() } func testFlatMapMerge_upstream_fulfill() { // NOTE: this is async test if !self.isAsync { return } let expect = self.expectationWithDescription(__FUNCTION__) let obj2 = MyObject() let stream = NSTimer.stream(timeInterval: 0.01, repeats: false) { _ in "hoge" } |> flatMap(.Merge) { (value: AnyObject?) -> Stream<AnyObject?> in // delay sending value for 0.01 sec return NSTimer.stream(timeInterval: 0.01, repeats: false) { _ in value } } // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj2.value, "initial") self.perform { XCTAssertEqual(obj2.value, "initial", "`obj2.value` should NOT be updated because `stream` is delayed.") // wait for "hoge" to arrive... Async.main(after: 0.1) { XCTAssertEqual(obj2.value, "hoge", "`obj2.value` should be updated because delayed `stream` message arrived.") expect.fulfill() } } self.wait() } func testBuffer() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let stream: Stream<[AnyObject?]> = KVO.stream(obj1, "value") |> buffer(3) var result: String? = "no result" // REACT stream ~> { (buffer: [AnyObject?]) in let buffer_: [String] = buffer.map { $0 as! String } result = "-".join(buffer_) } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(result!, "no result", "`result` should NOT be updated because `stream`'s newValue is buffered.") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(result!, "no result", "`result` should NOT be updated because `stream`'s newValue is buffered.") obj1.value = "piyo" XCTAssertEqual(obj1.value, "piyo") XCTAssertEqual(result!, "hoge-fuga-piyo", "`result` should be updated with buffered values because buffer reached maximum count.") obj1.value = "foo" XCTAssertEqual(obj1.value, "foo") XCTAssertEqual(result!, "hoge-fuga-piyo", "`result` should NOT be updated because `stream`'s newValue is buffered.") expect.fulfill() } self.wait() } func testBufferBy() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let trigger = MyObject() let triggerStream = KVO.stream(trigger, "value") let stream: Stream<[AnyObject?]> = KVO.stream(obj1, "value") |> bufferBy(triggerStream) var result: String? = "no result" // REACT stream ~> { (buffer: [AnyObject?]) in let buffer_: [String] = buffer.map { $0 as! String } result = "-".join(buffer_) } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(result!, "no result", "`result` should NOT be updated because `stream`'s newValue is buffered but `triggerStream` is not triggered yet.") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(result!, "no result", "`result` should NOT be updated because `stream`'s newValue is buffered but `triggerStream` is not triggered yet.") trigger.value = "DUMMY" // fire triggerStream XCTAssertEqual(result!, "hoge-fuga", "`result` should be updated with buffered values.") trigger.value = "DUMMY2" // fire triggerStream XCTAssertEqual(result!, "", "`result` should be updated with NO buffered values.") expect.fulfill() } self.wait() } func testGroupBy() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() // group by `key = countElement(value)` let stream: Stream<(Int, Stream<AnyObject?>)> = KVO.stream(obj1, "value") |> groupBy { count($0! as! String) } var lastKey: Int? var lastValue: String? // REACT stream ~> { (key: Int, groupedStream: Stream<AnyObject?>) in lastKey = key // REACT groupedStream ~> { value in lastValue = value as? String return } } println("*** Start ***") XCTAssertNil(lastKey) XCTAssertNil(lastValue) self.perform { obj1.value = "hoge" XCTAssertEqual(lastKey!, 4) XCTAssertEqual(lastValue!, "hoge") obj1.value = "fuga" XCTAssertEqual(lastKey!, 4) XCTAssertEqual(lastValue!, "fuga") obj1.value = "foo" XCTAssertEqual(lastKey!, 3) XCTAssertEqual(lastValue!, "foo") obj1.value = "&" XCTAssertEqual(lastKey!, 1) XCTAssertEqual(lastValue!, "&") obj1.value = "bar" XCTAssertEqual(lastKey!, 1, "`groupedStream` with key=3 is already emitted, so `lastKey` will not be updated.") XCTAssertEqual(lastValue!, "bar") expect.fulfill() } self.wait() } // MARK: filtering func testFilter() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> filter { (value: AnyObject?) -> Bool in return value as! String == "fuga" } // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "initial", "obj2.value should not be updated because stream is not sent via filter().") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "fuga") expect.fulfill() } self.wait() } func testFilter2() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() // NOTE: this is distinct stream let stream = KVO.stream(obj1, "value") |> filter2 { (oldValue: AnyObject??, newValue: AnyObject?) -> Bool in // don't filter for first value if oldValue == nil { return true } return oldValue as! String != newValue as! String } var count = 0 // REACT stream ~> { _ in count++; return } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(count, 1) obj1.value = "fuga" XCTAssertEqual(count, 2) obj1.value = "fuga" // same value as before XCTAssertEqual(count, 2, "`count` should NOT be incremented because previous value was same (should be distinct)") obj1.value = "hoge" XCTAssertEqual(count, 3, "`count` should be incremented.") expect.fulfill() } self.wait() } func testTake() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> take(1) // only take 1 event // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "hoge") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "hoge", "obj2.value should not be updated because stream is finished via take().") expect.fulfill() } self.wait() } func testTake_fulfilled() { let expect = self.expectationWithDescription(__FUNCTION__) var progressCount = 0 var successCount = 0 let obj1 = MyObject() let sourceStream = KVO.stream(obj1, "value") let takeStream = sourceStream |> take(1) // only take 1 event // REACT ^{ _ in progressCount++; return } <~ takeStream // success takeStream.success { successCount++ } println("*** Start ***") XCTAssertEqual(progressCount, 0) XCTAssertEqual(successCount, 0) self.perform { obj1.value = "hoge" XCTAssertEqual(progressCount, 1) XCTAssertEqual(successCount, 1) obj1.value = "fuga" XCTAssertEqual(progressCount, 1, "`progress()` will not be invoked because already fulfilled via `take(1)`.") XCTAssertEqual(successCount, 1) expect.fulfill() } self.wait() } func testTake_rejected() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let sourceStream = KVO.stream(obj1, "value") let takeStream = sourceStream |> take(1) // only take 1 event // failure takeStream.failure { errorInfo -> Void in XCTAssertEqual(errorInfo.error!.domain, ReactKitError.Domain, "`sourceStream` is cancelled before any progress, so `takeStream` should fail.") XCTAssertEqual(errorInfo.error!.code, ReactKitError.CancelledByUpstream.rawValue) XCTAssertFalse(errorInfo.isCancelled, "Though `sourceStream` is cancelled, `takeStream` is rejected rather than cancelled.") expect.fulfill() } takeStream.resume() // NOTE: resume manually self.perform { [weak sourceStream] in sourceStream?.cancel() return } self.wait() } func testTakeUntil() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stopper = MyObject() let stoppingStream = KVO.stream(stopper, "value") // store stoppingStream to live until end of runloop let stream = KVO.stream(obj1, "value") |> takeUntil(stoppingStream) // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "hoge") stopper.value = "DUMMY" // fire stoppingStream obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "hoge", "obj2.value should not be updated because stream is stopped via takeUntil(stoppingStream).") expect.fulfill() } self.wait() } func testSkip() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> skip(1) // skip 1 event // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "initial", "obj2.value should not be changed due to `skip(1)`.") obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "fuga", "obj2.value should be updated because already skipped once.") expect.fulfill() } self.wait() } func testSkipUntil() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stopper = MyObject() let startingStream = KVO.stream(stopper, "value") let stream = KVO.stream(obj1, "value") |> skipUntil(startingStream) // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "initial", "obj2.value should not be changed due to `skipUntil()`.") stopper.value = "DUMMY" // fire startingStream obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "fuga", "obj2.value should be updated because `startingStream` is triggered so that `skipUntil(startingStream)` should no longer skip.") expect.fulfill() } self.wait() } func testSample() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let sampler = MyObject() let samplingStream = KVO.stream(sampler, "value") let stream = KVO.stream(obj1, "value") |> sample(samplingStream) var reactCount = 0 // REACT (obj2, "value") <~ stream stream ~> { _ in reactCount++; return } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { sampler.value = "DUMMY" // fire samplingStream XCTAssertEqual(obj2.value, "initial", "`obj2.value` should not be updated because `obj1.value` has not sent yet.") XCTAssertEqual(reactCount, 0) obj1.value = "hoge" XCTAssertEqual(obj2.value, "initial", "`obj2.value` should not be updated because although `obj1` has changed, `samplingStream` has not triggered yet.") XCTAssertEqual(reactCount, 0) sampler.value = "DUMMY" XCTAssertEqual(obj2.value, "hoge", "`obj2.value` should be updated, triggered by `samplingStream` using latest `obj1.value`.") XCTAssertEqual(reactCount, 1) sampler.value = "DUMMY" XCTAssertEqual(obj2.value, "hoge") XCTAssertEqual(reactCount, 2) obj1.value = "fuga" obj1.value = "piyo" sampler.value = "** check ** " XCTAssertEqual(obj2.value, "piyo") XCTAssertEqual(reactCount, 3) expect.fulfill() } self.wait() } func testDistinct() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> map { (($0 as? String) ?? "") } // create stream with Hashable value-type for `distinct()` |> distinct |> map { $0 as String? } // convert: Stream<String> -> Stream<String?> var reactCount = 0 // REACT (obj2, "value") <~ stream stream ~> { _ in reactCount++; return } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj2.value, "hoge") XCTAssertEqual(reactCount, 1) obj1.value = "fuga" XCTAssertEqual(obj2.value, "fuga") XCTAssertEqual(reactCount, 2) obj1.value = "hoge" XCTAssertEqual(obj2.value, "fuga") XCTAssertEqual(reactCount, 2, "`reactCount` should not be incremented because `hoge` is already sent thus filtered by `distinct()` method.") obj1.value = "fuga" XCTAssertEqual(obj2.value, "fuga") XCTAssertEqual(reactCount, 2, "`reactCount` should not be incremented because `fuga` is already sent thus filtered by `distinct()` method.") obj1.value = "piyo" XCTAssertEqual(obj2.value, "piyo") XCTAssertEqual(reactCount, 3) expect.fulfill() } self.wait() } func testDistinctUntilChanged() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> map { (($0 as? String) ?? "") } |> distinctUntilChanged |> map { $0 as String? } var reactCount = 0 // REACT (obj2, "value") <~ stream stream ~> { _ in reactCount++; return } println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj2.value, "hoge") XCTAssertEqual(reactCount, 1) obj1.value = "fuga" XCTAssertEqual(obj2.value, "fuga") XCTAssertEqual(reactCount, 2) obj1.value = "fuga" XCTAssertEqual(obj2.value, "fuga") XCTAssertEqual(reactCount, 2, "`reactCount` should not be incremented because `fuga` is sent last time thus filtered by `distinctUntilChanged()` method.") obj1.value = "hoge" XCTAssertEqual(obj2.value, "hoge") XCTAssertEqual(reactCount, 3, "`hoge` is already sent but not at last time, so it should not be filtered by `distinctUntilChanged()`.") expect.fulfill() } self.wait() } // MARK: combining func testStartWith() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let stream1 = KVO.stream(obj1, "value") var bundledStream = stream1 |> startWith("start!") // REACT (obj2, "value") <~ bundledStream println("*** Start ***") self.perform { // NOTE: not "initial" XCTAssertEqual(obj2.value, "start!", "`obj2.value` should not stay with 'initial' & `startWith()`'s initialValue should be set.") obj1.value = "test1" XCTAssertEqual(obj2.value, "test1") expect.fulfill() } self.wait() } func testCombineLatest() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let obj3 = MyObject() let stream1 = KVO.stream(obj1, "value") let stream2 = KVO.stream(obj2, "number") let bundledStream = stream1 |> combineLatest(stream2) |> map { (values: [AnyObject?]) -> String? in let value0: AnyObject = values[0]! let value1: AnyObject = values[1]! return "\(value0)-\(value1)" } // REACT (obj3, "value") <~ bundledStream println("*** Start ***") XCTAssertEqual(obj3.value, "initial") self.perform { obj1.value = "test1" XCTAssertEqual(obj3.value, "initial") obj1.value = "test2" XCTAssertEqual(obj3.value, "initial") obj2.value = "test3" XCTAssertEqual(obj3.value, "initial", "`obj3.value` should NOT be updated because `bundledStream` doesn't react to `obj2.value` (reacts to `obj2.number`).") obj2.number = 123 XCTAssertEqual(obj3.value, "test2-123") expect.fulfill() } self.wait() } func testZip() { if self.isAsync { return } let expect = self.expectationWithDescription(__FUNCTION__) // create streams which will never be fulfilled/rejected let stream1: Stream<Any> = Stream.sequence([0, 1, 2, 3, 4]) |> concat(Stream.never()) let stream2: Stream<Any> = Stream.sequence(["A", "B", "C"]) |> concat(Stream.never()) var bundledStream = stream1 |> zip(stream2) |> map { (values: [Any]) -> String in let valueStrings = values.map { "\($0)" } return "-".join(valueStrings) } println("*** Start ***") var reactCount = 0 // REACT bundledStream ~> { value in reactCount++ println(value) switch reactCount { case 1: XCTAssertEqual(value, "0-A") case 2: XCTAssertEqual(value, "1-B") case 3: XCTAssertEqual(value, "2-C") default: XCTFail("Should never reach here.") } } bundledStream.then { _ -> Void in XCTAssertEqual(reactCount, 3) expect.fulfill() } // force-cancel after zip-test complete Async.main(after: 0.1) { bundledStream.cancel() } self.wait() XCTAssertEqual(reactCount, 3) } // see also: `testRetry()` func testCatch() { let expect = self.expectationWithDescription(__FUNCTION__) var buffer = [Int]() var streamProducer: Stream<Int>.Producer = { Stream.sequence(1...3) } if self.isAsync { streamProducer = streamProducer |>> interval(0.1) } let errorStream = streamProducer() |> concat(Stream.error(NSError(domain: "test", code: -1, userInfo: nil))) let recoveryStream = errorStream |> catch { errorInfo -> Stream<Int> in return streamProducer() } println("*** Start ***") // REACT recoveryStream ~> { value in buffer.append(value) } self.perform(after: 0.5) { expect.fulfill() } self.wait() XCTAssertEqual(buffer, [1, 2, 3, 1, 2, 3], "`recoveryStream` should handle `1 -> 2 -> 3 -> recovery from error -> 1 -> 2 -> 3 -> fulfilled`.") XCTAssertEqual(errorStream.state, TaskState.Rejected) XCTAssertEqual(recoveryStream.state, TaskState.Fulfilled) } func testCatch_noCatch() { let expect = self.expectationWithDescription(__FUNCTION__) var buffer = [Int]() var streamProducer: Stream<Int>.Producer = { Stream.sequence(1...3) } if self.isAsync { streamProducer = streamProducer |>> interval(0.1) } let errorStream = streamProducer() // |> concat(Stream.error(NSError(domain: "test", code: -1, userInfo: nil))) // comment-out: not attaching error at end for testing let recoveryStream = errorStream |> catch { errorInfo -> Stream<Int> in return streamProducer() } println("*** Start ***") // REACT recoveryStream ~> { value in buffer.append(value) } self.perform(after: 0.5) { expect.fulfill() } self.wait() XCTAssertEqual(buffer, [1, 2, 3], "`recoveryStream` won't catch any error to recover, so it will send `1 -> 2 -> 3 -> fulfilled`.") XCTAssertEqual(errorStream.state, TaskState.Fulfilled) XCTAssertEqual(recoveryStream.state, TaskState.Fulfilled) } // MARK: timing func testInterval() { if !self.isAsync { return } let expect = self.expectationWithDescription(__FUNCTION__) let faster: NSTimeInterval = 0.1 let stream = Stream.sequence(0...2) |> interval(1.0 * faster) var results = [Int]() // REACT stream ~> { value in results += [value] println("[REACT] value = \(value)") } println("*** Start ***") XCTAssertEqual(results, []) self.perform() { Async.main(after: 0.01 * faster) { XCTAssertEqual(results, [0]) } Async.main(after: 1.01 * faster) { XCTAssertEqual(results, [0, 1]) } Async.main(after: 2.01 * faster) { XCTAssertEqual(results, [0, 1, 2]) expect.fulfill() } } self.wait() } func testThrottle() { let expect = self.expectationWithDescription(__FUNCTION__) let timeInterval: NSTimeInterval = 0.2 let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> throttle(timeInterval) // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "hoge") obj1.value = "hoge2" XCTAssertEqual(obj1.value, "hoge2") XCTAssertEqual(obj2.value, "hoge", "obj2.value should not be updated because stream is throttled to \(timeInterval) sec.") // delay for `timeInterval`*1.05 sec dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1_050_000_000*timeInterval)), dispatch_get_main_queue()) { obj1.value = "fuga" XCTAssertEqual(obj1.value, "fuga") XCTAssertEqual(obj2.value, "fuga") expect.fulfill() } } self.wait() } func testDebounce() { let expect = self.expectationWithDescription(__FUNCTION__) let timeInterval: NSTimeInterval = 0.2 let obj1 = MyObject() let obj2 = MyObject() let stream = KVO.stream(obj1, "value") |> debounce(timeInterval) // REACT (obj2, "value") <~ stream println("*** Start ***") XCTAssertEqual(obj1.value, "initial") XCTAssertEqual(obj2.value, "initial") self.perform { obj1.value = "hoge" XCTAssertEqual(obj1.value, "hoge") XCTAssertEqual(obj2.value, "initial", "obj2.value should not be updated because of debounce().") Async.background(after: timeInterval/2) { XCTAssertEqual(obj2.value, "initial", "obj2.value should not be updated because it is still debounced.") } Async.background(after: timeInterval+0.1) { XCTAssertEqual(obj2.value, "hoge", "obj2.value should be updated after debouncing time.") expect.fulfill() } } self.wait() } // MARK: collecting func testReduce() { let expect = self.expectationWithDescription(__FUNCTION__) var stream = Stream.sequence([1, 2, 3]) if self.isAsync { stream = stream |> delay(0.01) } stream = stream |> reduce(100) { $0 + $1 } var result: Int? // REACT stream ~> { result = $0 } println("*** Start ***") self.perform(after: 0.1) { XCTAssertEqual(result!, 106, "`result` should be 106 (100 + 1 + 2 + 3).") expect.fulfill() } self.wait() } //-------------------------------------------------- // MARK: - Array Streams Operations //-------------------------------------------------- // // NOTE: // `merge2All()` works like both `Rx.merge()` and `Rx.combineLatest()`. // This test demonstrates `combineLatest` example. // func testMerge2All() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let obj3 = MyObject() let stream1 = KVO.stream(obj1, "value") let stream2 = KVO.stream(obj2, "number") let bundledStream = [stream1, stream2] |> merge2All |> map { (values: [AnyObject??], _) -> String? in let value0: AnyObject = (values[0] ?? "notYet") ?? "nil" let value1: AnyObject = (values[1] ?? "notYet") ?? "nil" return "\(value0)-\(value1)" } // REACT (obj3, "value") <~ bundledStream println("*** Start ***") self.perform { XCTAssertEqual(obj3.value, "initial") obj1.value = "test1" XCTAssertEqual(obj3.value, "test1-notYet") obj1.value = "test2" XCTAssertEqual(obj3.value, "test2-notYet") obj2.value = "test3" XCTAssertEqual(obj3.value, "test2-notYet", "`obj3.value` should NOT be updated because `bundledStream` doesn't react to `obj2.value` (reacts to `obj2.number`).") obj2.number = 123 XCTAssertEqual(obj3.value, "test2-123") expect.fulfill() } self.wait() } func testCombineLatestAll() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let obj3 = MyObject() let stream1 = KVO.stream(obj1, "value") let stream2 = KVO.stream(obj2, "number") let combinedStream = [stream1, stream2] |> combineLatestAll |> map { (values: [AnyObject?]) -> String? in let value0: AnyObject = (values[0] ?? "nil") let value1: AnyObject = (values[1] ?? "nil") return "\(value0)-\(value1)" } // REACT (obj3, "value") <~ combinedStream println("*** Start ***") self.perform { XCTAssertEqual(obj3.value, "initial") obj1.value = "test1" XCTAssertEqual(obj3.value, "initial", "`combinedStream` should not send value because only `obj1.value` is changed.") obj1.value = "test2" XCTAssertEqual(obj3.value, "initial", "`combinedStream` should not send value because only `obj1.value` is changed.") obj2.number = 123 XCTAssertEqual(obj3.value, "test2-123", "`obj3.value` should be updated for the first time because both `obj1.value` & `obj2.number` has been changed.") obj2.number = 456 XCTAssertEqual(obj3.value, "test2-456") obj1.value = "test4" XCTAssertEqual(obj3.value, "test4-456") expect.fulfill() } self.wait() } func testConcatInner() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let stream1: Stream<AnyObject?> = NSTimer.stream(timeInterval: 0.1, userInfo: nil, repeats: false) { _ in "Next" } let stream2: Stream<AnyObject?> = NSTimer.stream(timeInterval: 0.3, userInfo: nil, repeats: false) { _ in 123 } var concatStream = [stream1, stream2] |> concatInner |> map { (value: AnyObject?) -> String? in let valueString: AnyObject = value ?? "nil" return "\(valueString)" } // REACT (obj1, "value") <~ concatStream println("*** Start ***") self.perform { XCTAssertEqual(obj1.value, "initial") Async.main(after: 0.2) { XCTAssertEqual(obj1.value, "Next") } Async.main(after: 0.4) { XCTAssertEqual(obj1.value, "123") expect.fulfill() } } self.wait() } func testSwitchLatestInner() { if !self.isAsync { return } let expect = self.expectationWithDescription(__FUNCTION__) let faster: NSTimeInterval = 0.1 /// /// - innerStream0: starts at `t = 0` /// - emits 1 at `t = 0.0` /// - emits 2 at `t = 0.6` /// - emits 3 at `t = 1.2` (will be ignored by switchLatestInner) /// - innerStream1: starts at `t = 1` /// - emits 4 at `t = 0.0 + 1` /// - emits 5 at `t = 0.6 + 1` /// - emits 6 at `t = 1.2 + 1` (will be ignored by switchLatestInner) /// - innerStream2: starts at `t = 2` /// - emits 7 at `t = 0.0 + 2` /// - emits 8 at `t = 0.6 + 2` /// - emits 9 at `t = 1.2 + 2` /// let nestedStream: Stream<Stream<Int>> nestedStream = Stream.sequence(0...2) |> interval(1.0 * faster) |> map { (v: Int) -> Stream<Int> in let innerStream = Stream.sequence((3*v+1)...(3*v+3)) |> interval(0.6 * faster) innerStream.name = "innerStream\(v)" return innerStream } let switchingStream = nestedStream |> switchLatestInner var results = [Int]() // REACT switchingStream ~> { value in results += [value] println("[REACT] value = \(value)") } println("*** Start ***") self.perform(after: 4.0 * faster) { XCTAssertEqual(results, [1, 2, 4, 5, 7, 8, 9], "Some of values sent by `switchingStream`'s `innerStream`s should be ignored.") expect.fulfill() } self.wait() } //-------------------------------------------------- // MARK: - Nested Stream Operations //-------------------------------------------------- func testMergeInner() { let expect = self.expectationWithDescription(__FUNCTION__) let obj1 = MyObject() let obj2 = MyObject() let obj3 = MyObject() let stream1 = KVO.stream(obj1, "value") let stream2 = KVO.stream(obj2, "number") var bundledStream = [stream1, stream2] |> mergeInner |> map { (value: AnyObject?) -> String? in let valueString: AnyObject = value ?? "nil" return "\(valueString)" } // REACT (obj3, "value") <~ bundledStream println("*** Start ***") self.perform { XCTAssertEqual(obj3.value, "initial") obj1.value = "test1" XCTAssertEqual(obj3.value, "test1") obj1.value = "test2" XCTAssertEqual(obj3.value, "test2") obj2.value = "test3" XCTAssertEqual(obj3.value, "test2", "`obj3.value` should NOT be updated because `bundledStream` doesn't react to `obj2.value` (reacts to `obj2.number`).") obj2.number = 123 XCTAssertEqual(obj3.value, "123") expect.fulfill() } self.wait() } //-------------------------------------------------- // MARK: - Stream Producer Operations //-------------------------------------------------- func testRepeat() { let expect = self.expectationWithDescription(__FUNCTION__) var buffer = [Int]() var streamProducer: Stream<Int>.Producer = { Stream.sequence(1...3) } if self.isAsync { streamProducer = streamProducer |>> interval(0.01) } let repeatStreamProducer = streamProducer |>> repeat(3) println("*** Start ***") let repeatStream = repeatStreamProducer() // REACT repeatStream ~> { value in buffer.append(value) } self.perform(after: 0.5) { expect.fulfill() } self.wait() XCTAssertEqual(buffer, [1, 2, 3, 1, 2, 3, 1, 2, 3], "`repeatStream` should repeat `1 -> 2 -> 3 -> ignore complete` 3 times (retryCount is 2).") } // see also: `testCatch()` func testRetry() { let expect = self.expectationWithDescription(__FUNCTION__) var buffer = [Int]() var streamProducer: Stream<Int>.Producer = { Stream.sequence(1...3) } if self.isAsync { streamProducer = streamProducer |>> interval(0.01) } let errorStreamProducer = streamProducer |>> concat(Stream.error(NSError(domain: "test", code: -1, userInfo: nil))) let retryStreamProducer = errorStreamProducer |>> retry(2) println("*** Start ***") let retryStream = retryStreamProducer() // REACT retryStream ~> { value in buffer.append(value) } self.perform(after: 0.5) { expect.fulfill() } self.wait() XCTAssertEqual(buffer, [1, 2, 3, 1, 2, 3, 1, 2, 3], "`retryStream` should handle `1 -> 2 -> 3 -> recovery from error` 3 times (retryCount is 2).") } } class AsyncOperationTests: OperationTests { override var isAsync: Bool { return true } }
mit
2f92a202f9be6fcca0736608325d5f15
29.286928
175
0.484052
4.901936
false
true
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/SelectiveHSL.swift
1
5069
// // MTLSelectiveHSL.swift // Pods // // Created by Mohssen Fathi on 4/13/16. // // import UIKit struct SelectiveHSLUniforms: Uniforms { var mode: Int = 0 } public class SelectiveHSL: Filter { var uniforms = SelectiveHSLUniforms() private var adjustmentsTexture: MTLTexture? private var hueAdjustments = [Float](repeating: 0.0, count: 7) private var saturationAdjustments = [Float](repeating: 0.0, count: 7) private var luminanceAdjustments = [Float](repeating: 0.0, count: 7) @objc public var mode: Int = 0 { didSet { clamp(&mode, low: 0, high: 3) needsUpdate = true } } @objc public var adjustments: [Float] = [Float](repeating: 0.0, count: 7) { didSet { needsUpdate = true } } public init() { super.init(functionName: "selectiveHSL") title = "Selective HSL" let modeProperty = Property(key: "mode", title: "Mode", propertyType: .selection) modeProperty.selectionItems = [0 : "Hue", 1 : "Saturation", 2 : "Luminance"] properties = [Property(key: "red" , title: "Red" ), Property(key: "orange" , title: "Orange" ), Property(key: "yellow" , title: "Yellow" ), Property(key: "green" , title: "Green" ), Property(key: "aqua" , title: "Aqua" ), Property(key: "blue" , title: "Blue" ), Property(key: "purple" , title: "Purple" ), Property(key: "magenta", title: "Magenta"), modeProperty] update() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func update() { if self.input == nil { return } // uniforms.red = red * 20.0 // uniforms.orange = orange // uniforms.yellow = yellow * 20.0 // uniforms.green = green // uniforms.aqua = aqua // uniforms.blue = blue // uniforms.purple = purple // uniforms.magenta = magenta uniforms.mode = mode updateUniforms(uniforms: uniforms) } func loadColorAdjustmentTexture() { let adjustments = hueAdjustments + saturationAdjustments + luminanceAdjustments let size = adjustments.count let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .r32Float, width: size, height: 1, mipmapped: false) self.adjustmentsTexture = self.device.makeTexture(descriptor: textureDescriptor) self.adjustmentsTexture!.replace(region: MTLRegionMake2D(0, 0, size, 1), mipmapLevel: 0, withBytes: adjustments, bytesPerRow: MemoryLayout<Float>.size * size) } override func configureCommandEncoder(_ commandEncoder: MTLComputeCommandEncoder) { super.configureCommandEncoder(commandEncoder) if needsUpdate == true { loadColorAdjustmentTexture() } commandEncoder.setTexture(adjustmentsTexture, index: 2) } func updateColor(_ value: Float, index: Int) { switch mode { case 0: hueAdjustments[index] = value break case 0: saturationAdjustments[index] = value break case 0: luminanceAdjustments[index] = value break default: break } } // MARK: - Colors @objc public var red: Float = 0.0 { didSet { clamp(&red, low: 0, high: 1) needsUpdate = true updateColor(red, index: 0) } } @objc public var orange: Float = 0.0 { didSet { clamp(&orange, low: 0, high: 1) needsUpdate = true updateColor(orange, index: 1) } } @objc public var yellow: Float = 0.0 { didSet { clamp(&yellow, low: 0, high: 1) needsUpdate = true updateColor(yellow, index: 2) } } @objc public var green: Float = 0.0 { didSet { clamp(&green, low: 0, high: 1) needsUpdate = true updateColor(green, index: 3) } } @objc public var aqua: Float = 0.0 { didSet { clamp(&aqua, low: 0, high: 1) needsUpdate = true updateColor(orange, index: 4) } } @objc public var blue: Float = 0.0 { didSet { clamp(&blue, low: 0, high: 1) needsUpdate = true updateColor(blue, index: 5) } } @objc public var purple: Float = 0.0 { didSet { clamp(&purple, low: 0, high: 1) needsUpdate = true updateColor(purple, index: 6) } } @objc public var magenta: Float = 0.0 { didSet { clamp(&magenta, low: 0, high: 1) needsUpdate = true updateColor(magenta, index: 7) } } }
mit
d2f8e5eea69bb64488c7ac7f4d8329c6
28.817647
166
0.533833
4.339897
false
false
false
false
manuelbl/WirekiteMac
WirekiteMacTest/Controllers/EPaper.swift
1
6878
// // Wirekite for MacOS // // Copyright (c) 2017 Manuel Bleichenbacher // Licensed under MIT License // https://opensource.org/licenses/MIT // import CoreFoundation import Cocoa class EPaper: NSObject { private static let DriverOutputControl: UInt8 = 0x01 private static let BoosterSoftStartControl: UInt8 = 0x0C private static let WriteVCOMRegister: UInt8 = 0x11 private static let SetDummyLinePeriod: UInt8 = 0x3A private static let SetGateTime: UInt8 = 0x3B private static let DataEntryModeSetting: UInt8 = 0x11 private static let WriteLUTRegister: UInt8 = 0x32 private static let WriteRAM: UInt8 = 0x24 private static let MasterActivation: UInt8 = 0x20 private static let DisplayUpdateControl1: UInt8 = 0x21 private static let DisplayUpdateControl2: UInt8 = 0x22 private static let TerminateFrameReadWrite: UInt8 = 0xff private static let SetRAMXAddressStartEndPosition: UInt8 = 0x44 private static let SetRAMYAddressStartEndPosition: UInt8 = 0x45 private static let SetRAMXAddressCounter: UInt8 = 0x4E private static let SetRAMYAddressCounter: UInt8 = 0x4F static let LUTFullUpdate: [UInt8] = [ 0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22, 0x66, 0x69, 0x69, 0x59, 0x58, 0x99, 0x99, 0x88, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xB4, 0x13, 0x51, 0x35, 0x51, 0x51, 0x19, 0x01, 0x00 ] static let LUTPartialUpdate: [UInt8] = [ 0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x44, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] var Width = 200 var Height = 200 private var device: WirekiteDevice? private var spi: PortID private var csPort: PortID private var dcPort: PortID private var busyPort: PortID private var resetPort: PortID private var graphics: GraphicsBuffer? init(device: WirekiteDevice, spiPort: PortID, csPin: Int, dcPin: Int, busyPin: Int, resetPin: Int) { self.device = device self.spi = spiPort csPort = device.configureDigitalOutputPin(csPin, attributes: [], initialValue: true) dcPort = device.configureDigitalOutputPin(dcPin, attributes: [], initialValue: true) resetPort = device.configureDigitalOutputPin(resetPin, attributes: [], initialValue: true) busyPort = device.configureDigitalInputPin(busyPin, attributes: [], communication: .precached) } deinit { device?.releaseDigitalPin(onPort: csPort) device?.releaseDigitalPin(onPort: dcPort) device?.releaseDigitalPin(onPort: resetPort) device?.releaseDigitalPin(onPort: busyPort) } func initDevice() { graphics = GraphicsBuffer(width: Width, height: Height, isColor: false) reset() sendCommand(EPaper.DriverOutputControl, data: [ UInt8((Height - 1) & 0xff), UInt8(((Height - 1) >> 8) & 0xff), 0 ]) sendCommand(EPaper.BoosterSoftStartControl, data: [ 0xd7, 0xd6, 0x9d ]) sendCommand(EPaper.WriteVCOMRegister, data: [ 0xa8 ]) sendCommand(EPaper.SetDummyLinePeriod, data: [ 0x1a ]) sendCommand(EPaper.SetGateTime, data: [ 0x08 ]) sendCommand(EPaper.DataEntryModeSetting, data: [ 0x03 ]) sendCommand(EPaper.WriteLUTRegister, data: EPaper.LUTFullUpdate) } func prepareForDrawing() -> CGContext { return graphics!.prepareForDrawing() } func finishDrawing(shouldDither: Bool) { let pixels = graphics!.finishDrawing(format: shouldDither ? .blackAndWhiteDithered : .grayscale) let stride = Width / 8 var buf = [UInt8](repeating: 0xff, count: Height * stride) var srow = 0 var t = 0 for _ in 0 ..< Height { var s = srow for _ in 0 ..< stride { var byte: UInt8 = 0 for _ in 0 ..< 8 { byte <<= 1 if pixels[s] != 0 { byte |= 1 } s += 1 } buf[t] = byte t += 1 } srow += Width } setMemoryArea(x: 0, y: 0, width: Width - 1, height: Height - 1) setMemoryPointer(x: 0, y: 0) sendCommand(EPaper.WriteRAM, data: buf) displayFrame() } private func reset() { device!.writeDigitalPin(onPort: resetPort, value: false) Thread.sleep(forTimeInterval: 0.2) device!.writeDigitalPin(onPort: resetPort, value: true) Thread.sleep(forTimeInterval: 0.2) } private func waitUntilIdle() { while (device!.readDigitalPin(onPort: busyPort)) { Thread.sleep(forTimeInterval: 0.01) } } private func clearFrameMemory() { setMemoryArea(x: 0, y: 0, width: Width - 1, height: Height - 1) setMemoryPointer(x: 0, y: 0) sendCommand(EPaper.WriteRAM, data: [UInt8](repeating: 0xff, count: Width * Height / 8)) } private func displayFrame() { sendCommand(EPaper.DisplayUpdateControl2, data: [ 0xC4 ]) sendCommand(EPaper.MasterActivation, data: []) sendCommand(EPaper.TerminateFrameReadWrite, data: []) waitUntilIdle() } private func setMemoryArea(x: Int, y: Int, width: Int, height: Int) { sendCommand(EPaper.SetRAMXAddressStartEndPosition, data: [ UInt8((x >> 3) & 0xff), UInt8(((x + width) >> 3) & 0xff) ]) sendCommand(EPaper.SetRAMYAddressStartEndPosition, data: [ UInt8(y & 0xff), UInt8((y >> 8) & 0xff), UInt8((y + height) & 0xff), UInt8(((y + height) >> 8) & 0xff), ]) } private func setMemoryPointer(x: Int, y: Int) { sendCommand(EPaper.SetRAMXAddressCounter, data: [ UInt8((x >> 3) & 0xff) ]) sendCommand(EPaper.SetRAMYAddressCounter, data: [ UInt8(y & 0xff), UInt8((y >> 8) & 0xff) ]) waitUntilIdle() } private func sendCommand(_ command: UInt8, data: [UInt8]) { // select command mode device!.writeDigitalPin(onPort: dcPort, value: false) let commandData = Data(bytes: [ command ]) guard device!.transmit(onSPIPort: spi, data: commandData, chipSelect: csPort) == 1 else { NSLog("EPaper: Transmitting command byte failed") return } // select data mode device!.writeDigitalPin(onPort: dcPort, value: true) if (data.count > 0) { let commandLoad = Data(bytes: data) guard device!.transmit(onSPIPort: spi, data: commandLoad, chipSelect: csPort) == commandLoad.count else { NSLog("EPaper: Transmitting command data failed") return } } } }
mit
6f4a456e4ea5aea1c58e41afff1f1c47
36.178378
126
0.611224
3.654623
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift
10
3304
// // UITabBarController+Rx.swift // RxCocoa // // Created by Yusuke Kita on 2016/12/07. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif /** iOS only */ #if os(iOS) extension Reactive where Base: UITabBarController { /// Reactive wrapper for `delegate` message `tabBarController:willBeginCustomizing:`. public var willBeginCustomizing: ControlEvent<[UIViewController]> { let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willBeginCustomizing:))) .map { a in return try castOrThrow([UIViewController].self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `tabBarController:willEndCustomizing:changed:`. public var willEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willEndCustomizing:changed:))) .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in let viewControllers = try castOrThrow([UIViewController].self, a[1]) let changed = try castOrThrow(Bool.self, a[2]) return (viewControllers, changed) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `tabBarController:didEndCustomizing:changed:`. public var didEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didEndCustomizing:changed:))) .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in let viewControllers = try castOrThrow([UIViewController].self, a[1]) let changed = try castOrThrow(Bool.self, a[2]) return (viewControllers, changed) } return ControlEvent(events: source) } } #endif /** iOS and tvOS */ extension UITabBarController { /// Factory method that enables subclasses to implement their own `delegate`. /// /// - returns: Instance of delegate proxy that wraps `delegate`. public func createRxDelegateProxy() -> RxTabBarControllerDelegateProxy { return RxTabBarControllerDelegateProxy(parentObject: self) } } extension Reactive where Base: UITabBarController { /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy { return RxTabBarControllerDelegateProxy.proxyForObject(base) } /// Reactive wrapper for `delegate` message `tabBarController:didSelect:`. public var didSelect: ControlEvent<UIViewController> { let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didSelect:))) .map { a in return try castOrThrow(UIViewController.self, a[1]) } return ControlEvent(events: source) } } #endif
apache-2.0
904010436d5407ca9ce3abb0a0c12012
34.902174
130
0.669391
5.185243
false
false
false
false
gang462234887/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/model/CBRecommendModel.swift
1
4044
// // CBRecommendModel.swift // TestKitchen // // Created by qianfeng on 16/8/16. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit import SwiftyJSON class CBRecommendModel: NSObject { var code:NSNumber? var msg:Bool? var version:String? var timestamp:NSNumber? var data:CBRecommendDataModel? class func parseModel(data:NSData)->CBRecommendModel{ let model = CBRecommendModel() let jsonData = JSON(data: data) model.code = jsonData["code"].number model.msg = jsonData["msg"].bool model.version = jsonData["version"].string model.timestamp = jsonData["timestamp"].number let dataDict = jsonData["data"] model.data = CBRecommendDataModel.parseModel(dataDict) return model } } class CBRecommendDataModel:NSObject{ var banner:Array<CBRecommendBannerModel>? var widgetList:Array<CBRecommendWidgeListModel>? class func parseModel(jsonData:JSON)->CBRecommendDataModel{ let model = CBRecommendDataModel() //banner let bannerArray = jsonData["banner"] var bArray = Array<CBRecommendBannerModel>() for (_,subjson) in bannerArray{ let bannerModel = CBRecommendBannerModel.parseModel(subjson) bArray.append(bannerModel) } model.banner = bArray //widgetList let listArray = jsonData["widgetList"] var wlArray = Array<CBRecommendWidgeListModel>() for (_,subjson) in listArray{ let wlModel = CBRecommendWidgeListModel.parseModel(subjson) wlArray.append(wlModel) } model.widgetList = wlArray return model } } class CBRecommendBannerModel:NSObject{ var banner_id:NSNumber? var banner_title:String? var banner_picture:String? var banner_link:String? var is_link:String? var refer_key:String? var type_id:String? class func parseModel(jsonData:JSON)->CBRecommendBannerModel{ let model = CBRecommendBannerModel() model.banner_id = jsonData["banner_id"].number model.banner_title = jsonData["banner_title"].string model.banner_picture = jsonData["banner_picture"].string model.banner_link = jsonData["banner_link"].string model.refer_key = jsonData["refer_key"].string model.type_id = jsonData["type_id"].string return model } } class CBRecommendWidgeListModel:NSObject{ var widget_id:NSNumber? var widget_type:NSNumber? var title:String? var title_link:String? var desc:String? var widget_data:Array<CBRecommendWidgetDataModel>? class func parseModel(jsonData:JSON)->CBRecommendWidgeListModel{ let model = CBRecommendWidgeListModel() model.widget_id = jsonData["widget_id"].number model.widget_type = jsonData["widget_type"].number model.title = jsonData["title"].string model.title_link = jsonData["title_link"].string model.desc = jsonData["desc"].string let dataArray = jsonData["widget_data"] var wdArray = Array<CBRecommendWidgetDataModel>() for (_,subjson) in dataArray{ let wdModel = CBRecommendWidgetDataModel.parseModel(subjson) wdArray.append(wdModel) } model.widget_data = wdArray return model } } class CBRecommendWidgetDataModel:NSObject{ var id:NSNumber? var type:String? var content:String? var link:String? class func parseModel(jsonData:JSON)->CBRecommendWidgetDataModel{ let model = CBRecommendWidgetDataModel() model.id = jsonData["id"].number model.type = jsonData["type"].string model.content = jsonData["content"].string model.link = jsonData["link"].string return model } }
mit
6bc24b9e8deea1edb91de50888169da1
25.24026
72
0.624598
4.634174
false
false
false
false
suzuki-0000/HoneycombView
HoneycombView/HoneycombPhotoBrowser.swift
1
23224
// // HoneycombPhotoBrowser.swift // HoneycombViewExample // // Created by suzuki_keishi on 2015/10/01. // Copyright © 2015年 suzuki_keishi. All rights reserved. // import UIKit // MARK: - HoneycombPhotoBrowser public class HoneycombPhotoBrowser: UIViewController, UIScrollViewDelegate{ final let pageIndexTagOffset = 1000 final let screenBound = UIScreen.mainScreen().bounds var screenWidth :CGFloat { return screenBound.size.width } var screenHeight:CGFloat { return screenBound.size.height } var applicationWindow:UIWindow! var toolBar:UIToolbar! var toolCounterLabel:UILabel! var toolCounterButton:UIBarButtonItem! var toolPreviousButton:UIBarButtonItem! var toolNextButton:UIBarButtonItem! var pagingScrollView:UIScrollView! var panGesture:UIPanGestureRecognizer! var doneButton:UIButton! var visiblePages:Set<HoneycombZoomingScrollView> = Set() var initialPageIndex:Int = 0 var currentPageIndex:Int = 0 var photos:[HoneycombPhoto] = [HoneycombPhoto]() var numberOfPhotos:Int{ return photos.count } // senderView's property var senderViewForAnimation:UIView = UIView() var senderViewOriginalFrame:CGRect = CGRectZero // animation property var resizableImageView:UIImageView = UIImageView() // for status check var isDraggingPhoto:Bool = false var isViewActive:Bool = false var isPerformingLayout:Bool = false var isDisplayToolbar:Bool = true // scroll property var firstX:CGFloat = 0.0 var firstY:CGFloat = 0.0 var controlVisibilityTimer:NSTimer! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nil, bundle: nil) setup() } convenience init(photos:[HoneycombPhoto], animatedFromView:UIView) { self.init(nibName: nil, bundle: nil) self.photos = photos self.senderViewForAnimation = animatedFromView } func setup() { applicationWindow = (UIApplication.sharedApplication().delegate?.window)! modalPresentationStyle = UIModalPresentationStyle.Custom modalPresentationCapturesStatusBarAppearance = true modalTransitionStyle = UIModalTransitionStyle.CrossDissolve } // MARK: - override public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() view.clipsToBounds = true // setup paging let pagingScrollViewFrame = frameForPagingScrollView() pagingScrollView = UIScrollView(frame: pagingScrollViewFrame) pagingScrollView.pagingEnabled = true pagingScrollView.delegate = self pagingScrollView.showsHorizontalScrollIndicator = true pagingScrollView.showsVerticalScrollIndicator = true pagingScrollView.backgroundColor = UIColor.blackColor() pagingScrollView.contentSize = contentSizeForPagingScrollView() view.addSubview(pagingScrollView) // toolbar toolBar = UIToolbar(frame: frameForToolbarAtOrientation()) toolBar.backgroundColor = UIColor.clearColor() toolBar.clipsToBounds = true toolBar.translucent = true toolBar.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: .Default) view.addSubview(toolBar) if !isDisplayToolbar { toolBar.hidden = true } // arrows:back let bundle = NSBundle(identifier: "com.keishi.suzuki.HoneycombView") let previousBtn = UIButton(type: .Custom) let previousImage = UIImage(named: "btn_common_back_wh", inBundle: bundle, compatibleWithTraitCollection: nil) ?? UIImage() previousBtn.frame = CGRectMake(0, 0, 44, 44) previousBtn.imageEdgeInsets = UIEdgeInsetsMake(13.25, 17.25, 13.25, 17.25) previousBtn.setImage(previousImage, forState: .Normal) previousBtn.addTarget(self, action: "gotoPreviousPage", forControlEvents: .TouchUpInside) previousBtn.contentMode = .Center toolPreviousButton = UIBarButtonItem(customView: previousBtn) // arrows:next let nextBtn = UIButton(type: .Custom) let nextImage = UIImage(named: "btn_common_forward_wh", inBundle: bundle, compatibleWithTraitCollection: nil) ?? UIImage() nextBtn.frame = CGRectMake(0, 0, 44, 44) nextBtn.imageEdgeInsets = UIEdgeInsetsMake(13.25, 17.25, 13.25, 17.25) nextBtn.setImage(nextImage, forState: .Normal) nextBtn.addTarget(self, action: "gotoNextPage", forControlEvents: .TouchUpInside) nextBtn.contentMode = .Center toolNextButton = UIBarButtonItem(customView: nextBtn) toolCounterLabel = UILabel(frame: CGRectMake(0, 0, 95, 40)) toolCounterLabel.textAlignment = .Center toolCounterLabel.backgroundColor = UIColor.clearColor() toolCounterLabel.font = UIFont(name: "Helvetica", size: 16.0) toolCounterLabel.textColor = UIColor.whiteColor() toolCounterLabel.shadowColor = UIColor.darkTextColor() toolCounterLabel.shadowOffset = CGSizeMake(0.0, 1.0) toolCounterButton = UIBarButtonItem(customView: toolCounterLabel) // close let doneImage = UIImage(named: "btn_common_close_wh", inBundle: bundle, compatibleWithTraitCollection: nil) ?? UIImage() doneButton = UIButton(type: UIButtonType.Custom) doneButton.setImage(doneImage, forState: UIControlState.Normal) doneButton.frame = CGRectMake(5, 5, 44, 44) doneButton.imageEdgeInsets = UIEdgeInsetsMake(15.25, 15.25, 15.25, 15.25) doneButton.backgroundColor = UIColor.clearColor() doneButton.addTarget(self, action: "doneButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) doneButton.alpha = 0.0 view.addSubview(doneButton) // gesture panGesture = UIPanGestureRecognizer(target: self, action: "panGestureRecognized:") panGesture.minimumNumberOfTouches = 1 panGesture.maximumNumberOfTouches = 1 view.addGestureRecognizer(panGesture) // transition (this must be last call of view did load.) performPresentAnimation() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) reloadData() } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() isPerformingLayout = true pagingScrollView.frame = frameForPagingScrollView() pagingScrollView.contentSize = contentSizeForPagingScrollView() pagingScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex) toolBar.frame = frameForToolbarAtOrientation() isPerformingLayout = false } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) isViewActive = true } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(true) currentPageIndex = 0 pagingScrollView = nil visiblePages = Set() } // MARK: - initialize / setup public func reloadData(){ performLayout() view.setNeedsLayout() } public func performLayout(){ isPerformingLayout = true let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil) var items = [UIBarButtonItem]() items.append(flexSpace) items.append(toolPreviousButton) items.append(flexSpace) items.append(toolCounterButton) items.append(flexSpace) items.append(toolNextButton) items.append(flexSpace) toolBar.setItems(items, animated: false) updateToolbar() visiblePages.removeAll() // set content offset pagingScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex) // tile page tilePages() isPerformingLayout = false view.addGestureRecognizer(panGesture) } public func prepareForClosePhotoBrowser(){ applicationWindow.removeGestureRecognizer(panGesture) NSObject.cancelPreviousPerformRequestsWithTarget(self) } // MARK: - frame calculation public func frameForPagingScrollView() -> CGRect{ var frame = view.bounds frame.origin.x -= 10 frame.size.width += (2 * 10) return frame } public func frameForToolbarAtOrientation() -> CGRect{ let currentOrientation = UIApplication.sharedApplication().statusBarOrientation var height:CGFloat = 44 if UIInterfaceOrientationIsLandscape(currentOrientation){ height = 32 } return CGRectMake(0, view.bounds.size.height - height, view.bounds.size.width, height) } public func contentOffsetForPageAtIndex(index:Int) -> CGPoint{ let pageWidth = pagingScrollView.bounds.size.width let newOffset = CGFloat(index) * pageWidth return CGPointMake(newOffset, 0) } public func contentSizeForPagingScrollView() -> CGSize { let bounds = pagingScrollView.bounds return CGSizeMake(bounds.size.width * CGFloat(numberOfPhotos), bounds.size.height) } // MARK: - Toolbar public func updateToolbar(){ if numberOfPhotos > 1 { toolCounterLabel.text = "\(currentPageIndex + 1) / \(numberOfPhotos)" } else { toolCounterLabel.text = nil } toolPreviousButton.enabled = (currentPageIndex > 0) toolNextButton.enabled = (currentPageIndex < numberOfPhotos - 1) } // MARK: - paging public func initializePageIndex(index: Int){ var i = index if index >= numberOfPhotos { i = numberOfPhotos - 1 } initialPageIndex = i currentPageIndex = i if isViewLoaded() { jumpToPageAtIndex(index) if isViewActive { tilePages() } } } public func jumpToPageAtIndex(index:Int){ if index < numberOfPhotos { let pageFrame = frameForPageAtIndex(index) pagingScrollView.setContentOffset(CGPointMake(pageFrame.origin.x - 10, 0), animated: true) updateToolbar() } hideControlsAfterDelay() } public func photoAtIndex(index: Int) -> HoneycombPhoto { return photos[index] } public func frameForPageAtIndex(index: Int) -> CGRect { let bounds = pagingScrollView.bounds var pageFrame = bounds pageFrame.size.width -= (2 * 10) pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + 10 return pageFrame } // MARK: - panGestureRecognized public func panGestureRecognized(sender:UIPanGestureRecognizer){ let scrollView = pageDisplayedAtIndex(currentPageIndex) let viewHeight = scrollView.frame.size.height let viewHalfHeight = viewHeight/2 var translatedPoint = sender.translationInView(self.view) // gesture began if sender.state == .Began { firstX = scrollView.center.x firstY = scrollView.center.y senderViewForAnimation.hidden = (currentPageIndex == initialPageIndex) isDraggingPhoto = true setNeedsStatusBarAppearanceUpdate() } translatedPoint = CGPointMake(firstX, firstY + translatedPoint.y) scrollView.center = translatedPoint view.opaque = true // gesture end if sender.state == .Ended{ if scrollView.center.y > viewHalfHeight+40 || scrollView.center.y < viewHalfHeight-40 { if currentPageIndex == initialPageIndex { performCloseAnimationWithScrollView(scrollView) return } let finalX:CGFloat = firstX var finalY:CGFloat = 0.0 let windowHeight = applicationWindow.frame.size.height if scrollView.center.y > viewHalfHeight+30 { finalY = windowHeight * 2.0 } else { finalY = -(viewHalfHeight) } let animationDuration = 0.35 UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn) scrollView.center = CGPointMake(finalX, finalY) UIView.commitAnimations() dismissPhotoBrowser() } else { // Continue Showing View isDraggingPhoto = false setNeedsStatusBarAppearanceUpdate() let velocityY:CGFloat = 0.35 * sender.velocityInView(self.view).y let finalX:CGFloat = firstX let finalY:CGFloat = viewHalfHeight let animationDuration = Double(abs(velocityY) * 0.0002 + 0.2) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn) scrollView.center = CGPointMake(finalX, finalY) UIView.commitAnimations() } } } // MARK: - perform animation public func performPresentAnimation(){ view.alpha = 0.0 pagingScrollView.alpha = 0.0 senderViewOriginalFrame = (senderViewForAnimation.superview?.convertRect(senderViewForAnimation.frame, toView:nil))! let fadeView = UIView(frame: CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = UIColor.clearColor() applicationWindow.addSubview(fadeView) let imageFromView = getImageFromView(senderViewForAnimation) resizableImageView = UIImageView(image: imageFromView) resizableImageView.frame = senderViewOriginalFrame resizableImageView.clipsToBounds = true resizableImageView.contentMode = .ScaleAspectFill applicationWindow.addSubview(resizableImageView) senderViewForAnimation.hidden = true let scaleFactor = imageFromView.size.width / screenWidth let finalImageViewFrame = CGRectMake(0, (screenHeight/2) - ((imageFromView.size.height / scaleFactor)/2), screenWidth, imageFromView.size.height / scaleFactor) UIView.animateWithDuration(0.35, animations: { () -> Void in self.resizableImageView.layer.frame = finalImageViewFrame self.doneButton.alpha = 1.0 }, completion: { (Bool) -> Void in self.view.alpha = 1.0 self.pagingScrollView.alpha = 1.0 self.resizableImageView.alpha = 0.0 fadeView.removeFromSuperview() }) } public func performCloseAnimationWithScrollView(scrollView:HoneycombZoomingScrollView) { view.hidden = true let fadeView = UIView(frame: CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = UIColor.clearColor() fadeView.alpha = 1.0 applicationWindow.addSubview(fadeView) resizableImageView.alpha = 1.0 resizableImageView.clipsToBounds = true resizableImageView.contentMode = .ScaleAspectFill applicationWindow.addSubview(resizableImageView) UIView.animateWithDuration(0.35, animations: { () -> Void in fadeView.alpha = 0.0 self.resizableImageView.layer.frame = self.senderViewOriginalFrame }, completion: { (Bool) -> Void in self.resizableImageView.removeFromSuperview() fadeView.removeFromSuperview() self.senderViewForAnimation.hidden = false self.prepareForClosePhotoBrowser() self.dismissViewControllerAnimated(true, completion: {}) }) } private func getImageFromView(sender:UIView) -> UIImage{ let maskLayer = CAShapeLayer() maskLayer.fillRule = kCAFillRuleEvenOdd maskLayer.frame = sender.bounds let width:CGFloat = sender.frame.size.width let height:CGFloat = sender.frame.size.height // set hexagon using bezierpath UIGraphicsBeginImageContext(sender.frame.size) let path = UIBezierPath() path.moveToPoint(CGPointMake(width/2, 0)) path.addLineToPoint(CGPointMake(width, height / 4)) path.addLineToPoint(CGPointMake(width, height * 3 / 4)) path.addLineToPoint(CGPointMake(width / 2, height)) path.addLineToPoint(CGPointMake(0, height * 3 / 4)) path.addLineToPoint(CGPointMake(0, height / 4)) path.closePath() path.fill() maskLayer.path = path.CGPath sender.layer.mask = maskLayer sender.layer.renderInContext(UIGraphicsGetCurrentContext()!) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } //MARK - paging public func gotoPreviousPage(){ jumpToPageAtIndex(currentPageIndex - 1) } public func gotoNextPage(){ jumpToPageAtIndex(currentPageIndex + 1) } public func tilePages(){ let visibleBounds = pagingScrollView.bounds var firstIndex = Int(floor((CGRectGetMinX(visibleBounds) + 10 * 2) / CGRectGetWidth(visibleBounds))) var lastIndex = Int(floor((CGRectGetMaxX(visibleBounds) - 10 * 2 - 1) / CGRectGetWidth(visibleBounds))) if firstIndex < 0 { firstIndex = 0 } if firstIndex > numberOfPhotos - 1 { firstIndex = numberOfPhotos - 1 } if lastIndex < 0 { lastIndex = 0 } if lastIndex > numberOfPhotos - 1 { lastIndex = numberOfPhotos - 1 } for(var index = firstIndex; index <= lastIndex; index++){ if !isDisplayingPageForIndex(index){ let page = HoneycombZoomingScrollView(frame: view.frame, browser: self) page.frame = frameForPageAtIndex(index) page.tag = index + pageIndexTagOffset page.photo = photoAtIndex(index) visiblePages.insert(page) pagingScrollView.addSubview(page) } } } public func isDisplayingPageForIndex(index: Int) -> Bool{ for page in visiblePages{ if (page.tag - pageIndexTagOffset) == index { return true } } return false } public func pageDisplayedAtIndex(index: Int) -> HoneycombZoomingScrollView { var thePage:HoneycombZoomingScrollView = HoneycombZoomingScrollView() for page in visiblePages { if (page.tag - pageIndexTagOffset) == index { thePage = page break } } return thePage } public func pageDisplayingAtPhoto(photo: HoneycombPhoto) -> HoneycombZoomingScrollView { var thePage:HoneycombZoomingScrollView = HoneycombZoomingScrollView() for page in visiblePages { if page.photo == photo { thePage = page break } } return thePage } // MARK: - Control Hiding / Showing public func cancelControlHiding(){ if controlVisibilityTimer != nil{ controlVisibilityTimer.invalidate() controlVisibilityTimer = nil } } public func hideControlsAfterDelay(){ // reset cancelControlHiding() // start controlVisibilityTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "hideControls:", userInfo: nil, repeats: false) } public func hideControls(timer: NSTimer){ setControlsHidden(true, animated: true, permanent: false) } public func toggleControls(){ setControlsHidden(!areControlsHidden(), animated: true, permanent: false) } public func setControlsHidden(hidden:Bool, animated:Bool, permanent:Bool){ cancelControlHiding() UIView.animateWithDuration(0.35, animations: { () -> Void in let alpha:CGFloat = hidden ? 0.0 : 1.0 self.doneButton.alpha = alpha self.toolBar.alpha = alpha }, completion: { (Bool) -> Void in }) if !permanent { hideControlsAfterDelay() } setNeedsStatusBarAppearanceUpdate() } public func areControlsHidden() -> Bool{ return toolBar.alpha == 0.0 } // MARK: - Button public func doneButtonPressed(sender:UIButton) { if currentPageIndex == initialPageIndex { performCloseAnimationWithScrollView(pageDisplayedAtIndex(currentPageIndex)) } else { dismissPhotoBrowser() } } public func dismissPhotoBrowser(){ modalTransitionStyle = .CrossDissolve senderViewForAnimation.hidden = false prepareForClosePhotoBrowser() dismissViewControllerAnimated(true, completion: {}) } // MARK: - UIScrollView Delegate public func scrollViewDidScroll(scrollView: UIScrollView) { if !isViewActive { return } if isPerformingLayout { return } // tile page tilePages() // Calculate current page let visibleBounds = pagingScrollView.bounds var index = Int(floor(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds))) if index < 0 { index = 0 } if index > numberOfPhotos - 1 { index = numberOfPhotos } let previousCurrentPage = currentPageIndex currentPageIndex = index if currentPageIndex != previousCurrentPage { updateToolbar() } } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { setControlsHidden(true, animated: true, permanent: false) } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { hideControlsAfterDelay() } }
mit
4724e553a37d46f17aaeec6ef61603e9
34.184848
167
0.618363
5.648504
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/ObjLiplisVersion.swift
1
4039
// // ObjLiplisVersion.swift // Liplis // // バージョン管理クラス // touch.xmlのインスタンス // //アップデート履歴 // 2015/04/16 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/04/16. // Copyright (c) 2015年 sachin. All rights reserved. // import Foundation class ObjLiplisVersion : NSObject, NSXMLParserDelegate { ///============================= /// プロパティ internal var skinVersion : String! = "" internal var liplisMiniVersion : String! = "" internal var url : String! = "" internal var apkUrl : String! = "" internal var flgCheckOn : Bool = false //================================= //XML操作一時変数 internal var _ParseKey: String! = "" internal var _Value: String! = "" //============================================================ // //初期化処理 // //============================================================ internal init(url : NSURL) { self.skinVersion = "" self.liplisMiniVersion = "" self.url = "" self.apkUrl = "" self.flgCheckOn = false //スーパークラスのイニット super.init() //ロードXML loadXml(url) } internal func getFlgCheckOn()->Bool { return self.flgCheckOn } //============================================================ // //XMLロード // //============================================================ /** XMLのロード */ internal func loadXml(url : NSURL) { let parser : NSXMLParser? = NSXMLParser(contentsOfURL: url) if parser != nil { parser!.delegate = self parser!.parse() } else { } } /** 読み込み開始処理完了時処理 */ internal func parserDidStartDocument(parser: NSXMLParser) { //結果格納リストの初期化(イニシャラいざで初期化しているので省略) } /** 更新処理 */ internal func parserDidEndDocument(parser: NSXMLParser) { // 画面など、他オブジェクトを更新する必要がある場合はここに記述する(必要ないので省略) } /** タグの読み始めに呼ばれる */ internal func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI : String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { //エレメント取得 self._ParseKey = elementName } /** タグの最後で呼ばれる */ internal func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if (self._ParseKey == "skinVersion") { self.skinVersion = self._Value! } else if (self._ParseKey == "liplisMiniVersion") { self.liplisMiniVersion = self._Value! } else if (self._ParseKey == "url") { self.url = _Value! } else if (self._ParseKey == "apkUrl") { self.apkUrl = self._Value! } else { // nop } //エレメント初期化 self._ParseKey = "" self._Value = "" } /** パースする。 */ internal func parser(parser: NSXMLParser, foundCharacters value: String) { if (self._ParseKey == "skinVersion") { self._Value = self._Value + value } else if (self._ParseKey == "liplisMiniVersion") { self._Value = self._Value + value } else if (self._ParseKey == "url") { self._Value = self._Value + value } else if (self._ParseKey == "apkUrl") { self._Value = self._Value + value } else { // nop } } }
mit
ab435e21d27d6115c38ef83b0a34b323
23.16
133
0.479713
4.183603
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV1/Models/RuntimeResponseGenericRuntimeResponseTypeImage.swift
1
3556
/** * (C) Copyright IBM Corp. 2022. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** RuntimeResponseGenericRuntimeResponseTypeImage. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeImage: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeImage: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The `https:` URL of the image. */ public var source: String /** The title or introductory text to show before the response. */ public var title: String? /** The description to show with the response. */ public var description: String? /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? /** Descriptive text that can be used for screen readers or other situations where the image cannot be seen. */ public var altText: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case source = "source" case title = "title" case description = "description" case channels = "channels" case altText = "alt_text" } /** Initialize a `RuntimeResponseGenericRuntimeResponseTypeImage` with member variables. - parameter responseType: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - parameter source: The `https:` URL of the image. - parameter title: The title or introductory text to show before the response. - parameter description: The description to show with the response. - parameter channels: An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - parameter altText: Descriptive text that can be used for screen readers or other situations where the image cannot be seen. - returns: An initialized `RuntimeResponseGenericRuntimeResponseTypeImage`. */ public init( responseType: String, source: String, title: String? = nil, description: String? = nil, channels: [ResponseGenericChannel]? = nil, altText: String? = nil ) { self.responseType = responseType self.source = source self.title = title self.description = description self.channels = channels self.altText = altText } }
apache-2.0
01a3d66ccbb8f67f73eb84040784daaa
33.862745
120
0.68982
4.838095
false
false
false
false
sdhzwm/BaiSI-Swift-
BaiSi/BaiSi/Classes/FriendTrends(关注)/Controller/WMFirendsController.swift
1
4915
// // WMFirendsController.swift // BaiSi // // Created by 王蒙 on 15/7/25. // Copyright © 2015年 wm. All rights reserved. // import UIKit import Alamofire import SVProgressHUD import MJRefresh class WMFirendsController: UITableViewController { var category:WMCategory! override func viewDidLoad() { self.tableView.backgroundColor = UIColor.LobalBg() self.automaticallyAdjustsScrollViewInsets = false self.tableView.rowHeight = 70 self.tableView.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData") self.tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMoreFriends") self.tableView.footer.hidden = true } func loadNewData(){ category.currentPage = 1 let parameters = ["a":"list","c":"subscribe","category_id":category.id,"page":category.currentPage] Alamofire.request(.GET, URLString: "http://api.budejie.com/api/api_open.php", parameters: (parameters as! [String : AnyObject])) .responseJSON(completionHandler: { (request, response, data, error) -> Void in if((data) != nil){ if let data = data as? [String: AnyObject] { if let friendList = data["list"] { self.category.friends = WMFriend.friendsFromResults(friendList as! [[String : AnyObject]]) print(friendList) self.tableView.reloadData() self.tableView.header.endRefreshing() if let tool = data["total"]{ self.category.total = Int(tool as! NSNumber) print(self.category.total) } self.checkFooterState() } } }else{ dispatch_async(dispatch_get_main_queue()) { SVProgressHUD.showErrorWithStatus("获取数据失败") } } }) } func loadMoreFriends(){ let parameters = ["a":"list","c":"subscribe","category_id":category.id,"page":++category.currentPage] Alamofire.request(.GET, URLString: "http://api.budejie.com/api/api_open.php", parameters: (parameters as! [String : AnyObject])) .responseJSON(completionHandler: { (request, response, data, error) -> Void in if((data) != nil){ if let data = data as? [String: AnyObject] { if let friendList = data["list"] { self.category.friends += WMFriend.friendsFromResults(friendList as! [[String : AnyObject]]) self.tableView.reloadData() self.checkFooterState() } } }else{ dispatch_async(dispatch_get_main_queue()) { SVProgressHUD.showErrorWithStatus("获取数据失败") --self.category.currentPage } } }) } func checkFooterState() { if let zcategory = self.category { tableView.footer.hidden = zcategory.friends.isEmpty if zcategory.total == zcategory.friends.count { tableView.footer.noticeNoMoreData() } else { tableView.footer.endRefreshing() } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { checkFooterState() if let categorys = self.category { return categorys.friends.count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let firendId = "firendCell" let cell = tableView.dequeueReusableCellWithIdentifier(firendId) as! WMFriendCell let firend = self.category.friends[indexPath.row] cell.friend = firend return cell } } extension WMFirendsController :ConttainerControllerDeletage{ func conttainerController(conttainer: WMConttainerController, didSelectedCategory category: WMCategory) { self.category = category tableView.header.endRefreshing() tableView.footer.endRefreshing() tableView.reloadData() if self.category.friends.isEmpty { tableView.header.beginRefreshing() } } }
apache-2.0
ea09595f9f244c1cb6578355ba610f8d
35.721805
136
0.533374
5.456983
false
false
false
false
bizhara/TryMagnetic
Example/ViewController.swift
1
4223
// // ViewController.swift // Example // // Created by Lasha Efremidze on 3/8/17. // Copyright © 2017 efremidze. All rights reserved. // import SpriteKit import Magnetic class ViewController: UIViewController { @IBOutlet weak var magneticView: MagneticView! { didSet { magnetic.magneticDelegate = self #if DEBUG magneticView.showsFPS = true magneticView.showsDrawCount = true magneticView.showsQuadCount = true #endif } } var magnetic: Magnetic { return magneticView.magnetic } private let initialItems = Int(12) private func makeOne(withRadius: CGFloat) -> MainCategory { return MainCategory(text: "\(withRadius)", radius: withRadius) } @IBAction func load(_ sender: UIControl?) { let lastFrame = self.magneticView.frame self.magneticView.removeFromSuperview() let magneticView = MagneticView(frame: lastFrame) self.view.addSubview(magneticView) self.magneticView = magneticView for _ in 0 ..< self.initialItems { let one = self.makeOne(withRadius: CGFloat.radiuses.randomItem()) self.magnetic.addChild(one) } } @IBAction func add(_ sender: UIControl?) { let one = self.makeOne(withRadius: CGFloat.radiuses.randomItem()) magnetic.addChild(one) } @IBAction func reset(_ sender: UIControl?) { let speed = magnetic.physicsWorld.speed magnetic.physicsWorld.speed = 0 let sortedNodes = magnetic.children.flatMap { $0 as? Node }.sorted { node, nextNode in let distance = node.position.distance(from: magnetic.magneticField.position) let nextDistance = nextNode.position.distance(from: magnetic.magneticField.position) return distance < nextDistance && node.isSelected } var actions = [SKAction]() for (index, node) in sortedNodes.enumerated() { node.physicsBody = nil let action = SKAction.run { [unowned magnetic, unowned node] in if node.isSelected { let point = CGPoint(x: magnetic.size.width / 2, y: magnetic.size.height + 40) let movingXAction = SKAction.moveTo(x: point.x, duration: 0.2) let movingYAction = SKAction.moveTo(y: point.y, duration: 0.4) let resize = SKAction.scale(to: 0.3, duration: 0.4) let throwAction = SKAction.group([movingXAction, movingYAction, resize]) node.run(throwAction) { [unowned node] in node.removeFromParent() } } else { node.removeFromParent() } } actions.append(action) let delay = SKAction.wait(forDuration: TimeInterval(index) * 0.002) actions.append(delay) } magnetic.run(.sequence(actions)) { [unowned magnetic] in magnetic.physicsWorld.speed = speed } } } // MARK: - MagneticDelegate extension ViewController: MagneticDelegate { func magnetic(_ magnetic: Magnetic, didSelect node: Node) { print("didSelect -> \(node)") if let mainCategory = node as? MainCategory { self.magneticView.isUserInteractionEnabled = false mainCategory.isMovable = false mainCategory.isSelected = false let subCategoryView = SubCategoryView.make(withFrame: self.magneticView.frame, mainCategory: mainCategory) { [weak self] () in mainCategory.isMovable = true self?.magneticView.isUserInteractionEnabled = true } self.view.addSubview(subCategoryView) } } func magnetic(_ magnetic: Magnetic, didDeselect node: Node) { print("didDeselect -> \(node)") } } // MARK: - ImageNode class ImageNode: Node { override var image: UIImage? { didSet { sprite.texture = image.map { SKTexture(image: $0) } } } override func selectedAnimation() {} override func deselectedAnimation() {} }
mit
782d724ca72e68da4d921169e610b9a4
33.325203
138
0.5964
4.614208
false
false
false
false
xocialize/Kiosk
kiosk/GitHubImportManager.swift
1
8385
// // GitHubImportManager.swift // kiosk // // Created by Dustin Nielson on 5/4/15. // Copyright (c) 2015 Dustin Nielson. All rights reserved. // import Foundation class GitHubImportManager: NSObject { var gitJson = [NSDictionary]() var dm = DataManager() var settings:Dictionary<String,AnyObject> = [:] var gitUser = "" var gitRepo = "" var gitToken = "" var filesCount = 0 var working:Bool = false var gpErrorMsg:String = "" func beginImport(){ working = true gpErrorMsg = "" settings = dm.getSettings() if let user = settings["gitUser"] as? String { gitUser = user } if let repo = settings["gitRepo"] as? String { gitRepo = repo } if let token = settings["gitToken"] as? String { gitToken = token } getContents(path: "kiosk", stage: "check_kiosk") } func check_kiosk(jsonObject: AnyObject){ if let objects = jsonObject as? NSDictionary { working = false if let message:String = objects["message"] as? String { gpErrorMsg = message } else { gpErrorMsg = "Unknown Error Encountered" } } else if let objects = jsonObject as? NSArray { dm.clearLibraryDirectory() for object in objects as NSArray{ if let item:NSDictionary = object as? NSDictionary { if let type:String = item["type"] as? String{ if type == "dir" { process_directory(jsonObject) } } } } } } func process_directory(jsonObject: AnyObject){ if let objects = jsonObject as? NSArray { for object in objects as NSArray{ if let item:NSDictionary = object as? NSDictionary { if let type:String = item["type"] as? String{ if let path:String = item["path"] as? String{ if type == "dir" { getContents(path: path, stage: "process_directory") } else if type == "file" { filesCount++ getContents(path: path, stage: "process_file") } } } } } } } func process_file(jsonObject: AnyObject){ if let objects = jsonObject as? NSDictionary { if let content:String = objects["content"] as? String { if let data = NSData(base64EncodedString: objects["content"] as! String, options: NSDataBase64DecodingOptions(rawValue: 0)) { dm.saveToLibrary(data, path: objects["path"] as! String) } else { if let download_url:String = objects["download_url"] as? String { let url = NSURL(string: download_url) let urlRequest = NSURLRequest(URL: url!) NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { response,data,error in if error != nil { println(error) } else { self.dm.saveToLibrary(data, path: objects["path"] as! String) } }) } println("data decode failed. manually downloaded.") } } } filesCount-- checkCompleted() } func checkCompleted(){ if filesCount == 0 && working == true { working = false } } func getContents(path: String = "", stage: String = ""){ var jsonObject: AnyObject? var urlPath: String = "" if gitToken != "" { urlPath = "https://api.github.com/repos/\(gitUser)/\(gitRepo)/contents/\(path)?access_token=\(gitToken)" } else { urlPath = "https://api.github.com/repos/\(gitUser)/\(gitRepo)/contents/\(path)" } println(urlPath) let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in if let httpResponse = response as? NSHTTPURLResponse { if let XRateLimit = httpResponse.allHeaderFields["X-RateLimit-Remaining"] as? NSString { println("X-RateLimit-Remaining: \(XRateLimit)") } } if error != nil { println(error) } else { var jsonObject: AnyObject = self.processJson(data) switch stage { case "check_kiosk": self.check_kiosk(jsonObject) break case "process_directory": self.process_directory(jsonObject) break case "process_file": self.process_file(jsonObject) break default: println(stage) } } }) task.resume() } func processJson(data: NSData) -> AnyObject { var jsonError: NSError? var completed: AnyObject? if let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) { if let directoryArray = jsonObject as? NSArray{ completed = directoryArray as AnyObject } else if let directoryDictionary = jsonObject as? NSDictionary{ if let message:String = directoryDictionary["message"] as? String { gpErrorMsg = message } completed = directoryDictionary as AnyObject } } else { if let unwrappedError = jsonError { println("json error: \(unwrappedError)") } } return completed! } }
mit
03b534da848cc0fa2e652bc0ed43bf66
26.582237
155
0.374717
6.92403
false
false
false
false
owensd/swift-perf
src/main.swift
1
1762
/*! =========================================================================== @file main.swift @brief The performance test runner for Swift code. @copyright 2015 David Owens II. All rights reserved. ============================================================================ */ #if OPT_Ounchecked let opt = "Ounchecked" #else #if OPT_O let opt = "O" #else let opt = "Onone" #endif #endif let NumberOfSamples = 10 let NumberOfIterations = 30 let header = "Language: Swift, Optimization: -\(opt), Samples = \(NumberOfSamples), Iterations = \(NumberOfIterations)" perflib.header(header) perflib.test("RenderGradient ([Pixel])", NumberOfSamples, NumberOfIterations, renderGradient_PixelArray) perflib.test("RenderGradient ([UInt32])", NumberOfSamples, NumberOfIterations, renderGradient_PixelArray_UInt32) perflib.test("RenderGradient (UnsafeMutablePointer)", NumberOfSamples, NumberOfIterations, renderGradient_unsafeMutablePointer) perflib.test("RenderGradient (UnsafeMutablePointer<UInt32>)", NumberOfSamples, NumberOfIterations, renderGradient_unsafeMutablePointer_UInt32) perflib.test("RenderGradient ([Pixel].withUnsafeMutablePointer)", NumberOfSamples, NumberOfIterations, renderGradient_ArrayUsingUnsafeMutablePointer) perflib.test("RenderGradient ([UInt32].withUnsafeMutablePointer)", NumberOfSamples, NumberOfIterations, renderGradient_ArrayUsingUnsafeMutablePointer_UInt32) perflib.test("RenderGradient ([UInt32].withUnsafeMutablePointer (SIMD))", NumberOfSamples, NumberOfIterations, renderGradient_ArrayUsingUnsafeMutablePointer_UInt32_SIMD) perflib.test("RenderGradient ([Pixel].withUnsafeMutablePointer (SIMD))", NumberOfSamples, NumberOfIterations, renderGradient_ArrayUsingUnsafeMutablePointer_Pixel_SIMD) perflib.separator()
mit
80337fc11b8659fd1fcf15efcc299f5e
49.342857
169
0.743473
4.67374
false
true
false
false
artsy/eigen
ios/ArtsyTests/View_Controller_Tests/Live_Auction/LiveAuctionFancyLotCollectionViewLayoutTests.swift
1
4010
import Quick import Nimble import UIKit import Nimble_Snapshots @testable import Artsy class LiveAuctionFancyLotCollectionViewLayoutTests: QuickSpec { override func spec() { // This is test target-wide. beforeSuite { let fake = stub_auctionSalesPerson() for i in 0..<fake.lotCount { let lot = fake.lotViewModelForIndex(i) cacheColoredImageForURL(lot.urlForThumbnail) } } let frame = CGRect(x: 0, y: 0, width: 400, height: 400) var subject: LiveAuctionFancyLotCollectionViewLayout! var collectionView: UICollectionView! var dataSource: LiveAuctionLotCollectionViewDataSource! var container: UIView! var salesPerson: LiveAuctionsSalesPersonType! let rect = CGRect(x: 400, y: 0, width: 400, height: 400) it("looks good compact") { salesPerson = stub_auctionSalesPerson() dataSource = LiveAuctionLotCollectionViewDataSource(salesPerson: salesPerson) subject = LiveAuctionFancyLotCollectionViewLayout(delegate: dataSource, size: .compact) collectionView = UICollectionView(frame: frame, collectionViewLayout: subject) collectionView.register(LiveAuctionLotImageCollectionViewCell.self, forCellWithReuseIdentifier: LiveAuctionLotCollectionViewDataSource.CellIdentifier) collectionView.dataSource = dataSource collectionView.backgroundColor = .white container = UIView(frame: frame).then { $0.addSubview(collectionView) collectionView.align(toView: $0) } collectionView.scrollRectToVisible(rect, animated: false) expect(container) == snapshot() } describe("normal size") { beforeEach { salesPerson = stub_auctionSalesPerson() dataSource = LiveAuctionLotCollectionViewDataSource(salesPerson: salesPerson) subject = LiveAuctionFancyLotCollectionViewLayout(delegate: dataSource, size: .normal) collectionView = UICollectionView(frame: frame, collectionViewLayout: subject) collectionView.register(LiveAuctionLotImageCollectionViewCell.self, forCellWithReuseIdentifier: LiveAuctionLotCollectionViewDataSource.CellIdentifier) collectionView.dataSource = dataSource collectionView.backgroundColor = .white container = UIView(frame: frame).then { $0.addSubview(collectionView) collectionView.align(toView: $0) } collectionView.scrollRectToVisible(rect, animated: false) } it("looks good by default") { expect(container) == snapshot() } it("looks good when scrolled back a bit") { collectionView.setContentOffset(CGPoint(x: rect.origin.x-100, y: 0), animated: false) // simulates a scroll collectionView.reloadData() expect(container) == snapshot() } it("looks good when scrolled back a lot") { collectionView.setContentOffset(CGPoint(x: rect.origin.x-201, y: 0), animated: false) // simulates a scroll collectionView.reloadData() expect(container) == snapshot() } it("looks good when scrolled forward a bit") { collectionView.setContentOffset(CGPoint(x: rect.origin.x+100, y: 0), animated: false) // simulates a scroll collectionView.reloadData() expect(container) == snapshot() } it("looks good when scrolled forward a lot") { collectionView.setContentOffset(CGPoint(x: rect.origin.x+201, y: 0), animated: false) // simulates a scroll collectionView.reloadData() expect(container) == snapshot() } } } }
mit
e171b8e071cf7b9f6fc9e657bab4ed5c
41.210526
166
0.621197
5.639944
false
false
false
false
jdarowski/RGSnackBar
RGSnackBar/Classes/RGMessageSnackBarView.swift
1
8321
// // RGMessageSnackBarView.swift // RGSnackBar // // Created by Jakub Darowski on 31/08/2017. // // import UIKit import Stevia /** * The generic snack bar. * * */ open class RGMessageSnackBarView: RGMessageView { fileprivate var imageView = UIImageView() fileprivate var messageLabel = UILabel() fileprivate var blurView = UIVisualEffectView() fileprivate var actionStack = UIStackView() /// The view in which the message will be displayed var parentView: UIView /// A reference to the presenter which is presenting the snackbar var presenter: RGMessagePresenter? // ---- BEGIN STYLES ------------------------------------------------------- /// The distance between the snackbar's and `parentView`'s bottoms open var bottomMargin: CGFloat { didSet { style() } } /// The distance between the snackbar's and `parentView`'s sides open var sideMargins: CGFloat { didSet { style() } } /// Amount of curviness you desire open var cornerRadius: CGFloat { didSet { style() } } /// Font size for the message label open var textFontSize: CGFloat = 17.0 { didSet { style() } } /// Font size for the action buttons open var buttonFontSize: CGFloat = 17.0 { didSet { style() } } /// Font color for the message label open var textFontColor: UIColor = UIColor.white { didSet { style() } } /// Font color for the action buttons open var buttonFontColor: UIColor = UIColor.orange { didSet { style() } } /// Background blur effect open var backgroundBlurEffect = UIBlurEffect(style: .dark) { didSet { style() } } open var padding: UIEdgeInsets { didSet { style() } } // ---- END STYLES ------------------------------------------------------- /** * The main constructor * * - Parameter message: the message to be displayed * - Parameter containerView: The view in which the snackbar should be * displayed * - Parameter bottomMargin: the margin between the snackbar's * and the `containerView`'s bottoms * - Parameter sideMargins: the margins between the snackbar's * and the `containerView`'s sides * - Parameter cornerRadius: */ public init(message: RGMessage?, containerView: UIView, bottomMargin: CGFloat=20.0, sideMargins: CGFloat=8.0, cornerRadius: CGFloat=8.0, padding: UIEdgeInsets=UIEdgeInsets(top: 8.0, left: 20.0, bottom: 8.0, right: 20.0)) { parentView = containerView self.bottomMargin = bottomMargin self.sideMargins = sideMargins self.cornerRadius = cornerRadius self.padding = padding super.init(frame: containerView.frame, message: message) self.backgroundColor = UIColor.clear self.alpha = 0.0 parentView.addSubview(self) layoutMainView() disableTranslatingAutoresizing(self) layoutIfNeeded() } required public init?(coder aDecoder: NSCoder) { parentView = UIView() bottomMargin = 0.0 sideMargins = 0.0 cornerRadius = 0.0 padding = .zero super.init(coder: aDecoder) } override open func awakeFromNib() { super.awakeFromNib() self.layoutMainView() } /// Lays out the main snackbar view func layoutMainView() { sv(messageLabel, imageView, actionStack) self.bottom(bottomMargin) parentView.layout( |-sideMargins-self-sideMargins-| ) messageLabel.top(padding.top) if #available(iOS 11.0, *) { messageLabel.Bottom == safeAreaLayoutGuide.Bottom - padding.bottom } else { messageLabel.Bottom == Bottom - padding.bottom } self.layout( |-padding.left-imageView-messageLabel-actionStack-padding.right-| ) sv(blurView) messageLabel.numberOfLines = 0 messageLabel.textColor = UIColor.white messageLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 0), for: .horizontal) imageView.contentMode = .scaleAspectFit imageView.top(>=padding.top).bottom(>=padding.bottom) actionStack.top(padding.top) actionStack.alignment = .center actionStack.axis = .horizontal actionStack.distribution = .equalSpacing actionStack.spacing = 10.0 actionStack.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 900), for: .horizontal) if #available(iOS 11.0, *) { actionStack.Bottom == safeAreaLayoutGuide.Bottom - padding.bottom } else { actionStack.Bottom == Bottom - padding.bottom } blurView.frame = self.frame blurView.top(0).bottom(0).left(0).right(0) sendSubviewToBack(blurView) } override open func layoutMessage(_ message: RGMessage) { messageLabel.text = message.text imageView.image = message.image let imageDimension: CGFloat = imageView.image == nil ? 0.0 : 25.0 imageView.width(imageDimension).height(imageDimension) if message.text.lengthOfBytes(using: String.Encoding.utf8) > 30 || message.actions.count > 2 { actionStack.axis = .vertical } else { actionStack.axis = .horizontal } for action in message.actions { let button = RGActionButton(action: action) button.addTarget(self, action: #selector(actionTapped(_:)), for: .touchUpInside) button.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) actionStack.addArrangedSubview(button) } style() layoutIfNeeded() } override open func style() { // Buttons for button in actionStack.arrangedSubviews where button is UIButton { guard let butt = button as? UIButton else { // 😏 continue } butt.setTitleColor(buttonFontColor, for: UIControl.State()) var newFont: UIFont if let font = butt.titleLabel?.font { newFont = font.withSize(buttonFontSize) } else { newFont = UIFont.systemFont(ofSize: buttonFontSize) } butt.titleLabel?.font = newFont } // Image imageView.topConstraint?.constant = padding.top imageView.bottomConstraint?.constant = padding.bottom imageView.leftConstraint?.constant = padding.left // Message messageLabel.font = messageLabel.font.withSize(textFontSize) messageLabel.textColor = textFontColor messageLabel.topConstraint?.constant = padding.top messageLabel.bottomConstraint?.constant = -padding.bottom // Constraints self.bottomConstraint?.constant = -(bottomMargin) self.leftConstraint?.constant = sideMargins self.rightConstraint?.constant = -(sideMargins) // Actions actionStack.topConstraint?.constant = padding.top actionStack.bottomConstraint?.constant = -padding.bottom actionStack.rightConstraint?.constant = -padding.right // Corners layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0.0 // Background blurView.effect = backgroundBlurEffect // Tell UIKit what you want! setNeedsLayout() superview?.layoutIfNeeded() } override open func prepareForReuse() { messageLabel.text = nil imageView.image = nil for view in actionStack.arrangedSubviews { view.removeFromSuperview() } } @objc fileprivate func actionTapped(_ sender: RGActionButton?) { if let msg = self.message { presenter?.dismiss(msg) } } }
mit
43ac5ae2908dbe31bcf82a92a1a8405b
31.11583
95
0.588242
5.211779
false
false
false
false
noremac/UIKitExtensions
Extensions/Source/UIKit/Extensions/UIButtonExtensions.swift
1
1803
/* The MIT License (MIT) Copyright (c) 2017 Cameron Pulsford 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 UIButton { func setRelativeInsets(content: UIEdgeInsets = .zero, image: UIEdgeInsets? = nil, title: UIEdgeInsets? = nil) { guard image != nil || title != nil else { fatalError("Must define image, title, or both.") } var content = content if var image = image { content.left += image.left + image.right image.left = -image.right imageEdgeInsets = image } if var title = title { content.right += title.left + title.right title.right = -title.left titleEdgeInsets = title } contentEdgeInsets = content } }
mit
4f5de62f0f24f42806e8d38ebc482222
35.06
115
0.698835
4.846774
false
false
false
false
TongjiUAppleClub/WeCitizens
WeCitizens/DataModel.swift
1
1862
// // DataModel.swift // WeCitizens // // Created by Teng on 2/10/16. // Copyright © 2016 Tongji Apple Club. All rights reserved. // import Foundation import Parse class DataModel { func convertPFFileToImage(rawFile:PFFile?) -> UIImage? { var image:UIImage? = nil do { let imageData = try rawFile?.getData() if let data = imageData { image = UIImage(data: data) } } catch { print("") } return image } func convertArrayToImages(rawArray:NSArray) -> [UIImage] { var imageList = [UIImage]() for tmp in rawArray { let imageFile = tmp as! PFFile do { let imageData = try imageFile.getData() let image = UIImage(data: imageData) imageList.append(image!) } catch { print("") } } return imageList } func convertImageToPFFile(rawImageArray:[UIImage]) -> [PFFile] { var imageFileArray = [PFFile]() for image in rawImageArray { let imageData = UIImageJPEGRepresentation(image, 0.5) if let data = imageData { let imageFile = PFFile(name: nil, data: data) imageFileArray.append(imageFile!) } else { let imageDataPNG = UIImagePNGRepresentation(image) if let dataPNG = imageDataPNG { let imageFile = PFFile(name: nil, data: dataPNG) imageFileArray.append(imageFile!) } else { //图片格式非PNG或JPEG print("图片格式非PNG或JPEG,给用户个提示") } } } return imageFileArray } }
mit
6f6319420b77269e14eccbe6a44b1879
27.046154
68
0.499177
4.953804
false
false
false
false
hackersatcambridge/hac-website
Sources/HaCWebsiteLib/Middleware/CredentialsServer.swift
2
561
import Credentials import CredentialsHTTP import DotEnv struct CredentialsServer { static var credentials : Credentials { let credentials = Credentials() let basicCredentials = CredentialsHTTPBasic(verifyPassword: { userId, password, callback in if let storedPassword = DotEnv.get("API_PASSWORD"), storedPassword == password { callback(UserProfile(id: userId, displayName: userId, provider: "HTTPBasic")) } else { callback(nil) } }) credentials.register(plugin: basicCredentials) return credentials } }
mit
5341bbd9ab951bfad32d73b6d98c6adf
30.222222
95
0.714795
4.878261
false
false
false
false
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/model/apiclient/ConnectionOptions.swift
3
648
// // ConnectionOptions.swift // Emby.ApiClient // import Foundation public struct ConnectionOptions { public var enableWebSocket: Bool public var reportCapabilities: Bool public var updateDateLastAccessed: Bool public init(enableWebSocket: Bool, reportCapabilities: Bool, updateDateLastAccessed: Bool) { self.enableWebSocket = enableWebSocket self.reportCapabilities = reportCapabilities self.updateDateLastAccessed = updateDateLastAccessed } public init() { self.enableWebSocket = true self.reportCapabilities = true self.updateDateLastAccessed = true } }
mit
84acc73ec4b6abeccb7ab11c5c153e8d
24.96
96
0.712963
5.142857
false
false
false
false
yaoshenglong/GFDouYuZhiBo
DouYuZhiBo/DouYuZhiBo/Classes/Home/Model/Anchors.swift
1
1325
// // Anchors.swift // DouYuZhiBo // // Created by DragonYao on 2017/8/30. // Copyright © 2017年 DragonYao. All rights reserved. // import UIKit class Anchors: NSObject { var vertical_src: String = "" var nickname: String = "" var game_name: String = "" var room_name: String = "" var isVertical: Int = 0 var online: Int = 0 var avatar_mid: String = "" var room_id: String = "0" var anchor_city: String = "" init(dict:[String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} } /* "specific_catalog": "luguanfei", "vertical_src": "https://rpic.douyucdn.cn/acrpic/170830/453751_1001.jpg", "owner_uid": 27113213, "ranktype": "0", "nickname": "我叫撸管飞", "room_src": "https://rpic.douyucdn.cn/acrpic/170830/453751_1001.jpg", "cate_id": 1, "specific_status": 1, "game_name": "英雄联盟", "avatar_small": "https://apic.douyucdn.cn/upload/avatar/027/11/32/13_avatar_small.jpg", "online": "294425", "avatar_mid": "https://apic.douyucdn.cn/upload/avatar/027/11/32/13_avatar_middle.jpg", "room_name": "国服第一风暴诺克!光速血怒!", "room_id": "453751", "show_time": 1504050667, "isVertical": 0, "show_status": 1, "jumpUrl": "" */
apache-2.0
2ddb11e1530021b4024461cbbcc1cb54
23.075472
88
0.626176
2.860987
false
false
false
false
stasel/WWDC2015
StasSeldin/StasSeldin/Skills Scene/SkillsScene.swift
1
2389
// // GameScene.swift // StasSeldin // // Created by Stas Seldin on 15/04/2015. // Copyright (c) 2015 Stas Seldin. All rights reserved. // import SpriteKit class SkillsScene: SKScene { let fontSize: CGFloat = 40 var skillLabels = [SKLabelNode]() override func didMove(to view: SKView) { //Global physics let globalPhysics = SKPhysicsBody(edgeLoopFrom: self.view!.frame) globalPhysics.friction = 0.0 globalPhysics.isDynamic = false self.physicsBody = globalPhysics self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -0.05) //Create nodes for skill in Profile.me.skills { let skillNode = createSkillNode(skillText: skill) skillLabels += [skillNode] self.addChild(skillNode) } impulseAll() } func createSkillNode(skillText: String) -> (SKLabelNode) { let node = SKLabelNode(text: skillText) node.fontSize = self.fontSize let randomX = Int.random(range: 0...Int(self.frame.width)) let randomY = Int.random(range: 0...Int(self.frame.height)) node.position = CGPoint(x: randomX, y: randomY) let physics = SKPhysicsBody(rectangleOf: node.frame.size) physics.friction = 0.0 physics.restitution = 1.0 physics.linearDamping = 0.0 physics.allowsRotation = true node.physicsBody = physics return node } func impulseNode(node: SKNode) { if let physics = node.physicsBody { let f = 30 let randomVector = CGVector(dx: Int.random(range: -f...f), dy: Int.random(range: -f...f)) physics.applyImpulse(randomVector) } } func impulseAll() { for node in self.skillLabels { impulseNode(node: node) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let uiTouch = touch as UITouch let touchLocation = uiTouch.location(in: self) for node in self.skillLabels { if node.contains(touchLocation) { self.impulseNode(node: node) } } } } override func update(_ currentTime: CFTimeInterval) { } }
mit
3f62eeaac5d13c10f1fadcc012847e91
27.105882
101
0.569694
4.375458
false
false
false
false
WeMadeCode/ZXPageView
Example/Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UITextViewExtensions.swift
1
1178
// // UITextViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 9/28/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Methods public extension UITextView { /// SwifterSwift: Clear text. func clear() { text = "" attributedText = NSAttributedString(string: "") } /// SwifterSwift: Scroll to the bottom of text view func scrollToBottom() { // swiftlint:disable:next legacy_constructor let range = NSMakeRange((text as NSString).length - 1, 1) scrollRangeToVisible(range) } /// SwifterSwift: Scroll to the top of text view func scrollToTop() { // swiftlint:disable:next legacy_constructor let range = NSMakeRange(0, 1) scrollRangeToVisible(range) } /// SwifterSwift: Wrap to the content (Text / Attributed Text). func wrapToContent() { contentInset = UIEdgeInsets.zero scrollIndicatorInsets = UIEdgeInsets.zero contentOffset = CGPoint.zero textContainerInset = UIEdgeInsets.zero textContainer.lineFragmentPadding = 0 sizeToFit() } } #endif
mit
695b103745ca6fe754b00ef96f05ac30
24.042553
67
0.64486
4.726908
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/MediaContentType.swift
1
1615
// // MediaContentType.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// The possible content types for a media object. public enum MediaContentType: String { /// An externally hosted video. case externalVideo = "EXTERNAL_VIDEO" /// A Shopify hosted image. case image = "IMAGE" /// A 3d model. case model3d = "MODEL_3D" /// A Shopify hosted video. case video = "VIDEO" case unknownValue = "" } }
mit
2045afe9a4a22f115821c6c26b69554e
34.108696
81
0.726316
4.06801
false
false
false
false
roshanman/FriendCircle
FriendCircle/Classes/View/FCLikeView.swift
1
4754
// // FCLikeView.swift // FriendCircle // // Created by zhangxiuming on 2017/09/25. // import UIKit import Then protocol FCLikeViewDelegate: NSObjectProtocol { func didTapLikeUser(_ user: FCUserInfo) } class FCLikeView: UIView { var likes: [FCUserInfo]! { didSet { textView.attributedText = getAttributedText(likes: likes ?? []) textView.isScrollEnabled = likes.count > 50 } } weak var delegate: FCLikeViewDelegate? let textView = FCBaseTextView(frame: .zero).then { $0.backgroundColor = .fc $0.isEditable = false $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets(top: 4, left: 2, bottom: 4, right: 2) $0.linkTextAttributes = [ NSAttributedStringKey.foregroundColor.rawValue: UIColor.likeTextColor ] } func getAttributedText(likes: [FCUserInfo]) -> NSAttributedString { let attributed = NSMutableAttributedString() let attach = LikeViewImageAttachment().then { $0.image = UIImage.like $0.bounds = CGRect(x: 0, y: 0, width: 15, height: 15) } attributed.append(NSAttributedString(attachment: attach)) attributed.append(NSAttributedString(string: " ")) let namesAttr = likes.map { user -> NSMutableAttributedString in let attr = NSMutableAttributedString(string: user.name) let range = NSRange(0..<user.name.count) attr.addAttribute( NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 15), range: range ) attr.addAttribute( NSAttributedStringKey.link, value: user.id, range: range ) attr.addAttribute( NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range ) return attr } namesAttr.forEach { attributed.append($0) attributed.append(NSAttributedString(string: ",")) } attributed.replaceCharacters( in: NSRange(attributed.length - 1..<attributed.length), with: "" ) return attributed } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear addSubview(textView) textView.delegate = self } override func sizeThatFits(_ size: CGSize) -> CGSize { if likes.count > 50 { textView.attributedText = getAttributedText(likes: Array(likes![0..<50])) } let ret = textView.sizeThatFits(size) return CGSize(width: ret.width, height: ret.height + 10) } override func layoutSubviews() { textView.frame = CGRect(x: 0, y: 8, width: bounds.width, height: bounds.height - 10) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { guard let ctx = UIGraphicsGetCurrentContext() else { super.draw(rect) return } ctx.beginPath() let bound = CGRect(x: 0, y: 6, width: bounds.width, height: bounds.height) ctx.addRect(bound) ctx.move(to: CGPoint(x: 10, y: 6)) ctx.addLine(to: CGPoint(x: 15, y: 0)) ctx.addLine(to: CGPoint(x: 20, y: 6)) UIColor.fc.setFill() ctx.fillPath() } } extension FCLikeView: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { let userId = URL.absoluteString if let user = likes.first(where: {$0.id == userId}) { delegate?.didTapLikeUser(user) } return false } func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool { return false } } class LikeViewImageAttachment: NSTextAttachment { override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect { var bound = super.attachmentBounds(for: textContainer, proposedLineFragment: lineFrag, glyphPosition: position, characterIndex: charIndex) bound = bound.offsetBy(dx: 0, dy: -2) return bound } }
mit
8680f686e3633786a49130a783e819b0
28.515528
186
0.570076
4.934579
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Conversation/AssetCollectionBatchedTests.swift
1
18080
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // @testable import WireDataModel class AssetColletionBatchedTests: ModelObjectsTests { var sut: AssetCollectionBatched! var delegate: MockAssetCollectionDelegate! var conversation: ZMConversation! override func setUp() { super.setUp() delegate = MockAssetCollectionDelegate() conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.remoteIdentifier = UUID() uiMOC.saveOrRollback() } override func tearDown() { delegate = nil sut?.tearDown() XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) uiMOC.zm_fileAssetCache.wipeCaches() sut = nil conversation = nil super.tearDown() } var defaultMatchPair: CategoryMatch { return CategoryMatch(including: .image, excluding: .none) } @discardableResult func insertAssetMessages(count: Int) -> [ZMMessage] { var offset: TimeInterval = 0 var messages = [ZMMessage]() (0..<count).forEach { _ in let message = try! conversation.appendImage(from: verySmallJPEGData()) as! ZMMessage offset += 5 message.setValue(Date().addingTimeInterval(offset), forKey: "serverTimestamp") messages.append(message) message.setPrimitiveValue(NSNumber(value: 0), forKey: ZMMessageCachedCategoryKey) } uiMOC.saveOrRollback() return messages } func testThatItCanGetMessages_TotalMessageCountSmallerThanInitialFetchCount() { // given let totalMessageCount = AssetCollectionBatched.defaultFetchCount - 10 XCTAssertGreaterThan(totalMessageCount, 0) insertAssetMessages(count: totalMessageCount) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then XCTAssertEqual(delegate.result, .success) XCTAssertEqual(delegate.messagesByFilter.count, 1) XCTAssertTrue(sut.fetchingDone) let receivedMessageCount = delegate.messagesByFilter.first?[defaultMatchPair]?.count XCTAssertEqual(receivedMessageCount, totalMessageCount) guard let lastMessage = delegate.messagesByFilter.last?[defaultMatchPair]?.last, let context = lastMessage.managedObjectContext else { return XCTFail() } XCTAssertTrue(context.zm_isUserInterfaceContext) } func testThatItGetsMessagesInTheCorrectOrder() { // given let messages = insertAssetMessages(count: 10) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.allMessages(for: defaultMatchPair) XCTAssertTrue(receivedMessages.first!.compare(receivedMessages.last!) == .orderedDescending) XCTAssertEqual(messages.first, receivedMessages.last) XCTAssertEqual(messages.last, receivedMessages.first) } func testThatItReturnsUIObjects() { // given insertAssetMessages(count: 1) sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // when let messages = sut.assets(for: defaultMatchPair) // then XCTAssertEqual(messages.count, 1) guard let message = messages.first as? ZMMessage, let moc = message.managedObjectContext else {return XCTFail()} XCTAssertTrue(moc.zm_isUserInterfaceContext) } func testThatItCanGetMessages_TotalMessageCountEqualDefaultFetchCount() { // given let totalMessageCount = AssetCollectionBatched.defaultFetchCount insertAssetMessages(count: totalMessageCount) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then XCTAssertEqual(delegate.result, .success) XCTAssertEqual(delegate.messagesByFilter.count, 1) XCTAssertTrue(sut.fetchingDone) let receivedMessageCount = delegate.messagesByFilter.first?[defaultMatchPair]?.count XCTAssertEqual(receivedMessageCount, totalMessageCount) guard let lastMessage = delegate.messagesByFilter.last?[defaultMatchPair]?.last, let context = lastMessage.managedObjectContext else { return XCTFail() } XCTAssertTrue(context.zm_isUserInterfaceContext) } func testThatItCanGetMessages_TotalMessageCountGreaterThanInitialFetchCount() { // given let totalMessageCount = 2 * AssetCollectionBatched.defaultFetchCount insertAssetMessages(count: totalMessageCount) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then // messages were filtered in three batches XCTAssertEqual(delegate.result, .success) XCTAssertEqual(delegate.messagesByFilter.count, 2) XCTAssertTrue(sut.fetchingDone) let receivedMessages = delegate.allMessages(for: defaultMatchPair) XCTAssertEqual(receivedMessages.count, totalMessageCount) guard let lastMessage = receivedMessages.last, let context = lastMessage.managedObjectContext else { return XCTFail() } XCTAssertTrue(context.zm_isUserInterfaceContext) } func testThatItCallsTheDelegateWhenTheMessageCountIsZero() { // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then XCTAssertEqual(delegate.result, .noAssetsToFetch) XCTAssertTrue(delegate.didCallDelegate) XCTAssertTrue(sut.fetchingDone) } func testThatItCanCancelFetchingMessages() { // given let totalMessageCount = 5 * AssetCollectionBatched.defaultFetchCount insertAssetMessages(count: totalMessageCount) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) sut.tearDown() XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then // messages would filtered in three batches if the fetching was not cancelled XCTAssertNotEqual(delegate.messagesByFilter.count, 5) XCTAssertTrue(sut.fetchingDone) } func testPerformanceOfMessageFetching() { // Before caching: // 1 category, 100 paging, messages: average: 0.270, relative standard deviation: 8.876%, values: [0.341864, 0.262725, 0.264362, 0.266097, 0.260730, 0.264372, 0.257983, 0.262659, 0.260060, 0.261362], // 1 category, 200 paging, messages: average: 0.273, relative standard deviation: 9.173%, values: [0.346403, 0.260432, 0.262388, 0.263736, 0.262131, 0.278030, 0.264735, 0.265317, 0.262637, 0.261326], // 1 category, 500 paging, messages: average: 0.286, relative standard deviation: 9.671%, values: [0.368397, 0.275279, 0.274547, 0.276134, 0.275657, 0.275912, 0.274775, 0.274407, 0.278609, 0.288635] // 1 category, 1000 paging, messages: average: 0.299, relative standard deviation: 10.070%, values: [0.388566, 0.289169, 0.283670, 0.287618, 0.287593, 0.287147, 0.296063, 0.292828, 0.287014, 0.288455] // 1 category, 1000 paging, messages: average: 0.286, relative standard deviation: 9.671%, values: [0.368397, 0.275279, 0.274547, 0.276134, 0.275657, 0.275912, 0.274775, 0.274407, 0.278609, 0.288635] // 2 categories, 200 paging - average: 0.512, relative standard deviation: 4.773%, values: [0.584575, 0.500881, 0.510514, 0.499623, 0.502749, 0.502768, 0.505693, 0.502528, 0.505087, 0.503482] // 10.000 messages, 1 category, 200 paging, average: 2.960, relative standard deviation: 5.543%, values: [3.370468, 2.725436, 2.806839, 2.851691, 3.032464, 2.910135, 3.004918, 2.986125, 2.953004, 2.957812] // given insertAssetMessages(count: 1000) uiMOC.registeredObjects.forEach {uiMOC.refresh($0, mergeChanges: false)} self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: false) { // when self.startMeasuring() self.sut = AssetCollectionBatched(conversation: self.conversation, matchingCategories: [self.defaultMatchPair], delegate: self.delegate) XCTAssert(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5)) self.stopMeasuring() // then self.sut.tearDown() self.sut = nil self.uiMOC.registeredObjects.forEach {self.uiMOC.refresh($0, mergeChanges: false)} } } func testThatItReturnsPreCategorizedItems() { // given insertAssetMessages(count: 10) // when conversation.allMessages.forEach {_ = $0.cachedCategory} uiMOC.saveOrRollback() sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.allMessages(for: defaultMatchPair) XCTAssertEqual(receivedMessages.count, 10) } func testThatItGetsPreCategorizedMessagesInTheCorrectOrder() { // given let messages = insertAssetMessages(count: 10) conversation.allMessages.forEach {_ = $0.cachedCategory} uiMOC.saveOrRollback() // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.allMessages(for: defaultMatchPair) XCTAssertTrue(receivedMessages.first!.compare(receivedMessages.last!) == .orderedDescending) XCTAssertEqual(messages.first, receivedMessages.last) XCTAssertEqual(messages.last, receivedMessages.first) } func testThatItExcludesDefinedCategories_PreCategorized() { // given let data = self.data(forResource: "animated", extension: "gif")! _ = try! conversation.appendImage(from: data) as! ZMAssetClientMessage uiMOC.saveOrRollback() // when conversation.allMessages.forEach {_ = $0.cachedCategory} uiMOC.saveOrRollback() let excludingGif = CategoryMatch(including: .image, excluding: .GIF) sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [excludingGif], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.messagesByFilter.first?[excludingGif]?.count XCTAssertNil(receivedMessages) XCTAssertTrue(delegate.didCallDelegate) XCTAssertEqual(delegate.result, .noAssetsToFetch) } func testThatItExcludesDefinedCategories_NotPreCategorized() { // given let data = self.data(forResource: "animated", extension: "gif")! _ = try! conversation.appendImage(from: data) as! ZMAssetClientMessage uiMOC.saveOrRollback() // when let excludingGif = CategoryMatch(including: .image, excluding: .GIF) sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [excludingGif], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.allMessages(for: excludingGif) XCTAssertEqual(receivedMessages.count, 0) XCTAssertTrue(delegate.didCallDelegate) XCTAssertEqual(delegate.result, .noAssetsToFetch) } func testThatItFetchesImagesAndTextMessages() { // given insertAssetMessages(count: 10) try! conversation.appendText(content: "foo") uiMOC.saveOrRollback() // when let textMatchPair = CategoryMatch(including: .text, excluding: .none) sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair, textMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedAssets = delegate.allMessages(for: defaultMatchPair) XCTAssertEqual(receivedAssets.count, 10) let receivedTexts = delegate.allMessages(for: textMatchPair) XCTAssertEqual(receivedTexts.count, 1) XCTAssertEqual(delegate.result, .success) XCTAssertTrue(delegate.finished.contains(defaultMatchPair)) XCTAssertTrue(delegate.finished.contains(textMatchPair)) } func testThatItSortsExcludingCategories() { // given insertAssetMessages(count: 1) let data = self.data(forResource: "animated", extension: "gif")! _ = try! conversation.appendImage(from: data) as! ZMAssetClientMessage uiMOC.saveOrRollback() // when let excludingGif = CategoryMatch(including: .image, excluding: .GIF) let onlyGif = CategoryMatch(including: .GIF, excluding: .none) let allImages = CategoryMatch(including: .image, excluding: .none) sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [excludingGif, onlyGif, allImages], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedNonGifs = delegate.allMessages(for: excludingGif) let receivedGifs = delegate.allMessages(for: onlyGif) let receivedImages = delegate.allMessages(for: allImages) XCTAssertEqual(receivedNonGifs.count, 1) XCTAssertEqual(receivedGifs.count, 1) XCTAssertEqual(receivedImages.count, 2) XCTAssertTrue(delegate.didCallDelegate) XCTAssertEqual(delegate.result, .success) } func testThatItFetchesPreAndUncategorizedObjectsAndSavesThemAsUIDObjects() { // given let messages = insertAssetMessages(count: 20) messages[0..<10].forEach {_ = $0.cachedCategory} uiMOC.saveOrRollback() // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [defaultMatchPair], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let allMessages = sut.assets(for: defaultMatchPair) XCTAssertEqual(allMessages.count, 20) XCTAssertTrue(allMessages.allSatisfy { element in guard let message = element as? ZMMessage else { return false } return message.managedObjectContext!.zm_isUserInterfaceContext }) } func testThatItDoesNotReturnFailedToUploadAssets_Uncategorized() { // given let includedMessage = try! self.conversation.appendFile(with: ZMVideoMetadata(fileURL: self.fileURL(forResource: "video", extension: "mp4"), thumbnail: self.verySmallJPEGData())) as! ZMAssetClientMessage let excludedMessage = try! self.conversation.appendFile(with: ZMVideoMetadata(fileURL: self.fileURL(forResource: "video", extension: "mp4"), thumbnail: self.verySmallJPEGData())) as! ZMAssetClientMessage excludedMessage.transferState = .uploadingFailed excludedMessage.setPrimitiveValue(NSNumber(value: 0), forKey: ZMMessageCachedCategoryKey) includedMessage.setPrimitiveValue(NSNumber(value: 0), forKey: ZMMessageCachedCategoryKey) uiMOC.saveOrRollback() let match = CategoryMatch(including: .file, excluding: .none) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [match], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.allMessages(for: match) XCTAssertEqual(receivedMessages.count, 1) XCTAssertEqual(receivedMessages.first, includedMessage) } func testThatItDoesNotReturnFailedToUploadAssets_PreCategorized() { // given let includedMessage = try! self.conversation.appendFile(with: ZMVideoMetadata(fileURL: self.fileURL(forResource: "video", extension: "mp4"), thumbnail: self.verySmallJPEGData())) as! ZMAssetClientMessage let excludedMessage = try! self.conversation.appendFile(with: ZMVideoMetadata(fileURL: self.fileURL(forResource: "video", extension: "mp4"), thumbnail: self.verySmallJPEGData())) as! ZMAssetClientMessage excludedMessage.transferState = .uploadingFailed excludedMessage.updateCategoryCache() uiMOC.saveOrRollback() let match = CategoryMatch(including: .file, excluding: .none) // when sut = AssetCollectionBatched(conversation: conversation, matchingCategories: [match], delegate: delegate) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then let receivedMessages = delegate.allMessages(for: match) XCTAssertEqual(receivedMessages.count, 1) XCTAssertEqual(receivedMessages.first, includedMessage) } }
gpl-3.0
3bceebae792166b14971ba5bf01768a9
43.975124
213
0.702212
4.641849
false
false
false
false
Said-Re/VirtualAffairsAssignment
VirtualAffairsAssignment/VirtualAffairsAssignment/ViewController.swift
1
3948
// // ViewController.swift // VirtualAffairsAssignment // // Created by Said Rehouni on 6/6/16. // Copyright © 2016 Said Rehouni. All rights reserved. // import UIKit private let kBeginDateTableViewCellIdentifier = "beginDateTableViewCellIdentifier" private let kChooseDateTableViewCellIdentifier = "chooseDateTableViewCellIdentifier" private let kEndDateTableViewCellIdentifier = "endDateTableViewCellIdentifier" private let kBeginDateHeight = 80 private let kChooseDateHeight = 130 private let kEndDateHeight = 80 class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, TableViewInterface { @IBOutlet weak var tableView: UITableView! var beginDate : String! var endDate : String! var datePicker : NSDate! let items = [kBeginDateTableViewCellIdentifier, kChooseDateTableViewCellIdentifier, kEndDateTableViewCellIdentifier] let cellHeight = [kBeginDateHeight, kChooseDateHeight, kEndDateHeight] override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: "BeginDateTableViewCell", bundle: nil), forCellReuseIdentifier: kBeginDateTableViewCellIdentifier) tableView.registerNib(UINib(nibName: "ChooseDateTableViewCell", bundle: nil), forCellReuseIdentifier: kChooseDateTableViewCellIdentifier) tableView.registerNib(UINib(nibName: "EndDateTableViewCell", bundle: nil), forCellReuseIdentifier: kEndDateTableViewCellIdentifier) tableView.delegate = self tableView.dataSource = self tableView.scrollEnabled = false if let _ = navigationController { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Clear", style: .Plain, target: self, action: #selector(ViewController.clearDateFromView(_:))) navigationItem.title = "Schedule" } setInitialValues() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setInitialValues() { if datePicker == nil || beginDate == nil || endDate == nil { datePicker = NSDate() beginDate = "Today" endDate = datePicker.formatDateAfterWeek() } } //MARK: - TableViewInterface func updateData(date: NSDate) { datePicker = date if date == NSDate() { beginDate = "Today" } else { beginDate = date.formatDate() } endDate = date.formatDateAfterWeek() tableView.reloadData() } // MARK: - UITableView delegate func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return CGFloat(cellHeight[indexPath.row]) } // MARK: - UITableView data source func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(items[indexPath.row], forIndexPath: indexPath) if items[indexPath.row] == kChooseDateTableViewCellIdentifier { (cell as! ChooseDateTableViewCell).tableViewInterface = self (cell as! ChooseDateTableViewCell).chooseDatePicker.date = datePicker } else if items[indexPath.row] == kBeginDateTableViewCellIdentifier { (cell as! BeginDateTableViewCell).dateLabel.text = beginDate } else { (cell as! EndDateTableViewCell).dateEndLabel.text = endDate } return cell } // MARK: - IBAction methods @IBAction func clearDateFromView(sender: UIBarButtonItem) { datePicker = NSDate() beginDate = "Today" endDate = datePicker.formatDateAfterWeek() tableView.reloadData() } }
mit
8c76028d84dd91fc5a076363e4295046
34.567568
165
0.680517
5.497214
false
false
false
false
dingwilson/SwiftVideoBackground
SwiftVideoBackground/MoreViewController.swift
1
1731
import UIKit class MoreViewController: UIViewController { @IBOutlet weak var view1: UIView! @IBOutlet weak var view2: UIView! let videoBackground1 = VideoBackground() let videoBackground2 = VideoBackground() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.isNavigationBarHidden = true } // Video 1 - loads from web so takes a moment to start @IBAction func play1(_ sender: Any) { let url = URL(string: "https://storage.googleapis.com/coverr-main/mp4/Mt_Baker.mp4")! videoBackground1.play(view: view1, url: url, darkness: 0.1) } @IBAction func darker(_ sender: Any) { videoBackground1.darkness += 0.1 } @IBAction func lighter(_ sender: Any) { videoBackground1.darkness -= 0.1 } @IBAction func toggleRestart(_ sender: Any) { videoBackground1.willLoopVideo = !videoBackground1.willLoopVideo } // Video 2 @IBAction func play2(_ sender: Any) { try? videoBackground2.play(view: view2, videoName: "water", videoType: "mp4", isMuted: false) } @IBAction func pause(_ sender: Any) { videoBackground2.pause() } @IBAction func resume(_ sender: Any) { videoBackground2.resume() } @IBAction func restart(_ sender: Any) { videoBackground2.restart() } @IBAction func mute(_ sender: Any) { videoBackground2.isMuted = true } @IBAction func unmute(_ sender: Any) { videoBackground2.isMuted = false } }
mit
b76c57808ef74a8c2ea46f9954872050
26.919355
101
0.649913
4.181159
false
false
false
false
iAladdin/SwiftyFORM
Source/Cells/TextFieldCell.swift
1
11307
// // TextFieldCell.swift // SwiftyFORM // // Created by Simon Strandgaard on 01/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit public class CustomTextField: UITextField { public func configure() { backgroundColor = UIColor.whiteColor() autocapitalizationType = .Sentences autocorrectionType = .Default spellCheckingType = .No returnKeyType = .Done clearButtonMode = .WhileEditing } } public enum TextCellState { case NoMessage case TemporaryMessage(message: String) case PersistentMessage(message: String) } public class TextFieldFormItemCellSizes { public let titleLabelFrame: CGRect public let textFieldFrame: CGRect public let errorLabelFrame: CGRect public let cellHeight: CGFloat public init(titleLabelFrame: CGRect, textFieldFrame: CGRect, errorLabelFrame: CGRect, cellHeight: CGFloat) { self.titleLabelFrame = titleLabelFrame self.textFieldFrame = textFieldFrame self.errorLabelFrame = errorLabelFrame self.cellHeight = cellHeight } } public struct TextFieldFormItemCellModel { var title: String = "" var toolbarMode: ToolbarMode = .Simple var placeholder: String = "" var keyboardType: UIKeyboardType = .Default var returnKeyType: UIReturnKeyType = .Default var autocorrectionType: UITextAutocorrectionType = .No var autocapitalizationType: UITextAutocapitalizationType = .None var spellCheckingType: UITextSpellCheckingType = .No var secureTextEntry = false var model: TextFieldFormItem! = nil var valueDidChange: String -> Void = { (value: String) in DLog("value \(value)") } } public class TextFieldFormItemCell: UITableViewCell, UITextFieldDelegate, CellHeightProvider { public let model: TextFieldFormItemCellModel public let titleLabel = UILabel() public let textField = CustomTextField() public let errorLabel = UILabel() public var state: TextCellState = .NoMessage public init(model: TextFieldFormItemCellModel) { self.model = model super.init(style: .Default, reuseIdentifier: nil) self.addGestureRecognizer(tapGestureRecognizer) selectionStyle = .None titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) errorLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) errorLabel.textColor = UIColor.redColor() errorLabel.numberOfLines = 0 textField.configure() textField.delegate = self textField.addTarget(self, action: "valueDidChange:", forControlEvents: UIControlEvents.EditingChanged) contentView.addSubview(titleLabel) contentView.addSubview(textField) contentView.addSubview(errorLabel) titleLabel.text = model.title textField.placeholder = model.placeholder textField.autocapitalizationType = model.autocapitalizationType textField.autocorrectionType = model.autocorrectionType textField.keyboardType = model.keyboardType textField.returnKeyType = model.returnKeyType textField.spellCheckingType = model.spellCheckingType textField.secureTextEntry = model.secureTextEntry if self.model.toolbarMode == .Simple { textField.inputAccessoryView = toolbar } updateErrorLabel(model.model.liveValidateValueText()) // titleLabel.backgroundColor = UIColor.blueColor() // textField.backgroundColor = UIColor.greenColor() // errorLabel.backgroundColor = UIColor.yellowColor() clipsToBounds = true } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public lazy var toolbar: SimpleToolbar = { let instance = SimpleToolbar() weak var weakSelf = self instance.jumpToPrevious = { if let cell = weakSelf { cell.gotoPrevious() } } instance.jumpToNext = { if let cell = weakSelf { cell.gotoNext() } } instance.dismissKeyboard = { if let cell = weakSelf { cell.dismissKeyboard() } } return instance }() public func updateToolbarButtons() { if model.toolbarMode == .Simple { toolbar.updateButtonConfiguration(self) } } public func gotoPrevious() { DLog("make previous cell first responder") form_makePreviousCellFirstResponder() } public func gotoNext() { DLog("make next cell first responder") form_makeNextCellFirstResponder() } public func dismissKeyboard() { DLog("dismiss keyboard") resignFirstResponder() } public func handleTap(sender: UITapGestureRecognizer) { textField.becomeFirstResponder() } public lazy var tapGestureRecognizer: UITapGestureRecognizer = { let gr = UITapGestureRecognizer(target: self, action: "handleTap:") return gr }() public enum TitleWidthMode { case Auto case Assign(width: CGFloat) } public var titleWidthMode: TitleWidthMode = .Auto public func compute(cellWidth: CGFloat) -> TextFieldFormItemCellSizes { var titleLabelFrame = CGRectZero var textFieldFrame = CGRectZero var errorLabelFrame = CGRectZero var cellHeight: CGFloat = 0 let veryTallCell = CGRectMake(0, 0, cellWidth, CGFloat.max) let area = veryTallCell.rectByInsetting(dx: 16, dy: 0) let (topRect, _) = area.rectsByDividing(44, fromEdge: .MinYEdge) if true { let size = titleLabel.sizeThatFits(area.size) var titleLabelWidth = size.width switch titleWidthMode { case .Auto: break case let .Assign(width): let w = CGFloat(width) if w > titleLabelWidth { titleLabelWidth = w } } var (slice, remainder) = topRect.rectsByDividing(titleLabelWidth, fromEdge: .MinXEdge) titleLabelFrame = slice (_, remainder) = remainder.rectsByDividing(10, fromEdge: .MinXEdge) remainder.size.width += 4 textFieldFrame = remainder cellHeight = ceil(textFieldFrame.height) } if true { let size = errorLabel.sizeThatFits(area.size) // DLog("error label size \(size)") if size.height > 0.1 { var r = topRect r.origin.y = topRect.maxY - 6 let (slice, _) = r.rectsByDividing(size.height, fromEdge: .MinYEdge) errorLabelFrame = slice cellHeight = ceil(errorLabelFrame.maxY + 10) } } return TextFieldFormItemCellSizes(titleLabelFrame: titleLabelFrame, textFieldFrame: textFieldFrame, errorLabelFrame: errorLabelFrame, cellHeight: cellHeight) } public override func layoutSubviews() { super.layoutSubviews() //DLog("layoutSubviews") let sizes: TextFieldFormItemCellSizes = compute(bounds.width) titleLabel.frame = sizes.titleLabelFrame textField.frame = sizes.textFieldFrame errorLabel.frame = sizes.errorLabelFrame } public func valueDidChange(sender: AnyObject?) { //DLog("did change") model.valueDidChange(textField.text ?? "") let result: ValidateResult = model.model.liveValidateValueText() switch result { case .Valid: DLog("valid") case .HardInvalid: DLog("hard invalid") case .SoftInvalid: DLog("soft invalid") } } public func setValueWithoutSync(value: String) { DLog("set value \(value)") textField.text = value validateAndUpdateErrorIfNeeded(value, shouldInstallTimer: false, checkSubmitRule: false) } // Hide the keyboard when the user taps the return key in this UITextField public func textFieldShouldReturn(textField: UITextField) -> Bool { let s = textField.text ?? "" let isTextValid = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: true, checkSubmitRule: true) if isTextValid { textField.resignFirstResponder() } return false } public func updateErrorLabel(result: ValidateResult) { switch result { case .Valid: errorLabel.text = nil case .HardInvalid(let message): errorLabel.text = message case .SoftInvalid(let message): errorLabel.text = message } } public var lastResult: ValidateResult? public var hideErrorMessageAfterFewSecondsTimer: NSTimer? public func invalidateTimer() { if let timer = hideErrorMessageAfterFewSecondsTimer { timer.invalidate() hideErrorMessageAfterFewSecondsTimer = nil } } public func installTimer() { invalidateTimer() let timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "timerUpdate", userInfo: nil, repeats: false) hideErrorMessageAfterFewSecondsTimer = timer } // Returns true when valid // Returns false when invalid public func validateAndUpdateErrorIfNeeded(text: String, shouldInstallTimer: Bool, checkSubmitRule: Bool) -> Bool { let tableView: UITableView? = form_tableView() let result: ValidateResult = model.model.validateText(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: checkSubmitRule) if let lastResult = lastResult { if lastResult == result { switch result { case .Valid: //DLog("same valid") return true case .HardInvalid: //DLog("same hard invalid") invalidateTimer() if shouldInstallTimer { installTimer() } return false case .SoftInvalid: //DLog("same soft invalid") invalidateTimer() if shouldInstallTimer { installTimer() } return true } } } lastResult = result switch result { case .Valid: //DLog("different valid") if let tv = tableView { tv.beginUpdates() errorLabel.text = nil setNeedsLayout() tv.endUpdates() invalidateTimer() } return true case let .HardInvalid(message): //DLog("different hard invalid") if let tv = tableView { tv.beginUpdates() errorLabel.text = message setNeedsLayout() tv.endUpdates() invalidateTimer() if shouldInstallTimer { installTimer() } } return false case let .SoftInvalid(message): //DLog("different soft invalid") if let tv = tableView { tv.beginUpdates() errorLabel.text = message setNeedsLayout() tv.endUpdates() invalidateTimer() if shouldInstallTimer { installTimer() } } return true } } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let textFieldString: NSString = textField.text ?? "" let s = textFieldString.stringByReplacingCharactersInRange(range, withString:string) let valid = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: true, checkSubmitRule: false) return valid } public func timerUpdate() { invalidateTimer() //DLog("timer update") let s = textField.text ?? "" validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: false, checkSubmitRule: false) } public func reloadPersistentValidationState() { invalidateTimer() //DLog("reload persistent message") let s = textField.text ?? "" validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: false, checkSubmitRule: true) } public func form_cellHeight(indexPath: NSIndexPath, tableView: UITableView) -> CGFloat { let sizes: TextFieldFormItemCellSizes = compute(bounds.width) let value = sizes.cellHeight //DLog("compute height of row: \(value)") return value } public func textFieldDidBeginEditing(textField: UITextField) { updateToolbarButtons() } // MARK: UIResponder public override func canBecomeFirstResponder() -> Bool { return true } public override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } public override func resignFirstResponder() -> Bool { return textField.resignFirstResponder() } }
mit
538792fcdd2a21283e089a7c3eb94f62
26.050239
159
0.733351
4.058507
false
false
false
false
intmain/HairPowder
Sources/HairPowder.swift
1
3209
// // HairPowder.swift // iphonex // // Created by Leonard on 2017. 9. 20.. // Copyright © 2017년 intmain. All rights reserved. // import UIKit open class HairPowder { public static let instance = HairPowder() private class HairPowderView: UIView { static let cornerRadius: CGFloat = 40 static let cornerY: CGFloat = 35 override func draw(_ rect: CGRect) { let width = frame.width > frame.height ? frame.height : frame.width let rectPath = UIBezierPath() rectPath.move(to: CGPoint(x:0, y:0)) rectPath.addLine(to: CGPoint(x: width, y: 0)) rectPath.addLine(to: CGPoint(x: width, y: HairPowderView.cornerY)) rectPath.addLine(to: CGPoint(x: 0, y: HairPowderView.cornerY)) rectPath.close() rectPath.fill() let leftCornerPath = UIBezierPath() leftCornerPath.move(to: CGPoint(x: 0, y: HairPowderView.cornerY + HairPowderView.cornerRadius)) leftCornerPath.addLine(to: CGPoint(x: 0, y: HairPowderView.cornerY)) leftCornerPath.addLine(to: CGPoint(x: HairPowderView.cornerRadius, y: HairPowderView.cornerY)) leftCornerPath.addQuadCurve(to: CGPoint(x: 0, y: HairPowderView.cornerY+HairPowderView.cornerRadius), controlPoint: CGPoint(x: 0, y: HairPowderView.cornerY)) leftCornerPath.close() leftCornerPath.fill() let rightCornerPath = UIBezierPath() rightCornerPath.move(to: CGPoint(x: width, y: HairPowderView.cornerY+HairPowderView.cornerRadius)) rightCornerPath.addLine(to: CGPoint(x: width, y: HairPowderView.cornerY)) rightCornerPath.addLine(to: CGPoint(x: width-HairPowderView.cornerRadius, y: HairPowderView.cornerY)) rightCornerPath.addQuadCurve(to: CGPoint(x: width, y: 35+HairPowderView.cornerRadius), controlPoint: CGPoint(x: width, y: HairPowderView.cornerY)) rightCornerPath.close() rightCornerPath.fill() } } private var statusWindow: UIWindow = { let width = UIApplication.shared.keyWindow?.frame.width ?? 0 let height = UIApplication.shared.keyWindow?.frame.height ?? 0 let statusWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: width, height: 0)) statusWindow.windowLevel = UIWindowLevelStatusBar - 1 let hairPowderView = HairPowderView(frame: CGRect(x: 0, y: 0, width: width, height: height)) hairPowderView.backgroundColor = UIColor.clear hairPowderView.clipsToBounds = true statusWindow.addSubview(hairPowderView) return statusWindow }() public func spread() { guard let window = UIApplication.shared.keyWindow else { return } if #available(iOS 11.0, *) { if window.safeAreaInsets.top > 0.0 { DispatchQueue.main.async { [weak self] in self?.statusWindow.makeKeyAndVisible() DispatchQueue.main.async { [weak self] in window.makeKey() } } } } } }
mit
3e350b47007d6384ad237fa3ffe87eb4
41.746667
170
0.616344
3.943419
false
false
false
false
hth/StepSlider
Slider/Slider.swift
1
24738
import UIKit public enum ComponentStyle:Int { case iOS = 0 case rectangular case rounded case invisible case image } public protocol TGPControlsTicksProtocol { func tgpTicksDistanceChanged(ticksDistance:CGFloat, sender:AnyObject) func tgpValueChanged(value:UInt) } // Interface builder hides the IBInspectable for UIControl #if TARGET_INTERFACE_BUILDER public class TGPSlider_INTERFACE_BUILDER:UIView { } #else // !TARGET_INTERFACE_BUILDER public class TGPSlider_INTERFACE_BUILDER:UIControl { } #endif // TARGET_INTERFACE_BUILDER @IBDesignable public class TGPDiscreteSlider:TGPSlider_INTERFACE_BUILDER { @IBInspectable public var tickStyle:Int = ComponentStyle.rectangular.rawValue { didSet { layoutTrack() } } @IBInspectable public var tickSize:CGSize = CGSize(width:1, height:4) { didSet { tickSize.width = max(0, tickSize.width) tickSize.height = max(0, tickSize.height) layoutTrack() } } @IBInspectable public var tickCount:Int = 11 { didSet { tickCount = max(2, tickCount) layoutTrack() } } @IBInspectable public var tickImage:UIImage? = nil { didSet { layoutTrack() } } @IBInspectable public var trackStyle:Int = ComponentStyle.iOS.rawValue { didSet { layoutTrack() } } @IBInspectable public var trackThickness:CGFloat = 2 { didSet { trackThickness = max(0, trackThickness) layoutTrack() } } @IBInspectable public var trackImage:UIImage? = nil { didSet { layoutTrack() } } @IBInspectable public var minimumTrackTintColor:UIColor? = nil { didSet { layoutTrack() } } @IBInspectable public var maximumTrackTintColor:UIColor = UIColor(white: 0.71, alpha: 1) { didSet { layoutTrack() } } @IBInspectable public var thumbStyle:Int = ComponentStyle.iOS.rawValue { didSet { layoutTrack() } } @IBInspectable public var thumbSize:CGSize = CGSize(width:10, height:10) { didSet { thumbSize.width = max(1, thumbSize.width) thumbSize.height = max(1, thumbSize.height) layoutTrack() } } @IBInspectable public var thumbTintColor:UIColor? = nil { didSet { layoutTrack() } } @IBInspectable public var thumbImage:UIImage? = nil { didSet { if let thumbImage = thumbImage { thumbLayer.contents = thumbImage.cgImage } else { thumbLayer.contents = nil } layoutTrack() } } @IBInspectable public var thumbShadowRadius:CGFloat = 0 { didSet { layoutTrack() } } @IBInspectable public var thumbShadowOffset:CGSize = CGSize.zero { didSet { layoutTrack() } } @IBInspectable public var incrementValue:Int = 1 { didSet { if(0 == incrementValue) { incrementValue = 1; // nonZeroIncrement } layoutTrack() } } // MARK: UISlider substitution // AKA: UISlider value (as CGFloat for compatibility with UISlider API, but expected to contain integers) @IBInspectable public var minimumValue:CGFloat { get { return CGFloat(intMinimumValue) } set { intMinimumValue = Int(newValue) layoutTrack() } } @IBInspectable public var value:CGFloat { get { return CGFloat(intValue) } set { intValue = Int(newValue) layoutTrack() } } // MARK: @IBInspectable adapters public var tickComponentStyle:ComponentStyle { get { return ComponentStyle(rawValue: tickStyle) ?? .rectangular } set { tickStyle = newValue.rawValue } } public var trackComponentStyle:ComponentStyle { get { return ComponentStyle(rawValue: trackStyle) ?? .iOS } set { trackStyle = newValue.rawValue } } public var thumbComponentStyle:ComponentStyle { get { return ComponentStyle(rawValue: thumbStyle) ?? .iOS } set { thumbStyle = newValue.rawValue } } // MARK: Properties public override var tintColor: UIColor! { didSet { layoutTrack() } } public override var bounds: CGRect { didSet { layoutTrack() } } public var ticksDistance:CGFloat { get { assert(tickCount > 1, "2 ticks minimum \(tickCount)") let segments = CGFloat(max(1, tickCount - 1)) return trackRectangle.width / segments } set {} } public var ticksListener:TGPControlsTicksProtocol? = nil { didSet { ticksListener?.tgpTicksDistanceChanged(ticksDistance: ticksDistance, sender: self) } } var intValue:Int = 0 var intMinimumValue = -5 var ticksAbscisses:[CGPoint] = [] var thumbAbscisse:CGFloat = 0 var thumbLayer = CALayer() var leftTrackLayer = CALayer() var rightTrackLayer = CALayer() var trackLayer = CALayer() var ticksLayer = CALayer() var trackRectangle = CGRect.zero var touchedInside = false let iOSThumbShadowRadius:CGFloat = 4 let iOSThumbShadowOffset = CGSize(width:0, height:3) // MARK: UIControl required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initProperties() } override init(frame: CGRect) { super.init(frame: frame) initProperties() } public override func draw(_ rect: CGRect) { drawTrack() drawTicks() drawThumb() } func sendActionsForControlEvents() { // Automatic UIControlEventValueChanged notification if let ticksListener = ticksListener { ticksListener.tgpValueChanged(value: UInt(value-minimumValue)) } } // MARK: TGPDiscreteSlider func initProperties() { // Track is a clear clipping layer, and left + right sublayers, which brings in free animation trackLayer.masksToBounds = true trackLayer.backgroundColor = UIColor.clear.cgColor layer.addSublayer(trackLayer) if let backgroundColor = tintColor { leftTrackLayer.backgroundColor = backgroundColor.cgColor } trackLayer.addSublayer(leftTrackLayer) rightTrackLayer.backgroundColor = maximumTrackTintColor.cgColor trackLayer.addSublayer(rightTrackLayer) // Ticks in between track and thumb layer.addSublayer(ticksLayer) // The thumb is its own CALayer, which brings in free animation layer.addSublayer(thumbLayer) isMultipleTouchEnabled = false layoutTrack() } func drawTicks() { ticksLayer.frame = bounds if let backgroundColor = tintColor { ticksLayer.backgroundColor = backgroundColor.cgColor } let path = UIBezierPath() switch tickComponentStyle { case .rounded: fallthrough case .rectangular: fallthrough case .image: for originPoint in ticksAbscisses { let rectangle = CGRect(x: originPoint.x-(tickSize.width/2), y: originPoint.y-(tickSize.height/2), width: tickSize.width, height: tickSize.height) switch tickComponentStyle { case .rounded: path.append(UIBezierPath(roundedRect: rectangle, cornerRadius: rectangle.height/2)) case .rectangular: path.append(UIBezierPath(rect: rectangle)) case .image: // Draw image if exists if let image = tickImage, let cgImage = image.cgImage, let ctx = UIGraphicsGetCurrentContext() { let centered = CGRect(x: rectangle.origin.x + (rectangle.width/2) - (image.size.width/2), y: rectangle.origin.y + (rectangle.height/2) - (image.size.height/2), width: image.size.width, height: image.size.height) ctx.draw(cgImage, in: centered) } case .invisible: fallthrough case .iOS: fallthrough default: assert(false) break } } case .invisible: fallthrough case .iOS: fallthrough default: // Nothing to draw break } let maskLayer = CAShapeLayer() maskLayer.frame = trackLayer.bounds maskLayer.path = path.cgPath ticksLayer.mask = maskLayer } func drawTrack() { switch(trackComponentStyle) { case .rectangular: trackLayer.frame = trackRectangle trackLayer.cornerRadius = 0.0 case .invisible: trackLayer.frame = CGRect.zero case .image: trackLayer.frame = CGRect.zero // Draw image if exists if let image = trackImage, let cgImage = image.cgImage, let ctx = UIGraphicsGetCurrentContext() { let centered = CGRect(x: (frame.width/2) - (image.size.width/2), y: (frame.height/2) - (image.size.height/2), width: image.size.width, height: image.size.height) ctx.draw(cgImage, in: centered) } case .rounded: fallthrough case .iOS: fallthrough default: trackLayer.frame = trackRectangle trackLayer.cornerRadius = trackRectangle.height/2 break } leftTrackLayer.frame = { var frame = trackLayer.bounds frame.size.width = thumbAbscisse - trackRectangle.minX return frame }() if let backgroundColor = minimumTrackTintColor ?? tintColor { leftTrackLayer.backgroundColor = backgroundColor.cgColor } rightTrackLayer.frame = { var frame = trackLayer.bounds frame.size.width = trackRectangle.width - leftTrackLayer.frame.width frame.origin.x = leftTrackLayer.frame.maxX return frame }() rightTrackLayer.backgroundColor = maximumTrackTintColor.cgColor } func drawThumb() { if( value >= minimumValue) { // Feature: hide the thumb when below range let thumbSizeForStyle = thumbSizeIncludingShadow() let thumbWidth = thumbSizeForStyle.width let thumbHeight = thumbSizeForStyle.height let rectangle = CGRect(x:thumbAbscisse - (thumbWidth / 2), y: (frame.height - thumbHeight)/2, width: thumbWidth, height: thumbHeight) let shadowRadius = (thumbComponentStyle == .iOS) ? iOSThumbShadowRadius : thumbShadowRadius let shadowOffset = (thumbComponentStyle == .iOS) ? iOSThumbShadowOffset : thumbShadowOffset thumbLayer.frame = ((shadowRadius != 0.0) // Ignore offset if there is no shadow ? rectangle.insetBy(dx: shadowRadius + shadowOffset.width, dy: shadowRadius + shadowOffset.height) : rectangle.insetBy(dx: shadowRadius, dy: shadowRadius)) switch thumbComponentStyle { case .rounded: // A rounded thumb is circular thumbLayer.backgroundColor = (thumbTintColor ?? UIColor.lightGray).cgColor thumbLayer.borderColor = UIColor.clear.cgColor thumbLayer.borderWidth = 0.0 thumbLayer.cornerRadius = thumbLayer.frame.width/2 thumbLayer.allowsEdgeAntialiasing = true case .image: // image is set using layer.contents thumbLayer.backgroundColor = UIColor.clear.cgColor thumbLayer.borderColor = UIColor.clear.cgColor thumbLayer.borderWidth = 0.0 thumbLayer.cornerRadius = 0.0 thumbLayer.allowsEdgeAntialiasing = false case .rectangular: thumbLayer.backgroundColor = (thumbTintColor ?? UIColor.lightGray).cgColor thumbLayer.borderColor = UIColor.clear.cgColor thumbLayer.borderWidth = 0.0 thumbLayer.cornerRadius = 0.0 thumbLayer.allowsEdgeAntialiasing = false case .invisible: thumbLayer.backgroundColor = UIColor.clear.cgColor thumbLayer.cornerRadius = 0.0 case .iOS: fallthrough default: thumbLayer.backgroundColor = (thumbTintColor ?? UIColor.white).cgColor // Only default iOS thumb has a border if nil == thumbTintColor { let borderColor = UIColor(white:0.5, alpha: 1) thumbLayer.borderColor = borderColor.cgColor thumbLayer.borderWidth = 0.25 } else { thumbLayer.borderWidth = 0 } thumbLayer.cornerRadius = thumbLayer.frame.width/2 thumbLayer.allowsEdgeAntialiasing = true break } // Shadow if(shadowRadius != 0.0) { #if TARGET_INTERFACE_BUILDER thumbLayer.shadowOffset = CGSize(width: shadowOffset.width, height: -shadowOffset.height) #else // !TARGET_INTERFACE_BUILDER thumbLayer.shadowOffset = shadowOffset #endif // TARGET_INTERFACE_BUILDER thumbLayer.shadowRadius = shadowRadius thumbLayer.shadowColor = UIColor.black.cgColor thumbLayer.shadowOpacity = 0.15 } else { thumbLayer.shadowRadius = 0.0 thumbLayer.shadowOffset = CGSize.zero thumbLayer.shadowColor = UIColor.clear.cgColor thumbLayer.shadowOpacity = 0.0 } } } func layoutTrack() { assert(tickCount > 1, "2 ticks minimum \(tickCount)") let segments = max(1, tickCount - 1) let thumbWidth = thumbSizeIncludingShadow().width // Calculate the track ticks positions let trackHeight = (.iOS == trackComponentStyle) ? 2 : trackThickness var trackSize = CGSize(width: frame.width - thumbWidth, height: trackHeight) if(.image == trackComponentStyle) { if let image = trackImage { trackSize.width = image.size.width - thumbWidth } } trackRectangle = CGRect(x: (frame.width - trackSize.width)/2, y: (frame.height - trackSize.height)/2, width: trackSize.width, height: trackSize.height) let gradient = CAGradientLayer() gradient.frame = trackRectangle gradient.colors = [UIColor.init(colorLiteralRed: 253.0 / 255.0, green: 59.0 / 255.0, blue: 25.0 / 255.0, alpha: 1.0).cgColor, UIColor.init(colorLiteralRed: 235.0 / 255.0, green: 54.0 / 255.0, blue: 118.0 / 255.0, alpha: 1.0).cgColor] gradient.startPoint = CGPoint(x: 0.0, y: 0.5) gradient.endPoint = CGPoint(x: 1.0, y: 0.5) self.layer.insertSublayer(gradient, at: 0) let trackY = frame.height / 2 ticksAbscisses = [] for iterate in 0 ... segments { let ratio = Double(iterate) / Double(segments) let originX = trackRectangle.origin.x + (CGFloat)(trackSize.width * CGFloat(ratio)) ticksAbscisses.append(CGPoint(x: originX, y: trackY)) } layoutThumb() // If we have a TGPDiscreteSliderTicksListener (such as TGPCamelLabels), broadcast new spacing ticksListener?.tgpTicksDistanceChanged(ticksDistance:ticksDistance, sender:self) setNeedsDisplay() } func layoutThumb() { assert(tickCount > 1, "2 ticks minimum \(tickCount)") let segments = max(1, tickCount - 1) // Calculate the thumb position let nonZeroIncrement = ((0 == incrementValue) ? 1 : incrementValue) var thumbRatio = Double(value - minimumValue) / Double(segments * nonZeroIncrement) thumbRatio = max(0.0, min(thumbRatio, 1.0)) // Normalized thumbAbscisse = trackRectangle.origin.x + (CGFloat)(trackRectangle.width * CGFloat(thumbRatio)) } func thumbSizeIncludingShadow() -> CGSize { switch thumbComponentStyle { case .invisible: fallthrough case .rectangular: fallthrough case .rounded: return ((thumbShadowRadius != 0.0) ? CGSize(width:thumbSize.width + (thumbShadowRadius * 2) + (thumbShadowOffset.width * 2), height: thumbSize.height + (thumbShadowRadius * 2) + (thumbShadowOffset.height * 2)) : thumbSize) case .iOS: return CGSize(width: 28.0 + (iOSThumbShadowRadius * 2) + (iOSThumbShadowOffset.width * 2), height: 28.0 + (iOSThumbShadowRadius * 2) + (iOSThumbShadowOffset.height * 2)) case .image: if let thumbImage = thumbImage { return thumbImage.size } fallthrough default: return CGSize(width: 33, height: 33) } } // MARK: UIResponder public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { touchedInside = true touchDown(touches, animationDuration: 0.1) sendActionForControlEvent(controlEvent: .valueChanged, with: event) sendActionForControlEvent(controlEvent: .touchDown, with:event) if let touch = touches.first { if touch.tapCount > 1 { sendActionForControlEvent(controlEvent: .touchDownRepeat, with: event) } } } public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { touchDown(touches, animationDuration:0) let inside = touchesAreInside(touches) sendActionForControlEvent(controlEvent: .valueChanged, with: event) if inside != touchedInside { // Crossing boundary sendActionForControlEvent(controlEvent: (inside) ? .touchDragEnter : .touchDragExit, with: event) touchedInside = inside } // Drag sendActionForControlEvent(controlEvent: (inside) ? .touchDragInside : .touchDragOutside, with: event) } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { touchUp(touches) sendActionForControlEvent(controlEvent: .valueChanged, with: event) sendActionForControlEvent(controlEvent: (touchesAreInside(touches)) ? .touchUpInside : .touchUpOutside, with: event) } public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { touchUp(touches) sendActionForControlEvent(controlEvent: .valueChanged, with:event) sendActionForControlEvent(controlEvent: .touchCancel, with:event) } // MARK: Touches func touchDown(_ touches: Set<UITouch>, animationDuration duration:TimeInterval) { if let touch = touches.first { let location = touch.location(in: touch.view) moveThumbTo(abscisse: location.x, animationDuration: duration) } } func touchUp(_ touches: Set<UITouch>) { if let touch = touches.first { let location = touch.location(in: touch.view) let tick = pickTickFromSliderPosition(abscisse: location.x) moveThumbToTick(tick: tick) } } func touchesAreInside(_ touches: Set<UITouch>) -> Bool { var inside = false if let touch = touches.first { let location = touch.location(in: touch.view) if let bounds = touch.view?.bounds { inside = bounds.contains(location) } } return inside } // MARK: Notifications func moveThumbToTick(tick: UInt) { let nonZeroIncrement = ((0 == incrementValue) ? 1 : incrementValue) let intValue = Int(minimumValue) + (Int(tick) * nonZeroIncrement) if intValue != self.intValue { self.intValue = intValue sendActionsForControlEvents() } layoutThumb() setNeedsDisplay() } func moveThumbTo(abscisse:CGFloat, animationDuration duration:TimeInterval) { let leftMost = trackRectangle.minX let rightMost = trackRectangle.maxX thumbAbscisse = max(leftMost, min(abscisse, rightMost)) CATransaction.setAnimationDuration(duration) let tick = pickTickFromSliderPosition(abscisse: thumbAbscisse) let nonZeroIncrement = ((0 == incrementValue) ? 1 : incrementValue) let intValue = Int(minimumValue) + (Int(tick) * nonZeroIncrement) if intValue != self.intValue { self.intValue = intValue sendActionsForControlEvents() } setNeedsDisplay() } func pickTickFromSliderPosition(abscisse: CGFloat) -> UInt { let leftMost = trackRectangle.minX let rightMost = trackRectangle.maxX let clampedAbscisse = max(leftMost, min(abscisse, rightMost)) let ratio = Double(clampedAbscisse - leftMost) / Double(rightMost - leftMost) let segments = max(1, tickCount - 1) return UInt(round( Double(segments) * ratio)) } func sendActionForControlEvent(controlEvent:UIControlEvents, with event:UIEvent?) { for target in allTargets { if let caActions = actions(forTarget: target, forControlEvent: controlEvent) { for actionName in caActions { sendAction(NSSelectorFromString(actionName), to: target, for: event) } } } } #if TARGET_INTERFACE_BUILDER // MARK: TARGET_INTERFACE_BUILDER stub // Interface builder hides the IBInspectable for UIControl let allTargets: Set<AnyHashable> = Set() func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) {} func actions(forTarget target: Any?, forControlEvent controlEvent: UIControlEvents) -> [String]? { return nil } func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {} #endif // TARGET_INTERFACE_BUILDER }
mit
6a5b28adf12a70948a73c042a9469df8
33.647059
241
0.547983
5.315428
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Timer.swift
8
4340
// // Timer.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType where Element: RxAbstractInteger { /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) - parameter period: Period for producing the values in the resulting sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence that produces a value after each period. */ public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) -> Observable<Element> { return Timer( dueTime: period, period: period, scheduler: scheduler ) } } extension ObservableType where Element: RxAbstractInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - parameter scheduler: Scheduler to run timers on. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) -> Observable<Element> { return Timer( dueTime: dueTime, period: period, scheduler: scheduler ) } } import Foundation final private class TimerSink<Observer: ObserverType> : Sink<Observer> where Observer.Element : RxAbstractInteger { typealias Parent = Timer<Observer.Element> private let parent: Parent private let lock = RecursiveLock() init(parent: Parent, observer: Observer, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return self.parent.scheduler.schedulePeriodic(0 as Observer.Element, startAfter: self.parent.dueTime, period: self.parent.period!) { state in self.lock.performLocked { self.forwardOn(.next(state)) return state &+ 1 } } } } final private class TimerOneOffSink<Observer: ObserverType>: Sink<Observer> where Observer.Element: RxAbstractInteger { typealias Parent = Timer<Observer.Element> private let parent: Parent init(parent: Parent, observer: Observer, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return self.parent.scheduler.scheduleRelative(self, dueTime: self.parent.dueTime) { [unowned self] _ -> Disposable in self.forwardOn(.next(0)) self.forwardOn(.completed) self.dispose() return Disposables.create() } } } final private class Timer<Element: RxAbstractInteger>: Producer<Element> { fileprivate let scheduler: SchedulerType fileprivate let dueTime: RxTimeInterval fileprivate let period: RxTimeInterval? init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { self.scheduler = scheduler self.dueTime = dueTime self.period = period } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { if self.period != nil { let sink = TimerSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } else { let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } }
mit
990e8f836862fae5d101e7e743156b6b
36.08547
174
0.671122
4.919501
false
false
false
false
lkzhao/Hero
Sources/HeroViewControllerDelegate.swift
1
2655
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(UIKit) import UIKit @objc public protocol HeroViewControllerDelegate { @objc optional func heroWillStartAnimatingFrom(viewController: UIViewController) @objc optional func heroDidEndAnimatingFrom(viewController: UIViewController) @objc optional func heroDidCancelAnimatingFrom(viewController: UIViewController) @objc optional func heroWillStartTransition() @objc optional func heroDidEndTransition() @objc optional func heroDidCancelTransition() @objc optional func heroWillStartAnimatingTo(viewController: UIViewController) @objc optional func heroDidEndAnimatingTo(viewController: UIViewController) @objc optional func heroDidCancelAnimatingTo(viewController: UIViewController) } // delegate helper internal extension HeroTransition { func closureProcessForHeroDelegate<T: UIViewController>(vc: T, closure: (HeroViewControllerDelegate) -> Void) { if let delegate = vc as? HeroViewControllerDelegate { closure(delegate) } if let navigationController = vc as? UINavigationController, let delegate = navigationController.topViewController as? HeroViewControllerDelegate { closure(delegate) } else if let tabBarController = vc as? UITabBarController, let delegate = tabBarController.selectedViewController as? HeroViewControllerDelegate { closure(delegate) } else { for vc in vc.children where vc.isViewLoaded { self.closureProcessForHeroDelegate(vc: vc, closure: closure) } } } } #endif
mit
6844a33bae25512fe0d91e566b7bb61b
41.822581
113
0.772128
4.880515
false
false
false
false
mohamede1945/quran-ios
Quran/TranslationsViewController.swift
1
4757
// // TranslationsViewController.swift // Quran // // Created by Mohamed Afifi on 2/22/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import GenericDataSources import UIKit class TranslationsViewController: BaseTableBasedViewController, TranslationsDataSourceDelegate, EditControllerDelegate { override var screen: Analytics.Screen { return .translations } let editController = EditController(usesRightBarButton: true) private let dataSource: TranslationsDataSource private let interactor: AnyGetInteractor<[TranslationFull]> private let localTranslationsInteractor: AnyGetInteractor<[TranslationFull]> private var activityIndicator: UIActivityIndicatorView? { return navigationItem.leftBarButtonItem?.customView as? UIActivityIndicatorView } init(interactor: AnyGetInteractor<[TranslationFull]>, localTranslationsInteractor: AnyGetInteractor<[TranslationFull]>, dataSource: TranslationsDataSource) { self.interactor = interactor self.localTranslationsInteractor = localTranslationsInteractor self.dataSource = dataSource super.init(nibName: nil, bundle: nil) dataSource.delegate = self } required init?(coder aDecoder: NSCoder) { unimplemented() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("prefs_translations", tableName: "Android", comment: "") let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white) activityIndicator.hidesWhenStopped = true activityIndicator.stopAnimating() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: activityIndicator) tableView.sectionHeaderHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 70 tableView.allowsSelection = false tableView.ds_register(headerFooterClass: JuzTableViewHeaderFooterView.self) tableView.ds_register(cellNib: TranslationTableViewCell.self) tableView.ds_useDataSource(dataSource) refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged) tableView.addSubview(refreshControl) editController.configure(tableView: tableView, delegate: self, navigationItem: navigationItem) dataSource.downloadedDS.onItemsUpdated = { [weak self] _ in self?.editController.onEditableItemsUpdated() } dataSource.onEditingChanged = { [weak self] in self?.editController.onStartSwipingToEdit() } loadLocalData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) activityIndicator?.startAnimating() loadLocalData { self.refreshData() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) editController.endEditing(animated) } func translationsDataSource(_ dataSource: AbstractDataSource, errorOccurred error: Error) { showErrorAlert(error: error) } @objc private func refreshData() { interactor.get() .then(on: .main) { [weak self] translations -> Void in self?.dataSource.setItems(items: translations) self?.tableView.reloadData() }.catchToAlertView(viewController: self) .always(on: .main) { [weak self] in self?.refreshControl.endRefreshing() self?.activityIndicator?.stopAnimating() } } private func loadLocalData(completion: @escaping () -> Void = { }) { localTranslationsInteractor.get() .then(on: .main) { [weak self] translations -> Void in self?.dataSource.setItems(items: translations) self?.tableView.reloadData() } .always { completion() }.catchToAlertView(viewController: self) } func hasItemsToEdit() -> Bool { return !dataSource.downloadedDS.items.isEmpty } }
gpl-3.0
0cf3fee3c4952d3df6b4969544578a99
35.592308
120
0.688249
5.338945
false
false
false
false
woohyuknrg/GithubTrending
github/View Models/DiscoverViewModel.swift
1
2433
import Foundation import RxSwift import RxCocoa import Moya class DiscoverViewModel { var triggerRefresh = PublishSubject<Void>() var selectedItem = PublishSubject<IndexPath>() let results: Driver<[RepoCellViewModel]> let noResultsFound: Driver<Bool> let executing: Driver<Bool> let selectedViewModel: Driver<RepositoryViewModel> let title = "Trending" fileprivate let repos: BehaviorRelay<[Repo]> fileprivate let provider: MoyaProvider<GitHub> init(provider: MoyaProvider<GitHub>) { self.provider = provider let activityIndicator = ActivityIndicator() self.executing = activityIndicator.asDriver().distinctUntilChanged() let noResultFoundSubject = BehaviorRelay(value: false) self.noResultsFound = noResultFoundSubject.asDriver().distinctUntilChanged() let repos = BehaviorRelay(value: [Repo]()) self.repos = repos results = triggerRefresh.startWith(()) .flatMapLatest { provider.rx.request(.trendingReposSinceLastWeek(q: "created:>" + Date().lastWeek(), sort: "stars", order: "desc")) .retry(3) .observeOn(MainScheduler.instance) .trackActivity(activityIndicator) } .mapJSON() .mapToRepos() .do(onNext: { repos.accept($0) }) .mapToRepoCellViewModels() .catchErrorJustReturn([]) .do(onNext: { viewModels in noResultFoundSubject.accept(viewModels.isEmpty) }) .asDriver(onErrorJustReturn: []) selectedViewModel = selectedItem .asDriver(onErrorJustReturn: IndexPath()) .map { indexPath in let repo = repos.value[indexPath.row] return RepositoryViewModel(provider: provider, repo: repo) } } } extension Observable { func mapToRepos() -> Observable<[Repo]> { return self.map { json in let dict = json as? [String: Any] if let items = dict?["items"] as? [Any] { return Repo.fromJSONArray(items) } else { return [] } } } }
mit
7135cc22c8171291930a26530a3eeb01
32.328767
99
0.54665
5.580275
false
false
false
false
gaolichuang/actor-platform
actor-apps/app-ios/ActorApp/WallpapperPreviewController.swift
3
2176
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class WallpapperPreviewController: AAViewController { private let imageView = UIImageView() private let cancelButton = UIButton() private let setButton = UIButton() private let imageName: String init(imageName: String) { self.imageName = imageName super.init() imageView.image = UIImage(named: imageName)! imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true cancelButton.backgroundColor = MainAppTheme.tab.backgroundColor cancelButton.addTarget(self, action: "cancelDidTap", forControlEvents: .TouchUpInside) cancelButton.setTitle(localized("AlertCancel"), forState: .Normal) cancelButton.setTitleColor(MainAppTheme.tab.unselectedTextColor, forState: .Normal) setButton.backgroundColor = MainAppTheme.tab.backgroundColor setButton.addTarget(self, action: "setDidTap", forControlEvents: .TouchUpInside) setButton.setTitle(localized("AlertSet"), forState: .Normal) setButton.setTitleColor(MainAppTheme.tab.unselectedTextColor, forState: .Normal) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge.Top view.addSubview(imageView) view.addSubview(cancelButton) view.addSubview(setButton) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() imageView.frame = view.bounds cancelButton.frame = CGRect(x: 0, y: view.height - 55, width: view.width / 2, height: 55) setButton.frame = CGRect(x: view.width / 2, y: view.height - 55, width: view.width / 2, height: 55) } func cancelDidTap() { self.dismissViewControllerAnimated(true, completion: nil) } func setDidTap() { Actor.changeSelectedWallpaper("local:\(imageName)") self.dismissViewControllerAnimated(true, completion: nil) } }
mit
dabb847f7a1136770fc7dc39ef035e92
34.112903
107
0.670037
5.025404
false
false
false
false
bigsnickers/DPActivityIndicatorView
Pods/DPAdditionsKit/DPAdditionsKit/Extensions/UIView+Additions.swift
1
1150
// // UIView+Additions.swift // DPActivityIndicatorExample // // Created by Dennis Pashkov on 4/15/16. // Copyright © 2016 Dennis Pashkov. All rights reserved. // import UIKit extension UIView { public func removeAllSubviews() { while subviews.count > 0 { subviews.last?.removeFromSuperview() } } public func stickToSuperview() { guard superview != nil else { return } translatesAutoresizingMaskIntoConstraints = false let viewDictionary = ["self" : self] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[self]-0-|", options: .DirectionLeadingToTrailing, metrics: nil, views: viewDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[self]-0-|", options: .DirectionLeadingToTrailing, metrics: nil, views: viewDictionary) superview?.addConstraints(horizontalConstraints) superview?.addConstraints(verticalConstraints) superview?.setNeedsLayout() superview?.layoutIfNeeded() } }
mit
c2a3391eb104fe7728bd42ef94238927
29.263158
177
0.653612
5.745
false
false
false
false
vvw/XWebView
XWebView/XWVObject.swift
2
3445
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import WebKit public class XWVObject : NSObject { public let namespace: String public unowned let channel: XWVChannel public var webView: WKWebView? { return channel.webView } weak var origin: XWVObject! init(namespace: String, channel: XWVChannel, origin: XWVObject?) { self.namespace = namespace self.reference = 0 self.channel = channel super.init() self.origin = origin ?? self } // retain and autorelease private let reference: Int convenience init(reference: Int, channel: XWVChannel, origin: XWVObject) { let namespace = "\(origin.namespace).$references[\(reference)]" self.init(namespace: namespace, channel: channel, origin: origin) } deinit { if reference != 0 { let script = "\(origin.namespace).$releaseObject(\(reference))" webView?.evaluateJavaScript(script, completionHandler: nil) } } func wrapScriptObject(object: AnyObject?) -> AnyObject { if let dict = object as? [String: AnyObject] where dict["$sig"] as? NSNumber == 0x5857574F { if let num = dict["$ref"] as? NSNumber { return XWVScriptObject(reference: num.integerValue, channel: channel, origin: self) } else if let namespace = dict["$ns"] as? String { return XWVScriptObject(namespace: namespace, channel: channel, origin: self) } } return object ?? NSNull() } func serialize(object: AnyObject?) -> String { var obj: AnyObject? = object if let val = obj as? NSValue { obj = val.isObject ? val.nonretainedObjectValue : obj as? NSNumber } if let o = obj as? XWVObject { return o.namespace } else if let s = obj as? String { let d = NSJSONSerialization.dataWithJSONObject([s], options: NSJSONWritingOptions(0), error: nil) return dropFirst(dropLast(NSString(data: d!, encoding: NSUTF8StringEncoding) as! String)) } else if let n = obj as? NSNumber { if CFGetTypeID(n) == CFBooleanGetTypeID() { return n.boolValue.description } return n.stringValue } else if let date = obj as? NSDate { return "(new Date(\(date.timeIntervalSince1970 * 1000)))" } else if let date = obj as? NSData { // TODO: map to Uint8Array object } else if let a = obj as? [AnyObject] { return "[" + ",".join(a.map(serialize)) + "]" } else if let d = obj as? [String: AnyObject] { return "{" + ",".join(d.keys.map(){"'\($0)': \(self.serialize(d[$0]!))"}) + "}" } else if obj === NSNull() { return "null" } else if obj == nil { return "undefined" } return "'\(obj!.description)'" } }
apache-2.0
269e91188614e49fb5da9d45337e975b
38.147727
109
0.613062
4.515072
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift
113
6412
import Foundation #if _runtime(_ObjC) public struct AsyncDefaults { public static var Timeout: NSTimeInterval = 1 public static var PollInterval: NSTimeInterval = 0.01 } internal struct AsyncMatcherWrapper<T, U where U: Matcher, U.ValueType == T>: Matcher { let fullMatcher: U let timeoutInterval: NSTimeInterval let pollInterval: NSTimeInterval init(fullMatcher: U, timeoutInterval: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval) { self.fullMatcher = fullMatcher self.timeoutInterval = timeoutInterval self.pollInterval = pollInterval } func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let uncachedExpression = actualExpression.withoutCaching() let fnName = "expect(...).toEventually(...)" let result = pollBlock( pollInterval: pollInterval, timeoutInterval: timeoutInterval, file: actualExpression.location.file, line: actualExpression.location.line, fnName: fnName) { try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage) } switch (result) { case let .Completed(isSuccessful): return isSuccessful case .TimedOut: return false case let .ErrorThrown(error): failureMessage.actualValue = "an unexpected error thrown: <\(error)>" return false case let .RaisedException(exception): failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>" return false case .BlockedRunLoop: failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." return false case .Incomplete: internalError("Reached .Incomplete state for toEventually(...).") } } func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let uncachedExpression = actualExpression.withoutCaching() let result = pollBlock( pollInterval: pollInterval, timeoutInterval: timeoutInterval, file: actualExpression.location.file, line: actualExpression.location.line, fnName: "expect(...).toEventuallyNot(...)") { try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage) } switch (result) { case let .Completed(isSuccessful): return isSuccessful case .TimedOut: return false case let .ErrorThrown(error): failureMessage.actualValue = "an unexpected error thrown: <\(error)>" return false case let .RaisedException(exception): failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>" return false case .BlockedRunLoop: failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." return false case .Incomplete: internalError("Reached .Incomplete state for toEventuallyNot(...).") } } } private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function") extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually<U where U: Matcher, U.ValueType == T>(matcher: U, timeout: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { if expression.isClosure { let (pass, msg) = expressionMatches( expression, matcher: AsyncMatcherWrapper( fullMatcher: matcher, timeoutInterval: timeout, pollInterval: pollInterval), to: "to eventually", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot<U where U: Matcher, U.ValueType == T>(matcher: U, timeout: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { if expression.isClosure { let (pass, msg) = expressionDoesNotMatch( expression, matcher: AsyncMatcherWrapper( fullMatcher: matcher, timeoutInterval: timeout, pollInterval: pollInterval), toNot: "to eventually not", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually<U where U: Matcher, U.ValueType == T>(matcher: U, timeout: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description) } } #endif
apache-2.0
c42a83dac9f97955c041dee4a6fffb40
44.8
268
0.652838
5.719893
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableViewDataSources/InboxMessagesDataSource.swift
1
7917
// // InboxMessagesDataSource.swift // Habitica // // Created by Phillip Thelen on 25.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class InboxMessagesDataSource: BaseReactiveTableViewDataSource<InboxMessageProtocol> { @objc weak var viewController: InboxChatViewController? private var expandedChatPath: IndexPath? private let socialRepository = SocialRepository() private let userRepository = UserRepository() private let configRepository = ConfigRepository() private var user: UserProtocol? private var otherUserID: String? internal var otherUsername: String? private var member: MemberProtocol? private var startedEmpty: Bool? var loadedAllData = false var isLoading = false init(otherUserID: String?, otherUsername: String?) { self.otherUserID = otherUserID self.otherUsername = otherUsername super.init() sections.append(ItemSection<InboxMessageProtocol>()) disposable.add(userRepository.getUser().on(value: {[weak self] user in self?.user = user }).start()) disposable.add(socialRepository.getMember(userID: otherUserID ?? otherUsername ?? "", retrieveIfNotFound: true).on(value: {[weak self] member in self?.member = member if self?.otherUserID == nil { self?.otherUserID = member?.id self?.loadMessages() } self?.tableView?.reloadData() self?.viewController?.setTitleWith(username: member?.profile?.name) (self?.emptyDataSource as? SingleItemTableViewDataSource)?.styleFunction = EmptyTableViewCell.inboxChatStyleUsername(displayName: member?.profile?.name ?? "", contributorTier: member?.contributor?.level, username: member?.username ?? "") self?.tableView?.reloadData() }).start()) loadMessages() } private func loadMessages() { guard let userID = self.otherUserID else { return } disposable.add(socialRepository.getMessages(withUserID: userID).on(value: {[weak self] (messages, changes) in if self?.startedEmpty == nil { self?.startedEmpty = messages.isEmpty } self?.sections[0].items = messages self?.notify(changes: changes) }).start()) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = super.tableView(tableView, numberOfRowsInSection: section) if startedEmpty == true { return count + 1 } else { return count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let message = item(at: indexPath) else { let cell = tableView.dequeueReusableCell(withIdentifier: "emptyCell", for: indexPath) if let emptyCell = cell as? EmptyTableViewCell { EmptyTableViewCell.inboxChatStyleUsername(displayName: member?.profile?.name ?? "", contributorTier: member?.contributor?.level, username: member?.username ?? "")(emptyCell) } return cell } let cell = tableView.dequeueReusableCell(withIdentifier: "ChatMessageCell", for: indexPath) if let chatCell = cell as? ChatTableViewCell { self.configure(cell: chatCell, message: message, indexPath: indexPath) } return cell } private func configure(cell: ChatTableViewCell, message: InboxMessageProtocol, indexPath: IndexPath?) { var isExpanded = false if let expandedChatPath = self.expandedChatPath, let indexPath = indexPath { isExpanded = expandedChatPath == indexPath } cell.isFirstMessage = indexPath?.item == 0 cell.configure(inboxMessage: message, previousMessage: item(at: IndexPath(item: (indexPath?.item ?? 0)+1, section: indexPath?.section ?? 0)), nextMessage: item(at: IndexPath(item: (indexPath?.item ?? 0)-1, section: indexPath?.section ?? 0)), user: self.user, isExpanded: isExpanded) cell.profileAction = {[weak self] in guard let profileViewController = self?.viewController?.storyboard?.instantiateViewController(withIdentifier: "UserProfileViewController") as? UserProfileViewController else { return } if message.sent { profileViewController.userID = self?.user?.id profileViewController.username = self?.user?.profile?.name } else { profileViewController.userID = message.userID profileViewController.username = message.displayName } self?.viewController?.navigationController?.pushViewController(profileViewController, animated: true) } cell.copyAction = { let pasteboard = UIPasteboard.general pasteboard.string = message.text let toastView = ToastView(title: L10n.copiedMessage, background: .green) ToastManager.show(toast: toastView) } cell.deleteAction = {[weak self] in self?.socialRepository.delete(message: message).observeCompleted {} } cell.expandAction = {[weak self] in if let path = indexPath { self?.expandSelectedCell(path) } } if let transform = self.tableView?.transform { cell.transform = transform } } private func expandSelectedCell(_ indexPath: IndexPath) { if self.viewController?.isScrolling == true { return } var oldExpandedPath: IndexPath? = self.expandedChatPath if self.tableView?.numberOfRows(inSection: 0) ?? 0 < oldExpandedPath?.item ?? 0 { oldExpandedPath = nil } self.expandedChatPath = indexPath if let expandedPath = oldExpandedPath, indexPath.item != expandedPath.item { let oldCell = self.tableView?.cellForRow(at: expandedPath) as? ChatTableViewCell let cell = self.tableView?.cellForRow(at: indexPath) as? ChatTableViewCell self.tableView?.beginUpdates() cell?.isExpanded = true oldCell?.isExpanded = false self.tableView?.endUpdates() } else { let cell = self.tableView?.cellForRow(at: indexPath) as? ChatTableViewCell cell?.isExpanded = !(cell?.isExpanded ?? false) if !(cell?.isExpanded ?? false) { self.expandedChatPath = nil } self.tableView?.beginUpdates() self.tableView?.endUpdates() } } func sendMessage(messageText: String) { socialRepository.post(inboxMessage: messageText, toUserID: otherUserID ?? otherUsername ?? "").observeCompleted { self.tableView?.reloadData() } } func retrieveData(forced: Bool, completed: (() -> Void)?) { var page = (self.visibleSections.first?.items.count ?? 0) / 10 if forced { page = 0 loadedAllData = false } if loadedAllData || isLoading { return } isLoading = true userRepository.retrieveInboxMessages(conversationID: otherUserID ?? "", page: page) .on(value: { messages in if messages?.count ?? 0 < 10 { self.loadedAllData = true } self.isLoading = false }) .observeCompleted { completed?() } } override func checkForEmpty() { super.checkForEmpty() tableView?.separatorStyle = .none } }
gpl-3.0
c76ab384d76966cacdd974c510936386
39.804124
249
0.609904
5.228534
false
false
false
false
segmentio/analytics-swift
Examples/other_plugins/UIKitScreenTracking.swift
1
7144
// // UIKitScreenTracking.swift // SegmentUIKitExample // // Created by Brandon Sneed on 4/13/21. // // NOTE: You can see this plugin in use in the SwiftUIKitExample application. // // This plugin is NOT SUPPORTED by Segment. It is here merely as an example, // and for your convenience should you find it useful. // MIT License // // Copyright (c) 2021 Segment // // 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 Segment import UIKit /** Example plugin to replicate automatic screen tracking in iOS. */ // Conform to this protocol if self-tracking screens are desired @objc protocol UIKitScreenTrackable: NSObjectProtocol { @objc func seg__trackScreen(name: String?) } class UIKitScreenTracking: UtilityPlugin { static let notificationName = Notification.Name(rawValue: "UIKitScreenTrackNotification") static let screenNameKey = "name" static let controllerKey = "controller" let type = PluginType.utility weak var analytics: Analytics? = nil init() { setupUIKitHooks() } internal func setupUIKitHooks() { swizzle(forClass: UIViewController.self, original: #selector(UIViewController.viewDidAppear(_:)), new: #selector(UIViewController.seg__viewDidAppear) ) swizzle(forClass: UIViewController.self, original: #selector(UIViewController.viewDidDisappear(_:)), new: #selector(UIViewController.seg__viewDidDisappear) ) NotificationCenter.default.addObserver(forName: Self.notificationName, object: nil, queue: OperationQueue.main) { notification in let name = notification.userInfo?[Self.screenNameKey] as? String if let controller = notification.userInfo?[Self.controllerKey] as? UIKitScreenTrackable { // if the controller conforms to UIKitScreenTrackable, // call the trackScreen method with the name we have (possibly even nil) // and the implementor will decide what to do. controller.seg__trackScreen(name: name) } else if let name = name { // if we have a name, call screen self.analytics?.screen(title: name) } } } } extension UIKitScreenTracking { private func swizzle(forClass: AnyClass, original: Selector, new: Selector) { guard let originalMethod = class_getInstanceMethod(forClass, original) else { return } guard let swizzledMethod = class_getInstanceMethod(forClass, new) else { return } method_exchangeImplementations(originalMethod, swizzledMethod) } } extension UIViewController { internal func activeController() -> UIViewController? { // if a view is being dismissed, this will return nil if let root = viewIfLoaded?.window?.rootViewController { return root } else if #available(iOS 13.0, *) { // preferred way to get active controller in ios 13+ for scene in UIApplication.shared.connectedScenes { if scene.activationState == .foregroundActive { let windowScene = scene as? UIWindowScene let sceneDelegate = windowScene?.delegate as? UIWindowSceneDelegate if let target = sceneDelegate, let window = target.window { return window?.rootViewController } } } } else { // this was deprecated in ios 13.0 return UIApplication.shared.keyWindow?.rootViewController } return nil } internal func captureScreen() { var rootController = viewIfLoaded?.window?.rootViewController if rootController == nil { rootController = activeController() } guard let top = Self.seg__visibleViewController(activeController()) else { return } var name = String(describing: top.self.classForCoder).replacingOccurrences(of: "ViewController", with: "") print("Auto-tracking Screen: \(name)") // name could've been just "ViewController"... if name.count == 0 { name = top.title ?? "Unknown" } // post a notification that our plugin can capture. // if you were to do a custom implementation of how the name should // appear, you probably want to inspect the viewcontroller itself, `top` in this // case to generate your string for name and/or category. NotificationCenter.default.post(name: UIKitScreenTracking.notificationName, object: self, userInfo: [UIKitScreenTracking.screenNameKey: name, UIKitScreenTracking.controllerKey: top]) } @objc internal func seg__viewDidAppear(animated: Bool) { captureScreen() // it looks like we're calling ourselves, but we're actually // calling the original implementation of viewDidAppear since it's been swizzled. seg__viewDidAppear(animated: animated) } @objc internal func seg__viewDidDisappear(animated: Bool) { // call the original method first seg__viewDidDisappear(animated: animated) // the VC should be gone from the stack now, so capture where we're at now. captureScreen() } static func seg__visibleViewController(_ controller: UIViewController?) -> UIViewController? { if let navigationController = controller as? UINavigationController { return seg__visibleViewController(navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return seg__visibleViewController(selected) } } if let presented = controller?.presentedViewController { return seg__visibleViewController(presented) } return controller } }
mit
109affb4a4353c6df50f22ba1f080e45
41.272189
137
0.656775
5.276219
false
false
false
false
davidortinau/CameraManager
camera/ViewController.swift
1
3757
// // ViewController.swift // camera // // Created by Natalia Terlecka on 10/10/14. // Copyright (c) 2014 imaginaryCloud. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Constants let cameraManager = CameraManager.sharedInstance // MARK: - @IBOutlets @IBOutlet weak var cameraView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var cameraButton: UIButton! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() self.cameraManager.addPreviewLayerToView(self.cameraView, newCameraOutputMode: CameraOutputMode.VideoWithMic) self.cameraManager.cameraDevice = .Front self.imageView.hidden = true CameraManager.sharedInstance.showErrorBlock = { (erTitle: String, erMessage: String) -> Void in UIAlertView(title: erTitle, message: erMessage, delegate: nil, cancelButtonTitle: "OK").show() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.cameraManager.resumeCaptureSession() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.cameraManager.stopCaptureSession() } // MARK: - @IBActions @IBAction func changeFlashMode(sender: UIButton) { self.cameraManager.flashMode = CameraFlashMode(rawValue: (self.cameraManager.flashMode.rawValue+1)%3)! switch (self.cameraManager.flashMode) { case .Off: sender.setTitle("Flash Off", forState: UIControlState.Normal) case .On: sender.setTitle("Flash On", forState: UIControlState.Normal) case .Auto: sender.setTitle("Flash Auto", forState: UIControlState.Normal) } } @IBAction func recordButtonTapped(sender: UIButton) { switch (self.cameraManager.cameraOutputMode) { case .StillImage: self.cameraManager.capturePictureWithCompletition({ (image) -> Void in }) case .VideoWithMic, .VideoOnly: sender.selected = !sender.selected sender.setTitle(" ", forState: UIControlState.Selected) sender.backgroundColor = sender.selected ? UIColor.redColor() : UIColor.greenColor() if sender.selected { self.cameraManager.startRecordingVideo() } else { self.cameraManager.stopRecordingVideo({ (videoURL) -> Void in println(videoURL) }) } } } @IBAction func outputModeButtonTapped(sender: UIButton) { self.cameraManager.cameraOutputMode = self.cameraManager.cameraOutputMode == CameraOutputMode.VideoWithMic ? CameraOutputMode.StillImage : CameraOutputMode.VideoWithMic switch (self.cameraManager.cameraOutputMode) { case .StillImage: self.cameraButton.selected = false self.cameraButton.backgroundColor = UIColor.greenColor() sender.setTitle("Image", forState: UIControlState.Normal) case .VideoWithMic, .VideoOnly: sender.setTitle("Video", forState: UIControlState.Normal) } } @IBAction func changeCameraDevice(sender: UIButton) { self.cameraManager.cameraDevice = self.cameraManager.cameraDevice == CameraDevice.Front ? CameraDevice.Back : CameraDevice.Front switch (self.cameraManager.cameraDevice) { case .Front: sender.setTitle("Front", forState: UIControlState.Normal) case .Back: sender.setTitle("Back", forState: UIControlState.Normal) } } }
mit
7e9aee214d3275197f69966d08651e87
33.154545
176
0.642002
4.82285
false
false
false
false
mumbler/PReVo-iOS
DatumbazKonstruilo/DatumbazKonstruilo/main.swift
1
2987
// // main.swift // DatumbazKonstruilo // // Created by Robin Hill on 8/18/19. // Copyright © 2019 Robin Hill. All rights reserved. // import Foundation import CoreData import ReVoDatumbazoOSX var datumoRadiko = "." var produktajhoRadiko = "." if CommandLine.arguments.count > 1 { datumoRadiko = CommandLine.arguments[1] } if CommandLine.arguments.count > 2 { produktajhoRadiko = CommandLine.arguments[2] } let datumbazNomo = "PoshReVoDatumbazo" let datumejo = URL(fileURLWithPath: datumoRadiko) let produktajhejo = URL(fileURLWithPath: produktajhoRadiko + "/produktajhoj") if FileManager.default.fileExists(atPath: produktajhejo.absoluteString) { do { try FileManager.default.removeItem(at: produktajhejo) } catch { print("Ne sukcesis nuligi produktajhan dosierujon"); } } do { try FileManager.default.createDirectory(at: produktajhejo, withIntermediateDirectories: true, attributes: nil) } catch { print("Ekkonstruas datumbazon") } var managedObjectModel: NSManagedObjectModel = { let datumbazBundle = Bundle(identifier: "inthescales.ReVoDatumbazoOSX")! let modelURL = datumbazBundle.url(forResource: "PoshReVoDatumoj", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) let docsUrl = produktajhejo.appendingPathComponent(datumbazNomo + ".sqlite") do { let pragmas: [String : String] = ["journal_mode" : "DELETE", "synchronous" : "OFF"] do { // Forigi malnovan datumbazon try FileManager.default.removeItem(at: docsUrl) } catch { } let options = [NSSQLitePragmasOption : pragmas] try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: docsUrl, options: options) } catch { // Report any error we got. var dict = [String: Any]() dict[NSLocalizedDescriptionKey] = "Malsukcesis sharghante je datumoj" dict[NSLocalizedFailureReasonErrorKey] = "Eraro sharghante je datumoj" dict[NSUnderlyingErrorKey] = error as NSError print(dict) abort() } return coordinator }() var managedObjectContext: NSManagedObjectContext = { let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator return managedObjectContext }() // ================================================================================================ DatumLegilo.fariDatumbazon(en: managedObjectContext, datumoURL: datumejo, produktajhoURL: produktajhejo) let datumbazoValidas = DatumbazValidigilo.validas(konteksto: managedObjectContext) if datumbazoValidas { print("Datumbazo VALIDAS") exit(0) } else { print("Datumbazo NE VALIDAS") exit(1) }
mit
97edc0dae9002a21a1661ae951e46b55
31.813187
124
0.702947
3.970745
false
false
false
false
ilhanadiyaman/firefox-ios
Storage/SQL/BrowserDB.swift
2
16579
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import XCGLogger import Shared public let NotificationDatabaseWasRecreated = "NotificationDatabaseWasRecreated" private let log = Logger.syncLogger typealias Args = [AnyObject?] /* This is a base interface into our browser db. It holds arrays of tables and handles basic creation/updating of them. */ // Version 1 - Basic history table. // Version 2 - Added a visits table, refactored the history table to be a GenericTable. // Version 3 - Added a favicons table. // Version 4 - Added a readinglist table. // Version 5 - Added the clients and the tabs tables. // Version 6 - Visit timestamps are now microseconds. // Version 7 - Eliminate most tables. public class BrowserDB { private let db: SwiftData // XXX: Increasing this should blow away old history, since we currently don't support any upgrades. private let Version: Int = 7 private let files: FileAccessor private let filename: String private let secretKey: String? private let schemaTable: SchemaTable private var initialized = [String]() // SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can // appear in a query string. static let MaxVariableNumber = 999 public init(filename: String, secretKey: String? = nil, files: FileAccessor) { log.debug("Initializing BrowserDB: \(filename).") self.files = files self.filename = filename self.schemaTable = SchemaTable() self.secretKey = secretKey let file = ((try! files.getAndEnsureDirectory()) as NSString).stringByAppendingPathComponent(filename) self.db = SwiftData(filename: file, key: secretKey, prevKey: nil) if AppConstants.BuildChannel == .Developer && secretKey != nil { log.debug("Creating db: \(file) with secret = \(secretKey)") } // Create or update will also delete and create the database if our key was incorrect. self.createOrUpdate(self.schemaTable) } // Creates a table and writes its table info into the table-table database. private func createTable(conn: SQLiteDBConnection, table: SectionCreator) -> TableResult { log.debug("Try create \(table.name) version \(table.version)") if !table.create(conn) { // If creating failed, we'll bail without storing the table info log.debug("Creation failed.") return .Failed } var err: NSError? = nil return schemaTable.insert(conn, item: table, err: &err) > -1 ? .Created : .Failed } // Updates a table and writes its table into the table-table database. // Exposed internally for testing. func updateTable(conn: SQLiteDBConnection, table: SectionUpdater) -> TableResult { log.debug("Trying update \(table.name) version \(table.version)") var from = 0 // Try to find the stored version of the table let cursor = schemaTable.query(conn, options: QueryOptions(filter: table.name)) if cursor.count > 0 { if let info = cursor[0] as? TableInfoWrapper { from = info.version } } // If the versions match, no need to update if from == table.version { return .Exists } if !table.updateTable(conn, from: from) { // If the update failed, we'll bail without writing the change to the table-table. log.debug("Updating failed.") return .Failed } var err: NSError? = nil // Yes, we UPDATE OR INSERT… because we might be transferring ownership of a database table // to a different Table. It'll trigger exists, and thus take the update path, but we won't // necessarily have an existing schema entry -- i.e., we'll be updating from 0. if schemaTable.update(conn, item: table, err: &err) > 0 || schemaTable.insert(conn, item: table, err: &err) > 0 { return .Updated } return .Failed } // Utility for table classes. They should call this when they're initialized to force // creation of the table in the database. func createOrUpdate(tables: Table...) -> Bool { var success = true let doCreate = { (table: Table, connection: SQLiteDBConnection) -> () in switch self.createTable(connection, table: table) { case .Created: success = true return case .Exists: log.debug("Table already exists.") success = true return default: success = false } } if let _ = self.db.transaction({ connection -> Bool in let thread = NSThread.currentThread().description // If the table doesn't exist, we'll create it. for table in tables { log.debug("Create or update \(table.name) version \(table.version) on \(thread).") if !table.exists(connection) { log.debug("Doesn't exist. Creating table \(table.name).") doCreate(table, connection) } else { // Otherwise, we'll update it switch self.updateTable(connection, table: table) { case .Updated: log.debug("Updated table \(table.name).") success = true break case .Exists: log.debug("Table \(table.name) already exists.") success = true break default: log.error("Update failed for \(table.name). Dropping and recreating.") table.drop(connection) var err: NSError? = nil self.schemaTable.delete(connection, item: table, err: &err) doCreate(table, connection) } } if !success { log.warning("Failed to configure multiple tables. Aborting.") return false } } return success }) { // Err getting a transaction success = false } // If we failed, move the file and try again. This will probably break things that are already // attached and expecting a working DB, but at least we should be able to restart. var notify: NSNotification? = nil if !success { log.debug("Couldn't create or update \(tables.map { $0.name }).") log.debug("Attempting to move \(self.filename) to another location.") // Make sure that we don't still have open the files that we want to move! // Note that we use sqlite3_close_v2, which might actually _not_ close the // database file yet. For this reason we move the -shm and -wal files, too. db.forceClose() // Note that a backup file might already exist! We append a counter to avoid this. var bakCounter = 0 var bak: String repeat { bak = "\(self.filename).bak.\(++bakCounter)" } while self.files.exists(bak) do { try self.files.move(self.filename, toRelativePath: bak) let shm = self.filename + "-shm" let wal = self.filename + "-wal" log.debug("Moving \(shm) and \(wal)…") if self.files.exists(shm) { log.debug("\(shm) exists.") try self.files.move(shm, toRelativePath: bak + "-shm") } if self.files.exists(wal) { log.debug("\(wal) exists.") try self.files.move(wal, toRelativePath: bak + "-wal") } success = true // Notify the world that we moved the database. This allows us to // reset sync and start over in the case of corruption. let notification = NotificationDatabaseWasRecreated notify = NSNotification(name: notification, object: self.filename) } catch _ { success = false } assert(success) // Do this after the relevant tables have been created. defer { if let notify = notify { NSNotificationCenter.defaultCenter().postNotification(notify) } } if let _ = db.transaction({ connection -> Bool in for table in tables { doCreate(table, connection) if !success { return false } } return success }) { success = false; } } return success } typealias IntCallback = (connection: SQLiteDBConnection, inout err: NSError?) -> Int func withConnection<T>(flags flags: SwiftData.Flags, inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> T { var res: T! err = db.withConnection(flags) { connection in var err: NSError? = nil res = callback(connection: connection, err: &err) return err } return res } func withWritableConnection<T>(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> T { return withConnection(flags: SwiftData.Flags.ReadWrite, err: &err, callback: callback) } func withReadableConnection<T>(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Cursor<T>) -> Cursor<T> { return withConnection(flags: SwiftData.Flags.ReadOnly, err: &err, callback: callback) } func transaction(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) -> NSError? { return self.transaction(synchronous: true, err: &err, callback: callback) } func transaction(synchronous synchronous: Bool=true, inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) -> NSError? { return db.transaction(synchronous: synchronous) { connection in var err: NSError? = nil return callback(connection: connection, err: &err) } } } extension BrowserDB { func vacuum() { log.debug("Vacuuming a BrowserDB.") db.withConnection(SwiftData.Flags.ReadWriteCreate, synchronous: true) { connection in return connection.vacuum() } } func checkpoint() { log.debug("Checkpointing a BrowserDB.") db.transaction(synchronous: true) { connection in connection.checkpoint() return true } } } extension BrowserDB { public class func varlist(count: Int) -> String { return "(" + Array(count: count, repeatedValue: "?").joinWithSeparator(", ") + ")" } enum InsertOperation: String { case Insert = "INSERT" case Replace = "REPLACE" case InsertOrIgnore = "INSERT OR IGNORE" case InsertOrReplace = "INSERT OR REPLACE" case InsertOrRollback = "INSERT OR ROLLBACK" case InsertOrAbort = "INSERT OR ABORT" case InsertOrFail = "INSERT OR FAIL" } /** * Insert multiple sets of values into the given table. * * Assumptions: * 1. The table exists and contains the provided columns. * 2. Every item in `values` is the same length. * 3. That length is the same as the length of `columns`. * 4. Every value in each element of `values` is non-nil. * * If there are too many items to insert, multiple individual queries will run * in sequence. * * A failure anywhere in the sequence will cause immediate return of failure, but * will not roll back — use a transaction if you need one. */ func bulkInsert(table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success { // Note that there's a limit to how many ?s can be in a single query! // So here we execute 999 / (columns * rows) insertions per query. // Note that we can't use variables for the column names, so those don't affect the count. if values.isEmpty { log.debug("No values to insert.") return succeed() } let variablesPerRow = columns.count // Sanity check. assert(values[0].count == variablesPerRow) let cols = columns.joinWithSeparator(", ") let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES " let varString = BrowserDB.varlist(variablesPerRow) let insertChunk: [Args] -> Success = { vals -> Success in let valuesString = Array(count: vals.count, repeatedValue: varString).joinWithSeparator(", ") let args: Args = vals.flatMap { $0 } return self.run(queryStart + valuesString, withArgs: args) } let rowCount = values.count if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber { return insertChunk(values) } log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!") let rowsPerInsert = (999 / variablesPerRow) let chunks = chunk(values, by: rowsPerInsert) log.debug("Inserting in \(chunks.count) chunks.") // There's no real reason why we can't pass the ArraySlice here, except that I don't // want to keep fighting Swift. return walk(chunks, f: { insertChunk(Array($0)) }) } func runWithConnection<T>(block: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> Deferred<Maybe<T>> { return DeferredDBOperation(db: self.db, block: block).start() } func write(sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> { return self.runWithConnection() { (connection, err) -> Int in err = connection.executeChange(sql, withArgs: args) if err == nil { let modified = connection.numberOfRowsModified log.debug("Modified rows: \(modified).") return modified } return 0 } } public func forceClose() { db.forceClose() } func run(sql: String, withArgs args: Args? = nil) -> Success { return run([(sql, args)]) } func run(commands: [String]) -> Success { return self.run(commands.map { (sql: $0, args: nil) }) } /** * Runs an array of sql commands. Note: These will all run in order in a transaction and will block * the callers thread until they've finished. If any of them fail the operation will abort (no more * commands will be run) and the transaction will rollback, returning a DatabaseError. */ func run(sql: [(sql: String, args: Args?)]) -> Success { var err: NSError? = nil self.transaction(&err) { (conn, err) -> Bool in for (sql, args) in sql { err = conn.executeChange(sql, withArgs: args) if err != nil { return false } } return true } if let err = err { return deferMaybe(DatabaseError(err: err)) } return succeed() } func runQuery<T>(sql: String, args: Args?, factory: SDRow -> T) -> Deferred<Maybe<Cursor<T>>> { return runWithConnection { (connection, err) -> Cursor<T> in return connection.executeQuery(sql, factory: factory, withArgs: args) } } } extension SQLiteDBConnection { func tablesExist(names: [String]) -> Bool { let count = names.count let orClause = Array(count: count, repeatedValue: "name = ?").joinWithSeparator(" OR ") let tablesSQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND (\(orClause))" let res = self.executeQuery(tablesSQL, factory: StringFactory, withArgs: names.map { $0 as AnyObject }) log.debug("\(res.count) tables exist. Expected \(count)") return res.count > 0 } }
mpl-2.0
c8850f804de29762a6dde95ea38bd516
38.461905
164
0.584264
4.809344
false
false
false
false
rosslebeau/bytefish
App/Mustache/MustacheProvider.swift
1
495
import Foundation import Vapor public class MustacheProvider: Vapor.Provider { public var includeFiles: [String: String] public init(withIncludes includeFiles: [String: String] = [:]) { self.includeFiles = includeFiles } public func boot(with application: Application) { var files: [String: String] = [:] includeFiles.forEach { (name, file) in files[name] = application.workDir + "Resources/Views/" + file } View.renderers[".mustache"] = MustacheRenderer(files: files) } }
mit
b9d15e7758e446d57ffa4717957aa038
25.052632
65
0.717172
3.561151
false
false
false
false
devlucky/Kakapo
Examples/NewsFeed/Pods/Fakery/Source/Generators/Commerce.swift
1
1514
import Foundation open class Commerce: Generator { open func color() -> String { return generate("commerce.color") } open func department(maximum: Int = 3, fixedAmount: Bool = false) -> String { let amount = fixedAmount ? maximum : 1 + Int(arc4random_uniform(UInt32(maximum))) let fetchedCategories = categories(amount) let count = fetchedCategories.count var department = "" if count > 1 { department = mergeCategories(fetchedCategories) } else if count == 1 { department = fetchedCategories[0] } return department } open func productName() -> String { return generate("commerce.product_name.adjective") + " " + generate("commerce.product_name.material") + " " + generate("commerce.product_name.product") } open func price() -> Double { let arc4randoMax:Double = 0x100000000 return floor(Double((Double(arc4random()) / arc4randoMax) * 100.0) * 100) / 100.0 } // MARK: - Helpers func categories(_ amount: Int) -> [String] { var categories: [String] = [] while categories.count < amount { let category = generate("commerce.department") if !categories.contains(category) { categories.append(category) } } return categories } func mergeCategories(_ categories: [String]) -> String { let separator = generate("separator") let commaSeparated = categories[0..<categories.count - 1].joined(separator: ", ") return commaSeparated + separator + categories.last! } }
mit
c8a799aedbb0245ac4a676a066d2dd6d
27.037037
155
0.656539
4.11413
false
false
false
false
tominated/Quake3BSPParser
Tests/Quake3BSPParserTests/Quake3BSPParserTests.swift
1
852
// // Quake3BSPParserTests.swift // Quake3BSPParser // // Created by Thomas Brunoli on {TODAY}. // Copyright © 2017 Quake3BSPParser. All rights reserved. // import Foundation import XCTest import Quake3BSPParser class Quake3BSPParserTests: XCTestCase { func testBigBox() { let bigbox = try! loadMap(name: "test_bigbox"); let parser = try! Quake3BSPParser(bspData: bigbox) let _ = try! parser.parse(); } func testQ3dm6() { let q3dm6 = try! loadMap(name: "q3dm6"); let parser = try! Quake3BSPParser(bspData: q3dm6) let _ = try! parser.parse(); } private func loadMap(name: String) throws -> Data { let bundle = Bundle(for: type(of: self)) let filepath = bundle.url(forResource: name, withExtension: "bsp")! return try Data(contentsOf: filepath) } }
mit
a1aead3cbca81063d5898072dfe5b889
26.451613
75
0.641598
3.404
false
true
false
false
muenzpraeger/salesforce-einstein-vision-swift
SalesforceEinsteinVision/Classes/http/parts/MultiPartDatasetZipFile.swift
1
1274
// // MultiPartDatasetZipFile.swift // EinsteinVisionFramer // // Created by René Winkelmeyer on 14/03/2017. // Copyright © 2017 René Winkelmeyer. All rights reserved. // import Alamofire import Foundation public struct MultiPartDatasetZipFile : MultiPart { private var _data:String? public init() {} public mutating func build(fileName: String) throws { if fileName.isEmpty { throw ModelError.noFieldValue(field: "name") } let fileManager = FileManager.default if !fileManager.fileExists(atPath: fileName) { throw ModelError.fileDoesNotExist(fileName: fileName) } if (!fileName.lowercased().hasSuffix("zip")) { throw ModelError.fileNoZipFile(fileName: fileName) } let attr = try fileManager.attributesOfItem(atPath: fileName) let fileSize = attr[FileAttributeKey.size] as! UInt64 if (fileSize>50000000) { throw ModelError.fileTooLarge(fileName: fileName) } _data = fileName } public func form(multipart: MultipartFormData) { let url = URL(string: _data!) multipart.append(url!, withName: "data") } }
apache-2.0
cb0e12468138bbcb38c86662086f6f01
24.938776
69
0.610543
4.605072
false
false
false
false
hikki912/BeautyStory
BeautyStory/BeautyStory/Classes/Home/Controller/HomeVC.swift
1
5292
// // HomeVC.swift // BeautyStory // // Created by hikki on 2017/3/2. // Copyright © 2017年 hikki. All rights reserved. // import UIKit import Alamofire private let reuseIdentifier = "HomeCell" class HomeVC: UICollectionViewController { /// 数据源 fileprivate var homeDataSource: [ShopModel] = [ShopModel]() { didSet { collectionView?.reloadData() } } /// 显示的当前页 fileprivate var currentPage: Int = 1 /// 弹出的动画模型 fileprivate lazy var presentAnimation = PresentAnimation() /// 退出的动画模型 fileprivate lazy var dismissAnimation = DismissAnimation() override func viewDidLoad() { super.viewDidLoad() // 加载网络数据 loadNetworkData() } } // MARK: - 加载网络数据 extension HomeVC { func loadNetworkData(page: Int = 1, successHandler: (() -> Void)? = nil) -> Void { HttpTool.loadRequest(HomeURLString(page), method: .get) { [weak self] (jsonData: [String : Any], error: Error?) in // 1.判断是否有错误 if error != nil { return } // 2.取出响应中的字典数组 guard let dictArray = jsonData["goods_list"] as? [[String : Any]] else { return } // 3.遍历字典数组,将字典转换为模型,放到数据源中,刷新表格展示数据(在homeDataSource属性的didSet中同步刷新表格) if (page != 1) { // 加载更多 self?.homeDataSource.append(contentsOf: dictArray.map { ShopModel(dict: $0) }) } else { // 加载第一页 self?.homeDataSource = dictArray.map { ShopModel(dict: $0) } } // 网络数据加载成功,调用闭包 if let successHandler = successHandler { successHandler() } } } // 加载更多网络数据操作 fileprivate func loadMoreDataAction(updateBrowserClosure: BrowserClosureType?) { let nextPage = currentPage + 1 loadNetworkData(page: nextPage, successHandler: { [weak self] in self?.currentPage = nextPage print("主界面加载第\(nextPage)页") guard let updateBrowserClosure = updateBrowserClosure else { return } updateBrowserClosure((self?.homeDataSource)!) }) } } // MARK: - UICollectionViewDataSource extension HomeVC { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return homeDataSource.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HomeCell cell.shopModel = homeDataSource[indexPath.item] return cell } } // MARK: - UICollectionViewDelegate extension HomeVC { override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.item == homeDataSource.count - 1 { loadMoreDataAction(updateBrowserClosure: nil) } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 跳转到图片浏览器界面 (在自定义构造函数内部预先设置布局参数,UICollectionViewController创建的时候,必须指定布局) let pbVC = PhotoBrowserVC(pbDataSource: homeDataSource, currentIndexPath: indexPath, homeCollectionView: collectionView) { [weak self] (updateBrowserClosure: @escaping BrowserClosureType) in self?.loadMoreDataAction(updateBrowserClosure: updateBrowserClosure) } // case coverVertical : 默认的,从底部网上钻,直到覆盖整个屏幕 // case flipHorizontal : 三维翻转 // case crossDissolve : 淡入淡出 // case partialCurl : 翻页效果 // modal中系统的默认动画 // pbVC.modalTransitionStyle = .flipHorizontal // 1.设置转场动画代理:谁要来做整个动画 pbVC.transitioningDelegate = self // 2.给转场动画的模型赋值 let cell = collectionView.cellForItem(at: indexPath) as! HomeCell let image = cell.imageView.image presentAnimation.infoTuple = (image, cell) present(pbVC, animated: true, completion: nil) } } extension HomeVC: UIViewControllerTransitioningDelegate { /// 当控制器弹出另一个控制器的时候,会来到该方法 func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return presentAnimation } /// 当控制器dismiss掉之后会来到该方法 func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return dismissAnimation } }
mit
002e4647511e8fe2b70cf1fd52efea1a
32.514085
198
0.632276
4.811931
false
false
false
false
RoverPlatform/rover-ios
Sources/Data/SyncCoordinator/PagingSyncParticipant.swift
1
4212
// // PagingSyncParticipant.swift // RoverData // // Created by Sean Rucker on 2018-09-09. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import CoreData import Foundation import os public protocol PagingSyncParticipant: SyncParticipant { associatedtype Response: PagingResponse var context: NSManagedObjectContext { get } var cursorKey: String { get } var userDefaults: UserDefaults { get } func insertObject(from node: Response.Node) func nextRequest(cursor: String?) -> SyncRequest } extension PagingSyncParticipant { public var cursor: String? { get { return userDefaults.value(forKey: cursorKey) as? String } set { if let newValue = newValue { userDefaults.set(newValue, forKey: cursorKey) } else { userDefaults.removeObject(forKey: cursorKey) } } } public func initialRequest() -> SyncRequest? { return nextRequest(cursor: self.cursor) } public func saveResponse(_ data: Data) -> SyncResult { guard let response = decode(data) else { return .failed } guard let nodes = response.nodes else { return .noData } guard insertObjects(from: nodes) else { return .failed } updateCursor(from: response) return result(from: response) } public func decode(_ data: Data) -> Response? { do { return try JSONDecoder.default.decode(Response.self, from: data) } catch { os_log("Failed to decode response: %@", log: .sync, type: .error, error.logDescription) return nil } } public func insertObjects(from nodes: [Response.Node]) -> Bool { guard !nodes.isEmpty else { return true } os_log("Inserting %d objects", log: .sync, type: .debug, nodes.count) if #available(iOS 12.0, *) { os_signpost(.begin, log: .sync, name: "insertObjects", "count=%d", nodes.count) } if (context.persistentStoreCoordinator?.persistentStores.count).map({ $0 == 0 }) ?? true { os_log("Rover's Core Data persistent store not configured, unable to insert objects.", type: .error) return false } var saveError: Error? context.performAndWait { [context] in for node in nodes { insertObject(from: node) } do { try context.save() context.reset() } catch { saveError = error context.rollback() } } if let error = saveError { if let multipleErrors = (error as NSError).userInfo[NSDetailedErrorsKey] as? [Error] { multipleErrors.forEach { os_log("Failed to insert objects: %@", log: .sync, type: .error, $0.logDescription) } } else { os_log("Failed to insert objects: %@", log: .sync, type: .error, error.logDescription) } return false } os_log("Successfully inserted %d objects", log: .sync, type: .debug, nodes.count) if #available(iOS 12.0, *) { os_signpost(.end, log: .sync, name: "insertObjects", "count=%d", nodes.count) } return true } public func updateCursor(from response: Response) { if let endCursor = response.pageInfo.endCursor { self.cursor = endCursor } } public func result(from response: Response) -> SyncResult { guard let nodes = response.nodes, !nodes.isEmpty else { return .noData } let pageInfo = response.pageInfo guard pageInfo.hasNextPage, let endCursor = pageInfo.endCursor else { return .newData(nextRequest: nil) } let nextRequest = self.nextRequest(cursor: endCursor) return .newData(nextRequest: nextRequest) } }
apache-2.0
e6795ca89ad51278965b0788c0ae8871
29.294964
112
0.547376
4.768969
false
false
false
false
samodom/FoundationSwagger
FoundationSwaggerTests/Tools/Sample Types/SampleSwiftTypes.swift
1
2978
// // SwiftSwiftTypes.swift // FoundationSwagger // // Created by Sam Odom on 10/22/16. // Copyright © 2016 Swagger Soft. All rights reserved. // import FoundationSwagger // MARK: - Swift Structure public struct SampleSwiftStructure: Equatable { public let value: Int public init(value: Int) { self.value = value } } public func ==(lhs: SampleSwiftStructure, rhs: SampleSwiftStructure) -> Bool { return lhs.value == rhs.value } // MARK: - Swift Enumeration public enum SampleSwiftEnumeration: Equatable { case only(Int) } public func ==(lhs: SampleSwiftEnumeration, rhs: SampleSwiftEnumeration) -> Bool { switch (lhs, rhs) { case (.only(let leftValue), .only(let rightValue)): return leftValue == rightValue } } // MARK: - Swift Class public class SampleSwiftClass: Equatable, NSCopying, AssociatingObject, AssociatingClass, SampleType { private final var _instanceProperty = OriginalPropertyValue dynamic public var instanceProperty: String { get { return _instanceProperty } set { _instanceProperty = newValue } } private static var _classProperty = OriginalPropertyValue dynamic public class var classProperty: String { get { return _classProperty } set { _classProperty = newValue } } public class func className() -> String { return NSStringFromClass(SampleSwiftClass.self) } // MARK: - Lifecycle public init() { instanceProperty = OriginalPropertyValue } @objc public func copy() -> AnyObject { return self.copy(with: nil) as AnyObject } @objc public func copy(with zone: NSZone?) -> Any { let new = SampleSwiftClass() new.instanceProperty = instanceProperty return new } // MARK: - Sample methods @objc public class func sampleClassMethod() -> Int { return OriginalMethodReturnValue } @objc public class func otherClassMethod() -> Int { return AlternateMethodReturnValue } @objc public func sampleInstanceMethod() -> Int { return OriginalMethodReturnValue } @objc public func otherInstanceMethod() -> Int { return AlternateMethodReturnValue } // MARK: - Property alternates dynamic public class func otherClassPropertyGetter() -> String { return AlternatePropertyValue } dynamic public class func otherClassPropertySetter(_ newValue: String) { _classProperty = newValue + newValue } dynamic public func otherInstancePropertyGetter() -> String { return AlternatePropertyValue } dynamic public func otherInstancePropertySetter(_ newValue: String) { _instanceProperty = newValue + newValue } } public func ==(lhs: SampleSwiftClass, rhs: SampleSwiftClass) -> Bool { return lhs.instanceProperty == rhs.instanceProperty }
mit
0680974910f2dba9fe9a01d2d5d50116
22.077519
102
0.653678
4.928808
false
false
false
false
Havi4/Dodo
Dodo/Style/DodoBarStyle.swift
2
5896
import UIKit /// Defines styles related to the bar view in general. public class DodoBarStyle { /// The parent style is used to get the property value if the object is missing one. var parent: DodoBarStyle? init(parentStyle: DodoBarStyle? = nil) { self.parent = parentStyle } /// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties. public func clear() { _animationHide = nil _animationHideDuration = nil _animationShow = nil _animationShowDuration = nil _backgroundColor = nil _borderColor = nil _borderWidth = nil _cornerRadius = nil _debugMode = nil _hideAfterDelaySeconds = nil _hideOnTap = nil _locationTop = nil _marginToSuperview = nil _onTap = nil } // ----------------------------- private var _animationHide: DodoAnimation? /// Specify a function for animating the bar when it is hidden. public var animationHide: DodoAnimation { get { return (_animationHide ?? parent?.animationHide) ?? DodoBarDefaultStyles.animationHide } set { _animationHide = newValue } } // --------------------------- private var _animationHideDuration: NSTimeInterval? /// Duration of hide animation. When nil it uses default duration for selected animation function. public var animationHideDuration: NSTimeInterval? { get { return (_animationHideDuration ?? parent?.animationHideDuration) ?? DodoBarDefaultStyles.animationHideDuration } set { _animationHideDuration = newValue } } // --------------------------- private var _animationShow: DodoAnimation? /// Specify a function for animating the bar when it is shown. public var animationShow: DodoAnimation { get { return (_animationShow ?? parent?.animationShow) ?? DodoBarDefaultStyles.animationShow } set { _animationShow = newValue } } // --------------------------- private var _animationShowDuration: NSTimeInterval? /// Duration of show animation. When nil it uses default duration for selected animation function. public var animationShowDuration: NSTimeInterval? { get { return (_animationShowDuration ?? parent?.animationShowDuration) ?? DodoBarDefaultStyles.animationShowDuration } set { _animationShowDuration = newValue } } // --------------------------- private var _backgroundColor: UIColor? /// Background color of the bar. public var backgroundColor: UIColor? { get { return _backgroundColor ?? parent?.backgroundColor ?? DodoBarDefaultStyles.backgroundColor } set { _backgroundColor = newValue } } // ----------------------------- private var _borderColor: UIColor? /// Color of the bar's border. public var borderColor: UIColor? { get { return _borderColor ?? parent?.borderColor ?? DodoBarDefaultStyles.borderColor } set { _borderColor = newValue } } // ----------------------------- private var _borderWidth: CGFloat? /// Border width of the bar. public var borderWidth: CGFloat { get { return _borderWidth ?? parent?.borderWidth ?? DodoBarDefaultStyles.borderWidth } set { _borderWidth = newValue } } // ----------------------------- private var _cornerRadius: CGFloat? /// Corner radius of the bar view. public var cornerRadius: CGFloat { get { return _cornerRadius ?? parent?.cornerRadius ?? DodoBarDefaultStyles.cornerRadius } set { _cornerRadius = newValue } } // ----------------------------- private var _debugMode: Bool? /// When true it highlights the view background for spotting layout issues. public var debugMode: Bool { get { return _debugMode ?? parent?.debugMode ?? DodoBarDefaultStyles.debugMode } set { _debugMode = newValue } } // --------------------------- private var _hideAfterDelaySeconds: NSTimeInterval? /** Hides the bar automatically after the specified number of seconds. If nil the bar is kept on screen. */ public var hideAfterDelaySeconds: NSTimeInterval { get { return _hideAfterDelaySeconds ?? parent?.hideAfterDelaySeconds ?? DodoBarDefaultStyles.hideAfterDelaySeconds } set { _hideAfterDelaySeconds = newValue } } // ----------------------------- private var _hideOnTap: Bool? /// When true the bar is hidden when user taps on it. public var hideOnTap: Bool { get { return _hideOnTap ?? parent?.hideOnTap ?? DodoBarDefaultStyles.hideOnTap } set { _hideOnTap = newValue } } // ----------------------------- private var _locationTop: Bool? /// Position of the bar. When true the bar is shown on top of the screen. public var locationTop: Bool { get { return _locationTop ?? parent?.locationTop ?? DodoBarDefaultStyles.locationTop } set { _locationTop = newValue } } // ----------------------------- private var _marginToSuperview: CGSize? /// Margin between the bar edge and its superview. public var marginToSuperview: CGSize { get { return _marginToSuperview ?? parent?.marginToSuperview ?? DodoBarDefaultStyles.marginToSuperview } set { _marginToSuperview = newValue } } // --------------------------- private var _onTap: DodoBarOnTap? /// Supply a function that will be called when user taps the bar. public var onTap: DodoBarOnTap? { get { return _onTap ?? parent?.onTap ?? DodoBarDefaultStyles.onTap } set { _onTap = newValue } } // ----------------------------- }
mit
21d3ed2acb9cc9cb6f1044fa0649e2cd
22.400794
126
0.595319
5.663785
false
false
false
false
daisukenagata/BLEView
BLEView/Classes/BLECollectionView.swift
1
2203
// // BLEGraph.swift // Pods // // Created by 永田大祐 on 2017/01/15. // // import UIKit class BLECollectionView: UIView,UICollectionViewDataSource { let screenHeight = UIScreen.main.bounds.height let screenWidth = UIScreen.main.bounds.width var numArray :[Int] = [] var num = NSNumber() var collectionView:UICollectionView! override func draw(_ rect: CGRect) { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal flowLayout.itemSize = CGSize(width:screenWidth, height:screenHeight) collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowLayout) collectionView.register(BLECell.self, forCellWithReuseIdentifier: "cell") collectionView.dataSource = self collectionView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight/2) self.addSubview(collectionView) self.transform = CGAffineTransform(scaleX: 1, y: -1) self.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true self.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true self.heightAnchor.constraint(equalToConstant:UIScreen.main.bounds.height).isActive = true } func getArray(reset:Int)->[Int]{ let number = BLEView().setRSSI(rssi: num) numArray+=[number * -4] if numArray.count >= 8 { numArray.removeAll() BlModel.sharedBlUILabelOne.alpha = 0 } if reset >= 8 { numArray.removeAll() BlModel.sharedBlUILabelOne.alpha = 0 } return numArray } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return getArray(reset: 1).count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! BLECell return cell } }
mit
c1c5119de0557ff9fa61d4b2c1d6bb7f
32.257576
121
0.646469
4.954853
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Seller/SLV_814_UserPageStyle.swift
1
13173
// // SLV_814_UserPageStyle.swift // selluv-ios // // Created by 조백근 on 2017. 1. 31.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation import UIKit import SwifterSwift import PullToRefresh class SLV_814_UserPageStyle: UICollectionViewController { let refresher = PullToRefresh() var itemInfo: IndicatorInfo = IndicatorInfo(title: "스타일 0")//tab 정보 let selluvWaterFallCellIdentify = "userPageStyleWaterFallCellIdentify" var itemList: [SLVDetailProduct] = [] let delegateHolder = SLVTabContainNavigationControllerDelegate() weak var delegate: SLVButtonBarDelegate?// 델리게이트. weak var myNavigationDelegate: SLVNavigationControllerDelegate?// push를 위한 네비게이션 override func viewDidLoad() { super.viewDidLoad() self.prepare() self.setupLongPress() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func linkDelegate(controller: AnyObject) { self.delegate = controller as? SLVButtonBarDelegate // self.myNavigationDelegate = controller as? SLVNavigationControllerDelegate } func prepare() { self.navigationController!.delegate = delegateHolder self.view.backgroundColor = UIColor.clear self.automaticallyAdjustsScrollViewInsets = false self.loadProducts(isContinue: false) let collection :UICollectionView = collectionView!; collection.remembersLastFocusedIndexPath = true collection.frame = screenBounds collection.setCollectionViewLayout(CHTCollectionViewWaterfallLayout(), animated: false) collection.backgroundColor = UIColor.clear // collection.register(SLVMainFeedItemCell.self, forCellWithReuseIdentifier: selluvWaterFallCellIdentify) collection.register(UINib(nibName: "SLVUserProductCell", bundle: nil), forCellWithReuseIdentifier: selluvWaterFallCellIdentify) collection.reloadData() refresher.position = .bottom collection.addPullToRefresh(refresher) { self.loadProducts(isContinue: true) } } func setupLongPress() { let overlay = GHContextMenuView() overlay.delegate = self overlay.dataSource = self let selector = #selector(GHContextMenuView.longPressDetected(_:)) let longPress = UILongPressGestureRecognizer(target: overlay, action: selector) self.collectionView?.addGestureRecognizer(longPress) } deinit { self.collectionView?.removePullToRefresh((self.collectionView?.bottomPullToRefresh!)!) } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let parent = self.delegate as! SLV_800_UserPageController let definer = parent.myCustomBar?.behaviorDefiner definer?.scrollViewDidEndDecelerating(scrollView) } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let parent = self.delegate as! SLV_800_UserPageController let definer = parent.myCustomBar?.behaviorDefiner definer?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { let parent = self.delegate as! SLV_800_UserPageController let definer = parent.myCustomBar?.behaviorDefiner definer?.scrollViewDidScroll(scrollView) parent.updateSubScrollViewDidScroll(scrollView) if scrollView == self.collectionView { let off = scrollView.contentOffset if off.y > 0 { // hide self.delegate?.hideByScroll() } else { //show self.delegate?.showByScroll() } } } //MARK: DataCalling func loadProducts(isContinue: Bool) { let parent = self.delegate as! SLV_800_UserPageController let user = parent.sellerId//BBAuthToken.shared.name() ProductsModel.shared.productsForSeller(userId: user!, kind: "styles", isSame: isContinue) { (success, products) in if let products = products { self.itemList.append(contentsOf: products) parent.delay(time: 0.2) { self.collectionView?.reloadData() } } } } } // MARK: - IndicatorInfoProvider extension SLV_814_UserPageStyle: IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return itemInfo } } // MARK: - Collection View extension SLV_814_UserPageStyle { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let collectionCell: SLVUserProductCell = collectionView.dequeueReusableCell(withReuseIdentifier: selluvWaterFallCellIdentify, for: indexPath as IndexPath) as! SLVUserProductCell collectionCell.delegate = self let item = self.itemList[indexPath.row] collectionCell.setupData(item: item) return collectionCell } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.itemList.count; } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // let pageViewController = // NTHorizontalPageViewController(collectionViewLayout: pageViewControllerLayout(), currentIndexPath:indexPath as NSIndexPath) // pageViewController.imageNameList = imageNameList // collectionView.setToIndexPath(indexPath: indexPath as NSIndexPath) //// if let nc: UINavigationController = myNavigationDelegate?.linkMyNavigationForTransition() { //// nc.delegate = delegateHolder //// nc.pushViewController(pageViewController, animated: true) //// } else { // navigationController?.pushViewController(pageViewController, animated: true) //// } collectionView.setToIndexPath(indexPath: indexPath as NSIndexPath) let board = UIStoryboard(name:"Main", bundle: nil) let productController = board.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController // productController.parentCellImage = cell.imageViewContent!.image productController.imagePath = indexPath as NSIndexPath? navigationController?.pushViewController(productController, animated: true) } func pageViewControllerLayout () -> UICollectionViewFlowLayout { let flowLayout = UICollectionViewFlowLayout() let itemSize = self.navigationController!.isNavigationBarHidden ? CGSize(width: screenWidth, height: screenHeight+20) : CGSize(width: screenWidth, height: screenHeight-navigationHeaderAndStatusbarHeight) flowLayout.itemSize = itemSize flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.scrollDirection = .horizontal return flowLayout } } extension SLV_814_UserPageStyle: CHTCollectionViewDelegateWaterfallLayout, SLVCollectionTransitionProtocol { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ var itemSize = DEFAULT_PHOTO_SIZE var isFinish = true if self.itemList.count > 0 && self.itemList.count >= indexPath.row + 1 { let info = self.itemList[indexPath.row] var name = "" if info.photos != nil { if (info.photos?.count)! > 0 { name = (info.photos?.first)! } } if name != "" { let from = URL(string: "\(dnProduct)\(name)") isFinish = false ImageScout.shared.scoutImage(url: from!) { error, size, type in isFinish = true if let error = error { print(error.code) } else { print("Size: \(size)") print("Type: \(type.rawValue)") itemSize = size } } } } var cnt: Int = 0 var sec: Double = 0 while(isFinish == false && 2 < sec ) { RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) cnt = cnt + 1 sec = Double(cnt) * Double(0.01) } let imageHeight = itemSize.height*gridWidth/itemSize.width + SLVUserProductCell.infoHeight + SLVUserProductCell.humanHeight log.debug("remote image calc cell width: \(gridWidth) , height: \(imageHeight)") return CGSize(width: gridWidth, height: imageHeight) } func transitionTabCollectionView() -> UICollectionView!{ return collectionView } } extension SLV_814_UserPageStyle: SLVCollectionLinesDelegate { // 스타일 영역을 터치한다. func didTouchedStyleThumbnail(info: AnyObject) { } // 좋아요를 터치한다. func didTouchedLikeButton(info: AnyObject) { } func didTouchedItemDescription(info: AnyObject) { } func didTouchedUserDescription(info: AnyObject) { } } extension SLV_814_UserPageStyle: GHContextOverlayViewDataSource, GHContextOverlayViewDelegate { func shouldShowMenu(at point: CGPoint) -> Bool { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) return cell != nil } return false } func shouldShowMenuOnParentImage(at point: CGPoint) -> UIImage! { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell if cell != nil { let image = cell!.imageViewContent?.image return image } } return nil } func shouldShowMenuParentImageFrame(at point: CGPoint) -> CGRect { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell if cell != nil { let frame = cell?.imageViewContent?.frame var newFrame = self.view?.convert(frame!, to: nil) let x = ((screenWidth/2) > point.x) ? 17:(screenWidth/2 + 5) newFrame?.origin.x = x return newFrame! } } return .zero } func numberOfMenuItems() -> Int { return 4 } func itemInfoForItem(at index: Int) -> GHContextItemView! { let itemView = GHContextItemView() switch index { case 0: itemView.typeDesc = "좋아요" itemView.baseImage = UIImage(named: "longpress-like-nor.png") itemView.selectedImage = UIImage(named: "longpress-like-focus.png") // itemView.baseImage = UIImage(named: "longpress-like-not-nor.png") // itemView.selectedImage = UIImage(named: "longpress-like-not-focus.png") break case 1: itemView.typeDesc = "피드" itemView.baseImage = UIImage(named: "longpress-feed-nor.png") itemView.selectedImage = UIImage(named: "longpress-feed-focus.png") break case 2: itemView.typeDesc = "공유" itemView.baseImage = UIImage(named: "longpress-share-nor.png") itemView.selectedImage = UIImage(named: "longpress-share-focus.png") break case 3: itemView.typeDesc = "더보기" itemView.baseImage = UIImage(named: "longpress-more-nor.png") itemView.selectedImage = UIImage(named: "longpress-more-focus.png") break default: break } return itemView } func didSelectItem(at selectedIndex: Int, forMenuAt point: CGPoint) { // let path = self.collectionView?.indexPathForItem(at: point) var message = "" switch selectedIndex { case 0: message = "좋아요 selected" break case 1: message = "피드 selected" break case 2: message = "공유 selected" break case 3: message = "더보기 selected" break default: break } AlertHelper.alert(message: message) } }
mit
8967642d8883f52c87946d0230dbdbcf
36.613833
185
0.622663
5.429285
false
false
false
false
parrotbait/CorkWeather
Pods/CodableFirebase/CodableFirebase/Decoder.swift
1
57734
// // Decoder.swift // CodableFirebase // // Created by Oleksii on 27/12/2017. // Copyright © 2017 ViolentOctopus. All rights reserved. // import Foundation class _FirebaseDecoder : Decoder { /// Options set on the top-level encoder to pass down the decoding hierarchy. struct _Options { let dateDecodingStrategy: FirebaseDecoder.DateDecodingStrategy? let dataDecodingStrategy: FirebaseDecoder.DataDecodingStrategy? let skipFirestoreTypes: Bool let userInfo: [CodingUserInfoKey : Any] } // MARK: Properties /// The decoder's storage. fileprivate var storage: _FirebaseDecodingStorage fileprivate let options: _Options /// The path to the current point in encoding. fileprivate(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. init(referencing container: Any, at codingPath: [CodingKey] = [], options: _Options) { self.storage = _FirebaseDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not a dictionary") throw DecodingError.typeMismatch([String: Any].self, context) } let container = _FirebaseKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array") throw DecodingError.typeMismatch([Any].self, context) } return _FirebaseUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } fileprivate struct _FirebaseDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the plist types (NSNumber, Date, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return containers.count } fileprivate var topContainer: Any { precondition(containers.count > 0, "Empty container stack.") return containers.last! } fileprivate mutating func push(container: Any) { containers.append(container) } fileprivate mutating func popContainer() { precondition(containers.count > 0, "Empty container stack.") containers.removeLast() } } fileprivate struct _FirebaseKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _FirebaseDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _FirebaseDecoder, wrapping container: [String : Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return container.keys.compactMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return container[key.stringValue] != nil } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { guard let entry = container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try decoder.unbox(entry, as: T.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- no value found for key \"\(key.stringValue)\"")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _FirebaseKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested unkeyed container -- no value found for key \"\(key.stringValue)\"")) } guard let array = value as? [Any] else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array") throw DecodingError.typeMismatch([Any].self, context) } return _FirebaseUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let value: Any = container[key.stringValue] ?? NSNull() return _FirebaseDecoder(referencing: value, at: self.decoder.codingPath, options: decoder.options) } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _FirebaseKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _FirebaseUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _FirebaseDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _FirebaseDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return container.count } public var isAtEnd: Bool { return currentIndex >= count! } public mutating func decodeNil() throws -> Bool { guard !isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if container[currentIndex] is NSNull { currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: Int.Type) throws -> Int { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Unkeyed container is at end.")) } decoder.codingPath.append(_FirebaseKey(index: currentIndex)) defer { decoder.codingPath.removeLast() } guard let decoded = try decoder.unbox(container[currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: decoder.codingPath + [_FirebaseKey(index: currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } currentIndex += 1 return decoded } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: T.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_FirebaseKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not a dictionary") throw DecodingError.typeMismatch([String : Any].self, context) } self.currentIndex += 1 let container = _FirebaseKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested unkeyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array") throw DecodingError.typeMismatch([String : Any].self, context) } self.currentIndex += 1 return _FirebaseUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } public mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_FirebaseKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _FirebaseDecoder(referencing: value, at: decoder.codingPath, options: decoder.options) } } extension _FirebaseDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(T.self) return try self.unbox(self.storage.topContainer, as: T.self)! } } extension _FirebaseDecoder { /// Returns the given value unboxed from a container. func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int } func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int8 } func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int16 } func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int32 } func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int64 } func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint } func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint8 } func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint16 } func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint32 } func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint64 } func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } guard let options = options.dateDecodingStrategy else { guard let date = value as? Date else { throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) } return date } switch options { case .deferredToDate: self.storage.push(container: value) let date = try Date(from: self) self.storage.popContainer() return date case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) let date = try closure(self) self.storage.popContainer() return date } } func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } guard let options = options.dataDecodingStrategy else { guard let data = value as? Data else { throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) } return data } switch options { case .deferredToData: self.storage.push(container: value) let data = try Data(from: self) self.storage.popContainer() return data case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) let data = try closure(self) self.storage.popContainer() return data } } func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } // Attempt to bridge from NSDecimalNumber. if let decimal = value as? Decimal { return decimal } else { let doubleValue = try self.unbox(value, as: Double.self)! return Decimal(doubleValue) } } func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { let decoded: T if T.self == Date.self || T.self == NSDate.self { guard let date = try self.unbox(value, as: Date.self) else { return nil } decoded = date as! T } else if T.self == Data.self || T.self == NSData.self { guard let data = try self.unbox(value, as: Data.self) else { return nil } decoded = data as! T } else if T.self == URL.self || T.self == NSURL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } decoded = (url as! T) } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } decoded = decimal as! T } else if options.skipFirestoreTypes && (T.self is FirestoreDecodable.Type) { decoded = value as! T } else { self.storage.push(container: value) decoded = try T(from: self) self.storage.popContainer() } return decoded } } @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) internal var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }()
mit
34c711f10d74d93a00a4a566e8447906
45.1864
216
0.62725
5.100088
false
false
false
false
edmw/Volumio_ios
Volumio/Item.swift
1
2412
// // Item.swift // Volumio // // Created by Michael Baumgärtner on 23.01.17. // Copyright © 2017 Federico Sintucci. All rights reserved. // import Foundation /** This represents a Volumio item. It can be a song, a playlist, a folder, and so forth. */ protocol Item { /// Type of this Volumio item (track, song, playlist, folder, ...) var type: ItemType { get } /// Title for this item. var title: String? { get } /// Name for this item. Tracks have names, for all other items this is nil. var name: String? { get } /// Artist for this item. Maybe nil for some types. var artist: String? { get } /// Album for this item. Maybe nil for some types. var album: String? { get } /// Album art url string for this item. Maybe nil for some types. var albumArt: String? { get } } enum ItemType: String { case title case track case folder case playlist case song case cuesong case webradio case mywebradio case radio_favourites = "radio-favourites" case radio_category = "radio-category" case unknown var isTrack: Bool { return self == .track } var isSong: Bool { return self == .song || self == .cuesong } var isRadio: Bool { return self == .webradio || self == .mywebradio } } // MARK: - Localization // Localized strings for this item. Note: Some of this methods don’t really localize anything, but return a resonable default string if data is missing. extension Item { /// Returns the title of this item or an empty string if title data is missing. var localizedTitle: String { return title ?? name ?? "" } /// Returns the artist for this item or an empty string if artist data is missing. var localizedArtist: String { return artist ?? "" } /// Returns the album of this item or an empty string if album data is missing. var localizedAlbum: String { return album ?? "" } /// Returns a combined string with artist and album information for this item. var localizedArtistAndAlbum: String { if let artist = artist, !artist.isBlank { if let album = album, !album.isBlank { return "\(artist) - \(album)" } else { return "\(artist) - No album" } } else { return album ?? "" } } }
gpl-3.0
2afcb119ecafa6cfee4a0cf31bfc2a30
25.173913
152
0.61005
4.095238
false
false
false
false
nerdyc/Squeal
Sources/Core/DatabasePool.swift
1
5241
import Foundation /// Delegate public protocol DatabasePoolDelegate : class { /// Notifies the delegate that a new `Database` was opened. This gives the delegate an opportunity to setup the /// database. For example, executing `PRAGMA` statements to turn on WAL-mode. /// /// - Parameter database: The database that was opened. /// - Throws: Any error that occurs while setting up the database. func databaseOpened(_ database:Database) throws /// Notifies the delegate that a previously opened Database will be closed. /// /// - Parameter database: The database that will be closed. func databaseClosed(_ database:Database) } /// /// Manages a pool of Database objects. The pool does not have a maximum size, and will not block. The pool can be /// safely accessed from multiple threads concurrently. /// open class DatabasePool { /// The path of the database being pooled. public let databasePath : String /// The pool's delegate. open weak var delegate : DatabasePoolDelegate? /// Dispatch queue used to synchronize access to the pool between threads. fileprivate let syncQueue : DispatchQueue /// Creates a new database pool that pools connections to the database at the given path. Since by definition a /// pool will create multiple connections to a database, only persistent databases are supported. /// /// - Parameters: /// - databasePath: The path of the database to pool. /// - delegate: An optional delegate to notify when connections are opened or closed. public init(databasePath:String, delegate:DatabasePoolDelegate? = nil) { self.databasePath = databasePath self.syncQueue = DispatchQueue(label: "DatabasePool-(\(databasePath))", attributes: []) self.delegate = delegate } // ================================================================================================================= // MARK:- Databases fileprivate var inactiveDatabases = [Database]() fileprivate var activeDatabases = [Database]() /// The number of inactive database connections available. var inactiveDatabaseCount : Int { return inactiveDatabases.count } /// The number of active database connections being used. var activeDatabaseCount : Int { return activeDatabases.count } /// /// Creates or reuses a Database object. The database should be returned to the pool when it is no longer in use by /// calling `enqueueDatabase(database:)`. /// /// - Returns: An open Database. /// - Throws: /// An NSError with the sqlite error code and message. /// open func dequeueDatabase() throws -> Database { var database:Database? var error:NSError? syncQueue.sync { if self.inactiveDatabases.isEmpty { do { database = try self.openDatabase() self.activeDatabases.append(database!) } catch let openError as NSError { error = openError return } catch let e { fatalError("Unexpected error thrown opening a database \(e)") } } else { database = self.inactiveDatabases.removeLast() self.activeDatabases.append(database!) } } guard let dequeuedDatabase = database else { throw error! } return dequeuedDatabase } /// Return a database to the pool, allowing it to be reused. /// /// - Parameter database: The Database to return to the pool. open func enqueueDatabase(_ database:Database) { deactivateDatabase(database, notifyDelegate: false) syncQueue.sync { self.inactiveDatabases.append(database) } } /// Removes the database from the pool. It will not be reused. /// /// - Parameter database: The database to remove. open func removeDatabase(_ database:Database) { deactivateDatabase(database, notifyDelegate: true) } /// /// Closes and removes all unused Database objects from the pool. Active databases are not affected. /// open func drain() { syncQueue.sync { self.inactiveDatabases.removeAll(keepingCapacity: false) } } fileprivate func openDatabase() throws -> Database { let database = try Database(path: databasePath) try delegate?.databaseOpened(database) return database } fileprivate func deactivateDatabase(_ database:Database, notifyDelegate:Bool) { syncQueue.sync { if let index = self.activeDatabases.index(where: { $0 === database }) { self.activeDatabases.remove(at: index) } if let index = self.inactiveDatabases.index(where: { $0 === database }) { self.inactiveDatabases.remove(at: index) } if (notifyDelegate) { self.delegate?.databaseClosed(database) } } } }
mit
ad0dc9faed4ae5e258994cdd2daece5f
33.708609
120
0.600458
5.353422
false
false
false
false
esttorhe/RxSwift
RxExample/RxExample/ViewController.swift
1
1095
// // ViewController.swift // RxExample // // Created by Krunoslav Zaher on 4/25/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift #if os(iOS) import UIKit typealias OSViewController = UIViewController #elseif os(OSX) import Cocoa typealias OSViewController = NSViewController #endif class ViewController: OSViewController { #if TRACE_RESOURCES private let startResourceCount = RxSwift.resourceCount #endif override func viewDidLoad() { #if TRACE_RESOURCES print("Number of start resources = \(resourceCount)") #endif } deinit { #if TRACE_RESOURCES print("View controller disposed with \(resourceCount) resources") var numberOfResourcesThatShouldRemain = startResourceCount let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue(), { () -> Void in assert(resourceCount <= numberOfResourcesThatShouldRemain, "Resources weren't cleaned properly") }) #endif } }
mit
04fe730f8c6196a20c84980f4d9361e6
25.095238
108
0.696804
4.415323
false
false
false
false
jeremyrea/tekky
Tekky/AppDelegate.swift
1
3153
// // AppDelegate.swift // Tekky // // Created by Jeremy Rea on 2017-03-03. // Copyright © 2017 Jeremy Rea. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var preferences: Preferences! @IBOutlet var statusMenu: NSMenu? @IBOutlet var statusItem: NSStatusItem? var timer: Timer? func applicationDidFinishLaunching(_ aNotification: Notification) { timer = Timer.scheduledTimer(withTimeInterval: .init(60*60), repeats: true, block: {_ in self.fetchData() }) RunLoop.current.add(timer!, forMode: .commonModes) statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength) statusItem?.length = NSVariableStatusItemLength statusItem?.title = "Tekky" statusItem?.highlightMode = true self.initMenu() } func fetchData() { RequestManager.sharedInstance.getUsage(withKey: (preferences.getSetting(.apiKey) as? String ?? "")) { completionHandler in if let responseObjects = completionHandler { let reportedUsage = responseObjects.filter { return $0.isCurrent == true }.first!.onPeakDownload let allowedUsage = Float.init((self.preferences.getSetting(.bandwidthLimit) as? String)!) let remainingUsage = allowedUsage! - reportedUsage let usage = "Remaining usage: " + String(format: "%.2f", remainingUsage) self.updateMenu(withUsage: usage) } } // Edit last sync date and save somewhere for restart } func applicationWillTerminate(_ aNotification: Notification) { timer?.invalidate() } private func initMenu() { self.statusMenu = NSMenu() self.statusMenu?.addItem(NSMenuItem(title: "", action: nil, keyEquivalent: String())) self.statusMenu?.addItem(NSMenuItem(title: "Last sync: ", action: nil, keyEquivalent: String())) self.statusMenu?.addItem(NSMenuItem.separator()) self.statusMenu?.addItem(NSMenuItem(title: "Preferences", action: #selector(AppDelegate.displayPreferences), keyEquivalent: ",")) self.statusMenu?.addItem(NSMenuItem.separator()) self.statusMenu?.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitApplication), keyEquivalent: "q")) self.statusItem?.menu = self.statusMenu } private func updateMenu(withUsage usage: String) { self.statusMenu?.item(at: 0)?.title = usage let lastSync = "Last synced: " let syncDate = Date.init().currentTimestamp() as String self.statusMenu?.item(at: 1)?.title = lastSync + syncDate self.statusMenu?.update() } @objc func displayPreferences() { preferences.setup() preferences.makeKeyAndOrderFront(preferences) NSApp.activate(ignoringOtherApps: true) } @objc func quitApplication() { NSApplication.shared().terminate(self) } }
mit
23a283975f7ea4118a6ad0b99f13c2e5
32.178947
126
0.634201
4.948195
false
false
false
false
idomizrachi/Regen
regen/Images/ImagesValidator.swift
1
1250
// // Validator.swift // Regen // // Created by Ido Mizrachi on 7/8/16. // import Cocoa struct ValidationIssue { var firstImage : String var secondImage : String var property : String } extension Images { class Validator { func validate(_ images : [Image]) -> [ValidationIssue] { // Logger.debug("\tImages validation: started") var issues : [ValidationIssue] = [] guard images.count > 1 else { // Logger.debug("\tImages validation: finished") return issues } for i in 0...images.count-2 { for j in i+1...images.count-1 { if images[i].file.propertyName == images[j].file.propertyName { if images[i].folders.last?.propertyName == images[j].folders.last?.propertyName { issues.append(ValidationIssue(firstImage: images[i].file.name, secondImage: images[j].file.name, property: images[i].file.name)) } } } } // Logger.debug("\tImages validation: finished (\(issues.count) issue\\s found)") return issues } } }
mit
ebab862146a3e0900c7785dad9bed8e6
31.051282
156
0.5184
4.464286
false
false
false
false
Norod/Filterpedia
Filterpedia/customFilters/RefractedTextFilter.swift
1
8663
// // RefractedTextFilter.swift // Filterpedia // // Created by Simon Gladman on 07/02/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import UIKit import CoreImage class RefractedTextFilter: CIFilter { var inputImage: CIImage? { didSet { if inputImage?.extent != refractingImage?.extent { refractingImage = nil } } } var inputText: NSString = "Filterpedia" { didSet { refractingImage = nil } } var inputRefractiveIndex: CGFloat = 4.0 var inputLensScale: CGFloat = 50 var inputLightingAmount: CGFloat = 1.5 var inputLensBlur: CGFloat = 0 var inputBackgroundBlur: CGFloat = 2 var inputRadius: CGFloat = 15 { didSet { if oldValue != inputRadius { refractingImage = nil } } } private var refractingImage: CIImage? private var rawTextImage: CIImage? override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Refracted Text", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputText": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSString", kCIAttributeDisplayName: "Text", kCIAttributeDefault: "Filterpedia", kCIAttributeType: kCIAttributeTypeScalar], "inputRefractiveIndex": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 4.0, kCIAttributeDisplayName: "Refractive Index", kCIAttributeMin: -4.0, kCIAttributeSliderMin: -10.0, kCIAttributeSliderMax: 10, kCIAttributeType: kCIAttributeTypeScalar], "inputLensScale": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 50, kCIAttributeDisplayName: "Lens Scale", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputLightingAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 1.5, kCIAttributeDisplayName: "Lighting Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 5, kCIAttributeType: kCIAttributeTypeScalar], "inputRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 15, kCIAttributeDisplayName: "Edge Radius", kCIAttributeMin: 5, kCIAttributeSliderMin: 5, kCIAttributeSliderMax: 50, kCIAttributeType: kCIAttributeTypeScalar], "inputLensBlur": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Lens Blur", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputBackgroundBlur": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 2, kCIAttributeDisplayName: "Background Blur", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar] ] } override func setDefaults() { inputText = "Filterpedia" inputRefractiveIndex = 4.0 inputLensScale = 50 inputLightingAmount = 1.5 inputRadius = 15 inputLensBlur = 0 inputBackgroundBlur = 2 } override var outputImage: CIImage! { guard let inputImage = inputImage, let refractingKernel = refractingKernel else { return nil } if refractingImage == nil { generateRefractingImage() } let extent = inputImage.extent let arguments = [inputImage, refractingImage!, inputRefractiveIndex, inputLensScale, inputLightingAmount] as [Any] let blurMask = rawTextImage?.applyingFilter("CIColorInvert", withInputParameters: nil) return refractingKernel.apply(withExtent: extent, roiCallback: { (index, rect) in return rect }, arguments: arguments)! .applyingFilter("CIMaskedVariableBlur", withInputParameters: [ kCIInputRadiusKey: inputBackgroundBlur, "inputMask": blurMask!]) .applyingFilter("CIMaskedVariableBlur", withInputParameters: [ kCIInputRadiusKey: inputLensBlur, "inputMask": rawTextImage!]) } func generateRefractingImage() { let label = UILabel(frame: inputImage!.extent) label.text = String(inputText) label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 300) label.adjustsFontSizeToFitWidth = true label.numberOfLines = 0 label.textColor = UIColor.white UIGraphicsBeginImageContextWithOptions( CGSize(width: label.frame.width, height: label.frame.height), true, 1) label.layer.render(in: UIGraphicsGetCurrentContext()!) let textImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() rawTextImage = CIImage(image: textImage!)! refractingImage = CIFilter(name: "CIHeightFieldFromMask", withInputParameters: [ kCIInputRadiusKey: inputRadius, kCIInputImageKey: rawTextImage!])?.outputImage? .cropping(to: inputImage!.extent) } let refractingKernel = CIKernel(string: "float lumaAtOffset(sampler source, vec2 origin, vec2 offset)" + "{" + " vec3 pixel = sample(source, samplerTransform(source, origin + offset)).rgb;" + " float luma = dot(pixel, vec3(0.2126, 0.7152, 0.0722));" + " return luma;" + "}" + "kernel vec4 lumaBasedRefract(sampler image, sampler refractingImage, float refractiveIndex, float lensScale, float lightingAmount) \n" + "{ " + " vec2 d = destCoord();" + " float northLuma = lumaAtOffset(refractingImage, d, vec2(0.0, -1.0));" + " float southLuma = lumaAtOffset(refractingImage, d, vec2(0.0, 1.0));" + " float westLuma = lumaAtOffset(refractingImage, d, vec2(-1.0, 0.0));" + " float eastLuma = lumaAtOffset(refractingImage, d, vec2(1.0, 0.0));" + " vec3 lensNormal = normalize(vec3((eastLuma - westLuma), (southLuma - northLuma), 1.0));" + " vec3 refractVector = refract(vec3(0.0, 0.0, 1.0), lensNormal, refractiveIndex) * lensScale; " + " vec3 outputPixel = sample(image, samplerTransform(image, d + refractVector.xy)).rgb;" + " outputPixel += (northLuma - southLuma) * lightingAmount ;" + " outputPixel += (eastLuma - westLuma) * lightingAmount ;" + " return vec4(outputPixel, 1.0);" + "}" ) }
gpl-3.0
27260b6cdbf24270e4ffd4bf3633c2b6
34.068826
145
0.572039
5.304348
false
false
false
false
VirgilSecurity/virgil-crypto-ios
Source/VirgilCryptoError.swift
1
4233
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Errors for this framework /// /// - signerNotFound: signer not found /// - signatureNotFound: signature not found /// - signatureNotVerified: signature not verified /// - unknownAlgId: unknown alg id /// - rsaShouldBeConstructedDirectly: rsa should be constructed directly /// - unsupportedRsaLength: unsupported rsa length /// - passedKeyIsNotVirgil: passed key is not virgil /// - outputStreamError: output stream has no space left /// - inputStreamError: input stream has no space left /// - invalidSeedSize: invalid seed size /// - dataIsNotSigned: required signature is not present /// - invalidStreamSize: actual stream size doesn't match with provided @objc(VSMVirgilCryptoError) public enum VirgilCryptoError: Int, LocalizedError { case signerNotFound = 1 case signatureNotFound = 2 case signatureNotVerified = 3 case unknownAlgId = 4 case unsupportedRsaLength = 6 case passedKeyIsNotVirgil = 8 case outputStreamError = 9 case inputStreamError = 10 case invalidSeedSize = 11 case dataIsNotSigned = 12 case invalidStreamSize = 13 case compundKeyShouldBeGeneratedDirectly = 14 case unknownCompoundKey = 15 case keyIsNotCompound = 16 case unknownKeyType = 17 /// Human-readable localized description public var errorDescription: String? { switch self { case .signerNotFound: return "Signer not found" case .signatureNotFound: return "Signature not found" case .signatureNotVerified: return "Signature not verified" case .unknownAlgId: return "Unknown alg id" case .unsupportedRsaLength: return "Unsupported rsa length" case .passedKeyIsNotVirgil: return "Passed key is not virgil" case .outputStreamError: return "Output stream has no space left" case .inputStreamError: return "Input stream has no space left" case .invalidSeedSize: return "Invalid seed size" case .dataIsNotSigned: return "Data has no signature to verify" case .invalidStreamSize: return "Actual stream size doesn't match with given value" case .compundKeyShouldBeGeneratedDirectly: return "compund key should be generated directly" case .unknownCompoundKey: return "unknown compound key" case .keyIsNotCompound : return "key is not compound" case .unknownKeyType: return "Unknown key type" } } }
bsd-3-clause
b9032723ae84d0f35fa5010fe8ada469
39.314286
80
0.702339
4.729609
false
false
false
false
smartystreets/smartystreets-ios-sdk
Tests/SmartyStreetsTests/InternationalStreetTests/InternationalStreetCandidateTests.swift
1
13396
import XCTest @testable import SmartyStreets class InternationalCandidateTests: XCTestCase { var obj:NSDictionary! override func setUp() { super.setUp() self.obj = [ "organization": "1", "address1": "2", "address2": "3", "address3": "4", "address4": "5", "address5": "6", "address6": "7", "address7": "8", "address8": "9", "address9": "10", "address10": "11", "address11": "12", "address12": "13", "components": [ "country_iso_3": "14", "super_administrative_area": "15", "administrative_area": "16", "administrative_area_short": "16.1", "administrative_area_long": "16.2", "sub_administrative_area": "17", "dependent_locality": "18", "dependent_locality_name": "19", "double_dependent_locality": "20", "locality": "21", "postal_code": "22", "postal_code_short": "23", "postal_code_extra": "24", "premise": "25", "premise_extra": "26", "premise_number": "27", "premise_prefix_number": "27.5", "premise_type": "28", "thoroughfare": "29", "thoroughfare_predirection": "30", "thoroughfare_postdirection": "31", "thoroughfare_name": "32", "thoroughfare_trailing_type": "33", "thoroughfare_type": "34", "dependent_thoroughfare": "35", "dependent_thoroughfare_predirection": "36", "dependent_thoroughfare_postdirection": "37", "dependent_thoroughfare_name": "38", "dependent_thoroughfare_trailing_type": "39", "dependent_thoroughfare_type": "40", "building": "41", "building_leading_type": "42", "building_name": "43", "building_trailing_type": "44", "sub_building_type": "45", "sub_building_number": "46", "sub_building_name": "47", "sub_building": "48", "level_type": "48.1", "level_number": "48.2", "post_box": "49", "post_box_type": "50", "post_box_number": "51" ], "metadata": [ "latitude": 52.0, "longitude": 53.0, "geocode_precision": "54", "max_geocode_precision": "55", "address_format": "56" ], "analysis": [ "verification_status": "57", "address_precision": "58", "max_address_precision": "59", "changes": [ "organization": "60", "address1": "61", "address2": "62", "address3": "63", "address4": "64", "address5": "65", "address6": "66", "address7": "67", "address8": "68", "address9": "69", "address10": "70", "address11": "71", "address12": "72", "components": [ "country_iso_3": "73", "super_administrative_area": "74", "administrative_area": "75", "administrative_area_short": "75.1", "administrative_area_long": "75.2", "sub_administrative_area": "76", "dependent_locality": "77", "dependent_locality_name": "78", "double_dependent_locality": "79", "locality": "80", "postal_code": "81", "postal_code_short": "82", "postal_code_extra": "83", "premise": "84", "premise_extra": "85", "premise_number": "86", "premise_prefix_number": "87", "premise_type": "88", "thoroughfare": "89", "thoroughfare_predirection": "90", "thoroughfare_postdirection": "91", "thoroughfare_name": "92", "thoroughfare_trailing_type": "93", "thoroughfare_type": "94", "dependent_thoroughfare": "95", "dependent_thoroughfare_predirection": "96", "dependent_thoroughfare_postdirection": "97", "dependent_thoroughfare_name": "98", "dependent_thoroughfare_trailing_type": "99", "dependent_thoroughfare_type": "100", "building": "101", "building_leading_type": "102", "building_name": "103", "building_trailing_type": "104", "sub_building_type": "105", "sub_building_number": "106", "sub_building_name": "107", "sub_building": "108", "level_type": "108.1", "level_number": "108.2", "post_box": "109", "post_box_type": "110", "post_box_number": "111" ] ] ] ] } override func tearDown() { super.tearDown() } func testAllFieldsFilledCorrectly() { let candidate = InternationalStreetCandidate(dictionary: obj) XCTAssertEqual("1", candidate.organization) XCTAssertEqual("2", candidate.address1) XCTAssertEqual("3", candidate.address2) XCTAssertEqual("4", candidate.address3) XCTAssertEqual("5", candidate.address4) XCTAssertEqual("6", candidate.address5) XCTAssertEqual("7", candidate.address6) XCTAssertEqual("8", candidate.address7) XCTAssertEqual("9", candidate.address8) XCTAssertEqual("10", candidate.address9) XCTAssertEqual("11", candidate.address10) XCTAssertEqual("12", candidate.address11) XCTAssertEqual("13", candidate.address12) let components = candidate.components! XCTAssertNotNil(components) XCTAssertEqual("14", components.countryIso3) XCTAssertEqual("15", components.superAdministrativeArea) XCTAssertEqual("16", components.administrativeArea) XCTAssertEqual("16.1", components.administrativeAreaShort) XCTAssertEqual("16.2", components.administrativeAreaLong) XCTAssertEqual("17", components.subAdministrativeArea) XCTAssertEqual("18", components.dependentLocality) XCTAssertEqual("19", components.dependentLocalityName) XCTAssertEqual("20", components.doubleDependentLocality) XCTAssertEqual("21", components.locality) XCTAssertEqual("22", components.postalCode) XCTAssertEqual("23", components.postalCodeShort) XCTAssertEqual("24", components.postalCodeExtra) XCTAssertEqual("25", components.premise) XCTAssertEqual("26", components.premiseExtra) XCTAssertEqual("27", components.premiseNumber) XCTAssertEqual("27.5", components.premisePrefixNumber) XCTAssertEqual("28", components.premiseType) XCTAssertEqual("29", components.thoroughfare) XCTAssertEqual("30", components.thoroughfarePredirection) XCTAssertEqual("31", components.thoroughfarePostdirection) XCTAssertEqual("32", components.thoroughfareName) XCTAssertEqual("33", components.thoroughfareTrailingType) XCTAssertEqual("34", components.thoroughfareType) XCTAssertEqual("35", components.dependentThoroughfare) XCTAssertEqual("36", components.dependentThoroughfarePredirection) XCTAssertEqual("37", components.dependentThoroughfarePostdirection) XCTAssertEqual("38", components.dependentThoroughfareName) XCTAssertEqual("39", components.dependentThoroughfareTrailingType) XCTAssertEqual("40", components.dependentThoroughfareType) XCTAssertEqual("41", components.building) XCTAssertEqual("42", components.buildingLeadingType) XCTAssertEqual("43", components.buildingName) XCTAssertEqual("44", components.buildingTrailingType) XCTAssertEqual("45", components.subBuildingType) XCTAssertEqual("46", components.subBuildingNumber) XCTAssertEqual("47", components.subBuildingName) XCTAssertEqual("48", components.subBuilding) XCTAssertEqual("48.1", components.levelType) XCTAssertEqual("48.2", components.levelNumber) XCTAssertEqual("49", components.postBox) XCTAssertEqual("50", components.postBoxType) XCTAssertEqual("51", components.postBoxNumber) let metadata = candidate.metadata! XCTAssertNotNil(metadata) XCTAssertEqual(52, metadata.latitude) XCTAssertEqual(53, metadata.longitude) XCTAssertEqual("54", metadata.geocodePrecision) XCTAssertEqual("55", metadata.maxGeocodePrecision) XCTAssertEqual("56", metadata.addressFormat) let analysis = candidate.analysis! XCTAssertNotNil(analysis) XCTAssertEqual("57", analysis.verificationStatus) XCTAssertEqual("58", analysis.addressPrecision) XCTAssertEqual("59", analysis.maxAddressPrecision) let changes = analysis.changes! XCTAssertNotNil(changes) XCTAssertEqual("60", changes.organization) XCTAssertEqual("61", changes.address1) XCTAssertEqual("62", changes.address2) XCTAssertEqual("63", changes.address3) XCTAssertEqual("64", changes.address4) XCTAssertEqual("65", changes.address5) XCTAssertEqual("66", changes.address6) XCTAssertEqual("67", changes.address7) XCTAssertEqual("68", changes.address8) XCTAssertEqual("69", changes.address9) XCTAssertEqual("70", changes.address10) XCTAssertEqual("71", changes.address11) XCTAssertEqual("72", changes.address12) let ccomponents = changes.components! XCTAssertNotNil(components) XCTAssertEqual("73", ccomponents.countryIso3) XCTAssertEqual("74", ccomponents.superAdministrativeArea) XCTAssertEqual("75", ccomponents.administrativeArea) XCTAssertEqual("75.1", ccomponents.administrativeAreaShort) XCTAssertEqual("75.2", ccomponents.administrativeAreaLong) XCTAssertEqual("76", ccomponents.subAdministrativeArea) XCTAssertEqual("77", ccomponents.dependentLocality) XCTAssertEqual("78", ccomponents.dependentLocalityName) XCTAssertEqual("79", ccomponents.doubleDependentLocality) XCTAssertEqual("80", ccomponents.locality) XCTAssertEqual("81", ccomponents.postalCode) XCTAssertEqual("82", ccomponents.postalCodeShort) XCTAssertEqual("83", ccomponents.postalCodeExtra) XCTAssertEqual("84", ccomponents.premise) XCTAssertEqual("85", ccomponents.premiseExtra) XCTAssertEqual("86", ccomponents.premiseNumber) XCTAssertEqual("87", ccomponents.premisePrefixNumber) XCTAssertEqual("88", ccomponents.premiseType) XCTAssertEqual("89", ccomponents.thoroughfare) XCTAssertEqual("90", ccomponents.thoroughfarePredirection) XCTAssertEqual("91", ccomponents.thoroughfarePostdirection) XCTAssertEqual("92", ccomponents.thoroughfareName) XCTAssertEqual("93", ccomponents.thoroughfareTrailingType) XCTAssertEqual("94", ccomponents.thoroughfareType) XCTAssertEqual("95", ccomponents.dependentThoroughfare) XCTAssertEqual("96", ccomponents.dependentThoroughfarePredirection) XCTAssertEqual("97", ccomponents.dependentThoroughfarePostdirection) XCTAssertEqual("98", ccomponents.dependentThoroughfareName) XCTAssertEqual("99", ccomponents.dependentThoroughfareTrailingType) XCTAssertEqual("100", ccomponents.dependentThoroughfareType) XCTAssertEqual("101", ccomponents.building) XCTAssertEqual("102", ccomponents.buildingLeadingType) XCTAssertEqual("103", ccomponents.buildingName) XCTAssertEqual("104", ccomponents.buildingTrailingType) XCTAssertEqual("105", ccomponents.subBuildingType) XCTAssertEqual("106", ccomponents.subBuildingNumber) XCTAssertEqual("107", ccomponents.subBuildingName) XCTAssertEqual("108", ccomponents.subBuilding) XCTAssertEqual("108.1", ccomponents.levelType) XCTAssertEqual("108.2", ccomponents.levelNumber) XCTAssertEqual("109", ccomponents.postBox) XCTAssertEqual("110", ccomponents.postBoxType) XCTAssertEqual("111", ccomponents.postBoxNumber) } }
apache-2.0
ed8d3700380bec0876f814da5c79ca44
45.675958
76
0.565915
4.961481
false
false
false
false
rchatham/SwiftyTypeForm
Carthage/Checkouts/PhoneNumberKit/PhoneNumberKitTests/PhoneNumberKitParsingTests.swift
1
17304
// // PhoneNumberKitParsingTests.swift // PhoneNumberKit // // Created by Roy Marmelstein on 29/10/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import XCTest @testable import PhoneNumberKit class PhoneNumberKitParsingTests: XCTestCase { let phoneNumberKit = PhoneNumberKit() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testFailingNumber() { do { _ = try phoneNumberKit.parse("+5491187654321 ABC123", withRegion: "AR") XCTFail() } catch { XCTAssertTrue(true) } } func testUSNumberNoPrefix() { do { let phoneNumber1 = try phoneNumberKit.parse("650 253 0000", withRegion: "US") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international, withPrefix: false) XCTAssertTrue(phoneNumberInternationalFormat1 == "650-253-0000") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national, withPrefix: false) XCTAssertTrue(phoneNumberNationalFormat1 == "(650) 253-0000") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164, withPrefix: false) XCTAssertTrue(phoneNumberE164Format1 == "6502530000") let phoneNumber2 = try phoneNumberKit.parse("800 253 0000", withRegion: "US") XCTAssertNotNil(phoneNumber2) let phoneNumberInternationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .international, withPrefix: false) XCTAssertTrue(phoneNumberInternationalFormat2 == "800-253-0000") let phoneNumberNationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .national, withPrefix: false) XCTAssertTrue(phoneNumberNationalFormat2 == "(800) 253-0000") let phoneNumberE164Format2 = phoneNumberKit.format(phoneNumber2, toType: .e164, withPrefix: false) XCTAssertTrue(phoneNumberE164Format2 == "8002530000") } catch { XCTFail() } } func testUSNumber() { do { let phoneNumber1 = try phoneNumberKit.parse("650 253 0000", withRegion: "US") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+1 650-253-0000") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "(650) 253-0000") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+16502530000") let phoneNumber2 = try phoneNumberKit.parse("800 253 0000", withRegion: "US") XCTAssertNotNil(phoneNumber2) let phoneNumberInternationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat2 == "+1 800-253-0000") let phoneNumberNationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .national) XCTAssertTrue(phoneNumberNationalFormat2 == "(800) 253-0000") let phoneNumberE164Format2 = phoneNumberKit.format(phoneNumber2, toType: .e164) XCTAssertTrue(phoneNumberE164Format2 == "+18002530000") let phoneNumber3 = try phoneNumberKit.parse("900 253 0000", withRegion: "US") XCTAssertNotNil(phoneNumber3) let phoneNumberInternationalFormat3 = phoneNumberKit.format(phoneNumber3, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat3 == "+1 900-253-0000") let phoneNumberNationalFormat3 = phoneNumberKit.format(phoneNumber3, toType: .national) XCTAssertTrue(phoneNumberNationalFormat3 == "(900) 253-0000") let phoneNumberE164Format3 = phoneNumberKit.format(phoneNumber3, toType: .e164) XCTAssertTrue(phoneNumberE164Format3 == "+19002530000") } catch { XCTFail() } } func testBSNumber() { do { let phoneNumber1 = try phoneNumberKit.parse("242 365 1234", withRegion: "BS") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+1 242-365-1234") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "(242) 365-1234") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+12423651234") } catch { XCTFail() } } func testGBNumber() { do { let phoneNumber1 = try phoneNumberKit.parse("(020) 7031 3000", withRegion: "GB") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+44 20 7031 3000") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "020 7031 3000") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+442070313000") let phoneNumber2 = try phoneNumberKit.parse("(07912) 345 678", withRegion: "GB") XCTAssertNotNil(phoneNumber2) let phoneNumberInternationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat2 == "+44 7912 345678") let phoneNumberNationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .national) XCTAssertTrue(phoneNumberNationalFormat2 == "07912 345678") let phoneNumberE164Format2 = phoneNumberKit.format(phoneNumber2, toType: .e164) XCTAssertTrue(phoneNumberE164Format2 == "+447912345678") } catch { XCTFail() } } func testDENumber() { do { let phoneNumber1 = try phoneNumberKit.parse("0291 12345678", withRegion: "DE") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+49 291 12345678") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "0291 12345678") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+4929112345678") let phoneNumber2 = try phoneNumberKit.parse("04134 1234", withRegion: "DE") XCTAssertNotNil(phoneNumber2) let phoneNumberInternationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat2 == "+49 4134 1234") let phoneNumberNationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .national) XCTAssertTrue(phoneNumberNationalFormat2 == "04134 1234") let phoneNumberE164Format2 = phoneNumberKit.format(phoneNumber2, toType: .e164) XCTAssertTrue(phoneNumberE164Format2 == "+4941341234") let phoneNumber3 = try phoneNumberKit.parse("+49 8021 2345", withRegion: "DE") XCTAssertNotNil(phoneNumber3) let phoneNumberInternationalFormat3 = phoneNumberKit.format(phoneNumber3, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat3 == "+49 8021 2345") let phoneNumberNationalFormat3 = phoneNumberKit.format(phoneNumber3, toType: .national) XCTAssertTrue(phoneNumberNationalFormat3 == "08021 2345") let phoneNumberE164Format3 = phoneNumberKit.format(phoneNumber3, toType: .e164) XCTAssertTrue(phoneNumberE164Format3 == "+4980212345") } catch { XCTFail() } } func testITNumber() { do { let phoneNumber1 = try phoneNumberKit.parse("02 3661 8300", withRegion: "IT") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+39 02 3661 8300") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "02 3661 8300") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+390236618300") } catch { XCTFail() } } func testAUNumber() { do { let phoneNumber1 = try phoneNumberKit.parse("02 3661 8300", withRegion: "AU") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+61 2 3661 8300") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "(02) 3661 8300") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+61236618300") let phoneNumber2 = try phoneNumberKit.parse("+61 1800 123 456", withRegion: "AU") XCTAssertNotNil(phoneNumber2) let phoneNumberInternationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat2 == "+61 1800 123 456") let phoneNumberNationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .national) XCTAssertTrue(phoneNumberNationalFormat2 == "1800 123 456") let phoneNumberE164Format2 = phoneNumberKit.format(phoneNumber2, toType: .e164) XCTAssertTrue(phoneNumberE164Format2 == "+611800123456") } catch { XCTFail() } } // func testARNumber() { do { let phoneNumber1 = try phoneNumberKit.parse("011 8765-4321", withRegion: "AR") XCTAssertNotNil(phoneNumber1) let phoneNumberInternationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat1 == "+54 11 8765-4321") let phoneNumberNationalFormat1 = phoneNumberKit.format(phoneNumber1, toType: .national) XCTAssertTrue(phoneNumberNationalFormat1 == "011 8765-4321") let phoneNumberE164Format1 = phoneNumberKit.format(phoneNumber1, toType: .e164) XCTAssertTrue(phoneNumberE164Format1 == "+541187654321") let phoneNumber2 = try phoneNumberKit.parse("011 15 8765-4321", withRegion: "AR") XCTAssertNotNil(phoneNumber2) let phoneNumberInternationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .international) XCTAssertTrue(phoneNumberInternationalFormat2 == "+54 9 11 8765-4321") let phoneNumberNationalFormat2 = phoneNumberKit.format(phoneNumber2, toType: .national) XCTAssertTrue(phoneNumberNationalFormat2 == "011 15-8765-4321") let phoneNumberE164Format2 = phoneNumberKit.format(phoneNumber2, toType: .e164) XCTAssertTrue(phoneNumberE164Format2 == "+5491187654321") } catch { XCTFail() } } func testAllExampleNumbers() { let metaDataArray = phoneNumberKit.metadataManager.territories.filter{$0.codeID.characters.count == 2} for metadata in metaDataArray { let codeID = metadata.codeID let metadataWithTypes: [(MetadataPhoneNumberDesc?, PhoneNumberType?)] = [ (metadata.generalDesc, nil), (metadata.fixedLine, .fixedLine), (metadata.mobile, .mobile), (metadata.tollFree, .tollFree), (metadata.premiumRate, .premiumRate), (metadata.sharedCost, .sharedCost), (metadata.voip, .voip), (metadata.voicemail, .voicemail), (metadata.pager, .pager), (metadata.uan, .uan), (metadata.emergency, nil), ] metadataWithTypes.forEach { record in if let desc = record.0 { if let exampleNumber = desc.exampleNumber { do { let phoneNumber = try phoneNumberKit.parse(exampleNumber, withRegion: codeID) XCTAssertNotNil(phoneNumber) if let type = record.1 { if phoneNumber.type == .fixedOrMobile { XCTAssert(type == .fixedLine || type == .mobile) } else { XCTAssertEqual(phoneNumber.type, type, "Expected type \(type) for number \(phoneNumber)") } } } catch (let e) { XCTFail("Failed to create PhoneNumber for \(exampleNumber): \(e)") } } } } } } func testRegexMatchesEntirely() { let pattern = "[2-9]\\d{8}|860\\d{9}" let number = "860123456789" let regex = RegexManager() XCTAssert(regex.matchesEntirely(pattern, string: number)) XCTAssertFalse(regex.matchesEntirely("8", string: number)) } func testUSTollFreeNumberType() { guard let number = try? phoneNumberKit.parse("8002345678", withRegion: "US") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.tollFree) } func testBelizeTollFreeType() { guard let number = try? phoneNumberKit.parse("08001234123", withRegion: "BZ") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.tollFree) } func testItalyFixedLineType() { guard let number = try? phoneNumberKit.parse("0669812345", withRegion: "IT") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.fixedLine) } func testMaldivesPagerNumber() { guard let number = try? phoneNumberKit.parse("7812345", withRegion: "MV") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.pager) } func testZimbabweVoipType() { guard let number = try? phoneNumberKit.parse("8686123456", withRegion: "ZW") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.voip) } func testAntiguaPagerNumberType() { guard let number = try? phoneNumberKit.parse("12684061234", withRegion: "US") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.pager) } func testFranceMobileNumberType() { guard let number = try? phoneNumberKit.parse("+33 612-345-678") else { XCTFail() return } XCTAssertEqual(number.type, PhoneNumberType.mobile) } func testPerformanceSimple() { let numberOfParses = 1000 let startTime = Date() var endTime = Date() var numberArray: [String] = [] for _ in 0 ..< numberOfParses { numberArray.append("+5491187654321") } _ = phoneNumberKit.parse(numberArray, withRegion: "AR", ignoreType: true) endTime = Date() let timeInterval = endTime.timeIntervalSince(startTime) print("time to parse \(numberOfParses) phone numbers, \(timeInterval) seconds") XCTAssertTrue(timeInterval < 5) } func testMultipleMutated() { let numberOfParses = 500 let startTime = Date() var endTime = Date() var numberArray: [String] = [] for _ in 0 ..< numberOfParses { numberArray.append("+5491187654321") } let phoneNumbers = phoneNumberKit.parseManager.parseMultiple(numberArray, withRegion: "AR", ignoreType: true) { numberArray.remove(at: 100) } XCTAssertTrue(phoneNumbers.count == numberOfParses) endTime = Date() let timeInterval = endTime.timeIntervalSince(startTime) print("time to parse \(numberOfParses) phone numbers, \(timeInterval) seconds") } }
mit
3417ac4b0d455b022b9aa0e76531f310
46.405479
128
0.636017
4.980714
false
true
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Contacts/ContactsSearchSource.swift
9
1608
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class ContactsSearchSource: SearchSource { override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell { let reuseId = "cell_contact"; var cell = tableView.dequeueReusableCellWithIdentifier(reuseId) as! ContactCell?; if (cell == nil) { cell = ContactCell(reuseIdentifier:reuseId); } return cell!; } override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) { let contact = item as! ACContact; let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1; // Building short name var shortName : String? = nil; if (indexPath.row == 0) { shortName = contact.getName().smallValue(); } else { let prevContact = objectAtIndexPath(NSIndexPath(forRow: indexPath.row-1, inSection: indexPath.section)) as! ACContact; let prevName = prevContact.getName().smallValue(); let name = contact.getName().smallValue(); if (prevName != name){ shortName = name; } } (cell as! ContactCell).bindContact(contact, shortValue: shortName, isLast: isLast); } override func buildDisplayList() -> ARBindedDisplayList { return Actor.buildContactsDisplayList() } }
mit
3e34e45c8e05a1f409330a3d74a5ab28
33.978261
139
0.612562
5.187097
false
false
false
false
RoseEr/HealthyLifestyleTracker
HealthyLifestyleTracker/FoodTrackerSetupViewController.swift
1
3579
// // FoodTrackerSetupViewController.swift // HealthyLifestyleTracker // // Created by Eric Rose on 1/19/17. // Copyright © 2017 Eric Rose. All rights reserved. // import UIKit import CoreData class FoodTrackerSetupViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var proteinTextField: UITextField! @IBOutlet weak var dairyTextField: UITextField! @IBOutlet weak var fruitsTextField: UITextField! @IBOutlet weak var vegetablesTextField: UITextField! @IBOutlet weak var fatsTextField: UITextField! let categoryDataAccessor = CategoryDataAccessor() override func viewDidLoad() { super.viewDidLoad() setupTextFields() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupTextFields() { proteinTextField.delegate = self dairyTextField.delegate = self fruitsTextField.delegate = self vegetablesTextField.delegate = self fatsTextField.delegate = self } @IBAction func Pressed(_ sender: UIButton) { if (!didUserEnterAllValues()) { sendAlert(message: "Please enter a value for all categories.") } else { saveFoodTrackerCategory(name: "Protein", goal: proteinTextField.text!, helpText: "~100 calories/serving", calorieValue: 100) saveFoodTrackerCategory(name: "Dairy", goal: dairyTextField.text!, helpText: "~120 calories/serving", calorieValue: 120) saveFoodTrackerCategory(name: "Fruits", goal: fruitsTextField.text!, helpText: "~100 calories/serving", calorieValue: 100) saveFoodTrackerCategory(name: "Vegetables", goal: vegetablesTextField.text!, helpText: "~50 calories/serving", calorieValue: 50) saveFoodTrackerCategory(name: "Fats", goal: fatsTextField.text!, helpText: "~120 calories/serving", calorieValue: 120) } } private func saveFoodTrackerCategory(name: String, goal: String, helpText: String, calorieValue: Int) { let category = Category() if let dailyGoalIntValue = (NumberFormatter().number(from: goal)?.intValue) { category.dailyGoal = dailyGoalIntValue } else { category.dailyGoal = 0 } category.name = name category.helpText = helpText category.maxValue = 10 category.calorieValue = calorieValue self.categoryDataAccessor.addCategory(category: category) } private func didUserEnterAllValues() -> Bool { return !proteinTextField.text!.isEmpty && !dairyTextField.text!.isEmpty && !fruitsTextField.text!.isEmpty && !vegetablesTextField.text!.isEmpty && !fatsTextField.text!.isEmpty } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { guard let enteredValue = NumberFormatter().number(from: textField.text!) else { return false; } if (enteredValue.intValue > 10) { sendAlert(message: "Maximum value is 10."); return false; } else { return true; } } func sendAlert(message: String) { let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
mit
c5e9d54019d4de6a9ecf7ddffc220b3b
35.510204
140
0.654835
4.802685
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/SettingsCustomTheme.swift
1
23511
// // SettingsCustomTheme.swift // Slide for Reddit // // Created by Carlos Crane on 1/23/19. // Copyright © 2019 Haptic Apps. All rights reserved. // import Anchorage import RLBAlertsPickers import SDCAlertView import UIKit class SettingsCustomTheme: UITableViewController { var foreground: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "foreground") var background: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "background") var font: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "font") var navicon: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "navicon") var statusbar: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "status") var inputTheme = "" var isCurrentTheme = false var foregroundColor = UIColor.white var backgroundColor = UIColor.white var fontColor = UIColor.black.withAlphaComponent(0.85) var navIconColor = UIColor.black.withAlphaComponent(0.85) var statusbarEnabled = true var selectedRow = -1 var statusbarSwitch: UISwitch = UISwitch().then { $0.onTintColor = ColorUtil.baseAccent } public func createCell(_ cell: UITableViewCell, _ switchV: UISwitch? = nil, isOn: Bool, text: String) { cell.textLabel?.text = text cell.textLabel?.textColor = ColorUtil.theme.fontColor cell.backgroundColor = ColorUtil.theme.foregroundColor cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let s = switchV { s.isOn = isOn s.addTarget(self, action: #selector(SettingsLayout.switchIsChanged(_:)), for: UIControl.Event.valueChanged) cell.accessoryView = s } cell.selectionStyle = UITableViewCell.SelectionStyle.none } override func setupBaseBarColors(_ overrideColor: UIColor? = nil) { navigationController?.navigationBar.barTintColor = SettingValues.reduceColor ? backgroundColor : UserDefaults.standard.colorForKey(key: "color+") ?? ColorUtil.baseColor navigationController?.navigationBar.tintColor = SettingValues.reduceColor ? fontColor : UIColor.white let textAttributes = [NSAttributedString.Key.foregroundColor: SettingValues.reduceColor ? fontColor : .white] navigationController?.navigationBar.titleTextAttributes = textAttributes } override func viewDidLoad() { self.title = "New Custom Theme" doToolbar(UIColor.black) if !inputTheme.isEmpty() { print("Input theme is \(inputTheme)") let colors = UserDefaults.standard.string(forKey: "Theme+" + inputTheme)?.removingPercentEncoding ?? UserDefaults.standard.string(forKey: "Theme+" + inputTheme.replacingOccurrences(of: "#", with: "<H>").addPercentEncoding)?.removingPercentEncoding ?? UserDefaults.standard.string(forKey: "Theme+" + inputTheme.replacingOccurrences(of: "#", with: "<H>"))?.removingPercentEncoding ?? "" if !colors.isEmpty { let split = colors.split("#") print(colors) foregroundColor = UIColor(hex: split[2]) backgroundColor = UIColor(hex: split[3]) fontColor = UIColor(hex: split[4]) navIconColor = UIColor(hex: split[5]) statusbarEnabled = Bool(split[8])! doToolbar(navIconColor) isCurrentTheme = foregroundColor.hexString() == ColorUtil.theme.foregroundColor.hexString() && backgroundColor.hexString() == ColorUtil.theme.backgroundColor.hexString() && fontColor.hexString() == ColorUtil.theme.fontColor.hexString() && navIconColor.hexString() == ColorUtil.theme.navIconColor.hexString() self.title = split[1].removingPercentEncoding!.replacingOccurrences(of: "<H>", with: "#") self.setupViews() setupBaseBarColors() } } super.viewDidLoad() } var doneOnce = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupBaseBarColors() } var themeText: String? @objc public func save() { if inputTheme.isEmpty { let alert = AlertController(title: "Save theme?", message: "", preferredStyle: .alert) let date = Date() let calender = Calendar.current let components = calender.dateComponents([.year, .month, .day], from: date) let year = components.year let month = components.month let day = components.day let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) let config: TextField.Config = { textField in textField.becomeFirstResponder() textField.textColor = ColorUtil.theme.fontColor textField.attributedPlaceholder = NSAttributedString(string: "Theme name...", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor.withAlphaComponent(0.3)]) textField.layer.borderColor = ColorUtil.theme.fontColor.withAlphaComponent(0.3) .cgColor textField.backgroundColor = ColorUtil.theme.foregroundColor textField.layer.borderWidth = 1 textField.autocorrectionType = UITextAutocorrectionType.no textField.keyboardAppearance = .default textField.keyboardType = .default textField.returnKeyType = .done textField.text = today_string textField.action { textField in self.themeText = textField.text } } let textField = OneTextFieldViewController(vInset: 12, configuration: config).view! alert.setupTheme() alert.attributedTitle = NSAttributedString(string: "Save theme?", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) alert.contentView.addSubview(textField) textField.edgeAnchors == alert.contentView.edgeAnchors textField.heightAnchor == CGFloat(44 + 12) let blurEffect = (NSClassFromString("_UICustomBlurEffect") as! UIBlurEffect.Type).init() let blurView = UIVisualEffectView(frame: UIScreen.main.bounds) blurEffect.setValue(8, forKeyPath: "blurRadius") blurView.effect = blurEffect alert.addAction(AlertAction(title: "Save", style: .preferred, handler: { (_) in var colorString = "slide://colors" colorString += ("#" + (self.themeText?.replacingOccurrences(of: "#", with: "<H>") ?? today_string)).addPercentEncoding colorString += (self.foregroundColor.toHexString() + self.backgroundColor.toHexString() + self.fontColor.toHexString() + self.navIconColor.toHexString() + ColorUtil.baseColor.toHexString() + ColorUtil.baseAccent.toHexString() + "#" + String(self.statusbarEnabled)).addPercentEncoding UserDefaults.standard.set(colorString, forKey: "Theme+" + (self.themeText ?? today_string)) UserDefaults.standard.synchronize() SettingsTheme.needsRestart = true ColorUtil.initializeThemes() self.dismiss(animated: true, completion: nil) })) alert.addAction(AlertAction(title: "Discard", style: .destructive, handler: { (_) in self.dismiss(animated: true, completion: nil) })) alert.addCancelButton() alert.addBlurView() self.present(alert, animated: true, completion: nil) } else { var colorString = "slide://colors" colorString += ("#" + self.inputTheme).addPercentEncoding colorString += (self.foregroundColor.toHexString() + self.backgroundColor.toHexString() + self.fontColor.toHexString() + self.navIconColor.toHexString() + ColorUtil.baseColor.toHexString() + ColorUtil.baseAccent.toHexString() + "#" + String(self.statusbarEnabled)).addPercentEncoding UserDefaults.standard.set(colorString, forKey: "Theme+" + inputTheme) UserDefaults.standard.synchronize() if isCurrentTheme { _ = ColorUtil.doInit() MainViewController.needsReTheme = true } ColorUtil.initializeThemes() SettingsTheme.needsRestart = true self.dismiss(animated: true, completion: nil) } } var defaultButton: UIBarButtonItem? override func loadView() { super.loadView() setupViews() } func setupViews() { setupBaseBarColors() if #available(iOS 13.0, *) { self.isModalInPresentation = true } self.view.backgroundColor = backgroundColor // set the title self.tableView.separatorStyle = .none self.foreground.textLabel?.text = "Foreground color" self.foreground.accessoryType = .none self.foreground.backgroundColor = foregroundColor self.foreground.textLabel?.textColor = fontColor self.foreground.imageView?.image = UIImage(named: "circle")?.toolbarIcon().getCopy(withColor: foregroundColor) self.foreground.imageView?.layer.masksToBounds = true self.foreground.imageView?.layer.borderWidth = 1.5 self.foreground.imageView?.layer.borderColor = UIColor.white.cgColor self.foreground.imageView?.layer.cornerRadius = self.foreground.imageView!.bounds.width / 2 self.background.textLabel?.text = "Background color" self.background.accessoryType = .none self.background.backgroundColor = foregroundColor self.background.textLabel?.textColor = fontColor self.background.imageView?.image = UIImage(named: "circle")?.toolbarIcon().getCopy(withColor: backgroundColor) self.font.textLabel?.text = "Font color" self.font.accessoryType = .none self.font.backgroundColor = foregroundColor self.font.textLabel?.textColor = fontColor self.font.imageView?.image = UIImage(named: "circle")?.toolbarIcon().getCopy(withColor: fontColor) self.navicon.textLabel?.text = "Icons color" self.navicon.accessoryType = .none self.navicon.backgroundColor = foregroundColor self.navicon.textLabel?.textColor = fontColor self.navicon.imageView?.image = UIImage(named: "circle")?.toolbarIcon().getCopy(withColor: navIconColor) self.statusbar.textLabel?.text = "Light statusbar" self.statusbar.accessoryType = .none self.statusbar.backgroundColor = foregroundColor self.statusbar.textLabel?.textColor = fontColor statusbarSwitch.addTarget(self, action: #selector(switchIsChanged(_:)), for: .valueChanged) statusbarSwitch.isOn = !statusbarEnabled self.statusbar.accessoryView = statusbarSwitch self.tableView.tableFooterView = UIView() } func doToolbar(_ iconColor: UIColor) { let button = UIButtonWithContext.init(type: .custom) button.imageView?.contentMode = UIView.ContentMode.scaleAspectFit button.setImage(UIImage(sfString: SFSymbol.xmark, overrideString: "close")!.navIcon().getCopy(withColor: iconColor), for: UIControl.State.normal) button.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) button.addTarget(self, action: #selector(close), for: .touchUpInside) let barButton = UIBarButtonItem.init(customView: button) navigationItem.leftBarButtonItem = barButton let save = UIButtonWithContext(type: UIButton.ButtonType.system) save.setTitle("Save", for: UIControl.State.normal) save.tintColor = iconColor save.addTarget(self, action: #selector(self.save), for: .touchUpInside) let saveButton = UIBarButtonItem.init(customView: save) navigationItem.rightBarButtonItem = saveButton } @objc func close() { let alert = UIAlertController.init(title: "Discard changes?", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in self.dismiss(animated: true, completion: nil) })) alert.addAction(UIAlertAction.init(title: "No", style: .cancel)) present(alert, animated: true) } override var preferredStatusBarStyle: UIStatusBarStyle { if statusbarEnabled && SettingValues.reduceColor { return .default } else { return .lightContent } } @objc public func handleBackButton() { save() } @objc func switchIsChanged(_ changed: UISwitch) { if changed == statusbarSwitch { statusbarEnabled = !changed.isOn } cleanup() self.tableView.reloadData(with: .automatic) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { } override func viewWillDisappear(_ animated: Bool) { SubredditReorderViewController.changed = true } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: switch indexPath.row { case 0: return self.foreground case 1: return self.background case 2: return self.font case 3: return self.navicon case 4: return self.statusbar default: fatalError("Unknown row in section 0") } default: fatalError("Unknown section") } } func cleanup() { loadView() } var tagText: String? override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) ColorUtil.initializeThemes() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.row == 4 { return } if #available(iOS 14, *) { let vc = UIColorPickerViewController() vc.supportsAlpha = false vc.delegate = self self.selectedRow = indexPath.row switch indexPath.row { case 0: vc.selectedColor = foregroundColor vc.title = "Foreground color" case 1: vc.selectedColor = backgroundColor vc.title = "Background color" case 2: vc.selectedColor = fontColor vc.title = "Font color" default: vc.selectedColor = navIconColor vc.title = "Icons color" } present(vc, animated: true) } else { let alert = AlertController(title: "", message: "", preferredStyle: .alert) var color: UIColor switch indexPath.row { case 0: color = foregroundColor alert.attributedMessage = NSAttributedString(string: "Foreground color", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) case 1: color = backgroundColor alert.attributedMessage = NSAttributedString(string: "Background color", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) case 2: color = fontColor alert.attributedMessage = NSAttributedString(string: "Font color", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) default: color = navIconColor alert.attributedMessage = NSAttributedString(string: "Icons color", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) } let selection: ColorPickerViewController.Selection? = { color in switch indexPath.row { case 0: self.foregroundColor = color case 1: self.backgroundColor = color case 2: self.fontColor = color default: self.navIconColor = color self.doToolbar(color) } self.cleanup() } let buttonSelection = AlertAction(title: "Save", style: .normal) { _ in selection?(color) } buttonSelection.isEnabled = true alert.addAction(buttonSelection) let hexSelection = AlertAction(title: "Enter HEX code", style: .normal) { _ in alert.dismiss() let alert = AlertController(title: "", message: nil, preferredStyle: .alert) let confirmAction = AlertAction(title: "Set", style: .preferred) { (_) in if let text = self.tagText { let color = UIColor(hexString: text) switch indexPath.row { case 0: self.foregroundColor = color case 1: self.backgroundColor = color case 2: self.fontColor = color default: self.navIconColor = color self.doToolbar(color) } self.cleanup() } else { } } let config: TextField.Config = { textField in textField.becomeFirstResponder() textField.textColor = ColorUtil.theme.fontColor textField.attributedPlaceholder = NSAttributedString(string: "HEX String", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor.withAlphaComponent(0.3)]) textField.left(image: UIImage(named: "pallete")?.menuIcon(), color: ColorUtil.theme.fontColor) textField.layer.borderColor = ColorUtil.theme.fontColor.withAlphaComponent(0.3) .cgColor textField.backgroundColor = ColorUtil.theme.foregroundColor textField.leftViewPadding = 12 textField.layer.borderWidth = 1 textField.layer.cornerRadius = 8 textField.keyboardAppearance = .default textField.keyboardType = .default textField.returnKeyType = .done textField.text = color.hexString() textField.action { textField in self.tagText = textField.text } } let textField = OneTextFieldViewController(vInset: 12, configuration: config).view! alert.setupTheme() alert.attributedTitle = NSAttributedString(string: "Enter HEX color code", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) alert.contentView.addSubview(textField) textField.edgeAnchors == alert.contentView.edgeAnchors textField.heightAnchor == CGFloat(44 + 12) alert.addAction(confirmAction) alert.addCancelButton() alert.addBlurView() self.present(alert, animated: true, completion: nil) } alert.addAction(hexSelection) let storyboard = UIStoryboard(name: "Main", bundle: nil) guard let vc = storyboard.instantiateViewController(withIdentifier: "ColorPicker") as? ColorPickerViewController else { return } alert.addChild(vc) let vcv = vc.view! let view = UIView() alert.contentView.addSubview(view) view.edgeAnchors == alert.contentView.edgeAnchors view.heightAnchor == 400 vcv.isUserInteractionEnabled = true vcv.backgroundColor = UIColor.clear alert.setupTheme() alert.attributedTitle = NSAttributedString(string: color.hexString(), attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) vc.set(color: color) { new in color = new alert.attributedTitle = NSAttributedString(string: color.hexString(), attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) } alert.addCancelButton() alert.addBlurView() self.present(alert, animated: true) { } alert.view!.addSubview(vcv) vc.didMove(toParent: alert) vcv.horizontalAnchors == alert.contentView.superview!.horizontalAnchors vcv.topAnchor == alert.contentView.superview!.topAnchor + 70 vcv.bottomAnchor == alert.contentView.superview!.bottomAnchor vcv.heightAnchor == 400 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 5 default: fatalError("Unknown number of sections") } } } @available(iOS 14, *) extension SettingsCustomTheme: UIColorPickerViewControllerDelegate { func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) { let color = viewController.selectedColor switch selectedRow { case 0: self.foregroundColor = color case 1: self.backgroundColor = color case 2: self.fontColor = color default: self.navIconColor = color self.doToolbar(color) } self.cleanup() } }
apache-2.0
1b55b383748e596e6c3fee0a0fc61566
44.298651
396
0.606806
5.484021
false
false
false
false
airbnb/lottie-ios
Sources/Private/Model/Objects/Transform.swift
3
6773
// // Transform.swift // lottie-swift // // Created by Brandon Withrow on 1/7/19. // import Foundation /// The animatable transform for a layer. Controls position, rotation, scale, and opacity. final class Transform: Codable, DictionaryInitializable { // MARK: Lifecycle required init(from decoder: Decoder) throws { /// This manual override of decode is required because we want to throw an error /// in the case that there is not position data. let container = try decoder.container(keyedBy: Transform.CodingKeys.self) // AnchorPoint anchorPoint = try container .decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .anchorPoint) ?? KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0)) // Position if container.contains(.positionX), container.contains(.positionY) { // Position dimensions are split into two keyframe groups positionX = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionX) positionY = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionY) position = nil } else if let positionKeyframes = try? container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .position) { // Position dimensions are a single keyframe group. position = positionKeyframes positionX = nil positionY = nil } else if let positionContainer = try? container.nestedContainer(keyedBy: PositionCodingKeys.self, forKey: .position), let positionX = try? positionContainer.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionX), let positionY = try? positionContainer.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionY) { /// Position keyframes are split and nested. self.positionX = positionX self.positionY = positionY position = nil } else { /// Default value. position = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0)) positionX = nil positionY = nil } // Scale scale = try container .decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .scale) ?? KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100)) // Rotation if let rotationZ = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationZ) { rotation = rotationZ } else { rotation = try container .decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotation) ?? KeyframeGroup(LottieVector1D(0)) } rotationZ = nil // Opacity opacity = try container .decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .opacity) ?? KeyframeGroup(LottieVector1D(100)) } init(dictionary: [String: Any]) throws { if let anchorPointDictionary = dictionary[CodingKeys.anchorPoint.rawValue] as? [String: Any], let anchorPoint = try? KeyframeGroup<LottieVector3D>(dictionary: anchorPointDictionary) { self.anchorPoint = anchorPoint } else { anchorPoint = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0)) } if let xDictionary = dictionary[CodingKeys.positionX.rawValue] as? [String: Any], let yDictionary = dictionary[CodingKeys.positionY.rawValue] as? [String: Any] { positionX = try KeyframeGroup<LottieVector1D>(dictionary: xDictionary) positionY = try KeyframeGroup<LottieVector1D>(dictionary: yDictionary) position = nil } else if let positionDictionary = dictionary[CodingKeys.position.rawValue] as? [String: Any], positionDictionary[KeyframeGroup<LottieVector3D>.KeyframeWrapperKey.keyframeData.rawValue] != nil { position = try KeyframeGroup<LottieVector3D>(dictionary: positionDictionary) positionX = nil positionY = nil } else if let positionDictionary = dictionary[CodingKeys.position.rawValue] as? [String: Any], let xDictionary = positionDictionary[PositionCodingKeys.positionX.rawValue] as? [String: Any], let yDictionary = positionDictionary[PositionCodingKeys.positionY.rawValue] as? [String: Any] { positionX = try KeyframeGroup<LottieVector1D>(dictionary: xDictionary) positionY = try KeyframeGroup<LottieVector1D>(dictionary: yDictionary) position = nil } else { position = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0)) positionX = nil positionY = nil } if let scaleDictionary = dictionary[CodingKeys.scale.rawValue] as? [String: Any], let scale = try? KeyframeGroup<LottieVector3D>(dictionary: scaleDictionary) { self.scale = scale } else { scale = KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100)) } if let rotationDictionary = dictionary[CodingKeys.rotationZ.rawValue] as? [String: Any], let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary) { self.rotation = rotation } else if let rotationDictionary = dictionary[CodingKeys.rotation.rawValue] as? [String: Any], let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary) { self.rotation = rotation } else { rotation = KeyframeGroup(LottieVector1D(0)) } rotationZ = nil if let opacityDictionary = dictionary[CodingKeys.opacity.rawValue] as? [String: Any], let opacity = try? KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary) { self.opacity = opacity } else { opacity = KeyframeGroup(LottieVector1D(100)) } } // MARK: Internal enum CodingKeys: String, CodingKey { case anchorPoint = "a" case position = "p" case positionX = "px" case positionY = "py" case scale = "s" case rotation = "r" case rotationZ = "rz" case opacity = "o" } enum PositionCodingKeys: String, CodingKey { case split = "s" case positionX = "x" case positionY = "y" } /// The anchor point of the transform. let anchorPoint: KeyframeGroup<LottieVector3D> /// The position of the transform. This is nil if the position data was split. let position: KeyframeGroup<LottieVector3D>? /// The positionX of the transform. This is nil if the position property is set. let positionX: KeyframeGroup<LottieVector1D>? /// The positionY of the transform. This is nil if the position property is set. let positionY: KeyframeGroup<LottieVector1D>? /// The scale of the transform let scale: KeyframeGroup<LottieVector3D> /// The rotation of the transform. Note: This is single dimensional rotation. let rotation: KeyframeGroup<LottieVector1D> /// The opacity of the transform. let opacity: KeyframeGroup<LottieVector1D> /// Should always be nil. let rotationZ: KeyframeGroup<LottieVector1D>? }
apache-2.0
16ca860cdd6cc6c1b93fb58bdea839b8
36.010929
116
0.697328
4.314013
false
false
false
false
airbnb/lottie-ios
Sources/Public/AnimationCache/DefaultAnimationCache.swift
2
1274
// // DefaultAnimationCache.swift // Lottie // // Created by Marcelo Fabri on 10/18/22. // import Foundation /// A thread-safe Animation Cache that will store animations up to `cacheSize`. /// /// Once `cacheSize` is reached, animations can be ejected. /// The default size of the cache is 100. /// /// This cache implementation also responds to memory pressure, as it's backed by `NSCache`. public class DefaultAnimationCache: AnimationCacheProvider { // MARK: Lifecycle public init() { cache.countLimit = Self.defaultCacheCountLimit } // MARK: Public /// The global shared Cache. public static let sharedCache = DefaultAnimationCache() /// The size of the cache. public var cacheSize = defaultCacheCountLimit { didSet { cache.countLimit = cacheSize } } /// Clears the Cache. public func clearCache() { cache.removeAllObjects() } public func animation(forKey key: String) -> LottieAnimation? { cache.object(forKey: key as NSString) } public func setAnimation(_ animation: LottieAnimation, forKey key: String) { cache.setObject(animation, forKey: key as NSString) } // MARK: Private private static let defaultCacheCountLimit = 100 private var cache = NSCache<NSString, LottieAnimation>() }
apache-2.0
693134af5c7ea2101342ae6d96f7c974
22.592593
92
0.704867
4.408304
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/ReformaCrossing/Strategy/MOptionReformaCrossingStrategyEnd.swift
1
1243
import Foundation class MOptionReformaCrossingStrategyEnd:MGameStrategyMain<MOptionReformaCrossing> { private var initialTime:TimeInterval? private let kWait:TimeInterval = 1.5 override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionReformaCrossing>) { super.update(elapsedTime:elapsedTime, scene:scene) if let initialTime:TimeInterval = self.initialTime { let deltaTime:TimeInterval = elapsedTime - initialTime checkTimeout(deltaTime:deltaTime, scene:scene) } else { self.initialTime = elapsedTime } } //MARK: private private func checkTimeout( deltaTime:TimeInterval, scene:ViewGameScene<MOptionReformaCrossing>) { if deltaTime > kWait { guard let controller:COptionReformaCrossing = scene.controller as? COptionReformaCrossing else { return } timeOut(controller:controller) } } //MARK: public func timeOut(controller:COptionReformaCrossing) { } }
mit
9e74c5ebb72f7f4ea1cce3f9cb839954
23.372549
99
0.577635
5.75463
false
false
false
false
HongliYu/firefox-ios
Client/Frontend/Theme/Theme.swift
1
10436
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation protocol Themeable { func applyTheme() } protocol PrivateModeUI { func applyUIMode(isPrivate: Bool) } extension UIColor { static var theme: Theme { return ThemeManager.instance.current } } enum BuiltinThemeName: String { case normal case dark } // Convenience reference to these normal mode colors which are used in a few color classes. fileprivate let defaultBackground = UIColor.Photon.Grey10 fileprivate let defaultSeparator = UIColor.Photon.Grey30 fileprivate let defaultTextAndTint = UIColor.Photon.Grey80 class TableViewColor { var rowBackground: UIColor { return UIColor.Photon.White100 } var rowText: UIColor { return UIColor.Photon.Grey90 } var rowDetailText: UIColor { return UIColor.Photon.Grey60 } var disabledRowText: UIColor { return UIColor.Photon.Grey40 } var separator: UIColor { return defaultSeparator } var headerBackground: UIColor { return defaultBackground } // Used for table headers in Settings and Photon menus var headerTextLight: UIColor { return UIColor.Photon.Grey50 } // Used for table headers in home panel tables var headerTextDark: UIColor { return UIColor.Photon.Grey90 } var rowActionAccessory: UIColor { return UIColor.Photon.Blue40 } var controlTint: UIColor { return rowActionAccessory } var syncText: UIColor { return defaultTextAndTint } var errorText: UIColor { return UIColor.Photon.Red50 } var warningText: UIColor { return UIColor.Photon.Orange50 } } class ActionMenuColor { var foreground: UIColor { return defaultTextAndTint } var iPhoneBackgroundBlurStyle: UIBlurEffectStyle { return UIBlurEffectStyle.light } var iPhoneBackground: UIColor { return UIColor.theme.browser.background.withAlphaComponent(0.9) } var closeButtonBackground: UIColor { return defaultBackground } } class URLBarColor { var border: UIColor { return UIColor.Photon.Grey90A10 } func activeBorder(_ isPrivate: Bool) -> UIColor { return !isPrivate ? UIColor.Photon.Blue40A30 : UIColor.Defaults.MobilePrivatePurple } var tint: UIColor { return UIColor.Photon.Blue40A30 } // This text selection color is used in two ways: // 1) <UILabel>.background = textSelectionHighlight.withAlphaComponent(textSelectionHighlightAlpha) // To simulate text highlighting when the URL bar is tapped once, this is a background color to create a simulated selected text effect. The color will have an alpha applied when assigning it to the background. // 2) <UITextField>.tintColor = textSelectionHighlight. // When the text is in edit mode (tapping URL bar second time), this is assigned to the to set the selection (and cursor) color. The color is assigned directly to the tintColor. typealias TextSelectionHighlight = (labelMode: UIColor, textFieldMode: UIColor?) func textSelectionHighlight(_ isPrivate: Bool) -> TextSelectionHighlight { if isPrivate { let color = UIColor.Defaults.MobilePrivatePurple return (labelMode: color.withAlphaComponent(0.25), textFieldMode: color) } else { return (labelMode: UIColor.Defaults.iOSTextHighlightBlue, textFieldMode: nil) } } var readerModeButtonSelected: UIColor { return UIColor.Photon.Blue40 } var readerModeButtonUnselected: UIColor { return UIColor.Photon.Grey50 } var pageOptionsSelected: UIColor { return readerModeButtonSelected } var pageOptionsUnselected: UIColor { return UIColor.theme.browser.tint } } class BrowserColor { var background: UIColor { return defaultBackground } var urlBarDivider: UIColor { return UIColor.Photon.Grey90A10 } var tint: UIColor { return defaultTextAndTint } } // The back/forward/refresh/menu button (bottom toolbar) class ToolbarButtonColor { var selectedTint: UIColor { return UIColor.Photon.Blue40 } var disabledTint: UIColor { return UIColor.Photon.Grey30 } } class LoadingBarColor { func start(_ isPrivate: Bool) -> UIColor { return !isPrivate ? UIColor.Photon.Blue40A30 : UIColor.Photon.Magenta60A30 } func end(_ isPrivate: Bool) -> UIColor { return !isPrivate ? UIColor.Photon.Teal60 : UIColor.Photon.Purple60 } } class TabTrayColor { var tabTitleText: UIColor { return UIColor.black } var tabTitleBlur: UIBlurEffectStyle { return UIBlurEffectStyle.extraLight } var background: UIColor { return UIColor.Photon.Grey80 } var cellBackground: UIColor { return defaultBackground } var toolbar: UIColor { return defaultBackground } var toolbarButtonTint: UIColor { return defaultTextAndTint } var privateModeLearnMore: UIColor { return UIColor.Photon.Purple60 } var privateModePurple: UIColor { return UIColor.Photon.Purple60 } var privateModeButtonOffTint: UIColor { return toolbarButtonTint } var privateModeButtonOnTint: UIColor { return UIColor.Photon.Grey10 } var cellCloseButton: UIColor { return UIColor.Photon.Grey50 } var cellTitleBackground: UIColor { return UIColor.clear } var faviconTint: UIColor { return UIColor.Photon.White100 } var searchBackground: UIColor { return UIColor.Photon.Grey30 } } class TopTabsColor { var background: UIColor { return UIColor.Photon.Grey80 } var tabBackgroundSelected: UIColor { return UIColor.Photon.Grey10 } var tabBackgroundUnselected: UIColor { return UIColor.Photon.Grey80 } var tabForegroundSelected: UIColor { return UIColor.Photon.Grey90 } var tabForegroundUnselected: UIColor { return UIColor.Photon.Grey40 } func tabSelectedIndicatorBar(_ isPrivate: Bool) -> UIColor { return !isPrivate ? UIColor.Photon.Blue40 : UIColor.Photon.Purple60 } var buttonTint: UIColor { return UIColor.Photon.Grey40 } var privateModeButtonOffTint: UIColor { return buttonTint } var privateModeButtonOnTint: UIColor { return UIColor.Photon.Grey10 } var closeButtonSelectedTab: UIColor { return tabBackgroundUnselected } var closeButtonUnselectedTab: UIColor { return tabBackgroundSelected } var separator: UIColor { return UIColor.Photon.Grey70 } } class TextFieldColor { var background: UIColor { return UIColor.Photon.Grey90A10 } var backgroundInOverlay : UIColor { return .white } var textAndTint: UIColor { return defaultTextAndTint } var separator: UIColor { return .white } } class HomePanelColor { var toolbarBackground: UIColor { return defaultBackground } var toolbarHighlight: UIColor { return UIColor.Photon.Blue40 } var toolbarTint: UIColor { return UIColor.Photon.Grey50 } var panelBackground: UIColor { return UIColor.Photon.White100 } var separator: UIColor { return defaultSeparator } var border: UIColor { return UIColor.Photon.Grey60 } var buttonContainerBorder: UIColor { return separator } var welcomeScreenText: UIColor { return UIColor.Photon.Grey50 } var bookmarkIconBorder: UIColor { return UIColor.Photon.Grey30 } var bookmarkFolderBackground: UIColor { return UIColor.Photon.Grey10.withAlphaComponent(0.3) } var bookmarkFolderText: UIColor { return UIColor.Photon.Grey80 } var bookmarkCurrentFolderText: UIColor { return UIColor.Photon.Blue40 } var bookmarkBackNavCellBackground: UIColor { return UIColor.clear } var siteTableHeaderBorder: UIColor { return UIColor.Photon.Grey30.withAlphaComponent(0.8) } var topSiteDomain: UIColor { return UIColor.black } var activityStreamHeaderText: UIColor { return UIColor.Photon.Grey50 } var activityStreamCellTitle: UIColor { return UIColor.black } var activityStreamCellDescription: UIColor { return UIColor.Photon.Grey60 } var readingListActive: UIColor { return defaultTextAndTint } var readingListDimmed: UIColor { return UIColor.Photon.Grey40 } var downloadedFileIcon: UIColor { return UIColor.Photon.Grey60 } var historyHeaderIconsBackground: UIColor { return UIColor.Photon.White100 } var searchSuggestionPillBackground: UIColor { return UIColor.Photon.White100 } var searchSuggestionPillForeground: UIColor { return UIColor.Photon.Blue40 } } class SnackBarColor { var highlight: UIColor { return UIColor.Defaults.iOSTextHighlightBlue.withAlphaComponent(0.9) } var highlightText: UIColor { return UIColor.Photon.Blue40 } var border: UIColor { return UIColor.Photon.Grey30 } var title: UIColor { return UIColor.Photon.Blue40 } } class GeneralColor { var faviconBackground: UIColor { return UIColor.clear } var passcodeDot: UIColor { return UIColor.Photon.Grey60 } var highlightBlue: UIColor { return UIColor.Photon.Blue40 } var destructiveRed: UIColor { return UIColor.Photon.Red50 } var separator: UIColor { return defaultSeparator } var settingsTextPlaceholder: UIColor? { return nil } var controlTint: UIColor { return UIColor.Photon.Blue40 } } protocol Theme { var name: String { get } var tableView: TableViewColor { get } var urlbar: URLBarColor { get } var browser: BrowserColor { get } var toolbarButton: ToolbarButtonColor { get } var loadingBar: LoadingBarColor { get } var tabTray: TabTrayColor { get } var topTabs: TopTabsColor { get } var textField: TextFieldColor { get } var homePanel: HomePanelColor { get } var snackbar: SnackBarColor { get } var general: GeneralColor { get } var actionMenu: ActionMenuColor { get } } class NormalTheme: Theme { var name: String { return BuiltinThemeName.normal.rawValue } var tableView: TableViewColor { return TableViewColor() } var urlbar: URLBarColor { return URLBarColor() } var browser: BrowserColor { return BrowserColor() } var toolbarButton: ToolbarButtonColor { return ToolbarButtonColor() } var loadingBar: LoadingBarColor { return LoadingBarColor() } var tabTray: TabTrayColor { return TabTrayColor() } var topTabs: TopTabsColor { return TopTabsColor() } var textField: TextFieldColor { return TextFieldColor() } var homePanel: HomePanelColor { return HomePanelColor() } var snackbar: SnackBarColor { return SnackBarColor() } var general: GeneralColor { return GeneralColor() } var actionMenu: ActionMenuColor { return ActionMenuColor() } }
mpl-2.0
412f30a326f61faba84138c79aea8cfc
44.373913
214
0.745496
4.559196
false
false
false
false
gbuela/kanjiryokucha
KanjiRyokucha/GetStatusRequest.swift
1
799
// // GetStatusRequest.swift // KanjiRyokucha // // Created by German Buela on 12/3/16. // Copyright © 2016 German Buela. All rights reserved. // import Foundation struct GetStatusModel: Decodable { let newCards: Int let expiredCards: Int let failedCards: Int let learnedCards: Int enum CodingKeys: String, CodingKey { case newCards = "new_cards" case expiredCards = "due_cards" case failedCards = "relearn_cards" case learnedCards = "learned_cards" } } struct GetStatusRequest: KoohiiRequest { typealias ModelType = GetStatusModel typealias InputType = NoInput let apiMethod = "srs/info" let useEndpoint = true let sendApiKey = true let method = RequestMethod.get let contentType = ContentType.form }
mit
b3059284a05c887058f417c16316dbcd
23.181818
55
0.679198
4.01005
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Extensions/String+SwiftLint.swift
1
2926
import Foundation import SourceKittenFramework extension String { internal func hasTrailingWhitespace() -> Bool { if isEmpty { return false } if let unicodescalar = unicodeScalars.last { return CharacterSet.whitespaces.contains(unicodescalar) } return false } internal func isUppercase() -> Bool { return self == uppercased() } internal func isLowercase() -> Bool { return self == lowercased() } internal func nameStrippingLeadingUnderscoreIfPrivate(_ dict: [String: SourceKitRepresentable]) -> String { if let aclString = dict.accessibility, let acl = AccessControlLevel(identifier: aclString), acl.isPrivate && first == "_" { return String(self[index(after: startIndex)...]) } return self } private subscript (range: Range<Int>) -> String { let nsrange = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound) if let indexRange = nsrangeToIndexRange(nsrange) { return String(self[indexRange]) } queuedFatalError("invalid range") } internal func substring(from: Int, length: Int? = nil) -> String { if let length = length { return self[from..<from + length] } return String(self[index(startIndex, offsetBy: from, limitedBy: endIndex)!...]) } internal func lastIndex(of search: String) -> Int? { if let range = range(of: search, options: [.literal, .backwards]) { return distance(from: startIndex, to: range.lowerBound) } return nil } internal func nsrangeToIndexRange(_ nsrange: NSRange) -> Range<Index>? { guard nsrange.location != NSNotFound else { return nil } let from16 = utf16.index(utf16.startIndex, offsetBy: nsrange.location, limitedBy: utf16.endIndex) ?? utf16.endIndex let to16 = utf16.index(from16, offsetBy: nsrange.length, limitedBy: utf16.endIndex) ?? utf16.endIndex guard let fromIndex = Index(from16, within: self), let toIndex = Index(to16, within: self) else { return nil } return fromIndex..<toIndex } public func absolutePathStandardized() -> String { return bridge().absolutePathRepresentation().bridge().standardizingPath } internal var isFile: Bool { var isDirectoryObjC: ObjCBool = false if FileManager.default.fileExists(atPath: self, isDirectory: &isDirectoryObjC) { #if os(Linux) && (!swift(>=4.1) || (!swift(>=4.0) && swift(>=3.3))) return !isDirectoryObjC #else return !isDirectoryObjC.boolValue #endif } return false } }
mit
63f7eb1f078315f47de023f9eb674076
31.876404
111
0.585783
4.942568
false
false
false
false
Constantine-Fry/wunderlist.swift
Source/Shared/Endpoints/Tasks.swift
1
2171
// // Tasks.swift // Wunderlist // // Created by Constantine Fry on 05/12/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation /** Represents Tasks endpoint on Wunderilst. https://developer.wunderlist.com/documentation/endpoints/task */ public class Tasks: Endpoint { override var endpoint: String { return "tasks" } public func createTask(listId: Int, title: String, dueDate: NSDate?, completionHandler: (task: Task?, error: NSError?) -> Void) -> SessionTask { var parameters = [ "list_id" : listId, "title" : title ] as [String: AnyObject] if dueDate != nil { parameters["due_date"] = DateFormatter.sharedInstance().stringFromDate(dueDate!) } return taskWithPath(nil, parameters: parameters, HTTPMethod: "POST", transformClosure: { Task(JSON: $0) }) { (result, error) -> Void in completionHandler(task: result as Task?, error: error) } } public func updateTask(taskId: Int, revision: Int, title: String?, dueDate: NSDate?, completionHandler: (task: Task?, error: NSError?) -> Void) -> SessionTask { var parameters = [String: AnyObject]() parameters["revision"] = revision if title != nil { parameters["title"] = title } if dueDate != nil { parameters["due_date"] = DateFormatter.sharedInstance().stringFromDate(dueDate!) } let path = String(taskId) return taskWithPath(path, parameters: parameters, HTTPMethod: "PATCH", transformClosure: { Task(JSON: $0) }) { (result, error) -> Void in completionHandler(task: result as Task?, error: error) } } public func getTaskWithId(taskId: Int, completionHandler: (task: Task?, error: NSError?) -> Void) -> SessionTask { let path = String(taskId) return taskWithPath(path, parameters: nil, HTTPMethod: "GET", transformClosure: { Task(JSON: $0) }) { (result, error) -> Void in completionHandler(task: result as Task?, error: error) } } }
bsd-2-clause
071086a274c8f1932c03c91d1f5b31c1
36.431034
164
0.602487
4.394737
false
false
false
false
lanit-tercom-school/grouplock
GroupLockiOS/GroupLock/Models/File.swift
1
719
// // File.swift // GroupLock // // Created by Sergej Jaskiewicz on 18.07.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // import Foundation struct File: Equatable { var contents: Data? var encrypted: Bool var name: String var type: String static func == (lhs: File, rhs: File) -> Bool { return lhs.name == rhs.name && lhs.type == rhs.type && lhs.encrypted == rhs.encrypted && lhs.contents == rhs.contents } } extension File { init(_ managedFile: ManagedFile) { name = managedFile.name encrypted = managedFile.encrypted type = managedFile.type contents = managedFile.contents } }
apache-2.0
e6ec101fd3c33dd79179f162f8e97ddf
20.117647
62
0.600279
3.923497
false
false
false
false
khizkhiz/swift
test/Interpreter/SDK/libc.swift
5
1408
/* magic */ // Do not edit the line above. // RUN: rm -rf %t && mkdir -p %t // RUN: %target-run-simple-swift %s %t | FileCheck %s // REQUIRES: executable_test // XFAIL: linux import Darwin let sourcePath = Process.arguments[1] let tempPath = Process.arguments[2] + "/libc.txt" // CHECK: Hello world fputs("Hello world", stdout) // CHECK: 4294967295 print("\(UINT32_MAX)") // CHECK: the magic word is ///* magic */// let sourceFile = open(sourcePath, O_RDONLY) assert(sourceFile >= 0) var bytes = UnsafeMutablePointer<CChar>(allocatingCapacity: 12) var readed = read(sourceFile, bytes, 11) close(sourceFile) assert(readed == 11) bytes[11] = CChar(0) print("the magic word is //\(String(cString: bytes))//") // CHECK: O_CREAT|O_EXCL returned errno *17* let errFile = open(sourcePath, O_RDONLY | O_CREAT | O_EXCL) if errFile != -1 { print("O_CREAT|O_EXCL failed to return an error") } else { print("O_CREAT|O_EXCL returned errno *\(errno)*") } // CHECK: created mode *33216* let tempFile = open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR) let written = write(tempFile, bytes, 11) assert(written == 11) close(tempFile) var statbuf = stat() let err = stat(tempPath, &statbuf) if err != 0 { print("stat returned \(err), errno \(errno)") } else { print("created mode *\(statbuf.st_mode)*") assert(statbuf.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR) }
apache-2.0
b927143e8fb726f89bf4578d45924d9b
25.074074
72
0.661932
3.027957
false
false
false
false
marmelroy/FileBrowser
FileBrowser/FBFile.swift
1
3642
// // FBFile.swift // FileBrowser // // Created by Roy Marmelstein on 14/02/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation /// FBFile is a class representing a file in FileBrowser @objc open class FBFile: NSObject { /// Display name. String. @objc open let displayName: String // is Directory. Bool. open let isDirectory: Bool /// File extension. open let fileExtension: String? /// File attributes (including size, creation date etc). open let fileAttributes: NSDictionary? /// NSURL file path. open let filePath: URL // FBFileType open let type: FBFileType open func delete() { do { try FileManager.default.removeItem(at: self.filePath) } catch { print("An error occured when trying to delete file:\(self.filePath) Error:\(error)") } } /** Initialize an FBFile object with a filePath - parameter filePath: NSURL filePath - returns: FBFile object. */ init(filePath: URL) { self.filePath = filePath let isDirectory = checkDirectory(filePath) self.isDirectory = isDirectory if self.isDirectory { self.fileAttributes = nil self.fileExtension = nil self.type = .Directory } else { self.fileAttributes = getFileAttributes(self.filePath) self.fileExtension = filePath.pathExtension if let fileExtension = fileExtension { self.type = FBFileType(rawValue: fileExtension) ?? .Default } else { self.type = .Default } } self.displayName = filePath.lastPathComponent } } /** FBFile type */ public enum FBFileType: String { /// Directory case Directory = "directory" /// GIF file case GIF = "gif" /// JPG file case JPG = "jpg" /// PLIST file case JSON = "json" /// PDF file case PDF = "pdf" /// PLIST file case PLIST = "plist" /// PNG file case PNG = "png" /// ZIP file case ZIP = "zip" /// Any file case Default = "file" /** Get representative image for file type - returns: UIImage for file type */ public func image() -> UIImage? { let bundle = Bundle(for: FileParser.self) var fileName = String() switch self { case .Directory: fileName = "[email protected]" case .JPG, .PNG, .GIF: fileName = "[email protected]" case .PDF: fileName = "[email protected]" case .ZIP: fileName = "[email protected]" default: fileName = "[email protected]" } let file = UIImage(named: fileName, in: bundle, compatibleWith: nil) return file } } /** Check if file path NSURL is directory or file. - parameter filePath: NSURL file path. - returns: isDirectory Bool. */ func checkDirectory(_ filePath: URL) -> Bool { var isDirectory = false do { var resourceValue: AnyObject? try (filePath as NSURL).getResourceValue(&resourceValue, forKey: URLResourceKey.isDirectoryKey) if let number = resourceValue as? NSNumber , number == true { isDirectory = true } } catch { } return isDirectory } func getFileAttributes(_ filePath: URL) -> NSDictionary? { let path = filePath.path let fileManager = FileParser.sharedInstance.fileManager do { let attributes = try fileManager.attributesOfItem(atPath: path) as NSDictionary return attributes } catch {} return nil }
mit
e505ad147807e7cceb42bd36db5a6551
25.194245
103
0.590222
4.556946
false
false
false
false
yoshinorisano/RxSwift
RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaAPI.swift
11
2571
// // WikipediaAPI.swift // Example // // Created by Krunoslav Zaher on 3/25/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif func apiError(error: String) -> NSError { return NSError(domain: "WikipediaAPI", code: -1, userInfo: [NSLocalizedDescriptionKey: error]) } public let WikipediaParseError = apiError("Error during parsing") protocol WikipediaAPI { func getSearchResults(query: String) -> Observable<[WikipediaSearchResult]> func articleContent(searchResult: WikipediaSearchResult) -> Observable<WikipediaPage> } func URLEscape(pathSegment: String) -> String { return pathSegment.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! } class DefaultWikipediaAPI: WikipediaAPI { static let sharedAPI = DefaultWikipediaAPI() // Singleton let $: Dependencies = Dependencies.sharedDependencies private init() {} // Example wikipedia response http://en.wikipedia.org/w/api.php?action=opensearch&search=Rx func getSearchResults(query: String) -> Observable<[WikipediaSearchResult]> { let escapedQuery = URLEscape(query) let urlContent = "http://en.wikipedia.org/w/api.php?action=opensearch&search=\(escapedQuery)" let url = NSURL(string: urlContent)! return $.URLSession.rx_JSON(url) .observeOn($.backgroundWorkScheduler) .map { json in guard let json = json as? [AnyObject] else { throw exampleError("Parsing error") } return try WikipediaSearchResult.parseJSON(json) } .observeOn($.mainScheduler) } // http://en.wikipedia.org/w/api.php?action=parse&page=rx&format=json func articleContent(searchResult: WikipediaSearchResult) -> Observable<WikipediaPage> { let escapedPage = URLEscape(searchResult.title) let url = NSURL(string: "http://en.wikipedia.org/w/api.php?action=parse&page=\(escapedPage)&format=json") if url == nil { return failWith(apiError("Can't create url")) } return $.URLSession.rx_JSON(url!) .map { jsonResult in guard let json = jsonResult as? NSDictionary else { throw exampleError("Parsing error") } return try WikipediaPage.parseJSON(json) } .observeOn($.mainScheduler) } }
mit
13c8f10565d44660e5afa0b81c70124b
33.293333
113
0.640218
4.860113
false
false
false
false
xingerdayu/dayu
dayu/ReplyListViewController.swift
1
5555
// // ReplyListViewController.swift // dayu // // Created by Xinger on 15/9/3. // Copyright (c) 2015年 Xinger. All rights reserved. // import UIKit class ReplyListViewController: BaseUIViewController, UITableViewDelegate, UITableViewDataSource, OnBackListener, ReplyDelegate { var topic:Topic! //这个topic必须传入 var replyList = NSMutableArray() var itemsView:ItemsView2! @IBOutlet weak var myTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.automaticallyAdjustsScrollViewInsets = false myTableView.tableHeaderView = createHeaderView() getReplyList() itemsView = NSBundle.mainBundle().loadNibNamed("ItemsView2", owner: self, options: nil)[0] as! ItemsView2 itemsView.frame = CGRectMake(0, 528 * app.autoSizeScaleY, 320 * app.autoSizeScaleX, 40 * app.autoSizeScaleY) itemsView.backDelegete = self itemsView.replyDelegate = self itemsView.setTopicValue(topic) myAutoLayout(itemsView) self.view.addSubview(itemsView) } func onBack() { self.navigationController?.popViewControllerAnimated(true) } func onReplyFinished(reply:Reply) { self.replyList.addObject(reply) self.myTableView.reloadData() self.myTableView.scrollToNearestSelectedRowAtScrollPosition(UITableViewScrollPosition.Bottom, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return replyList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reply = replyList[indexPath.row] as! Reply let cell = tableView.dequeueReusableCellWithIdentifier("ReplyCell", forIndexPath: indexPath) as UITableViewCell let ivPhoto = cell.viewWithTag(31) as! UIImageView let lbTime = cell.viewWithTag(32) as! UILabel let lbName = cell.viewWithTag(33) as! UILabel cell.viewWithTag(34)?.removeFromSuperview() lbTime.text = reply.timeString lbName.text = reply.username ivPhoto.sd_setImageWithURL(NSURL(string: URLConstants.getUserPhotoUrl(reply.userId)), placeholderImage:UIImage(named: "user_default_photo.png")) ivPhoto.layer.cornerRadius = 20 ivPhoto.clipsToBounds = true var contentLable:UILabel! if reply.receiver != nil { let str = NSString(string:"回复\(reply.receiver!):") let range = NSMakeRange(0, str.length) let attrContent = NSMutableAttributedString(string: reply.content as String) attrContent.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range) attrContent.addAttribute(NSFontAttributeName, value: UIFont(name: "Arial", size: 14.0)!, range: range) contentLable = ViewUtil.createLabelByString(reply.content, x: 20, y: 55, width: 280 * app.autoSizeScaleX, attrContent:attrContent) } else { contentLable = ViewUtil.createLabelByString(reply.content, x: 20, y: 55, width: 280 * app.autoSizeScaleX) } contentLable.textColor = Colors.ReplyContentColor contentLable.tag = 34 cell.addSubview(contentLable) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let reply = replyList[indexPath.row] as! Reply let size = reply.content.textSizeWithFont(UIFont.systemFontOfSize(FONT_SIZE), constrainedToSize: CGSizeMake(app.ScreenWidth - 40, 20000)); return (65 + size.height) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) itemsView.reply_reply = replyList[indexPath.row] as? Reply itemsView.reply() } func createHeaderView() -> UIView { let topicView = NSBundle.mainBundle().loadNibNamed("TopicView", owner: self, options: nil)[0] as! TopicView topicView.shouldShowItems = false topicView.shouldShowCommentLabel = true topicView.setTopic(topic) return topicView } func getReplyList() { let params = ["token":app.getToken(), "topicId":topic.id] self.replyList.removeAllObjects() HttpUtil.post(URLConstants.getReplysUrl, params: params, success: {(response:AnyObject!) in print(response) //if response["stat"] as String == "OK" { self.parseReply(response) //} }, failure: {(error:NSError!) in print(error.localizedDescription) }) } func parseReply(response:AnyObject!) { let array = response["replys"] as! NSArray for item in array { let reply = Reply.parseReply(item as! NSDictionary) self.replyList.addObject(reply) } self.myTableView.reloadData() // if self.shouldScrollToBottom { // self.myTableView.scrollToNearestSelectedRowAtScrollPosition(UITableViewScrollPosition.Bottom, animated: true) // } } }
bsd-3-clause
3ec17ac0753ffa37865757d30f5da745
37.172414
152
0.658898
4.872359
false
false
false
false