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
AgeProducts/WatchRealmSync
Share module/SupportLibs.swift
1
13964
// // SupportLibs.swift // WatchRealmSync // // Created by Takuji Hori on 2017/02/14. // Copyright ยฉ 2017 AgePro. All rights reserved. // import UIKit class Crypto { static func MD5(input:Any) -> String { let className = String(describing: type(of: input)) var data = Data() if className == "Int" { data = String(format: "%x", input as! Int).description.data(using: .utf8)! } else { data = (input as AnyObject).description.data(using: .utf8)! } let length = Int(CC_MD5_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: length) _ = data.withUnsafeBytes { CC_MD5($0, CC_LONG(data.count), &digest) } let cryptDigest = digest.map { String(format: "%02x", $0) }.joined(separator: "") return cryptDigest } } class DateHelper { static func onceUponATime() -> Date { var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! let date1970_01_01_00_00_00_00 = calendar.date(from: DateComponents(year: 1970, month: 01, day: 01, hour: 00, minute: 00, second: 00, nanosecond: 0))! return date1970_01_01_00_00_00_00 } static func farDistantFuture() -> Date { // In iOS, Year2038 problem is not matter! var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! let date2030_01_19_03_14_07_00 = calendar.date(from: DateComponents(year: 2038, month: 01, day: 19, hour: 03, minute: 14, second: 07, nanosecond: 00))! return date2030_01_19_03_14_07_00 } static func makeDateFormatter( _ dateFormatter: inout DateFormatter) { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) dateFormatter.calendar = calendar dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .medium } static func firstDateFromYearMonthDay(_ year:Int, month:Int, day:Int) -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let resuleDate = calendar.date(from: DateComponents(year: year, month: month, day: day, hour: 00, minute: 00, second: 00, nanosecond: 00))! return resuleDate } static func firstDateFromYear(_ year:Int) -> Date { return firstDateFromYearMonthDay(year, month: 01, day: 01) } static func lastDateFromYearMonthDay(_ year:Int, month:Int, day:Int) -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let resuleDate = calendar.date(from: DateComponents(year: year, month: month, day: day, hour: 23, minute: 59, second: 59, nanosecond: 00)) // hour: 23, minute: 59, second: 59, nanosecond: 1_000_000_000 - 1)) return resuleDate! } static func lastDateFromYear(_ year:Int) -> Date { let lastDay = dateCountFromYearMonth(year, month: 12) return lastDateFromYearMonthDay(year, month: 12, day: lastDay) } static func dateCountFromYearMonth(_ year:Int, month:Int) -> Int { var tmpFormatter = DateFormatter() makeDateFormatter(&tmpFormatter) tmpFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"; let tmpDate = tmpFormatter.date(from: String(format: "%4d-%2d-01 00:00:00", year, month)) let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let range = (calendar as NSCalendar?)?.range(of: .day, in: .month, for:tmpDate!) return range!.length } static func firstDateFromDate(_ date:Date) -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) var dateComponents = (calendar as Calendar).dateComponents([.day, .month, .year], from: date) dateComponents.hour = 00 dateComponents.minute = 00 dateComponents.second = 00 return calendar.date(from: dateComponents)! } static func lastDateFromDate(_ date:Date) -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) var dateComponents = (calendar as Calendar).dateComponents([.day, .month, .year], from: date) dateComponents.hour = 23 dateComponents.minute = 59 dateComponents.second = 59 // dateComponents.nanosecond = 1_000_000_000 - 1 return calendar.date(from: dateComponents)! } static func yearMonthDayFromDate(_ date:Date) -> (Int, Int, Int) { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let dateComponents = (calendar as Calendar).dateComponents([.day, .month, .year], from: date) return (dateComponents.year!, dateComponents.month!, dateComponents.day!) } static func getDateBeforeOrAfterSomeDay(baseDate:Date, day:Double) -> Date { var resultDate:Date if day > 0 { resultDate = Date(timeInterval: (60*60*24)*day, since: baseDate as Date) } else { resultDate = Date(timeInterval: -(60*60*24)*fabs(day), since: baseDate as Date) } return resultDate } static func getDateBeforeOrAfterSomeWeek(baseDate:Date, week:Double) -> Date { return getDateBeforeOrAfterSomeDay(baseDate: baseDate, day: week*7) } static func getDateBeforeOrAfterSomeMonth(baseDate:Date, month:Double) -> Date { return getDateBeforeOrAfterSomeDay(baseDate: baseDate, day: month*31) } } public class FileHelper { // tmp/ static func temporaryDirectory() -> String { return NSTemporaryDirectory() } // tmp/fileName static func temporaryDirectoryWithFileName(fileName: String) -> String { return temporaryDirectory().stringByAppendingPathComponent(path: fileName) } // Documents/ static func documentDirectory() -> String { return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! } // Documents/fileName static func documentDirectoryWithFileName(fileName: String) -> String { return documentDirectory().stringByAppendingPathComponent(path: fileName) } static func fileExists(path: String) -> Bool { return FileManager.default.fileExists(atPath: path) } static func removeFilePath(path: String) -> Bool { do { try FileManager.default.removeItem(atPath: path) return true } catch let error as NSError { NSLog ("File remove error: \(error.localizedDescription) \(path)") return false } } static func fileSizePath(path: String) -> Int { do { let attributes = try FileManager.default.attributesOfItem(atPath: path) as NSDictionary return Int(attributes.fileSize()) } catch let error as NSError { NSLog ("File size error: \(error.localizedDescription) \(path)") return 0 } } static func readFileWithData(path: String) -> Data! { if fileExists(path: path) == false { return nil } guard let fileHandle = FileHandle(forReadingAtPath: path) else { return nil } let data = fileHandle.readDataToEndOfFile() fileHandle.closeFile() return data } static func readFileWithImage(path: String) -> UIImage! { guard let data = readFileWithData(path: path) else { print("File read error") return nil } guard let imageData = UIImage.init(data: data, scale: 1.0) else { print("UIImage convert error") return nil } return imageData } static func writeFileWithData(path: String, data: Data) -> Bool { if FileManager.default.createFile(atPath: path, contents: data, attributes: nil) == true { // print ("File successful creation: \(path)") return true } else { print ("File already exist: \(path)") return false } } static func directorContents(atPath: String) -> [String] { var contents: [String] = [] var isDir: ObjCBool = true if FileManager.default.fileExists(atPath: atPath, isDirectory: &isDir) { do { contents = try FileManager.default.contentsOfDirectory(atPath: atPath) } catch let error as NSError { print(error.localizedDescription) } } return contents } static func isElapsedFileModificationDate(path: String, elapsedTime: TimeInterval) throws -> Bool { if !fileExists(path: path) { return false } let attributes = try FileManager.default.attributesOfItem(atPath: path) as NSDictionary guard let date = attributes.fileModificationDate() else { return false } return elapsedTime < NSDate().timeIntervalSince(date) } } class RandomMaker { static func randomFloat(Min _Min : Float, Max _Max : Float)->Float { return (Float(arc4random_uniform(UINT32_MAX)) / Float(UINT32_MAX) ) * (_Max - _Min) + _Min } static func randomDouble(Min _Min : Double, Max _Max : Double)->Double { return (Double(arc4random_uniform(UINT32_MAX)) / Double(UINT32_MAX) ) * (_Max - _Min) + _Min } static func randomNumIntegerWithLimits(lower:Int, upper:Int) -> Int { if upper < lower { return -1 } return Int(arc4random_uniform(UInt32(upper) - UInt32(lower)) + UInt32(lower)) } static func randomStringWithLength(_ len:Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var result:String = "" if len <= 0 { NSLog ("randomStringWithLength: error length 0 error"); return "" } for _ in 0..<len { let startindex = letters.characters.index(letters.startIndex, offsetBy: Int(arc4random_uniform(UInt32(letters.characters.count)))) let endindex = letters.index(startindex, offsetBy: 1) result += letters.substring(with: startindex..<endindex) } return result } static func randomNihonngoStringWithLength(_ len:Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789้›จใซใ‚‚ใพใ‘ใš้ขจใซใ‚‚ใพใ‘ใš้›ชใซใ‚‚ๅคใฎๆš‘ใ•ใซใ‚‚ใพใ‘ใฌไธˆๅคซใชใ‹ใ‚‰ใ ใ‚’ใ‚‚ใกๆฌฒใฏใชใๆฑบใ—ใฆๆ€’ใ‚‰ใšใ„ใคใ‚‚ใ—ใšใ‹ใซใ‚ใ‚‰ใฃใฆใ„ใ‚‹ไธ€ๆ—ฅใซ็Ž„็ฑณๅ››ๅˆใจๅ‘ณๅ™Œใจๅฐ‘ใ—ใฎ้‡Ž่œใ‚’ใŸในใ‚ใ‚‰ใ‚†ใ‚‹ใ“ใจใ‚’ใ˜ใถใ‚“ใ‚’ใ‹ใ‚“ใ˜ใ‚‡ใ†ใซๅ…ฅใ‚Œใšใซใ‚ˆใใฟใใใ—ใ‚ใ‹ใ‚Šใใ—ใฆใ‚ใ™ใ‚Œใš้‡ŽๅŽŸใฎๆพใฎๆž—ใฎ่”ญใฎๅฐใ•ใช่“ใถใใฎๅฐๅฑ‹ใซใ„ใฆๆฑใซ็—…ๆฐ—ใฎใ“ใฉใ‚‚ใ‚ใ‚Œใฐ่กŒใฃใฆ็œ‹็—…ใ—ใฆใ‚„ใ‚Š่ฅฟใซใคใ‹ใ‚ŒใŸๆฏใ‚ใ‚Œใฐ่กŒใฃใฆใใฎ็จฒใฎๆŸใ‚’่ฒ ใ„ๅ—ใซๆญปใซใใ†ใชไบบใ‚ใ‚Œใฐ่กŒใฃใฆใ“ใ‚ใŒใ‚‰ใชใใฆใ‚‚ใ„ใ„ใจใ„ใ„ๅŒ—ใซใ‘ใ‚“ใ‹ใ‚„ใใ—ใ‚‡ใ†ใŒใ‚ใ‚Œใฐใคใพใ‚‰ใชใ„ใ‹ใ‚‰ใ‚„ใ‚ใ‚ใจใ„ใ„ใฒใงใ‚Šใฎใจใใฏใชใฟใ ใ‚’ใชใŒใ—ใ•ใ‚€ใ•ใฎใชใคใฏใ‚ชใƒญใ‚ชใƒญใ‚ใ‚‹ใใฟใ‚“ใชใซใƒ‡ใ‚ฏใƒŽใƒœใƒผใจใ‚ˆใฐใ‚Œใปใ‚ใ‚‰ใ‚Œใ‚‚ใ›ใšใใซใ‚‚ใ•ใ‚Œใšใใ†ใ„ใ†ใ‚‚ใฎใซใ‚ใŸใ—ใฏใชใ‚ŠใŸใ„" var result:String = "" if len <= 0 { NSLog ("randomStringWithLength: error length 0 error"); return "" } for _ in 0..<len { let startindex = letters.characters.index(letters.startIndex, offsetBy: Int(arc4random_uniform(UInt32(letters.characters.count)))) let endindex = letters.index(startindex, offsetBy: 1) result += letters.substring(with: startindex..<endindex) } return result } static func randomDate3(_ firstDate:Date?, lastDate:Date?) -> Date? { let interval = (lastDate?.timeIntervalSince(firstDate!))! return firstDate?.addingTimeInterval(randomDouble(Min : 0, Max : interval)) } static func randomBool(percent:Double) -> Bool { let result = randomDouble(Min : 0, Max : 100.0) if result < percent { return true } else { return false } } } extension String { func stringByAppendingPathComponent(path: String) -> String { let nsSt = self as NSString return nsSt.appendingPathComponent(path) } } extension UIColor { class func rgbColor(_ rgbValue: UInt) -> UIColor{ return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat( rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } let yearformatter: DateFormatter = { let f = DateFormatter() f.dateFormat = "yy/M/dd HH:mm" // f.dateFormat = "yy/MM/dd" // f.dateStyle = .none // f.timeStyle = .short return f }() let dateformatter: DateFormatter = { let f = DateFormatter() f.dateFormat = "M/dd HH:mm:ss" // f.dateFormat = "yy/MM/dd" // f.dateStyle = .none // f.timeStyle = .short return f }() let timeformatter: DateFormatter = { let f = DateFormatter() f.dateFormat = "M/dd HH:mm:ss" // f.dateFormat = "HH:mm:ss" // f.dateStyle = .none // f.timeStyle = .short return f }() func dispatch_async_main(_ block: @escaping () -> ()) { DispatchQueue.main.async(execute: block) } func dispatch_async_global(_ block: @escaping () -> ()) { DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: block) }
mit
06383d58e50d3daf8d7a31d690a248a5
36.239554
383
0.615828
4.079646
false
false
false
false
Jakobeha/lAzR4t
lAzR4t iOS/GameViewController.swift
1
1138
// // GameViewController.swift // lAzR4t iOS // // Created by Jakob Hain on 9/29/17. // Copyright ยฉ 2017 Jakob Hain. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let controller = GameController() // Present the scene let skView = self.view as! SKView skView.presentScene(controller.scene) skView.ignoresSiblingOrder = true skView.showsFPS = true skView.showsNodeCount = true } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
mit
a8127c6984518a7894937a3488003400
22.204082
77
0.636763
5.288372
false
false
false
false
n8iveapps/N8iveKit
InterfaceKit/InterfaceKit/source/viewControllers/NKNavigationController.swift
1
4003
// // NKNavigationController.swift // N8iveKit // // Created by Muhammad Bassio on 6/15/17. // Copyright ยฉ 2017 N8ive Apps. All rights reserved. // import UIKit open class NKNavigationController: UINavigationController { open var adaptableNavigationBar = NKNavigationBar(frame: CGRect.zero) @IBInspectable open var canSloppySwipe:Bool = false { didSet { self.interactiveTransition.isSloppy = self.canSloppySwipe } } let interactiveTransition = NKNavigationInteractiveTransition() open override func viewDidLoad() { super.viewDidLoad() self.initNavigationBar() } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } open func initNavigationBar() { self.isNavigationBarHidden = true self.delegate = self self.view.addSubview(self.adaptableNavigationBar) } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let topViewController = self.viewControllers.last as? NKViewController { if let containerView = self.adaptableNavigationBar.superview { self.adaptableNavigationBar.frame = CGRect(x: 0, y: 0, width: containerView.bounds.width, height: topViewController.navigationBarCurrentHeight) } } } open override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) { super.setViewControllers(viewControllers, animated: animated) self.adaptableNavigationBar.navigationViews.forEach { $0.removeFromSuperview() } self.adaptableNavigationBar.navigationViews = [] for viewController in self.viewControllers { if let nkViewController = viewController as? NKViewController { self.adaptableNavigationBar.navigationViews.append(nkViewController.navigationView) self.adaptableNavigationBar.addSubview(nkViewController.navigationView) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension NKNavigationController: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { interactiveTransition.reverse = operation == .pop return interactiveTransition } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition.transitionInProgress ? interactiveTransition : nil } public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { self.viewWillLayoutSubviews() if viewController != viewControllers.first { // Exclude root viewController interactiveTransition.attachToViewController(viewController: viewController) } } public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { self.adaptableNavigationBar.navigationViews.forEach { $0.removeFromSuperview() } self.adaptableNavigationBar.navigationViews = [] for viewController in self.viewControllers { if let nkViewController = viewController as? NKViewController { self.adaptableNavigationBar.navigationViews.append(nkViewController.navigationView) self.adaptableNavigationBar.addSubview(nkViewController.navigationView) } } self.viewWillLayoutSubviews() } }
mit
81c0d49b530fcca71280af80992c4bc1
37.854369
251
0.767866
5.628692
false
false
false
false
happyeverydayzhh/WWDC
WWDC/AppDelegate.swift
2
4044
// // AppDelegate.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Crashlytics import Updater @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow? private var downloadListWindowController: DownloadListWindowController? private var preferencesWindowController: PreferencesWindowController? func applicationOpenUntitledFile(sender: NSApplication) -> Bool { window?.makeKeyAndOrderFront(nil) return false } func applicationDidFinishLaunching(aNotification: NSNotification) { // start checking for live event LiveEventObserver.SharedObserver().start() // check for updates checkForUpdates(nil) // Keep a reference to the main application window window = NSApplication.sharedApplication().windows.last // continue any paused downloads VideoStore.SharedStore().initialize() // initialize Crashlytics GRCrashlyticsHelper.install() // tell the user he can watch the live keynote using the app, only once if !Preferences.SharedPreferences().userKnowsLiveEventThing { tellUserAboutTheLiveEventThing() } } func applicationWillFinishLaunching(notification: NSNotification) { // register custom URL scheme handler URLSchemeHandler.SharedHandler().register() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func checkForUpdates(sender: AnyObject?) { UDUpdater.sharedUpdater().updateAutomatically = true UDUpdater.sharedUpdater().checkForUpdatesWithCompletionHandler { newRelease in if newRelease != nil { if sender != nil { let alert = NSAlert() alert.messageText = "New version available" alert.informativeText = "Version \(newRelease.version) is now available. It will be installed automatically the next time you launch the app." alert.addButtonWithTitle("Ok") alert.runModal() } else { let notification = NSUserNotification() notification.title = "New version available" notification.informativeText = "A new version is available, relaunch the app to update" NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) } } else { if sender != nil { let alert = NSAlert() alert.messageText = "You're up to date!" alert.informativeText = "You have the newest version" alert.addButtonWithTitle("Ok") alert.runModal() } } } } @IBAction func showDownloadsWindow(sender: AnyObject?) { if downloadListWindowController == nil { downloadListWindowController = DownloadListWindowController() } downloadListWindowController?.showWindow(self) } @IBAction func showPreferencesWindow(sender: AnyObject?) { if preferencesWindowController == nil { preferencesWindowController = PreferencesWindowController() } preferencesWindowController?.showWindow(self) } private func tellUserAboutTheLiveEventThing() { let alert = NSAlert() alert.messageText = "Did you know?" alert.informativeText = "You can watch live WWDC events using this app! Just open the app while the event is live and It will start playing automatically." alert.addButtonWithTitle("Got It!") alert.runModal() Preferences.SharedPreferences().userKnowsLiveEventThing = true } }
bsd-2-clause
a64aa0d2ac0fef9e4d37caefd90e98aa
35.107143
163
0.630564
6.090361
false
false
false
false
TongjiUAppleClub/WeCitizens
WeCitizens/MapViewController.swift
1
1615
// // MapViewController.swift // WeCitizens // // Created by Harold LIU on 4/6/16. // Copyright ยฉ 2016 Tongji Apple Club. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController,MKMapViewDelegate{ @IBOutlet weak var MapView: MKMapView! var voiceList = [Voice]() override func viewDidLoad() { super.viewDidLoad() self.title = "ๅœฐๅ›พ" MapView.delegate = self MapView.showsUserLocation = true if self.voiceList.count > 0 { MapView.centerCoordinate = CLLocationCoordinate2D(latitude: voiceList[0].latitude, longitude: voiceList[0].longitude) } MapView.userTrackingMode = MKUserTrackingMode.Follow drawPins() cameraSetUp() print("voice size:\(self.voiceList.count)") } func drawPins() { voiceList.forEach { voice in let drapPin = MKPointAnnotation() drapPin.coordinate = CLLocationCoordinate2DMake(voice.latitude, voice.longitude) drapPin.title = voice.title MapView.addAnnotation(drapPin) } } private func cameraSetUp() { MapView.camera.altitude = 1400 MapView.camera.pitch = 50 MapView.camera.heading = 180 } @IBAction func ChangeMapType(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 1: MapView.mapType = .HybridFlyover cameraSetUp() default: MapView.mapType = .Standard cameraSetUp() } } }
mit
a74418d437ad2778aa1bcc708ae2cf73
25.833333
129
0.606832
4.749263
false
false
false
false
clwm01/RTKit
RTKit/RTAudio.swift
1
9148
// // RTAudio.swift // RTKit // // Created by Rex Tsao on 10/4/2016. // Copyright ยฉ 2016 rexcao.net. All rights reserved. // import Foundation import UIKit import AVFoundation public class RTAudio: NSObject { public var remoteSoundUrl: String? { willSet { self.soundData = nil } } public var soundFile: String? private var audioSession: AVAudioSession? private lazy var errorPoint: NSErrorPointer? = nil private var recorder: AVAudioRecorder? private var player: AVAudioPlayer? /// current audio playing route. private lazy var currentRouteSpeaker = false public var soundData: NSData? public var completionHandler: (() -> Void)? private var timeStartRecord: Int? private var timeStopRecord: Int? /// Total duration of voice you recorded. public var recordedDuration: Int? { get { return self.timeStopRecord! - self.timeStartRecord! } } public override init() { super.init() if self.audioSession == nil { self.audioSession = AVAudioSession.sharedInstance() } } public func startRecording(soundFileName: String) { print("recording started...") let path = RTFile.appDirectory(.DocumentDirectory, domainMask: .UserDomainMask) self.soundFile = path + "/" + soundFileName print("will save sound data to \(self.soundFile)") let recordSetting: [String: AnyObject] = [ AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue, AVEncoderBitRateKey: 16, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0 ] do { try self.audioSession?.setCategory(AVAudioSessionCategoryPlayAndRecord) } catch let error as NSError { self.errorPoint?.memory = error } do { try self.audioSession?.setActive(true) } catch let error as NSError { self.errorPoint?.memory = error } do { self.recorder = try AVAudioRecorder(URL: NSURL(fileURLWithPath: self.soundFile!), settings: recordSetting) } catch let error as NSError { self.errorPoint?.memory = error self.recorder = nil } self.recorder?.prepareToRecord() self.recorder?.delegate = self self.recorder?.record() self.timeStartRecord = RTTime.time() } public func stopRecording() { self.recorder?.stop() self.timeStopRecord = RTTime.time() } /// Attempt to play remote sound. /// /// - parameter loadingHandler: Processing before remote sound loaded. /// - parameter completionHandler: Processing after sound playing finished. public func playRemote(loadingHandler: (() -> Void)?) { // Important: Not all the devices support proximityMonitoring.!! // Enable proximity monitoring. UIDevice.currentDevice().proximityMonitoringEnabled = true // If currentDevice support proximityMonitoring, add observer. if UIDevice.currentDevice().proximityMonitoringEnabled == true { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sensorStateChanged(_:)), name: "UIDeviceProximityStateDidChangeNotification", object: nil) } let loadedHandler = { self.playWithSpeakers() } self.currentRouteSpeaker = true self.loadSound(loadingHandler, loadedHandler: loadedHandler) } /// Attempt to play local sound. /// /// - parameter soundPath: Path of sound file in bundle. public func playLocal(soundPath: String) { print("preparing to play: \(soundPath)") // reset player to preparing for next sound. self.player = nil // Important: Not all the devices support proximityMonitoring.!! // Enable proximity monitoring. UIDevice.currentDevice().proximityMonitoringEnabled = true // If currentDevice support proximityMonitoring, add observer. if UIDevice.currentDevice().proximityMonitoringEnabled == true { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sensorStateChanged(_:)), name: "UIDeviceProximityStateDidChangeNotification", object: nil) } let fileManager = NSFileManager.defaultManager() // check if file exists if(!fileManager.fileExistsAtPath(soundPath)) { print("voice file does not exist") } else { self.soundData = NSData(contentsOfFile: soundPath) self.playWithSpeakers() self.currentRouteSpeaker = true } } private func loadSound(loadingHandler: (() -> Void)?, loadedHandler: (() -> Void)?) { if self.soundData == nil { let qos = Int(QOS_CLASS_USER_INITIATED.rawValue) dispatch_async(dispatch_get_global_queue(qos, 0), { loadingHandler?() let soundData = NSData(contentsOfURL: NSURL(string: self.remoteSoundUrl!)!) dispatch_async(dispatch_get_main_queue(), { self.soundData = soundData loadedHandler?() }) }) } else { loadedHandler?() } } private func playWithHeadphone() { do { try self.audioSession?.setCategory(AVAudioSessionCategoryPlayAndRecord) } catch let error as NSError { self.errorPoint?.memory = error } do { try self.audioSession?.overrideOutputAudioPort(AVAudioSessionPortOverride.None) } catch let error as NSError { self.errorPoint?.memory = error } if self.player == nil { do { self.player = try AVAudioPlayer(data: self.soundData!) } catch let error as NSError { self.errorPoint?.memory = error self.player = nil } self.player?.delegate = self } self.player?.prepareToPlay() self.player?.play() } private func playWithSpeakers() { do { try self.audioSession?.setCategory(AVAudioSessionCategoryPlayback) } catch let error as NSError { self.errorPoint?.memory = error } do { try self.audioSession?.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker) } catch let error as NSError { self.errorPoint?.memory = error } if self.player == nil { do { self.player = try AVAudioPlayer(data: self.soundData!) } catch let error as NSError { self.errorPoint?.memory = error self.player = nil } self.player?.delegate = self } self.player?.prepareToPlay() self.player?.play() } // Process observation. public func sensorStateChanged(notification: NSNotificationCenter) { // device is close to user if UIDevice.currentDevice().proximityState == true { do { try self.audioSession?.setCategory(AVAudioSessionCategoryPlayAndRecord) } catch let error as NSError { self.errorPoint?.memory = error } do { try self.audioSession?.overrideOutputAudioPort(AVAudioSessionPortOverride.None) } catch let error as NSError { self.errorPoint?.memory = error } self.currentRouteSpeaker = false } else { do { try self.audioSession?.setCategory(AVAudioSessionCategoryPlayback) } catch let error as NSError { self.errorPoint?.memory = error } do { try self.audioSession?.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker) } catch let error as NSError { self.errorPoint?.memory = error } self.currentRouteSpeaker = true } } /// Clear cached data public func clear() { self.soundFile = nil self.soundData = nil } /// Only vibrate the phone when it has been silenced. public class func playVibrate() { AudioServicesPlaySystemSound(UInt32(kSystemSoundID_Vibrate)) } public class func playSystemSound(id: UInt32 = 1007) { AudioServicesPlaySystemSound(id) } } extension RTAudio: AVAudioPlayerDelegate { public func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { // Close proximityMonitoring when playing finished. UIDevice.currentDevice().proximityMonitoringEnabled = false self.completionHandler?() } } extension RTAudio: AVAudioRecorderDelegate { public func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) { self.completionHandler?() } }
apache-2.0
2bc65f3cf0f8951498582b45e07ff2e1
33.916031
182
0.601509
5.314933
false
false
false
false
vector-im/vector-ios
Riot/Modules/KeyVerification/Common/ScanConfirmation/KeyVerificationScanConfirmationViewController.swift
1
8632
// File created from ScreenTemplate // $ createScreen.sh KeyVerification/Common/ScanConfirmation KeyVerificationScanConfirmation /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class KeyVerificationScanConfirmationViewController: UIViewController { // MARK: - Constants // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var waitingLabel: UILabel! @IBOutlet private weak var scannedContentView: UIView! @IBOutlet private weak var scannedInformationLabel: UILabel! @IBOutlet private weak var rejectButton: RoundedButton! @IBOutlet private weak var confirmButton: RoundedButton! // MARK: Private private var viewModel: KeyVerificationScanConfirmationViewModelType! private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! // MARK: - Setup class func instantiate(with viewModel: KeyVerificationScanConfirmationViewModelType) -> KeyVerificationScanConfirmationViewController { let viewController = StoryboardScene.KeyVerificationScanConfirmationViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide back button self.navigationItem.setHidesBackButton(true, animated: animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.waitingLabel.textColor = theme.textSecondaryColor self.scannedInformationLabel.textColor = theme.textPrimaryColor self.confirmButton.update(theme: theme) self.rejectButton.update(theme: theme) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.confirmButton.layer.masksToBounds = true self.rejectButton.layer.masksToBounds = true self.confirmButton.setTitle(VectorL10n.yes, for: .normal) self.rejectButton.setTitle(VectorL10n.no, for: .normal) self.rejectButton.actionStyle = .cancel } private func render(viewState: KeyVerificationScanConfirmationViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(let viewData): self.renderLoaded(viewData: viewData) case .error(let error): self.render(error: error) case .cancelled(let reason): self.renderCancelled(reason: reason) case .cancelledByMe(let reason): self.renderCancelledByMe(reason: reason) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(viewData: KeyVerificationScanConfirmationViewData) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.waitingLabel.isHidden = !viewData.isScanning self.scannedContentView.isHidden = viewData.isScanning var title: String var waitingInfo: String? var scannedInfo: String? if viewData.isScanning { title = VectorL10n.keyVerificationScanConfirmationScanningTitle switch viewData.verificationKind { case .otherSession, .thisSession, .newSession: waitingInfo = VectorL10n.keyVerificationScanConfirmationScanningDeviceWaitingOther case .user: waitingInfo = VectorL10n.keyVerificationScanConfirmationScanningUserWaitingOther(viewData.otherDisplayName) } } else { title = VectorL10n.keyVerificationScanConfirmationScannedTitle switch viewData.verificationKind { case .otherSession, .thisSession, .newSession: scannedInfo = VectorL10n.keyVerificationScanConfirmationScannedDeviceInformation case .user: scannedInfo = VectorL10n.keyVerificationScanConfirmationScannedUserInformation(viewData.otherDisplayName) } } self.title = viewData.verificationKind.verificationTitle self.titleLabel.text = title self.waitingLabel.text = waitingInfo self.scannedInformationLabel.text = scannedInfo } private func renderCancelled(reason: MXTransactionCancelCode) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, title: "", message: VectorL10n.deviceVerificationCancelled, animated: true) { self.viewModel.process(viewAction: .cancel) } } private func renderCancelledByMe(reason: MXTransactionCancelCode) { if reason.value != MXTransactionCancelCode.user().value { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, title: "", message: VectorL10n.deviceVerificationCancelledByMe(reason.humanReadable), animated: true) { self.viewModel.process(viewAction: .cancel) } } else { self.activityPresenter.removeCurrentActivityIndicator(animated: true) } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } // MARK: - Actions @IBAction private func rejectButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .acknowledgeOtherScannedMyCode(false)) } @IBAction private func confirmButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .acknowledgeOtherScannedMyCode(true)) } private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - KeyVerificationScanConfirmationViewModelViewDelegate extension KeyVerificationScanConfirmationViewController: KeyVerificationScanConfirmationViewModelViewDelegate { func keyVerificationScanConfirmationViewModel(_ viewModel: KeyVerificationScanConfirmationViewModelType, didUpdateViewState viewSate: KeyVerificationScanConfirmationViewState) { self.render(viewState: viewSate) } }
apache-2.0
be89d01ad0d474beb7162bfc691eef0b
36.530435
181
0.695783
5.789403
false
false
false
false
vector-im/vector-ios
Riot/Modules/Settings/Security/SecureBackup/SettingsSecureBackupViewModel.swift
1
6191
/* Copyright 2021 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class SettingsSecureBackupViewModel: SettingsSecureBackupViewModelType { // MARK: - Properties weak var viewDelegate: SettingsSecureBackupViewModelViewDelegate? // MARK: Private private let recoveryService: MXRecoveryService private let keyBackup: MXKeyBackup init(recoveryService: MXRecoveryService, keyBackup: MXKeyBackup) { self.recoveryService = recoveryService self.keyBackup = keyBackup self.registerKeyBackupVersionDidChangeStateNotification() } private func registerKeyBackupVersionDidChangeStateNotification() { NotificationCenter.default.addObserver(self, selector: #selector(keyBackupDidStateChange), name: NSNotification.Name.mxKeyBackupDidStateChange, object: self.keyBackup) } @objc private func keyBackupDidStateChange() { self.checkKeyBackupState() } func process(viewAction: SettingsSecureBackupViewAction) { guard let viewDelegate = self.viewDelegate else { return } switch viewAction { case .load: viewDelegate.settingsSecureBackupViewModel(self, didUpdateViewState: .loading) self.checkKeyBackupState() case .resetSecureBackup, .createSecureBackup: // The implement supports both viewDelegate.settingsSecureBackupViewModelShowSecureBackupReset(self) case .createKeyBackup: viewDelegate.settingsSecureBackupViewModelShowKeyBackupCreate(self) case .restoreFromKeyBackup(let keyBackupVersion): viewDelegate.settingsSecureBackupViewModel(self, showKeyBackupRecover: keyBackupVersion) case .confirmDeleteKeyBackup(let keyBackupVersion): viewDelegate.settingsSecureBackupViewModel(self, showKeyBackupDeleteConfirm: keyBackupVersion) case .deleteKeyBackup(let keyBackupVersion): self.deleteKeyBackupVersion(keyBackupVersion) } } // MARK: - Private private func checkKeyBackupState() { // Check homeserver update in background self.keyBackup.forceRefresh(nil, failure: nil) if let keyBackupVersion = self.keyBackup.keyBackupVersion { self.keyBackup.trust(for: keyBackupVersion, onComplete: { [weak self] (keyBackupVersionTrust) in guard let sself = self else { return } sself.computeState(withBackupVersionTrust: keyBackupVersionTrust) }) } else { computeState() } } private func computeState(withBackupVersionTrust keyBackupVersionTrust: MXKeyBackupVersionTrust? = nil) { var viewState: SettingsSecureBackupViewState? var keyBackupState: SettingsSecureBackupViewState.KeyBackupState? switch self.keyBackup.state { case MXKeyBackupStateUnknown, MXKeyBackupStateCheckingBackUpOnHomeserver: viewState = .loading case MXKeyBackupStateDisabled, MXKeyBackupStateEnabling: keyBackupState = .noKeyBackup case MXKeyBackupStateNotTrusted: guard let keyBackupVersion = self.keyBackup.keyBackupVersion, let keyBackupVersionTrust = keyBackupVersionTrust else { return } keyBackupState = .keyBackupNotTrusted(keyBackupVersion, keyBackupVersionTrust) case MXKeyBackupStateReadyToBackUp, MXKeyBackupStateWillBackUp, MXKeyBackupStateBackingUp: guard let keyBackupVersion = self.keyBackup.keyBackupVersion, let keyBackupVersionTrust = keyBackupVersionTrust else { return } // Get the backup progress before updating the state self.keyBackup.backupProgress { [weak self] (progress) in guard let self = self else { return } let keyBackupState: SettingsSecureBackupViewState.KeyBackupState = .keyBackup(keyBackupVersion, keyBackupVersionTrust, progress) let viewState: SettingsSecureBackupViewState = self.recoveryService.hasRecovery() ? .secureBackup(keyBackupState) : .noSecureBackup(keyBackupState) self.viewDelegate?.settingsSecureBackupViewModel(self, didUpdateViewState: viewState) } default: break } // Turn secure backup and key back states into view state if let keyBackupState = keyBackupState { viewState = recoveryService.hasRecovery() ? .secureBackup(keyBackupState) : .noSecureBackup(keyBackupState) } if let viewState = viewState { self.viewDelegate?.settingsSecureBackupViewModel(self, didUpdateViewState: viewState) } } private func deleteKeyBackupVersion(_ keyBackupVersion: MXKeyBackupVersion) { guard let keyBackupVersionVersion = keyBackupVersion.version else { return } self.viewDelegate?.settingsSecureBackupViewModel(self, didUpdateNetworkRequestViewState: .loading) self.keyBackup.deleteVersion(keyBackupVersionVersion, success: { [weak self] () in guard let sself = self else { return } sself.viewDelegate?.settingsSecureBackupViewModel(sself, didUpdateNetworkRequestViewState: .loaded) }, failure: { [weak self] error in guard let sself = self else { return } sself.viewDelegate?.settingsSecureBackupViewModel(sself, didUpdateNetworkRequestViewState: .error(error)) }) } }
apache-2.0
dc032ab051688cbb26c0f2bbf02a80f2
39.201299
175
0.685996
5.592593
false
false
false
false
mlgoogle/viossvc
viossvc/AppAPI/SocketAPI/SocketReqeust/SocketRequestManage.swift
1
5884
// // SocketPacketManage.swift // viossvc // // Created by yaowang on 2016/11/22. // Copyright ยฉ 2016ๅนด ywwlcom.yundian. All rights reserved. // import UIKit import XCGLogger class SocketRequestManage: NSObject { static let shared = SocketRequestManage(); private var socketRequests = [UInt32: SocketRequest]() private var _timer: NSTimer? private var _lastHeardBeatTime:NSTimeInterval! private var _lastConnectedTime:NSTimeInterval! private var _reqeustId:UInt32 = 10000 private var _socketHelper:APISocketHelper? private var _sessionId:UInt64 = 0 var receiveChatMsgBlock:CompleteBlock? func start() { _lastHeardBeatTime = timeNow() _lastConnectedTime = timeNow() stop() _timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(didActionTimer), userInfo: nil, repeats: true) _socketHelper = APISocketHelper() _socketHelper?.connect() } func stop() { _timer?.invalidate() _timer = nil objc_sync_enter(self) _socketHelper?.disconnect() _socketHelper = nil objc_sync_exit(self) } var reqeustId:UInt32 { get { objc_sync_enter(self) if _reqeustId > 2000000000 { _reqeustId = 10000 } _reqeustId += 1 objc_sync_exit(self) return _reqeustId; } } func notifyResponsePacket(packet: SocketDataPacket) { if packet.operate_code == SocketConst.OPCode.ChatReceiveMessage.rawValue { let response:SocketJsonResponse = SocketJsonResponse(packet:packet) dispatch_async(dispatch_get_main_queue(), {[weak self] in self?.receiveChatMsgBlock?(response) }) } else { objc_sync_enter(self) _sessionId = packet.session_id let socketReqeust = socketRequests[packet.request_id] socketRequests.removeValueForKey(packet.request_id) objc_sync_exit(self) let response:SocketJsonResponse = SocketJsonResponse(packet:packet) if (packet.type == SocketConst.type.Error.rawValue) { let dict:NSDictionary? = response.responseJson() var errorCode: Int? = dict?["error_"] as? Int if errorCode == nil { errorCode = -1; } socketReqeust?.onError(errorCode) } else { socketReqeust?.onComplete(response) } } } func checkReqeustTimeout() { objc_sync_enter(self) for (key,reqeust) in socketRequests { if reqeust.isReqeustTimeout() { socketRequests.removeValueForKey(key) // reqeust.onError(-11011) break } } objc_sync_exit(self) } private func sendRequest(packet: SocketDataPacket) { let block:dispatch_block_t = { [weak self] in if packet.operate_code != SocketConst.OPCode.Login.rawValue && (self?._socketHelper?.disconnected)! { self?._socketHelper?.relogin() let when = dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)) dispatch_after(when,dispatch_get_main_queue(), { () in self?._socketHelper?.sendData(packet.serializableData()!) }) } else { self?._socketHelper?.sendData(packet.serializableData()!) } } objc_sync_enter(self) if _socketHelper == nil { SocketRequestManage.shared.start() let when = dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)) dispatch_after(when,dispatch_get_main_queue(),block) } else { block() } objc_sync_exit(self) } func startJsonRequest(packet: SocketDataPacket, complete: CompleteBlock?, error: ErrorBlock?) { let socketReqeust = SocketRequest(); socketReqeust.error = error; socketReqeust.complete = complete; packet.request_id = reqeustId; packet.session_id = _sessionId; objc_sync_enter(self) socketRequests[packet.request_id] = socketReqeust; objc_sync_exit(self) XCGLogger.debug("Request \(packet.operate_code) \(packet.request_id) \(packet.session_id)") sendRequest(packet) } func sendChatMsg(packet: SocketDataPacket,complete:CompleteBlock,error:ErrorBlock) { packet.request_id = reqeustId; packet.session_id = _sessionId; sendRequest(packet) } private func timeNow() ->NSTimeInterval { return NSDate().timeIntervalSince1970 } private func lastTimeNow(last:NSTimeInterval) ->NSTimeInterval { return timeNow() - last } private func isDispatchInterval(inout lastTime:NSTimeInterval,interval:NSTimeInterval) ->Bool { if timeNow() - lastTime >= interval { lastTime = timeNow() return true } return false } private func sendHeart() { let packet = SocketDataPacket(opcode: .Heart,dict:[SocketConst.Key.uid: CurrentUserHelper.shared.userInfo.uid]) sendRequest(packet) } func didActionTimer() { if _socketHelper != nil && _socketHelper!.isConnected { if CurrentUserHelper.shared.isLogin && isDispatchInterval(&_lastHeardBeatTime!,interval: 10) { sendHeart() } _lastConnectedTime = timeNow() } else if( isDispatchInterval(&_lastConnectedTime!,interval: 10) ) { _socketHelper?.connect() } checkReqeustTimeout() } }
apache-2.0
caff0dd82485a47701d0200024b79a38
32.039326
139
0.581874
4.773539
false
false
false
false
scherersoftware/SSHolidays
SSHolidays/HolidayMapsAT.swift
1
4746
// // HolidayMapsAT.swift // SSHolidays // // Created by Ralf Peters on 26/07/16. // Copyright ยฉ 2016 scherer software. All rights reserved. // import UIKit // MARK: Constants struct AustrianHolidayConstants { // MARK: all german holiday names struct kAustrianHolidayNames { static let kNewYear = "Neujahr" static let kEpiphany = "Heilige Drei Kรถnige" static let kAllHallows = "Allerheiligen" static let kChristmas = "Weihnachten" static let kMariaAscension = "Mariรค Himmelfahrt" static let kNationalDay = "Nationalfeiertag" static let kStatesDay = "Staatsfeiertag" static let kMariaConception = "Mariรค Empfรคngnis" static let kStefanieDay = "Stefanietag" } } struct AustrianStatesConstants { // MARK: all german States struct kStates { static let kStateB = "Burgenland" static let kStateK = "Kรคrnten" static let kStateNO = "Niederรถsterreich" static let kStateOO = "Oberรถsterreich" static let kStateS = "Salzburg" static let kStateST = "Steiermark" static let kStateT = "Tirol" static let kStateV = "Vorarlberg" static let kStateW = "Wien" } } class HolidayMapsAT: NSObject { static func getATHolidays(year year: Int) -> Array<Holiday> { var holidays = Array<Holiday>() let newYear = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kNewYear, year: year, month: 1, day: 1, fixedWithStates: false, states: []) holidays.append(newYear) let ephany = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kEpiphany, year: year, month: 1, day: 6, fixedWithStates: false, states: []) holidays.append(ephany) let allHallows = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kAllHallows, year: year, month: 11, day: 1, fixedWithStates: false, states: []) holidays.append(allHallows) let mariaAscension = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kMariaAscension, year: year, month: 8, day: 15, fixedWithStates: false, states: []) holidays.append(mariaAscension) let statesDay = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kStatesDay, year: year, month: 5, day: 1, fixedWithStates: false, states: []) holidays.append(statesDay) let nationalDay = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kNationalDay, year: year, month: 10, day: 26, fixedWithStates: false, states: []) holidays.append(nationalDay) let mariaConcetpion = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kMariaConception, year: year, month: 12, day: 8, fixedWithStates: false, states: []) holidays.append(mariaConcetpion) let christmas = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kChristmas, year: year, month: 12, day: 25, fixedWithStates: false, states: []) holidays.append(christmas) let stefaniesDay = Holiday(name: AustrianHolidayConstants.kAustrianHolidayNames.kStefanieDay, year: year, month: 12, day: 26, fixedWithStates: false, states: []) holidays.append(stefaniesDay) return holidays } }
mit
e4060540ef07f1a40a47df1818635b9c
35.728682
108
0.477417
4.884536
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Inline/InlineQueryResult/InlineResultDocument.swift
1
2241
// // InlineResultDocument.swift // Pelican // // Created by Takanu Kyriako on 20/12/2017. // import Foundation /** Represents either a link to a file stored on the Telegram servers, or an external URL link to one. By default, this file will be sent by the user with an optional caption. Alternatively, you can use the `content` property to send a message with the specified content instead of the file. - note: Currently, only .PDF and .ZIP files can be sent using this method. */ public struct InlineResultDocument: InlineResult { /// A metatype, used to Encode and Decode itself as part of the InlineResult protocol. public var metatype: InlineResultType = .document /// Type of the result being given. public var type: String = "document" /// Unique Identifier for the result, 1-64 bytes. public var id: String /// Content of the message to be sent. public var content: InputMessageContent? /// Inline keyboard attached to the message public var markup: MarkupInline? /// A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB public var url: String? /// A valid file identifier for the file. public var fileID: String? /// A caption for the document to be sent, 200 characters maximum. public var caption: String? /// The title of the inline result. public var title: String? /// A short description of the inline result. public var description: String? /// Mime type of the content of the file, either โ€œapplication/pdfโ€ or โ€œapplication/zipโ€. Not optional for un-cached results. var mimeType: String? /// URL of the thumbnail to use for the result. public var thumbURL: String? /// Thumbnail width. public var thumbWidth: Int? /// Thumbnail height. public var thumbHeight: Int? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case type case id case content = "input_message_content" case markup = "reply_markup" case url = "document_url" case fileID = "document_file_id" case caption case title case description case mimeType = "mime_type" case thumbURL = "thumb_url" case thumbWidth = "thumb_width" case thumbHeight = "thumb_height" } }
mit
564f4d19edb89c2cf515a142a0b5bdb6
25.583333
188
0.717868
3.85
false
false
false
false
markspanbroek/Shhwift
ShhwiftTests/ShhNewFilterSpec.swift
1
3162
import Quick import Nimble import Mockingjay import SwiftyJSON import Shhwift class ShhNewFilterSpec: QuickSpec { override func spec () { let url = "http://some.ethereum.node:8545" var shh: Shh! beforeEach { shh = Shh(url: url) } describe("new filter") { let topics = [Topic.example, Topic.example] let receiver = Identity.example it("calls the shh_newFilter JSON-RPC method") { waitUntil { done in self.interceptJSONRequests(to: url) { json in expect(json?["method"]) == "shh_newFilter" done() } shh.newFilter(topics: topics) { _, _ in return } } } it("adds the topics") { waitUntil { done in self.interceptJSONRequests(to: url) { json in let jsonTopics = json?["params"][0]["topics"] expect(jsonTopics) == JSON(topics.map { $0.asHexString }) done() } shh.newFilter(topics: topics) { _, _ in return } } } it("adds the receiver") { waitUntil { done in self.interceptJSONRequests(to: url) { json in let jsonReceiver = json?["params"][0]["to"] expect(jsonReceiver) == JSON(receiver.asHexString) done() } shh.newFilter(topics: topics, receiver: receiver) { _, _ in return } } } it("returns the correct result") { let someFilter = Filter.example self.stubRequests( to: url, result: json(["result": someFilter.id.asHexString]) ) waitUntil { done in shh.newFilter(topics: topics) { filter, _ in expect(filter) == someFilter done() } } } it("notifies about JSON-RPC errors") { self.stubRequests(to: url, result: http(404)) waitUntil { done in shh.newFilter(topics: topics) { _, error in expect(error).toNot(beNil()) done() } } } it("notifies when result is not a filter id string") { self.stubRequests(to: url, result: json(["result": "0xZZ"])) waitUntil { done in shh.newFilter(topics: topics) { _, error in let expectedError = ShhError.ShhFailed( message: "Result is not a valid filter id" ) expect(error) == expectedError done() } } } } } }
mit
32d0f4c8f7cd9857ab11ec396fe2f987
29.403846
81
0.411132
5.305369
false
false
false
false
geter/TransitDataImport-Swift
ConcurrentCoreData/FetchResultsTableDataSource.swift
2
5136
// // FetchResultsTableDataSource.swift // ConcurrentCoreData // // Created by Andy on 1/28/15. // Copyright (c) 2015 Andy Geter. All rights reserved. // import UIKit import CoreData class FetchedResultsTableDataSource:NSObject,UITableViewDataSource,NSFetchedResultsControllerDelegate { var configureCellBlock:((cell:UITableViewCell,item:Stop)->())? private let fetchedResultsController:NSFetchedResultsController private let tableView:UITableView init(tableView:UITableView, fetchedResultsController:NSFetchedResultsController) { self.fetchedResultsController = fetchedResultsController self.tableView = tableView super.init() self.setup() } func changePredicate(p:NSPredicate) -> Bool { if fetchedResultsController.cacheName != nil { return false } fetchedResultsController.fetchRequest.predicate = p fetchedResultsController.performFetch(nil) tableView.reloadData() return true } private func setup() { tableView.dataSource = self fetchedResultsController.delegate = self fetchedResultsController.performFetch(nil) } // MARK: - UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedResultsController.sections!.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.fetchedObjects!.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let info:NSFetchedResultsSectionInfo = fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo return info.name } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell configureCell(cell, indexPath: indexPath) return cell } // MARK: - Cell configuration private func itemAtIndexPath(indexPath:NSIndexPath) -> Stop? { if fetchedResultsController.fetchedObjects == nil || fetchedResultsController.fetchedObjects!.count == 0 { return nil } return fetchedResultsController.objectAtIndexPath(indexPath) as? Stop } private func configureCell(cell:UITableViewCell, indexPath:NSIndexPath) { let item:Stop? = itemAtIndexPath(indexPath) if let confCell = configureCellBlock { if let stop = item { confCell(cell: cell, item: stop) } } } func selectedItem() -> Stop? { if let indexPath = tableView.indexPathForSelectedRow() { return itemAtIndexPath(indexPath) } return nil } // MARK: - NSFetchedResultsControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case NSFetchedResultsChangeType.Insert: tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade) case NSFetchedResultsChangeType.Delete: tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade) default: break } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case NSFetchedResultsChangeType.Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) case NSFetchedResultsChangeType.Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) case NSFetchedResultsChangeType.Update: if tableView.indexPathsForVisibleRows()!.reduce(false, combine: { $1.isEqual(indexPath) || $0 }) { configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, indexPath: indexPath!) } case NSFetchedResultsChangeType.Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) } } }
mit
cdfea8cd7521985f88f53551e7e710ce
33.47651
211
0.675428
6.704961
false
false
false
false
QuaereVeritatem/TopHackIncStartup
TopHackIncStartUp/HackIncStartUp.swift
1
2840
// // HackIncStartUpeal.swift // TopHackIncStartup // // Created by Robert Martin on 9/4/16. // Copyright ยฉ 2016 Robert Martin. All rights reserved. // import UIKit //This is class is equivalent to Meal (classifications for user-side stuff) //data for EventsVC and POIVC class HackIncStartUp: NSObject, NSCoding, JSONSerializable { // MARK: Common Properties Shared by Archiver and Backendless var name: String var progUrl: String? //full website address var progType: EventData.ProgTypes? var areaLoc: EventData.AreaLoc? var logo: String? // an image here but an url string in BackendlessTopHack var dateOrTimeFrame: EventData.TimeFrame? // MARK: Archiver Only Properties var photo: UIImage? // MARK: Backendless Only Properties var objectId: String? var photoUrl: String? var thumbnailUrl: String? var replacePhoto: Bool = false // MARK: Archiving Paths //a persistent path on the file system where data will be saved and loaded.. //access the path using the syntax HackIncStartUp.ArchiveURL.path!(when accessed outside the class) static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! //string literal said "meals" up to recently 10-24 static let ArchiveURL = DocumentsDirectory.appendingPathComponent("events") //constants marked with static keyword apply to the class instead of an instance of the class. // MARK: Types struct PropertyKey { static let nameKey = "name" static let photoKey = "photo" //static let ratingKey = "rating" } // MARK: Initialization init?(name: String, photo: UIImage?) { // Initialize stored properties. self.name = name self.photo = photo super.init() // Initialization should fail if there is no name. if name.isEmpty { return nil } } // MARK: NSCoding //The encodeWithCoder(_:) method prepares the classโ€™s information to be archived, and the initializer unarchives the data when the class is created. func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: PropertyKey.nameKey) aCoder.encode(photo, forKey: PropertyKey.photoKey) } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: PropertyKey.nameKey) as! String // Because photo is an optional property of Meal, use conditional cast. let photo = aDecoder.decodeObject(forKey: PropertyKey.photoKey) as? UIImage // Must call designated initializer. self.init(name: name, photo: photo) } }
mit
0a6031f7ec737ef10035d15513dd365f
30.876404
152
0.649277
4.82483
false
false
false
false
marcelmueller/MyWeight
MyWeight/Screens/AuthorizationRequest/AuthorizationRequestViewModel.swift
1
2331
// // AuthorizationRequestViewModel.swift // MyWeight // // Created by Diogo on 19/10/16. // Copyright ยฉ 2016 Diogo Tridapalli. All rights reserved. // import Foundation public protocol AuthorizationRequestViewModelProtocol: TitleDescriptionViewModelProtocol { var okTitle: String { get } var cancelTitle: String { get } var didTapOkAction: () -> Void { get } var didTapCancelAction: () -> Void { get } } public struct AuthorizationRequestViewModel: AuthorizationRequestViewModelProtocol { public let title: NSAttributedString public let description: NSAttributedString public let flexibleHeight: Bool public let okTitle: String public let cancelTitle: String public let didTapOkAction: () -> Void public let didTapCancelAction: () -> Void } extension AuthorizationRequestViewModel { public init() { self.init(didTapOkAction: { _ in Log.debug("Ok") }, didTapCancelAction: { _ in Log.debug("Cancel" ) }) } public init(didTapOkAction: @escaping () -> Void, didTapCancelAction: @escaping () -> Void) { let style: StyleProvider = Style() title = NSAttributedString(string: Localization.authorizationTitle, font: style.title1, color: style.textColor) var description = NSAttributedString(string: Localization.authorizationDescription, font: style.body, color: style.textLightColor) description = description.highlight(string: Localization.authorizationDescriptionHighlight1, font: nil, color: style.textColor) description = description.highlight(string: Localization.authorizationDescriptionHighlight2, font: nil, color: style.textColor) self.description = description flexibleHeight = true okTitle = Localization.authorizationOkButton cancelTitle = Localization.authorizationCancelButton self.didTapOkAction = didTapOkAction self.didTapCancelAction = didTapCancelAction } }
mit
3cb41b7067cc956fb87a7e3f54d3e317
30.486486
100
0.608584
5.710784
false
false
false
false
sebbu/SwiftlyLRU
SwiftlyLRU/Source/SwiftlyLRU.swift
1
4625
// // Copyright (c) 2014 Justin M Fischer // // 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. // // Created by JUSTIN M FISCHER on 12/1/14. // Copyright (c) 2013 Justin M Fischer. All rights reserved. // import Foundation class Node<K, V> { var next: Node? var previous: Node? var key: K var value: V? init(key: K, value: V?) { self.key = key self.value = value } } class LinkedList<K, V> { var head: Node<K, V>? var tail: Node<K, V>? init() { } func addToHead(_ node: Node<K, V>) { if self.head == nil { self.head = node self.tail = node } else { let temp = self.head self.head?.previous = node self.head = node self.head?.next = temp } } func remove(_ node: Node<K, V>) { if node === self.head { if self.head?.next != nil { self.head = self.head?.next self.head?.previous = nil } else { self.head = nil self.tail = nil } } else if node.next != nil { node.previous?.next = node.next node.next?.previous = node.previous } else { node.previous?.next = nil self.tail = node.previous } } func display() -> String { var description = "" var current = self.head while current != nil { description += "Key: \(current!.key) Value: \(String(describing: current?.value)) \n" current = current?.next } return description } } class SwiftlyLRU<K : Hashable, V> : CustomStringConvertible { let capacity: Int var length = 0 internal let queue: LinkedList<K, V> fileprivate var hashtable: [K : Node<K, V>] /** Least Recently Used "LRU" Cache, capacity is the number of elements to keep in the Cache. */ init(capacity: Int) { self.capacity = capacity self.queue = LinkedList() self.hashtable = [K : Node<K, V>](minimumCapacity: self.capacity) } subscript (key: K) -> V? { get { if let node = self.hashtable[key] { self.queue.remove(node) self.queue.addToHead(node) return node.value } else { return nil } } set(value) { if let node = self.hashtable[key] { node.value = value self.queue.remove(node) self.queue.addToHead(node) } else { let node = Node(key: key, value: value) if self.length < capacity { self.queue.addToHead(node) self.hashtable[key] = node self.length += 1 } else { hashtable.removeValue(forKey: self.queue.tail!.key) self.queue.tail = self.queue.tail?.previous if let node = self.queue.tail { node.next = nil } self.queue.addToHead(node) self.hashtable[key] = node } } } } var description : String { return "SwiftlyLRU Cache(\(self.length)) \n" + self.queue.display() } }
mit
32d0577c8a00d9f2cfee8401b7c08bfb
28.83871
97
0.523676
4.516602
false
false
false
false
ethanneff/iOS-Swift-Drag-And-Drop-TableView-Cell-1
DragAndDropTableViewCell1/TableViewController.swift
1
5696
// // TableViewController.swift // DragAndDropTableViewCell // // Created by Ethan Neff on 2/2/16. // Copyright ยฉ 2016 Ethan Neff. All rights reserved. // import UIKit class TableViewController: UITableViewController { // controller properties var itemsArray : [String] required init(coder aDecoder: NSCoder) { // init controller properties itemsArray = ["Advantageous", "Ameliorate", "Cognizant", "Commence", "Commensurate", "Consolidate", "Deleterious", "Disseminate", "Endeavor", "Erroneous", "Expeditious", "Facilitate", "Inception", "Implement", "Leverage", "Optimize", "Prescribed", "Proficiencies", "Promulgate", "Proximity", "Regarding", "Remuneration", "Subsequently"] super.init(coder: aDecoder)! } override func viewDidLoad() { super.viewDidLoad() // nav controller properties navigationController?.navigationBarHidden = true // table properties tableView.contentInset = UIEdgeInsetsZero tableView.separatorInset = UIEdgeInsetsZero tableView.scrollIndicatorInsets = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.tableFooterView = UIView(frame: CGRectZero) // table guestures let longpress = UILongPressGestureRecognizer(target: self, action: "longPressGestureRecognized:") longpress.minimumPressDuration = 0.35 tableView.addGestureRecognizer(longpress) } func longPressGestureRecognized(gestureRecognizer: UIGestureRecognizer) { // long press on cell let longPress = gestureRecognizer as! UILongPressGestureRecognizer let state = longPress.state let locationInView = longPress.locationInView(tableView) let indexPath = tableView.indexPathForRowAtPoint(locationInView) struct My { static var cellSnapshot : UIView? = nil } struct Path { static var initialIndexPath : NSIndexPath? = nil } switch state { case UIGestureRecognizerState.Began: // pick up cell if indexPath != nil { Path.initialIndexPath = indexPath let cell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell! var center = cell.center // create the pick-up cell My.cellSnapshot = snapshopOfCell(cell) My.cellSnapshot!.center = center My.cellSnapshot!.alpha = 0.0 tableView.addSubview(My.cellSnapshot!) UIView.animateWithDuration(0.25, animations: { () -> Void in center.y = locationInView.y // pick up cell My.cellSnapshot!.center = center My.cellSnapshot!.transform = CGAffineTransformMakeScale(1.05, 1.05) My.cellSnapshot!.alpha = 0.8 // hide old cell (will be there the entire time) cell.alpha = 0.0 }, completion: { (finished) -> Void in if finished { cell.hidden = true } }) } case UIGestureRecognizerState.Changed: // move cell var center = My.cellSnapshot!.center center.y = locationInView.y My.cellSnapshot!.center = center if ((indexPath != nil) && (indexPath != Path.initialIndexPath)) { // update items array swap(&itemsArray[indexPath!.row], &itemsArray[Path.initialIndexPath!.row]) // update tableview (move the hidden cell below the hoving cell) tableView.moveRowAtIndexPath(Path.initialIndexPath!, toIndexPath: indexPath!) // where the cell is hovering over Path.initialIndexPath = indexPath } default: // place cell down (unhide the hidden cell) let cell = tableView.cellForRowAtIndexPath(Path.initialIndexPath!) as UITableViewCell! cell.hidden = false cell.alpha = 0.0 UIView.animateWithDuration(0.25, animations: { () -> Void in My.cellSnapshot!.center = cell.center My.cellSnapshot!.transform = CGAffineTransformIdentity My.cellSnapshot!.alpha = 0.0 cell.alpha = 1.0 }, completion: { (finished) -> Void in if finished { Path.initialIndexPath = nil My.cellSnapshot!.removeFromSuperview() My.cellSnapshot = nil print(self.itemsArray) } }) } } func snapshopOfCell(inputView: UIView) -> UIView { // the pick up cell (view properties) UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0) inputView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() let cellSnapshot : UIView = UIImageView(image: image) cellSnapshot.layer.masksToBounds = false cellSnapshot.layer.cornerRadius = 0.0 cellSnapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0) cellSnapshot.layer.shadowRadius = 3.0 cellSnapshot.layer.shadowOpacity = 0.4 return cellSnapshot } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemsArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) // cell properties cell.separatorInset = UIEdgeInsetsZero cell.layoutMargins = UIEdgeInsetsZero cell.selectionStyle = .None cell.textLabel?.text = itemsArray[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) } }
mit
76fc1459891a6e2fe58650417aacdd15
35.741935
340
0.678139
4.947871
false
false
false
false
oddnetworks/odd-sample-apps
apple/tvos/tvOSSampleApp/tvOSSampleApp/CollectionInfoViewController.swift
1
1832
// // CollectionInfoViewController.swift // tvOSSampleApp // // Created by Patrick McConnell on 1/28/16. // Copyright ยฉ 2016 Odd Networks. All rights reserved. // import UIKit import OddSDKtvOS class CollectionInfoViewController: UIViewController { @IBOutlet var collectionThumbnailImageView: UIImageView! @IBOutlet var collectionTitleLabel: UILabel! @IBOutlet weak var collectionNotesTextView: UITextView! var collection = OddMediaObjectCollection() { didSet { configureForCollection() } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let id = segue.identifier else { return } switch id { case "videoTableEmbed": guard let vc = segue.destination as? CollectionInfoVideoTableViewController, let node = self.collection.relationshipNodeWithName("entities"), let ids = node.allIds else { break } OddContentStore.sharedStore.objectsOfType(.video, ids: ids, include:nil, callback: { (objects, errors) -> Void in if let videos = objects as? Array<OddVideo> { vc.videos = videos } }) default: break } } // MARK: - Helpers func configureForCollection() { DispatchQueue.main.async { () -> Void in self.collectionTitleLabel?.text = self.collection.title self.collectionNotesTextView?.text = self.collection.notes self.collection.thumbnail { (image) -> Void in if let thumbnail = image { self.collectionThumbnailImageView?.image = thumbnail } } } } }
apache-2.0
63fafb8527e83fb9fc50591c1e4a2b13
23.743243
119
0.664664
4.682864
false
false
false
false
StanZabroda/Hydra
Hydra/HRNavigationController.swift
1
920
// // HRNavigationController.swift // Hydra // // Created by Evgeny Abramov on 7/1/15. // Copyright (c) 2015 Evgeny Abramov. All rights reserved. // import UIKit class HRNavigationController: BufferedNavigationController { override func viewDidLoad() { super.viewDidLoad() self.navigationBar.tintColor = UIColor.whiteColor() self.navigationBar.barTintColor = UIColor(red: 20/255, green: 20/255, blue: 20/255, alpha: 1.0) self.navigationItem.titleView?.tintColor = UIColor.whiteColor() self.interactivePopGestureRecognizer!.enabled = true self.navigationBar.translucent = false let titleDict = [NSFontAttributeName : UIFont(name: "HelveticaNeue-Thin", size: 20)!, NSForegroundColorAttributeName : UIColor.whiteColor()] self.navigationBar.titleTextAttributes = titleDict } }
mit
2201f622c64ce37e95a8906b0c65ae90
28.677419
148
0.663043
4.972973
false
false
false
false
lucasharding/antenna
Service/TVGuide.swift
1
7496
// // TVGuide.swift // ustvnow-tvos // // Created by Lucas Harding on 2015-09-11. // Copyright ยฉ 2015 Lucas Harding. All rights reserved. // import Foundation import ObjectMapper import Alamofire import AlamofireObjectMapper import TVServices open class TVGuide { var startDate : Date = Date() var endDate : Date = Date() var programs = Array<TVProgram>() var channels = Array<TVChannel>() var channelsFilter: ((Void) -> TVChannelFilter)? fileprivate var programsMap = [String: Array<TVProgram>]() open var allChannels = Array<TVChannel>() public init(startDate: Date = Date(), completionHandler: @escaping (TVGuide, Error?) -> Void) { NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: nil) { n in self.recalculate() NotificationCenter.default.post(name: Notification.Name(rawValue: TVService.didRefreshGuideNotification), object: nil) } refresh { (error) in completionHandler(self, error) } } //MARK: Refreshing @discardableResult open func refresh(_ completionHandler: @escaping (Error?) -> Void) -> Request { var channels = [TVChannel]() return TVService.sharedInstance.getPrograms(nil).responseArray(keyPath: "results") { (response: DataResponse<[TVChannel]>) in channels = response.result.value ?? channels }.responseArray(keyPath: "results") { (response: DataResponse<[TVProgram]>) in var endDate : Date? var channelsMap = [String: TVChannel]() var allChannels = [TVChannel]() var allPrograms = [TVProgram]() var programsMap = [String: [TVProgram]]() if let programs = response.result.value { for (index, program) in programs.enumerated() { // Find or create channel var channel = channelsMap[program.channelCode] if channel == nil { channel = channels[index] allChannels.append(channel!) channelsMap[channel!.streamCode!] = channel } // Find or create array of programs for channel var programsForChannel = programsMap[channel!.streamCode!] if programsForChannel == nil { programsForChannel = Array<TVProgram>() } programsForChannel?.append(program) // Set new endDate if program endDate is later if endDate == nil || program.endDate > endDate! { endDate = program.endDate } // Update respective collections allPrograms.append(program) programsMap[channel!.streamCode!] = programsForChannel } } TVImageService.sharedInstance.fillProgramImages(allPrograms) { _ in self.allChannels = allChannels self.programs = allPrograms self.programsMap = programsMap self.endDate = self.startDate.addingTimeInterval(3 * 3600) self.recalculate() DispatchQueue.main.async() { completionHandler(response.result.error) } self.scheduleRefreshTimer() } } } open func recalculate() { //Round startdate to last half hour var units = Calendar.current.dateComponents([.day,.month,.year,.hour,.minute], from: Date()) units.minute = (units.minute! / 30) * 30 units.second = 1 self.startDate = Calendar.current.date(from: units)! print("Recalculate", self.startDate) //Filter programs self.programs = self.programs.filter({ (self.startDate as NSDate).laterDate($0.endDate as Date) == $0.endDate as Date }) for (key, programs) in self.programsMap { self.programsMap[key] = programs.filter({ (self.startDate as NSDate).laterDate($0.endDate as Date) == $0.endDate as Date }) } var channels = self.allSortedChannels //Filter if self.channelsFilter != nil { if self.channelsFilter!() == .Favorites { channels = channels.filter({ TVPreferences.sharedInstance.isFavoriteChannel($0) }) } else if self.channelsFilter!() == .Available { channels = channels.filter({ (channel) -> Bool in return channel.available }) } } self.channels = channels self.scheduleRecalcTimer() DispatchQueue.main.async { NotificationCenter.default.post(name: Notification.Name(rawValue: TVService.didRefreshGuideNotification), object: nil) NotificationCenter.default.post(name: NSNotification.Name.TVTopShelfItemsDidChange, object: nil) } } //MARK: Accessors var allSortedChannels: [TVChannel] { get { var oldChannels = self.allChannels var channels = [TVChannel]() for streamCode in TVPreferences.sharedInstance.channelsOrderKeys { if let index = oldChannels.index(where: { return $0.streamCode == streamCode }) { channels.append(oldChannels.remove(at: index)) } } channels.append(contentsOf: oldChannels) return channels } } open func programsForChannel(_ channel: TVChannel) -> Array<TVProgram>? { return self.programsMap[channel.streamCode!] } open func channelWithStreamCode(_ streamCode: String) -> TVChannel? { for channel in self.channels { if channel.streamCode == streamCode { return channel } } return nil } //MARK: Timers var refreshTimer: Timer? { didSet { oldValue?.invalidate() } } func scheduleRefreshTimer() { let date = Date(timeIntervalSinceNow: 60 * 30) self.refreshTimer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(TVGuide.timerFire), userInfo: nil, repeats: false) RunLoop.main.add(self.refreshTimer!, forMode: RunLoopMode.commonModes) print("** Scheduling refresh for:", date) } @objc func timerFire() { self.refresh {_ in } } var recalcTimer: Timer? { didSet { oldValue?.invalidate() } } func scheduleRecalcTimer() { var units = (Calendar.current as NSCalendar).components([.day,.month,.year,.hour,.minute], from: Date()) units.minute = ((units.minute! + 30) / 30) * 30 let date = Calendar.current.date(from: units)! self.recalcTimer = Timer(fireAt: date, interval: 0, target: self, selector:#selector(TVGuide.recalcTimerFire), userInfo: nil, repeats: false) RunLoop.main.add(self.recalcTimer!, forMode: RunLoopMode.commonModes) print("** Scheduling recalc for:", date) } @objc func recalcTimerFire() { self.recalculate() } }
gpl-3.0
7c8bc964850a3bcfa99768e54abab9cf
35.921182
149
0.565043
5.06077
false
false
false
false
feistydog/FeistyDB
Sources/FeistyDB/Row.swift
1
2506
// // Copyright (c) 2015 - 2020 Feisty Dog, LLC // // See https://github.com/feistydog/FeistyDB/blob/master/LICENSE.txt for license information // import Foundation import CSQLite /// A result row containing one or more columns with type-safe value access. /// /// **Creation** /// /// A row is not created directly but is obtained from a `Statement`. /// /// ```swift /// try statement.execute() { row in /// // Do something with `row` /// } /// ``` /// /// **Column Value Access** /// /// The database-native column value is expressed by `DatabaseValue`, however custom type conversion is possible when /// a type implements either the `ColumnConvertible` or `DatabaseSerializable` protocol. /// /// The value of columns is accessed by the `value(at:)` or `value(named:)` methods. /// /// ```swift /// let value = try row.value(at: 0) /// let uuid: UUID = try row.value(named: "session_uuid") /// ``` /// /// It is also possible to iterate over column values: /// /// ```swift /// for row in statement { /// for value in row { /// // Do something with `value` /// } /// /// } /// ``` /// /// This allows for simple result row processing at the expense of error handling. public struct Row { /// The statement owning this row. public let statement: Statement /// Creates a result row. /// /// - parameter statement: The owning statement init(statement: Statement) { self.statement = statement self.columnCount = Int(sqlite3_data_count(statement.stmt)) } /// The number of columns in the row. public let columnCount: Int /// Returns the name of the column at `index`. /// /// This is a shortcut for `statement.name(ofColumn: index)`. /// /// - note: Column indexes are 0-based. The leftmost column in a result row has index 0. /// /// - requires: `index >= 0` /// - requires: `index < columnCount` /// /// - parameter index: The index of the desired column /// /// - throws: An error if `index` is out of bounds /// /// - returns: The name of the column public func name(ofColumn index: Int) throws -> String { return try statement.name(ofColumn: index) } /// Returns the index of the column with name `name`. /// /// This is a shortcut for `statement.index(ofColumn: name)`. /// /// - parameter name: The name of the desired column /// /// - throws: An error if the column doesn't exist /// /// - returns: The index of the column public func index(ofColumn name: String) throws -> Int { return try statement.index(ofColumn: name) } }
mit
42feb7f440dfa4300d33adbe0c1d8380
26.538462
117
0.653232
3.58
false
false
false
false
fireunit/login
Pods/Material/Sources/iOS/FabButton.swift
2
2158
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of Material 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ import UIKit public class FabButton : MaterialButton { /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public override func prepareView() { super.prepareView() depth = .Depth1 shape = .Circle pulseAnimation = .CenterWithBacking pulseColor = MaterialColor.white tintColor = MaterialColor.white backgroundColor = MaterialColor.red.base } }
mit
0196208786db78369f98aec1e736b2d8
42.18
86
0.780816
4.467909
false
false
false
false
presence-insights/pi-clientsdk-ios
IBMPIGeofence/PIServiceCreateOrgRequest.swift
1
3515
/** * IBMPIGeofence * PIServiceCreateOrgRequest * * Performs all communication to the PI Rest API. * * ยฉ Copyright 2016 IBM Corp. * * Licensed under the Presence Insights Client iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 CocoaLumberjack @objc(IBMPIServiceCreateOrgRequest) final class PIServiceCreateOrgRequest:NSObject,PIRequest { let completionBlock: PIServiceCreateOrgResponse -> Void let orgName:String public init(orgName:String,completionBlock:PIServiceCreateOrgResponse -> Void) { self.orgName = orgName self.completionBlock = completionBlock } public func execute(service:PIService) -> PIResponse { DDLogInfo("PIServiceCreateOrgRequest.execute",asynchronous:false) let operation = PIServiceCreateOrgOperation(service:service,orgName:orgName) let response = PIServiceCreateOrgResponse(piRequest: self,operation:operation) operation.completionBlock = {[unowned self] in operation.completionBlock = nil dispatch_async(dispatch_get_main_queue(), { () -> Void in switch operation.result { case .OK(let data)?: guard let data = data else { response.result = .OK(nil) DDLogError("PIServiceCreateOrgRequest,OK but No data",asynchronous:false) break } do { let json = try NSJSONSerialization.JSONObjectWithData(data,options:[]) response.result = .OK(json) guard let orgCode = json["@code"] as? String else { DDLogError("PIServiceCreateOrgRequest,Missing Org",asynchronous:false) break } response.orgCode = orgCode DDLogInfo("PIServiceCreateOrgRequest Org:\(orgCode)",asynchronous:false) } catch { DDLogError("PIServiceCreateOrgRequest,Json parsing error \(error)",asynchronous:false) response.result = .OK(nil) } case .Cancelled?: response.result = .Cancelled case let .HTTPStatus(status, data)?: if let data = data { let json = try? NSJSONSerialization.JSONObjectWithData(data,options:[]) response.result = .HTTPStatus(status,json) } else { response.result = .HTTPStatus(status,nil) } case .Error(let error)?: response.result = .Error(error) case .Exception(let exception)?: response.result = .Exception(exception) case nil: response.result = .Cancelled } self.completionBlock(response) }) } return response } }
epl-1.0
e0a005ae71e41c78f1f8e8a01118fe0a
36.795699
97
0.582527
5.137427
false
false
false
false
yourtion/SwiftDesignPatterns-Demo1
BlueLibrarySwift/AlbumView.swift
2
1745
// // AlbumView.swift // BlueLibrarySwift // // Created by YourtionGuo on 9/17/15. // Copyright ยฉ 2015 Raywenderlich. All rights reserved. // import UIKit class AlbumView: UIView { private var coverImage: UIImageView! private var indicator: UIActivityIndicatorView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } init(frame: CGRect, albumCover: String) { super.init(frame: frame) backgroundColor = UIColor.blackColor() coverImage = UIImageView(frame: CGRectMake(5, 5, frame.size.width - 10, frame.size.height - 10)) addSubview(coverImage) coverImage.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions([.New]), context: nil) indicator = UIActivityIndicatorView() indicator.center = center indicator.activityIndicatorViewStyle = .WhiteLarge indicator.startAnimating() addSubview(indicator) NSNotificationCenter.defaultCenter().postNotificationName("BLDownloadImageNotification", object: self, userInfo: ["imageView":coverImage, "coverUrl" : albumCover]) } deinit { coverImage.removeObserver(self, forKeyPath: "image") } func highlightAlbum(didHighlightView didHighlightView: Bool) { if didHighlightView == true { backgroundColor = UIColor.whiteColor() } else { backgroundColor = UIColor.blackColor() } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "image" { indicator.stopAnimating() } } }
mit
d928ce572a7c14a46a6d8c79c007839a
31.90566
171
0.65539
5.069767
false
false
false
false
github/Nimble
Nimble/Matchers/Contain.swift
77
1991
import Foundation public func contain<S: SequenceType, T: Equatable where S.Generator.Element == T>(items: T...) -> MatcherFunc<S> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(_arrayAsString(items))>" if let actual = actualExpression.evaluate() { return _all(items) { return contains(actual, $0) } } return false } } public func contain(substrings: String...) -> MatcherFunc<String> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(_arrayAsString(substrings))>" if let actual = actualExpression.evaluate() { return _all(substrings) { let scanRange = Range(start: actual.startIndex, end: actual.endIndex) let range = actual.rangeOfString($0, options: nil, range: scanRange, locale: nil) return range != nil && !range!.isEmpty } } return false } } public func contain(items: AnyObject?...) -> MatcherFunc<NMBContainer> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(_arrayAsString(items))>" let actual = actualExpression.evaluate() return _all(items) { item in return actual != nil && actual!.containsObject(item) } } } extension NMBObjCMatcher { public class func containMatcher(expected: NSObject?) -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block: () -> NMBContainer? = ({ if let value = actualBlock() as? NMBContainer { return value } return nil }) let expr = Expression(expression: block, location: location) return contain(expected).matches(expr, failureMessage: failureMessage) } } }
apache-2.0
9d1c17d820b52d72cf703c10ffc28dbe
37.288462
114
0.608739
5.239474
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Home/View/AmuseMenuView.swift
1
2725
// // AmuseMenuView.swift // DYZB // // Created by xiudou on 16/10/27. // Copyright ยฉ 2016ๅนด xiudo. All rights reserved. // import UIKit // MARK:- ๅธธ้‡ private let sAmuseMenuIdentifier = "sAmuseMenuIdentifier" private let sPageControlW : CGFloat = sScreenW private let sPageControlH : CGFloat = 30 class AmuseMenuView: UIView { @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var collectionView: UICollectionView! var groups : [AnchorGroup]?{ didSet{ collectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: sAmuseMenuIdentifier) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension AmuseMenuView { class func creatAmuseMenuView()->AmuseMenuView{ return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)!.first as! AmuseMenuView } } extension AmuseMenuView : UICollectionViewDataSource { // ้œ€่ฆๅฑ•็คบๅ‡ ไธชitem, func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ if groups == nil { return 0 } let pageNum = (groups!.count - 1) / 8 + 1 pageControl.numberOfPages = pageNum return pageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: sAmuseMenuIdentifier, for: indexPath) as! AmuseMenuViewCell setupCell(cell, indexPath: indexPath) return cell } func setupCell(_ cell : AmuseMenuViewCell,indexPath : IndexPath){ // 1 0 ~ 7 // 2 8 ~ 15 // 3 16 ~ 23 // ๅ–ๅ‡บๅฏนๅบ”็š„้กต้ขๆ•ฐๆฎ็š„ไธชๆ•ฐไผ ้€’็ป™cellไธญ็š„collectionView let startItem = indexPath.item * 8 var endItem = (indexPath.item + 1) * 8 - 1 // ๅค„็†่ถŠ็•Œ้—ฎ้ข˜ if endItem > groups!.count - 1{ endItem = groups!.count - 1 } let tempGroup = Array(groups![startItem ... endItem]) cell.groups = tempGroup } } extension AmuseMenuView : UIScrollViewDelegate{ func scrollViewDidScroll(_ scrollView: UIScrollView) { let currentPage = scrollView.contentOffset.x / scrollView.frame.size.width pageControl.currentPage = Int(currentPage) } }
mit
5bb27260f47ae7042ae15b5d0c034abc
27.913043
134
0.652256
4.944238
false
false
false
false
nerdycat/Cupcake
Cupcake/TextView.swift
1
3653
// // TextView.swift // Cupcake // // Created by nerdycat on 2017/3/25. // Copyright ยฉ 2017 nerdycat. All rights reserved. // import UIKit public var TextView: UITextView { cpk_swizzleMethodsIfNeed() return UITextView().font(17) } public extension UITextView { /** * Setting text or attributedText * str can take any kind of value, even primitive type like Int. * Usages: .str(1024) .str("hello world") .str( AttStr("hello world").strikethrough() ) ... */ @objc @discardableResult func str(_ any: Any?) -> Self { if let attStr = any as? NSAttributedString { self.attributedText = attStr } else if let any = any { self.text = String(describing: any) } else { self.text = nil } return self } /** * Setting placeholder or attributedPlaceholder * hint can take any kind of value, even primitive type like Int. * Usages: .hint(1024) .hint("Enter here") .hint( AttStr("Enter here").font(13) ) */ @objc @discardableResult func hint(_ any: Any?) -> Self { cpk_setPlaceholder(any) return self } /** * Setting font * font use Font() internally, so it can take any kind of values that Font() supported. * See Font.siwft for more information. * Usages: .font(15) .font("20") .font("body") .font(someLabel.font) ... **/ @objc @discardableResult func font(_ any: Any) -> Self { self.font = Font(any) return self } /** * Setting textColor * color use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .color(@"red") .color(@"#F00") .color(@"255,0,0") .color(someLabel.textColor) ... */ @objc @discardableResult func color(_ any: Any) -> Self { self.textColor = Color(any) return self } /** * Max input length * Usages: .maxLength(10) */ @objc @discardableResult func maxLength(_ length: CGFloat) -> Self { self.cpkMaxLength = Int(length) return self } /** * contentEdgeInsets for UITextView * Usages: .padding(10) //top: 10, left: 10, bottom: 10, right: 10 .padding(10, 20) //top: 10, left: 20, bottom: 10, right: 20 .padding(10, 20, 30) //top: 10, left: 20, bottom: 0 , right: 30 .padding(10, 20, 30, 40) //top: 10, left: 20, bottom: 30, right: 40 */ @discardableResult func padding(_ contentEdgeInsets: CGFloat...) -> Self { cpk_updatePadding(contentEdgeInsets, forView: self) return self } /** * Setting textAlignment * Usages: .align(.center) .align(.justified) ... */ @objc @discardableResult func align(_ textAlignment: NSTextAlignment) -> Self { self.textAlignment = textAlignment return self } /** * Setup text changed handler. * Be aware of retain cycle when using this method. * Usages: .onChange({ textView in /* ... */ }) .onChange({ _ in /* ... */ }) .onChange({ [weak self] textView in /* ... */ }) //capture self as weak reference when needed */ @discardableResult func onChange(_ closure: @escaping (UITextView)->()) -> Self { self.cpkTextChangedClosure = cpk_generateCallbackClosure(closure, nil) return self } }
mit
94e17bb054fa436cbe967aebb3a4d790
26.458647
101
0.549014
4.16895
false
false
false
false
maxadamski/SwiftyRegex
Playground.playground/Contents.swift
1
999
import SwiftyRegex //: Check if contains one or more alphanumeric words var words = "RegEx is tough, but useful." let wordsMatcher = Regex("[a-zA-Z]+") wordsMatcher.test(words) //: Show which substrings match wordsMatcher.matches(words) //: Replace one matching substring var greeting = "Hi <name>." let nameMatcher = Regex("<name>") nameMatcher.replaceIn(greeting, with: "Jane") //: Replace all matching substrings var color = "I like color, color is my favourite." var blueMatcher = Regex("color") blueMatcher.replaceAllIn(color, with: "green") //: Use shorthand operator to test for match "http://something.com/users/13/profile" =~ "/users/[0-9]" //: It works with Regex objects too let userMatcher = Regex("/users/[0-9]") "http://something.com/users/13/profile" =~ userMatcher //: POSIX limitations // Find four letter words let fourLetter = Regex("\\b\\w{5}\\b") fourLetter.matches(words) // Sorry, POSIX regex doesn't support \b \w and others // (at least in the OS X implementation)
mit
c2856fc7f8159d88262263f86526cb37
27.542857
57
0.71972
3.567857
false
true
false
false
thebluepotato/AlamoFuzi
Pods/Alamofire/Source/Alamofire.swift
1
22788
// // Alamofire.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Global namespace containing API for the `default` `Session` instance. public enum AF { // MARK: - Data Request /// Creates a `DataRequest` using `SessionManager.default` to retrive the contents of the specified `url` /// using the `method`, `parameters`, `encoding`, and `headers` provided. /// /// - Parameters: /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.get` by default. /// - parameters: The `Parameters`, `nil` by default. /// - encoding: The `ParameterEncoding`, `URLEncoding.default` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `DataRequest`. public static func request(_ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil) -> DataRequest { return Session.default.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers, interceptor: interceptor) } /// Creates a `DataRequest` using `SessionManager.default` to retrive the contents of the specified `url` /// using the `method`, `parameters`, `encoding`, and `headers` provided. /// /// - Parameters: /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.get` by default. /// - parameters: The `Encodable` parameters, `nil` by default. /// - encoding: The `ParameterEncoding`, `URLEncodedFormParameterEncoder.default` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `DataRequest`. public static func request<Parameters: Encodable>(_ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil) -> DataRequest { return Session.default.request(url, method: method, parameters: parameters, encoder: encoder, headers: headers, interceptor: interceptor) } /// Creates a `DataRequest` using `SessionManager.default` to execute the specified `urlRequest`. /// /// - Parameters: /// - urlRequest: The `URLRequestConvertible` value. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `DataRequest`. public static func request(_ urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { return Session.default.request(urlRequest, interceptor: interceptor) } // MARK: - Download Request /// Creates a `DownloadRequest` using `SessionManager.default` to download the contents of the specified `url` to /// the provided `destination` using the `method`, `parameters`, `encoding`, and `headers` provided. /// /// If `destination` is not specified, the download will remain at the temporary location determined by the /// underlying `URLSession`. /// /// - Parameters: /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.get` by default. /// - parameters: The `Parameters`, `nil` by default. /// - encoding: The `ParameterEncoding`, `URLEncoding.default` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the /// downloaded file. `nil` by default. /// /// - Returns: The created `DownloadRequest`. public static func download(_ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil, to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { return Session.default.download(url, method: method, parameters: parameters, encoding: encoding, headers: headers, interceptor: interceptor, to: destination) } /// Creates a `DownloadRequest` using `SessionManager.default` to download the contents of the specified `url` to /// the provided `destination` using the `method`, encodable `parameters`, `encoder`, and `headers` provided. /// /// If `destination` is not specified, the download will remain at the temporary location determined by the /// underlying `URLSession`. /// /// - Parameters: /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.get` by default. /// - parameters: The `Encodable` parameters, `nil` by default. /// - encoder: The `ParameterEncoder`, `URLEncodedFormParameterEncoder.default` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the /// downloaded file. `nil` by default. /// /// - Returns: The created `DownloadRequest`. public static func download<Parameters: Encodable>(_ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil, to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { return Session.default.download(url, method: method, parameters: parameters, encoder: encoder, headers: headers, interceptor: interceptor, to: destination) } // MARK: URLRequest /// Creates a `DownloadRequest` using `SessionManager.default` to execute the specified `urlRequest` and download /// the result to the provided `destination`. /// /// - Parameters: /// - urlRequest: The `URLRequestConvertible` value. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the /// downloaded file. `nil` by default. /// /// - Returns: The created `DownloadRequest`. public static func download(_ urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil, to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { return Session.default.download(urlRequest, interceptor: interceptor, to: destination) } // MARK: Resume Data /// Creates a `DownloadRequest` using the `SessionManager.default` from the `resumeData` produced from a previous /// `DownloadRequest` cancellation to retrieve the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` /// generation logic where the data is written incorrectly and will always fail to resume the download. For more /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). /// /// - Parameters: /// - resumeData: The resume `Data`. This is an opaque blob produced by `URLSessionDownloadTask` when a task is /// cancelled. See [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel) /// for more information. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - destination: The `DownloadRequest.Destination` closure used to determine the destination of the downloaded /// file. `nil` by default. /// /// - Returns: The created `DownloadRequest`. public static func download(resumingWith resumeData: Data, interceptor: RequestInterceptor? = nil, to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { return Session.default.download(resumingWith: resumeData, interceptor: interceptor, to: destination) } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` using `SessionManager.default` to upload the contents of the `fileURL` specified /// using the `url`, `method` and `headers` provided. /// /// - Parameters: /// - fileURL: The `URL` of the file to upload. /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.post` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(_ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(fileURL, to: url, method: method, headers: headers, interceptor: interceptor) } /// Creates an `UploadRequest` using the `SessionManager.default` to upload the contents of the `fileURL` specificed /// using the `urlRequest` provided. /// /// - Parameters: /// - fileURL: The `URL` of the file to upload. /// - urlRequest: The `URLRequestConvertible` value. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(fileURL, with: urlRequest, interceptor: interceptor) } // MARK: Data /// Creates an `UploadRequest` using `SessionManager.default` to upload the contents of the `data` specified using /// the `url`, `method` and `headers` provided. /// /// - Parameters: /// - data: The `Data` to upload. /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.post` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - retryPolicies: The `RetryPolicy` types, `[]` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(_ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(data, to: url, method: method, headers: headers, interceptor: interceptor) } /// Creates an `UploadRequest` using `SessionManager.default` to upload the contents of the `data` specified using /// the `urlRequest` provided. /// /// - Parameters: /// - data: The `Data` to upload. /// - urlRequest: The `URLRequestConvertible` value. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(_ data: Data, with urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(data, with: urlRequest, interceptor: interceptor) } // MARK: InputStream /// Creates an `UploadRequest` using `SessionManager.default` to upload the content provided by the `stream` /// specified using the `url`, `method` and `headers` provided. /// /// - Parameters: /// - stream: The `InputStream` to upload. /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.post` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(_ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(stream, to: url, method: method, headers: headers, interceptor: interceptor) } /// Creates an `UploadRequest` using `SessionManager.default` to upload the content provided by the `stream` /// specified using the `urlRequest` specified. /// /// - Parameters: /// - stream: The `InputStream` to upload. /// - urlRequest: The `URLRequestConvertible` value. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(stream, with: urlRequest, interceptor: interceptor) } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` and uploads the result using `SessionManager.default` /// with the `url`, `method`, and `headers` provided. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - Parameters: /// - multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - encodingMemoryThreshold: The encoding memory threshold in bytes. `10_000_000` bytes by default. /// - fileManager: The `FileManager` instance to use to manage streaming and encoding. /// - url: The `URLConvertible` value. /// - method: The `HTTPMethod`, `.post` by default. /// - headers: The `HTTPHeaders`, `nil` by default. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The created `UploadRequest`. public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, fileManager: FileManager = .default, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, fileManager: fileManager, to: url, method: method, headers: headers, interceptor: interceptor) } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and uploads the result using `SessionManager.default` /// using the `urlRequest` provided. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - Parameters: /// - multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - encodingMemoryThreshold: The encoding memory threshold in bytes. `10_000_000` bytes by default. /// - urlRequest: The `URLRequestConvertible` value. /// - interceptor: The `RequestInterceptor`, `nil` by default. /// /// - Returns: The `UploadRequest` created. @discardableResult public static func upload(multipartFormData: MultipartFormData, usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, with urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> UploadRequest { return Session.default.upload(multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, interceptor: interceptor) } }
mit
f88fee9272b925d729747c05b796fa66
56.545455
157
0.585133
5.378334
false
false
false
false
baottran/nSURE
nSURE/ASLogDamageViewController.swift
1
6425
// // ASLogDamageViewController.swift // nSURE // // Created by Bao Tran on 7/16/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit protocol ASLogDamageViewControllerDelegate: class { func saveDamage(vehicleSectionObj: vehicleDamageSection) } class ASLogDamageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ASNotePopoverControllerDelegate, UICollectionViewDataSource { @IBOutlet weak var notesTextView: UITextView! @IBOutlet weak var damageSwitch: UISwitch! @IBOutlet weak var paintLabel: UILabel! @IBOutlet weak var paintSwitch: UISwitch! @IBOutlet weak var bodyWorkLabel: UILabel! @IBOutlet weak var bodyWorkSwitch: UISwitch! @IBOutlet weak var mechanicalLabel: UILabel! @IBOutlet weak var mechanicalSwitch: UISwitch! @IBOutlet weak var damageImagesCollectionView: UICollectionView! var damageImages = [UIImage]() var alreadyCompleted = false var alreadyTakenImage: UIImage? var delegate: ASLogDamageViewControllerDelegate? var vehicleSection: String! var carSection: vehicleDamageSection! let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() paintLabel.hidden = true paintSwitch.hidden = true bodyWorkLabel.hidden = true bodyWorkSwitch.hidden = true mechanicalLabel.hidden = true mechanicalSwitch.hidden = true title = carSection.sectionName self.view.addSubview(damageImagesCollectionView) damageImagesCollectionView.dataSource = self if carSection.alreadycompleted == true { // imageView.image = carSection.damageImage damageImages = carSection.damageImages if carSection.isDamaged == true { damageSwitch.on = true paintLabel.hidden = false paintSwitch.hidden = false paintSwitch.on = carSection.paintDamage bodyWorkLabel.hidden = false bodyWorkSwitch.hidden = false bodyWorkSwitch.on = carSection.bodyWorkDamage mechanicalLabel.hidden = false mechanicalSwitch.hidden = false mechanicalSwitch.on = carSection.mechanicalDamage } notesTextView.text = carSection.damageNotes } else { takePicture() } imagePicker.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // image picking doesn't work in landscape mode. // @IBAction func chooseExistingImage(sender: UIButton){ //// let picker = UIImagePickerController() //// picker.delegate = self //// picker.sourceType = .PhotoLibrary //// //// presentViewController(picker, animated: true, completion: nil) // imagePicker.allowsEditing = false // imagePicker.sourceType = .PhotoLibrary // // presentViewController(imagePicker, animated: true, completion: nil) // // } @IBAction func takePicture(){ let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .Camera presentViewController(picker, animated: true, completion: nil) } @IBAction func save(){ carSection.alreadycompleted = true carSection.isDamaged = damageSwitch.on carSection.paintDamage = paintSwitch.on carSection.bodyWorkDamage = bodyWorkSwitch.on carSection.mechanicalDamage = mechanicalSwitch.on carSection.damageNotes = notesTextView.text delegate?.saveDamage(carSection!) self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func cancel(){ self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func toggleDamage(){ if damageSwitch.on == false { paintLabel.hidden = true paintSwitch.hidden = true bodyWorkLabel.hidden = true bodyWorkSwitch.hidden = true mechanicalLabel.hidden = true mechanicalSwitch.hidden = true } else if damageSwitch.on == true { paintLabel.hidden = false paintSwitch.hidden = false bodyWorkLabel.hidden = false bodyWorkSwitch.hidden = false mechanicalLabel.hidden = false mechanicalSwitch.hidden = false } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let imageTaken = info[UIImagePickerControllerOriginalImage] as! UIImage // imageView.image = imageTaken damageImages.append(imageTaken) damageImagesCollectionView.reloadData() carSection?.damageImage = imageTaken carSection?.damageImages.append(imageTaken) dismissViewControllerAnimated(true, completion: nil) } func chosenNote(text: String) { print("this is the text \(text)", terminator: "") notesTextView.text = notesTextView.text + text } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return damageImages.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! RepairImageCollectionViewCell cell.repairImage.image = damageImages[indexPath.row] return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "Add Note" { let navController = segue.destinationViewController as! UINavigationController let popoverController = navController.viewControllers.first as! ASNotePopoverController popoverController.delegate = self } } }
mit
b78600374f8ffd9f8317727e7930d231
33.543011
177
0.648405
5.538793
false
false
false
false
zhenghao58/On-the-road
OnTheRoadB/TripImageHelper.swift
1
3172
// // TripImageHelper.swift // OnTheRoadB // // Created by Cunqi.X on 11/29/14. // Copyright (c) 2014 CS9033. All rights reserved. // import UIKit class TripImageHelper: NSObject,UIImagePickerControllerDelegate, UINavigationControllerDelegate { init(viewController: AddNewTripDetailViewController) { super.init() fileHelper = FileHelper() fileHelper.setCurrentFolderPath(viewController.currentTrip.name) self.viewController = viewController imageData.addObject(UIImage(named: defaultAddImagePath)!) imagePicker = UIImagePickerController() imagePicker.delegate = self } /*Important method of creating cell*/ func generateNewCollectionCell(collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as TripImageCell cell.tag = indexPath.row cell.deleteBtn.tag = indexPath.row cell.thumbNail.image = (imageData.objectAtIndex(indexPath.row) as UIImage) cell.deleteBtn.addTarget(self, action: "deleteCurrentImage:", forControlEvents: UIControlEvents.TouchUpInside) if(isEditMode) { if(indexPath.row == getLastIndexOfImageData()) { cell.deleteBtn.hidden = true }else { cell.deleteBtn.hidden = false } }else { cell.deleteBtn.hidden = true } return cell } func getImagePicker() -> UIImagePickerController { return imagePicker } func activeEditMode() { isEditMode = !isEditMode viewController.imageCv.reloadData() } /*Implement Delegate & DataSource Method*/ func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { let index = getLastIndexOfImageData() imageData.insertObject(image, atIndex: index) imagePath.insertObject(fileHelper.generateRelativePath("Day\(viewController.currentDay)"), atIndex: index) viewController.imageCv.reloadData() picker.dismissViewControllerAnimated(true, completion: nil) } func deleteCurrentImage(sender: AnyObject) { let cell = sender.superview!!.superview as TripImageCell let indexPath = viewController.imageCv.indexPathForCell(cell) imageData.removeObjectAtIndex(indexPath!.row) imagePath.removeObjectAtIndex(indexPath!.row) viewController.imageCv.deleteItemsAtIndexPaths([indexPath!]) } /*get & set method*/ func getImageData() -> NSMutableArray { return imageData } func getLastIndexOfImageData() -> Int { return imageData.count - 1 } func getImagePath() -> NSMutableArray { return imagePath } func getFileHelper() -> FileHelper { return fileHelper } /*Global & Local constant*/ private let defaultAddImagePath = "addPhoto.png" private let cellIdentifier = "imageCell" /*Local Varible*/ private var fileHelper: FileHelper! private var imageData: NSMutableArray = NSMutableArray() private var imagePath: NSMutableArray = NSMutableArray() private var tagIndex = -1 //use nextTag() method to increase the count private var isEditMode = false private var imagePicker: UIImagePickerController! private var viewController: AddNewTripDetailViewController! }
mit
eabb88343cefbcddb8d5edc40956693c
28.37037
140
0.764817
4.357143
false
false
false
false
PureSwift/Cacao
Sources/Cacao/UITableViewCell.swift
1
21236
// // UITableViewCell.swift // Cacao // // Created by Alsey Coleman Miller on 6/26/17. // import Foundation #if os(iOS) import UIKit import CoreGraphics #else import Silica #endif /// A cell in a table view. /// /// This class includes properties and methods for setting and managing cell content /// and background (including text, images, and custom views), managing the cell /// selection and highlight state, managing accessory views, and initiating the /// editing of the cell contents. open class UITableViewCell: UIView { // MARK: - Initializing a `UITableViewCell` Object /// Initializes a table cell with a style and a reuse identifier and returns it to the caller. public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.style = style self.reuseIdentifier = reuseIdentifier // while `UIView.init()` creates a view with an empty frame, // UIKit creates a {0,0, 320, 44} cell with this initializer super.init(frame: CGRect(origin: .zero, size: UITableViewCell.defaultSize)) self.setupTableViewCellCommon() } #if os(iOS) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } #endif // MARK: - Reusing Cells /// A string used to identify a cell that is reusable. public let reuseIdentifier: String? /// Prepares a reusable cell for reuse by the table view'ย€ย™s delegate. open func prepareForReuse() { } // default implementation is empty // MARK: - Managing the Predefined Content /// Returns the label used for the main textual content of the table cell. public var textLabel: UILabel? { return _contentView.textLabel } /// Returns the secondary label of the table cell if one exists. public var detailTextLabel: UILabel? { return _contentView.detailTextLabel } /// Returns the image view of the table cell. public var imageView: UIImageView? { return _contentView.imageView } // MARK: - Accessing Views of the Cell Object /// Returns the content view of the cell object. /// /// The content view of a `UITableViewCell` object is the default superview for content displayed by the cell. /// If you want to customize cells by simply adding additional views, you should add them to the content view /// so they will be positioned appropriately as the cell transitions into and out of editing mode. public var contentView: UIView { return _contentView } private lazy var _contentView: UITableViewCellContentView = UITableViewCellContentView(frame: CGRect(origin: .zero, size: self.bounds.size), cell: self) /// The view used as the background of the cell. /// /// The default is `nil` for cells in plain-style tables (`.plain`) /// and non-nil for grouped-style tables (`.grouped`). /// `UITableViewCell` adds the background view as a subview behind all other views and uses its current frame location. public var backgroundView: UIView? /// The view used as the background of the cell when it is selected. /// /// The default is nil for cells in plain-style tables (`.plain`) /// and non-nil for section-group tables (`.grouped`). /// `UITableViewCell` adds the value of this property as a subview only when the cell is selected. /// It adds the selected background view as a subview directly above the background view (`backgroundView`) /// if it is not nil, or behind all other views. /// Calling `setSelected(_:animated:)` causes the selected background view to animate in and out with an alpha fade. public var selectedBackgroundView: UIView? /// The background view to use for a selected cell when the table view allows multiple row selections. public var multipleSelectionBackgroundView: UIView? // MARK: - Managing Accessory Views /// The type of standard accessory view the cell should use (normal state). /// /// The accessory view appears in the right side of the cell in the table viewโ€™s normal (default) state. /// The standard accessory views include the disclosure chevron; for a description of valid accessoryType constants, /// see `UITableViewCellAccessoryType`. /// The default is `.none`. /// If a custom accessory view is set through the accessoryView property, the value of this property is ignored. /// If the cell is enabled and the accessory type is detailDisclosureButton, the accessory view tracks touches and, /// when tapped, sends the data-source object a `tableView(_:accessoryButtonTappedForRowWith:)` message. /// /// The accessory-type image cross-fades between normal and editing states if it set for both states; /// use the `editingAccessoryType` property to set the accessory type for the cell during editing mode. /// If this property is not set for both states, the cell is animated to slide in or out, as necessary. public var accessoryType: UITableViewCellAccessoryType = .none /// A view that is used, typically as a control, on the right side of the cell (normal state). public var accessoryView: UIView? /// The type of standard accessory view the cell should use in the table viewโ€™s editing state. public var editingAccessoryType: UITableViewCellAccessoryType = .none /// A view that is used typically as a control on the right side of the cell when it is in editing mode. public var editingAccessoryView: UIView? // MARK: - Managing Cell Selection and Highlighting /// The style of selection for a cell. public var selectionStyle: UITableViewCellSelectionStyle = .blue /// A Boolean value that indicates whether the cell is selected. public var isSelected: Bool = false /// Sets the selected state of the cell, optionally animating the transition between states. public func setSelected(_ selected: Bool, animated: Bool) { } /// A Boolean value that indicates whether the cell is highlighted. public var isHighlighted: Bool = false /// Sets the highlighted state of the cell, optionally animating the transition between states. public func setHighlighted(_ highlighted: Bool, animated: Bool) { } // MARK: - Editing the Cell /// A Boolean value that indicates whether the cell is in an editable state. public var isEditing: Bool = false /// Toggles the receiver into and out of editing mode. public func setEditing(_ editing: Bool, animated: Bool) { } /// The editing style of the cell. public internal(set) var editingStyle: UITableViewCellEditingStyle = .none /// Returns whether the cell is currently showing the delete-confirmation button. /// /// When users tap the deletion control (the red circle to the left of the cell), /// the cell displays a "Delete" button on the right side of the cell; this string is localized. public internal(set) var showingDeleteConfirmation: Bool = false /// A Boolean value that determines whether the cell shows the reordering control. /// /// The reordering control is gray, multiple horizontal bar control on the right side of the cell. /// Users can drag this control to reorder the cell within the table. /// The default value is `false`. /// If the value is `true`, the reordering control temporarily replaces any accessory view. public var showsReorderControl: Bool = false // MARK: - Managing Content Indentation /// The indentation level of the cellโ€™s content. /// /// The default value of the property is zero (no indentation). /// Assigning a positive value to this property indents the cellโ€™s content from /// the left edge of the cell separator. The amount of indentation is equal to /// the indentation level multiplied by the value in the `indentationWidth` property. public var indentationLevel: Int = 0 /// The width for each level of indentation of a cell'ย€ย™s content. /// /// The default indentation width is 10.0 points. public var indentationWidth: CGFloat = 10 /// A Boolean value that controls whether the cell background is indented when the table view is in editing mode. /// /// The default value is `true`. /// This property is unrelated to `indentationLevel`. /// The delegate can override this value in `tableView(_:shouldIndentWhileEditingRowAt:)`. /// This property has an effect only on table views created in the grouped style (`.grouped`); /// it has no effect on plain table views. public var shouldIndentWhileEditing: Bool = true /// The inset values for the cellโ€™s content. /// /// You can use this property to add space between the current cellโ€™s contents and the left and right edges of the table. /// Positive inset values move the cell content and cell separator inward and away from the table edges. /// Negative values are treated as if the inset is set to `0`. /// /// Only the left and right inset values are respected; the top and bottom inset values are ignored. /// The value assigned to this property takes precedence over any default separator insets set on the table view. public var separatorInset: UIEdgeInsets = UITableView.defaultSeparatorInset // MARK: - Overriden Methods open override func layoutSubviews() { super.layoutSubviews() // layoutFloatingContentView() // UIKit`-[UITableViewCellLayoutManager layoutSubviewsOfCell:]: // UIKit`-[UITableViewCell layoutSubviews]: // https://gist.github.com/colemancda/7d39b640cca32849e0d33c17f8761270 UITableViewCellLayoutManager.layoutSubviews(of: self) } // MARK: - Private internal static let defaultSize = CGSize(width: 320, height: UITableView.defaultRowHeight) internal weak var tableView: UITableView? @_versioned internal let style: UITableViewCellStyle // added as subview in `init()` fileprivate lazy var separatorView: UITableViewCellSeparatorView = UITableViewCellSeparatorView() internal func configureSeparator(style: UITableViewCellSeparatorStyle, color: UIColor?) { separatorView.style = style separatorView.color = color } private func setupTableViewCellCommon() { // add mandatory subviews self.addSubview(separatorView) self.addSubview(contentView) // layout subviews self.layoutIfNeeded() } /// Arranges the subviews in the proper order private func orderSubviews() { if let view = selectedBackgroundView { sendSubview(toBack: view) } if let view = backgroundView { sendSubview(toBack: view) } bringSubview(toFront: contentView) if let view = accessoryView { bringSubview(toFront: view) } bringSubview(toFront: separatorView) } /// Called after default text label's text is changed fileprivate func contentViewLabelTextDidChange(_ label: UITableViewLabel) { setNeedsLayout() } } // MARK: - Supporting Types public enum UITableViewCellAccessoryType: Int { case none case disclosureIndicator case detailDisclosureButton case checkmark } public enum UITableViewCellSeparatorStyle: Int { case none case singleLine case singleLineEtched } public enum UITableViewCellStyle: Int { case `default` case value1 case value2 case subtitle } public enum UITableViewCellSelectionStyle: Int { case none case blue case gray } public enum UITableViewCellEditingStyle: Int { case none case delete case insert } // MARK: - Private Supporting Types internal final class UITableViewCellContentView: UIView { private(set) weak var cell: UITableViewCell! /// Returns the label used for the main textual content of the table cell. private(set) weak var textLabel: UITableViewLabel? /// Returns the secondary label of the table cell if one exists. private(set) weak var detailTextLabel: UITableViewLabel? /// Returns the image view of the table cell. private(set) weak var imageView: UIImageView? var isLayoutEngineSuspended: Bool = false required init(frame: CGRect, cell: UITableViewCell) { super.init(frame: frame) self.cell = cell // setup predefined views self.tableViewCellContentViewCommonSetup() } #if os(iOS) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } #endif private func tableViewCellContentViewCommonSetup() { // should only be called once assert(self.textLabel == nil) guard let cell = self.cell else { fatalError("No cell configured") } let textLabel = UITableViewCellLayoutManager.textLabel(for: cell) let detailTextLabel = UITableViewCellLayoutManager.detailTextLabel(for: cell) let imageView = UITableViewCellLayoutManager.imageView(for: cell) // add subviews let contentSubviews: [UIView?] = [textLabel, detailTextLabel, imageView] // add as subviews to content view contentSubviews.forEach { if let view = $0 { self.addSubview(view) } } // set properties self.textLabel = textLabel self.detailTextLabel = detailTextLabel self.imageView = imageView } override func layoutSubviews() { let contentFrame = self.frame let style = self.cell.style // layout default subviews switch style { case .default: let imageWidth = imageView?.image?.size.width ?? 0.0 let imageViewFrame = CGRect(x: 5, y: 0, width: imageWidth, height: contentFrame.size.height) let textLabelX = imageViewFrame.origin.x + 15 let textLabelFrame = CGRect(x: textLabelX, y: 0, width: contentFrame.size.width - textLabelX, height: contentFrame.size.height) imageView?.frame = imageViewFrame textLabel?.frame = textLabelFrame assert(detailTextLabel == nil, "No detail text label for \(style)") case .subtitle: // FIXME: subtitle layout break case .value1: // FIXME: value1 layout break case .value2: // FIXME: value2 layout break } } } /// Actual name is `_UITableViewCellSeparatorView` internal typealias UITableViewCellSeparatorView = _UITableViewCellSeparatorView internal final class _UITableViewCellSeparatorView: UIView { var style: UITableViewCellSeparatorStyle = .none { didSet { setNeedsDisplay() isHidden = style == .none } } var color: UIColor? { didSet { setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) self.isHidden = true } #if os(iOS) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } #endif override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext(), let color = self.color, style != .none else { return } color.setStroke() let line = UIBezierPath() line.move(to: .zero) line.addLine(to: CGPoint(x: bounds.size.width, y: 0)) line.lineWidth = 1 switch style { case .none: break case .singleLine: line.stroke() case .singleLineEtched: context.saveGState() context.setLineDash(phase: 0, lengths: [2, 2]) line.stroke() context.restoreGState() } } } internal final class UITableViewCellSelectedBackground: UIView { } internal struct UITableViewCellLayoutManager { static func layoutSubviews(of cell: UITableViewCell) { let bounds = cell.bounds let isSeparatorVisible = cell.separatorView.isHidden == false var contentFrame = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - (isSeparatorVisible ? 1 : 0)) if let accessoryView = cell.accessoryView { /// calculate frame var frame = CGRect(x: bounds.size.width, y: 0, width: 0, height: 0) frame.size = accessoryView.sizeThatFits(bounds.size) frame.origin.x = bounds.size.width - frame.size.width frame.origin.y = round( 0.5 * (bounds.size.height - frame.size.height)) // set accessory frame accessoryView.frame = frame // adjust content frame based on accessory contentFrame.size.width = frame.origin.x - 1 } // set content frames cell.backgroundView?.frame = contentFrame cell.selectedBackgroundView?.frame = contentFrame; cell.contentView.frame = contentFrame; // set separator frame let separatorFrame = CGRect(x: cell.separatorInset.left, y: bounds.size.height - 1, width: bounds.size.width - (cell.separatorInset.right + cell.separatorInset.left), height: 1) cell.separatorView.frame = isSeparatorVisible ? separatorFrame : .zero } @inline(__always) static private func createLabel(for cell: UITableViewCell) -> UITableViewLabel { return UITableViewLabel(frame: .zero, cell: cell) } static func textLabel(for cell: UITableViewCell) -> UITableViewLabel { let style = cell.style let label = createLabel(for: cell) switch style { case .default: break case .subtitle: break case .value1: break case .value2: break } return label } static func detailTextLabel(for cell: UITableViewCell) -> UITableViewLabel? { let style = cell.style switch style { case .default: return nil case .subtitle: let label = createLabel(for: cell) return label case .value1: let label = createLabel(for: cell) return label case .value2: let label = createLabel(for: cell) return label } } static func imageView(for cell: UITableViewCell) -> UIImageView? { let style = cell.style switch style { case .default: let imageView = UIImageView() return imageView case .subtitle: let imageView = UIImageView() return imageView case .value1, .value2: return nil } } /* static func backgroundEndingRect(for cell: UITableViewCell) -> CGRect { }*/ } internal class UITableViewLabel: UILabel { private(set) weak var cell: UITableViewCell! override var text: String? { didSet { guard text != oldValue else { return } // inform cell of text change cell?.contentViewLabelTextDidChange(self) } } required init(frame: CGRect, cell: UITableViewCell) { super.init(frame: frame) self.cell = cell } #if os(iOS) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } #endif } // MARK: - ReusableView Protocol internal protocol ReusableView { var reuseIdentifier: String? { get } func prepareForReuse() } extension UITableViewCell: ReusableView { }
mit
e19916145ac9b2ecbca545a933d45ef8
31.200303
156
0.615174
5.385787
false
false
false
false
malaonline/iOS
mala-ios/Resource/Application/Strings.swift
1
14978
// // String.swift // mala-ios // // Created by ็Ž‹ๆ–ฐๅฎ‡ on 2017/2/28. // Copyright ยฉ 2017ๅนด Mala Online. All rights reserved. // // Generated using SwiftGen, by O.Halligon โ€” https://github.com/AliSoftware/SwiftGen import Foundation enum L10n { /// ๅฎŒ่ฏพ่ฏ„ไปท static let ableToComment = L10n.tr("Able to comment") /// ๅ…ณไบŽ้บป่พฃ่€ๅธˆ static let aboutMala = L10n.tr("About mala") /// ๆ”ฏไป˜ๅฎ static let alipay = L10n.tr("Alipay") /// ๆ”ฏไป˜ๅฎๆ”ฏไป˜ static let alipayPayment = L10n.tr("Alipay payment") /// ๆ”ฏไป˜ๅฎไบŒ็ปด็ ่Žทๅ–้”™่ฏฏ static let alipayQRCodeInfoGetError = L10n.tr("Alipay QRCode info get error") /// ๆ”ฏไป˜ๅฎๅฎ‰ๅ…จๆ”ฏไป˜ static let alipaySecurityPayment = L10n.tr("Alipay security payment") /// ๅ–ๆถˆ static let cancel = L10n.tr("Cancel") /// ๅ–ๆถˆ่ฎขๅ• static let cancelOrder = L10n.tr("Cancel order") /// ๅŽปๆŸฅ็œ‹ static let check = L10n.tr("Check") /// ๆ•ฌ่ฏทๆœŸๅพ… static let comingSoon = L10n.tr("ComingSoon") /// ไธŠๅฎŒ่ฏพๅŽๅ†ๆฅ่ฟ™้‡Œๅง static let commentLater = L10n.tr("Comment later") /// ็กฎ่ฎค่ฎขๅ• static let confirmOrder = L10n.tr("Confirm order") /// ้”™้ข˜ๆœฌ static let correctedRecord = L10n.tr("corrected record") /// ้’ˆๅฏนๆฏไธชๅญฆๅ‘˜่ฎฐๅฝ•ๅนถ็”Ÿๆˆ้”™้ข˜ๆœฌ๏ผŒๆ–นไพฟๆŸฅๆ‰พ็Ÿฅ่ฏ†ๆผๆดž๏ผŒๅนถ็”Ÿๆˆ้’ˆๅฏนๆ€ง็ปƒไน  static let correctedRecordDesc = L10n.tr("corrected record desc") /// ๅฟƒ็†่พ…ๅฏผ static let counseling = L10n.tr("Counseling") /// ๅ…่ดน่Žทๅพ—ไธ“ไธšๅฟƒ็†ๅ’จ่ฏขๅธˆไธ€ๅฏนไธ€ๅฟƒ็†่พ…ๅฏผ๏ผŒไฟƒ่ฟ›ๅญฆๅ‘˜่บซๅฟƒๅฅๅบทๆˆ้•ฟ static let counselingDesc = L10n.tr("Counseling desc") /// ๅฅ–ๅญฆ้‡‘ static let coupon = L10n.tr("Coupon") /// ๅฅ–ๅญฆ้‡‘ไฝฟ็”จไฟกๆฏๆœ‰่ฏฏ๏ผŒ่ฏท้‡ๆ–ฐ้€‰ๆ‹ฉ static let couponInfoError = L10n.tr("Coupon info error") /// ๅฅ–ๅญฆ้‡‘ไฝฟ็”จ่ง„ๅˆ™ static let couponRule = L10n.tr("Coupon rule") /// ๅฅ–ๅญฆ้‡‘ๅณๅฐ†ๅˆฐๆœŸ static let couponWillExpire = L10n.tr("Coupon will expire") /// ่ฏพ็จ‹ๅ˜ๅŠจ static let courseChanged = L10n.tr("Course changed") /// ่ฏพ็จ‹่ดญไนฐ static let courseChoosing = L10n.tr("Course choosing") /// ๆ‰€้€‰่ฏพ็จ‹ๅ้ขๅทฒๆปก๏ผŒ่ฏท้€‰ๆ‹ฉๅ…ถไป–่ฏพ็จ‹ static let courseQuotaSoldOut = L10n.tr("Course quota sold out") /// ่ฏพๅ‰้€š็Ÿฅ static let courseRemind = L10n.tr("Course remind") /// ๆ‚จๆƒณ่ฆ่ดญไนฐ็š„่ฏพ็จ‹ๅทฒ่ขซไป–ไบบๆŠขไนฐ๏ผŒๆ”ฏไป˜้‡‘้ขๅฐ†ๅŽŸ่ทฏ้€€ๅ›ž static let courseSoldout = L10n.tr("Course soldout") /// ็กฎ่ฎคๅ–ๆถˆ่ฎขๅ•ๅ—๏ผŸ static let doYouWantToCancelThisOrder = L10n.tr("Do you want to cancel this order") /// ็กฎ่ฎค้€€ๅ‡บๅฝ“ๅ‰่ดฆๅทๅ—๏ผŸ static let doYouWantToLogout = L10n.tr("Do you want to logout") /// ไธไฝฟ็”จๅฅ–ๅญฆ้‡‘ static let donTUseCoupon = L10n.tr("Don't use coupon") /// ๆต‹่ฏ„ๅปบๆกฃๆœๅŠก static let evaluation = L10n.tr("Evaluation") /// ่€ƒๅ‰ไธฒ่ฎฒ static let examOutline = L10n.tr("Exam outline") /// ไธ“ไธš่งฃ่ฏป่€ƒ่ฏ•่ถ‹ๅŠฟ๏ผŒๅ‰–ๆž่€ƒ่ฏ•้šพ็‚นๅˆ†ไบซ้ซ˜ๅˆ†็ป้ชŒใ€‚่ฟ˜ๆœ‰ๅ‘ฝ้ข˜ไธ“ๅฎถ่ฟ›่กŒไธญ้ซ˜่€ƒๆŠผ้ข˜ static let examOutlineDesc = L10n.tr("Exam outline desc") /// ็ญ›้€‰็ป“ๆžœ static let filterResult = L10n.tr("Filter result") /// ่Žทๅ–้ชŒ่ฏ็  static let getVerificationCode = L10n.tr("Get verification code") /// ๅŽป็™ปๅฝ• static let goToLogin = L10n.tr("Go to login") /// ๅŽปๆ›ดๆ”น static let goto = L10n.tr("Goto") /// ่ฏทๅ†™ไธ‹ๅฏน่€ๅธˆ็š„ๆ„Ÿๅ—ๅง๏ผŒๅฏนไป–ไบบ็š„ๅธฎๅŠฉๅพˆๅคงๅ“ฆ~ๆœ€ๅคšๅฏ่พ“ๅ…ฅ200ๅญ— static let inputComment = L10n.tr("Input comment") /// ่ฏท่พ“ๅ…ฅ้ชŒ่ฏ็  static let inputVerificationCode = L10n.tr("Input verification code") /// ่ฏท่พ“ๅ…ฅๆ‰‹ๆœบๅท static let inputYourNumber = L10n.tr("Input your number") /// ๆ‰‹ๆœบๅท้”™่ฏฏ static let invalidNumber = L10n.tr("Invalid number") /// ็Ÿฅ้“ไบ† static let later = L10n.tr("Later") /// ็‰น่‰ฒ่ฎฒๅบง static let lectures = L10n.tr("Lectures") /// ็‰น้‚€ๅ„้ข†ๅŸŸไธ“ๅฎถ่ฟ›่กŒๅคš็ง็‰น่‰ฒ่ฎฒๅบง๏ผŒ่ฅๅ…ปๅฅๅบทใ€ๅฎถๅบญๆ•™่‚ฒใ€้ซ˜ๆ•ˆๅญฆไน ๅบ”ๆœ‰ๅฐฝๆœ‰ static let lecturesDesc = L10n.tr("lectures desc") /// ๅŒๅธˆ็›ดๆ’ญ static let live = L10n.tr("Live") /// ๅŒๅธˆ่ฏพ็จ‹ๆดปๅŠจ static let liveActivities = L10n.tr("Live activities") /// ่ฏพ็จ‹้กต static let liveCourse = L10n.tr("Live course") /// ๆญฃๅœจๅŠ ่ฝฝ static let loading = L10n.tr("Loading") /// ็™ปๅฝ• static let login = L10n.tr("Login") /// ้€€ๅ‡บ็™ปๅฝ• static let logout = L10n.tr("Logout") /// ้€€ ๅ‡บ static let logoutText = L10n.tr("Logout text") /// ้บป่พฃ่€ๅธˆ static let mala = L10n.tr("Mala") /// ใ€Š้บป่พฃ่€ๅธˆ็”จๆˆทๆœๅŠกๅ่ฎฎใ€‹ static let malaUserProtocol = L10n.tr("Mala user protocol") /// ไผšๅ‘˜ไธ“ไบซ static let member = L10n.tr("Member") /// ๅฝ“ๅ‰ๆ— ๆณ•่ฎฟ้—ฎ้ข˜็›ฎๆ•ฐๆฎ๏ผŒ่ฏท็จๅŽๅ†่ฏ• static let memberServerError = L10n.tr("Member server error") /// ๆˆ‘็š„ๆ”ถ่— static let myCollect = L10n.tr("My collect") /// ๆˆ‘็š„่ฏ„ไปท static let myComment = L10n.tr("My comment") /// ๆˆ‘็š„ๅฅ–ๅญฆ้‡‘ static let myCoupon = L10n.tr("My coupon") /// ๆˆ‘็š„่ฎขๅ• static let myOrder = L10n.tr("My order") /// ็ฝ‘็ปœๅ‡บ้”™ๅ•ฆ๏ฝž static let networkError = L10n.tr("Network error") /// ็ฝ‘็ปœ็Žฏๅขƒ่พƒๅทฎ๏ผŒ่ฏท็จๅŽ้‡่ฏ• static let networkNotReachable = L10n.tr("Network notReachable") /// ๆ‚จๆ”ถ่—็š„่€ๅธˆไผšๅ‡บ็Žฐๅœจ่ฟ™้‡Œๅ“ฆ static let noCollect = L10n.tr("No collect") /// ๅฝ“ๅ‰ๆš‚ๆ— ่ฏ„ไปท static let noComment = L10n.tr("No comment") /// ๆ‚จๅฝ“ๅ‰ๆฒกๆœ‰ๅฅ–ๅญฆ้‡‘ๅ“ฆ๏ผ static let noCoupon = L10n.tr("No coupon") /// ๆš‚ๆ—ถ่ฟ˜ๆฒกๆœ‰่ฏพ็จ‹ๅ“ฆ static let noCourse = L10n.tr("No course") /// ๅฝ“ๅ‰ๅŸŽๅธ‚ๆš‚ๆ— ็›ดๆ’ญ่ฏพ็จ‹๏ผ static let noLiveCourse = L10n.tr("No live course") /// ๆฒกๆœ‰่ฎขๅ• static let noOrder = L10n.tr("No order") /// ๅฝ“ๅ‰ๅŸŽๅธ‚ๆฒกๆœ‰่€ๅธˆ๏ผ static let noTeacher = L10n.tr("No teacher") /// ๅฝ“ๅ‰ๆš‚ๆ— ๅŒน้…่€ๅธˆ static let noMatchTeacher = L10n.tr("No match teacher") /// ๆš‚ไธๅ–ๆถˆ static let notNow = L10n.tr("Not now") /// ้€š็Ÿฅๆถˆๆฏ static let notifyMessage = L10n.tr("Notify message") /// ่ฎขๅ•ๅ–ๆถˆๅคฑ่ดฅ static let orderCanceledFailure = L10n.tr("Order canceled failure") /// ่ฎขๅ•ๅ–ๆถˆๆˆๅŠŸ static let orderCanceledSuccess = L10n.tr("Order canceled success") /// ่ฎขๅ•่ฏฆๆƒ… static let orderDetail = L10n.tr("Order detail") /// ่ฎขๅ•ๅทฒๅคฑๆ•ˆ๏ผŒ่ฏท้‡ๆ–ฐไธ‹ๅ• static let orderExpired = L10n.tr("Order expired") /// ่ฎขๅ•ไฟกๆฏๆœ‰่ฏฏ๏ผŒ่ฏทๅˆทๆ–ฐๅŽ้‡่ฏ• static let orderInfoError = L10n.tr("Order info error") /// ่ฎขๅ•็Šถๆ€้”™่ฏฏ๏ผŒ่ฏท้‡่ฏ• static let orderStatusError = L10n.tr("Order status error") /// ๅ…ถๅฎƒ static let other = L10n.tr("Other") /// ๅฎถ้•ฟไปฃไป˜ static let payByParents = L10n.tr("Pay by Parents") /// ๆ‰ซไบŒ็ปด็ ๆ”ฏไป˜ static let payByQRCode = L10n.tr("Pay by QRCode") /// ๆ”ฏไป˜ๅฎŒๆˆ static let paymentCompleted = L10n.tr("Payment completed") /// ๆ”ฏไป˜ๅคฑ่ดฅ๏ผŒ่ฏท้‡่ฏ•๏ผ static let paymentFailure = L10n.tr("Payment failure") /// ๆ”ฏไป˜ๅทฒๅ–ๆถˆ static let paymentHasBeenCanceled = L10n.tr("Payment has been canceled") /// ๆ”ฏไป˜ไฟกๆฏ่Žทๅ–ไธญ๏ผŒ่ฎขๅ•ไฟกๆฏๅฐ†ไผš็จๅŽๆ›ดๆ–ฐ static let paymentInfoFetching = L10n.tr("Payment info fetching") /// ๆญๅ–œๆ‚จๅทฒๆ”ฏไป˜ๆˆๅŠŸ๏ผๆ‚จ็š„่ฏพ่กจๅทฒ็ปๅฎ‰ๆŽ’ๅฅฝ๏ผŒๅฟซๅŽปๆŸฅ็œ‹ๅง๏ผ static let paymentSuccess = L10n.tr("Payment success") /// ่ฏพๆ—ถไฟกๆฏๆœ‰่ฏฏ static let periodError = L10n.tr("Period error") /// ๆ‰‹ๆœบๅท static let phoneNumber = L10n.tr("Phone number") /// ๅŽปๆŠฅๅ static let pickCourse = L10n.tr("Pick course") /// ้€‰ๆ‹ฉ็…ง็‰‡ static let pickPhoto = L10n.tr("Pick photo") /// ่ฏท้€‰ๆ‹ฉๆŽˆ่ฏพๅนด็บง static let pleaseCheckGrade = L10n.tr("Please check grade") /// ่ฏพๆ—ถๆ•ฐไธๅพ—ๅฐ‘ไบŽๅทฒ้€‰ไธŠ่ฏพๆ—ถ้—ด static let pleaseCheckPeriod = L10n.tr("Please check period") /// ่ฏท้€‰ๆ‹ฉไธŠ่ฏพๅœฐ็‚น static let pleaseCheckSchool = L10n.tr("Please check school") /// ่ฏท้€‰ๆ‹ฉไธŠ่ฏพๆ—ถ้—ด static let pleaseCheckTimeslots = L10n.tr("Please check timeslots") /// ่ฏทๅฎŒๆˆไป˜ๆฌพๅŽ๏ผŒ็‚นๅ‡ปๆ”ฏไป˜ๅฎŒๆˆ static let pleaseCompleteThePayment = L10n.tr("Please complete the payment") /// ๅฎถ้•ฟๅฎŒๆˆๆ”ฏไป˜ๅŽ ็‚นๅ‡ปๆ”ฏไป˜ๅฎŒๆˆๆŒ‰้’ฎ static let pleaseCompleteThePaymentBeforeCheckIt = L10n.tr("Please complete the payment before check it") /// ๆˆ‘็š„ static let profile = L10n.tr("Profile") /// ่ฝป่งฆไธŠ้ขโ€œ็™ปๅฝ•โ€ๆŒ‰้’ฎ๏ผŒๅณ่กจ็คบไฝ ๅทฒๅŒๆ„ static let protocolDesc = L10n.tr("Protocol desc") /// ๆ”ฏไป˜ๅ‡ญ่ฏ่Žทๅ–้”™่ฏฏ static let qrCodeCredentialGetError = L10n.tr("QRCode credential get error") /// ไบŒ็ปด็ ่Žทๅ–้”™่ฏฏ static let qrCodeGetError = L10n.tr("QRCode get error") /// ๆ”ฏไป˜ไฟกๆฏ่Žทๅ–้”™่ฏฏ static let qrCodePaymentInfoGetError = L10n.tr("QRCode payment info get error") /// ้‡ๆ–ฐ้€‰่ฏพ static let reChoosing = L10n.tr("ReChoosing") /// ๅˆทๆ–ฐ static let refresh = L10n.tr("Refresh") /// ้€€่ดนๆˆๅŠŸ static let refundSuccess = L10n.tr("Refund success") /// ้‡ๆ–ฐ็™ปๅฝ• static let relogin = L10n.tr("Relogin") /// ๅญฆไน ๆŠฅๅ‘Š static let report = L10n.tr("Report") /// ๅ…จ้ข่ฎฐๅฝ•ๅญฆ็”Ÿๅญฆไน ๆ•ฐๆฎ๏ผŒๆ–นไพฟๅฎถ้•ฟใ€้šๆ—ถๆŸฅ็œ‹๏ผŒๅ……ๅˆ†ไบ†่งฃๅญฆๅ‘˜็Ÿฅ่ฏ†็‚นๆŽŒๆกๆƒ…ๅ†ต static let reportDesc = L10n.tr("Report desc") /// ๅญฆไน ๆŠฅๅ‘Šๆ ทๆœฌ static let reportSample = L10n.tr("Report sample") /// ่ฏท้‡ๆ–ฐ่ฎพๅฎš็ญ›้€‰ๆกไปถ๏ผ static let resetCondition = L10n.tr("Reset condition") /// ไฝฟ็”จ่ง„ๅˆ™ static let rule = L10n.tr("Rule") /// ่ฏพ่กจ static let schedule = L10n.tr("schedule") /// ่ฏฅ่€ๅธˆ้ƒจๅˆ†ๆ—ถๆฎตๅทฒ่ขซๅ ็”จ๏ผŒ่ฏท้‡ๆ–ฐ้€‰ๆ‹ฉไธŠ่ฏพๆ—ถ้—ด static let someTimeslotsHasBeenAllocated = L10n.tr("Some timeslots has been allocated") /// SPPSๆต‹่ฏ„ static let sppsTest = L10n.tr("SPPS test ") /// ๅฎšๆœŸ่ฟ›่กŒSPPSๆต‹่ฏ„๏ผŒๅ……ๅˆ†ไบ†่งฃๅญฆๅ‘˜ๅญฆไน ๆƒ…ๅ†ต static let sppsTestDesc = L10n.tr("SPPS test desc") /// ๅญฆ็”Ÿๅง“ๅ static let studentName = L10n.tr("Student name") /// ๆ‰ซ็ ๆ”ฏไป˜ static let sweepPayment = L10n.tr("Sweep payment") /// ๆ‹็…ง static let takePicture = L10n.tr("Take picture") /// ๅฟซๅŽป่€ๅธˆ่ฏฆๆƒ…้กตๆ”ถ่—ๅง static let takeSomeCollect = L10n.tr("take some collect") /// ็‚นๅ‡ป้‡่ฏ• static let tapToRetry = L10n.tr("Tap to retry") /// ๆ‰พ่€ๅธˆ static let teacher = L10n.tr("Teacher") /// ่€ๅธˆ็›ธๅ†Œ static let teacherAlbums = L10n.tr("Teacher albums") /// ่ดญ่ฏพๅคฑ่ดฅ๏ผ่ฏฅ่€ๅธˆๅทฒไธ‹ๆžถ๏ผŒๆ”ฏไป˜้‡‘้ขๅฐ†ๅŽŸ่ทฏ้€€ๅ›ž static let teacherOffShelves = L10n.tr("Teacher off shelves") /// ไธŠ่ฏพๆ—ถ้—ดไฟกๆฏๆœ‰่ฏฏ static let timeslotsError = L10n.tr("Timeslots error") /// ไธŠ่ฏพๆ—ถ้—ด่Žทๅ–ๆœ‰่ฏฏ๏ผŒ่ฏท้‡่ฏ• static let timeslotsGetError = L10n.tr("Timeslots get error") /// ๆ ‡้ข˜ static let title = L10n.tr("Title") /// ไปŠๅคฉ static let today = L10n.tr("Today") /// ไธ€ๅฏนไธ€ static let tuition = L10n.tr("Tuition") /// ่‡ชไน ้™ช่ฏป static let tutor = L10n.tr("Tutor") /// ไบซๅ—ไธ“ไธš่€ๅธˆๅ…่ดน้™ช่ฏปๆœๅŠก๏ผŒ้šๆ—ถ่งฃๅ†ณๅญฆไน ้—ฎ้ข˜ static let tutorDesc = L10n.tr("Tutor desc") /// ็”จๆˆท้ชŒ่ฏ้”™่ฏฏ๏ผŒ่ฏท้‡ๆ–ฐ็™ปๅฝ•๏ผ static let userAuthenticationError = L10n.tr("User authentication error") /// ้ชŒ่ฏ็  static let verificationCode = L10n.tr("Verification code") /// %02dsๅŽ่Žทๅ– static let verificationCodeCountdown = L10n.tr("Verification code countdown") /// ้ชŒ่ฏ็ ้”™่ฏฏ static let verificationCodeNotMatch = L10n.tr("Verification code not match") /// ้ชŒ่ฏ็ ๅ‘้€ๅคฑ่ดฅ static let verificationCodeSentFailure = L10n.tr("Verification code sent failure") /// ้ชŒ่ฏ็ ๅ‘้€ๆˆๅŠŸ static let verificationCodeSentSuccess = L10n.tr("Verification code sent success") /// ้ชŒ่ฏ static let verify = L10n.tr("Verify") /// ๆŸฅ็œ‹่ฎขๅ• static let viewOrder = L10n.tr("View order") /// ๅพฎไฟกๆ”ฏไป˜ static let weChatPayment = L10n.tr("WeChat payment") /// ๅพฎไฟกๆ”ฏไป˜ไบŒ็ปด็ ่Žทๅ–้”™่ฏฏ static let weChatQRCodeInfoGetError = L10n.tr("WeChat QRCode info get error") /// ๅพฎไฟกๅฟซๆทๆ”ฏไป˜ static let weChatShortcutPayment = L10n.tr("WeChat shortcut payment") /// ไฝ ๆœ‰ไธ€ๆกๆ–ฐๆถˆๆฏ static let youHaveANewMessage = L10n.tr("You have a new message") /// ๆ‚จๅทฒๆŠฅๅๅ‚ๅŠ ่ฏฅ่ฏพ็จ‹๏ผŒ่ฏทๅ‹ฟ้‡ๅค่ดญไนฐ static let youHaveBoughtThisCourse = L10n.tr("You have bought this course") /// ๆ‚จๆœ‰่ฎขๅ•ๅฐšๆœชๆ”ฏไป˜ static let youHaveSomeUnpaidOrder = L10n.tr("You have some unpaid order") /// ๆ‚จ่ฟ˜ๆฒกๆœ‰็™ปๅฝ• static let youNeedToLogin = L10n.tr("You need to login") enum Access { /// ๆ‹็…งๅคฑ่ดฅ static let camera = L10n.tr("access.camera") /// ๅœฐ็†ไฝ็ฝฎ่Žทๅ–ๅคฑ่ดฅ static let location = L10n.tr("access.location") /// ้บฆๅ…‹้ฃŽ่ฎฟ้—ฎๅคฑ่ดฅ static let mic = L10n.tr("access.mic") /// ็…ง็‰‡่ฎฟ้—ฎๅคฑ่ดฅ static let photo = L10n.tr("access.photo") enum Camera { /// ่ฏทๅœจ่ฎพ็ฝฎ-้š็ง-็›ธๆœบ้‡Œๆ‰“ๅผ€ๆƒ้™ static let desc = L10n.tr("access.camera.desc") } enum Location { /// ่ฏทๅœจ่ฎพ็ฝฎ-้š็ง-ๅฎšไฝๆœๅŠก้‡Œๆ‰“ๅผ€ๆƒ้™ static let desc = L10n.tr("access.location.desc") } enum Mic { /// ่ฏทๅœจ่ฎพ็ฝฎ-้š็ง-้บฆๅ…‹้ฃŽ้‡Œๆ‰“ๅผ€ๆƒ้™ static let desc = L10n.tr("access.mic.desc") } enum Photo { /// ่ฏทๅœจ่ฎพ็ฝฎ-้š็ง-็…ง็‰‡้‡Œๆ‰“ๅผ€ๆƒ้™ static let desc = L10n.tr("access.photo.desc") } } enum Chart { /// ๅœ† static let circle = L10n.tr("Chart.circle") /// ๅ…จ็ญ‰ static let congruent = L10n.tr("Chart.congruent") /// ๅ‡ฝๆ•ฐๅˆๆญฅ static let function = L10n.tr("Chart.function") /// ๅคš่พนๅฝข static let polygon = L10n.tr("Chart.polygon") /// ๅฎžๆ•ฐ static let realNumber = L10n.tr("Chart.realNumber") /// ็›ธไผผ static let similar = L10n.tr("Chart.similar") enum Geo { /// ๅ‡ ไฝ•ๆ“ไฝœ static let operation = L10n.tr("Chart.geo.operation") /// ๅ‡ ไฝ•ๅ˜ๆข static let transfor = L10n.tr("Chart.geo.transfor") } } } extension L10n { fileprivate static func tr(_ key: String, _ args: CVarArg...) -> String { let format = NSLocalizedString(key, comment: "") return String(format: format, locale: Locale.current, arguments: args) } }
mit
ddf875a0a4dc549873345f92eb07b909
34.287324
109
0.63415
3.118496
false
false
false
false
spritekitbook/spritekitbook-swift
Chapter 9/Start/SpaceRunner/SpaceRunner/Background.swift
22
2505
// // Background.swift // SpaceRunner // // Created by Jeremy Novak on 8/30/16. // Copyright ยฉ 2016 Spritekit Book. All rights reserved. // import SpriteKit class Background: SKNode { // MARK: - Private class constants private let backgroundRunSpeed:CGFloat = 200.0 private let backgroundStopSpeed:CGFloat = 50.0 // MARK: - Private class variables private var particlesLarge = SKEmitterNode() private var particlesMedium = SKEmitterNode() private var particlesSmall = SKEmitterNode() private var particlesArray = [SKEmitterNode]() // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() self.setup() } // MARK: - Setup private func setup() { self.zPosition = -1.0 particlesLarge = GameParticles.sharedInstance.createParticles(particles: .background) particlesMedium = GameParticles.sharedInstance.createParticles(particles: .background) particlesSmall = GameParticles.sharedInstance.createParticles(particles: .background) particlesLarge.particleScale = 1.0 particlesMedium.particleScale = 0.5 particlesSmall.particleScale = 0.25 particlesArray.append(particlesLarge) particlesArray.append(particlesMedium) particlesArray.append(particlesSmall) for particles in particlesArray { self.addChild(particles) } stopBackground() } // MARK: - Actions func startBackground() { for particles in particlesArray { particles.particleBirthRate = particles.particleBirthRate * 4.0 particles.particleLifetime = particles.particleLifetime / 4.0 particles.particleSpeed = backgroundRunSpeed particles.particleSpeedRange = backgroundRunSpeed / 4 } } func stopBackground() { for particles in particlesArray { particles.particleBirthRate = particles.particleBirthRate / 4.0 particles.particleLifetime = particles.particleLifetime * 4.0 particles.particleSpeed = backgroundStopSpeed particles.particleSpeedRange = backgroundStopSpeed / 4 } } func gameOver() { for particles in particlesArray { particles.particleColor = SKColor.gray } } }
apache-2.0
23039963c7739568f00f68906f0545b0
28.458824
94
0.632987
4.733459
false
false
false
false
therealglazou/quaxe-for-swift
quaxe/core/HTMLCollection.swift
1
1444
/** * Quaxe for Swift * * Copyright 2016-2017 Disruptive Innovations * * Original author: * Daniel Glazman <[email protected]> * * Contributors: * */ /** * https://dom.spec.whatwg.org/#interface-htmlcollection * * status: done */ public class HTMLCollection: pHTMLCollection { internal func append(_ element: pElement) -> Void { mArray.append(element) } internal func clobber() -> Void { mArray = [] } internal var mArray: Array<pElement> = [] /** * https://dom.spec.whatwg.org/#dom-htmlcollection-length */ public var length: ulong { return ulong(self.mArray.count) } /** * https://dom.spec.whatwg.org/#dom-htmlcollection-item */ public func item(_ index: ulong) -> pElement? { if index >= self.length { return nil } return mArray[Int(index)] } /** * https://dom.spec.whatwg.org/#dom-htmlcollection-nameditem */ public func namedItem(_ name: DOMString) -> pElement? { // Step 1 if name.isEmpty { return nil } // Step 2 for element in mArray { if element.getAttribute("id") == name || (element.namespaceURI != nil && element.namespaceURI! == Namespaces.HTML_NAMESPACE && element.getAttributeNS(nil, "name") == name) { return element } } return nil; } init() {} init(_ elements: Array<pElement>) { mArray = elements } }
mpl-2.0
4e1f4639a247ec525e2d54ae5096613d
18.780822
63
0.603186
3.655696
false
false
false
false
SwiftKit/Lipstick
LipstickTests/UICollectionView+InitTest.swift
1
671
// // UICollectionView+InitTest.swift // Lipstick // // Created by Filip Dolnik on 18.10.16. // Copyright ยฉ 2016 Brightify. All rights reserved. // import Quick import Nimble import Lipstick class UICollectionViewInitTest: QuickSpec { override func spec() { describe("UICollectionView init") { it("creates UICollectionView with zero CGRect") { let layout = UICollectionViewFlowLayout() let view = UICollectionView(collectionViewLayout: layout) expect(view.frame) == CGRect.zero expect(view.collectionViewLayout) == layout } } } }
mit
42684c6a6a4354ed5122d22d5705b6fc
24.769231
73
0.607463
5.037594
false
true
false
false
nguyenantinhbk77/practice-swift
Notifications/Scheduling Local Notifications/Scheduling Local Notifications/AppDelegate.swift
2
2163
// // AppDelegate.swift // Scheduling Local Notifications // // Created by Domenico Solazzo on 15/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { /* First ask the user if we are allowed to perform local notifications */ let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil) application.registerUserNotificationSettings(settings) return true } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { if notificationSettings.types == nil{ /* The user did not allow us to send notifications */ return } let notification = UILocalNotification() // This is a property of type NSDate that dictates to iOS // when the instance of the local notification has to be fired. This is required. notification.fireDate = NSDate(timeIntervalSinceNow: 8) // The time zone in which the given fire-date is specified notification.timeZone = NSCalendar.currentCalendar().timeZone // The text that has to be displayed to the user when // your notification is displayed on screen notification.alertBody = "A new item has been downloaded" notification.hasAction = true // It represents the action that the user can take on your local notification notification.alertAction = "View" // The badge number for your app icon notification.applicationIconBadgeNumber++ // More additional information about the local notification notification.userInfo = [ "Key 1": "Value1", "Key 2": "Value2" ] /* Schedule the notification */ application.scheduleLocalNotification(notification) } }
mit
43dc72ca78a46c63c1affd48314b9579
32.796875
136
0.649098
5.942308
false
false
false
false
JadenGeller/Axiomatic
Sources/Axiomatic/Clause.swift
1
7228
// // Clause.swift // Axiomatic // // Created by Jaden Geller on 1/18/16. // Copyright ยฉ 2016 Jaden Geller. All rights reserved. // import Gluey /// A statement whose `head` is true given that its `body` is true. When the `body` is empty, /// a clause is commonly called a "fact". Otherwise, it is called a "rule". `Clause` is often /// used with unification variables such that conditional truths can be expressed, such as /// `grandparent(A, B) :- parent(A, X), parent(X, B)`. public struct Clause<Atom: Hashable> { /// The term that is true conditional on all terms of the `body` being true. public var head: Term<Atom> /// The collection of terms that all must be true in order for `head` to be true. public var body: [Term<Atom>] private init(head: Term<Atom>, body: [Term<Atom>]) { self.head = head self.body = body } } extension Clause { /// Constructs a `Clause` that is always true. public init(fact: Term<Atom>) { self.init(head: fact, body: []) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions`. public init(rule: Term<Atom>, conditions: [Term<Atom>]) { self.init(head: rule, body: conditions) } } extension Clause: CustomStringConvertible { /// A textual description of `self`. public var description: String { guard body.count > 0 else { return head.description + "." } return head.description + " :- " + body.map { String(describing: $0) }.joined(separator: ", ") + "." } } // Bindings used in a `Clause` are expected to remain local to a clause. As such, initializers that properly scope needed bindings // are provided for convenience and correctness. extension Clause { /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 0 unused bindings. public init(build: () -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build() self.init(rule: rule, conditions: conditions) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 1 unused bindings. public init(build: (Binding<Term<Atom>>) -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build(Binding()) self.init(rule: rule, conditions: conditions) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 2 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>) -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build(Binding(), Binding()) self.init(rule: rule, conditions: conditions) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 3 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build(Binding(), Binding(), Binding()) self.init(rule: rule, conditions: conditions) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 4 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build(Binding(), Binding(), Binding(), Binding()) self.init(rule: rule, conditions: conditions) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 5 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build(Binding(), Binding(), Binding(), Binding(), Binding()) self.init(rule: rule, conditions: conditions) } /// Constructs a `Clause` that defines a rule that is true given some set of `conditions` /// using the `build` closure that provides 6 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> (rule: Term<Atom>, conditions: [Term<Atom>])) { let (rule, conditions) = build(Binding(), Binding(), Binding(), Binding(), Binding(), Binding()) self.init(rule: rule, conditions: conditions) } } extension Clause { /// Constructs a `Clause` that defines a fact using the `build` closure that provides 0 unused bindings. public init(build: () -> Term<Atom>) { self.init(fact: build()) } /// Constructs a `Clause` that defines a fact using the `build` closure that provides 1 unused bindings. public init(build: (Binding<Term<Atom>>) -> Term<Atom>) { self.init(fact: build(Binding())) } /// Constructs a `Clause` that defines a fact using the `build` closure that provides 2 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>) -> Term<Atom>) { self.init(fact: build(Binding(), Binding())) } /// Constructs a `Clause` that defines a fact using the `build` closure that provides 3 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> Term<Atom>) { self.init(fact: build(Binding(), Binding(), Binding())) } /// Constructs a `Clause` that defines a fact using the `build` closure that provides 4 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> Term<Atom>) { self.init(fact: build(Binding(), Binding(), Binding(), Binding())) } /// Constructs a `Clause` that defines a fact using the `build` closure that provides 5 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> Term<Atom>) { self.init(fact: build(Binding(), Binding(), Binding(), Binding(), Binding())) } /// Constructs a `Clause` that defines a fact using the `build` closure that provides 6 unused bindings. public init(build: (Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>, Binding<Term<Atom>>) -> Term<Atom>) { self.init(fact: build(Binding(), Binding(), Binding(), Binding(), Binding(), Binding())) } } extension Clause: ContextCopyable { /// Copies `this` reusing any substructure that has already been copied within /// this context, and storing any newly generated substructure into the context. public static func copy(_ this: Clause, withContext context: CopyContext) -> Clause { return Clause(head: Term.copy(this.head, withContext: context), body: this.body.map { Term.copy($0, withContext: context) }) } }
mit
7d0367c8b91bde66da919c9d7eb9a9fb
49.1875
200
0.65878
3.953501
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/APE/APETagGenresTest.swift
1
12197
// // APETagGenresTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 XCTest @testable import Metatron class APETagGenresTest: XCTestCase { // MARK: Instance Methods func test() { let tag = APETag() do { let value: [String] = [] tag.genres = value XCTAssert(tag.genres == value) XCTAssert(tag["Genre"] == nil) do { tag.version = APEVersion.v1 XCTAssert(tag.toData() == nil) } do { tag.version = APEVersion.v2 XCTAssert(tag.toData() == nil) } guard let item = tag.appendItem("Genre") else { return XCTFail() } item.stringListValue = value XCTAssert(tag.genres == value) } do { let value = [""] tag.genres = value XCTAssert(tag.genres == []) XCTAssert(tag["Genre"] == nil) do { tag.version = APEVersion.v1 XCTAssert(tag.toData() == nil) } do { tag.version = APEVersion.v2 XCTAssert(tag.toData() == nil) } guard let item = tag.appendItem("Genre") else { return XCTFail() } item.stringListValue = value XCTAssert(tag.genres == []) } do { let value = ["Abc 123"] tag.genres = value XCTAssert(tag.genres == value) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == value) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } item.stringListValue = value XCTAssert(tag.genres == value) } do { let value = ["ะะฑะฒ 123"] tag.genres = value XCTAssert(tag.genres == value) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == value) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } item.stringListValue = value XCTAssert(tag.genres == value) } do { let value = ["Abc 1", "Abc 2"] tag.genres = value XCTAssert(tag.genres == value) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == value) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } item.stringListValue = value XCTAssert(tag.genres == value) } do { let value = ["", "Abc 2"] tag.genres = value XCTAssert(tag.genres == ["Abc 2"]) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == ["Abc 2"]) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 2"]) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 2"]) } item.stringListValue = value XCTAssert(tag.genres == ["Abc 2"]) } do { let value = ["Abc 1", ""] tag.genres = value XCTAssert(tag.genres == ["Abc 1"]) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == ["Abc 1"]) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1"]) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == ["Abc 1"]) } item.stringListValue = value XCTAssert(tag.genres == ["Abc 1"]) } do { let value = ["", ""] tag.genres = value XCTAssert(tag.genres == []) XCTAssert(tag["Genre"] == nil) do { tag.version = APEVersion.v1 XCTAssert(tag.toData() == nil) } do { tag.version = APEVersion.v2 XCTAssert(tag.toData() == nil) } guard let item = tag.appendItem("Genre") else { return XCTFail() } item.stringListValue = value XCTAssert(tag.genres == []) } do { let value = [Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")] tag.genres = value XCTAssert(tag.genres == value) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == value) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } item.stringListValue = value XCTAssert(tag.genres == value) } do { let value = Array<String>(repeating: "Abc", count: 123) tag.genres = value XCTAssert(tag.genres == value) guard let item = tag["Genre"] else { return XCTFail() } guard let itemValue = item.stringListValue else { return XCTFail() } XCTAssert(itemValue == value) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.genres == value) } item.stringListValue = value XCTAssert(tag.genres == value) } guard let item = tag.appendItem("Genre") else { return XCTFail() } do { item.value = [UInt8](String("Abc 1\0Abc 2").utf8) XCTAssert(tag.genres == ["Abc 1", "Abc 2"]) } do { item.value = [UInt8](String("\0Abc 2").utf8) XCTAssert(tag.genres == ["Abc 2"]) } do { item.value = [UInt8](String("Abc 1\0").utf8) XCTAssert(tag.genres == ["Abc 1"]) } do { item.value = [0] XCTAssert(tag.genres == []) } } }
mit
4c43596b4e65b57907df7a602593505b
23.146535
93
0.443251
5.197783
false
false
false
false
ryuichis/swift-lint
Sources/Lint/Reporter/JSONReporter.swift
2
1762
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors 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 Source class JSONReporter : Reporter { func handle(issues: [Issue]) -> String { if issues.isEmpty { return """ "issues": [] """ } let issuesText = issues.map({ $0.jsonString }).joined(separator: ",\n") return """ "issues": [ \(issuesText) ] """ } func handle(numberOfTotalFiles: Int, issueSummary: IssueSummary) -> String { let numberOfIssueFiles = issueSummary.numberOfFiles var summaryJson = """ "summary": { "numberOfFiles": \(numberOfTotalFiles), "numberOfFilesWithIssues": \(numberOfIssueFiles), """ summaryJson += Issue.Severity.allSeverities .map({ """ "numberOfIssuesIn\($0.rawValue.capitalized)": \(issueSummary.numberOfIssues(withSeverity: $0)) """ }).joined(separator: ",\n") summaryJson += """ }, """ return summaryJson } var header: String { return """ { "version": "\(SWIFT_LINT_VERSION)", "url": "http://yanagiba.org/swift-lint", "timestamp": "\(Date().jsonFomatted)", """ } var footer: String { return "}" } }
apache-2.0
c902e89dbd5f19ca1e3580bd8d3be089
23.136986
102
0.644154
4.297561
false
false
false
false
anlaital/Swan
Swan/Swan/Observatory.swift
1
3924
// // Observatory.swift // Swan // // Created by Antti Laitala on 09/07/15. // // import Foundation public final class Observatory { public init() { } public typealias ClosureKVO = () -> () public typealias ClosureNotificationCenter = (Notification) -> () /// Registers a closure to receive KVO notifications for the specified key-path relative to the `object`. @discardableResult public func observe(_ object: NSObject, keyPath: String, closure: @escaping ClosureKVO) -> String { let token = createToken() kvoProxy.observers[token] = KVOProxy.Observer(object: object, keyPath: keyPath, closure: closure) object.addObserver(kvoProxy, forKeyPath: keyPath, options: [.new], context: nil) return token } /// Registers a closure to receive notifications for the specified `name` and `object`. @discardableResult public func observe(name: Notification.Name?, object: AnyObject?, closure: @escaping ClosureNotificationCenter) -> String { let token = createToken() let observer = NotificationCenter.default.addObserver(forName: name, object: object, queue: nil) { note in closure(note) } observers[token] = observer return token } /// Registers a closure to receive notifications for the specified `name` and `object`. Notification is automatically removed after the first time it's fired. @discardableResult public func observeOnce(name: Notification.Name?, object: AnyObject?, closure: @escaping ClosureNotificationCenter) -> String { let token = createToken() let observer = NotificationCenter.default.addObserver(forName: name, object: object, queue: nil) { [unowned self] note in self.removeObserverForToken(token) closure(note) } observers[token] = observer return token } /// Removes an observer corresponding to `observerToken`. public func removeObserverForToken(_ token: String) { if let observer = observers[token] { NotificationCenter.default.removeObserver(observer) observers[token] = nil } if let observer = kvoProxy.observers[token] { observer.object.removeObserver(kvoProxy, forKeyPath: observer.keyPath) kvoProxy.observers[token] = nil } } // MARK: Private fileprivate lazy var observers = [String: NSObjectProtocol]() fileprivate lazy var kvoProxy = KVOProxy() fileprivate func createToken() -> String { return UUID().uuidString } deinit { let notificationCenter = NotificationCenter.default for observer in observers.values { notificationCenter.removeObserver(observer) } } } extension Observatory { fileprivate class KVOProxy: NSObject { fileprivate struct Observer { let object: NSObject let keyPath: String let closure: ClosureKVO init(object: NSObject, keyPath: String, closure: @escaping ClosureKVO) { self.object = object self.keyPath = keyPath self.closure = closure } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { for observer in observers.values { if observer.object == object as? NSObject && keyPath == observer.keyPath { observer.closure() } } } deinit { for observer in observers.values { observer.object.removeObserver(self, forKeyPath: observer.keyPath) } } fileprivate lazy var observers = [String: Observer]() } }
mit
a7b12ce80684629595c2d567990bebff
32.827586
162
0.620795
5.225033
false
false
false
false
ahoppen/swift
test/attr/attr_backDeploy.swift
2
13702
// RUN: %target-typecheck-verify-swift -parse-as-library \ // RUN: -define-availability "_myProject 2.0:macOS 12.0" // MARK: - Valid declarations // OK: top level functions @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedTopLevelFunc() {} // OK: internal decls may be back deployed when @usableFromInline @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @usableFromInline internal func backDeployedUsableFromInlineTopLevelFunc() {} // OK: function/property/subscript decls in a struct public struct TopLevelStruct { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public var backDeployedComputedProperty: Int { 98 } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public subscript(_ index: Int) -> Int { index } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public var readWriteProperty: Int { get { 42 } set(newValue) {} } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public subscript(at index: Int) -> Int { get { 42 } set(newValue) {} } public var explicitReadAndModify: Int { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) _read { yield 42 } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) _modify {} } } // OK: final function decls in a non-final class public class TopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public func backDeployedFinalMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public var backDeployedFinalComputedProperty: Int { 98 } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public static func backDeployedStaticMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public final class func backDeployedClassMethod() {} } // OK: function decls in a final class final public class FinalTopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public var backDeployedComputedProperty: Int { 98 } } // OK: final function decls on an actor @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) public actor TopLevelActor { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public func finalActorMethod() {} // OK: actor methods are effectively final @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func actorMethod() {} } // OK: function decls in extension on public types extension TopLevelStruct { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedExtensionMethod() {} } extension TopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public func backDeployedExtensionMethod() {} } extension FinalTopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedExtensionMethod() {} } public protocol TopLevelProtocol {} extension TopLevelProtocol { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedExtensionMethod() {} } // MARK: - Unsupported declaration types @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public class CannotBackDeployClass {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public struct CannotBackDeployStruct { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' must not be used on stored properties}} public var cannotBackDeployStoredProperty: Int = 83 @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' must not be used on stored properties}} public lazy var cannotBackDeployLazyStoredProperty: Int = 15 } @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public enum CannotBackDeployEnum { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} case cannotBackDeployEnumCase } @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' must not be used on stored properties}} public var cannotBackDeployTopLevelVar = 79 @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} extension TopLevelStruct {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} protocol CannotBackDeployProtocol {} @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public actor CannotBackDeployActor {} // MARK: - Function body diagnostics public struct FunctionBodyDiagnostics { public func publicFunc() {} @usableFromInline func usableFromInlineFunc() {} func internalFunc() {} // expected-note {{instance method 'internalFunc()' is not '@usableFromInline' or public}} fileprivate func fileprivateFunc() {} // expected-note {{instance method 'fileprivateFunc()' is not '@usableFromInline' or public}} private func privateFunc() {} // expected-note {{instance method 'privateFunc()' is not '@usableFromInline' or public}} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedMethod() { struct Nested {} // expected-error {{type 'Nested' cannot be nested inside a '@_backDeploy' function}} publicFunc() usableFromInlineFunc() internalFunc() // expected-error {{instance method 'internalFunc()' is internal and cannot be referenced from a '@_backDeploy' function}} fileprivateFunc() // expected-error {{instance method 'fileprivateFunc()' is fileprivate and cannot be referenced from a '@_backDeploy' function}} privateFunc() // expected-error {{instance method 'privateFunc()' is private and cannot be referenced from a '@_backDeploy' function}} } } // MARK: - Incompatible declarations @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on fileprivate declarations}} fileprivate func filePrivateFunc() {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on private declarations}} private func privateFunc() {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on internal declarations}} internal func internalFunc() {} private struct PrivateTopLevelStruct { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on private declarations}} public func effectivelyPrivateFunc() {} } public class TopLevelClass2 { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' cannot be applied to a non-final instance method}} public func nonFinalMethod() {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' cannot be applied to a non-final class method}} public class func nonFinalClassMethod() {} } @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' requires that 'missingAllAvailabilityFunc()' have explicit availability for macOS}} public func missingAllAvailabilityFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, iOS 15.0) // expected-error {{'@_backDeploy' requires that 'missingiOSAvailabilityFunc()' have explicit availability for iOS}} public func missingiOSAvailabilityFunc() {} @available(macOS 12.0, *) @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' has no effect because 'availableSameVersionAsBackDeployment()' is not available before macOS 12.0}} public func availableSameVersionAsBackDeployment() {} @available(macOS 12.1, *) @_backDeploy(before: macOS 12.0) // expected-error {{'availableAfterBackDeployment()' is not available before macOS 12.0}} public func availableAfterBackDeployment() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, macOS 13.0) // expected-error {{'@_backDeploy' contains multiple versions for macOS}} public func duplicatePlatformsFunc1() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @_backDeploy(before: macOS 13.0) // expected-error {{'@_backDeploy' contains multiple versions for macOS}} public func duplicatePlatformsFunc2() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @_alwaysEmitIntoClient // expected-error {{'@_alwaysEmitIntoClient' cannot be applied to a back deployed global function}} public func alwaysEmitIntoClientFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @inlinable // expected-error {{'@inlinable' cannot be applied to a back deployed global function}} public func inlinableFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @_transparent // expected-error {{'@_transparent' cannot be applied to a back deployed global function}} public func transparentFunc() {} // MARK: - Attribute parsing @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, unknownOS 1.0) // expected-warning {{unknown platform 'unknownOS' for attribute '@_backDeploy'}} public func unknownOSFunc() {} @_backDeploy(before: @) // expected-error {{expected platform in '@_backDeploy' attribute}} public func badPlatformFunc1() {} @_backDeploy(before: @ 12.0) // expected-error {{expected platform in '@_backDeploy' attribute}} public func badPlatformFunc2() {} @_backDeploy(before: macOS) // expected-error {{expected version number in '@_backDeploy' attribute}} public func missingVersionFunc1() {} @_backDeploy(before: macOS 12.0, iOS) // expected-error {{expected version number in '@_backDeploy' attribute}} public func missingVersionFunc2() {} @_backDeploy(before: macOS, iOS) // expected-error 2{{expected version number in '@_backDeploy' attribute}} public func missingVersionFunc3() {} @available(macOS 11.0, iOS 14.0, *) @_backDeploy(before: macOS 12.0, iOS 15.0,) // expected-error {{unexpected ',' separator}} public func unexpectedSeparatorFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0.1) // expected-warning {{'@_backDeploy' only uses major and minor version number}} public func patchVersionFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, * 9.0) // expected-warning {{* as platform name has no effect in '@_backDeploy' attribute}} public func wildcardWithVersionFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, *) // expected-warning {{* as platform name has no effect in '@_backDeploy' attribute}} public func trailingWildcardFunc() {} @available(macOS 11.0, iOS 14.0, *) @_backDeploy(before: macOS 12.0, *, iOS 15.0) // expected-warning {{* as platform name has no effect in '@_backDeploy' attribute}} public func embeddedWildcardFunc() {} @_backDeploy(before: _myProject 3.0) // expected-error {{reference to undefined version '3.0' for availability macro '_myProject'}} public func macroVersioned() {} @_backDeploy(before: _myProject) // expected-error {{reference to undefined version '0' for availability macro '_myProject'}} public func missingMacroVersion() {} // Fall back to the default diagnostic when the macro is unknown. @_backDeploy(before: _unknownMacro) // expected-warning {{unknown platform '_unknownMacro' for attribute '@_backDeploy'}} // expected-error@-1 {{expected version number in '@_backDeploy' attribute}} public func unknownMacroMissingVersion() {} @_backDeploy(before: _unknownMacro 1.0) // expected-warning {{unknown platform '_unknownMacro' for attribute '@_backDeploy'}} // expected-error@-1 {{expected at least one platform version in '@_backDeploy' attribute}} public func unknownMacroVersioned() {} @available(macOS 11.0, *) @_backDeploy(before: _unknownMacro 1.0, _myProject 2.0) // expected-warning {{unknown platform '_unknownMacro' for attribute '@_backDeploy'}} public func knownAndUnknownMacroVersioned() {} @_backDeploy() // expected-error {{expected 'before:' in '@_backDeploy' attribute}} // expected-error@-1 {{expected at least one platform version in '@_backDeploy' attribute}} public func emptyAttributeFunc() {} @available(macOS 11.0, *) @_backDeploy(macOS 12.0) // expected-error {{expected 'before:' in '@_backDeploy' attribute}} {{14-14=before:}} public func missingBeforeFunc() {} @_backDeploy(before) // expected-error {{expected ':' after 'before' in '@_backDeploy' attribute}} {{20-20=:}} // expected-error@-1 {{expected at least one platform version in '@_backDeploy' attribute}} public func missingColonAfterBeforeFunc() {} @available(macOS 11.0, *) @_backDeploy(before macOS 12.0) // expected-error {{expected ':' after 'before' in '@_backDeploy' attribute}} {{20-20=:}} public func missingColonBetweenBeforeAndPlatformFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0,) // expected-error {{unexpected ',' separator}} {{32-33=}} public func unexpectedTrailingCommaFunc() {} @available(macOS 11.0, iOS 14.0, *) @_backDeploy(before: macOS 12.0,, iOS 15.0) // expected-error {{unexpected ',' separator}} {{33-34=}} public func extraCommaFunc() {} @_backDeploy(before:) // expected-error {{expected at least one platform version in '@_backDeploy' attribute}} public func emptyPlatformVersionsFunc() {} @_backDeploy // expected-error {{expected '(' in '@_backDeploy' attribute}} public func expectedLeftParenFunc() {} @_backDeploy(before: macOS 12.0 // expected-note {{to match this opening '('}} public func expectedRightParenFunc() {} // expected-error {{expected ')' in '@_backDeploy' argument list}}
apache-2.0
b1a6b3fc6b64790ebb2e917aacc44623
39.901493
167
0.725442
4.03
false
false
false
false
txlong/iOS
swift/02-SimpleValues/02-SimpleValues/main.swift
1
1002
// // main.swift // 02-SimpleValues // // Created by iAnonymous on 15/7/5. // Copyright (c) 2015ๅนด iAnonymous. All rights reserved. // import Foundation var myVariable = 42 myVariable = 50 let myConstant = 42 let implicitInteger = 70 let implicitDobule = 70.0 let explicitDouble:Double = 70 let newConstant:Float = 4 let lable = "The width is " let width = 94 let widthLable = lable + String(width) let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." println("Hi,tom.Today's tempureture is \(48.5)ยฐ") var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle oft water" var occuptions = [ "Malclm":"Captain", "Kaylee":"Mechanic" ] occuptions["Jayne"] = "Public Relations" let emptyArray = [String]() let emptyDictionary = [String:Float]() // ๅฆ‚ๆžœ็ฑปๅž‹ๅฏไปฅๆŽจๆ–ญๅ‡บๆฅ๏ผŒๅฏไปฅ่ฟ™ๆ ทๅˆ›ๅปบ็ฉบๆ•ฐ็ป„ var shoppingList1 = [] var shoppingDictionary1 = [:]
gpl-2.0
cb1ec47d503c49245794d8bc39b490fc
19.869565
64
0.695516
3.093548
false
false
false
false
megavolt605/CNLDataProvider
CNLDataProvider/CNLModelLoadable.swift
1
7214
// // CNLModelLoadable.swift // CNLDataProvider // // Created by Igor Smirnov on 28/12/2016. // Copyright ยฉ 2016 Complex Numbers. All rights reserved. // import UIKit import CoreTelephony import CNLFoundationTools private var cancelLoadingTaskCallbacksFunc = "cancelLoadingTaskCallbacksFunc" public protocol CNLModelDataLoadable: class { func loadData(_ url: URL?, priority: Float?, userData: Any?, success: @escaping CNLNetwork.Download.File.Success, fail: @escaping CNLNetwork.Download.File.Failed) func cancelLoading() } public extension CNLModelDataLoadable { public func loadData(_ url: URL?, priority: Float?, userData: Any?, success: @escaping CNLNetwork.Download.File.Success, fail: @escaping CNLNetwork.Download.File.Failed) { let cancelTask = CNLModel.networkProvider?.downloadFileFromURL( url, priority: priority ?? 1.0, userData: userData, success: { url, data, userData in success(url, data, userData) if let key = url?.absoluteString { self.cancelLoadingTaskCallbacks[key] = nil } }, fail: { url, error, userData in if let urlError = error as? URLError, urlError.code != .cancelled { fail(url, error, userData) } if let key = url?.absoluteString { self.cancelLoadingTaskCallbacks[key] = nil } } ) if let cancelTask = cancelTask { if let key = url?.absoluteString { cancelLoadingTaskCallbacks[key] = { [url, userData] in cancelTask(url, userData) } } } } fileprivate typealias CNLCancelLoadingCallbacks = [String: () -> Void] fileprivate var cancelLoadingTaskCallbacks: CNLCancelLoadingCallbacks { get { if let value = (objc_getAssociatedObject(self, &cancelLoadingTaskCallbacksFunc) as? CNLAssociated<CNLCancelLoadingCallbacks>)?.closure { return value } else { return [:] } } set { objc_setAssociatedObject(self, &cancelLoadingTaskCallbacksFunc, CNLAssociated<CNLCancelLoadingCallbacks>(closure: newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } public func cancelLoading() { for task in cancelLoadingTaskCallbacks { task.value() } cancelLoadingTaskCallbacks = [:] } } public protocol CNLModelImageLoadable: CNLModelDataLoadable { func loadImage(_ url: URL?, priority: Float?, userData: Any?, success: @escaping CNLNetwork.Download.Image.Success, fail: @escaping CNLNetwork.Download.File.Failed) } public extension CNLModelImageLoadable { public func loadImage(_ url: URL?, priority: Float?, userData: Any?, success: @escaping CNLNetwork.Download.Image.Success, fail: @escaping CNLNetwork.Download.File.Failed) { let start = Date() guard let url = url else { fail(nil, nil, userData) return } loadData( url, priority: priority, userData: userData, success: { url, fileData, userData in let networkStop = Date().timeIntervalSince(start) if let data = fileData, let img = UIImage(data: data) { #if DEBUG let stop = Date().timeIntervalSince(start) cnlLog( .ImageDownloadedSuccess, .debug, url!.absoluteString, "\(floor(networkStop * 1000.0 * 1000.0) / 1000.0)", "\(floor(stop * 1000.0 * 1000.0) / 1000.0)", "\(img.size.width)", "\(img.size.height)", "\(data.count)" ) #endif success(url, img, data, userData) } else { #if DEBUG cnlLog(.ImageDownloadingError, .error, url!.absoluteString) #endif fail(url, nil, userData) } }, fail: fail ) } } public protocol CNLModelResizableImageLoadable: CNLModelImageLoadable { func loadImage( _ url: URL?, priority: Float?, userData: Any?, size: CGSize, scale: CGFloat?, success: @escaping CNLNetwork.Download.Image.Success, fail: @escaping CNLNetwork.Download.File.Failed ) } public extension CNLModelResizableImageLoadable { public func loadImage( _ url: URL?, priority: Float?, userData: Any?, size: CGSize, scale: CGFloat?, success: @escaping CNLNetwork.Download.Image.Success, fail: @escaping CNLNetwork.Download.File.Failed ) { guard let url = url else { fail(nil, nil, userData) return } let scale = scale ?? imageScale() var newURL = url let urlString = newURL.absoluteString if size.width != 0 && size.height != 0 && !urlString.contains(".gif") { let newURLString = urlString.appendSuffixBeforeExtension("@\(Int(scale * size.width))x\(Int(scale * size.height))") if let updatedURL = URL(string: newURLString) { newURL = updatedURL } else { fail(url, nil, userData) return } } loadImage( newURL, priority: priority, userData: userData, success: { _, image, imageData, userData in success(url, image, imageData, userData) }, fail: { _, error, userData in fail(url, error, userData) } ) } public func imageScale() -> CGFloat { var scale: CGFloat = 0.0 if !(CNLModel.networkProvider?.isReachableOnEthernetOrWiFi ?? true) { if let networkType = CTTelephonyNetworkInfo().currentRadioAccessTechnology { switch networkType { case CTRadioAccessTechnologyGPRS: scale = 1.5 case CTRadioAccessTechnologyEdge: scale = 1.0 case CTRadioAccessTechnologyWCDMA: scale = 1.5 case CTRadioAccessTechnologyHSDPA: scale = 1.5 case CTRadioAccessTechnologyHSUPA: scale = 1.5 case CTRadioAccessTechnologyCDMA1x: scale = 0.0 case CTRadioAccessTechnologyCDMAEVDORev0: scale = 1.0 case CTRadioAccessTechnologyCDMAEVDORevA: scale = 1.5 case CTRadioAccessTechnologyCDMAEVDORevB: scale = 1.5 case CTRadioAccessTechnologyeHRPD: scale = 1.0 case CTRadioAccessTechnologyLTE: scale = 0.0 default: scale = 0.0 } } } if scale < 0.1 { scale = UIScreen.main.scale } return scale } }
mit
d960348c093fa3860f388b9c4a06cba4
34.885572
184
0.551643
4.967631
false
false
false
false
pikachu987/PKCUtil
PKCUtil/Classes/UI/UITextField+.swift
1
2720
//Copyright (c) 2017 pikachu987 <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit public extension UITextField{ // MARK: func /** maxLength - parameter maxLength: Int - parameter range: NSRange - parameter string: String - returns: Bool */ public func maxLength(_ maxLength: Int = 200, range: NSRange, string: String) -> Bool{ return maxLength == -1 ? true : ((self.text?.utf16.count ?? 0) + string.utf16.count - range.length) <= maxLength } /** makeToolBar - parameter target: Any? - parameter action: Selector - parameter color: UIColor - parameter selectString: String - parameter cancelString: String */ public func toolBar(_ target: Any?, action: Selector, color: UIColor = UIColor(white: 224/255, alpha: 1), selectString: String = "Done", cancelString: String = "Cancel"){ let toolBar = UIToolbar() toolBar.barStyle = .default toolBar.isTranslucent = true toolBar.tintColor = color toolBar.setItems([ UIBarButtonItem(title: cancelString, style: .plain, target: self, action: #selector(self.cancelAction(_:))), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil), UIBarButtonItem(title: selectString, style: .done, target: target, action: action) ], animated: true) toolBar.isUserInteractionEnabled = true toolBar.sizeToFit() self.inputAccessoryView = toolBar } /// cancelAction @objc private func cancelAction(_ sender: UIBarButtonItem){ self.resignFirstResponder() } }
mit
5d05d62ce6db14b981fae4bf57bc1b1c
39.597015
174
0.688235
4.705882
false
false
false
false
cache0928/CCWeibo
CCWeibo/CCWeibo/Classes/Discover/DiscoverTableViewController.swift
1
3469
// // DiscoverTableViewController.swift // CCWeibo // // Created by ๅพๆ‰่ถ… on 16/2/2. // Copyright ยฉ 2016ๅนด ๅพๆ‰่ถ…. All rights reserved. // import UIKit class DiscoverTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !isLogin { (view as! VisitorView).setupViews(false, iconName: "visitordiscover_image_message", info: "็™ปๅฝ•ๅŽ๏ผŒๆœ€ๆ–ฐใ€ๆœ€็ƒญๅพฎๅšๅฐฝๅœจๆŽŒๆก๏ผŒไธๅ†ไผšไธŽๅฎžไบ‹ๆฝฎๆตๆ“ฆ่‚ฉ่€Œ่ฟ‡") } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
58064ebbf40543f8f77209621dea16eb
34.030928
157
0.684815
5.368088
false
false
false
false
tLewisII/SwiftStyledStrings
SwiftStyledStrings/Source/Monoid.swift
1
1512
// // Monoid.swift // AttributedStringBuilder // // Created by Terry Lewis II on 7/28/14. // Copyright (c) 2014 Blue Plover Productions LLC. All rights reserved. // import Foundation public protocol Monoid { typealias M func mempty() -> M func mappend(a:M) -> M } public operator infix <> { associativity left } @infix public func <><A:Monoid where A.M == A>(lhs:A, rhs:A) -> A { return lhs.mappend(rhs) } extension NSAttributedString : Monoid { public typealias M = NSAttributedString public func mempty() -> M { return NSAttributedString() } public func mappend(a:M) -> M { let mutable = NSMutableAttributedString(attributedString:self) mutable.appendAttributedString(a) return NSAttributedString(attributedString: mutable) } } extension Array : Monoid { public typealias M = Array public func mempty() -> M { return [] } public func mappend(a:M) -> M { var lhs = Array(self) lhs.extend(a) return lhs } } extension Dictionary : Monoid { public typealias M = Dictionary public func mempty() -> M { return Dictionary() } public func mappend(a:M) -> M { var lhs = Dictionary() for (key, val) in self { lhs.updateValue(val, forKey: key) } for (key, val) in a { if !lhs[key] { lhs.updateValue(val, forKey: key) } } return lhs } }
mit
0602f471859b3a743768d6d9363c9310
20.295775
72
0.579365
4.032
false
false
false
false
eduarenas/SwiftArrayDiff
ArrayDiff.swift
1
3405
// // ArrayDiff.swift // // Created by Eduardo Arenas on 1/1/17. // Licensed Under MIT. See https://github.com/eduarenas/SwiftArrayDiff/blob/master/LICENSE. // import Foundation struct DiffItem<T> { let index: Int let element: T } struct Diff<T> { let additions: [DiffItem<T>] let deletions: [DiffItem<T>] } extension Array where Element: Equatable { func diff(other: Array<Element>) -> Diff<Element> { let reducedArrays = nonMatchingSubArray(old: self, new: other) let lcsTable = lcsLengthTable(old: reducedArrays.old, new: reducedArrays.new) return diffFromLCSTable(table: lcsTable, old: reducedArrays.old, new: reducedArrays.new, indexOffset: reducedArrays.startIndex) } } private func nonMatchingSubArray<T: Equatable>(old: [T], new: [T]) -> (old: [T], new: [T], startIndex: Int) { guard old.count > 0 && new.count > 0 else { return (old, new, 0) } var startIndex = 0 var oldEndIndex = old.count - 1 var newEndIndex = new.count - 1 while startIndex < oldEndIndex && startIndex < newEndIndex && old[startIndex] == new[startIndex] { startIndex += 1 } while oldEndIndex > startIndex && newEndIndex > startIndex && old[oldEndIndex] == new[newEndIndex] { oldEndIndex -= 1 newEndIndex -= 1 } return (Array(old[startIndex...oldEndIndex]), Array(new[startIndex...newEndIndex]), startIndex) } private struct TableItem { let length: Int let previousIndex: (x: Int, y: Int)? } private func lcsLengthTable<T: Equatable>(old: [T], new: [T]) -> [[TableItem]] { let n = old.count let m = new.count var table = Array<[TableItem]>(repeating: Array(repeating: TableItem(length: 0, previousIndex: nil), count: m + 1), count: n + 1) for i in 0...n { for j in 0...m { if i == 0 && j == 0 { table[i][j] = TableItem(length: 0, previousIndex: nil) } else if i == 0 { table[i][j] = TableItem(length: 0, previousIndex: (i, j - 1)) } else if j == 0 { table[i][j] = TableItem(length: 0, previousIndex: (i - 1, j)) } else if old[i - 1] == new[j - 1] { table[i][j] = TableItem(length: table[i - 1][j - 1].length + 1, previousIndex: (i - 1, j - 1)) } else { if table[i][j - 1].length >= table[i - 1][j].length { table[i][j] = TableItem(length: table[i][j - 1].length, previousIndex: (i, j - 1)) } else { table[i][j] = TableItem(length: table[i - 1][j].length, previousIndex: (i - 1, j)) } } } } return table } private func diffFromLCSTable<T: Equatable>(table: [[TableItem]], old: [T], new: [T], indexOffset: Int) -> Diff<T> { var currentIndex = (x: table.count - 1, y: table[0].count - 1) var currentItem = table[currentIndex.x][currentIndex.y] var additions = [DiffItem<T>]() var deletions = [DiffItem<T>]() while let previousIndex = currentItem.previousIndex { if previousIndex.x == currentIndex.x && previousIndex.y < currentIndex.y { additions.append(DiffItem(index: currentIndex.y - 1 + indexOffset, element: new[currentIndex.y - 1])) } else if previousIndex.x < currentIndex.x && previousIndex.y == currentIndex.y { deletions.append(DiffItem(index: currentIndex.x - 1 + indexOffset, element: old[currentIndex.x - 1])) } currentIndex = previousIndex currentItem = table[currentIndex.x][currentIndex.y] } return Diff(additions: additions, deletions: deletions) }
mit
b62c0f14f9e862227a532f16500ca128
32.382353
131
0.638767
3.405
false
false
false
false
tensorflow/swift-models
PersonLab/Backbone.swift
1
7738
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Checkpoints import TensorFlow public struct DepthwiseSeparableConvBlock: Layer { var dConv: DepthwiseConv2D<Float> var conv: Conv2D<Float> public init( depthWiseFilter: Tensor<Float>, depthWiseBias: Tensor<Float>, pointWiseFilter: Tensor<Float>, pointWiseBias: Tensor<Float>, strides: (Int, Int) ) { dConv = DepthwiseConv2D<Float>( filter: depthWiseFilter, bias: depthWiseBias, activation: relu6, strides: strides, padding: .same ) conv = Conv2D<Float>( filter: pointWiseFilter, bias: pointWiseBias, activation: relu6, padding: .same ) } @differentiable public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> { return input.sequenced(through: dConv, conv) } } public struct MobileNetLikeBackbone: Layer { @noDerivative let ckpt: CheckpointReader public var convBlock0: Conv2D<Float> public var dConvBlock1: DepthwiseSeparableConvBlock public var dConvBlock2: DepthwiseSeparableConvBlock public var dConvBlock3: DepthwiseSeparableConvBlock public var dConvBlock4: DepthwiseSeparableConvBlock public var dConvBlock5: DepthwiseSeparableConvBlock public var dConvBlock6: DepthwiseSeparableConvBlock public var dConvBlock7: DepthwiseSeparableConvBlock public var dConvBlock8: DepthwiseSeparableConvBlock public var dConvBlock9: DepthwiseSeparableConvBlock public var dConvBlock10: DepthwiseSeparableConvBlock public var dConvBlock11: DepthwiseSeparableConvBlock public var dConvBlock12: DepthwiseSeparableConvBlock public var dConvBlock13: DepthwiseSeparableConvBlock public init(checkpoint: CheckpointReader) { self.ckpt = checkpoint self.convBlock0 = Conv2D<Float>( filter: ckpt.load(from: "Conv2d_0/weights"), bias: ckpt.load(from: "Conv2d_0/biases"), activation: relu6, strides: (2, 2), padding: .same ) self.dConvBlock1 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_1_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_1_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_1_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_1_pointwise/biases"), strides: (1, 1) ) self.dConvBlock2 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_2_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_2_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_2_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_2_pointwise/biases"), strides: (2, 2) ) self.dConvBlock3 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_3_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_3_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_3_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_3_pointwise/biases"), strides: (1, 1) ) self.dConvBlock4 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_4_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_4_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_4_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_4_pointwise/biases"), strides: (2, 2) ) self.dConvBlock5 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_5_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_5_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_5_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_5_pointwise/biases"), strides: (1, 1) ) self.dConvBlock6 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_6_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_6_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_6_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_6_pointwise/biases"), strides: (2, 2) ) self.dConvBlock7 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_7_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_7_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_7_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_7_pointwise/biases"), strides: (1, 1) ) self.dConvBlock8 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_8_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_8_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_8_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_8_pointwise/biases"), strides: (1, 1) ) self.dConvBlock9 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_9_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_9_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_9_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_9_pointwise/biases"), strides: (1, 1) ) self.dConvBlock10 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_10_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_10_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_10_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_10_pointwise/biases"), strides: (1, 1) ) self.dConvBlock11 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_11_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_11_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_11_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_11_pointwise/biases"), strides: (1, 1) ) self.dConvBlock12 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_12_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_12_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_12_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_12_pointwise/biases"), strides: (1, 1) ) self.dConvBlock13 = DepthwiseSeparableConvBlock( depthWiseFilter: ckpt.load(from: "Conv2d_13_depthwise/depthwise_weights"), depthWiseBias: ckpt.load(from: "Conv2d_13_depthwise/biases"), pointWiseFilter: ckpt.load(from: "Conv2d_13_pointwise/weights"), pointWiseBias: ckpt.load(from: "Conv2d_13_pointwise/biases"), strides: (1, 1) ) } @differentiable public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> { var x = convBlock0(input) x = dConvBlock1(x) x = dConvBlock2(x) x = dConvBlock3(x) x = dConvBlock4(x) x = dConvBlock5(x) x = dConvBlock6(x) x = dConvBlock7(x) x = dConvBlock8(x) x = dConvBlock9(x) x = dConvBlock10(x) x = dConvBlock11(x) x = dConvBlock12(x) x = dConvBlock13(x) return x } }
apache-2.0
7aa59861c2034b635a25c9dc50ca18a9
39.302083
80
0.707418
3.12394
false
false
false
false
JackLearning/Weibo
Weibo/Weibo/Classes/Module/Message/MessageTableViewController.swift
1
3084
// // MessageTableViewController.swift // Weibo // // Created by apple on 15/12/13. // Copyright ยฉ 2015ๅนด apple. All rights reserved. // import UIKit class MessageTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() visitorLoginView?.setupInfo("็™ปๅฝ•ๅŽ๏ผŒๅˆซไบบ่ฏ„่ฎบไฝ ็š„ๅพฎๅš๏ผŒๅ‘็ป™ไฝ ็š„ๆถˆๆฏ๏ผŒ้ƒฝไผšๅœจ่ฟ™้‡Œๆ”ถๅˆฐ้€š็Ÿฅ", imageName: "visitordiscover_image_message") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
760373e77b4e94ca27937ec1550b0170
32.588889
157
0.684089
5.466546
false
false
false
false
ScreamShot/ScreamShot
ScreamShot/AppDelegate.swift
1
7709
/* This file is part of mac2imgur. * * mac2imgur 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. * mac2imgur 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 mac2imgur. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa import Foundation import ScreamUtils import AVFoundation import Fabric import Crashlytics @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate { @IBOutlet weak var menu: NSMenu! @IBOutlet weak var deleteAfterUploadOption: NSMenuItem! @IBOutlet weak var launchAtStartup: NSMenuItem! @IBOutlet weak var disableDetectionOption: NSMenuItem! @IBOutlet weak var lastItems: NSMenuItem! @IBOutlet weak var copyLastLink: NSMenuItem! @IBOutlet weak var overlayWindow: OverlayWindow! @IBOutlet weak var selectionView: SelectionView! let menuView = MenuView() let defaults = NSUserDefaults.standardUserDefaults() var prefs: PreferencesManager! var monitor: ScreenshotMonitor! var uploadController: UploadController! var authController: ConfigurationWindowController! var currentCaptureOutput: AVCaptureMovieFileOutput? // Delegate methods func applicationDidFinishLaunching(aNotification: NSNotification) { defaults.registerDefaults(["NSApplicationCrashOnExceptions": true]) Fabric.with([Crashlytics.self]) NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self prefs = PreferencesManager() uploadController = UploadController(uploadUrl: prefs.getUploadUrl()) menuView.setupMenu(menu) deleteAfterUploadOption.state = prefs.shouldDeleteAfterUpload() ? NSOnState : NSOffState; disableDetectionOption.state = prefs.isDetectionDisabled() ? NSOnState : NSOffState; launchAtStartup.state = (LaunchServicesHelper.applicationIsInStartUpItems) ? NSOnState : NSOffState; // Start monitoring for screenshots monitor = ScreenshotMonitor() monitor.startMonitoring() selectionView.captureStartedHandler = captureStarted selectionView.captureOutputHandler = recordOutput } func applicationWillTerminate(aNotification: NSNotification) { NSStatusBar.systemStatusBar().removeStatusItem(menuView.statusItem) monitor.stopMonitoring() } @objc @IBAction func copyLink(item: NSMenuItem){ if item.representedObject == nil { return; } copyToClipboard(item.representedObject as! String!); } @IBAction func accountAction(sender: NSMenuItem) { authController = ConfigurationWindowController(windowNibName: "ConfigurationWindow"); authController.callback = { self.uploadController.setUploadUrl(self.prefs.getUploadUrl()) ScreamUtils.displayNotification("Configuration updated!", informativeText: ""); } authController.prefs = prefs; NSApplication.sharedApplication().activateIgnoringOtherApps(true); authController.showWindow(self); } func recordOutput(outputFileURL: NSURL!){ sendFile(outputFileURL, deleteAfter: true) } @IBAction func record(sender: NSMenuItem) { // Check if currently recording if let captureOutput = currentCaptureOutput { // Stop recording captureOutput.stopRecording() // Close the overlay window selectionView.cancelOperation(sender) // Reset the menu menuView.setRecording(false) // Clear the capture currentCaptureOutput = nil } else { print("Click and drag to create a selection! :)") guard let screen = NSScreen.mainScreen() else { return // You don't have a screen? :o } // Make the overlay window fullscreen overlayWindow.setFrame(screen.frame, display: false) overlayWindow.makeKeyAndOrderFront(sender) NSApplication.sharedApplication().activateIgnoringOtherApps(true) selectionView.startSelection(screen) } } // Selector methods @IBAction func selectImages(sender: NSMenuItem) { let panel = NSOpenPanel(); panel.title = "Select files"; panel.prompt = "Upload"; panel.canChooseDirectories = false; panel.allowsMultipleSelection = true; if panel.runModal() == NSModalResponseOK { for imageURL in panel.URLs { sendFile(imageURL, deleteAfter: false) } } } @IBAction func toggleStartup(sender: NSMenuItem) { LaunchServicesHelper.toggleLaunchAtStartup(); launchAtStartup.state = (LaunchServicesHelper.applicationIsInStartUpItems) ? NSOnState : NSOffState; } @IBAction func deleteAfterUploadOption(sender: NSMenuItem) { let delete = (sender.state != NSOnState); prefs.setDeleteAfterUpload(delete); if !delete { sender.state = NSOffState; } else { sender.state = NSOnState; } } @IBAction func disableDetectionOption(sender: NSMenuItem) { let disabled = (sender.state != NSOnState); prefs.setDetectionDisabled(disabled); if !disabled { sender.state = NSOffState; monitor.startMonitoring(); } else { sender.state = NSOnState; monitor.stopMonitoring(); } } func sendScreenshot(filePath: NSURL){ if prefs.isDetectionDisabled() { return } sendFile(filePath, deleteAfter: self.prefs.shouldDeleteAfterUpload()) } func sendFile(filePath: NSURL, deleteAfter: Bool){ menuView.setUploading(true); let upload = Upload(filePath: filePath); upload.addProgressCallback(menuView.setProgress); upload.addSuccessCallback({(link: String) -> () in // Tell the user ScreamUtils.copyToClipboard(link); ScreamUtils.displayNotification("File uploaded successfully!", informativeText: link); // Remove the file self.menuView.setLastItem(filePath.lastPathComponent!, link: link) if deleteAfter { print("Deleting file @ \(filePath)", terminator: ""); deleteFile(filePath.path!); } // Reset the menu icon self.uploadController.next(); self.menuView.setUploading(false); self.menuView.setProgress(0); }); upload.addErrorCallback({(error: String) -> () in NSLog(error); ScreamUtils.displayNotification("Upload failed...", informativeText: ""); }); upload.addStartingCallback({() -> () in self.menuView.setUploading(true) }); uploadController.addToQueue(upload); } func captureStarted(captureOutput: AVCaptureMovieFileOutput) { currentCaptureOutput = captureOutput menuView.setRecording(true) } }
gpl-3.0
d63c1c2c79e4844e47d7ba215a932cca
35.197183
108
0.645739
5.475142
false
false
false
false
lresner/gifu
Source/AnimatableImageView.swift
5
3091
import Runes import UIKit /// A subclass of `UIImageView` that can be animated using an image name string or raw data. public class AnimatableImageView: UIImageView { /// An `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = CADisplayLink(target: self, selector: Selector("updateFrame")) /// The size of the frame cache. public var framePreloadCount = 50 /// A computed property that returns whether the image view is animating. public var isAnimatingGIF: Bool { return !displayLink.paused } /// Prepares the frames using a GIF image file name, without starting the animation. /// The file name should include the `.gif` extension. /// /// :param: imageName The name of the GIF file. The method looks for the file in the app bundle. public func prepareForAnimation(imageNamed imageName: String) { let path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent(imageName) prepareForAnimation <^> NSData(contentsOfFile: path) } /// Prepares the frames using raw GIF image data, without starting the animation. /// /// :param: data GIF image data. public func prepareForAnimation(imageData data: NSData) { image = UIImage(data: data) animator = Animator(data: data, size: frame.size, contentMode: contentMode, framePreloadCount: framePreloadCount) animator?.prepareFrames() attachDisplayLink() } /// Prepares the frames using a GIF image file name and starts animating the image view. /// /// :param: imageName The name of the GIF file. The method looks for the file in the app bundle. public func animateWithImage(named imageName: String) { prepareForAnimation(imageNamed: imageName) startAnimatingGIF() } /// Prepares the frames using raw GIF image data and starts animating the image view. /// /// :param: data GIF image data. public func animateWithImageData(#data: NSData) { prepareForAnimation(imageData: data) startAnimatingGIF() } /// Updates the `UIImage` property of the image view if necessary. This method should not be called manually. override public func displayLayer(layer: CALayer!) { image = animator?.currentFrame } /// Update the current frame with the displayLink duration func updateFrame() { if animator?.updateCurrentFrame(displayLink.duration) ?? false { layer.setNeedsDisplay() } } /// Starts the image view animation. public func startAnimatingGIF() { if animator?.isAnimatable ?? false { displayLink.paused = false } } /// Stops the image view animation. public func stopAnimatingGIF() { displayLink.paused = true } /// Invalidate the displayLink so it releases this object. public func cleanup() { displayLink.invalidate() } /// Attaches the display link. private func attachDisplayLink() { displayLink.addToRunLoop(.mainRunLoop(), forMode: NSRunLoopCommonModes) } }
mit
bfa10f96b0fed631b870be12cfd0be7f
34.125
117
0.724361
4.883096
false
false
false
false
glbuyer/GbKit
GbKit/Models/HomePageComponents/GBHomepageComponentProductsTail.swift
1
1413
// // GBHomepageComponentProductsTail.swift // GbKit // // Created by Ye Gu on 24/10/17. // Copyright ยฉ 2017 glbuyer. All rights reserved. // enum GBHomepageComponentProductsTailRefreshNewContentLoadingIconType : String { //้ป˜่ฎคๆ ทๅผ case normal = "NORMAL" //่‡ชๅฎšไน‰ๆ ทๅผ1 case customized1 = "CUSTOMIZED1" //ไธๅฏ็”จ case notAppliable = "N/A" } enum GBHomepageComponentProductsTailLoadMoreContentLoadingIconType : String { //้ป˜่ฎคๆ ทๅผ case normal = "NORMAL" //ไธๅฏ็”จ case notAppliable = "N/A" } import Foundation class GBHomepageComponentProductsTail: GBHomepageBaseComponent { //ๆ ‡้ข˜ var titleCell = GBHomepageCell() //ๅ†…ๅฎน cells var contentCells = [GBHomepageCell]() //ๅˆทๆ–ฐๅ•†ๅ“ ๅŠ ่ฝฝ ๅ›พๆ ‡ var refreshNewContentLoadingIconType = GBHomepageComponentProductsTailRefreshNewContentLoadingIconType.customized1 //ๅŠ ่ฝฝๆ›ดๅคšๅ•†ๅ“ ๅŠ ่ฝฝ ๅ›พๆ ‡ var loadMoreContentLoadingIconType = GBHomepageComponentProductsTailRefreshNewContentLoadingIconType.normal //ๅˆทๆ–ฐๅ•†ๅ“ var refreshNewContentCellsAPI = "" //ๅŠ ่ฝฝๆ›ดๅคšๅ•†ๅ“ var loadMoreContentCellsAPI = "" //component ้ซ˜ๅบฆ ๅฏนไบŽ 750px ๅฎฝๅบฆๅฑๅน• var componentHeightTo750pxWidth:Double = 600 //component ๅฎฝๅบฆ ๅฏนไบŽ 750px ๅฎฝๅบฆๅฑๅน• var componentWidthTo750pxWidth:Double = 750 }
mit
25670792c11438ded114be612b7b3b16
22.666667
118
0.71205
4.070064
false
false
false
false
pinterest/tulsi
src/Tulsi/OptionsTargetSelectorController.swift
1
3804
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Cocoa import TulsiGenerator /// Models a UIRuleEntry as a node suitable for display in the options target selector. class OptionsTargetNode: UISelectableOutlineViewNode { /// Tooltip to be displayed for this node. @objc var toolTip: String? = nil @objc var boldFont: Bool { return !children.isEmpty } } protocol OptionsTargetSelectorControllerDelegate: class { /// Invoked when the target selection has been changed. func didSelectOptionsTargetNode(_ node: OptionsTargetNode) } // Delegate for the target selector outline view. class OptionsTargetSelectorController: NSObject, NSOutlineViewDelegate { static let projectSectionTitle = NSLocalizedString("OptionsTarget_ProjectSectionTitle", comment: "Short header shown before the project in the options editor's target selector.") static let targetSectionTitle = NSLocalizedString("OptionsTarget_TargetSectionTitle", comment: "Short header shown before the build targets in the options editor's target selector.") weak var view: NSOutlineView! @objc dynamic var nodes = [OptionsTargetNode]() weak var delegate: OptionsTargetSelectorControllerDelegate? weak var model: OptionsEditorModelProtocol! = nil { didSet { if model == nil || model.projectName == nil { return } let projectSection = OptionsTargetNode(name: OptionsTargetSelectorController.projectSectionTitle) projectSection.addChild(OptionsTargetNode(name: model.projectName!)) var newNodes = [projectSection] if model.shouldShowPerTargetOptions, let targetEntries = model.optionsTargetUIRuleEntries { let targetSection = OptionsTargetNode(name: OptionsTargetSelectorController.targetSectionTitle) for entry in targetEntries { let node = OptionsTargetNode(name: entry.targetName!) node.toolTip = entry.fullLabel node.entry = entry targetSection.addChild(node) } newNodes.append(targetSection) } nodes = newNodes // Expand all children in the target selector and select the project. view.expandItem(nil, expandChildren: true) view.selectRowIndexes(IndexSet(integer: 1), byExtendingSelection: false) } } init(view: NSOutlineView, delegate: OptionsTargetSelectorControllerDelegate) { self.view = view self.delegate = delegate super.init() self.view.delegate = self } func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool { // The top level items are not selectable. return outlineView.level(forItem: item) > 0 } func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool { return false } func outlineView(_ outlineView: NSOutlineView, shouldShowOutlineCellForItem item: Any) -> Bool { return false } func outlineViewSelectionDidChange(_ notification: Notification) { if delegate == nil { return } let selectedTreeNode = view.item(atRow: view.selectedRow) as! NSTreeNode let selectedTarget = selectedTreeNode.representedObject as! OptionsTargetNode delegate!.didSelectOptionsTargetNode(selectedTarget) } }
apache-2.0
994f61157438a9e8ff6bff7baa010492
36.294118
120
0.733701
4.81519
false
false
false
false
hikelee/cinema
Sources/App/Controllers/MovieController.swift
1
5611
import Vapor import HTTP import Fluent class MovieAdminController : ChannelBasedController<Movie> { typealias Model = Movie let pageSize=30 override var path:String {return "/admin/cinema/movie"} required init(droplet:Droplet,routerGroup:RouterGroup){ super.init(droplet:droplet,routerGroup:routerGroup) routerGroup.get("\(path)/info"){try self.info($0)} //routerGroup.get("\(path)/json"){try self.json($0)} } func info(_ request: Request) throws -> ResponseRepresentable { var data:[Node] = [] if let ids = request.data["ids"]?.string, !ids.isEmpty{ let order = Order() order.movies = ids try order.movieIds.forEach{ if let movie = try Model.load(channelId:request.channelId,bizId:$0), let title = movie.title,!title.isEmpty{ let node = try Node( node:["id": movie.id, "title": movie.title, "length": movie.movieLength]) data.append(node) } } } return try JSON(node:["list":data.makeNode()]) } override func create(_ request: Request) throws -> ResponseRepresentable { var new = try getModel(request) new.bizId = try Node(Model.getNextBizId(channelId:request.channelId)) if let response = try validate(new,true){ return response } new.id = nil try new.save() return new } override func preChange(request:Request,model:Model) throws{ if request.isRoot{ throw AuthorError.rejected(message:"ๆฒกๆœ‰ๆƒ้™ๆ‰ง่กŒๆญคๆ“ไฝœ๏ผ") } } override func preView(request: Request) throws -> ResponseRepresentable? { return request.isRoot ? Response(redirect: "/admin/cinema/movieTemplate") : nil } override func list(_ request: Request) throws -> ResponseRepresentable { if request.contentType?.range(of:"json") != nil { return try JSON(node:Model.simpleList(channelId:request.channelId)).makeBytes().string } return try preView(request:request) ?? renderLeaf(request,"List",[:]) } //used in list/form page override func additonalFormData(_ request: Request) throws ->[String:Node]{ let categories = try Category.allNodes(channelId:request.channelId) let hots = (1...10).map{11-$0} return try [ "hots":hots.makeNode(), "categories":categories.makeNode(), ] } } class MovieApiController: Controller{ let path = "/api/cinema/movie" required init(droplet:Droplet,routerGroup:RouterGroup){ super.init(droplet:droplet,routerGroup:routerGroup) } override func makeRouter(){ routerGroup.group(path){group in group.post("/sync"){try self.sync($0)} group.get("/sync"){try self.sync($0)} } } func sync(_ request: Request) throws -> ResponseRepresentable { guard let macAddress = request.data["mac"]?.string?.uppercased() else { return "error,no-mac" } guard let ids = request.data["ids"]?.string else { return "error,no-ids" } log(macAddress) log(ids) return try Movie.sync(macAddress:macAddress,ids:ids) } } class MovieSiteController : RestController<Movie>{ typealias M = Movie override var path:String {return "/site/cinema/movie"} required init(droplet:Droplet,routerGroup:RouterGroup){ super.init(droplet:droplet,routerGroup:routerGroup) } //list page override func list(_ request: Request) throws -> ResponseRepresentable { if request.data["elements"]?.bool ?? false { guard let channelId = request.data["channel"]?.int, channelId>0 else { return try JSON(node:["error":"no-channel"]) } guard let server = try Server.query() .filter("channel_id",channelId).filter("is_primary",true).first() else { return try JSON(node:["error":"no server-found"]) } guard let serverId = server.id?.int else { return try JSON(node:["error":"server-id-empty"]) } let categoryId = request.data["category"]?.int let key = request.data["key"]?.string let array = try Movie.siteList(channelId:channelId, serverId:serverId,categoryId:categoryId,key:key) return try JSON(node:["movies":array.makeNode()]) } return try renderList(request:request,data:[:]) } override func additonalListData(_ request: Request) throws ->[String:Node]{ if let channelId = request.data["channel"]?.int, channelId>0 { var array:[Node] = [] try array.append(Node(node:["id":0,"title":"ๅ…จ้ƒจๅฝฑ็‰‡"])) try Category.getAvailabeList(channelId:channelId).forEach{ array.append($0) } return try ["categories":array.makeNode()] } return [:] } override func additonalData(_ request: Request) throws ->[String:Node]{ if let channelId = request.data["channel"]?.int, let server = try Server.query().filter("channel_id",.equals,channelId) .filter("is_primary",.equals,true).first(), let ipAddress = server.ipAddress{ return [ "host": Node(ipAddress), "path": Node(path), "channel":Node(channelId)] } return [:] } }
mit
65f394eceb764244b3d260c214182cf5
36.469799
98
0.58714
4.399527
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.Name.swift
1
1973
import Foundation public extension AnyCharacteristic { static func name( _ value: String = "", permissions: [CharacteristicPermission] = [.read], description: String? = "Name", format: CharacteristicFormat? = .string, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.name( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func name( _ value: String = "", permissions: [CharacteristicPermission] = [.read], description: String? = "Name", format: CharacteristicFormat? = .string, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<String> { GenericCharacteristic<String>( type: .name, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
b19da77edc6368267e399fd22a26ec09
31.344262
66
0.564622
5.480556
false
false
false
false
Incipia/Conduction
Conduction/Classes/ConductionState.swift
1
3160
// // ConductionState.swift // Bindable // // Created by Gregory Klein on 6/28/17. // import Foundation public protocol ConductionState { init() mutating func update(_ block: (inout Self) -> Void) } extension ConductionState { mutating public func update(_ block: (inout Self) -> Void) { block(&self) } } public struct EmptyConductionState: ConductionState { public init() {} } public typealias ConductionObserverHandle = UInt public protocol ConductionStateObserverType: class { // MARK: - Associated Types associatedtype State: ConductionState typealias StateChangeBlock = (_ old: State, _ new: State) -> Void // MARK: - Public Properties var state: State { get } var _stateChangeBlocks: [ConductionObserverHandle : StateChangeBlock] { get set } // MARK: - Public @discardableResult func addStateObserver(_ changeBlock: @escaping StateChangeBlock) -> ConductionObserverHandle func removeStateObserver(handle: ConductionObserverHandle) func stateChanged(oldState: State?) } public extension ConductionStateObserverType { @discardableResult public func addStateObserver(_ changeBlock: @escaping StateChangeBlock) -> ConductionObserverHandle { changeBlock(state, state) return _stateChangeBlocks.add(newValue: changeBlock) } public func removeStateObserver(handle: ConductionObserverHandle) { _stateChangeBlocks[handle] = nil } public func stateChanged(oldState: State? = nil) { _stateChangeBlocks.forEach { $0.value(oldState ?? state, state) } } } open class ConductionStateObserver<State: ConductionState>: ConductionStateObserverType { // MARK: - Nested Types public typealias StateChangeBlock = (_ old: State, _ new: State) -> Void // MARK: - Private Properties public var _stateChangeBlocks: [ConductionObserverHandle : StateChangeBlock] = [:] // MARK: - Public Properties public var state: State = State() { willSet { stateWillChange(nextState: newValue) } didSet { stateChanged(oldState: oldValue) } } // MARK: - Init public init() {} // MARK: - Subclass Hooks open func stateWillChange(nextState: State) {} open func stateChanged(oldState: State? = nil) { _stateChangeBlocks.forEach { $0.value(oldState ?? state, state) } } // MARK: - Public public func resetState() { state = State() } } protocol ConductionObserverHandleType { // MARK: - Public Properties static var first: Self { get } var next: Self { get } } extension ConductionObserverHandle: ConductionObserverHandleType { static var first: ConductionObserverHandle { return 0 } var next: ConductionObserverHandle { return self + 1 } } extension Dictionary where Key: ConductionObserverHandleType { // MARK: - Public Properties var nextHandle: Key { var handle = Key.first while self.keys.contains(handle) { handle = handle.next } return handle } // MARK: - Public mutating func add(newValue: Value) -> Key { let newKey = nextHandle self[newKey] = newValue return newKey } }
mit
8d08e7759f76bd64c9e2d904a16e4337
26.008547
123
0.686076
4.553314
false
false
false
false
drewcrawford/XcodeServerSDK
XcodeServerSDK/Server Entities/SourceControlBlueprint.swift
2
9654
// // SourceControlBlueprint.swift // Buildasaur // // Created by Honza Dvorsky on 11/01/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils extension String { public var base64Encoded: String? { let data = dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) return data?.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed) } } public class SourceControlBlueprint : XcodeServerEntity { public let branch: String public let projectWCCIdentifier: String public let wCCName: String public let projectName: String public let projectURL: String public let projectPath: String public let commitSHA: String? public let privateSSHKey: String? public let publicSSHKey: String? public let sshPassphrase: String? public var certificateFingerprint: String? = nil public required init(json: NSDictionary) { self.wCCName = json.stringForKey(XcodeBlueprintNameKey) let primaryRepoId = json.stringForKey(XcodeBlueprintPrimaryRemoteRepositoryKey) self.projectWCCIdentifier = primaryRepoId let workingCopyPaths = json.dictionaryForKey(XcodeBlueprintWorkingCopyPathsKey) self.projectName = workingCopyPaths.stringForKey(primaryRepoId) let repos: [NSDictionary] = json.arrayForKey(XcodeBlueprintRemoteRepositoriesKey) let primarys: [NSDictionary] = repos.filter { (item: NSDictionary) -> Bool in return item.stringForKey(XcodeBlueprintRemoteRepositoryIdentifierKey) == primaryRepoId } self.projectPath = json.stringForKey(XcodeBlueprintRelativePathToProjectKey) let repo = primarys.first! self.projectURL = repo.stringForKey(XcodeBlueprintRemoteRepositoryURLKey) self.certificateFingerprint = repo.optionalStringForKey(XcodeBlueprintRemoteRepositoryCertFingerprintKey) let locations = json.dictionaryForKey(XcodeBlueprintLocationsKey) let location = locations.dictionaryForKey(primaryRepoId) self.branch = location.optionalStringForKey(XcodeBranchIdentifierKey) ?? "" self.commitSHA = location.optionalStringForKey(XcodeLocationRevisionKey) let authenticationStrategy = json.optionalDictionaryForKey(XcodeRepositoryAuthenticationStrategiesKey)?.optionalDictionaryForKey(primaryRepoId) self.privateSSHKey = authenticationStrategy?.optionalStringForKey(XcodeRepoAuthenticationStrategiesKey) self.publicSSHKey = authenticationStrategy?.optionalStringForKey(XcodeRepoPublicKeyDataKey) self.sshPassphrase = authenticationStrategy?.optionalStringForKey(XcodeRepoPasswordKey) super.init(json: json) } public init(branch: String, projectWCCIdentifier: String, wCCName: String, projectName: String, projectURL: String, projectPath: String, publicSSHKey: String?, privateSSHKey: String?, sshPassphrase: String?, certificateFingerprint: String? = nil) { self.branch = branch self.projectWCCIdentifier = projectWCCIdentifier self.wCCName = wCCName self.projectName = projectName self.projectURL = projectURL self.projectPath = projectPath self.commitSHA = nil self.publicSSHKey = publicSSHKey self.privateSSHKey = privateSSHKey self.sshPassphrase = sshPassphrase self.certificateFingerprint = certificateFingerprint super.init() } //for credentials verification only public convenience init(projectURL: String, publicSSHKey: String?, privateSSHKey: String?, sshPassphrase: String?) { self.init(branch: "", projectWCCIdentifier: "", wCCName: "", projectName: "", projectURL: projectURL, projectPath: "", publicSSHKey: publicSSHKey, privateSSHKey: privateSSHKey, sshPassphrase: sshPassphrase) } public func dictionarifyRemoteAndCredentials() -> NSDictionary { let dictionary = NSMutableDictionary() let repoId = self.projectWCCIdentifier let remoteUrl = self.projectURL let sshPublicKey = self.publicSSHKey?.base64Encoded ?? "" let sshPrivateKey = self.privateSSHKey?.base64Encoded ?? "" let sshPassphrase = self.sshPassphrase ?? "" let certificateFingerprint = self.certificateFingerprint ?? "" //blueprint is not valid without this magic version dictionary[XcodeBlueprintVersion] = 203 //now, a repo is defined by its server location. so let's throw that in. dictionary[XcodeBlueprintRemoteRepositoriesKey] = [ [ XcodeBlueprintRemoteRepositoryURLKey: remoteUrl, XcodeBlueprintRemoteRepositorySystemKey: "com.apple.dt.Xcode.sourcecontrol.Git", //TODO: add more SCMs XcodeBlueprintRemoteRepositoryIdentifierKey: repoId, //new - certificate fingerprint XcodeBlueprintRemoteRepositoryCertFingerprintKey: certificateFingerprint, XcodeBlueprintRemoteRepositoryTrustSelfSignedCertKey: true ] ] //but since there might be multiple repos (think git submodules), we need to declare //the primary one. dictionary[XcodeBlueprintPrimaryRemoteRepositoryKey] = repoId //now, this is enough for a valid blueprint. it might not be too useful, but it's valid. //to make our supported (git) repos work, we also need some credentials. //repo authentication //again, since we can provide information for multiple repos, keep the repo's id close. dictionary[XcodeRepositoryAuthenticationStrategiesKey] = [ repoId: [ XcodeRepoAuthenticationTypeKey: XcodeRepoSSHKeysAuthenticationStrategy, XcodeRepoUsernameKey: "git", //TODO: see how to add https support? XcodeRepoPasswordKey: sshPassphrase, XcodeRepoAuthenticationStrategiesKey: sshPrivateKey, XcodeRepoPublicKeyDataKey: sshPublicKey ] ] //up to this is all we need to verify credentials and fingerprint during preflight //which is now under /api/scm/branches. all the stuff below is useful for actually *creating* //a bot. return dictionary } private func dictionarifyForBotCreation() -> NSDictionary { let dictionary = self.dictionarifyRemoteAndCredentials().mutableCopy() as! NSMutableDictionary let repoId = self.projectWCCIdentifier var workingCopyPath = self.projectName //ensure a trailing slash if !workingCopyPath.hasSuffix("/") { workingCopyPath = workingCopyPath + "/" } let relativePathToProject = self.projectPath let blueprintName = self.wCCName let branch = self.branch //we're creating a bot now. //our bot has to know which code to check out - we declare that by giving it a branch to track. //in our case it can be "master", for instance. dictionary[XcodeBlueprintLocationsKey] = [ repoId: [ XcodeBranchIdentifierKey: branch, XcodeBranchOptionsKey: 156, //super magic number XcodeBlueprintLocationTypeKey: "DVTSourceControlBranch" //TODO: add more types? ] ] //once XCS checks out your repo, it also needs to know how to get to your working copy, in case //you have a complicated multiple-folder repo setup. coming from the repo's root, for us it's //something like "XcodeServerSDK/" dictionary[XcodeBlueprintWorkingCopyPathsKey] = [ repoId: workingCopyPath ] //once we're in our working copy, we need to know which Xcode project/workspace to use! //this is relative to the working copy above. all coming together, huh? here //it would be "XcodeServerSDK.xcworkspace" dictionary[XcodeBlueprintRelativePathToProjectKey] = relativePathToProject //now we've given it all we knew. what else? //turns out there are a couple more keys that XCS needs to be happy. so let's feed the beast. //every nice data structure needs a name. so give the blueprint one as well. this is usually //the same as the name of your project, "XcodeServerSDK" in our case here dictionary[XcodeBlueprintNameKey] = blueprintName //just feed the beast, ok? this has probably something to do with working copy state, git magic. //we pass 0. don't ask. dictionary[XcodeBlueprintWorkingCopyStatesKey] = [ repoId: 0 ] //and to uniquely identify this beauty, we also need to give it a UUID. well, technically I think //Xcode generates a hash from the data somehow, but passing in a random UUID works as well, so what the hell. //if someone figures out how to generate the same ID as Xcode does, I'm all yours. //TODO: give this a good investigation. dictionary[XcodeBlueprintIdentifierKey] = NSUUID().UUIDString //and this is the end of our journey to create a new Blueprint. I hope you enjoyed the ride, please return the 3D glasses to the green bucket on your way out. return dictionary } public override func dictionarify() -> NSDictionary { return self.dictionarifyForBotCreation() } }
mit
9082f41711b2a69ca8d11247b3cc81bc
44.11215
214
0.679407
5.165329
false
false
false
false
debugsquad/Hyperborea
Hyperborea/View/Search/VSearchResultsFlow.swift
1
3937
import UIKit class VSearchResultsFlow:UICollectionViewLayout { private weak var controller:CSearch! private var layoutAttributes:[UICollectionViewLayoutAttributes] private var contentWidth:CGFloat private var contentHeight:CGFloat private let kContentBottom:CGFloat = 20 private let kMarginHorizontal:CGFloat = 10 private let kMarginVertical:CGFloat = 10 private let kSection:Int = 0 init(controller:CSearch) { contentWidth = 0 contentHeight = 0 layoutAttributes = [] self.controller = controller super.init() } required init?(coder:NSCoder) { return nil } override func prepare() { super.prepare() layoutAttributes = [] guard let model:MSearchResults = controller.modelResults else { return } contentWidth = UIScreen.main.bounds.maxX let maxWidth:CGFloat = contentWidth - kMarginHorizontal var positionY:CGFloat = controller.viewSearch.barOptionsTop + kMarginVertical var positionX:CGFloat = kMarginHorizontal var maxCurrentY:CGFloat = 0 var item:Int = 0 for result:MSearchResultsItem in model.items { let indexPath:IndexPath = IndexPath( item:item, section:kSection) let cellWidth:CGFloat = result.cellWidth let cellHeight:CGFloat = result.cellHeight if positionX + cellWidth > maxWidth { positionX = kMarginHorizontal positionY += maxCurrentY + kMarginVertical maxCurrentY = 0 } let frame:CGRect = CGRect( x:positionX, y:positionY, width:cellWidth, height:cellHeight) if cellHeight > maxCurrentY { maxCurrentY = cellHeight } item += 1 positionX += cellWidth + kMarginHorizontal let attributes:UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes( forCellWith:indexPath) attributes.frame = frame layoutAttributes.append(attributes) } contentHeight = positionY + maxCurrentY + kContentBottom controller.viewSearch.resultsHeight(resultsHeight:contentHeight) } override var collectionViewContentSize:CGSize { get { let size:CGSize = CGSize( width:contentWidth, height:contentHeight) return size } } override func layoutAttributesForElements(in rect:CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes:[UICollectionViewLayoutAttributes]? for layoutAttribute:UICollectionViewLayoutAttributes in layoutAttributes { let frame:CGRect = layoutAttribute.frame if frame.intersects(rect) { if attributes == nil { attributes = [] } attributes!.append(layoutAttribute) } } return attributes } override func layoutAttributesForItem(at indexPath:IndexPath) -> UICollectionViewLayoutAttributes? { for layoutAttribute:UICollectionViewLayoutAttributes in layoutAttributes { if layoutAttribute.indexPath == indexPath { return layoutAttribute } } return nil } override func shouldInvalidateLayout(forBoundsChange newBounds:CGRect) -> Bool { return false } }
mit
873a5c87a96984a65f935f8c33ee9b3d
26.921986
102
0.555245
6.4967
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/MailingAddressInput.swift
1
8518
// // MailingAddressInput.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 { /// Specifies the fields accepted to create or update a mailing address. open class MailingAddressInput { /// The first line of the address. Typically the street address or PO Box /// number. open var address1: Input<String> /// The second line of the address. Typically the number of the apartment, /// suite, or unit. open var address2: Input<String> /// The name of the city, district, village, or town. open var city: Input<String> /// The name of the customer's company or organization. open var company: Input<String> /// The name of the country. open var country: Input<String> /// The first name of the customer. open var firstName: Input<String> /// The last name of the customer. open var lastName: Input<String> /// A unique phone number for the customer. Formatted using E.164 standard. For /// example, _+16135551111_. open var phone: Input<String> /// The region of the address, such as the province, state, or district. open var province: Input<String> /// The zip or postal code of the address. open var zip: Input<String> /// Creates the input object. /// /// - parameters: /// - address1: The first line of the address. Typically the street address or PO Box number. /// - address2: The second line of the address. Typically the number of the apartment, suite, or unit. /// - city: The name of the city, district, village, or town. /// - company: The name of the customer's company or organization. /// - country: The name of the country. /// - firstName: The first name of the customer. /// - lastName: The last name of the customer. /// - phone: A unique phone number for the customer. Formatted using E.164 standard. For example, _+16135551111_. /// - province: The region of the address, such as the province, state, or district. /// - zip: The zip or postal code of the address. /// public static func create(address1: Input<String> = .undefined, address2: Input<String> = .undefined, city: Input<String> = .undefined, company: Input<String> = .undefined, country: Input<String> = .undefined, firstName: Input<String> = .undefined, lastName: Input<String> = .undefined, phone: Input<String> = .undefined, province: Input<String> = .undefined, zip: Input<String> = .undefined) -> MailingAddressInput { return MailingAddressInput(address1: address1, address2: address2, city: city, company: company, country: country, firstName: firstName, lastName: lastName, phone: phone, province: province, zip: zip) } private init(address1: Input<String> = .undefined, address2: Input<String> = .undefined, city: Input<String> = .undefined, company: Input<String> = .undefined, country: Input<String> = .undefined, firstName: Input<String> = .undefined, lastName: Input<String> = .undefined, phone: Input<String> = .undefined, province: Input<String> = .undefined, zip: Input<String> = .undefined) { self.address1 = address1 self.address2 = address2 self.city = city self.company = company self.country = country self.firstName = firstName self.lastName = lastName self.phone = phone self.province = province self.zip = zip } /// Creates the input object. /// /// - parameters: /// - address1: The first line of the address. Typically the street address or PO Box number. /// - address2: The second line of the address. Typically the number of the apartment, suite, or unit. /// - city: The name of the city, district, village, or town. /// - company: The name of the customer's company or organization. /// - country: The name of the country. /// - firstName: The first name of the customer. /// - lastName: The last name of the customer. /// - phone: A unique phone number for the customer. Formatted using E.164 standard. For example, _+16135551111_. /// - province: The region of the address, such as the province, state, or district. /// - zip: The zip or postal code of the address. /// @available(*, deprecated, message: "Use the static create() method instead.") public convenience init(address1: String? = nil, address2: String? = nil, city: String? = nil, company: String? = nil, country: String? = nil, firstName: String? = nil, lastName: String? = nil, phone: String? = nil, province: String? = nil, zip: String? = nil) { self.init(address1: address1.orUndefined, address2: address2.orUndefined, city: city.orUndefined, company: company.orUndefined, country: country.orUndefined, firstName: firstName.orUndefined, lastName: lastName.orUndefined, phone: phone.orUndefined, province: province.orUndefined, zip: zip.orUndefined) } internal func serialize() -> String { var fields: [String] = [] switch address1 { case .value(let address1): guard let address1 = address1 else { fields.append("address1:null") break } fields.append("address1:\(GraphQL.quoteString(input: address1))") case .undefined: break } switch address2 { case .value(let address2): guard let address2 = address2 else { fields.append("address2:null") break } fields.append("address2:\(GraphQL.quoteString(input: address2))") case .undefined: break } switch city { case .value(let city): guard let city = city else { fields.append("city:null") break } fields.append("city:\(GraphQL.quoteString(input: city))") case .undefined: break } switch company { case .value(let company): guard let company = company else { fields.append("company:null") break } fields.append("company:\(GraphQL.quoteString(input: company))") case .undefined: break } switch country { case .value(let country): guard let country = country else { fields.append("country:null") break } fields.append("country:\(GraphQL.quoteString(input: country))") case .undefined: break } switch firstName { case .value(let firstName): guard let firstName = firstName else { fields.append("firstName:null") break } fields.append("firstName:\(GraphQL.quoteString(input: firstName))") case .undefined: break } switch lastName { case .value(let lastName): guard let lastName = lastName else { fields.append("lastName:null") break } fields.append("lastName:\(GraphQL.quoteString(input: lastName))") case .undefined: break } switch phone { case .value(let phone): guard let phone = phone else { fields.append("phone:null") break } fields.append("phone:\(GraphQL.quoteString(input: phone))") case .undefined: break } switch province { case .value(let province): guard let province = province else { fields.append("province:null") break } fields.append("province:\(GraphQL.quoteString(input: province))") case .undefined: break } switch zip { case .value(let zip): guard let zip = zip else { fields.append("zip:null") break } fields.append("zip:\(GraphQL.quoteString(input: zip))") case .undefined: break } return "{\(fields.joined(separator: ","))}" } } }
mit
bd63319bb79ee3fc54270bda8afc8297
37.542986
419
0.677859
3.708315
false
false
false
false
debugsquad/Hyperborea
Hyperborea/Model/Store/Purchases/MStoreItemPlus.swift
1
974
import UIKit class MStoreItemPlus:MStoreItem { private let kStorePurchaseId:MStore.PurchaseId = "iturbide.Hyperborea.plus" init() { let title:String = NSLocalizedString("MStoreItemPlus_title", comment:"") let descr:String = NSLocalizedString("MStoreItemPlus_descr", comment:"") let image:UIImage = #imageLiteral(resourceName: "assetGenericStorePlus") super.init( purchaseId:kStorePurchaseId, title:title, descr:descr, image:image) } override func purchaseAction() { MSession.sharedInstance.settings?.purchasePlus = true DManager.sharedInstance?.save() } override func validatePurchase() -> Bool { guard let purchased:Bool = MSession.sharedInstance.settings?.purchasePlus else { return false } return purchased } }
mit
956468b28f35b3124c943a6261f5b5ea
23.974359
80
0.585216
5.099476
false
false
false
false
sekouperry/pulltomakesoup-fix
PullToMakeSoup/PullToMakeSoup/PullToRefresh/PullToRefresh.swift
1
7194
// // PullToRefresh.swift // CookingPullToRefresh // // Created by Anastasiya Gorban on 4/14/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit import Foundation public protocol RefreshViewAnimator { func animateState(state: State) } // MARK: PullToRefresh public class PullToRefresh: NSObject { let refreshView: UIView var action: (() -> ())? private let animator: RefreshViewAnimator private var scrollViewDefaultInsets = UIEdgeInsetsZero weak var scrollView: UIScrollView? { didSet { oldValue?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) if let scrollView = scrollView { scrollViewDefaultInsets = scrollView.contentInset scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &KVOContext) } } } // MARK: - State var state: State = .Inital { didSet { animator.animateState(state) switch state { case .Loading: if let scrollView = scrollView where (oldValue != .Loading) { scrollView.contentOffset = previousScrollViewOffset scrollView.bounces = false UIView.animateWithDuration(0.3, animations: { let insets = self.refreshView.frame.height + self.scrollViewDefaultInsets.top scrollView.contentInset.top = insets scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets) }, completion: { finished in scrollView.bounces = true }) action?() } case .Finished: UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveLinear, animations: { self.scrollView?.contentInset = self.scrollViewDefaultInsets self.scrollView?.contentOffset.y = -self.scrollViewDefaultInsets.top }, completion: nil) default: break } } } // MARK: - Initialization public init(refreshView: UIView, animator: RefreshViewAnimator) { self.refreshView = refreshView self.animator = animator } public override convenience init() { let refreshView = DefaultRefreshView() self.init(refreshView: refreshView, animator: DefaultViewAnimator(refreshView: refreshView)) } deinit { scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) } // MARK: KVO private var KVOContext = "PullToRefreshKVOContext" private let contentOffsetKeyPath = "contentOffset" private var previousScrollViewOffset: CGPoint = CGPointZero override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<()>) { if (context == &KVOContext && keyPath == contentOffsetKeyPath && object as? UIScrollView == scrollView) { let offset = previousScrollViewOffset.y + scrollViewDefaultInsets.top let refreshViewHeight = refreshView.frame.size.height switch offset { case 0: state = .Inital case -refreshViewHeight...0 where (state != .Loading && state != .Finished): state = .Releasing(progress: -offset / refreshViewHeight) case -1000...(-refreshViewHeight): if state == State.Releasing(progress: 1) && scrollView?.dragging == false { state = .Loading } else if state != .Loading { state = .Releasing(progress: 1) } default: break } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } previousScrollViewOffset.y = scrollView!.contentOffset.y } // MARK: - Start/End Refreshing func startRefreshing() { if self.state != State.Inital { return } scrollView?.setContentOffset(CGPointMake(0, -refreshView.frame.height - scrollViewDefaultInsets.top), animated: true) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.27 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue(), { self.state = State.Loading }) } func endRefreshing() { if state == .Loading { state = .Finished } } } // MARK: - State enumeration public enum State:Equatable { case Inital, Loading, Finished case Releasing(progress: CGFloat) } public func ==(a: State, b: State) -> Bool { switch (a, b) { case (.Inital, .Inital): return true case (.Loading, .Loading): return true case (.Finished, .Finished): return true case (.Releasing(let a), .Releasing(let b)): return true default: return false } } // MARK: Default PullToRefresh class DefaultRefreshView: UIView { private(set) var activicyIndicator: UIActivityIndicatorView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, 40) } override func layoutSubviews() { if (activicyIndicator == nil) { activicyIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) activicyIndicator.center = convertPoint(center, fromView: superview) activicyIndicator.hidesWhenStopped = false addSubview(activicyIndicator) } super.layoutSubviews() } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if let superview = newSuperview { frame = CGRectMake(frame.origin.x, frame.origin.y, superview.frame.width, 40) } } } class DefaultViewAnimator: RefreshViewAnimator { private let refreshView: DefaultRefreshView init(refreshView: DefaultRefreshView) { self.refreshView = refreshView } func animateState(state: State) { switch state { case .Inital: refreshView.activicyIndicator?.stopAnimating() case .Releasing(let progress): var transform = CGAffineTransformIdentity transform = CGAffineTransformScale(transform, progress, progress); transform = CGAffineTransformRotate(transform, 3.14 * progress * 2); refreshView.activicyIndicator.transform = transform case .Loading: refreshView.activicyIndicator.startAnimating() default: break } } }
mit
9c089058f9f8bff8a6aa263caaea258c
33.421053
171
0.610648
5.309225
false
false
false
false
androidrivne/rebekka
rebekka-source/Rebekka/ResourceListOperation.swift
1
5294
// // ResourceListOperation.swift // Rebekka // // Created by Constantine Fry on 25/05/15. // Copyright (c) 2015 Constantine Fry. All rights reserved. // import Foundation /* Resource type, values defined in `sys/dirent.h`. */ public enum ResourceType: String { case Unknown = "Unknown" // DT_UNKNOWN case Directory = "Directory" // DT_DIR case RegularFile = "RegularFile" // DT_REG case SymbolicLink = "SymbolicLink" // DT_LNK case NamedPipe = "NamedPipe" // DT_FIFO case CharacterDevice = "CharacterDevice" // DT_CHR case BlockDevice = "BlockDevice" // DT_BLK case LocalDomainSocket = "LocalDomainSocket" // DT_SOCK case Whiteout = "Whiteout" // DT_WHT } public class ResourceItem: CustomStringConvertible { public var type: ResourceType = .Unknown public var name: String = "" public var link: String = "" public var date: NSDate = NSDate() public var size: Int = 0 public var mode: Int32 = 0 public var owner: String = "" public var group: String = "" public var path: String = "/" public var description: String { get { return "\nResourceItem: \(name), \(type.rawValue)" } } } private let _resourceTypeMap: [Int:ResourceType] = [ Int(DT_UNKNOWN): ResourceType.Unknown, Int(DT_FIFO): ResourceType.NamedPipe, Int(DT_SOCK): ResourceType.LocalDomainSocket, Int(DT_CHR): ResourceType.CharacterDevice, Int(DT_DIR): ResourceType.Directory, Int(DT_BLK): ResourceType.BlockDevice, Int(DT_REG): ResourceType.RegularFile, Int(DT_LNK): ResourceType.SymbolicLink, Int(DT_WHT): ResourceType.Whiteout ] /** Operation for resource listing. */ internal class ResourceListOperation: ReadStreamOperation { private var inputData: NSMutableData? var resources: [ResourceItem]? override func streamEventEnd(aStream: NSStream) -> (Bool, NSError?) { var offset = 0 let bytes = UnsafePointer<UInt8>(self.inputData!.bytes) let totalBytes = CFIndex(self.inputData!.length) var parsedBytes = CFIndex(0) let entity = UnsafeMutablePointer<Unmanaged<CFDictionary>?>.alloc(1) resources = [ResourceItem]() repeat { parsedBytes = CFFTPCreateParsedResourceListing(nil, bytes.advancedBy(offset), totalBytes - offset, entity) if parsedBytes > 0 { if let fptResource = entity.memory?.takeUnretainedValue() { resources!.append(self.mapFTPResources(fptResource as [NSObject : AnyObject])) } offset += parsedBytes } } while (parsedBytes > 0) entity.destroy() return (true, nil) } private func mapFTPResources(ftpResources: [NSObject : AnyObject]) -> ResourceItem { let item = ResourceItem() if let mode = ftpResources[kCFFTPResourceMode as String] as? Int32 { item.mode = mode } if let name = ftpResources[kCFFTPResourceName as String] as? String { // CFFTPCreateParsedResourceListing assumes that teh names are in MacRoman. // To fix it we create data from string and read it with correct encoding. // https://devforums.apple.com/message/155626#155626 if configuration.encoding == NSMacOSRomanStringEncoding { item.name = name } else if let nameData = name.dataUsingEncoding(NSMacOSRomanStringEncoding) { if let encodedName = NSString(data: nameData, encoding: self.configuration.encoding) { item.name = encodedName as String } } item.path = self.path!.stringByAppendingString(item.name) } if let owner = ftpResources[kCFFTPResourceOwner as String] as? String { item.owner = owner } if let group = ftpResources[kCFFTPResourceGroup as String] as? String { item.group = group } if let link = ftpResources[kCFFTPResourceLink as String] as? String { item.link = link } if let size = ftpResources[kCFFTPResourceSize as String] as? Int { item.size = size } if let type = ftpResources[kCFFTPResourceType as String] as? Int { if let resourceType = _resourceTypeMap[type] { item.type = resourceType } } if let date = ftpResources[kCFFTPResourceModDate as String] as? NSDate { item.date = date } return item } override func streamEventHasBytes(aStream: NSStream) -> (Bool, NSError?) { if let inputStream = aStream as? NSInputStream { let buffer = UnsafeMutablePointer<UInt8>.alloc(1024) let result = inputStream.read(buffer, maxLength: 1024) if result > 0 { if self.inputData == nil { self.inputData = NSMutableData(bytes: buffer, length: result) } else { self.inputData!.appendBytes(buffer, length: result) } } buffer.destroy() } return (true, nil) } }
bsd-2-clause
e2437e977f50670e582ed0d814ff7ed8
37.086331
118
0.602002
4.448739
false
false
false
false
kickstarter/ios-oss
Library/OptimizelyClientType.swift
1
5328
import Foundation import KsApi import Prelude public protocol OptimizelyClientType: AnyObject { func activate(experimentKey: String, userId: String, attributes: [String: Any?]?) throws -> String func getVariationKey(experimentKey: String, userId: String, attributes: [String: Any?]?) throws -> String func allExperiments() -> [String] func isFeatureEnabled(featureKey: String, userId: String, attributes: [String: Any?]?) -> Bool func track(eventKey: String, userId: String, attributes: [String: Any?]?, eventTags: [String: Any]?) throws } extension OptimizelyClientType { public func variant( for experiment: OptimizelyExperiment.Key, userAttributes: [String: Any]? = optimizelyUserAttributes() ) -> OptimizelyExperiment.Variant { let variationString: String? let userId = deviceIdentifier(uuid: UUID()) let isAdmin = AppEnvironment.current.currentUser?.isAdmin ?? false if isAdmin { variationString = try? self.getVariationKey( experimentKey: experiment.rawValue, userId: userId, attributes: userAttributes ) } else { variationString = try? self.activate( experimentKey: experiment.rawValue, userId: userId, attributes: userAttributes ) } guard let variation = variationString, let variant = OptimizelyExperiment.Variant(rawValue: variation) else { return .control } return variant } /* Calls `getVariation` on the Optimizely SDK for the given experiment, using the default attributes and deviceId Does *not* record an Optimizely impression. If you wish to record an experiment impression, use `variant(for experiment)`, which calls `activate` on the Optimizely SDK */ public func getVariation(for experimentKey: String) -> OptimizelyExperiment.Variant { let userId = deviceIdentifier(uuid: UUID()) let attributes = optimizelyUserAttributes() let variationString = try? self.getVariationKey( experimentKey: experimentKey, userId: userId, attributes: attributes ) guard let variation = variationString, let variant = OptimizelyExperiment.Variant(rawValue: variation) else { return .control } return variant } /* Returns all experiments the app knows about */ public func allExperiments() -> [String] { return OptimizelyExperiment.Key.allCases.map { $0.rawValue } } /* Returns all features the app knows about */ public func allFeatures() -> [OptimizelyFeature] { return OptimizelyFeature.allCases } public func isFeatureEnabled(featureKey: String) -> Bool { return self.isFeatureEnabled( featureKey: featureKey, userId: deviceIdentifier(uuid: UUID()), attributes: optimizelyUserAttributes() ) } public func track(eventName: String) { let userAttributes = optimizelyUserAttributes() let userId = deviceIdentifier(uuid: UUID()) try? self.track( eventKey: eventName, userId: userId, attributes: userAttributes, eventTags: nil ) } } // MARK: - Tracking Properties public func optimizelyProperties(environment: Environment? = AppEnvironment.current) -> [String: Any]? { guard let env = environment else { return nil } let environmentType = env.environmentType var sdkKey: String switch environmentType { case .production: sdkKey = Secrets.OptimizelySDKKey.production case .staging: sdkKey = Secrets.OptimizelySDKKey.staging case .development, .local, .custom: sdkKey = Secrets.OptimizelySDKKey.development } return [ "optimizely_api_key": sdkKey, "optimizely_environment": environmentType.description ] } public func optimizelyUserAttributes( with project: Project? = nil, refTag: RefTag? = nil ) -> [String: Any] { let user = AppEnvironment.current.currentUser let user_country = user?.location?.country let properties: [String: Any?] = [ "user_distinct_id": debugDeviceIdentifier(), "user_backed_projects_count": user?.stats.backedProjectsCount, "user_launched_projects_count": user?.stats.createdProjectsCount, "user_country": (user_country ?? AppEnvironment.current.config?.countryCode)?.lowercased(), "user_facebook_account": user?.facebookConnected, "user_display_language": AppEnvironment.current.language.rawValue, "session_os_version": AppEnvironment.current.device.systemVersion, "session_user_is_logged_in": user != nil, "session_app_release_version": AppEnvironment.current.mainBundle.shortVersionString, "session_apple_pay_device": AppEnvironment.current.applePayCapabilities.applePayDevice(), "session_device_type": AppEnvironment.current.device.deviceType ] return properties.compact() .withAllValuesFrom(sessionRefTagProperties(with: project, refTag: refTag)) } private func sessionRefTagProperties(with project: Project?, refTag: RefTag?) -> [String: Any] { return ([ "session_referrer_credit": project.flatMap(cookieRefTagFor(project:)).coalesceWith(refTag)?.stringTag, "session_ref_tag": refTag?.stringTag ] as [String: Any?]).compact() } private func debugDeviceIdentifier() -> String? { guard AppEnvironment.current.environmentType != .production, AppEnvironment.current.mainBundle.isRelease == false else { return nil } return deviceIdentifier(uuid: UUID()) }
apache-2.0
081fbd6d90db678138ef788818259855
31.687117
109
0.719595
4.484848
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/LoadingBarButtonItemViewModel.swift
1
1947
import Foundation import ReactiveSwift public protocol LoadingBarButtonItemViewModelOutputs { var activityIndicatorIsLoading: Signal<Bool, Never> { get } var titleButtonIsEnabled: Signal<Bool, Never> { get } var titleButtonIsHidden: Signal<Bool, Never> { get } var titleButtonText: Signal<String, Never> { get } } public protocol LoadingBarButtonItemViewModelInputs { func setIsEnabled(isEnabled: Bool) func setTitle(title: String) func setAnimating(isAnimating: Bool) } public protocol LoadingBarButtonItemViewModelType { var inputs: LoadingBarButtonItemViewModelInputs { get } var outputs: LoadingBarButtonItemViewModelOutputs { get } } public final class LoadingBarButtonItemViewModel: LoadingBarButtonItemViewModelType, LoadingBarButtonItemViewModelInputs, LoadingBarButtonItemViewModelOutputs { public init() { self.activityIndicatorIsLoading = self.isAnimatingProperty.signal self.titleButtonIsEnabled = self.isEnabledProperty.signal self.titleButtonIsHidden = self.isAnimatingProperty.signal self.titleButtonText = self.titleProperty.signal.skipNil() } private var isEnabledProperty = MutableProperty(false) public func setIsEnabled(isEnabled: Bool) { self.isEnabledProperty.value = isEnabled } private var titleProperty = MutableProperty<String?>(nil) public func setTitle(title: String) { self.titleProperty.value = title } private var isAnimatingProperty = MutableProperty(false) public func setAnimating(isAnimating: Bool) { self.isAnimatingProperty.value = isAnimating } public let activityIndicatorIsLoading: Signal<Bool, Never> public let titleButtonIsEnabled: Signal<Bool, Never> public let titleButtonIsHidden: Signal<Bool, Never> public let titleButtonText: Signal<String, Never> public var inputs: LoadingBarButtonItemViewModelInputs { return self } public var outputs: LoadingBarButtonItemViewModelOutputs { return self } }
apache-2.0
7fb6eb88af3caac1dd8bba1201558a19
32.568966
84
0.791474
4.992308
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/binary-tree-maximum-path-sum.swift
2
1223
/** * https://leetcode.com/problems/binary-tree-maximum-path-sum/ * * */ // Date: Wed Apr 29 10:02:51 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { /// - Complexity: /// - Time: O(n), n is the number of nodes in the tree. func maxPathSum(_ root: TreeNode?) -> Int { var result = Int.min self.pathSum(root, &result) return result } fileprivate func pathSum(_ root: TreeNode?, _ result: inout Int) -> Int { guard let root = root else { return 0 } let left = max(0, pathSum(root.left, &result)) let right = max(0, pathSum(root.right, &result)) result = max(result, root.val + left + right) return root.val + max(left, right) } }
mit
c7df20e1079852d10a42cd9950f5d711
29.575
85
0.555192
3.406685
false
false
false
false
rundfunk47/Juice
Example/Juice.playground/Contents.swift
1
4592
import Juice // To make a model Decodable and Encodable: struct Car: Juice.Decodable, Juice.Encodable { let model: String let color: String init(fromJson json: JSONDictionary) throws { model = try json.decode("model") color = try json.decode("color") } func encode() throws -> JSONDictionary { var dictionary = JSONDictionary() try dictionary.encode(["model"], value: model) try dictionary.encode(["color"], value: color) return dictionary } } struct Person: Juice.Decodable, Juice.Encodable { let title: String let firstName: String let lastName: String let age: Int let car: Car? let children: [String] init(fromJson json: JSONDictionary) throws { title = try json.decode(["name", "title"]) firstName = try json.decode(["name", "fullName", "firstName"]) lastName = try json.decode(["name", "fullName", "lastName"]) age = try json.decode("age") car = try json.decode("car") children = try json.decode("children") } func encode() throws -> JSONDictionary { var dictionary = JSONDictionary() try dictionary.encode(["name", "title"], value: title) try dictionary.encode(["name", "fullName", "firstName"], value: firstName) try dictionary.encode(["name", "fullName", "lastName"], value: lastName) try dictionary.encode(["age"], value: age) try dictionary.encode(["car"], value: car) try dictionary.encode(["children"], value: children) return dictionary } } let string = "{\"age\": 29, \"children\": [], \"name\": {\"title\": \"Mr.\", \"fullName\": {\"firstName\": \"John\", \"lastName\": \"Doe\"}}}" // Create a model from a string: let person = try! Person(fromJson: toStrictlyTypedJSON(toLooselyTypedJSON(string)) as! JSONDictionary) try! person.encode().jsonString // A Decodable and Encodable enum with raw value: enum PhoneNumberType: String, Juice.Decodable, Juice.Encodable { case home case office case mobile } // A decodable enum without raw value: enum Distance: Juice.Decodable { case reallyClose case close case far init(fromJson json: Double) throws { switch json { case _ where json < 2: self = .reallyClose case _ where json < 6: self = .close default: self = .far } } } struct BadURLError : Error, CustomNSError { /// The user-info dictionary. public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: localizedDescription] } /// The error code within the given domain. public var errorCode: Int { return 1 } /// The domain of the error. public static var errorDomain = "BadURLErrorDomain" var attemptedUrl: String var localizedDescription: String { return "Not a valid URL: \"" + attemptedUrl + "\"" } } // Possible to decode any type by using transforms: struct TransformHomePage: Juice.Decodable { let title: String let url: URL init(fromJson json: JSONDictionary) throws { title = try json.decode("title") url = try json.decode("url", transform: { (input: String) -> URL in if let url = URL(string: input) { return url } else { throw BadURLError(attemptedUrl: input) } }) } } // Or by using protocol extensions: extension URL: Juice.Decodable { public init(fromJson json: String) throws { if let url = URL(string: json) { self = url } else { throw BadURLError(attemptedUrl: json) } } } // On classes you can't directly modify: extension NSURL: Juice.FactoryDecodable { public static func create<T>(fromJson json: String) throws -> T { if let url = NSURL(string: json) { return url as! T } else { throw BadURLError(attemptedUrl: json) } } } struct ProtocolHomePage: Juice.Decodable { let title: String let url: URL init(fromJson json: JSONDictionary) throws { title = try json.decode("title") url = try json.decode("url") } } // Error catching: do { let dict = JSONDictionary(["title": "Apple", "url": "ht tps://apple.com"]) try ProtocolHomePage(fromJson: dict) } catch { // Error at key path ["url"]: Failure when attempting to decode type URL: Not a valid URL: "ht tps://apple.com" print(error.localizedDescription) }
mit
6835e2348c0268243d8d9efae54882c8
28.063291
142
0.606054
4.332075
false
false
false
false
mibaldi/IOS_MIMO_APP
iosAPP/shopping/ShoopingListViewController.swift
1
6643
// // ShoopingListViewController.swift // iosAPP // // Created by mikel balduciel diaz on 31/1/16. // Copyright ยฉ 2016 mikel balduciel diaz. All rights reserved. // import UIKit class ShoopingListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ @IBOutlet weak var table: UITableView! @IBOutlet weak var titleLabel: UILabel! var ingredients = [Ingredient]() var sections = [[Ingredient]]() override func viewDidLoad() { super.viewDidLoad() setText() self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "shoppingCell") } func setText(){ titleLabel.text = NSLocalizedString("TITULOLISTACOMPRA",comment:"Lista de la Compra") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) sections.removeAll() do{ ingredients = try IngredientDataHelper.findIngredientsInCart()! var ingredients2 = try IngredientDataHelper.findIngredientsNotInStorageCart()! ingredients.sortInPlace({ $0.name < $1.name }) ingredients2.sortInPlace({ $0.name < $1.name }) sections.append(ingredients) sections.append(ingredients2) table.reloadData() }catch _{ print("Error al recibir los ingredientes") } } @IBAction func actionButton(sender: AnyObject) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if appDelegate.isConected { let instance = self.storyboard!.instantiateViewControllerWithIdentifier("categoryShopping") as? CategoriesViewController self.navigationController?.pushViewController(instance!, animated: true) }else{ self.view.makeToast(NSLocalizedString("SINCONEXION",comment:"No tienes conexiรณn"), duration: 2, position: .Top) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.table.dequeueReusableCellWithIdentifier("shoppingCell")! let section = sections[indexPath.section] cell.addBorderBottom(size: 0.5, color: UIColor(red: 78, green: 159, blue: 255, alpha: 0)) cell.backgroundColor = UIColor.whiteColor() cell.textLabel!.text = section[indexPath.row].name return cell } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return indexPath.section == 0 ? true : false } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1{ let ingredient = sections[1][indexPath.row] do{ try Ingredient.updateIngredientCart(ingredient) sections[indexPath.section].removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Top) sections[0].append(ingredient) sections[0].sortInPlace({ $0.name < $1.name }) let index = sections[0].indexOf(ingredient) tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index!, inSection: 0)], withRowAnimation: .Automatic) }catch _{ print("Error al insertar ingrediente en storage") } } } func deleteIngredientStore(ingredient: Ingredient){ do{ try Ingredient.deleteIngredientCart(ingredient) }catch _{ print("Error al eliminar del cart") } } func buyIngredientStore(ingredient: Ingredient){ do{ try Ingredient.deleteIngredientCart(ingredient) try Ingredient.updateIngredientStorage(ingredient) view.makeToast(NSLocalizedString("COMPRAREALIZADA",comment:"Compra Realizada"), duration: 2.0, position: .Center) }catch _{ print("Error al comprar del cart") } } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.addBorderBottom(size: 1, color: UIColor.blackColor()) header.textLabel?.textAlignment = .Center } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {} func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let buyAction = UITableViewRowAction(style: .Normal, title: NSLocalizedString("COMPRAR",comment:"Comprar")) { action, index in var section = self.sections[indexPath.section] let ingredient = section[indexPath.row] self.sections[indexPath.section].removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Top) self.buyIngredientStore(ingredient) } buyAction.backgroundColor = UIColor.blueColor() let deleteAction = UITableViewRowAction(style: .Normal, title: NSLocalizedString("BORRAR",comment:"Borrar")) { action, index in var section = self.sections[indexPath.section] let ingredient = section[indexPath.row] self.sections[indexPath.section].removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Top) self.deleteIngredientStore(ingredient) self.sections[1].append(ingredient) self.sections[1].sortInPlace({ $0.name < $1.name }) let index = self.sections[1].indexOf(ingredient) tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index!, inSection: 1)], withRowAnimation: .Automatic) } deleteAction.backgroundColor = UIColor.redColor() return [buyAction,deleteAction] } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0{ return NSLocalizedString("COMPRA",comment:"Compra") }else{ return NSLocalizedString("HISTORICO",comment:"Histรณrico") } } }
apache-2.0
339124b4b492fb59d8a2e5a062cb1f2c
41.564103
149
0.650904
5.18345
false
false
false
false
tarunon/AutoSnapping
AutoSnapping/UITableView+autoSnapping.swift
1
1148
// // UITableView+autoSnapping.swift // AutoSnapping // // Created by Nobuo Saito on 2015/08/20. // Copyright ยฉ 2015 tarunon. All rights reserved. // import Foundation private let roundingHeight: CGFloat = 160.0 public extension UITableView { func autoSnapping(velocity velocity: CGPoint, targetOffset: UnsafeMutablePointer<CGPoint>) { if CGPointEqualToPoint(velocity, CGPointZero) || targetOffset.memory.y >= self.contentSize.height - self.frame.size.height - self.contentInset.top - self.contentInset.bottom { return } guard let indexPath = self.indexPathForRowAtPoint(targetOffset.memory) else { return } var offset = targetOffset.memory let cellRect = self.rectForRowAtIndexPath(indexPath) let targetOffsetYDif = offset.y - cellRect.minY if targetOffsetYDif < roundingHeight { offset.y = cellRect.minY - self.contentInset.top } else if targetOffsetYDif > cellRect.height - roundingHeight { offset.y = cellRect.maxY - self.contentInset.top } targetOffset.memory = offset } }
mit
1c4ac47d8f691842ea6bcd39e74581c9
33.757576
183
0.671316
4.533597
false
false
false
false
iwheelbuy/VK
VK/Object/VK+Object+ResolvedScreenName.swift
1
1806
import Foundation public extension Object { /// ะžะฑัŠะตะบั‚ ะพั‚ะฒะตั‡ะฐัŽั‰ะธะน ะบะพั€ะพั‚ะบะพะผัƒ ะธะผะตะฝะธ screen_name public struct ResolvedScreenName: Decodable { /// ะขะธะฟ ะพะฑัŠะตะบั‚ะฐ public enum Typะต: Decodable { /// ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ case user /// ะกะพะพะฑั‰ะตัั‚ะฒะพ case group /// ะŸั€ะธะปะพะถะตะฝะธะต case application /// ะะตะธะทะฒะตัั‚ะฝะพะต ะทะฝะฐั‡ะตะฝะธะต case unexpected(String) init(rawValue: String) { switch rawValue { case "user": self = .user case "group": self = .group case "application": self = .application default: self = .unexpected(rawValue) } } public var rawValue: String { switch self { case .user: return "user" case .group: return "group" case .application: return "application" case .unexpected(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: String = try container.decode() self = Object.ResolvedScreenName.Typะต(rawValue: rawValue) } } /// ะ˜ะดะตะฝั‚ะธั„ะธะบะฐั‚ะพั€ ะพะฑัŠะตะบั‚ะฐ public let object_id: Int /// ะขะธะฟ ะพะฑัŠะตะบั‚ะฐ public let type: Object.ResolvedScreenName.Typะต } }
mit
08752444f2d79fb78dc0afdc044254f2
30.148148
73
0.453627
5.551155
false
false
false
false
J-Mendes/Weather
Weather/Weather/Core Layer/Network/NetworkConstants.swift
1
806
// // NetworkConstants.swift // Weather // // Created by Jorge Mendes on 04/07/17. // Copyright ยฉ 2017 Jorge Mendes. All rights reserved. // import Foundation class NetworkConstants { static let baseUrl: String = "https://query.yahooapis.com/v1/public/yql" struct Url { static let weatherForecast: String = "\(NetworkConstants.baseUrl)?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%@\")%@&format=json&env=store://datatables.org/alltableswithkeys" static let weatherUnitsModifier: String = " and u='c'" static let place: String = "\(NetworkConstants.baseUrl)?q=select admin1.content, admin2.content, country.code from geo.places where text=\"(%f,%f)\" limit 1&diagnostics=false&format=json" } }
gpl-3.0
63d5e264af9f6af61197555db39ccc46
35.590909
233
0.688199
3.692661
false
false
false
false
ijovi23/JvPunchIO
JvPunchIO-Recorder/Pods/FileKit/Sources/DataFile.swift
2
3517
// // DataFile.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2016 Nikolai Vazquez // // 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 /// A representation of a filesystem data file. /// /// The data type is Data. open class DataFile: File<Data> { /// Reads the file and returns its data. /// - Parameter options: A mask that specifies write options /// described in `Data.ReadingOptions`. /// /// - Throws: `FileKitError.ReadFromFileFail` /// - Returns: The data read from file. public func read(_ options: Data.ReadingOptions) throws -> Data { return try Data.read(from: path, options: options) } /// Writes data to the file. /// /// - Parameter data: The data to be written to the file. /// - Parameter options: A mask that specifies write options /// described in `Data.WritingOptions`. /// /// - Throws: `FileKitError.WriteToFileFail` /// public func write(_ data: Data, options: Data.WritingOptions) throws { try data.write(to: self.path, options: options) } } /// A representation of a filesystem data file, /// with options to read or write. /// /// The data type is Data. open class DataFileWithOptions: DataFile { open var readingOptions: Data.ReadingOptions = [] open var writingOptions: Data.WritingOptions? = nil /// Initializes a file from a path with options. /// /// - Parameter path: The path to be created a text file from. /// - Parameter readingOptions: The options to be used to read file. /// - Parameter writingOptions: The options to be used to write file. /// If nil take into account `useAuxiliaryFile` public init(path: Path, readingOptions: Data.ReadingOptions = [], writingOptions: Data.WritingOptions? = nil) { self.readingOptions = readingOptions self.writingOptions = writingOptions super.init(path: path) } open override func read() throws -> Data { return try read(readingOptions) } open override func write(_ data: Data, atomically useAuxiliaryFile: Bool) throws { // If no option take into account useAuxiliaryFile let options: Data.WritingOptions = (writingOptions == nil) ? (useAuxiliaryFile ? Data.WritingOptions.atomic : []) : writingOptions! try self.write(data, options: options) } }
mit
ac533c098c4f5294df13fc0cf028c875
37.228261
115
0.673301
4.474555
false
false
false
false
skyfe79/RxPlayground
RxToDoList-MVVM/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift
24
4021
// // RxTableViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/15/15. // Copyright ยฉ 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif let tableViewDataSourceNotSet = TableViewDataSourceNotSet() class TableViewDataSourceNotSet : NSObject , UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { rxAbstractMethodWithMessage(dataSourceNotSet) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { rxAbstractMethodWithMessage(dataSourceNotSet) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { rxAbstractMethodWithMessage(dataSourceNotSet) } } /** For more information take a look at `DelegateProxyType`. */ public class RxTableViewDataSourceProxy : DelegateProxy , UITableViewDataSource , DelegateProxyType { /** Typed parent object. */ public weak private(set) var tableView: UITableView? private weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet /** Initializes `RxTableViewDelegateProxy` - parameter parentObject: Parent object for delegate proxy. */ public required init(parentObject: AnyObject) { self.tableView = (parentObject as! UITableView) super.init(parentObject: parentObject) } // MARK: delegate /** Required delegate method implementation. */ public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSectionsInTableView?(tableView) ?? 1 } /** Required delegate method implementation. */ public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section) } /** Required delegate method implementation. */ public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAtIndexPath: indexPath) } // MARK: proxy /** For more information take a look at `DelegateProxyType`. */ public override class func createProxyForObject(object: AnyObject) -> AnyObject { let tableView = (object as! UITableView) return castOrFatalError(tableView.rx_createDataSourceProxy()) } /** For more information take a look at `DelegateProxyType`. */ public override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> { return _pointer(&dataSourceAssociatedTag) } /** For more information take a look at `DelegateProxyType`. */ public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UITableView = castOrFatalError(object) collectionView.dataSource = castOptionalOrFatalError(delegate) } /** For more information take a look at `DelegateProxyType`. */ public class func currentDelegateFor(object: AnyObject) -> AnyObject? { let collectionView: UITableView = castOrFatalError(object) return collectionView.dataSource } /** For more information take a look at `DelegateProxyType`. */ public override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UITableViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? tableViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
mit
eea4d8369628d282eceddcee57f23e69
30.653543
127
0.717662
5.929204
false
false
false
false
mluedke2/jsonjam
Example/Tests/Tests.swift
2
8645
import UIKit import XCTest import JSONJam import JSONJam_Example class Tests: XCTestCase { override func setUp() { super.setUp() } func testSerializeAndDeserialize() { var randomProduct = self.createRandomProduct() var serializedProduct = randomProduct.parameterize() XCTAssertNotNil(serializedProduct, "serialized product can't be nil") var rebuiltProduct: Product? rebuiltProduct <-- (serializedProduct as AnyObject?) XCTAssertNotNil(rebuiltProduct, "rebuilt product can't be nil") if let rebuiltProduct = rebuiltProduct { XCTAssertNotNil(rebuiltProduct.productDescription, "product description can't be nil") if let productDescription = randomProduct.productDescription, rebuiltProductDescription = rebuiltProduct.productDescription { XCTAssertEqual(productDescription, rebuiltProductDescription, "product description must match") } XCTAssertNotNil(rebuiltProduct.tags, "tags can't be nil") if let tags = randomProduct.tags, rebuiltTags = rebuiltProduct.tags { XCTAssertEqual(tags, rebuiltTags, "tags must match") } XCTAssertNotNil(rebuiltProduct.price, "price can't be nil") if let price = randomProduct.price, rebuildPrice = rebuiltProduct.price { XCTAssertEqual(price, rebuildPrice, "price must match") } XCTAssertNotNil(rebuiltProduct.creationDate, "creationDate can't be nil") if let creationDate = randomProduct.creationDate, rebuiltCreationDate = rebuiltProduct.creationDate { XCTAssertEqualWithAccuracy(creationDate.timeIntervalSinceReferenceDate, rebuiltCreationDate.timeIntervalSinceReferenceDate, 1, "creationDate must match") } XCTAssertNotNil(rebuiltProduct.creationDate, "creationDate can't be nil") if let transactionDates = randomProduct.transactionDates, rebuiltTransactionDates = rebuiltProduct.transactionDates { for i in 0..<transactionDates.count { XCTAssertEqualWithAccuracy(transactionDates[i].timeIntervalSinceReferenceDate, rebuiltTransactionDates[i].timeIntervalSinceReferenceDate, 1, "transactionDates must match") } } XCTAssertNotNil(rebuiltProduct.detailURL, "detailURL can't be nil") if let detailURL = randomProduct.detailURL, rebuildDetailURL = rebuiltProduct.detailURL { XCTAssertEqual(detailURL, rebuildDetailURL, "detailURL must match") } XCTAssertNotNil(rebuiltProduct.photoURLs, "photoURLs can't be nil") if let photoURLs = randomProduct.photoURLs, rebuildPhotoURLs = rebuiltProduct.photoURLs { XCTAssertEqual(photoURLs, rebuildPhotoURLs, "photoURLs must match") } XCTAssertNotNil(rebuiltProduct.owner, "owner can't be nil") if let owner = randomProduct.owner, rebuiltOwner = rebuiltProduct.owner { XCTAssertNotNil(rebuiltOwner.name, "owner name can't be nil") if let name = owner.name, rebuiltName = rebuiltOwner.name { XCTAssertEqual(name, rebuiltName, "owner name must match") } XCTAssertNotNil(rebuiltOwner.shoeSize, "owner shoeSize can't be nil") if let shoeSize = owner.shoeSize, rebuiltShoeSize = rebuiltOwner.shoeSize { XCTAssertNotNil(rebuiltShoeSize.size, "shoeSize size can't be nil") if let size = shoeSize.size, rebuiltSize = rebuiltShoeSize.size { XCTAssertEqual(size, rebuiltSize, "shoeSize size must match") } XCTAssertNotNil(rebuiltShoeSize.sizeSystem?.rawValue, "shoeSize sizeSystem can't be nil") if let sizeSystem = shoeSize.sizeSystem, rebuiltSizeSystem = rebuiltShoeSize.sizeSystem { XCTAssertEqual(sizeSystem, rebuiltSizeSystem, "shoeSize sizeSystem must match") } } } XCTAssertEqual(randomProduct.buyers![0].shoeSize!.size!, rebuiltProduct.buyers![0].shoeSize!.size!, "first buyer's shoe size must match") } } func testDeserializeAndSerialize() { var jsonObject: JSONDictionary = ["product_description": "This is a wonderful thing.", "tags": ["imaginary", "terrific"], "price": 35.50, "creation_date": "1985-11-05 04:30:15", "transaction_dates": ["1987-05-03 04:15:30", "2005-09-20 08:45:52"], "owner": ["name": "Coleman Francis", "shoe_size": ["size": 9, "system": "AUS"]], "buyers": [["name": "Coleman Francis", "shoe_size": ["size": 9, "system": "AUS"]], ["name": "Mateo Mateo", "shoe_size": ["size": 8, "system": "UK"]]], "url": "http://www.mattluedke.com", "photos": ["http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_2495.jpg", "http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_24971.jpg"]] var deserializedProduct: Product? deserializedProduct <-- (jsonObject as AnyObject?) XCTAssertNotNil(deserializedProduct, "deserialized product can't be nil") var reserializedProduct = deserializedProduct?.parameterize() XCTAssertNotNil(reserializedProduct, "reserialized product can't be nil") XCTAssertEqual(reserializedProduct!["product_description"] as! String, jsonObject["product_description"] as! String, "product description must match") XCTAssertEqual((reserializedProduct!["owner"] as! JSONDictionary)["name"] as! String, (jsonObject["owner"] as! JSONDictionary)["name"] as! String, "owner name must match") XCTAssertEqual(((reserializedProduct!["buyers"] as! [JSONDictionary])[0]["shoe_size"] as! JSONDictionary)["size"] as! Int, ((jsonObject["buyers"] as! [JSONDictionary])[0]["shoe_size"] as! JSONDictionary)["size"] as! Int, "first buyer's shoe size must match") } func createRandomShoeSize() -> ShoeSize { var shoeSize = ShoeSize() shoeSize.size = Int(arc4random_uniform(15)) var randomNumber = Int(arc4random_uniform(4)) switch randomNumber { case 0: shoeSize.sizeSystem = .UnitedStates case 1: shoeSize.sizeSystem = .Europe case 2: shoeSize.sizeSystem = .UnitedKingdom default: shoeSize.sizeSystem = .Australia } return shoeSize } func createRandomUser() -> User { var user = User() var randomNumber = Int(arc4random_uniform(2)) switch randomNumber { case 0: user.name = "Mateo" default: user.name = "Matthias" } user.shoeSize = self.createRandomShoeSize() return user } func createRandomProduct() -> Product { var product = Product() var randomDescNumber = Int(arc4random_uniform(2)) switch randomDescNumber { case 0: product.productDescription = "This item will change your life." default: product.productDescription = "This item is best enjoyed with green tea." } var randomTagNumber = Int(arc4random_uniform(2)) switch randomTagNumber { case 0: product.tags = ["timid", "interstellar", "quiet"] default: product.tags = ["tempestuous", "populist"] } product.price = Double(arc4random_uniform(200)) product.creationDate = NSDate() product.transactionDates = [NSDate(), NSDate()] product.owner = createRandomUser() product.buyers = [createRandomUser(), createRandomUser(), createRandomUser()] product.detailURL = NSURL(string: "http://mattluedke.com/") product.photoURLs = [NSURL(string: "http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_2495.jpg")!, NSURL(string: "http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_24971.jpg")!] return product } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } }
mit
b95dc9d6d2e506a94a1848df70d32bfd
47.027778
689
0.617698
4.835011
false
false
false
false
Driftt/drift-sdk-ios
Drift/Models/AppointmentInformation.swift
2
1500
// // AppointmentInformation.swift // Drift-SDK // // Created by Eoin O'Connell on 07/02/2018. // Copyright ยฉ 2018 Drift. All rights reserved. // struct AppointmentInformation{ let availabilitySlot: Date let slotDuration: Int let agentId: Int64 let conversationId: Int64 let endUserTimeZone: String? let agentTimeZone: String? } class AppointmentInformationDTO: Codable, DTO { typealias DataObject = AppointmentInformation var availabilitySlot: Date? var slotDuration: Int? var agentId: Int64? var conversationId: Int64? var endUserTimeZone: String? var agentTimeZone: String? enum CodingKeys: String, CodingKey { case availabilitySlot = "availabilitySlot" case slotDuration = "slotDuration" case agentId = "agentId" case conversationId = "conversationId" case endUserTimeZone = "endUserTimeZone" case agentTimeZone = "agentTimeZone" } func mapToObject() -> AppointmentInformation? { return AppointmentInformation(availabilitySlot: availabilitySlot ?? Date(), slotDuration: slotDuration ?? -1, agentId: agentId ?? -1, conversationId: conversationId ?? -1, endUserTimeZone: endUserTimeZone, agentTimeZone: agentTimeZone) } }
mit
c948952506dccc38b5ac88bcc8d0baac
31.586957
83
0.594396
5.013378
false
false
false
false
himadrisj/SiriPay
Client/SiriPay/ezPay-SiriIntent/IntentHandler.swift
1
7475
// // IntentHandler.swift // ezPay-SiriIntent // // Created by Himadri Sekhar Jyoti on 11/09/16. // Copyright // import Intents // As an example, this class is set up to handle Message intents. // You will want to replace this or add other intents as appropriate. // The intents you wish to handle must be declared in the extension's Info.plist. // You can test your example integration by saying things to Siri like: // "Send a message using <myApp>" // "<myApp> John saying hello" // "Search for messages in <myApp>" class IntentHandler: INExtension, INSendPaymentIntentHandling { override func handler(for intent: INIntent) -> Any { // This is the default implementation. If you want different objects to handle different intents, // you can override this and return the handler you want for that particular intent. return self } /*! @brief handling method @abstract Execute the task represented by the INSendPaymentIntent that's passed in @discussion This method is called to actually execute the intent. The app must return a response for this intent. @param sendPaymentIntent The input intent @param completion The response handling block takes a INSendPaymentIntentResponse containing the details of the result of having executed the intent @see INSendPaymentIntentResponse */ public func handle(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Swift.Void) { // Implement your application logic for payment here. var thePhoneNO = "9886957281" //"9711165687" //"9742048795" let defaults = UserDefaults(suiteName: "group.com.example.ezpay") if let contactDict = defaults?.object(forKey: contactsSharedKey) as? [String: String] { if let lowerCaseName = intent.payee?.displayName.lowercased() { if let phNo = contactDict[lowerCaseName] { thePhoneNO = phNo } } } // if(intent.payee?.displayName.caseInsensitiveCompare("Jatin") == .orderedSame) { // phoneNo = "9711165687" // } let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendPaymentIntent.self)) var response = INSendPaymentIntentResponse(code: .failure, userActivity: userActivity) if let intAmount = intent.currencyAmount?.amount?.intValue { var payInfo = [String:String]() payInfo["phone"] = thePhoneNO payInfo["amount"] = String(intAmount) let defaults = UserDefaults(suiteName: "group.com.example.ezpay") defaults?.set(payInfo, forKey: payInfoUserDefaultsKey) defaults?.synchronize() response = INSendPaymentIntentResponse(code: .success, userActivity: userActivity) response.paymentRecord = self.makePaymentRecord(for: intent) } completion(response) } /*! @brief Confirmation method @abstract Validate that this intent is ready for the next step (i.e. handling) @discussion These methods are called prior to asking the app to handle the intent. The app should return a response object that contains additional information about the intent, which may be relevant for the system to show the user prior to handling. If unimplemented, the system will assume the intent is valid following resolution, and will assume there is no additional information relevant to this intent. @param sendPaymentIntent The input intent @param completion The response block contains an INSendPaymentIntentResponse containing additional details about the intent that may be relevant for the system to show the user prior to handling. @see INSendPaymentIntentResponse */ public func confirm(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Swift.Void) { let response = INSendPaymentIntentResponse(code: .success, userActivity: nil) response.paymentRecord = self.makePaymentRecord(for: intent) completion(response) } func makePaymentRecord(for intent: INSendPaymentIntent, status: INPaymentStatus = .completed) -> INPaymentRecord? { let paymentMethod = INPaymentMethod(type: .unknown, name: "SimplePay", identificationHint: nil, icon: nil) let localCurrencyAmmount = INCurrencyAmount(amount: (intent.currencyAmount?.amount)!, currencyCode: "INR") return INPaymentRecord( payee: intent.payee, payer: nil, currencyAmount: localCurrencyAmmount, paymentMethod: paymentMethod, note: intent.note, status: status ) } /*! @brief Resolution methods @abstract Determine if this intent is ready for the next step (confirmation) @discussion These methods are called to make sure the app extension is capable of handling this intent in its current form. This method is for validating if the intent needs any further fleshing out. @param sendPaymentIntent The input intent @param completion The response block contains an INIntentResolutionResult for the parameter being resolved @see INIntentResolutionResult */ public func resolvePayee(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INPersonResolutionResult) -> Swift.Void) { guard let payee = intent.payee else { completion(INPersonResolutionResult.needsValue()) return } // if let type = payee.personHandle?.type { // if(type == .phoneNumber) { // completion(INPersonResolutionResult.success(with: payee)) // return // } // } let defaults = UserDefaults(suiteName: "group.com.example.ezpay") if let contactDict = defaults?.object(forKey: contactsSharedKey) as? [String: String] { if(contactDict[payee.displayName.lowercased()]?.characters.count == 10) { completion(INPersonResolutionResult.success(with: payee)) return } } // if (payee.displayName.caseInsensitiveCompare("om") == .orderedSame || payee.displayName.caseInsensitiveCompare("jatin") == .orderedSame) { // completion(INPersonResolutionResult.success(with: payee)) // } completion(INPersonResolutionResult.disambiguation(with: [payee])) } public func resolveCurrencyAmount(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INCurrencyAmountResolutionResult) -> Swift.Void) { guard let amount = intent.currencyAmount else { completion(INCurrencyAmountResolutionResult.needsValue()) return } guard amount.amount != nil else { completion(INCurrencyAmountResolutionResult.needsValue()) return } completion(INCurrencyAmountResolutionResult.success(with: amount)) } // public func resolveNote(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INStringResolutionResult) -> Swift.Void) { // // } // }
mit
6a9ddd97d8a2b494afd43551d1e99ab0
40.527778
414
0.660602
4.980013
false
false
false
false
ilhanadiyaman/firefox-ios
StorageTests/TestBrowserDB.swift
2
3762
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCTest import XCGLogger private let log = XCGLogger.defaultInstance() class TestBrowserDB: XCTestCase { let files = MockFiles() private func rm(path: String) { do { try files.remove(path) } catch { } } override func setUp() { super.setUp() rm("foo.db") rm("foo.db-shm") rm("foo.db-wal") rm("foo.db.bak.1") rm("foo.db.bak.1-shm") rm("foo.db.bak.1-wal") } class MockFailingTable: Table { var name: String { return "FAILURE" } var version: Int { return 1 } func exists(db: SQLiteDBConnection) -> Bool { return false } func drop(db: SQLiteDBConnection) -> Bool { return true } func create(db: SQLiteDBConnection) -> Bool { return false } func updateTable(db: SQLiteDBConnection, from: Int) -> Bool { return false } } private class MockListener { var notification: NSNotification? @objc func onDatabaseWasRecreated(notification: NSNotification) { self.notification = notification } } func testMovesDB() { let db = BrowserDB(filename: "foo.db", files: self.files) XCTAssertTrue(db.createOrUpdate(BrowserTable())) db.run("CREATE TABLE foo (bar TEXT)").value // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // Grab a pointer to the -shm so we can compare later. let shmA = try! files.fileWrapper("foo.db-shm") let creationA = shmA.fileAttributes[NSFileCreationDate] as! NSDate let inodeA = (shmA.fileAttributes[NSFileSystemFileNumber] as! NSNumber).unsignedLongValue XCTAssertFalse(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) let center = NSNotificationCenter.defaultCenter() let listener = MockListener() center.addObserver(listener, selector: "onDatabaseWasRecreated:", name: NotificationDatabaseWasRecreated, object: nil) defer { center.removeObserver(listener) } // It'll still fail, but it moved our old DB. // Our current observation is that closing the DB deletes the .shm file and also // checkpoints the WAL. XCTAssertFalse(db.createOrUpdate(MockFailingTable())) db.run("CREATE TABLE foo (bar TEXT)").value // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // But now it's been reopened, it's not the same -shm! let shmB = try! files.fileWrapper("foo.db-shm") let creationB = shmB.fileAttributes[NSFileCreationDate] as! NSDate let inodeB = (shmB.fileAttributes[NSFileSystemFileNumber] as! NSNumber).unsignedLongValue XCTAssertTrue(creationA.compare(creationB) != NSComparisonResult.OrderedDescending) XCTAssertNotEqual(inodeA, inodeB) XCTAssertTrue(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) // The right notification was issued. XCTAssertEqual("foo.db", (listener.notification?.object as? String)) } }
mpl-2.0
d91fd19a7a4c8bee7a49371f79248ad6
34.838095
126
0.632642
4.309278
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Laundry/Model/LaundryRoom.swift
1
4303
// // LaundryHall.swift // Penn Mobile // // Created by Zhilei Zheng on 2017/10/24. // Copyright ยฉ 2017ๅนด Zhilei Zheng. All rights reserved. // import Foundation import SwiftyJSON class LaundryRoom: Codable { static let directory = "laundryHallData-v2.json" enum CodingKeys: String, CodingKey { case id = "hall_id" case name case building = "location" } let id: Int let name: String let building: String var washers = [LaundryMachine]() var dryers = [LaundryMachine]() var usageData: [Double]! = nil init(id: Int, name: String, building: String) { self.id = id self.name = name self.building = building } init(json: JSON) { self.id = json["id"].intValue self.name = json["hall_name"].string ?? "Unknown" self.building = json["location"].string ?? "Unknown" let runningMachines = json["machines"]["details"].arrayValue.map { LaundryMachine(json: $0, roomName: name) } washers = runningMachines.filter { $0.isWasher }.sorted() dryers = runningMachines.filter { !$0.isWasher }.sorted() let usageJSON = json["usage_data"] guard let washerData = usageJSON["washer_data"].dictionary, let dryerData = usageJSON["dryer_data"].dictionary else { return } usageData = [Double](repeating: 0, count: 27) washerData.forEach { (key, val) in usageData[Int(key)!] = val.doubleValue } dryerData.forEach { (key, val) in usageData[Int(key)!] += val.doubleValue } let dataMax = usageData.max()! let dataMin = usageData.min()! if dataMin == dataMax { usageData = Array.init(repeating: 0.01, count: usageData.count) } else { for i in usageData.indices { usageData[i] = ((dataMax - usageData[i]) / (dataMax - dataMin)) } } } static func getLaundryHall(for id: Int) -> LaundryRoom? { return LaundryAPIService.instance.idToRooms?[id] } static func setPreferences(for ids: [Int]) { UserDefaults.standard.setLaundryPreferences(to: ids) } static func setPreferences(for halls: [LaundryRoom]) { let ids = halls.map { $0.id } LaundryRoom.setPreferences(for: ids) } static func getPreferences() -> [LaundryRoom] { if UIApplication.isRunningFastlaneTest { var halls = [LaundryRoom]() for id in [1, 2, 3] { if let hall = getLaundryHall(for: id) { halls.append(hall) } } return halls } else { if let ids = UserDefaults.standard.getLaundryPreferences() { var halls = [LaundryRoom]() for id in ids { if let hall = getLaundryHall(for: id) { halls.append(hall) } } return halls } return [LaundryRoom]() } } func decrementTimeRemaining(by minutes: Int) { washers.decrementTimeRemaining(by: minutes) dryers.decrementTimeRemaining(by: minutes) washers = washers.sorted() dryers = dryers.sorted() } } // MARK: - Equatable extension LaundryRoom: Equatable { static func == (lhs: LaundryRoom, rhs: LaundryRoom) -> Bool { return lhs.id == rhs.id } } // MARK: - Array Extension extension Array where Element == LaundryRoom { func containsRunningMachine() -> Bool { return filter({ (hall) -> Bool in return hall.washers.containsRunningMachine() || hall.dryers.containsRunningMachine() }).count > 0 } } // MARK: - Default Selection extension LaundryRoom { static func getDefaultRooms() -> [LaundryRoom] { var rooms = getPreferences() while rooms.count < 3 { let lastId = rooms.last?.id ?? -1 guard let nextRoom = getLaundryHall(for: lastId + 1) else { continue } rooms.append(nextRoom) } return rooms } } // MARK: - Default Room extension LaundryRoom { static func getDefaultRoom() -> LaundryRoom { return LaundryRoom(id: 0, name: "Bishop White", building: "Quad") } }
mit
20bc8f0515ee445874f3a75ea01edacb
28.655172
134
0.575814
3.96679
false
false
false
false
Jnosh/swift
test/Serialization/search-paths.swift
7
2795
// RUN: rm -rf %t && mkdir -p %t/secret // RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift // RUN: mkdir -p %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/ // RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias // RUN: %target-swift-frontend -emit-module -o %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks -parse-as-library %S/Inputs/has_xref.swift // RUN: %target-swift-frontend %s -typecheck -I %t -verify -show-diagnostics-after-fatal // Try again, treating has_xref as a main file to force serialization to occur. // RUN: %target-swift-frontend -emit-module -o %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks %S/Inputs/has_xref.swift // RUN: %target-swift-frontend %s -typecheck -I %t // RUN: %target-swift-frontend -emit-module -o %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks -parse-as-library %S/Inputs/has_xref.swift -serialize-debugging-options // RUN: %target-swift-frontend %s -typecheck -I %t // RUN: %target-swift-frontend -emit-module -o %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks -parse-as-library %S/Inputs/has_xref.swift -application-extension // RUN: %target-swift-frontend %s -typecheck -I %t // Make sure we don't end up with duplicate search paths. // RUN: %target-swiftc_driver -emit-module -o %t/has_xref.swiftmodule -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks -parse-as-library %S/Inputs/has_xref.swift %S/../Inputs/empty.swift -Xfrontend -serialize-debugging-options // RUN: %target-swift-frontend %s -typecheck -I %t // RUN: llvm-bcanalyzer -dump %t/has_xref.swiftmodule | %FileCheck %s // RUN: %target-swift-frontend %s -emit-module -o %t/main.swiftmodule -I %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks // RUN: llvm-bcanalyzer -dump %t/main.swiftmodule | %FileCheck %s // XFAIL: linux import has_xref // expected-error {{missing required modules: 'has_alias', 'struct_with_operators'}} numeric(42) // expected-error {{use of unresolved identifier 'numeric'}} // CHECK: <INPUT_BLOCK // CHECK-NOT: /secret' // CHECK-NOT: /Frameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=0/> blob data = '{{.+}}/Frameworks' // CHECK-NOT: /secret' // CHECK-NOT: /Frameworks' // CHECK-NOT: /SystemFrameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=1/> blob data = '{{.+}}/SystemFrameworks' // CHECK-NOT: /secret' // CHECK-NOT: /Frameworks' // CHECK-NOT: /SystemFrameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0 op1=0/> blob data = '{{.+}}/secret' // CHECK-NOT: /secret' // CHECK-NOT: /Frameworks' // CHECK-NOT: /SystemFrameworks' // CHECK: </INPUT_BLOCK>
apache-2.0
b0172f9ce502c55637b41609ec1f9d38
57.229167
236
0.706261
3.018359
false
false
false
false
nmartinson/Bluetooth-Camera-Controller
BLE Test/TimerTriggerController.swift
1
2313
// // ControllerViewController.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 11/25/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import UIKit class TimerTriggerController: UIViewController, UITextFieldDelegate { var delegate:UARTViewControllerDelegate? @IBOutlet weak var timeTextField: UITextField! @IBOutlet weak var timeLabel: UILabel! private let buttonPrefix = "!B" var timer:NSTimer! var seconds = 0.0 override func viewDidLoad() { super.viewDidLoad() var appDelegate = UIApplication.sharedApplication().delegate as! BLEAppDelegate delegate = appDelegate.mainViewController! self.title = "Timer" } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { // Stop updates if we're returning to main view timer.invalidate() if self.isMovingFromParentViewController() { //Stop receiving app active notification NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) } super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Shutter Button @IBAction func shutterButtonPressed(sender:UIButton) { if seconds != 0 { timer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "fireShutter", userInfo: nil, repeats: false) } } func fireShutter() { var str = NSString(string:buttonPrefix + TIMELAPSE + "1" ) // a = basic mode var data = NSData(bytes: str.UTF8String, length: str.length) delegate?.sendData(appendCRC(data)) println("triggered") } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField.text != "" { seconds = (textField.text as NSString).doubleValue timeLabel.text = "\(seconds) seconds" } textField.resignFirstResponder() return true } }
bsd-3-clause
c3342967fb92faffea230b69e74d8e65
29.447368
137
0.644617
5.162946
false
false
false
false
AniOSDeveloper/SearchTwitterWithOauth
SearchTwitterWithOauth/AppDelegate.swift
1
4289
// // AppDelegate.swift // SearchTwitterWithOauth // // Created by Larry on 16/5/14. // Copyright ยฉ 2016ๅนด Larry. All rights reserved. // import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? //MARK: -Location let locationManager = CLLocationManager() func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.NotDetermined || status == CLAuthorizationStatus.Denied || status == CLAuthorizationStatus.Restricted { locationManager.startUpdatingLocation() locationManager.requestWhenInUseAuthorization() //ๅฝ“app่ฟ›ๅ…ฅๅ‰ๅฐ็š„ๆ—ถๅ€™ๅ†ๅผ€ๅฏๅฎšไฝ } } func configLocation(){ locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = 50 if CLLocationManager.locationServicesEnabled() { locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let newLocation = locations.last { let currentLongtitude = Float(newLocation.coordinate.longitude) let currentLatitude = Float(newLocation.coordinate.latitude) longitude = String(format: "%.6f", currentLongtitude) latitude = String(format: "%.6f", currentLatitude) locationManager.stopUpdatingLocation() } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("locationManager didFailWithError:\(error)") longitude = "" latitude = "" } //MARK: - Application life cycle func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { configLocation() Tools.getCountryCodes({ (code) in guard let newCountryCodes = code else{ return } language = newCountryCodes }, failure: nil) Tools.getTwitterOauth({ (header) in guard let newQueryHeader = header as? String else{ return } queryHeader = newQueryHeader }, failure: nil) Constants.setUserDefaults() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
39dc30fafbd5958bc76239c893c2fe49
38.813084
285
0.679577
6.042553
false
false
false
false
seivan/ScalarArithmetic
ScalarArithmetic/ScalarArithmetic.swift
1
11882
import Darwin import CoreGraphics public protocol ScalarFloatingPointType: Comparable { var toDouble:Double { get } init(_ value:Double) } extension CGFloat : ScalarFloatingPointType { public var toDouble:Double { return Double(self) } } extension Float : ScalarFloatingPointType { public var toDouble:Double { return Double(self) } } extension Double { public var toCGFloat:CGFloat { return CGFloat(self) } } public protocol FloatingPointOperating { associatedtype Main : FloatingPointType associatedtype Alternative : FloatingPointType associatedtype Avoid : FloatingPointType var abs:Main {get} var acos:Main {get} var asin:Main {get} var atan:Main {get} func atan2(rhs:Main) -> Main func atan2(rhs:Alternative) -> Main var cos:Main {get} var sin:Main {get} var tan:Main {get} var exp:Main {get} var exp2:Main {get} var log:Main {get} var log10:Main {get} var log2:Main {get} func pow(rhs:Main) -> Main func pow(rhs:Alternative) -> Main var sqrt:Main {get} } extension Double : FloatingPointOperating { public typealias Main = Double public typealias Alternative = CGFloat public typealias Avoid = Float public var abs:Main { return Main.abs(self) } public var acos:Main { return Darwin.acos(self) } public var asin:Main { return Darwin.asin(self) } public var atan:Main { return Darwin.atan(self) } public func atan2(x:Main) -> Main { return Darwin.atan2(self,x) } public func atan2(x:Alternative) -> Main { return Darwin.atan2(self, Main(x)) } public var cos:Main { return Darwin.cos(self) } public var sin:Main { return Darwin.sin(self) } public var tan:Main { return Darwin.tan(self) } public var exp:Main { return Darwin.exp(self) } public var exp2:Main { return Darwin.exp2(self) } public var log:Main { return Darwin.log(self) } public var log10:Main{ return Darwin.log10(self) } public var log2:Main { return Darwin.log2(self) } public func pow(rhs:Main)-> Main { return Darwin.pow(self, rhs) } public func pow(rhs:Alternative)-> Main { return Darwin.pow(self, Main(rhs)) } public var sqrt:Main { return Darwin.sqrt(self) } } extension CGFloat : FloatingPointOperating { public typealias Main = CGFloat public typealias Alternative = Double public typealias Avoid = Float public var abs:Main { return Main.abs(self) } public var acos:Main { return Main(Darwin.acos(self.native)) } public var asin:Main { return Main(Darwin.asin(self.native)) } public var atan:Main { return Main(Darwin.atan(self.native)) } public func atan2(rhs:Main) -> Main { return Main(Darwin.atan2(self.native, rhs.native)) } public func atan2(rhs:Alternative) -> Main { return Main(Darwin.atan2(self.native, Main(rhs).native)) } public var cos:Main { return Main(Darwin.cos(self.native)) } public var sin:Main { return Main(Darwin.sin(self.native)) } public var tan:Main { return Main(Darwin.tan(self.native)) } public var exp:Main { return Main(Darwin.exp(self.native)) } public var exp2:Main { return Main(Darwin.exp2(self.native)) } public var log:Main { return Main(Darwin.log(self.native)) } public var log10:Main { return Main(Darwin.log10(self.native)) } public var log2:Main { return Main(Darwin.log2(self.native)) } public func pow(rhs:Main)-> Main { return Main(Darwin.pow(self.native, rhs.native)) } public func pow(rhs:Alternative)-> Main { return Main(Darwin.pow(self.native, Alternative(rhs))) } public var sqrt:Main { return Main(Darwin.sqrt(self.native)) } } extension Float : FloatingPointOperating { public typealias Main = Double public typealias Alternative = CGFloat public typealias Avoid = Float public var abs:Main { return Main.abs(Main(self)) } public var acos:Main { return Darwin.acos(Main(self)) } public var asin:Main { return Darwin.asin(Main(self)) } public var atan:Main { return Darwin.atan(Main(self)) } public func atan2(x:Main) -> Main { return Darwin.atan2(Main(self), x) } public func atan2(x:Alternative) -> Main { return Darwin.atan2(Main(self), Main(x)) } public var cos:Main { return Darwin.cos(Main(self)) } public var sin:Main { return Darwin.sin(Main(self)) } public var tan:Main { return Darwin.tan(Main(self)) } public var exp:Main { return Darwin.exp(Main(self)) } public var exp2:Main { return Darwin.exp2(Main(self)) } public var log:Main { return Darwin.log(Main(self)) } public var log10:Main{ return Darwin.log10(Main(self)) } public var log2:Main { return Darwin.log2(Main(self)) } public func pow(rhs:Main)-> Main { return Darwin.pow(Main(self), rhs) } public func pow(rhs:Alternative)-> Main { return Darwin.pow(Main(self), Main(rhs)) } public var sqrt:Main { return Darwin.sqrt(Main(self)) } } public protocol ScalarIntegerType : ScalarFloatingPointType { var toInt:Int { get } } extension Int : ScalarIntegerType { public var toDouble:Double { return Double(self) } public var toInt:Int { return Int(self) } } extension Int16 : ScalarIntegerType { public var toDouble:Double { return Double(self) } public var toInt:Int { return Int(self) } } extension Int32 : ScalarIntegerType { public var toDouble:Double { return Double(self) } public var toInt:Int { return Int(self) } } extension Int64 : ScalarIntegerType { public var toDouble:Double { return Double(self) } public var toInt:Int { return Int(self) } } extension UInt : ScalarFloatingPointType { public var toDouble:Double { return Double(self) } } extension UInt16 : ScalarFloatingPointType { public var toDouble:Double { return Double(self) } } extension UInt32 : ScalarFloatingPointType { public var toDouble:Double { return Double(self) } } extension UInt64 : ScalarFloatingPointType { public var toDouble:Double { return Double(self) } } ////Equality T<===>T func == <T:ScalarFloatingPointType, U:ScalarFloatingPointType> (lhs:U,rhs:T) -> Bool { return (lhs.toDouble == rhs.toDouble) } func == <T:ScalarFloatingPointType> (lhs:Double,rhs:T) -> Bool { return (lhs == rhs.toDouble) } func == <T:ScalarFloatingPointType> (lhs:T,rhs:Double) -> Bool { return (lhs.toDouble == rhs) } func != <T:ScalarFloatingPointType, U:ScalarFloatingPointType> (lhs:U,rhs:T) -> Bool { return (lhs.toDouble == rhs.toDouble) == false } func != <T:ScalarFloatingPointType> (lhs:Double,rhs:T) -> Bool { return (lhs == rhs.toDouble) == false } func != <T:ScalarFloatingPointType> (lhs:T,rhs:Double) -> Bool { return (lhs.toDouble == rhs) == false } func <= <T:ScalarFloatingPointType, U:ScalarFloatingPointType> (lhs:T,rhs:U) -> Bool { return (lhs.toDouble <= rhs.toDouble) } func <= <T:ScalarFloatingPointType> (lhs:Double, rhs:T) -> Bool { return (lhs <= rhs.toDouble) } func <= <T:ScalarFloatingPointType> (lhs:T,rhs:Double) -> Bool { return (lhs.toDouble <= rhs) } func < <T:ScalarFloatingPointType, U:ScalarFloatingPointType> (lhs:T,rhs:U) -> Bool { return (lhs.toDouble < rhs.toDouble) } func < <T:ScalarFloatingPointType> (lhs:Double, rhs:T) -> Bool { return (lhs < rhs.toDouble) } func < <T:ScalarFloatingPointType> (lhs:T,rhs:Double) -> Bool { return (lhs.toDouble < rhs) } func > <T:ScalarFloatingPointType, U:ScalarFloatingPointType> (lhs:T,rhs:U) -> Bool { return (lhs <= rhs) == false } func > <T:ScalarFloatingPointType> (lhs:Double, rhs:T) -> Bool { return (lhs <= rhs) == false} func > <T:ScalarFloatingPointType> (lhs:T,rhs:Double) -> Bool { return (lhs <= rhs) == false } func >= <T:ScalarFloatingPointType, U:ScalarFloatingPointType> (lhs:T,rhs:U) -> Bool { return (lhs < rhs) == false } func >= <T:ScalarFloatingPointType> (lhs:Double, rhs:T) -> Bool { return (lhs < rhs) == false } func >= <T:ScalarFloatingPointType> (lhs:T,rhs:Double) -> Bool { return (lhs < rhs) == false } // // // ////SUBTRACTION func - <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:T, rhs:U) -> T {return T(lhs.toDouble - rhs.toDouble) } func - <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:U, rhs:T) -> T {return T(lhs.toDouble - rhs.toDouble) } func - <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> T { return T(lhs - rhs.toDouble) } func - <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> T { return T(lhs.toDouble - rhs) } func - <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> Double { return lhs - rhs.toDouble } func - <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> Double { return lhs.toDouble - rhs } func -= <T:ScalarIntegerType, U:ScalarIntegerType>(inout lhs:T, rhs:U) { lhs = T(lhs - rhs.toDouble) } func -= <T:ScalarFloatingPointType>(inout lhs:Double, rhs:T) { lhs = lhs - rhs.toDouble } func -= (inout lhs:CGFloat, rhs:Double) { lhs = lhs - rhs } func -= <T:ScalarFloatingPointType>(inout lhs:CGFloat, rhs:T) { lhs = CGFloat(lhs - rhs.toDouble) } ////ADDITION // func + <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:T, rhs:U) -> T {return T(lhs.toDouble + rhs.toDouble) } func + <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:U, rhs:T) -> T {return T(lhs.toDouble + rhs.toDouble) } func + <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> T { return T(lhs + rhs.toDouble) } func + <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> T { return T(lhs.toDouble + rhs) } func + <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> Double { return lhs + rhs.toDouble } func + <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> Double { return lhs.toDouble + rhs } func += <T:ScalarIntegerType, U:ScalarIntegerType>(inout lhs:T, rhs:U) { lhs = T(lhs + rhs.toDouble) } func += <T:ScalarFloatingPointType>(inout lhs:Double, rhs:T) { lhs = lhs + rhs.toDouble } func += (inout lhs:CGFloat, rhs:Double) { lhs = lhs + rhs } func += <T:ScalarFloatingPointType>(inout lhs:CGFloat, rhs:T) { lhs = CGFloat(lhs + rhs.toDouble) } ////MULTIPLICATION func * <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:T, rhs:U) -> T {return T(lhs.toDouble * rhs.toDouble) } func * <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:U, rhs:T) -> T {return T(lhs.toDouble * rhs.toDouble) } func * <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> T { return T(lhs * rhs.toDouble) } func * <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> T { return T(lhs.toDouble * rhs) } func * <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> Double { return lhs * rhs.toDouble } func * <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> Double { return lhs.toDouble * rhs } func *= <T:ScalarIntegerType, U:ScalarIntegerType>(inout lhs:T, rhs:U) { lhs = T(lhs * rhs.toDouble) } func *= <T:ScalarFloatingPointType>(inout lhs:Double, rhs:T) { lhs = lhs * rhs.toDouble } func *= (inout lhs:CGFloat, rhs:Double) { lhs = lhs * rhs } func *= <T:ScalarFloatingPointType>(inout lhs:CGFloat, rhs:T) { lhs = CGFloat(lhs * rhs.toDouble) } // ////DIVISION func / <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:T, rhs:U) -> T {return T(lhs.toDouble / rhs.toDouble) } func / <T:ScalarFloatingPointType, U:ScalarFloatingPointType>(lhs:U, rhs:T) -> T {return T(lhs.toDouble / rhs.toDouble) } func / <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> T { return T(lhs / rhs.toDouble) } func / <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> T { return T(lhs.toDouble / rhs) } func / <T:ScalarFloatingPointType>(lhs:Double, rhs:T) -> Double { return lhs / rhs.toDouble } func / <T:ScalarFloatingPointType>(lhs:T, rhs:Double) -> Double { return lhs.toDouble / rhs } func /= <T:ScalarIntegerType, U:ScalarIntegerType>(inout lhs:T, rhs:U) { lhs = T(lhs / rhs.toDouble) } func /= <T:ScalarFloatingPointType>(inout lhs:Double, rhs:T) { lhs = lhs / rhs.toDouble } func /= (inout lhs:CGFloat, rhs:Double) { lhs = lhs / rhs } func /= <T:ScalarFloatingPointType>(inout lhs:CGFloat, rhs:T) { lhs = CGFloat(lhs / rhs.toDouble) } // //
mit
1f405d1a2bfe78062cad30d56d5bde34
45.779528
135
0.694243
3.268776
false
false
false
false
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/SwiftImageLoader/MKAnnotationViewExtensions.swift
1
9222
#if os(iOS) import UIKit import MapKit // MARK: - MKAnnotationView Associated Value Keys fileprivate var completionAssociationKey: UInt8 = 0 // MARK: - MKAnnotationView Extensions extension MKAnnotationView: AssociatedValue {} public extension MKAnnotationView { // MARK: - Associated Values final internal var completion: ((_ finished: Bool, _ error: Error?) -> Void)? { get { return getAssociatedValue(key: &completionAssociationKey, defaultValue: nil) } set { setAssociatedValue(key: &completionAssociationKey, value: newValue) } } // MARK: - Image Loading Methods /** Asynchronously downloads an image and loads it into the `MKAnnotationView` using a URL `String`. - parameter urlString: The image URL in the form of a `String`. - parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`. - parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`. */ final func loadImage(urlString: String, placeholder: UIImage? = nil, completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil) { guard let url = URL(string: urlString) else { DispatchQueue.main.async { completion?(false, nil) } return } loadImage(url: url, placeholder: placeholder, completion: completion) } /** Asynchronously downloads an image and loads it into the `MKAnnotationView` using a `URL`. - parameter url: The image `URL`. - parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`. - parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`. */ final func loadImage(url: URL, placeholder: UIImage? = nil, completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil) { let cacheManager = ImageCacheManager.shared var request = URLRequest(url: url, cachePolicy: cacheManager.session.configuration.requestCachePolicy, timeoutInterval: cacheManager.session.configuration.timeoutIntervalForRequest) request.addValue("image/*", forHTTPHeaderField: "Accept") loadImage(request: request, placeholder: placeholder, completion: completion) } /** Asynchronously downloads an image and loads it into the `MKAnnotationView` using a `URLRequest`. - parameter request: The image URL in the form of a `URLRequest`. - parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`. - parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`. */ final func loadImage(request: URLRequest, placeholder: UIImage? = nil, completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil) { self.completion = completion guard let urlAbsoluteString = request.url?.absoluteString else { self.completion?(false, nil) return } let cacheManager = ImageCacheManager.shared let fadeAnimationDuration = cacheManager.fadeAnimationDuration let sharedURLCache = URLCache.shared func loadImage(_ image: UIImage) -> Void { UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: { self.image = image }) self.completion?(true, nil) } // If there's already a cached image, load it into the image view. if let image = cacheManager[urlAbsoluteString] { loadImage(image) } // If there's already a cached response, load the image data into the image view. else if let cachedResponse = sharedURLCache.cachedResponse(for: request), let image = UIImage(data: cachedResponse.data), let creationTimestamp = cachedResponse.userInfo?["creationTimestamp"] as? CFTimeInterval, (Date.timeIntervalSinceReferenceDate - creationTimestamp) < Double(cacheManager.diskCacheMaxAge) { loadImage(image) cacheManager[urlAbsoluteString] = image } // Either begin downloading the image or become an observer for an existing request. else { // Remove the stale disk-cached response (if any). sharedURLCache.removeCachedResponse(for: request) // Set the placeholder image if it was provided. if let placeholder = placeholder { self.image = placeholder } // If the image isn't already being downloaded, begin downloading the image. if cacheManager.isDownloadingFromURL(urlAbsoluteString) == false { cacheManager.setIsDownloadingFromURL(true, urlString: urlAbsoluteString) let dataTask = cacheManager.session.dataTask(with: request) { taskData, taskResponse, taskError in guard let data = taskData, let response = taskResponse, let image = UIImage(data: data), taskError == nil else { DispatchQueue.main.async { cacheManager.setIsDownloadingFromURL(false, urlString: urlAbsoluteString) cacheManager.removeImageCacheObserversForKey(urlAbsoluteString) self.completion?(false, taskError) } return } DispatchQueue.main.async { UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: { self.image = image }) cacheManager[urlAbsoluteString] = image let responseDataIsCacheable = cacheManager.diskCacheMaxAge > 0 && Double(data.count) <= 0.05 * Double(sharedURLCache.diskCapacity) && (cacheManager.session.configuration.requestCachePolicy == .returnCacheDataElseLoad || cacheManager.session.configuration.requestCachePolicy == .returnCacheDataDontLoad) && (request.cachePolicy == .returnCacheDataElseLoad || request.cachePolicy == .returnCacheDataDontLoad) if let httpResponse = response as? HTTPURLResponse, let url = httpResponse.url, responseDataIsCacheable { if var allHeaderFields = httpResponse.allHeaderFields as? [String: String] { allHeaderFields["Cache-Control"] = "max-age=\(cacheManager.diskCacheMaxAge)" if let cacheControlResponse = HTTPURLResponse(url: url, statusCode: httpResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: allHeaderFields) { let cachedResponse = CachedURLResponse(response: cacheControlResponse, data: data, userInfo: ["creationTimestamp": Date.timeIntervalSinceReferenceDate], storagePolicy: .allowed) sharedURLCache.storeCachedResponse(cachedResponse, for: request) } } } self.completion?(true, nil) } } dataTask.resume() } // Since the image is already being downloaded and hasn't been cached, register the image view as a cache observer. else { weak var weakSelf = self cacheManager.addImageCacheObserver(weakSelf!, initialIndexIdentifier: -1, key: urlAbsoluteString) } } } } #endif
mit
5202253019b9ebbc3d29ca552f032e30
53.247059
320
0.600412
6.023514
false
true
false
false
sdkshredder/SocialMe
SocialMe/SocialMe/TableVC.swift
1
18214
// // TableVC.swift // SocialMe // // Created by Matt Duhamel on 5/6/15. // Copyright (c) 2015 new. All rights reserved. // import UIKit import Parse import MobileCoreServices // import CoreImage class TableVC: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { let locationManager = CLLocationManager() let picker = UIImagePickerController() @IBOutlet weak var navTitle: UIButton! @IBOutlet weak var constraint: NSLayoutConstraint! @IBOutlet weak var table: UITableView! var editingAge = false var editingAbout = false var aboutMeText : String! func colorTable() { for subview in table.subviews { // subview.contentView.backgroundColor = UIColor.blueColor() } } func registerNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(TableVC.handleNotification(_:)), name: "ageNotification", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(TableVC.updateAboutMeText(_:)), name: "updateAboutMe", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(TableVC.handleAboutMeNotification(_:)), name: "aboutMeNotification", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"handleAboutMeEndNotification:", name: "aboutMeNotificationEnd", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(TableVC.handleImageNotification(_:)), name: "imageNotification", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TableVC.handleKeyboardWillShowNotification(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TableVC.handleKeyboardWillHideNotification(_:)), name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TableVC.logOut(_:)), name: "logoutNotification", object: nil) } func logOut(notification: NSNotification) { PFUser.logOut() let vc = storyboard?.instantiateViewControllerWithIdentifier("root") as! RootVC navigationController?.presentViewController(vc, animated: true, completion: nil) } func handleKeyboardWillShowNotification(notification: NSNotification) { keyboardWillChangeFrameWithNotification(notification, showsKeyboard: true) } func handleKeyboardWillHideNotification(notification: NSNotification) { keyboardWillChangeFrameWithNotification(notification, showsKeyboard: false) } func keyboardWillChangeFrameWithNotification(notification: NSNotification, showsKeyboard: Bool) { let userInfo = notification.userInfo! let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window) let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window) let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y if showsKeyboard == false { self.table.frame.size.height = view.frame.height - (49 + 64) } else { let height = self.table.frame.size.height print(height) let a = height + originDelta + 50 self.table.frame.size.height = a } UIView.animateWithDuration(animationDuration, delay: 0, options: .BeginFromCurrentState, animations: { }, completion: nil) // Scroll to the selected text once the keyboard frame changes. //let selectedRange = textView.selectedRange //textView.scrollRangeToVisible(selectedRange) } func updateAboutMeText(notification: NSNotification) { if let info = notification.userInfo as? [String : String] { aboutMeText = info["value"] } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 8 } @IBAction func navTap(sender: UIButton) { let a = (UINib(nibName: "swagView", bundle: nil ).instantiateWithOwner(nil, options: nil)[0] as? SwagView)! a.frame = CGRectMake(view.frame.width/2.0 - 140, -100, 280, 200) view.addSubview(a) UIView.animateWithDuration(1, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.4, options: UIViewAnimationOptions.CurveEaseInOut, animations: { a.frame.origin = CGPointMake(a.frame.origin.x, 140) }, completion: nil) } @IBAction func cancel(sender: UIBarButtonItem) { NSNotificationCenter.defaultCenter().postNotificationName("hideSettings", object: nil) navigationController?.popViewControllerAnimated(true) } func getCellID(path : Int) -> String { let a = getTitleForPath(path) if a == "Age" { return "ageCell" } else if a == "" { return "logoutCell" } else if a == "Privacy" { return "privacyCell" } else if a == "Profile Picture"{ return "profilePictureCell" } else if a == "Location" { return "locationCell" } else if a == "About Me" { return "aboutMeCell" } return "tableCell" } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return getTitleForPath(section) } func configureStandardCell(cell: TableTVCell, indexPath: NSIndexPath) { cell.textField.placeholder = getTitleForPath(indexPath.section) cell.editButton.tag = indexPath.section let user = PFUser.currentUser() let attr = getTitleForPath(indexPath.section) if let val = user?.objectForKey(attr) as? String { cell.textField.placeholder = val } } func configureAgeCell(cell: AgeTVCell) { } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 7 { performSegueWithIdentifier("privacyVC", sender: nil) } print(indexPath.section) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let ID = getCellID(indexPath.section) if ID == "profilePictureCell" { var cell = tableView.dequeueReusableCellWithIdentifier(ID) as! ProfilePictureTVCell if let picFile = PFUser.currentUser()?.objectForKey("photo") as? PFFile { picFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in if error == nil { if let imageData = imageData { let image = UIImage(data:imageData) cell.profilePicture.image = image cell.profilePicture.layer.cornerRadius = cell.profilePicture.frame.height / 2.0 cell.profilePicture.clipsToBounds = true } } } } cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } else if ID == "logoutCell" { var cell = tableView.dequeueReusableCellWithIdentifier(ID) as! LogOutTVCell cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } else if ID == "aboutMeCell" { var cell = tableView.dequeueReusableCellWithIdentifier(ID) as! AboutMeTVCell cell.aboutMeLabel.numberOfLines = 0 print(aboutMeText) if aboutMeText == "" { let user = PFUser.currentUser() if let aboutMe = user!.objectForKey("aboutMe") as? String { cell.aboutMeLabel.text = aboutMe aboutMeText = aboutMe } else { cell.aboutMeLabel.text = "" } } else { cell.aboutMeLabel.text = aboutMeText } cell.aboutMeTF.delegate = self cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } else if ID == "locationCell" { var c = tableView.dequeueReusableCellWithIdentifier(ID) as! LocationTVCell if c.editButton.enabled == true { c.editButton.alpha = 1 } else { if (CLLocationManager.authorizationStatus() == .AuthorizedAlways) { c.control.selectedSegmentIndex = 0 } else if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse) { c.control.selectedSegmentIndex = 1 } else { c.control.selectedSegmentIndex = 2 } c.selectionStyle = UITableViewCellSelectionStyle.None } return c } else if ID == "tableCell" { var cell = tableView.dequeueReusableCellWithIdentifier(ID) as! TableTVCell cell.layoutMargins = UIEdgeInsetsZero cell.separatorInset = UIEdgeInsetsZero let title = getTitleForPath(indexPath.section) cell.editButton.tag = indexPath.section cell.textField.delegate = self cell.textField.attributedPlaceholder = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.darkGrayColor()]) let user = PFUser.currentUser() let attr = getTitleForPath(indexPath.section) if let val = user?.objectForKey(attr) as? String { cell.textField.attributedPlaceholder = NSAttributedString(string: val, attributes: [NSForegroundColorAttributeName : UIColor.darkGrayColor()]) } cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } else if ID == "ageCell" { var b = tableView.dequeueReusableCellWithIdentifier(ID) as! AgeTVCell b.selectionStyle = UITableViewCellSelectionStyle.None return b } else if ID == "privacyCell" { // if let b = tableView.dequeueReusableCellWithIdentifier(ID) as? UITableViewCell { // b.selectionStyle = UITableViewCellSelectionStyle.Blue // return b return UITableViewCell() } else { var c = tableView.dequeueReusableCellWithIdentifier(ID) as! LocationTVCell if (CLLocationManager.authorizationStatus() == .AuthorizedAlways) { c.control.selectedSegmentIndex = 0 } else if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse) { c.control.selectedSegmentIndex = 1 } else { c.control.selectedSegmentIndex = 2 } c.selectionStyle = UITableViewCellSelectionStyle.None return c } } override func viewDidLoad() { super.viewDidLoad() table.delegate = self table.dataSource = self registerNotifications() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) table.reloadData() } func presentPicker(type : UIImagePickerControllerSourceType) { if UIImagePickerController.isSourceTypeAvailable(type) { let picker = UIImagePickerController() picker.sourceType = type if type == .Camera { picker.showsCameraControls = true picker.mediaTypes = [kUTTypeImage as String] } picker.delegate = self picker.allowsEditing = true presentViewController(picker, animated: true, completion: nil) } } func handleAbouMeNotification(notification: NSNotification) { /* let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) actionSheet.addAction(UIAlertAction(title:"Upload Photo", style:UIAlertActionStyle.Default, handler:{ action in let type = UIImagePickerControllerSourceType.PhotoLibrary self.presentPicker(type) })) actionSheet.addAction(UIAlertAction(title:"Take a Picture", style:UIAlertActionStyle.Default, handler:{ action in let type = UIImagePickerControllerSourceType.Camera self.presentPicker(type) })) actionSheet.addAction(UIAlertAction(title:"Cancel", style:UIAlertActionStyle.Cancel, handler:nil)) presentViewController(actionSheet, animated:true, completion:nil) */ } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if range.length + range.location > 300 { return false } return true } func handleImageNotification(notification: NSNotification) { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) actionSheet.addAction(UIAlertAction(title:"Take Photo", style:UIAlertActionStyle.Default, handler:{ action in let type = UIImagePickerControllerSourceType.Camera self.presentPicker(type) })) actionSheet.addAction(UIAlertAction(title:"Photo Library", style:UIAlertActionStyle.Default, handler:{ action in let type = UIImagePickerControllerSourceType.PhotoLibrary self.presentPicker(type) })) actionSheet.addAction(UIAlertAction(title:"Cancel", style:UIAlertActionStyle.Cancel, handler:nil)) presentViewController(actionSheet, animated:true, completion:nil) } // func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { // var image = info[UIImagePickerControllerEditedImage] as? UIImage // if image == nil { // image = info[UIImagePickerControllerOriginalImage] as? UIImage // // } // // let file = PFFile(name:"photo.png", data:UIImagePNGRepresentation(image!)!) // let currentUser = PFUser.currentUser() // currentUser!.setObject(file, forKey: "photo") // currentUser!.saveInBackgroundWithBlock{ // (succeeded, error) -> Void in // if error == nil { // print("image saved") // } else { // print("error saving image") // } // } // // dismissViewControllerAnimated(true, completion: nil) // NSNotificationCenter.defaultCenter().postNotificationName("hideSettings", object: nil) // } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) NSNotificationCenter.defaultCenter().postNotificationName("hideSettings", object: nil) } func handleNotification(notification: NSNotification) { editingAge = !editingAge table.beginUpdates() table.endUpdates() NSNotificationCenter.defaultCenter().postNotificationName("pickerNotification", object: nil) } func handleAboutMeNotification(notification: NSNotification) { editingAbout = !editingAbout if editingAbout == true { } table.beginUpdates() table.endUpdates() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let a = getTitleForPath(indexPath.section) if a == "Age" && editingAge == true { return 340 } else if a == "Location" { return 90 } else if a == "Profile Picture" { return 240 } else if a == "Log Out" || a == "Privacy" { return 44 } else if a == "About Me" && editingAbout == false { let cell = tableView.dequeueReusableCellWithIdentifier("aboutMeCell") as! AboutMeTVCell let maxWidth = CGFloat(cell.aboutMeLabel.frame.width) let maxHeight = CGFloat(10000.0) let size = CGSizeMake(maxWidth, maxHeight) if let aboutMe = aboutMeText { } else { aboutMeText = "" } let frame = NSString(string: aboutMeText).boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(17)], context: nil) return frame.height + 40 } return 44 } func getTitleForPath(path : Int) -> String { switch path { case 0: return "Profile Picture" case 1: return "About Me" case 2: return "Name" case 3: return "Hometown" case 4: return "School" case 5: return "Occupation" case 6: return "Location" default: return "" } } }
mit
f2c09e8f724cd9ac0392e839f0a6e0be
40.871264
192
0.623586
5.632035
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/SignUp/Cell/Input/InputCell.swift
1
3771
// // InputCell.swift // FoodAndFitness // // Created by Mylo Ho on 4/5/17. // Copyright ยฉ 2017 SuHoVan. All rights reserved. // import UIKit import SwiftDate protocol InputCellDelegate: NSObjectProtocol { func cell(_ cell: InputCell, withInputString string: String) } final class InputCell: BaseTableViewCell { @IBOutlet fileprivate(set) weak var titleLabel: UILabel! @IBOutlet fileprivate(set) weak var textField: UITextField! weak var delegate: InputCellDelegate? static let maxValue: Int = 250 struct Data { var title: String var placeHolder: String var detailText: String? } var cellType: SignUpController.SignUpRow = .fullName { didSet { switch cellType { case .password, .confirmPassword: textField.isSecureTextEntry = true case .birthday: let picker = datePicker() textField.inputView = picker textField.text = DateInRegion(timeIntervalSince1970: 0).toString(format: .date) case .height: textField.keyboardType = .numberPad textField.setUnit(text: Strings.centimeter, textColor: Color.green64) case .weight: textField.keyboardType = .numberPad textField.setUnit(text: Strings.kilogam, textColor: Color.green64) default: break } } } var data: Data? { didSet { guard let data = data else { return } titleLabel.text = data.title textField.placeholder = data.placeHolder textField.text = data.detailText } } override func setupUI() { super.setupUI() textField.delegate = self } private func datePicker() -> UIDatePicker { let datePicker = UIDatePicker() datePicker.setDate(Date(timeIntervalSince1970: 0), animated: true) datePicker.minimumDate = Date(timeIntervalSince1970: 0) datePicker.maximumDate = Date() datePicker.datePickerMode = .date datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged) return datePicker } @objc fileprivate func datePickerChanged(_ sender: Any) { guard let picker = textField.inputView as? UIDatePicker else { return } let date = DateInRegion(absoluteDate: picker.date).toString(format: .date) textField.text = date } } // MARK: - UITextFieldDelegate extension InputCell: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { switch cellType { case .height, .weight: textField.text = Strings.empty default: break } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { switch cellType { case .height, .weight: guard let text = textField.text else { return true } guard let number = Int(text + string) else { return false } if number > InputCell.maxValue, string != Strings.empty { return false } default: break } return true } func textFieldDidEndEditing(_ textField: UITextField) { switch cellType { case .height, .weight: guard let text = textField.text else { textField.text = "0" return } if text.characters.isEmpty { textField.text = "0" } default: break } if let string = textField.text { delegate?.cell(self, withInputString: string) } } }
mit
4a3121680a042bbe4159b03851bd58e7
30.157025
129
0.596817
5.129252
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/InteractiveNotifications/WebViewController/WebViewToolbar.swift
1
1261
// // WebViewToolbar.swift // MobileMessaging // // Created by Andrey Kadochnikov on 28.04.2020. // import Foundation protocol WebViewToolbarDelegate { func webViewToolbarDidPressDismiss() } class WebViewToolbar: UIToolbar { var dismissDelegate: WebViewToolbarDelegate? lazy private var titleLabel: UILabel = UILabel(frame: CGRect.zero) var titleColor: UIColor? { set { titleLabel.textColor = newValue } get { return titleLabel.textColor } } var title: String? { set { titleLabel.text = newValue titleLabel.sizeToFit() } get { return titleLabel.text } } override init(frame: CGRect) { super.init(frame: frame) titleLabel.backgroundColor = UIColor.clear titleLabel.textAlignment = .center let dismissBtn = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(dismiss)) let labelItem = UIBarButtonItem.init(customView: titleLabel) let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) self.setItems([flexible, labelItem, flexible, dismissBtn], animated: false) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func dismiss() { dismissDelegate?.webViewToolbarDidPressDismiss() } }
apache-2.0
f0e897a7ec9a55dc60eac882b4448b67
21.927273
104
0.736717
3.786787
false
false
false
false
FraDeliro/ISaMaterialLogIn
Example/Pods/Material/Sources/iOS/ImageCard.swift
1
3455
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of CosmicMind 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ import UIKit @objc(ToolbarAlignment) public enum ToolbarAlignment: Int { case top case bottom } open class ImageCard: Card { /// A preset wrapper around imageViewEdgeInsets. open var imageViewEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { imageViewEdgeInsets = EdgeInsetsPresetToValue(preset: imageViewEdgeInsetsPreset) } } /// A reference to imageViewEdgeInsets. @IBInspectable open var imageViewEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the imageView. @IBInspectable open var imageView: UIImageView? { didSet { oldValue?.removeFromSuperview() if let v = imageView { container.addSubview(v) } layoutSubviews() } } /// An ImageCardToolbarAlignment value. open var toolbarAlignment = ToolbarAlignment.bottom { didSet { layoutSubviews() } } open override func reload() { var h: CGFloat = 0 if let v = imageView { h = prepare(view: v, with: imageViewEdgeInsets, from: h) container.sendSubview(toBack: v) } if let v = toolbar { prepare(view: v, with: toolbarEdgeInsets, from: h) v.y = .top == toolbarAlignment ? toolbarEdgeInsets.top : h - v.height - toolbarEdgeInsets.bottom container.bringSubview(toFront: v) } if let v = contentView { h = prepare(view: v, with: contentViewEdgeInsets, from: h) } if let v = bottomBar { h = prepare(view: v, with: bottomBarEdgeInsets, from: h) } container.height = h bounds.size.height = h } }
mit
0e746379a52d90bcf623269604d9b382
33.89899
108
0.657598
4.845722
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Search/ZSSearchResultCell.swift
1
3861
// // ZSSearchResultCell.swift // zhuishushenqi // // Created by yung on 2019/10/27. // Copyright ยฉ 2019 QS. All rights reserved. // import UIKit import Kingfisher class ZSSearchResultCell: UITableViewCell { lazy var bookIconView:UIImageView = { let icon = UIImageView(frame: .zero) return icon }() lazy var bookNameLB:UILabel = { let icon = UILabel(frame: .zero) icon.textColor = UIColor.black icon.font = UIFont.systemFont(ofSize: 15) return icon }() lazy var authorLB:UILabel = { let icon = UILabel(frame: .zero) icon.textColor = UIColor.black icon.font = UIFont.systemFont(ofSize: 13) return icon }() lazy var typeLB:UILabel = { let icon = UILabel(frame: .zero) icon.textColor = UIColor.gray icon.font = UIFont.systemFont(ofSize: 15) return icon }() lazy var sourceLB:UILabel = { let icon = UILabel(frame: .zero) icon.textColor = UIColor.gray icon.font = UIFont.systemFont(ofSize: 15) icon.textAlignment = .right return icon }() lazy var bookDescLB:UILabel = { let icon = UILabel(frame: .zero) icon.textColor = UIColor.gray icon.font = UIFont.systemFont(ofSize: 13) icon.numberOfLines = 0 return icon }() override func layoutSubviews() { super.layoutSubviews() self.bookIconView.frame = CGRect(x: 15, y: 15, width: 80, height: 100) self.bookNameLB.frame = CGRect(x: self.bookIconView.frame.maxX + 20, y: 15, width: 200, height: 15) self.sourceLB.frame = CGRect(x: self.contentView.bounds.width - 100 - 15, y: 20, width: 100, height: 15) self.authorLB.frame = CGRect(x: self.bookIconView.frame.maxX + 20, y: self.bookNameLB.frame.maxY + 5, width: 200, height: 15) self.bookDescLB.frame = CGRect(x: self.bookIconView.frame.maxX + 20, y: self.authorLB.frame.maxY + 5, width: self.contentView.bounds.width - self.bookIconView.frame.maxX - 20 - 20, height: 45) } func configure(model:ZSAikanParserModel) { let icon = model.bookIcon.length != 0 ? model.bookIcon:model.detailBookIcon let resource = QSResource(url: URL(string: "\(icon)") ?? URL(string: "https://www.baidu.com")!) self.bookIconView.kf.setImage(with: resource,placeholder: UIImage(named: "default_book_cover")) self.bookDescLB.text = model.bookDesc.length != 0 ? model.bookDesc:model.detailBookDesc self.sourceLB.text = model.name self.authorLB.text = model.bookAuthor self.bookNameLB.text = model.bookName } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(self.bookIconView) contentView.addSubview(self.bookNameLB) contentView.addSubview(self.authorLB) contentView.addSubview(self.typeLB) contentView.addSubview(self.sourceLB) contentView.addSubview(self.bookDescLB) } override func prepareForReuse() { let resource = QSResource(url: URL(string: "") ?? URL(string: "https://www.baidu.com")!) self.bookIconView.kf.setImage(with: resource) self.bookDescLB.text = "" self.sourceLB.text = "" self.authorLB.text = "" self.bookNameLB.text = "" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
651961289a4ba1abc9b261acc9ad4f49
33.774775
200
0.634197
4.020833
false
false
false
false
Crowdmix/Buildasaur
Buildasaur/BuildTemplateViewController.swift
1
19819
// // BuildTemplateViewController.swift // Buildasaur // // Created by Honza Dvorsky on 09/03/15. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import AppKit import BuildaUtils import XcodeServerSDK import BuildaKit class BuildTemplateViewController: SetupViewController, NSComboBoxDelegate, NSTableViewDataSource, NSTableViewDelegate, SetupViewControllerDelegate, NSComboBoxDataSource { var storageManager: StorageManager! var project: Project! var buildTemplate: BuildTemplate! var xcodeServer: XcodeServer? @IBOutlet weak var nameTextField: NSTextField! @IBOutlet weak var schemesComboBox: NSComboBox! @IBOutlet weak var archiveButton: NSButton! @IBOutlet weak var testButton: NSButton! @IBOutlet weak var analyzeButton: NSButton! @IBOutlet weak var saveButton: NSButton! @IBOutlet weak var triggersTableView: NSTableView! @IBOutlet weak var scheduleComboBox: NSComboBox! @IBOutlet weak var cleaninPolicyComboBox: NSComboBox! @IBOutlet weak var testDeviceFilterComboBox: NSComboBox! @IBOutlet weak var testDevicesTableView: NSTableView! @IBOutlet weak var testDevicesActivityIndicator: NSProgressIndicator! private var triggerToEdit: Trigger? private var allAvailableTestingDevices: [Device] = [] func allSchedules() -> [BotSchedule.Schedule] { //scheduled not yet supported, just manual vs commit return [ BotSchedule.Schedule.Manual, BotSchedule.Schedule.Commit //TODO: add UI support for proper schedule - hourly/daily/weekly ] } func allCleaningPolicies() -> [BotConfiguration.CleaningPolicy] { return [ BotConfiguration.CleaningPolicy.Never, BotConfiguration.CleaningPolicy.Always, BotConfiguration.CleaningPolicy.Once_a_Day, BotConfiguration.CleaningPolicy.Once_a_Week ] } func allFilters() -> [DeviceFilter.FilterType] { let currentPlatformType = self.buildTemplate.platformType ?? .Unknown let allFilters = DeviceFilter.FilterType.availableFiltersForPlatform(currentPlatformType) return allFilters } override func viewDidLoad() { super.viewDidLoad() if let xcodeServerConfig = self.storageManager.servers.first { let xcodeServer = XcodeServerFactory.server(xcodeServerConfig) self.xcodeServer = xcodeServer } self.testDeviceFilterComboBox.delegate = self self.testDeviceFilterComboBox.usesDataSource = true self.testDeviceFilterComboBox.dataSource = self let schemes = self.project.schemeNames() self.schemesComboBox.removeAllItems() self.schemesComboBox.addItemsWithObjectValues(schemes) let temp = self.buildTemplate let projectName = self.project.projectName self.buildTemplate.projectName = projectName //name self.nameTextField.stringValue = temp.name ?? "" //schemes if let preferredScheme = temp.scheme { self.schemesComboBox.selectItemWithObjectValue(preferredScheme) } //stages self.analyzeButton.state = (temp.shouldAnalyze ?? false) ? NSOnState : NSOffState self.testButton.state = (temp.shouldTest ?? false) ? NSOnState : NSOffState self.archiveButton.state = (temp.shouldArchive ?? false) ? NSOnState : NSOffState //cleaning policy and schedule self.scheduleComboBox.removeAllItems() self.scheduleComboBox.addItemsWithObjectValues(self.allSchedules().map({ $0.toString() })) if let schedule = self.buildTemplate.schedule { let index = self.allSchedules().indexOfFirstObjectPassingTest({ $0 == schedule.schedule })! self.scheduleComboBox.selectItemAtIndex(index) } self.scheduleComboBox.delegate = self self.cleaninPolicyComboBox.removeAllItems() self.cleaninPolicyComboBox.addItemsWithObjectValues(self.allCleaningPolicies().map({ $0.toString() })) let cleaningPolicy = self.buildTemplate.cleaningPolicy let cleaningIndex = self.allCleaningPolicies().indexOfFirstObjectPassingTest({ $0 == cleaningPolicy })! self.cleaninPolicyComboBox.selectItemAtIndex(cleaningIndex) self.cleaninPolicyComboBox.delegate = self self.refreshDataInDeviceFilterComboBox() self.triggersTableView.reloadData() self.testDeviceFilterComboBox.reloadData() } func refreshDataInDeviceFilterComboBox() { self.testDeviceFilterComboBox.reloadData() let filters = self.allFilters() let filter = self.buildTemplate.deviceFilter ?? .AllAvailableDevicesAndSimulators if let destinationIndex = filters.indexOfFirstObjectPassingTest({ $0 == filter }) { self.testDeviceFilterComboBox.selectItemAtIndex(destinationIndex) } } func fetchDevices(completion: () -> ()) { self.testDevicesActivityIndicator.startAnimation(nil) self.allAvailableTestingDevices.removeAll(keepCapacity: true) self.testDevicesTableView.reloadData() if let xcodeServer = self.xcodeServer { xcodeServer.getDevices({ (devices, error) -> () in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in if let error = error { UIUtils.showAlertWithError(error) return } self.allAvailableTestingDevices = self.processReceivedDevices(devices!) self.testDevicesTableView.reloadData() self.testDevicesActivityIndicator.stopAnimation(nil) }) }) } else { UIUtils.showAlertWithText("Please setup Xcode Server first, so that we can fetch testing devices") completion() } } func processReceivedDevices(devices: [Device]) -> [Device] { //pull filter from platform type guard let platform = self.buildTemplate.platformType else { return [] } let allowedPlatforms: Set<DevicePlatform.PlatformType> switch platform { case .iOS, .iOS_Simulator: allowedPlatforms = Set([.iOS, .iOS_Simulator]) default: allowedPlatforms = Set([platform]) } //filter first let filtered = devices.filter { allowedPlatforms.contains($0.platform) } let sortDevices = { (a: Device, b: Device) -> (equal: Bool, shouldGoBefore: Bool) in if a.simulator == b.simulator { return (equal: true, shouldGoBefore: true) } return (equal: false, shouldGoBefore: !a.simulator) } let sortConnected = { (a: Device, b: Device) -> (equal: Bool, shouldGoBefore: Bool) in if a.connected == b.connected { return (equal: true, shouldGoBefore: false) } return (equal: false, shouldGoBefore: a.connected) } //then sort, devices first and if match, connected first let sortedDevices = filtered.sort { (a, b) -> Bool in let (equalDevices, goBeforeDevices) = sortDevices(a, b) if !equalDevices { return goBeforeDevices } let (equalConnected, goBeforeConnected) = sortConnected(a, b) if !equalConnected { return goBeforeConnected } return true } return sortedDevices } override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { let destinationController = segue.destinationController as! NSViewController if let triggerViewController = destinationController as? TriggerViewController { triggerViewController.inTrigger = self.triggerToEdit if let sender = sender as? SetupViewControllerDelegate { triggerViewController.delegate = sender } } super.prepareForSegue(segue, sender: sender) } override func viewWillAppear() { super.viewWillAppear() self.schemesComboBox.delegate = self self.fetchDevices { () -> () in Log.verbose("Finished fetching devices") } } override func reloadUI() { super.reloadUI() self.triggersTableView.reloadData() //enable devices table view only if selected devices is chosen let filter = self.buildTemplate.deviceFilter ?? .AllAvailableDevicesAndSimulators let selectable = filter == .SelectedDevicesAndSimulators self.testDevicesTableView.enabled = selectable //also change the device filter picker based on the platform self.refreshDataInDeviceFilterComboBox() } func pullStagesFromUI() -> Bool { self.buildTemplate.shouldAnalyze = (self.analyzeButton.state == NSOnState) self.buildTemplate.shouldTest = (self.testButton.state == NSOnState) self.buildTemplate.shouldArchive = (self.archiveButton.state == NSOnState) return true } override func pullDataFromUI(interactive: Bool) -> Bool { if super.pullDataFromUI(interactive) { let scheme = self.pullSchemeFromUI(interactive) let name = self.pullNameFromUI() let stages = self.pullStagesFromUI() let schedule = self.pullScheduleFromUI(interactive) let cleaning = self.pullCleaningPolicyFromUI(interactive) let filter = self.pullFilterFromUI(interactive) return scheme && name && stages && schedule && cleaning && filter } return false } func pullCleaningPolicyFromUI(interactive: Bool) -> Bool { let index = self.cleaninPolicyComboBox.indexOfSelectedItem if index > -1 { let policy = self.allCleaningPolicies()[index] self.buildTemplate.cleaningPolicy = policy return true } if interactive { UIUtils.showAlertWithText("Please choose a cleaning policy") } return false } func pullScheduleFromUI(interactive: Bool) -> Bool { let index = self.scheduleComboBox.indexOfSelectedItem if index > -1 { let scheduleType = self.allSchedules()[index] let schedule: BotSchedule switch scheduleType { case .Commit: schedule = BotSchedule.commitBotSchedule() case .Manual: schedule = BotSchedule.manualBotSchedule() default: assertionFailure("Other schedules not yet supported") schedule = BotSchedule(json: NSDictionary()) } self.buildTemplate.schedule = schedule return true } if interactive { UIUtils.showAlertWithText("Please choose a bot schedule (choose 'Manual' for Syncer-controller bots)") } return false } func pullNameFromUI() -> Bool { let name = self.nameTextField.stringValue if !name.isEmpty { self.buildTemplate.name = name return true } else { self.buildTemplate.name = nil return false } } func pullSchemeFromUI(interactive: Bool) -> Bool { //validate that the selection is valid if let selectedScheme = self.schemesComboBox.objectValueOfSelectedItem as? String { let schemes = self.project.schemeNames() if schemes.indexOf(selectedScheme) != nil { //found it, good, use it self.buildTemplate.scheme = selectedScheme //also refresh devices for testing based on the scheme type do { let platformType = try XcodeDeviceParser.parseDeviceTypeFromProjectUrlAndScheme(self.project.url, scheme: selectedScheme).toPlatformType() self.buildTemplate.platformType = platformType self.reloadUI() self.fetchDevices({ () -> () in // }) return true } catch { print("\(error)") return false } } } if interactive { UIUtils.showAlertWithText("Please select a scheme to build with") } return false } func pullFilterFromUI(interactive: Bool) -> Bool { let index = self.testDeviceFilterComboBox.indexOfSelectedItem if index > -1 { let filter = self.allFilters()[index] self.buildTemplate.deviceFilter = filter return true } if interactive && self.testDeviceFilterComboBox.numberOfItems > 0 { UIUtils.showAlertWithText("Please select a device filter to test on") } return false } private func cleanTestingDeviceIds() { self.buildTemplate.testingDeviceIds = [] } func comboBoxSelectionDidChange(notification: NSNotification) { if let comboBox = notification.object as? NSComboBox { if comboBox == self.testDeviceFilterComboBox { self.pullFilterFromUI(true) self.reloadUI() self.cleanTestingDeviceIds() //filter changed, refetch self.fetchDevices({ () -> () in // }) } else if comboBox == self.schemesComboBox { if self.testDeviceFilterComboBox.numberOfItems > 0 { self.testDeviceFilterComboBox.selectItemAtIndex(0) } self.pullSchemeFromUI(true) self.cleanTestingDeviceIds() } } } override func willSave() { self.storageManager.saveBuildTemplate(self.buildTemplate) super.willSave() } @IBAction func addTriggerButtonTapped(sender: AnyObject) { self.editTrigger(nil) } @IBAction func deleteButtonTapped(sender: AnyObject) { UIUtils.showAlertAskingForRemoval("Are you sure you want to delete this build template?", completion: { (remove) -> () in if remove { self.storageManager.removeBuildTemplate(self.buildTemplate) self.buildTemplate = nil self.cancel() } }) } //MARK: filter combo box func numberOfItemsInComboBox(aComboBox: NSComboBox) -> Int { if (aComboBox == self.testDeviceFilterComboBox) { return self.allFilters().count } return 0 } func comboBox(aComboBox: NSComboBox, objectValueForItemAtIndex index: Int) -> AnyObject { if (aComboBox == self.testDeviceFilterComboBox) { if index >= 0 { return self.allFilters()[index].toString() } } return "" } //MARK: triggers table view func numberOfRowsInTableView(tableView: NSTableView) -> Int { if tableView == self.triggersTableView { return self.buildTemplate.triggers.count } else if tableView == self.testDevicesTableView { return self.allAvailableTestingDevices.count } return 0 } func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { if self.buildTemplate != nil { if tableView == self.triggersTableView { let triggers = self.buildTemplate.triggers if tableColumn!.identifier == "names" { let trigger = triggers[row] return trigger.name } } else if tableView == self.testDevicesTableView { let device = self.allAvailableTestingDevices[row] switch tableColumn!.identifier { case "name": let simString = device.simulator ? "Simulator " : "" let connString = device.connected ? "" : "[disconnected]" let string = "\(simString)\(device.name) (\(device.osVersion)) \(connString)" return string case "enabled": let devices = self.buildTemplate.testingDeviceIds ?? [] let index = devices.indexOfFirstObjectPassingTest({ $0 == device.id }) let enabled = index > -1 return enabled default: return nil } } } return nil } func setupViewControllerDidSave(viewController: SetupViewController) { if let triggerViewController = viewController as? TriggerViewController { if let outTrigger = triggerViewController.outTrigger { if let inTrigger = triggerViewController.inTrigger { //was an existing trigger, just replace in place let index = self.buildTemplate.triggers.indexOfFirstObjectPassingTest { $0.uniqueId == inTrigger.uniqueId }! self.buildTemplate.triggers[index] = outTrigger } else { //new trigger, just add self.buildTemplate.triggers.append(outTrigger) } } } self.reloadUI() } func setupViewControllerDidCancel(viewController: SetupViewController) { // } func editTrigger(trigger: Trigger?) { self.triggerToEdit = trigger self.performSegueWithIdentifier("showTrigger", sender: self) } @IBAction func triggerTableViewEditTapped(sender: AnyObject) { let index = self.triggersTableView.selectedRow let trigger = self.buildTemplate.triggers[index] self.editTrigger(trigger) } @IBAction func triggerTableViewDeleteTapped(sender: AnyObject) { let index = self.triggersTableView.selectedRow self.buildTemplate.triggers.removeAtIndex(index) self.reloadUI() } @IBAction func testDevicesTableViewRowCheckboxTapped(sender: AnyObject) { //toggle selection in model and reload data //get device at index first let device = self.allAvailableTestingDevices[self.testDevicesTableView.selectedRow] //see if we are checking or unchecking let foundIndex = self.buildTemplate.testingDeviceIds.indexOfFirstObjectPassingTest({ $0 == device.id }) if let foundIndex = foundIndex { //found, remove it self.buildTemplate.testingDeviceIds.removeAtIndex(foundIndex) } else { //not found, add it self.buildTemplate.testingDeviceIds.append(device.id) } self.testDevicesTableView.reloadData() } }
mit
1b0ac8e9119fdf81e565b87902993e35
35.166058
171
0.591907
5.557768
false
true
false
false
meetkei/KeiSwiftFramework
KeiSwiftFramework/View/Button/KRoundButton.swift
1
2073
// // KRoundButton.swift // // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @IBDesignable open class KRoundButton: UIButton { @IBInspectable open var cornerRadius: CGFloat = 3 { didSet { setupView() } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { setupView() } } @IBInspectable open var borderColor: UIColor = UIColor.clear { didSet { setupView() } } public override init(frame: CGRect) { super.init(frame: frame) setupView() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupView() } func setupView() { layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor clipsToBounds = true } }
mit
68acee1e4efbc1521477999615f8b5cb
27.791667
81
0.65316
4.743707
false
false
false
false
hollance/swift-algorithm-club
Counting Sort/CountingSort.swift
2
1229
// // Sort.swift // test // // Created by Kauserali on 11/04/16. // Copyright ยฉ 2016 Ali Hafizji. All rights reserved. // func countingSort(_ array: [Int])-> [Int] { guard array.count > 0 else {return []} // Step 1 // Create an array to store the count of each element let maxElement = array.max() ?? 0 var countArray = [Int](repeating: 0, count: Int(maxElement + 1)) for element in array { countArray[element] += 1 } // Step 2 // Set each value to be the sum of the previous two values for index in 1 ..< countArray.count { let sum = countArray[index] + countArray[index - 1] countArray[index] = sum } print(countArray) // Step 3 // Place the element in the final array as per the number of elements before it // Loop through the array in reverse to keep the stability of the new sorted array // (For Example: 7 is at index 3 and 6, thus in sortedArray the position of 7 at index 3 should be before 7 at index 6 var sortedArray = [Int](repeating: 0, count: array.count) for index in stride(from: array.count - 1, through: 0, by: -1) { let element = array[index] countArray[element] -= 1 sortedArray[countArray[element]] = element } return sortedArray }
mit
25f623e8609df705ad2448913eb91230
28.95122
120
0.666124
3.601173
false
false
false
false
Gruppio/Invoke
Tests/Invoke/KeychainSwiftTests.swift
1
4162
import XCTest @testable import Invoke class KeychainSwiftTests: XCTestCase { var obj: KeychainSwift! override func setUp() { super.setUp() obj = KeychainSwift() obj.clear() obj.lastQueryParameters = nil } // MARK: - Set text // ----------------------- func testSet() { XCTAssertTrue(obj.set("hello :)", forKey: "key 1")) XCTAssertEqual("hello :)", obj.getString("key 1")!) } func testSet_usesAccessibleWhenUnlockedByDefault() { XCTAssertTrue(obj.set("hello :)", forKey: "key 1")) let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!) } func testSetWithAccessOption() { obj.set("hello :)", forKey: "key 1", withAccess: .accessibleAfterFirstUnlock) let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String XCTAssertEqual(KeychainSwiftAccessOptions.accessibleAfterFirstUnlock.value, accessValue!) } // MARK: - Set strng array // ----------------------- func testSetStringArray() { XCTAssertTrue(obj.set(["hello :)"], forKey: "key 1")) XCTAssertEqual(["hello :)"], obj.getStringArray("key 1")!) } func testSetEmptyStringArray() { XCTAssertTrue(obj.set([], forKey: "key 1")) XCTAssertNil(obj.getStringArray("key 1")) } func testSetStringArray_usesAccessibleWhenUnlockedByDefault() { XCTAssertTrue(obj.set(["hello :)"], forKey: "key 1")) let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!) } func testSetStringArrayWithAccessOption() { obj.set(["hello :)"], forKey: "key 1", withAccess: .accessibleAfterFirstUnlock) let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String XCTAssertEqual(KeychainSwiftAccessOptions.accessibleAfterFirstUnlock.value, accessValue!) } // MARK: - Set data // ----------------------- func testSetData() { let data = "hello world".data(using: String.Encoding.utf8)! XCTAssertTrue(obj.set(data, forKey: "key 123")) let dataFromKeychain = obj.getData("key 123")! let textFromKeychain = String(data: dataFromKeychain, encoding:String.Encoding.utf8)! XCTAssertEqual("hello world", textFromKeychain) } func testSetData_usesAccessibleWhenUnlockedByDefault() { let data = "hello world".data(using: String.Encoding.utf8)! obj.set(data, forKey: "key 123") let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!) } // MARK: - Set bool // ----------------------- func testSetBool() { XCTAssertTrue(obj.set(true, forKey: "key bool")) XCTAssertTrue(obj.getBool("key bool")!) XCTAssertTrue(obj.set(false, forKey: "key bool")) XCTAssertFalse(obj.getBool("key bool")!) } func testSetBool_usesAccessibleWhenUnlockedByDefault() { XCTAssertTrue(obj.set(false, forKey: "key bool")) let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!) } // MARK: - Get // ----------------------- func testGet_returnNilWhenValueNotSet() { XCTAssert(obj.getString("key 1") == nil) } // MARK: - Get bool // ----------------------- func testGetBool_returnNilWhenValueNotSet() { XCTAssert(obj.getBool("some bool key") == nil) } // MARK: - Delete // ----------------------- func testDelete() { obj.set("hello :)", forKey: "key 1") obj.delete("key 1") XCTAssert(obj.getString("key 1") == nil) } func testDelete_deleteOnSingleKey() { obj.set("hello :)", forKey: "key 1") obj.set("hello two", forKey: "key 2") obj.delete("key 1") XCTAssertEqual("hello two", obj.getString("key 2")!) } }
mit
b359fe7f2d8946e8f4815eee5a6075da
30.293233
97
0.652331
4.470462
false
true
false
false
apple/swift
test/decl/ext/objc_implementation.swift
2
12660
// RUN: %target-typecheck-verify-swift -import-objc-header %S/Inputs/objc_implementation.h // REQUIRES: objc_interop // FIXME: Should complain about method(fromHeader4:) and propertyFromHeader9 @_objcImplementation extension ObjCClass { // expected-note@-1 {{previously implemented by extension here}} func method(fromHeader1: CInt) { // FIXME: OK, provides an implementation for the header's method. // expected-error@-2 {{instance method 'method(fromHeader1:)' does not match any instance method declared in the headers for 'ObjCClass'; did you use the instance method's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible instance method not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift instance method that cannot be overridden}} {{3-3=final }} } @objc func method(fromHeader2: CInt) { // OK, provides an implementation for the header's method. } func categoryMethod(fromHeader3: CInt) { // FIXME: Should complain about the wrong category // expected-error@-2 {{instance method 'categoryMethod(fromHeader3:)' does not match any instance method declared in the headers for 'ObjCClass'; did you use the instance method's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible instance method not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift instance method that cannot be overridden}} {{3-3=final }} } @objc fileprivate func methodNot(fromHeader1: CInt) { // OK, declares a new @objc dynamic method. } final func methodNot(fromHeader2: CInt) { // OK, declares a new Swift method. } func methodNot(fromHeader3: CInt) { // expected-error@-1 {{instance method 'methodNot(fromHeader3:)' does not match any instance method declared in the headers for 'ObjCClass'; did you use the instance method's Swift name?}} // expected-note@-2 {{add '@objc' to define an Objective-C-compatible instance method not declared in the header}} {{3-3=@objc }} // expected-note@-3 {{add 'final' to define a Swift instance method that cannot be overridden}} {{3-3=final }} } var propertyFromHeader1: CInt // FIXME: OK, provides an implementation with a stored property // expected-error@-2 {{property 'propertyFromHeader1' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} @objc var propertyFromHeader2: CInt // OK, provides an implementation with a stored property var propertyFromHeader3: CInt { // FIXME: OK, provides an implementation with a computed property // expected-error@-2 {{property 'propertyFromHeader3' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} get { return 1 } set {} } @objc var propertyFromHeader4: CInt { // OK, provides an implementation with a computed property get { return 1 } set {} } @objc let propertyFromHeader5: CInt // FIXME: bad, needs to be settable @objc var propertyFromHeader6: CInt { // FIXME: bad, needs a setter get { return 1 } } final var propertyFromHeader8: CInt // FIXME: Should complain about final not fulfilling the @objc requirement var readonlyPropertyFromHeader1: CInt // FIXME: OK, provides an implementation with a stored property that's nonpublicly settable // expected-error@-2 {{property 'readonlyPropertyFromHeader1' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} @objc var readonlyPropertyFromHeader2: CInt // OK, provides an implementation with a stored property that's nonpublicly settable var readonlyPropertyFromHeader3: CInt { // FIXME: OK, provides an implementation with a computed property // expected-error@-2 {{property 'readonlyPropertyFromHeader3' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} get { return 1 } set {} } @objc var readonlyPropertyFromHeader4: CInt { // OK, provides an implementation with a computed property get { return 1 } set {} } @objc let readonlyPropertyFromHeader5: CInt // OK, provides an implementation with a stored read-only property @objc var readonlyPropertyFromHeader6: CInt { // OK, provides an implementation with a computed read-only property get { return 1 } } var propertyNotFromHeader1: CInt // expected-error@-1 {{property 'propertyNotFromHeader1' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-2 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-3 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} @objc var propertyNotFromHeader2: CInt // OK, provides a nonpublic but ObjC-compatible stored property @objc var propertyNotFromHeader3: CInt { // OK, provides a nonpublic but ObjC-compatible computed property get { return 1 } set {} } final var propertyNotFromHeader4: CInt // OK, provides a Swift-only stored property @objc final var propertyNotFromHeader5: CInt // OK, @objc final is weird but supported, not a member impl override open func superclassMethod(_: CInt) { // OK } override open var superclassProperty: CInt { get { // OK } set { // OK } } override public init(fromSuperclass _: CInt) { // OK } } // FIXME: Should complain about categoryMethodFromHeader4: @_objcImplementation(PresentAdditions) extension ObjCClass { // expected-note@-1 {{previously implemented by extension here}} func method(fromHeader3: CInt) { // FIXME: Should complain about wrong category // expected-error@-2 {{instance method 'method(fromHeader3:)' does not match any instance method declared in the headers for 'ObjCClass'; did you use the instance method's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible instance method not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift instance method that cannot be overridden}} {{3-3=final }} } var propertyFromHeader7: CInt { // FIXME: Should complain about wrong category // expected-error@-2 {{property 'propertyFromHeader7' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} get { return 1 } } func categoryMethod(fromHeader1: CInt) { // FIXME: OK, provides an implementation for the header's method. // expected-error@-2 {{instance method 'categoryMethod(fromHeader1:)' does not match any instance method declared in the headers for 'ObjCClass'; did you use the instance method's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible instance method not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift instance method that cannot be overridden}} {{3-3=final }} } @objc func categoryMethod(fromHeader2: CInt) { // OK, provides an implementation for the header's method. } @objc fileprivate func categoryMethodNot(fromHeader1: CInt) { // OK, declares a new @objc dynamic method. } final func categoryMethodNot(fromHeader2: CInt) { // OK, declares a new Swift method. } func categoryMethodNot(fromHeader3: CInt) { // expected-error@-1 {{instance method 'categoryMethodNot(fromHeader3:)' does not match any instance method declared in the headers for 'ObjCClass'; did you use the instance method's Swift name?}} // expected-note@-2 {{add '@objc' to define an Objective-C-compatible instance method not declared in the header}} {{3-3=@objc }} // expected-note@-3 {{add 'final' to define a Swift instance method that cannot be overridden}} {{3-3=final }} } var categoryPropertyFromHeader1: CInt // expected-error@-1 {{extensions must not contain stored properties}} // FIXME: expected-error@-2 {{property 'categoryPropertyFromHeader1' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // FIXME: expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // FIXME: expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} @objc var categoryPropertyFromHeader2: CInt // expected-error@-1 {{extensions must not contain stored properties}} var categoryPropertyFromHeader3: CInt { // FIXME: OK, provides an implementation with a computed property // expected-error@-2 {{property 'categoryPropertyFromHeader3' does not match any property declared in the headers for 'ObjCClass'; did you use the property's Swift name?}} // expected-note@-3 {{add '@objc' to define an Objective-C-compatible property not declared in the header}} {{3-3=@objc }} // expected-note@-4 {{add 'final' to define a Swift property that cannot be overridden}} {{3-3=final }} get { return 1 } set {} } @objc var categoryPropertyFromHeader4: CInt { // OK, provides an implementation with a computed property get { return 1 } set {} } } @_objcImplementation extension ObjCClass {} // expected-error@-1 {{duplicate implementation of Objective-C class 'ObjCClass'}} @_objcImplementation(PresentAdditions) extension ObjCClass {} // expected-error@-1 {{duplicate implementation of Objective-C category 'PresentAdditions' on class 'ObjCClass'}} @_objcImplementation(MissingAdditions) extension ObjCClass {} // expected-error@-1 {{could not find category 'MissingAdditions' on Objective-C class 'ObjCClass'; make sure your umbrella or bridging header imports the header that declares it}} // expected-note@-2 {{remove arguments to implement the main '@interface' for this class}} {{21-39=}} @_objcImplementation extension ObjCStruct {} // expected-error@-1 {{cannot mark extension of struct 'ObjCStruct' with '@_objcImplementation'; it is not an imported Objective-C class}} {{1-22=}} @_objcImplementation(CantWork) extension ObjCStruct {} // expected-error@-1 {{cannot mark extension of struct 'ObjCStruct' with '@_objcImplementation'; it is not an imported Objective-C class}} {{1-32=}} @objc class SwiftClass {} // expected-note@-1 2 {{'SwiftClass' declared here}} @_objcImplementation extension SwiftClass {} // expected-error@-1 {{'@_objcImplementation' cannot be used to extend class 'SwiftClass' because it was defined by a Swift 'class' declaration, not an imported Objective-C '@interface' declaration}} {{1-22=}} @_objcImplementation(WTF) extension SwiftClass {} // expected // expected-error@-1 {{'@_objcImplementation' cannot be used to extend class 'SwiftClass' because it was defined by a Swift 'class' declaration, not an imported Objective-C '@interface' declaration}} {{1-27=}} func usesAreNotAmbiguous(obj: ObjCClass) { obj.method(fromHeader1: 1) obj.method(fromHeader2: 2) obj.method(fromHeader3: 3) obj.method(fromHeader4: 4) obj.methodNot(fromHeader1: 1) obj.methodNot(fromHeader2: 2) obj.categoryMethod(fromHeader1: 1) obj.categoryMethod(fromHeader2: 2) obj.categoryMethod(fromHeader3: 3) obj.categoryMethod(fromHeader4: 4) obj.categoryMethodNot(fromHeader1: 1) obj.categoryMethodNot(fromHeader2: 2) }
apache-2.0
77be535160d0f9a5448e15932d7b58c8
48.647059
209
0.717694
4.11039
false
false
false
false
thii/FontAwesome.swift
Sources/FontAwesome/FontAwesome.swift
1
11878
// FontAwesome.swift // // Copyright (c) 2014-present FontAwesome.swift contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreText // MARK: - Public /// A configuration namespace for FontAwesome. public struct FontAwesomeConfig { // Marked private to prevent initialization of this struct. private init() { } /// Taken from FontAwesome.io's Fixed Width Icon CSS. public static let fontAspectRatio: CGFloat = 1.28571429 /// Whether Font Awesome Pro fonts should be used (not included). /// /// To use Font Awesome Pro fonts, you should add these to your main project and /// make sure they are added to the target and are included in the Info.plist file. public static var usesProFonts: Bool = false } public enum FontAwesomeStyle: String { case solid /// WARNING: Font Awesome Free doesn't include a Light variant. Using this with Free will fallback to Regular. case light case regular case brands func fontName() -> String { switch self { case .solid: return FontAwesomeConfig.usesProFonts ? "FontAwesome5Pro-Solid" : "FontAwesome5Free-Solid" case .light: return FontAwesomeConfig.usesProFonts ? "FontAwesome5Pro-Light" : "FontAwesome5Free-Regular" case .regular: return FontAwesomeConfig.usesProFonts ? "FontAwesome5Pro-Regular" : "FontAwesome5Free-Regular" case .brands: return "FontAwesome5Brands-Regular" } } func fontFilename() -> String { switch self { case .solid: return FontAwesomeConfig.usesProFonts ? "Font Awesome 5 Pro-Solid-900" : "Font Awesome 5 Free-Solid-900" case .light: return FontAwesomeConfig.usesProFonts ? "Font Awesome 5 Pro-Light-300" : "Font Awesome 5 Free-Regular-400" case .regular: return FontAwesomeConfig.usesProFonts ? "Font Awesome 5 Pro-Regular-400" : "Font Awesome 5 Free-Regular-400" case .brands: return "Font Awesome 5 Brands-Regular-400" } } func fontFamilyName() -> String { switch self { case .brands: return "Font Awesome 5 Brands" case .regular, .light, .solid: return FontAwesomeConfig.usesProFonts ? "Font Awesome 5 Pro" : "Font Awesome 5 Free" } } } /// A FontAwesome extension to UIFont. public extension UIFont { /// Get a UIFont object of FontAwesome. /// /// - parameter ofSize: The preferred font size. /// - returns: A UIFont object of FontAwesome. class func fontAwesome(ofSize fontSize: CGFloat, style: FontAwesomeStyle) -> UIFont { loadFontAwesome(ofStyle: style) return UIFont(name: style.fontName(), size: fontSize)! } /// Loads the FontAwesome font in to memory. /// This method should be called when setting icons without using code. class func loadFontAwesome(ofStyle style: FontAwesomeStyle) { if UIFont.fontNames(forFamilyName: style.fontFamilyName()).contains(style.fontName()) { return } FontLoader.loadFont(style.fontFilename()) } /// Get a UIFont object of FontAwesome for a given text style /// /// - parameter forTextStyle: The preferred text style /// - parameter style: FontAwesome font style /// - returns: A UIFont object of FontAwesome class func fontAwesome(forTextStyle textStyle: UIFont.TextStyle, style: FontAwesomeStyle) -> UIFont { let userFont = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle) let pointSize = userFont.pointSize loadFontAwesome(ofStyle: style) let awesomeFont = UIFont(name: style.fontName(), size: pointSize)! if #available(iOS 11.0, *), #available(watchOSApplicationExtension 4.0, *), #available(tvOS 11.0, *) { return UIFontMetrics.default.scaledFont(for: awesomeFont) } else { let scale = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).pointSize / 17 return awesomeFont.withSize(scale * awesomeFont.pointSize) } } } /// A FontAwesome extension to String. public extension String { /// Get a FontAwesome icon string with the given icon name. /// /// - parameter name: The preferred icon name. /// - returns: A string that will appear as icon with FontAwesome. static func fontAwesomeIcon(name: FontAwesome) -> String { let toIndex = name.unicode.index(name.unicode.startIndex, offsetBy: 1) return String(name.unicode[name.unicode.startIndex..<toIndex]) } /// Get a FontAwesome icon string with the given CSS icon code. Icon code can be found here: http://fontawesome.io/icons/ /// /// - parameter code: The preferred icon name. /// - returns: A string that will appear as icon with FontAwesome. static func fontAwesomeIcon(code: String) -> String? { guard let name = self.fontAwesome(code: code) else { return nil } return self.fontAwesomeIcon(name: name) } /// Get a FontAwesome icon with the given CSS icon code. Icon code can be found here: http://fontawesome.io/icons/ /// /// - parameter code: The preferred icon name. /// - returns: An internal corresponding FontAwesome code. static func fontAwesome(code: String) -> FontAwesome? { return FontAwesome(rawValue: code) } } /// A FontAwesome extension to UIImage. public extension UIImage { /// Get a FontAwesome image with the given icon name, text color, size and an optional background color. /// /// - parameter name: The preferred icon name. /// - parameter style: The font style. Either .solid, .regular or .brands. /// - parameter textColor: The text color. /// - parameter size: The image size. /// - parameter backgroundColor: The background color (optional). /// - returns: A string that will appear as icon with FontAwesome static func fontAwesomeIcon(name: FontAwesome, style: FontAwesomeStyle, textColor: UIColor, size: CGSize, backgroundColor: UIColor = UIColor.clear, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.clear) -> UIImage { // Prevent application crash when passing size where width or height is set equal to or less than zero, by clipping width and height to a minimum of 1 pixel. var size = size if size.width <= 0 { size.width = 1 } if size.height <= 0 { size.height = 1 } let paragraph = NSMutableParagraphStyle() paragraph.alignment = NSTextAlignment.center let fontSize = min(size.width / FontAwesomeConfig.fontAspectRatio, size.height) // stroke width expects a whole number percentage of the font size let strokeWidth: CGFloat = fontSize == 0 ? 0 : (-100 * borderWidth / fontSize) let attributedString = NSAttributedString(string: String.fontAwesomeIcon(name: name), attributes: [ NSAttributedString.Key.font: UIFont.fontAwesome(ofSize: fontSize, style: style), NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: backgroundColor, NSAttributedString.Key.paragraphStyle: paragraph, NSAttributedString.Key.strokeWidth: strokeWidth, NSAttributedString.Key.strokeColor: borderColor ]) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) attributedString.draw(in: CGRect(x: 0, y: (size.height - fontSize) / 2, width: size.width, height: fontSize)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } /// Get a FontAwesome image with the given icon css code, text color, size and an optional background color. /// /// - parameter code: The preferred icon css code. /// - parameter style: The font style. Either .solid, .regular or .brands. /// - parameter textColor: The text color. /// - parameter size: The image size. /// - parameter backgroundColor: The background color (optional). /// - returns: A string that will appear as icon with FontAwesome static func fontAwesomeIcon(code: String, style: FontAwesomeStyle, textColor: UIColor, size: CGSize, backgroundColor: UIColor = UIColor.clear, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.clear) -> UIImage? { guard let name = String.fontAwesome(code: code) else { return nil } return fontAwesomeIcon(name: name, style: style, textColor: textColor, size: size, backgroundColor: backgroundColor, borderWidth: borderWidth, borderColor: borderColor) } } // FontAwesome internal helpers public extension FontAwesome { /// Indicator to check whether a style is supported for the font /// /// - Parameter style: The font style. Either .solid, .regular or .brands. /// - returns: A boolean which is true if the style is supported by the font func isSupported(style: FontAwesomeStyle) -> Bool { return self.supportedStyles.contains(style) } /// List all fonts supported in a style /// /// - Parameter style: The font style. Either .solid, .regular or .brands. /// - returns: An array of FontAwesome static func fontList(style: FontAwesomeStyle) -> [FontAwesome] { return FontAwesome.allCases.filter({ $0.isSupported(style: style) }) } } // MARK: - Private private class FontLoader { class func loadFont(_ name: String) { guard let fontURL = URL.fontURL(for: name) as CFURL? else { return } var error: Unmanaged<CFError>? if !CTFontManagerRegisterFontsForURL(fontURL, .process, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) guard let nsError = error?.takeUnretainedValue() as AnyObject as? NSError else { return } NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } } extension URL { static func fontURL(for fontName: String) -> URL? { #if SWIFT_PACKAGE if let fontURL = Bundle.module.url(forResource: fontName, withExtension: "otf") { return fontURL } #endif let bundle = Bundle(for: FontLoader.self) if let fontURL = bundle.url(forResource: fontName, withExtension: "otf") { return fontURL } // If this framework is added using CocoaPods, resources is placed under a subdirectory if let fontURL = bundle.url(forResource: fontName, withExtension: "otf", subdirectory: "FontAwesome.swift.bundle") { return fontURL } return nil } }
mit
7ca78c840bbce41338457a1361de69b0
41.120567
228
0.67705
4.713492
false
false
false
false
xuanyi0627/jetstream-ios
JetstreamTests/ConstraintTests.swift
1
9772
// // ConstraintTests.swift // Jetstream // // Copyright (c) 2014 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import XCTest import Jetstream class ConstraintTests: XCTestCase { func testMultipleMatching() { var json: [[String: AnyObject]] = [ [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly"] ], [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "AnotherTestModel", "properties": ["anotherString": "set correctly"] ], [ "type": "change", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["integer": 3] ] ] var fragments = json.map { SyncFragment.unserialize($0)! } var constraints1: [String: AnyObject] = [ "string": "set correctly" ] var constraints2: [String: AnyObject] = [ "anotherString": "set correctly" ] var constraints3: [String: AnyObject] = [ "integer": 3 ] var constraints = [ Constraint(type: .Add, clsName: "TestModel", properties: constraints1, allowAdditionalProperties: false), Constraint(type: .Add, clsName: "AnotherTestModel", properties: constraints2, allowAdditionalProperties: false), Constraint(type: .Change, clsName: "TestModel", properties: constraints3, allowAdditionalProperties: false), ] XCTAssertTrue(Constraint.matchesAllConstraints(constraints, syncFragments: fragments), "Constraint should match fragment") } func testSimpleValueExistsChangeMatching() { var json: [String: AnyObject] = [ "type": "change", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set new value", "integer": NSNull(), "childModel":"11111-11111-11111-11111-1111"] ] var fragment = SyncFragment.unserialize(json) let constraint = Constraint(type: .Change, clsName: "TestModel", properties: [ "string": HasNewValuePropertyConstraint(), "integer": HasNewValuePropertyConstraint(), "childModel": HasNewValuePropertyConstraint() ]) XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleAddMatching() { var json: [String: AnyObject] = [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly"] ] var fragment = SyncFragment.unserialize(json) let constraint = Constraint(type: .Add, clsName: "TestModel") XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleAddWithPropertiesMatching() { var json: [String: AnyObject] = [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly"] ] var fragment = SyncFragment.unserialize(json) let constraint = Constraint(type: .Add, clsName: "TestModel", properties: ["string": "set correctly"], allowAdditionalProperties: false) XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleAddWithPropertiesMatchingWithBadAdditionalProperties() { var json: [String: AnyObject] = [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "integer": 3] ] var fragment = SyncFragment.unserialize(json) let constraint = Constraint(type: .Add, clsName: "TestModel", properties: ["string": "set correctly"], allowAdditionalProperties: false) XCTAssertFalse(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleAddWithPropertiesMatchingWithAllowedAdditionalProperties() { var json: [String: AnyObject] = [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "integer": 3] ] var fragment = SyncFragment.unserialize(json) let constraint = Constraint(type: .Add, clsName: "TestModel", properties: ["string": "set correctly"], allowAdditionalProperties: true) XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleAddWithArrayInsertPropertyMatching() { var json: [String: AnyObject] = [ "type": "add", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "array": [NSUUID().UUIDString]] ] var fragment = SyncFragment.unserialize(json) let constraint = Constraint(type: .Add, clsName: "TestModel", properties: [ "string": "set correctly", "array": ArrayPropertyConstraint(type: .Insert) ], allowAdditionalProperties: false) XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleChangeWithArrayInsertPropertyMatching() { var json: [String: AnyObject] = [ "type": "change", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "array": [NSUUID().UUIDString]] ] var fragment = SyncFragment.unserialize(json) fragment!.originalProperties = [ "array": [] ] let constraint = Constraint(type: .Change, clsName: "TestModel", properties: [ "string": "set correctly", "array": ArrayPropertyConstraint(type: .Insert) ], allowAdditionalProperties: false) XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleChangeWithArrayInsertPropertyNotMatching() { var json: [String: AnyObject] = [ "type": "change", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "array": [NSUUID().UUIDString]] ] var fragment = SyncFragment.unserialize(json) fragment!.originalProperties = [ "array": [NSUUID().UUIDString] ] let constraint = Constraint(type: .Change, clsName: "TestModel", properties: [ "string": "set correctly", "array": ArrayPropertyConstraint(type: .Insert) ], allowAdditionalProperties: false) XCTAssertFalse(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleChangeWithArrayRemovePropertyMatching() { var json: [String: AnyObject] = [ "type": "change", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "array": []] ] var fragment = SyncFragment.unserialize(json) fragment!.originalProperties = [ "array": [NSUUID().UUIDString] ] let constraint = Constraint(type: .Change, clsName: "TestModel", properties: [ "string": "set correctly", "array": ArrayPropertyConstraint(type: .Remove) ], allowAdditionalProperties: false) XCTAssertTrue(constraint.matches(fragment!), "Constraint should match fragment") } func testSimpleChangeWithArrayRemovePropertyNotMatching() { var json: [String: AnyObject] = [ "type": "change", "uuid": NSUUID().UUIDString, "clsName": "TestModel", "properties": ["string": "set correctly", "array": [NSUUID().UUIDString]] ] var fragment = SyncFragment.unserialize(json) fragment!.originalProperties = [ "array": [NSUUID().UUIDString] ] let constraint = Constraint(type: .Change, clsName: "TestModel", properties: [ "string": "set correctly", "array": ArrayPropertyConstraint(type: .Remove) ], allowAdditionalProperties: false) XCTAssertFalse(constraint.matches(fragment!), "Constraint should match fragment") } }
mit
5e285cfd34fcc81d458a3d595cf31380
40.582979
144
0.601003
4.980632
false
true
false
false
SuPair/firefox-ios
Storage/FileAccessor.swift
18
4800
/* 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 /** * A convenience class for file operations under a given root directory. * Note that while this class is intended to be used to operate only on files * under the root, this is not strictly enforced: clients can go outside * the path using ".." or symlinks. */ open class FileAccessor { open let rootPath: String public init(rootPath: String) { self.rootPath = rootPath } /** * Gets the absolute directory path at the given relative path, creating it if it does not exist. */ open func getAndEnsureDirectory(_ relativeDir: String? = nil) throws -> String { var absolutePath = rootPath if let relativeDir = relativeDir { absolutePath = URL(fileURLWithPath: absolutePath).appendingPathComponent(relativeDir).path } try createDir(absolutePath) return absolutePath } /** * Removes the file or directory at the given path, relative to the root. */ open func remove(_ relativePath: String) throws { let path = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path try FileManager.default.removeItem(atPath: path) } /** * Removes the contents of the directory without removing the directory itself. */ open func removeFilesInDirectory(_ relativePath: String = "") throws { let fileManager = FileManager.default let path = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path let files = try fileManager.contentsOfDirectory(atPath: path) for file in files { try remove(URL(fileURLWithPath: relativePath).appendingPathComponent(file).path) } return } /** * Determines whether a file exists at the given path, relative to the root. */ open func exists(_ relativePath: String) -> Bool { let path = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path return FileManager.default.fileExists(atPath: path) } open func attributesForFileAt(relativePath: String) throws -> [FileAttributeKey: Any] { return try FileManager.default.attributesOfItem(atPath: URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path) } /** * Moves the file or directory to the given destination, with both paths relative to the root. * The destination directory is created if it does not exist. */ open func move(_ fromRelativePath: String, toRelativePath: String) throws { let rootPathURL = URL(fileURLWithPath: rootPath) let fromPath = rootPathURL.appendingPathComponent(fromRelativePath).path let toPath = rootPathURL.appendingPathComponent(toRelativePath) let toDir = toPath.deletingLastPathComponent() let toDirPath = toDir.path try createDir(toDirPath) try FileManager.default.moveItem(atPath: fromPath, toPath: toPath.path) } open func copyMatching(fromRelativeDirectory relativePath: String, toAbsoluteDirectory absolutePath: String, matching: (String) -> Bool) throws { let fileManager = FileManager.default let pathURL = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath) let path = pathURL.path let destURL = URL(fileURLWithPath: absolutePath, isDirectory: true) let files = try fileManager.contentsOfDirectory(atPath: path) for file in files { if !matching(file) { continue } let from = pathURL.appendingPathComponent(file, isDirectory: false).path let to = destURL.appendingPathComponent(file, isDirectory: false).path do { try fileManager.copyItem(atPath: from, toPath: to) } catch { } } } open func copy(_ fromRelativePath: String, toAbsolutePath: String) throws -> Bool { let fromPath = URL(fileURLWithPath: rootPath).appendingPathComponent(fromRelativePath).path let dest = URL(fileURLWithPath: toAbsolutePath).deletingLastPathComponent().path try createDir(dest) try FileManager.default.copyItem(atPath: fromPath, toPath: toAbsolutePath) return true } /** * Creates a directory with the given path, including any intermediate directories. * Does nothing if the directory already exists. */ fileprivate func createDir(_ absolutePath: String) throws { try FileManager.default.createDirectory(atPath: absolutePath, withIntermediateDirectories: true, attributes: nil) } }
mpl-2.0
2348a2deb81fdff48eb9d0d86441f2cc
40.025641
149
0.686042
5.122732
false
false
false
false
ReiVerdugo/uikit-fundamentals
step6.4-bondVillains-flowLayoutTemplate/BondVillains/VillainCollectionViewController.swift
1
2159
// // VillainCollectionViewController.swift // BondVillains // // Created by Gabrielle Miller-Messner on 2/3/15. // Copyright (c) 2015 Udacity. All rights reserved. // import Foundation import UIKit // MARK: - VillainCollectionViewController: UICollectionViewController class VillainCollectionViewController: UICollectionViewController { // MARK: Properties // TODO: Add outlet to flowLayout here. // Get ahold of some villains, for the table // This is an array of Villain instances let allVillains = Villain.allVillains // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() //TODO: Implement flowLayout here. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.hidden = false } // MARK: Collection View Data Source override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.allVillains.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("VillainCollectionViewCell", forIndexPath: indexPath) as! VillainCollectionViewCell let villain = self.allVillains[indexPath.row] // Set the name and image cell.nameLabel.text = villain.name cell.villainImageView?.image = UIImage(named: villain.imageName) //cell.schemeLabel.text = "Scheme: \(villain.evilScheme)" return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath:NSIndexPath) { let detailController = self.storyboard!.instantiateViewControllerWithIdentifier("VillainDetailViewController") as! VillainDetailViewController detailController.villain = self.allVillains[indexPath.row] self.navigationController!.pushViewController(detailController, animated: true) } }
mit
54b500ccaf12afdfed4af2ffb7d0a55c
33.269841
156
0.705882
5.681579
false
false
false
false
lukesutton/uut
Sources/PropertyValues.swift
1
3166
public struct PropertyValues { private init() {} public enum Color: PropertyValue { case Value(Values.Color) case Initial case Inherit case Black case White case Red case Blue case Green public var stringValue: String { switch self { case let Value(x): return x.stringValue default: return String(self).lowercaseString } } } public enum URL: PropertyValue { case None case URL(String) case Initial case Inherit public var stringValue: String { switch self { case let .URL(s): return s default: return String(self).lowercaseString } } } public enum Reset: String { case Initial = "initial" case Inherit = "inherit" var stringValue: String { return rawValue } } public enum Box: String, PropertyValue { case BorderBox = "border-box" case PaddingBox = "padding-box" case ContentBox = "content-box" case Initial = "initial" case Inherit = "inherit" public var stringValue: String { return rawValue } } public enum Opacity: PropertyValue { case Value(Double) case Initial case Inherit public var stringValue: String { switch self { case let .Value(value): return String(value) default: return String(self).lowercaseString } } } public enum Shadow: PropertyValue { case None case Initial case Inherit case Inset case Shadow(Measurement, Measurement, Double?, Double?, Values.Color?) public var stringValue: String { switch self { case let .Shadow(h, v, blur, spread, color): let output = [ h.stringValue, v.stringValue, blur != nil ? String(blur) : "", spread != nil ? String(spread) : "", color != nil ? color!.stringValue : "" ].filter {!$0.isEmpty} return output.joinWithSeparator(" ") default: return String(self).lowercaseString } } } public struct ShadowCollection: PropertyValue { public let shadows: [Shadow] init(_ shadows: [Shadow]) { self.shadows = shadows } public var stringValue: String { return shadows.map {$0.stringValue}.joinWithSeparator(", ") } } public enum Number: PropertyValue { case Value(Int) case Initial case Inherit public var stringValue: String { switch self { case let .Value(x): return String(x) default: return String(self).lowercaseString } } } public enum NumberWithAuto: PropertyValue { case Value(Int) case Auto case Initial case Inherit public var stringValue: String { switch self { case let .Value(x): return String(x) default: return String(self).lowercaseString } } } public enum NumberWithNone: PropertyValue { case Value(Int) case None case Initial case Inherit public var stringValue: String { switch self { case let .Value(x): return String(x) default: return String(self).lowercaseString } } } }
mit
99baf75661e6fa080f4c870ff8b6802b
20.537415
74
0.604548
4.568543
false
false
false
false
Vespen/SimpleJson
Sources/Features/Json+Number.swift
1
5169
// // Json+Number.swift // // Copyright (c) 2017 Anton Lagutin // // 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 /// `NSNumber` based methods. public extension Json { /// Returns the `NSNumber` value. /// /// - Throws: `JsonError`. /// - Returns: `NSNumber`. public func asNumber() throws -> NSNumber { guard let number = root as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath, NSNumber.self) } return number } /// Returns the `Int` value. /// /// - Throws: `JsonError`. /// - Returns: `Int`. public func asInt() throws -> Int { guard let number = root as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath, Int.self) } return number.intValue } /// Returns the `Float` value. /// /// - Throws: `JsonError`. /// - Returns: `Float`. public func asFloat() throws -> Float { guard let number = root as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath, Float.self) } return number.floatValue } /// Returns the `Double` value. /// /// - Throws: `JsonError`. /// - Returns: `Double`. public func asDouble() throws -> Double { guard let number = root as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath, Double.self) } return number.doubleValue } /// Returns the `Bool` value. /// /// - Throws: `JsonError`. /// - Returns: `Bool`. public func asBool() throws -> Bool { guard let number = root as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath, Bool.self) } return number.boolValue } /// Returns the `NSNumber` value identified by a given path. /// /// - Parameter path: Path. /// - Throws: `JsonError`. /// - Returns: The `NSNumber` value identified by `path`. public func number(at path: JsonPath) throws -> NSNumber { guard let number = try self.value(at: path) as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath.appending(path), NSNumber.self) } return number } /// Returns the `Int` value identified by a given path. /// /// - Parameter path: Path. /// - Throws: `JsonError`. /// - Returns: The `Int` value identified by `path`. public func int(at path: JsonPath) throws -> Int { guard let number = try self.value(at: path) as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath.appending(path), Int.self) } return number.intValue } /// Returns the `Float` value identified by a given path. /// /// - Parameter path: Path. /// - Throws: `JsonError`. /// - Returns: The `Float` value identified by `path`. public func float(at path: JsonPath) throws -> Float { guard let number = try self.value(at: path) as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath.appending(path), Float.self) } return number.floatValue } /// Returns the `Double` value identified by a given path. /// /// - Parameter path: Path. /// - Throws: `JsonError`. /// - Returns: The `Double` value identified by `path`. public func double(at path: JsonPath) throws -> Double { guard let number = try self.value(at: path) as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath.appending(path), Double.self) } return number.doubleValue } /// Returns the `Bool` value identified by a given path. /// /// - Parameter path: Path. /// - Throws: `JsonError`. /// - Returns: The `Bool` value identified by `path`. public func bool(at path: JsonPath) throws -> Bool { guard let number = try self.value(at: path) as? NSNumber else { throw JsonError.componentTypeMismatch(absolutePath.appending(path), Bool.self) } return number.boolValue } }
mit
da8c6f857c714ff7062d418bafe3bc75
32.564935
94
0.631457
4.362025
false
false
false
false
nomothetis/CookieWars
Cookie Wars/Cookie Wars/StatusViewController.swift
1
2634
// // StatusViewController.swift // Canvas // // Created by Salazar, Alexandros on 6/18/14. // Copyright (c) 2014 nomothetis. All rights reserved. // import UIKit class StatusViewController: UIViewController { @IBOutlet var targetLabel: UILabel @IBOutlet var currentLabel: UILabel @IBOutlet var titleLabel: UILabel @IBOutlet var neededCommitmentsBar: UIView @IBOutlet var commitmentsBar: UIView @IBOutlet var barGraphConstraint: NSLayoutConstraint var statusModel:StatusViewModel = StatusViewModel(state:AppState.LoggedOut) override func viewDidLoad() { super.viewDidLoad() self.barGraphConstraint.constant = self.neededCommitmentsBar.frame.size.width * self.statusModel.barFraction self.neededCommitmentsBar.backgroundColor = self.statusModel.targetBarColor self.targetLabel.text = self.statusModel.targetLabelText self.targetLabel.alpha = self.statusModel.targetLabelAlpha self.currentLabel.text = self.statusModel.currentLabelText self.currentLabel.alpha = self.statusModel.currentLabelAlpha } @IBAction func toggleLoginState(button:UIButton) { switch self.statusModel.state { case .LoggedOut: self.statusModel = self.statusModel.login() button.selected = true case .LoggedIn: self.statusModel = self.statusModel.logout() button.selected = false } UIView.animateWithDuration(0.25, animations: { self.titleLabel.alpha = 0 }, completion: { done in UIView.animateWithDuration(0.25, animations: { self.titleLabel.alpha = 1 self.titleLabel.text = self.statusModel.titleLabelText }, completion: { done in self.barGraphConstraint.constant = self.statusModel.barFraction * self.neededCommitmentsBar.frame.size.width UIView.animateWithDuration(0.5) { self.neededCommitmentsBar.backgroundColor = self.statusModel.targetBarColor self.targetLabel.text = self.statusModel.targetLabelText self.targetLabel.alpha = self.statusModel.targetLabelAlpha self.currentLabel.text = self.statusModel.currentLabelText self.currentLabel.alpha = self.statusModel.currentLabelAlpha self.view.layoutIfNeeded() } }) }) } }
bsd-2-clause
5d9a9dc5ae503e49a77456a43f53e8d1
40.15625
132
0.623007
5.195266
false
false
false
false