repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hooliooo/Astral
refs/heads/master
Sources/Astral/HTTPMethod.swift
mit
1
// // Astral // Copyright (c) Julio Miguel Alorro // Licensed under the MIT license. See LICENSE file // /** An enum that represents http methods */ public enum HTTPMethod { /** - http GET method */ case get /** - http DELETE method */ case delete /** - http POST method */ case post /** - http PUT method */ case put /** - http PATCH method */ case patch /** - other http method */ case method(String) // MARK: Initializer /** Initializer for creating an instance of HTTPMethod - parameter method: The stringValue of the HTTPMethod to be created */ public init(_ method: String) { switch method { case "GET": self = HTTPMethod.get case "DELETE": self = HTTPMethod.delete case "POST": self = HTTPMethod.post case "PUT": self = HTTPMethod.put case "PATCH": self = HTTPMethod.patch default: self = HTTPMethod.method(method) } } /** String representation of the HTTPMethod */ public var stringValue: String { switch self { case .get: return "GET" case .delete: return "DELETE" case .post: return "POST" case .put: return "PUT" case .patch: return "PATCH" case .method(let method): return method } } } // MARK: Hashable Protocol extension HTTPMethod: Hashable { public static func == (lhs: HTTPMethod, rhs: HTTPMethod) -> Bool { switch (lhs, rhs) { case (.get, .get): return true case (.delete, .delete): return true case (.post, .post): return true case (.put, .put): return true case (.patch, .patch): return true case let (.method(lhsMethod), .method(rhsMethod)): return lhsMethod == rhsMethod default: return false } } public func hash(into hasher: inout Hasher) { switch self { case .get: hasher.combine(1337) case .delete: hasher.combine(1338) case .post: hasher.combine(1339) case .put: hasher.combine(1340) case .patch: hasher.combine(1341) case .method(let method): hasher.combine(1342 &+ method.hashValue) } } } extension HTTPMethod: CustomStringConvertible { public var description: String { return self.stringValue } } extension HTTPMethod: CustomDebugStringConvertible { public var debugDescription: String { return self.description } }
cba2f2a9c08f253ec637425d87c89c57
19.573913
86
0.625528
false
false
false
false
superpixelhq/AbairLeat-iOS
refs/heads/master
Abair Leat/Table Cells/OneToOneTableViewCell.swift
apache-2.0
1
// // OneToOneTableViewCell.swift // Abair Leat // // Created by Aaron Signorelli on 30/11/2015. // Copyright © 2015 Superpixel. All rights reserved. // import UIKit import Firebase class OneToOneTableViewCell: UITableViewCell, ChatsListTableViewControllerCell { @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var otherPersonsName: UILabel! @IBOutlet weak var lastChatMessage: UILabel! @IBOutlet weak var dateLastMessageSent: UILabel! override func awakeFromNib() { self.contentView.backgroundColor = UIColor.clearColor() self.contentView.opaque = false self.contentView.superview?.backgroundColor = UIColor.clearColor() self.contentView.superview?.opaque = false } func setup(conversation: ConversationMetadata) { let me = AbairLeat.shared.profile.me! let theirIndex = conversation.participants.indexOf({$0.1.id != me.id})! let them = conversation.participants[theirIndex].1 self.avatar.hnk_setImageFromURL(NSURL(string: them.avatarUrlString)!) self.otherPersonsName.text = them.name self.lastChatMessage.text = conversation.lastMessageSent if let sentDate = conversation.dateLastMessageSent { self.dateLastMessageSent.text = sentDate.occuredToday() ? sentDate.toShortTimeStyle() : sentDate.toShortDateStyle() } else { self.dateLastMessageSent.text = "" } } }
12ac012bf20edb849cb3fd68f1e0742f
34.902439
127
0.690897
false
false
false
false
royhsu/tiny-core
refs/heads/master
Sources/Core/Array+InsertBetween.swift
mit
1
// // Array+InsertBetween.swift // TinyCore // // Created by Roy Hsu on 2018/4/5. // Copyright © 2018 TinyWorld. All rights reserved. // // MARK: - Insert Between extension Array { /// You can specify the between to return nil for skipping the certain insertions. /// /// For example: /// /// let output = [ 1.0, 2.0, 3.0 ].insert { previous, next in /// /// Only insert values if the previous is greater than or equal to 2.0 /// if previous >= 2.0 { return nil } /// /// return (previous + next) / 2.0 /// /// } /// /// The output is: [ 1.0, 1.5, 2.0, 3.0 ] /// public func inserted( between: (_ previous: Element, _ next: Element) -> Element? ) -> [Element] { return reduce([]) { currentResult, next in var nextResult = currentResult guard let previous = currentResult.last, let between = between(previous, next) else { nextResult.append(next); return nextResult } nextResult.append(contentsOf: [ between, next ]) return nextResult } } public mutating func insert( between: (_ previous: Element, _ next: Element) -> Element? ) { self = inserted(between: between) } }
6a03cf4ed489294093e577f53c1b26ff
23.166667
86
0.547126
false
false
false
false
dokun1/jordan-meme-ios
refs/heads/master
JordanHeadMeme/JordanHeadMeme/AppDelegate.swift
mit
1
// // AppDelegate.swift // JordanHeadMeme // // Created by David Okun on 12/18/15. // Copyright © 2015 David Okun, LLC. All rights reserved. // import UIKit import SVProgressHUD import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? @available(iOS 9.0, *) lazy var shortcutItem: UIApplicationShortcutItem? = { return nil }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. SVProgressHUD.setBackgroundColor(UIColor.colorSchemeTwo()) SVProgressHUD.setForegroundColor(UIColor.colorSchemeOne()) application.statusBarHidden = true var performShortcutDelegate = true if #available(iOS 9.0, *) { if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem { self.shortcutItem = shortcutItem performShortcutDelegate = false } } if UIApplication.sharedApplication().isDebugMode { print("APP LOADED IN DEBUG MODE") } else { Fabric.with([Answers.self, Crashlytics.self]) } return performShortcutDelegate } @available(iOS 9.0, *) func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { completionHandler(handleShortcut(shortcutItem)) } @available(iOS 9.0, *) func handleShortcut( shortcutItem:UIApplicationShortcutItem ) -> Bool { var succeeded = true let mainViewController = self.window?.rootViewController as! ViewController if shortcutItem.type.containsString("takeSelfie") { Analytics.logCustomEventWithName("Shortcut Used", customAttributes: ["Method":"Take Selfie"]) mainViewController.takeSelfieTapped() } else if shortcutItem.type.containsString("choosePhoto") { Analytics.logCustomEventWithName("Shortcut Used", customAttributes: ["Method":"Choose Photo"]) mainViewController.choosePhotoTapped() } else if shortcutItem.type.containsString("takePhoto") { Analytics.logCustomEventWithName("Shortcut Used", customAttributes: ["Method":"Take Photo"]) mainViewController.takePhotoTapped() } else { succeeded = false } return succeeded } 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:. } }
31fe8a3d253a642e442f8cd5a6625b3a
45.681319
285
0.713748
false
false
false
false
DianQK/rx-sample-code
refs/heads/master
TextInput/InputCollectionViewCell.swift
mit
1
// // InputCollectionViewCell.swift // TextInputDemo // // Created by DianQK on 18/01/2017. // Copyright © 2017 T. All rights reserved. // import UIKit import RxSwift import RxCocoa class InputCollectionViewCell: UICollectionViewCell { @IBOutlet weak var textField: InputTextField! var isInputing: UIBindingObserver<InputCollectionViewCell, Bool> { return UIBindingObserver(UIElement: self, binding: { (UIElement, value) in UIElement.textField._canBecomeFirstResponder = value if value { _ = UIElement.becomeFirstResponder() } else { _ = UIElement.resignFirstResponder() } }) } var canInput: UIBindingObserver<InputCollectionViewCell, Bool> { return UIBindingObserver(UIElement: self, binding: { (UIElement, value) in UIElement.textField._canBecomeFirstResponder = value }) } override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } override var canBecomeFirstResponder: Bool { return textField.canBecomeFirstResponder } override var canResignFirstResponder: Bool { return textField.canResignFirstResponder } override func resignFirstResponder() -> Bool { return textField.resignFirstResponder() } override var isFirstResponder: Bool { return textField.isFirstResponder } private(set) var reuseDisposeBag = DisposeBag() override func awakeFromNib() { super.awakeFromNib() textField.text = nil } override func prepareForReuse() { super.prepareForReuse() textField.text = nil reuseDisposeBag = DisposeBag() } }
5e87af22611ebc8deafef113b9aac628
25.089552
82
0.657895
false
false
false
false
NickAger/elm-slider
refs/heads/master
Modules/HTTPFile/Sources/HTTPFile/Response+File.swift
mit
5
extension Response { public init(status: Status = .ok, headers: Headers = [:], filePath: String) throws { do { var filePath = filePath let file: File // This logic should not be here. It should be defined before calling the initializer. // Also use some String extension like String.fileExtension? if filePath.split(separator: ".").count == 1 { filePath += ".html" } do { file = try File(path: filePath, mode: .read) } catch { file = try File(path: filePath + "html", mode: .read) } self.init(status: status, headers: headers, body: file) if let fileExtension = file.fileExtension, let mediaType = mediaType(forFileExtension: fileExtension) { self.contentType = mediaType } } catch { throw HTTPError.notFound } } }
419f3adea1d6591caa3ca9d58612b3ff
33.678571
115
0.532441
false
false
false
false
sebcode/SwiftHelperKit
refs/heads/master
Source/IniParser.swift
mit
1
// // IniParser.swift // SwiftHelperKit // // Copyright © 2015 Sebastian Volland. All rights reserved. // import Foundation open class IniParser { open class func parse(string: String) -> [String: [String: String]] { guard string != "" else { return [:] } let lines = string.components(separatedBy: "\n") as [String] var currentSectionName = "" var currentSection: [String: String] = [:] var ret: [String: [String: String]] = [:] for line in lines { if line.hasPrefix("[") { if currentSectionName != "" { ret[currentSectionName] = currentSection currentSection = [:] } currentSectionName = String(line[line.index(line.startIndex, offsetBy: 1)..<line.index(line.endIndex, offsetBy: -1)]) } if line != "" && currentSectionName != "" { if let range = line.range(of: "=") { let key = line[..<range.lowerBound].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let value = String(line.suffix(from: range.upperBound)).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) currentSection[key] = value } } } if currentSectionName != "" { ret[currentSectionName] = currentSection } return ret } }
657489c01c6400ee59bec3d5f4a657cd
30.804348
135
0.539986
false
false
false
false
JerrySir/YCOA
refs/heads/master
YCOA/Main/Attendance/Controller/AttendanceViewController.swift
mit
1
// // AttendanceViewController.swift // YCOA // // Created by Jerry on 2016/12/15. // Copyright © 2016年 com.baochunsteel. All rights reserved. // // 考勤中心 import UIKit import MapKit import CoreLocation class AttendanceViewController: UIViewController, MKMapViewDelegate, UITableViewDataSource { private var mapView : MKMapView? private var locationManager : CLLocationManager? private var geocoder : CLGeocoder? private var annotation = MKPointAnnotation() private var latitude : CGFloat = 0.0 private var longitude: CGFloat = 0.0 private var addressString : String? private var historyRecordArr : [String] = [] //历史签到记录 private var tableView : UITableView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.groupTableViewBackground self.title = "签到中心" self.initMapView() self.initHistoryRecordView() self.getHistoryRecord() // Do any additional setup after loading the view. } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.mapView?.showsUserLocation = false self.mapView?.userTrackingMode = MKUserTrackingMode.none self.mapView?.layer.removeAllAnimations() self.mapView?.removeOverlays((self.mapView?.overlays)!) self.mapView?.removeFromSuperview() self.mapView?.delegate = nil self.mapView = nil self.locationManager = nil self.geocoder = nil self.annotation = MKPointAnnotation() self.view.removeAllSubviews() } deinit { NSLog("签到控制器正常释放") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - History record View func initHistoryRecordView() { // let label = UILabel(frame: CGRect(x: 8, y: JRSCREEN_HEIGHT - 170, width: JRSCREEN_WIDTH - 16, height: 50)) label.text = "历史签到记录:" self.view.addSubview(label) //签到按钮 let button = UIButton(frame: CGRect(x: JRSCREEN_WIDTH - 108, y: JRSCREEN_HEIGHT - 160, width: 100, height: 30)) button.setTitle("签到", for: UIControlState.normal) button.setTitleColor(UIColor.white, for: UIControlState.normal) button.backgroundColor = UIColor.lightGray button.rac_signal(for: UIControlEvents.touchUpInside).subscribeNext { (sender) in NSLog("签到") guard self.addressString != nil else{ self.view.jrShow(withTitle: "还未定位成功,请稍后!") return } guard UserCenter.shareInstance().isLogin else { self.view.jrShow(withTitle: "未登录!") return } let parameters = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!, "location_x": self.latitude, "location_y": self.longitude, "scale": 18, "label": self.addressString!] as [String : Any] YCOA_NetWork.get(url: "/index.php?d=taskrun&m=kaoqin|appapi&a=dwdk&ajaxbool=true", parameters: parameters, completionHandler: { (error, returnValue) in if(error != nil){ self.navigationController?.view.jrShow(withTitle: error!.domain) return } self.navigationController?.view.jrShow(withTitle: "签到成功!") self.getHistoryRecord() }) } self.view.addSubview(button) button.layer.masksToBounds = true button.layer.cornerRadius = 10/2 //历史签到记录列表 self.tableView = UITableView(frame: CGRect(x: 8, y: JRSCREEN_HEIGHT - 120, width: JRSCREEN_WIDTH - 16, height: 120), style: UITableViewStyle.plain) self.tableView!.dataSource = self self.view.addSubview(self.tableView!) } //MARK: - Map View func initMapView() { let rect = CGRect(x: 0, y: 0, width: JRSCREEN_WIDTH, height: JRSCREEN_HEIGHT - 170) self.mapView = MKMapView(frame: rect) self.view.addSubview(self.mapView!) //设置代理 self.mapView!.delegate = self //请求定位服务 self.locationManager = CLLocationManager() if(!CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedWhenInUse){ self.locationManager?.requestWhenInUseAuthorization() } //用户位置追踪(用户位置追踪用于标记用户当前位置,此时会调用定位服务) self.mapView!.userTrackingMode = MKUserTrackingMode.follow //设置地图类型 self.mapView!.mapType = MKMapType.standard } /// 添加大头针 func addAnnotation() { self.mapView?.removeAnnotation(self.annotation) let location = CLLocationCoordinate2DMake(CLLocationDegrees(self.latitude), CLLocationDegrees(self.longitude)) self.annotation = MKPointAnnotation() self.annotation.title = "当前位置" self.annotation.subtitle = self.addressString self.annotation.coordinate = location self.mapView?.addAnnotation(self.annotation) self.mapView?.selectAnnotation(self.annotation, animated: true) } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { self.latitude = CGFloat(userLocation.coordinate.latitude) self.longitude = CGFloat(userLocation.coordinate.longitude) self.getAddressByLatitude(latitude: CLLocationDegrees(self.latitude), longitude: CLLocationDegrees(self.longitude)) self.mapView?.showsUserLocation = true } func getAddressByLatitude(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let location = CLLocation(latitude: latitude, longitude: longitude) self.geocoder = CLGeocoder() self.geocoder!.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in guard error == nil else{ return } let placemark = placemarks?.first guard let addressDic : NSDictionary = placemark?.addressDictionary as NSDictionary? else{ return } let adressString_ = (addressDic["FormattedAddressLines"] as! NSArray).componentsJoined(by: " ") NSLog("\(adressString_)") self.addressString = adressString_ self.mapView?.userLocation.title = self.addressString self.mapView?.selectAnnotation(self.mapView!.userLocation, animated: true) }) } //MARK: - get history record func getHistoryRecord() { guard UserCenter.shareInstance().isLogin else { self.view.jrShow(withTitle: "未登录!") return } let parameters = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!] YCOA_NetWork.get(url: "/index.php?d=taskrun&m=kaoqin|appapi&a=getlocation&ajaxbool=true", parameters: parameters) { (error, returnValue) in if(error != nil) { self.navigationController?.view.jrShow(withTitle: error!.domain) return } guard let data : NSArray = (returnValue as! NSDictionary).value(forKey: "data") as? NSArray else{ self.navigationController?.view.jrShow(withTitle: "暂无数据") return } //同步数据 self.historyRecordArr = [] for item in data { guard let itemDic = item as? NSDictionary else{ continue } let adress = itemDic["label"] as! String let index = itemDic["id"] as! String self.historyRecordArr.append(index + "次: " + adress) } self.tableView!.reloadData() } } //MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.historyRecordArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if(cell == nil){ cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell") } cell!.textLabel!.text = self.historyRecordArr[indexPath.row] return cell! } /* // 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. } */ }
61d6ea1154119c0c8fbb14dbd9134c65
37.498054
155
0.585102
false
false
false
false
lgp123456/tiantianTV
refs/heads/master
douyuTV/douyuTV/Classes/Live/Controller/ChildVc/XTTechnologyViewController.swift
mit
1
// // XTTechnologyViewController.swift // douyuTV // // Created by 李贵鹏 on 16/8/31. // Copyright © 2016年 李贵鹏. All rights reserved. // import UIKit class XTTechnologyViewController: XTBaseLiveViewController { override func viewDidLoad() { super.viewDidLoad() // url = "http://capi.douyucdn.cn/api/v1/getColumnRoom/3?aid=ios&client_sys=ios&limit=20&offset=0&time=1469008980&auth=3392837008aa8938f7dce0d8c72c321d" url = "http://capi.douyucdn.cn/api/v1/getColumnRoom/3?limit=20&offset=0" } }
bc93aded020639bb18cef67d87776ba8
27.157895
160
0.695327
false
false
false
false
Keymochi/Keymochi
refs/heads/master
Keymochi/AppDelegate.swift
bsd-3-clause
1
// // AppDelegate.swift // Keymochi // // Created by Huai-Che Lu on 2/28/16. // Copyright © 2016 Cornell Tech. All rights reserved. // import UIKit import UserNotifications import UserNotificationsUI import Crashlytics import Fabric import Firebase import FirebaseDatabase import FirebaseMessaging import PAM import RealmSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func applicationDidFinishLaunching(_ application: UIApplication) { Fabric.with([Crashlytics.self]) FIRApp.configure() if #available(iOS 10.0, *) { let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self // For iOS 10 data message (sent via FCM) FIRMessaging.messaging().remoteMessageDelegate = self } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() } @nonobjc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool { // Override point for customization after application launch. Fabric.with([Crashlytics.self]) let directoryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupIdentifier) let realmPath = (directoryURL?.appendingPathComponent("db.realm").path)! var realmConfig = Realm.Configuration() realmConfig.fileURL = URL.init(string: realmPath) realmConfig.schemaVersion = 5 realmConfig.migrationBlock = { (migration, oldSchemaVersion) in if oldSchemaVersion < 2 { migration.enumerateObjects(ofType: DataChunk.className()) { (oldObject, newObject) in newObject!["appVersion"] = "0.2.0" } } if oldSchemaVersion < 3 { migration.enumerateObjects(ofType: DataChunk.className()) { (oldObject, newObject) in newObject!["firebaseKey"] = nil } } } Realm.Configuration.defaultConfiguration = realmConfig return true } override init() { super.init() // not really needed unless you really need it FIRDatabase.database().persistenceEnabled = 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:. } } extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print(response) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print(userInfo) } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // Convert token to string let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) // Print it to console print("APNs device token: \(deviceTokenString)") // Persist it in your backend in case it's new } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Fail to register for remote notification: \(error)") } } extension AppDelegate: FIRMessagingDelegate { func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { print(remoteMessage) } }
685365bf987955f3221e3ef515c00c3d
42.251852
285
0.686076
false
true
false
false
macmade/AtomicKit
refs/heads/main
AtomicKitTests/Semaphore.swift
mit
1
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ import XCTest import AtomicKit class SemaphoreTest: XCTestCase { var testHelper: String? override func setUp() { super.setUp() let bundle = Bundle( identifier: "com.xs-labs.AtomicKitTests" ) if( bundle == nil || bundle?.executableURL == nil ) { XCTFail( "Invalid bundle" ) } let url = bundle?.executableURL?.deletingLastPathComponent().appendingPathComponent( "Test-Helper" ) if( url == nil || FileManager.default.fileExists( atPath: url!.path ) == false ) { XCTFail( "Cannot find Test-Helper executable" ) } self.testHelper = url!.path } override func tearDown() { super.tearDown() } func runHelper( command: String, args: [ String ] ) { self.runHelper( commands: [ command : args ] ) } func runHelper( commands: [ String : [ String ] ] ) { var args = [ String ]() if( self.testHelper == nil ) { XCTFail( "Cannot find Test-Helper executable" ) } for p in commands { args.append( p.key ) args.append( contentsOf: p.value ) } let task = Process.launchedProcess( launchPath: self.testHelper!, arguments: args ) task.waitUntilExit() } func testUnnamedBinaryTryWait() { let sem = try? Semaphore() XCTAssertNotNil( sem ) XCTAssertTrue( sem!.tryWait() ) XCTAssertFalse( sem!.tryWait() ) sem!.signal() } func testNamedBinaryTryWait() { let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" ) let sem2 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" ) XCTAssertNotNil( sem1 ) XCTAssertNotNil( sem2 ) XCTAssertTrue( sem1!.tryWait() ) XCTAssertFalse( sem1!.tryWait() ) XCTAssertFalse( sem2!.tryWait() ) sem1!.signal() XCTAssertTrue( sem2!.tryWait() ) XCTAssertFalse( sem2!.tryWait() ) XCTAssertFalse( sem1!.tryWait() ) sem2!.signal() } func testUnnamedTryWait() { let sem = try? Semaphore( count: 2 ) XCTAssertNotNil( sem ) XCTAssertTrue( sem!.tryWait() ) XCTAssertTrue( sem!.tryWait() ) XCTAssertFalse( sem!.tryWait() ) sem!.signal() sem!.signal() } func testNamedTryWait() { let sem1 = try? Semaphore( count: 2, name: "XS-Test-Semaphore-2" ) let sem2 = try? Semaphore( count: 2, name: "XS-Test-Semaphore-2" ) XCTAssertNotNil( sem1 ) XCTAssertNotNil( sem2 ) XCTAssertTrue( sem1!.tryWait() ) XCTAssertTrue( sem1!.tryWait() ) XCTAssertFalse( sem1!.tryWait() ) XCTAssertFalse( sem2!.tryWait() ) sem1!.signal() XCTAssertTrue( sem2!.tryWait() ) XCTAssertFalse( sem1!.tryWait() ) sem1!.signal() sem2!.signal() } func testUnnamedWaitSignal() { let sem = try? Semaphore( count: 1 ) XCTAssertNotNil( sem ) sem!.wait() XCTAssertFalse( sem!.tryWait() ) sem!.signal() XCTAssertTrue( sem!.tryWait() ) sem!.signal() } func testNamedWaitSignal() { let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" ) let sem2 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" ) XCTAssertNotNil( sem1 ) XCTAssertNotNil( sem2 ) sem1!.wait() XCTAssertFalse( sem1!.tryWait() ) XCTAssertFalse( sem2!.tryWait() ) sem1!.signal() XCTAssertTrue( sem2!.tryWait() ) XCTAssertFalse( sem1!.tryWait() ) sem2!.signal() } func testUnnamedThrowOnInvalidCount() { XCTAssertThrowsError( try Semaphore( count: 0 ) ); } func testNamedThrowOnInvalidCount() { XCTAssertThrowsError( try Semaphore( count: 0, name: "XS-Test-Semaphore-0" ) ); } func testNamedThrowOnInvalidName() { var name = "XS-Test-Semaphore-" for _ in 0 ... 256 { name += "X"; } XCTAssertThrowsError( try Semaphore( count: 1, name:name ) ); } func testIsNamed() { let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" ) let sem2 = try? Semaphore() XCTAssertNotNil( sem1 ) XCTAssertNotNil( sem2 ) XCTAssertTrue( sem1!.isNamed ); XCTAssertFalse( sem2!.isNamed ); } func testGetName() { let sem1 = try? Semaphore( count: 1, name: "XS-Test-Semaphore-1" ) let sem2 = try? Semaphore() XCTAssertNotNil( sem1 ) XCTAssertNotNil( sem2 ) XCTAssertEqual( sem1!.name, "/XS-Test-Semaphore-1" ) XCTAssertEqual( sem2!.name, nil ) } }
8ad86760dc6c65bcecf552ceb613cfe7
27.769912
108
0.549985
false
true
false
false
damoyan/BYRClient
refs/heads/master
FromScratch/Utils.swift
mit
1
// // Utils.swift // FromScratch // // Created by Yu Pengyang on 11/7/15. // Copyright © 2015 Yu Pengyang. All rights reserved. // import UIKit import ImageIO class Utils: NSObject { static var defaultDateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateStyle = .LongStyle formatter.timeStyle = .LongStyle return formatter }() static var main: UIStoryboard = { return UIStoryboard.init(name: "Main", bundle: nil) }() static func dateFromUnixTimestamp(ts: Int?) -> NSDate? { guard let ts = ts else { return nil } return NSDate(timeIntervalSince1970: NSTimeInterval(ts)) } static func getImagesFromData(data: NSData) throws -> [UIImage] { guard let source = CGImageSourceCreateWithData(data, nil) else { throw BYRError.CreateImageSourceFailed } var images = [UIImage]() autoreleasepool { let frameCount = CGImageSourceGetCount(source) for var i = 0; i < frameCount; i++ { if let image = CGImageSourceCreateImageAtIndex(source, i, nil) { let alphaInfo = CGImageGetAlphaInfo(image).rawValue & CGBitmapInfo.AlphaInfoMask.rawValue let hasAlpha: Bool if (alphaInfo == CGImageAlphaInfo.PremultipliedLast.rawValue || alphaInfo == CGImageAlphaInfo.PremultipliedFirst.rawValue || alphaInfo == CGImageAlphaInfo.Last.rawValue || alphaInfo == CGImageAlphaInfo.First.rawValue) { hasAlpha = true } else { hasAlpha = false } // // BGRA8888 (premultiplied) or BGRX8888 // // same as UIGraphicsBeginImageContext() and -[UIView drawRect:] var bitmapInfo = CGBitmapInfo.ByteOrderDefault.rawValue // kCGBitmapByteOrder32Host; bitmapInfo |= hasAlpha ? CGImageAlphaInfo.PremultipliedLast.rawValue : CGImageAlphaInfo.NoneSkipFirst.rawValue; let context = CGBitmapContextCreate(nil, CGImageGetWidth(image), CGImageGetHeight(image), 8, 0, CGColorSpaceCreateDeviceRGB(), bitmapInfo) CGContextDrawImage(context, CGRect(x: 0, y: 0, width: CGImageGetWidth(image), height: CGImageGetHeight(image)), image) // decode let newImage = CGBitmapContextCreateImage(context)! images.append(UIImage(CGImage: newImage)) } } } return images } static func getEmotionData(name: String) -> NSData? { var imageName: String, imageFolder: String let folderPrefix = "emotions/" if name.hasPrefix("emc") { imageFolder = folderPrefix + "emc" imageName = (name as NSString).substringFromIndex(3) } else if name.hasPrefix("emb") { imageFolder = folderPrefix + "emb" imageName = (name as NSString).substringFromIndex(3) } else if name.hasPrefix("ema") { imageFolder = folderPrefix + "ema" imageName = (name as NSString).substringFromIndex(3) } else { imageFolder = folderPrefix + "em" imageName = (name as NSString).substringFromIndex(2) } let path = NSBundle.mainBundle().pathForResource(imageName, ofType: "gif", inDirectory: imageFolder) if let path = path, data = NSData(contentsOfFile: path) { return data } return nil } } extension UIViewController { func navigateToLogin() { dismissViewControllerAnimated(true, completion: nil) } func navigateToSectionDetail(section: Section) { let vc = Utils.main.instantiateViewControllerWithIdentifier("vcSection") as! SectionViewController vc.section = section navigationController?.pushViewController(vc, animated: true) } func navigateToFavorite(level: Int) { let vc = Utils.main.instantiateViewControllerWithIdentifier("vcFavorite") as! FavoriteViewController vc.level = level navigationController?.pushViewController(vc, animated: true) } func navigateToBoard(name: String) { let vc = Utils.main.instantiateViewControllerWithIdentifier("vcBoard") as! BoardViewController vc.boardName = name navigationController?.pushViewController(vc, animated: true) } func navigateToThread(article: Article) { let vc = Utils.main.instantiateViewControllerWithIdentifier("vcThread") as! ThreadViewController vc.topic = article navigationController?.pushViewController(vc, animated: true) } } extension NSDate { } extension UIImage { class func imageWithColor(color: UIColor, side: CGFloat) -> UIImage { let rect = CGRect(x: 0, y: 0, width: side, height: side) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } extension UIColor { convenience init(rgb: UInt, alpha: CGFloat = 1) { self.init(red: CGFloat((rgb & 0xff0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00ff00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000ff) / 255.0, alpha: CGFloat(alpha)) } convenience init(rgbString: String) { var r: UInt32 = 0 var g: UInt32 = 0 var b: UInt32 = 0 let str = rgbString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString var start = -1 if str.hasPrefix("#") && str.characters.count == 7 { start = 1 } else if str.hasPrefix("0X") && str.characters.count == 9 { start = 2 } if (start >= 0) { let rStr = str[start..<start+2] let gStr = str[start+2..<start+4] let bStr = str[start+4..<start+6] NSScanner(string: rStr).scanHexInt(&r) NSScanner(string: gStr).scanHexInt(&g) NSScanner(string: bStr).scanHexInt(&b) } self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1)) } } extension String { subscript (r: Range<Int>) -> String { get { let startIndex = self.startIndex.advancedBy(r.startIndex) let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } var floatValue: Float { return (self as NSString).floatValue } var integerValue: Int { return (self as NSString).integerValue } var sha1: String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joinWithSeparator("") } }
46503a80940ed5879e2f5dfac20f6427
36.903553
158
0.600991
false
false
false
false
BrisyIOS/CustomAlbum
refs/heads/master
CustomAlbum/CustomAlbum/ModalAnimationDelegate.swift
apache-2.0
1
// // ModalAnimationDelegate.swift // 仿微信照片弹出动画 // // Created by zhangxu on 2016/12/21. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit class ModalAnimationDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { // ⚠️ 一定要写成单粒,不然,下面的方法不会执行 static let shared: ModalAnimationDelegate = ModalAnimationDelegate(); private var isPresentAnimationing: Bool = true; func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresentAnimationing = true; return self; } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresentAnimationing = false; return self; } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5; } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresentAnimationing { presentViewAnimation(transitionContext: transitionContext); } else { dismissViewAnimation(transitionContext: transitionContext); } } // 弹出动画 func presentViewAnimation(transitionContext: UIViewControllerContextTransitioning) { // 过渡view guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return; } // 容器view let containerView = transitionContext.containerView; // 过渡view添加到容器view上 containerView.addSubview(toView); // 目标控制器 guard let toVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? PhotoDetailController else { return; } // indexPath guard let indexPath = toVc.indexPath else { return; } // 当前跳转的控制器 guard let fromVc = ((transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? UINavigationController)?.topViewController) as? PhotoListController else { return; }; // 获取collectionView let collectionView = fromVc.collectionView; // 获取当前选中的cell guard let selectedCell = collectionView.cellForItem(at: indexPath) as? PhotoCell else { return; } // 新建一个imageview添加到目标view之上,做为动画view let imageView = UIImageView(); imageView.image = selectedCell.image; imageView.contentMode = .scaleAspectFit; imageView.clipsToBounds = true; // 获取window guard let window = UIApplication.shared.keyWindow else { return; } // 被选中的cell到目标view上的座标转换 let originFrame = collectionView.convert(selectedCell.frame, to: window); imageView.frame = originFrame; // 将imageView 添加到容器视图上 containerView.addSubview(imageView); let endFrame = window.bounds; toView.alpha = 0; UIView.animate(withDuration: 0.5, animations: { _ in imageView.frame = endFrame; }, completion: { _ in transitionContext.completeTransition(true); UIView.animate(withDuration: 0.2, animations: { _ in toView.alpha = 1; }, completion: { _ in imageView.removeFromSuperview(); }); }) } // 消失动画 func dismissViewAnimation(transitionContext: UIViewControllerContextTransitioning) { let transitionView = transitionContext.view(forKey: UITransitionContextViewKey.from); let contentView = transitionContext.containerView; // 取出modal出的来控制器 guard let fromVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? PhotoDetailController else { return; } // 取出当前显示的collectionview let collectionView = fromVc.collectionView; // 取出控制器当前显示的cell guard let dismissCell = collectionView.visibleCells.first as? PhotoDetailCell else { return; } // 新建过渡动画imageview let imageView = UIImageView(); imageView.contentMode = .scaleAspectFit; imageView.clipsToBounds = true; // 获取当前显示的cell 的image imageView.image = dismissCell.icon.image; // 获取当前显示cell在window中的frame imageView.frame = dismissCell.icon.frame; contentView.addSubview(imageView); // 动画最后停止的frame guard let indexPath = collectionView.indexPath(for: dismissCell) else { return; } // 取出要返回的控制器 guard let toVC = ((transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? UINavigationController)?.topViewController) as? PhotoListController else { return; } let originView = toVC.collectionView; guard let originCell = originView.cellForItem(at: indexPath) as? PhotoCell else { originView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false) return; } guard let window = UIApplication.shared.keyWindow else { return; } let originFrame = originView.convert(originCell.frame, to: window); // 执行动画 UIView.animate(withDuration: 0.5, animations: { _ in imageView.frame = originFrame; transitionView?.alpha = 0; }, completion: { _ in imageView.removeFromSuperview(); transitionContext.completeTransition(true); }) } }
3928991cf6afadcda7c3eb09410226d4
33.404624
191
0.624832
false
false
false
false
MiniDOM/MiniDOM
refs/heads/master
Sources/MiniDOM/Search.swift
mit
1
// // Search.swift // MiniDOM // // Copyright 2017-2020 Anodized Software, 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 class ElementSearch: Visitor { private(set) var elements: [Element] = [] let predicate: (Element) -> Bool init(predicate: @escaping (Element) -> Bool) { self.predicate = predicate } func beginVisit(_ element: Element) { if predicate(element) { elements.append(element) } } } public extension Document { /** Traverses the document tree, collecting `Element` nodes with the specified tag name from anywhere in the document. - parameter name: Collect elements with this tag name. - returns: An array of elements with the specified tag name. */ final func elements(withTagName name: String) -> [Element] { return elements(where: { $0.tagName == name }) } /** Traverses the document tree, collecting `Element` nodes that satisfy the given predicate from anywhere in the document. - parameter predicate: A closure that takes an element as its argument and returns a Boolean value indicating whether the element should be included in the returned array. - returns: An array of the elements that `predicate` allowed. */ final func elements(where predicate: @escaping (Element) -> Bool) -> [Element] { let visitor = ElementSearch(predicate: predicate) documentElement?.accept(visitor) return visitor.elements } }
2ad3eb960984a516b5c937d909bfa85d
34.902778
84
0.700193
false
false
false
false
daggmano/photo-management-studio
refs/heads/develop
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/MediaObject.swift
mit
1
// // MediaObject.swift // Photo Management Studio // // Created by Darren Oster on 6/04/2016. // Copyright © 2016 Criterion Software. All rights reserved. // import Cocoa class MediaObject: NSObject, JsonProtocol { internal private(set) var mediaId: String? internal private(set) var mediaRev: String? internal private(set) var importId: String? internal private(set) var uniqueId: String? internal private(set) var fullFilePath: String? internal private(set) var fileName: String? internal private(set) var shotDate: String? internal private(set) var rating: Int? internal private(set) var dateAccuracy: Int? internal private(set) var caption: String? internal private(set) var rotate: Int? internal private(set) var metadata: [MetadataObject]? internal private(set) var tagIds: [String]? init(mediaId: String, mediaRev: String, importId: String, uniqueId: String, fullFilePath: String, fileName: String, shotDate: String, rating: Int, dateAccuracy: Int, caption: String, rotate: Int, metadata: [MetadataObject], tagIds: [String]) { self.mediaId = mediaId self.mediaRev = mediaRev self.importId = importId self.uniqueId = uniqueId self.fullFilePath = fullFilePath self.fileName = fileName self.shotDate = shotDate self.rating = rating self.dateAccuracy = dateAccuracy self.caption = caption self.rotate = rotate self.metadata = metadata self.tagIds = tagIds } required init(json: [String: AnyObject]) { self.mediaId = json["_id"] as? String self.mediaRev = json["_rev"] as? String self.importId = json["importId"] as? String self.uniqueId = json["uniqueId"] as? String self.fullFilePath = json["fullFilePath"] as? String self.fileName = json["fileName"] as? String self.shotDate = json["shotDate"] as? String self.rating = json["rating"] as? Int self.dateAccuracy = json["dateAccuracy"] as? Int self.caption = json["caption"] as? String self.rotate = json["rotate"] as? Int if let metadata = json["metadata"] as? [[String: AnyObject]] { self.metadata = [MetadataObject]() for item in metadata { self.metadata!.append(MetadataObject(json: item)) } } self.tagIds = json["tagIds"] as? [String] } func toJSON() -> [String: AnyObject] { var result = [String: AnyObject]() if let mediaId = self.mediaId { result["_id"] = mediaId } if let mediaRev = self.mediaRev { result["_rev"] = mediaRev } if let importId = self.importId { result["importId"] = importId } if let uniqueId = self.uniqueId { result["uniqueId"] = uniqueId } if let fullFilePath = self.fullFilePath { result["fullFilePath"] = fullFilePath } if let fileName = self.fileName { result["fileName"] = fileName } if let shotDate = self.shotDate { result["shotDate"] = shotDate } if let rating = self.rating { result["rating"] = rating } if let dateAccuracy = self.dateAccuracy { result["dateAccuracy"] = dateAccuracy } if let caption = self.caption { result["caption"] = caption } if let rotate = self.rotate { result["rotate"] = rotate } if let metadata = self.metadata { var array = [[String: AnyObject]]() for item in metadata { array.append(item.toJSON()) } result["metadata"] = array } if let tagIds = self.tagIds { result["tagIds"] = tagIds } return result } } class MetadataObject: NSObject, JsonProtocol { internal private(set) var group: String? internal private(set) var name: String? internal private(set) var value: String? init(group: String, name: String, value: String) { self.group = group self.name = name self.value = value } required init(json: [String: AnyObject]) { self.group = json["group"] as? String self.name = json["name"] as? String self.value = json["value"] as? String } func toJSON() -> [String: AnyObject] { var result = [String: AnyObject]() if let group = self.group { result["group"] = group } if let name = self.name { result["name"] = name } if let value = self.value { result["value"] = value } return result } }
83d55d70eb81da58cb029fe9e8e13cff
31.986395
247
0.573108
false
false
false
false
JadenGeller/CS-81-Project
refs/heads/master
Sources/DecimalDigit.swift
mit
1
// // DecimalDigit.swift // Language // // Created by Jaden Geller on 2/22/16. // Copyright © 2016 Jaden Geller. All rights reserved. // public enum DecimalDigit: Int, Equatable { case Zero case One case Two case Three case Four case Five case Six case Seven case Eight case Nine } extension DecimalDigit: IntegerLiteralConvertible { public init(integerLiteral value: Int) { guard let this = DecimalDigit(rawValue: value) else { fatalError("Decimal digit must be between 0 and 9") } self = this } } public func ==(lhs: DecimalDigit, rhs: DecimalDigit) -> Bool { return lhs.rawValue == rhs.rawValue }
18073f4c37038e27b3ddcdf0304220be
20.060606
63
0.641727
false
false
false
false
hpsoar/Knife
refs/heads/master
Knife/ViewController.swift
mit
1
// // ViewController.swift // Knife // // Created by HuangPeng on 8/23/14. // Copyright (c) 2014 Beacon. All rights reserved. // import UIKit class DateView: UIView { var solarDateView: UIView! var lunarDateView: UIView! var weekLabel: UILabel! var yearLabel: UILabel! var dateLabel: UILabel! var lunarDateLabel: UILabel! init(frame: CGRect) { super.init(frame: frame) self.setup() } func weekString(week: NSInteger) -> String { let weekString = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] return weekString[week - 1] } func setup() { let date = NSDate() /* * --------------------------- * solar date: week * ---- month / day * year * --------------------------- * lunar date: month day * --------------------------- */ solarDateView = UIView(frame: CGRectMake(0, 0, 110, 44)) solarDateView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.6) self.addSubview(solarDateView) weekLabel = UILabel(frame: CGRectMake(4, 3, 30, solarDateView.frame.height / 2)) weekLabel.font = UIFont.systemFontOfSize(12) weekLabel.textColor = UIColor.whiteColor() yearLabel = UILabel(frame: CGRectMake(4, weekLabel.frame.height - 3, 30, solarDateView.frame.height / 2)) yearLabel.font = UIFont.systemFontOfSize(12) yearLabel.textColor = UIColor.whiteColor() weekLabel.text = self.weekString(date.week) yearLabel.text = String(date.year) solarDateView.addSubview(weekLabel) solarDateView.addSubview(yearLabel) dateLabel = UILabel(frame: CGRectMake(40, 0, solarDateView.frame.width - weekLabel.frame.width, solarDateView.frame.height)) dateLabel.font = UIFont.systemFontOfSize(28) dateLabel.text = String(date.month) + "/" + String(date.day) dateLabel.textColor = UIColor.whiteColor() solarDateView.addSubview(dateLabel) lunarDateView = UIView(frame: CGRectMake(0, solarDateView.frame.origin.y + solarDateView.frame.height, 110, 22)) lunarDateView.backgroundColor = UIColor(white: 0.3, alpha: 0.6) self.addSubview(lunarDateView) var lunarDate = LunarDate(date: date) lunarDateLabel = UILabel(frame: CGRectMake(4, 0, lunarDateView.frame.width, lunarDateView.frame.height)) lunarDateLabel.text = "农历 \(lunarDate.monthString)月\(lunarDate.dayString)" lunarDateLabel.textColor = UIColor.whiteColor() lunarDateLabel.font = UIFont.systemFontOfSize(12) lunarDateView.addSubview(lunarDateLabel) } } class ViewController: UIViewController, WeatherUtilityDelegate { var backgroundImageView: UIImageView? var scrollView: UIScrollView? var dateView: DateView? var imageNames: NSString[] = NSString[]() let weatherUtility = YahooWeather() override func viewDidLoad() { super.viewDidLoad() imageNames = [ "nature-wallpaper-beach-wallpapers-delightful-tropical-images_Beaches_wallpapers_196.jpg" ] var image = UIImage(named: imageNames[0]) image = image.applyBlurWithRadius(40, tintColor:nil, saturationDeltaFactor: 0.85, maskImage: nil, atFrame:CGRectMake(0, 0, image.size.width, image.size.height)) backgroundImageView = UIImageView(image: image) backgroundImageView!.contentMode = UIViewContentMode.ScaleAspectFill backgroundImageView!.frame = self.view.bounds self.view.addSubview(backgroundImageView!) scrollView = UIScrollView(frame: self.view.bounds) scrollView!.alwaysBounceVertical = true self.view.addSubview(scrollView!) dateView = DateView(frame: CGRectMake(0, 20, 320, 44)) self.view.addSubview(dateView!) weatherUtility.delegate = self weatherUtility.updateWeather("Beijing") weatherUtility.updatePM10("beijing") weatherUtility.updatePM2_5("beijing") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func geometricLocationUpdated() { println("hello") } func weatherUpdated() { } func pm10Updated() { } func pm2_5Updated() { } }
0fbd6e411270aa68cfef09af636e2edf
32.029197
168
0.609945
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Thread/Thread_Swift3.0/Thread_Swift3.0/SecondController.swift
mit
1
// // SecondController.swift // Thread_Swift3.0 // // Created by 伯驹 黄 on 2016/10/26. // Copyright © 2016年 xiAo_Ju. All rights reserved. // import UIKit // https://www.allaboutswift.com/dev/2016/7/12/gcd-with-swfit3 // http://www.cnblogs.com/ludashi/p/5336169.html // https://justinyan.me/post/2420 // https://bestswifter.com/deep-gcd/ // http://www.cocoachina.com/ios/20170829/20404.html class SecondController: UIViewController { fileprivate lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.frame, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") return tableView }() let tags: [[(String, Selector)]] = [ [ ("同步执行串行队列", #selector(performSerialQueuesUseSynchronization)), ("同步执行并行队列", #selector(performConcurrentQueuesUseSynchronization)) ], [ ("异步执行串行队列", #selector(performSerialQueuesUseAsynchronization)), ("异步执行并行队列", #selector(performConcurrentQueuesUseAsynchronization)) ], [ ("延迟执行", #selector(deferPerform)) ], [ ("设置全局队列的优先级", #selector(globalQueuePriority)), ("设置自建队列优先级", #selector(setCustomeQueuePriority)) ], [ ("自动执行任务组", #selector(autoGlobalQueue)), ("手动执行任务组", #selector(performGroupUseEnterAndleave)) ], [ ("使用信号量添加同步锁", #selector(useSemaphoreLock)) ], [ ("使用Apply循环执行", #selector(useDispatchApply)), ("暂停和重启队列", #selector(queueSuspendAndResume)), ("使用任务隔离栅栏", #selector(useBarrierAsync)) ], [ ("dispatch源,ADD", #selector(useDispatchSourceAdd)), ("dispatch源,OR", #selector(useDispatchSourceOR)), ("dispatch源,定时器", #selector(useDispatchSourceTimer)) ], [ ("不同queue opration 依赖", #selector(diffQueue)) ] ] override func viewDidLoad() { super.viewDidLoad() title = "Swift5.0 GCD" view.addSubview(tableView) } @objc func performSerialQueuesUseSynchronization() { let queue = DispatchQueue(label: "syn.serial.queue") for i in 0..<3 { queue.sync() { currentThreadSleep(1) print("当前执行线程:\(Thread.current)") print("执行\(i.toEmoji)") } print("\(i.toEmoji)执行完毕") } print("所有队列使用同步方式执行完毕") ended() } @objc func performConcurrentQueuesUseSynchronization() { let queue = DispatchQueue(label: "syn.concurrent.queue", attributes: .concurrent) for i in 0..<3 { queue.sync() { currentThreadSleep(1) print("当前执行线程:\(Thread.current)") print("执行\(i.toEmoji)") } print("\(i.toEmoji)执行完毕") } print("所有队列使用同步方式执行完毕") ended() } @objc func performSerialQueuesUseAsynchronization() { //一个串行队列,用于同步执行 let queue = DispatchQueue(label: "asyn.serial.queue") let group = DispatchGroup() let q = DispatchQueue(label: "serialQueue") for i in 0..<3 { group.enter() queue.async(group: group) { self.currentThreadSleep(Double(arc4random()%3)) let currentThread = Thread.current q.sync { //同步锁 group.leave() print("①Sleep的线程\(currentThread)") print("②当前输出内容的线程\(Thread.current)") print("③执行\(i.toEmoji):\(queue)\n") } } print("\(i.toEmoji)添加完毕\n") } print("使用异步方式添加队列") group.notify(queue: DispatchQueue.main) { self.ended() } } @objc func performConcurrentQueuesUseAsynchronization() { //一个串行队列,用于同步执行 let queue = DispatchQueue(label: "asyn.concurrent.queue", attributes: .concurrent) let group = DispatchGroup() let q = DispatchQueue(label: "serialQueue") for i in 0..<3 { group.enter() queue.async(group: group) { self.currentThreadSleep(Double(arc4random()%3)) let currentThread = Thread.current print("asyn.concurrent.queue", currentThread) q.sync { //同步锁 group.leave() print("①Sleep的线程\(currentThread)") print("②当前输出内容的线程\(Thread.current)") print("③执行\(i.toEmoji):\(queue)\n") } } print("\(i.toEmoji)添加完毕\n") } print("使用异步方式添加队列") group.notify(queue: DispatchQueue.main) { self.ended() } } @objc func diffQueue() { let queue1 = OperationQueue() queue1.name = "queue1" let queue2 = OperationQueue() queue2.name = "queue2" let opration1 = BlockOperation { sleep(2) print("我是1") } queue1.addOperation(opration1) let opration2 = BlockOperation { print("我是2") } opration2.addDependency(opration1) queue2.addOperation(opration2) } func currentThreadSleep(_ timer: TimeInterval) { print("😪😪😪延时😪😪😪") Thread.sleep(forTimeInterval: timer) } /// 创建并行队列 func getConcurrentQueue(_ label: String) -> DispatchQueue { return DispatchQueue(label: label, attributes: .concurrent) } /// 延迟执行 @objc func deferPerform(_ time: Int = 1) { let semaphore = DispatchSemaphore(value: 0) let queue = globalQueue() let delaySecond = DispatchTimeInterval.seconds(time) print(Date()) let delayTime = DispatchTime.now() + delaySecond queue.asyncAfter(deadline: delayTime) { print("执行线程:\(Thread.current)\ndispatch_time: 延迟\(time)秒执行\n",Date()) semaphore.signal() } //DispatchWallTime用于计算绝对时间,而DispatchWallTime是根据挂钟来计算的时间,即使设备睡眠了,他也不会睡眠。 // let nowInterval = Date().timeIntervalSince1970 // let nowStruct = timespec(tv_sec: Int(nowInterval), tv_nsec: 0) // let delayWalltime = DispatchWallTime(timespec: nowStruct) let delayWalltime = DispatchWallTime.now() + delaySecond queue.asyncAfter(wallDeadline: delayWalltime) { print("执行线程:\(Thread.current)\ndispatch_walltime: 延迟\(time)秒执行\n", Date()) } semaphore.wait() ended() } /// 全局队列的优先级关系 @objc func globalQueuePriority() { //高 > 默认 > 低 > 后台 let queueHeight = globalQueue(qos: .userInitiated) let queueDefault = globalQueue() let queueLow = globalQueue(qos: .utility) let queueBackground = globalQueue(qos: .background) let group = DispatchGroup() //优先级不是绝对的,大体上会按这个优先级来执行。 一般都是使用默认(default)优先级 queueLow.async(group: group) { print("Low:\(Thread.current)") } queueBackground.async(group: group) { print("Background:\(Thread.current)") } queueDefault.async(group: group) { print("Default:\(Thread.current)") } queueHeight.async(group: group) { print("High:\(Thread.current)") } group.wait() ended() } /// 给串行队列或者并行队列设置优先级 @objc func setCustomeQueuePriority() { //优先级的执行顺序也不是绝对的 //给serialQueueHigh设定DISPATCH_QUEUE_PRIORITY_HIGH优先级 let serialQueueHigh = DispatchQueue(label: "cn.zeluli.serial1") globalQueue(qos: .userInitiated).setTarget(queue: serialQueueHigh) let serialQueueLow = DispatchQueue(label: "cn.zeluli.serial1") globalQueue(qos: .utility).setTarget(queue: serialQueueLow) serialQueueLow.async { print("低:\(Thread.current)") } serialQueueHigh.async { print("高:\(Thread.current)") self.ended() } } func performGroupQueue() { let concurrentQueue = getConcurrentQueue("cn.zeluli") let group = DispatchGroup() //将group与queue进行管理,并且自动执行 for i in 1...3 { concurrentQueue.async(group: group) { self.currentThreadSleep(1) print("任务\(i)执行完毕\n") } } //队列组的都执行完毕后会进行通知 group.notify(queue: DispatchQueue.main) { self.ended() } print("异步执行测试,不会阻塞当前线程") } @objc func autoGlobalQueue() { globalQueue().async { self.performGroupQueue() } } /// 使用enter与leave手动管理group与queue @objc func performGroupUseEnterAndleave() { let concurrentQueue = getConcurrentQueue("cn.zeluli") let group = DispatchGroup() //将group与queue进行手动关联和管理,并且自动执行 for i in 1...3 { group.enter() //进入队列组 concurrentQueue.async { self.currentThreadSleep(1) print("任务\(i.toEmoji)执行完毕\n") group.leave() //离开队列组 } } _ = group.wait(timeout: .distantFuture) //阻塞当前线程,直到所有任务执行完毕 print("任务组执行完毕") group.notify(queue: concurrentQueue) { self.ended() } } //信号量同步锁 @objc func useSemaphoreLock() { let concurrentQueue = getConcurrentQueue("cn.zeluli") //创建信号量 let semaphoreLock = DispatchSemaphore(value: 2) var testNumber = 0 for index in 0 ... 9 { concurrentQueue.async { let wait = semaphoreLock.wait(timeout: .distantFuture) //上锁 print("wait=\(wait)") testNumber += 1 self.currentThreadSleep(1) print(Thread.current) print("第\(index.toEmoji)次执行: testNumber = \(testNumber)\n") semaphoreLock.signal() //开锁 } } } @objc func useBarrierAsync() { // 那你啥时候改用 barrier 方法,啥时候不该用呢? // // * 自定义串行队列 Custom Serial Queue: 没有必要在串行队列中使用,barrier 对于串行队列来说毫无用处,因为本来串行队列就是一次只会执行一个任务的。 // * 全局并发队列 Global Concurrent Queue: 要小心使用。在全局队列中使用 barrier 可能不是太好,因为系统也会使用这个队列,一般你不会希望自己的操作垄断了这个队列从而导致系统调用的延迟。 // * 自定义并发队列 Custom Concurrent Queue: 对于需要原子操作和访问临界区的代码,barrier 方法是最佳使用场景。任何你需要线程安全的实例,barrier 都是一个不错的选择。 let concurrentQueue = getConcurrentQueue("cn.zeluli") for i in 0...2 { concurrentQueue.async { self.currentThreadSleep(Double(i)) print("第一批:\(i.toEmoji)\(Thread.current)") } } for i in 0...3 { concurrentQueue.async(flags: .barrier) { self.currentThreadSleep(Double(i)) print("第二批:\(i.toEmoji)\(Thread.current)") } } let workItem = DispatchWorkItem(flags: .barrier) { print("\n第二批执行完毕后才会执行第三批\n\(Thread.current)\n") } concurrentQueue.async(execute: workItem) for i in 0...3 { concurrentQueue.async { self.currentThreadSleep(Double(i)) print("第三批:\(i.toEmoji)\(Thread.current)") } } print("😁😁😁不会阻塞主线程😁😁😁") } /// 循环执行 @objc func useDispatchApply() { print("循环多次执行并行队列") DispatchQueue.global(qos: .background).async { DispatchQueue.concurrentPerform(iterations: 3) { index in self.currentThreadSleep(Double(index)) print("第\(index)次执行,\n\(Thread.current)\n") } DispatchQueue.main.async { self.ended() } } } //暂停和重启队列 @objc func queueSuspendAndResume() { let concurrentQueue = getConcurrentQueue("cn.zeluli") concurrentQueue.suspend() //将队列进行挂起 concurrentQueue.async { print("任务执行, \(Thread.current)") } currentThreadSleep(2) concurrentQueue.resume() //将挂起的队列进行唤醒 ended() } /// 以加法运算的方式合并数据 // http://www.tanhao.me/pieces/360.html/ @objc func useDispatchSourceAdd() { var sum = 0 //手动计数的sum, 来模拟记录merge的数据 let queue = globalQueue() //创建source let dispatchSource = DispatchSource.makeUserDataAddSource(queue: queue) dispatchSource.setEventHandler() { print("source中所有的数相加的和等于\(dispatchSource.data)") print("sum = \(sum)\n") sum = 0 self.currentThreadSleep(0.3) } // DispatchQueue启动时默认状态是挂起的,创建完毕之后得主动恢复,否则事件不会被传送 dispatchSource.resume() for i in 1...10 { sum += i print("i=\(i)") dispatchSource.add(data: UInt(i)) currentThreadSleep(0.1) } ended() } /// 以或运算的方式合并数据 @objc func useDispatchSourceOR() { var or = 0 //手动计数的sum, 来记录merge的数据 let queue = globalQueue() //创建source let dispatchSource = DispatchSource.makeUserDataOrSource(queue: queue) dispatchSource.setEventHandler { print("source中所有的数相加的和等于\(dispatchSource.data)") print("or = \(or)\n") or = 0 self.currentThreadSleep(0.3) } dispatchSource.resume() for i in 1...10 { or |= i print("i=\(i)") dispatchSource.or(data: UInt(i)) currentThreadSleep(0.1) } print("\nsum = \(or)") } /// 使用DispatchSource创建定时器 @objc func useDispatchSourceTimer() { let queue = globalQueue() let source = DispatchSource.makeTimerSource(queue: queue) // deadline 结束时间 // interval 时间间隔 // leeway 时间精度 // source.schedule(deadline: .now(), leeway: .nanoseconds(0)) source.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(0)) // source.scheduleRepeating(deadline: .now(), interval: 1, leeway: .nanoseconds(0)) var timeout = 10 //倒计时时间 //设置要处理的事件, 在我们上面创建的queue队列中进行执行 source.setEventHandler { print(Thread.current) if timeout <= 0 { source.cancel() } else { print("\(timeout)s", Date()) timeout -= 1 } } //倒计时结束的事件 source.setCancelHandler { print("倒计时结束") } source.resume() } func ended() { print("**************************结束**************************\n") } // http://www.jianshu.com/p/7efbecee6af8 /* * DISPATCH_QUEUE_PRIORITY_HIGH: .userInitiated * DISPATCH_QUEUE_PRIORITY_DEFAULT: .default * DISPATCH_QUEUE_PRIORITY_LOW: .utility * DISPATCH_QUEUE_PRIORITY_BACKGROUND: .background */ // * QOS_CLASS_USER_INTERACTIVE:User Interactive(用户交互)类的任务关乎用户体验,这类任务是需要立刻被执行的。这类任务应该用在更新 UI,处理事件,执行一些需要低延迟的轻量的任务。这种类型的任务应该要压缩到尽可能少。 // * QOS_CLASS_USER_INITIATED: User Initiated(用户发起)类是指由 UI 发起的可以异步执行的任务。当用户在等待任务返回的结果,然后才能执行下一步动作的时候可以使用这种类型。 // * QOS_CLASS_UTILITY:Utility(工具)类是指耗时较长的任务,通常会展示给用户一个进度条。这种类型应该用在大量计算,I/O 操作,网络请求,实时数据推送之类的任务。这个类是带有节能设计的。 // * QOS_CLASS_BACKGROUND:background(后台)类是指用户并不会直接感受到的任务。这个类应该用在数据预拉取,维护以及其他不需要用户交互,对时间不敏感的任务。 func globalQueue(qos: DispatchQoS.QoSClass = .default) -> DispatchQueue { return DispatchQueue.global(qos: qos) } } extension DispatchQueue { private static var _onceTracker = [String]() /** Executes a block of code, associated with a unique token, only once. The code is thread safe and will only execute the code once even in the presence of multithreaded calls. - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID - parameter block: Block to execute once */ public class func once(token: String, block: () -> Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTracker.contains(token) { return } _onceTracker.append(token) block() } } extension Int { var toEmoji: String { let dict = [ 0: "0️⃣", 1: "1️⃣", 2: "2️⃣", 3: "3️⃣", 4: "4️⃣", 5: "5️⃣", 6: "6️⃣", 7: "7️⃣", 8: "8️⃣", 9: "9️⃣", ] return dict[self] ?? self.description } } extension SecondController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return tags.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tags[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) } } extension SecondController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.tintColor = UIColor.red cell.accessoryType = .disclosureIndicator cell.textLabel?.text = tags[indexPath.section][indexPath.row].0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let tag = tags[indexPath.section][indexPath.row] print("🍀🍀🍀\(tag.0)🍀🍀🍀") print("**************************开始**************************") perform(tag.1) } }
5657cc9023e099773280f7a4f660ac96
29.91015
139
0.536255
false
false
false
false
S7Vyto/TouchVK
refs/heads/master
TouchVK/TouchVK/Services/Network/NetworkService.swift
apache-2.0
1
// // NetworkService.swift // TouchVK // // Created by Sam on 07/02/2017. // Copyright © 2017 Semyon Vyatkin. All rights reserved. // import Foundation import UIKit import RxSwift import RealmSwift enum NetworkError: Error { case responseMalformed case responseStatusCode(code: Int) case unknownError(Error) } class NetworkService { private let url: URL init(url: URL) { self.url = url } private func data(for urlResourse: URLResource) -> Observable<Data> { let request = urlResourse.request(with: url) return Observable.create({ (observer) -> Disposable in UIApplication.shared.isNetworkActivityIndicatorVisible = true let session = NetworkSession.shared.session let task = session.dataTask(with: request as URLRequest, completionHandler: { (jsonData, responseUrl, responseError) in if let error = responseError { observer.onError(NetworkError.unknownError(error)) } else { guard let httpResponse = responseUrl as? HTTPURLResponse else { observer.onError(NetworkError.responseMalformed) return } if 200 ..< 300 ~= httpResponse.statusCode { observer.onNext(jsonData ?? Data()) observer.onCompleted() } else { observer.onError(NetworkError.responseStatusCode(code: httpResponse.statusCode)) } } }) task.resume() return Disposables.create(with: { task.cancel() }) }) } func responseObjects<T: ParserService>(for urlResourse: URLResource) -> Observable<[T]> { return data(for: urlResourse) .observeOn(MainScheduler.instance) .do(onNext: { _ in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) .map({ data in guard let objects: [T] = data.decode() else { throw NetworkError.responseMalformed } return objects }) } }
7751b8028c2535f1d1f890bbb01cd380
36.594937
132
0.424242
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/BottomSheet/BottomSheetViewController.swift
mpl-2.0
1
/* 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 UIKit import SnapKit import Shared enum BottomSheetState { case none case partial case full } protocol BottomSheetDelegate { func closeBottomSheet() func showBottomToolbar() } class BottomSheetViewController: UIViewController, Themeable { // Delegate var delegate: BottomSheetDelegate? private var currentState: BottomSheetState = .none private var isLandscape: Bool { return UIApplication.shared.statusBarOrientation.isLandscape } private var orientationBasedHeight: CGFloat { return isLandscape ? DeviceInfo.screenSizeOrientationIndependent().width : DeviceInfo.screenSizeOrientationIndependent().height } // shows how much bottom sheet should be visible // 1 = full, 0.5 = half, 0 = hidden // and for landscape we show 0.5 specifier just because of very small height private var heightSpecifier: CGFloat { let height = orientationBasedHeight let heightForTallScreen: CGFloat = height > 850 ? 0.65 : 0.74 var specifier = height > 668 ? heightForTallScreen : 0.84 if isLandscape { specifier = 0.5 } return specifier } private var navHeight: CGFloat { return navigationController?.navigationBar.frame.height ?? 0 } private var fullHeight: CGFloat { return orientationBasedHeight - navHeight } private var partialHeight: CGFloat { return fullHeight * heightSpecifier } private var maxY: CGFloat { return fullHeight - partialHeight } private var minY: CGFloat { return orientationBasedHeight } private var endedYVal: CGFloat = 0 private var endedTranslationYVal: CGFloat = 0 // Container child view controller var containerViewController: UIViewController? // Views private var overlay: UIView = { let view = UIView() view.backgroundColor = UIColor.black.withAlphaComponent(0.50) return view }() private var panView: UIView = { let view = UIView() return view }() // MARK: Initializers init() { super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() roundViews() initialViewSetup() applyTheme() } // MARK: View setup private func initialViewSetup() { self.view.backgroundColor = .clear self.view.addSubview(overlay) overlay.snp.makeConstraints { make in make.edges.equalToSuperview() make.centerX.equalToSuperview() } self.view.addSubview(panView) panView.snp.makeConstraints { make in make.bottom.equalTo(self.view.safeArea.bottom) make.centerX.equalToSuperview() make.left.right.equalToSuperview() make.height.equalTo(fullHeight) } let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(panGesture)) panView.addGestureRecognizer(gesture) panView.translatesAutoresizingMaskIntoConstraints = true let overlayTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.hideViewWithAnimation)) overlay.addGestureRecognizer(overlayTapGesture) hideView(shouldAnimate: false) } private func roundViews() { panView.layer.cornerRadius = 10 view.clipsToBounds = true panView.clipsToBounds = true } // MARK: Bottomsheet swipe methods private func moveView(state: BottomSheetState) { self.currentState = state let yVal = state == .full ? navHeight : state == .partial ? maxY : minY panView.frame = CGRect(x: 0, y: yVal, width: view.frame.width, height: fullHeight) } private func moveView(panGestureRecognizer recognizer: UIPanGestureRecognizer) { let translation = recognizer.translation(in: view) let yVal: CGFloat = translation.y let startedYVal = endedTranslationYVal + maxY let newYVal = currentState == .full ? navHeight + yVal : startedYVal + yVal let downYShiftSpecifier: CGFloat = isLandscape ? 0.3 : 0.2 // top guard newYVal >= navHeight else { endedTranslationYVal = 0 return } // move the frame according to pan gesture panView.frame = CGRect(x: 0, y: newYVal, width: view.frame.width, height: fullHeight) if recognizer.state == .ended { self.endedTranslationYVal = 0 // moving down if newYVal > self.maxY { // past middle if newYVal > self.maxY + (self.partialHeight * downYShiftSpecifier) { hideView(shouldAnimate: true) } else { self.moveView(state: .partial) } // moving up } else if newYVal < self.maxY { self.showFullView(shouldAnimate: true) } } } @objc func hideView(shouldAnimate: Bool) { let closure = { self.moveView(state: .none) self.view.isUserInteractionEnabled = true } guard shouldAnimate else { closure() self.overlay.alpha = 0 self.view.isHidden = true delegate?.showBottomToolbar() return } self.view.isUserInteractionEnabled = false UIView.animate(withDuration: 0.25) { closure() self.overlay.alpha = 0 } completion: { value in if value { self.view.isHidden = true self.delegate?.showBottomToolbar() self.containerViewController?.view.removeFromSuperview() } } } @objc func showView() { if let container = containerViewController { panView.addSubview(container.view) } UIView.animate(withDuration: 0.26, animations: { self.moveView(state: self.isLandscape ? .full : .partial) self.overlay.alpha = 1 self.view.isHidden = false }) } func showFullView(shouldAnimate: Bool) { let closure = { self.moveView(state: .full) self.overlay.alpha = 1 self.view.isHidden = false } guard shouldAnimate else { closure() return } UIView.animate(withDuration: 0.26, animations: { closure() }) } @objc private func panGesture(_ recognizer: UIPanGestureRecognizer) { moveView(panGestureRecognizer: recognizer) } @objc private func hideViewWithAnimation() { hideView(shouldAnimate: true) } func applyTheme() { if ThemeManager.instance.currentName == .normal { panView.backgroundColor = UIColor(rgb: 0xF2F2F7) } else { panView.backgroundColor = UIColor(rgb: 0x1C1C1E) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in let orient = UIApplication.shared.statusBarOrientation switch orient { case .portrait: self.moveView(state: .partial) case .landscapeLeft, .landscapeRight: self.moveView(state: .full) default: print("orientation not supported") } }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in self.view.setNeedsLayout() self.view.layoutIfNeeded() self.containerViewController?.view.setNeedsLayout() }) } }
75a3af7aa805a5690b0f0cf2751f877b
32.180723
135
0.609053
false
false
false
false
j13244231/BlackDesertNote
refs/heads/master
GameNote/Dish.swift
mit
1
// // Dish.swift // GameNote // // Created by 劉進泰 on 2017/6/26. // Copyright © 2017年 劉進泰. All rights reserved. // import Foundation import Firebase class Dish:NSObject, NSCoding { private var _dishRef:DatabaseReference! //MARK: Types struct PropertyKey { static let key:String = "key" static let dictionary:String = "dictionary" } //MARK: Archiving Paths static let DocumentsDirectory:URL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("dishs") private var _dishKey:String! private var _dishName:String! private var _dishDifficulty:String! private var _dishMaterial:[String]! private var _materialAmount:[Int]! private var _dictionary:Dictionary<String, AnyObject>! var dishKey:String { return _dishKey } var dishName:String { return _dishName } var dishDifficulty:String { return _dishDifficulty } var dishMaterial:[String] { return _dishMaterial } var materialAmount:[Int] { return _materialAmount } var dictionary:Dictionary<String, AnyObject> { return _dictionary } init(key:String, dictionary:Dictionary<String, AnyObject>) { self._dishKey = key self._dictionary = dictionary if let dishName = dictionary["名稱"] as? String { self._dishName = dishName } if let dishDifficulty = dictionary["難度"] as? String { self._dishDifficulty = dishDifficulty } if let dishMaterial = dictionary["材料"] as? [String] { self._dishMaterial = dishMaterial } if let materialAmount = dictionary["材料數量"] as? [Int] { self._materialAmount = materialAmount } self._dishRef = Database.database().reference().child("料理").child(key) } //MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(dishKey, forKey: PropertyKey.key) aCoder.encode(dictionary, forKey: PropertyKey.dictionary) } required convenience init?(coder aDecoder: NSCoder) { guard let key = aDecoder.decodeObject(forKey: PropertyKey.key) as? String else { print("解碼 key 失敗!") return nil } guard let dictionary = aDecoder.decodeObject(forKey: PropertyKey.dictionary) as? Dictionary<String, AnyObject> else { print("解碼 dictionary 失敗!") return nil } self.init(key: key, dictionary: dictionary) } }
9eac1bfac35360656573c0406c538c92
26.530612
125
0.604893
false
false
false
false
elationfoundation/Reporta-iOS
refs/heads/master
IWMF/Modal/Circle.swift
gpl-3.0
1
// // Circle.swift // IWMF // // This class is used for Store circle detail. // // import Foundation enum CircleType: Int { case Private = 1 case Public = 2 case Social = 3 } class Circle: NSObject { var circleName: String! var circleType: CircleType! var contactsList: NSMutableArray! override init() { circleName = "" circleType = .Private contactsList = NSMutableArray() super.init() } init(name:String, type:CircleType, contactList:NSMutableArray ){ self.circleName = name; circleType = type; contactsList = contactList super.init() } required init(coder aDecoder: NSCoder) { self.circleName = aDecoder.decodeObjectForKey("circleName") as! String self.contactsList = aDecoder.decodeObjectForKey("contactsList") as! NSMutableArray let circleTypeValue = Int(aDecoder.decodeObjectForKey("circleType") as! NSNumber) if circleTypeValue == 1 { self.circleType = CircleType.Private } else if circleTypeValue == 2 { self.circleType = CircleType.Public } else if circleTypeValue == 3 { self.circleType = CircleType.Social } } func encodeWithCoder(aCoder: NSCoder) { if let circleName = self.circleName{ aCoder.encodeObject(circleName, forKey: "circleName") } if let contactsList = self.contactsList{ aCoder.encodeObject(contactsList, forKey: "contactsList") } let circleTypeValue = NSNumber(integer: self.circleType.rawValue) aCoder.encodeObject(circleTypeValue, forKey: "circleType") } func insertContactsListInCircle(conList: ContactList){ self.contactsList.addObject(conList) } }
beb603eae722021aa535c58f9f28859e
26.746269
91
0.617869
false
false
false
false
cxk1992/Bonjour
refs/heads/master
Bonjour/ViewController.swift
mit
1
// // ViewController.swift // Bonjour // // Created by 陈旭珂 on 2016/8/16. // Copyright © 2016年 陈旭珂. All rights reserved. // import UIKit class ViewController: UIViewController , UITextFieldDelegate { var handler : ConnectHandler?{ didSet{ handler?.dataReceiveClouser = { (data:Data ,handler:ConnectHandler) in let message = String(data: data, encoding: String.Encoding.utf8) let messageh = Message() messageh.type = .fromOther messageh.message = message self.dataSource.append(messageh) self.tableView.reloadData() } self.dataSource = (handler?.messages)! self.tableView.reloadData() } } var name = "viewController"{ didSet{ titleLabel.text = name } } var dataSource : [Message] = [] let tableView = UITableView(frame: CGRect(), style: .plain) let textField = UITextField() let titleLabel = { () -> UILabel in let label = UILabel() label.textAlignment = .center return label }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.white titleLabel.frame = CGRect(x: 0, y: 20, width: view.bounds.size.width, height: 30) titleLabel.autoresizingMask = [.flexibleWidth,.flexibleHeight] view.addSubview(titleLabel) view.addSubview(tableView) tableView.frame = CGRect(x: 0, y: 50, width: view.bounds.size.width, height: view.bounds.size.height - 80) tableView.delegate = self tableView.dataSource = self tableView.autoresizingMask = [.flexibleWidth,.flexibleHeight] textField.frame = CGRect(x: 0, y: view.bounds.size.height - 50, width: view.bounds.size.width, height: 30) textField.autoresizingMask = [.flexibleTopMargin,.flexibleWidth] textField.delegate = self textField.borderStyle = .roundedRect view.addSubview(textField) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.text?.characters.count != 0{ handler?.send(data: (textField.text?.data(using: .utf8))!) let message = Message() message.message = textField.text self.dataSource.append(message) self.tableView.reloadData() textField.text = "" } textField.resignFirstResponder() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print(#function) } deinit { print(#function) } } extension ViewController : UITableViewDelegate , UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "cell") cell?.detailTextLabel?.textColor = .black cell?.textLabel?.textColor = .black } let message = dataSource[indexPath.row] if message.type == .fromOther { cell?.textLabel?.text = message.message }else{ cell?.detailTextLabel?.text = message.message } return cell! } }
5d4a4cc208edfd6512f16891e5acf6de
29.992188
114
0.594908
false
false
false
false
WestlakeAPC/game-off-2016
refs/heads/master
external/Fiber2D/Fiber2D/PhysicsContact.swift
apache-2.0
1
// // PhysicsContact.swift // Fiber2D // // Created by Andrey Volodin on 22.09.16. // Copyright © 2016 s1ddok. All rights reserved. // import SwiftMath public enum EventCode { case none, begin, presolve, postsolve, separate } /** * An object that implements the PhysicsContactDelegate protocol can respond * when two physics bodies are in contact with each other in a physics world. * To receive contact messages, you set the contactDelegate property of a PhysicsWorld object. * The delegate is called when a contact starts or ends. */ public protocol PhysicsContactDelegate: class { /** Called when two bodies first contact each other. */ func didBegin(contact: PhysicsContact) /** Called when the contact ends between two physics bodies. */ func didEnd(contact: PhysicsContact) } public struct PhysicsContactData { let points: [Point] let normal: Vector2f } /** * @brief Contact information. * It will be created automatically when two shape contact with each other. * And it will be destroyed automatically when two shape separated. */ public struct PhysicsContact { /** Get contact shape A. */ public unowned var shapeA: PhysicsShape /** Get contact shape B. */ public unowned var shapeB: PhysicsShape /** Get contact data */ public var contactData: PhysicsContactData /** Get previous contact data */ //public let previousContactData: PhysicsContactData internal let arbiter: UnsafeMutablePointer<cpArbiter>! internal init(shapeA: PhysicsShape, shapeB: PhysicsShape, arb: UnsafeMutablePointer<cpArbiter>!) { self.shapeA = shapeA self.shapeB = shapeB self.arbiter = arb let count = cpArbiterGetCount(arb) var points = [Point](repeating: Point.zero, count: Int(count)) for i in 0..<count { points[Int(i)] = Point(cpArbiterGetPointA(arb, i)) } let normal = count == 0 ? vec2.zero : vec2(cpArbiterGetNormal(arb)) self.contactData = PhysicsContactData(points: points, normal: normal) } } /** * @brief Presolve value generated when onContactPreSolve called. */ public struct PhysicsContactPreSolve { /** Get elasticity between two bodies.*/ let elasticity: Float /** Get friction between two bodies.*/ let friction: Float /** Get surface velocity between two bodies.*/ let surfaceVelocity: Vector2f internal var contactInfo: OpaquePointer /** Ignore the rest of the contact presolve and postsolve callbacks. */ func ignore() { } } /** * @brief Postsolve value generated when onContactPostSolve called. */ public struct PhysicsContactPostSolve { /** Get elasticity between two bodies.*/ let elasticity: Float /** Get friction between two bodies.*/ let friction: Float /** Get surface velocity between two bodies.*/ let surfaceVelocity: Vector2f internal var contactInfo: OpaquePointer }
6936ec9e421ada4de2cf37c066c3baea
28.84
102
0.689678
false
false
false
false
Rochester-Ting/DouyuTVDemo
refs/heads/master
RRDouyuTV/RRDouyuTV/Classes/Tools(工具)/NetworkTools.swift
mit
1
// // NetworkTools.swift // RRDouyuTV // // Created by 丁瑞瑞 on 13/10/16. // Copyright © 2016年 Rochester. All rights reserved. // import UIKit import Alamofire enum MethodType { case GET case POST } class NetworkTools { class func requestData(type : MethodType,urlString : String ,paramters : [String : NSString]? = nil,finishedCallBack : @escaping (_ result : AnyObject)->()) { let methodType = type == .GET ? HTTPMethod.get : HTTPMethod.post Alamofire.request(urlString, method: methodType, parameters: paramters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in guard let result = response.result.value else{ print(response.result.error) return } finishedCallBack(result as AnyObject) } } }
6de8de34fb053a95c70297dc74ba65e2
26.580645
162
0.62807
false
false
false
false
BlakeBarrett/wndw
refs/heads/master
wtrmrkr/VideoPreviewPlayerViewController.swift
mit
1
// // VideoPreviewPlayerViewController.swift // wndw // // Created by Blake Barrett on 6/9/16. // Copyright © 2016 Blake Barrett. All rights reserved. // import Foundation import AVFoundation import AVKit class VideoPreviewPlayerViewController: UIViewController { var url :NSURL? var player :AVPlayer? override func viewDidLoad() { guard let url = url else { return } self.player = AVPlayer(URL: url) let playerController = AVPlayerViewController() playerController.player = player self.addChildViewController(playerController) self.view.addSubview(playerController.view) playerController.view.frame = self.view.frame } override func viewDidAppear(animated: Bool) { player?.play() } }
a861c998456acf8b0deb190927b99756
24.09375
58
0.673724
false
false
false
false
NikolaiRuhe/SwiftDigest
refs/heads/master
SwiftDigestTests/MD5DigestTests.swift
mit
1
import SwiftDigest import XCTest class MD5Tests: XCTestCase { func testEmpty() { XCTAssertEqual( Data().md5, MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e") ) } func testData() { XCTAssertEqual( MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")?.data, Data([212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126,]) ) } func testBytes() { XCTAssertEqual( "\(MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!.bytes)", "(212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126)" ) } func testFox1() { let input = "The quick brown fox jumps over the lazy dog" XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "9e107d9d372bb6826bd81d3542a419d6") ) } func testFox2() { let input = "The quick brown fox jumps over the lazy dog." XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "e4d909c290d0fb1ca068ffaddf22cbd0") ) } func testTwoFooterChunks() { let input = Data(count: 57) XCTAssertEqual( input.md5, MD5Digest(rawValue: "ab9d8ef2ffa9145d6c325cefa41d5d4e") ) } func test4KBytes() { var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100) XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "7052292b1c02ae4b0b35fabca4fbd487") ) } func test4MBytes() { var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100000) XCTAssertEqual( input.utf8.md5, MD5Digest(rawValue: "f8a4ffa8b1c902f072338caa1e4482ce") ) } func testRecursive() { XCTAssertEqual( "".utf8.md5.description.utf8.md5.description.utf8.md5.description.utf8.md5, MD5Digest(rawValue: "5a8dccb220de5c6775c873ead6ff2e43") ) } func testEncoding() { let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")! let json = String(bytes: try! JSONEncoder().encode([sut]), encoding: .utf8)! XCTAssertEqual(json, "[\"\(sut)\"]") } func testDecoding() { let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")! let json = Data("[\"\(sut)\"]".utf8) let digest = try! JSONDecoder().decode(Array<MD5Digest>.self, from: json).first! XCTAssertEqual(digest, sut) } }
a4ed55ae9917bda6c2bcf849d68bc656
28.873563
100
0.586764
false
true
false
false
ThunderStruct/MSCircularSlider
refs/heads/master
MSCircularSliderExample/MSCircularSliderExample/SliderPropertiesVC.swift
mit
1
// // SliderPropertiesVC.swift // MSCircularSliderExample // // Created by Mohamed Shahawy on 10/2/17. // Copyright © 2017 Mohamed Shahawy. All rights reserved. // import UIKit class SliderProperties: UIViewController, MSCircularSliderDelegate, ColorPickerDelegate { // Outlets @IBOutlet weak var slider: MSCircularSlider! @IBOutlet weak var handleTypeLbl: UILabel! @IBOutlet weak var unfilledColorBtn: UIButton! @IBOutlet weak var filledColorBtn: UIButton! @IBOutlet weak var handleColorBtn: UIButton! @IBOutlet weak var descriptionLbl: UILabel! @IBOutlet weak var valueLbl: UILabel! // Members var currentColorPickTag = 0 var colorPicker: ColorPickerView? var animationTimer: Timer? var animationReversed = false var currentRevolutions = 0 var currentValue = 0.0 // Actions @IBAction func handleTypeValueChanged(_ sender: UIStepper) { slider.handleType = MSCircularSliderHandleType(rawValue: Int(sender.value)) ?? slider.handleType handleTypeLbl.text = handleTypeStrFrom(slider.handleType) } @IBAction func maxAngleAction(_ sender: UISlider) { slider.maximumAngle = CGFloat(sender.value) descriptionLbl.text = getDescription() } @IBAction func colorPickAction(_ sender: UIButton) { currentColorPickTag = sender.tag colorPicker?.isHidden = false } @IBAction func rotationAngleAction(_ sender: UISlider) { descriptionLbl.text = getDescription() if sender.value == 0 { slider.rotationAngle = nil return } slider.rotationAngle = CGFloat(sender.value) } @IBAction func lineWidthAction(_ sender: UIStepper) { slider.lineWidth = Int(sender.value) descriptionLbl.text = getDescription() } // Init override func viewDidLoad() { super.viewDidLoad() handleTypeLbl.text = handleTypeStrFrom(slider.handleType) colorPicker = ColorPickerView(frame: CGRect(x: 0, y: view.center.y - view.frame.height * 0.3 / 2.0, width: view.frame.width, height: view.frame.height * 0.3)) colorPicker?.isHidden = true colorPicker?.delegate = self slider.delegate = self currentValue = slider.currentValue valueLbl.text = String(format: "%.1f", currentValue) descriptionLbl.text = getDescription() view.addSubview(colorPicker!) } override func viewDidAppear(_ animated: Bool) { // Slider animation animateSlider() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Support Methods func handleTypeStrFrom(_ type: MSCircularSliderHandleType) -> String { switch type { case .smallCircle: return "Small Circle" case .mediumCircle: return "Medium Circle" case .largeCircle: return "Large Circle" case .doubleCircle: return "Double Circle" } } func directionToString(_ direction: MSCircularSliderDirection) -> String { return direction == .none ? "None" : (direction == .clockwise ? "Clockwise" : "Counter-Clockwise") } func getDescription(_ sliderDirection: MSCircularSliderDirection = .none) -> String { let rotationAngle = slider.rotationAngle == nil ? "Computed" : String(format: "%.1f", slider.rotationAngle!) + "°" return "Maximum Angle: \(String(format: "%.1f", slider.maximumAngle))°\nLine Width: \(slider.lineWidth)\nRotation Angle: \(rotationAngle)\nSliding Direction: " + directionToString(sliderDirection) } // Delegate Methods func circularSlider(_ slider: MSCircularSlider, valueChangedTo value: Double, fromUser: Bool) { currentValue = value if !slider.endlesslyLoops || !slider.fullCircle { valueLbl.text = String(format: "%.1f\nx%d", currentValue, currentRevolutions + 1) } else { valueLbl.text = String(format: "%.1f", currentValue) } } func circularSlider(_ slider: MSCircularSlider, startedTrackingWith value: Double) { // optional delegate method } func circularSlider(_ slider: MSCircularSlider, endedTrackingWith value: Double) { // optional delegate method } func circularSlider(_ slider: MSCircularSlider, directionChangedTo value: MSCircularSliderDirection) { descriptionLbl.text = getDescription(value) } func circularSlider(_ slider: MSCircularSlider, revolutionsChangedTo value: Int) { currentRevolutions = value valueLbl.text = String(format: "%.1f\nx%d", currentValue, currentRevolutions + 1) } func colorPickerTouched(sender: ColorPickerView, color: UIColor, point: CGPoint, state: UIGestureRecognizer.State) { switch currentColorPickTag { case 0: unfilledColorBtn.setTitleColor(color, for: .normal) slider.unfilledColor = color case 1: filledColorBtn.setTitleColor(color, for: .normal) slider.filledColor = color case 2: handleColorBtn.setTitleColor(color, for: .normal) slider.handleColor = color default: break } colorPicker?.isHidden = true } func animateSlider() { animationTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateSliderValue), userInfo: nil, repeats: true) } @objc func updateSliderValue() { slider.currentValue += animationReversed ? -1.0 : 1.0 if slider.currentValue >= slider.maximumValue { animationTimer?.invalidate() // Reverse animation animationReversed = true animationTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateSliderValue), userInfo: nil, repeats: true) } else if slider.currentValue <= slider.minimumValue && animationReversed { // Animation ended animationTimer?.invalidate() } } }
d589db9d626fe5db1c271b6a27d041fe
34.559322
204
0.640769
false
false
false
false
sunweifeng/SWFKit
refs/heads/master
Example/SWFKit/TestPresentViewController.swift
mit
1
// // TestPresentViewController.swift // TestApp // // Created by 孙伟峰 on 2017/6/19. // Copyright © 2017年 Sun Weifeng. All rights reserved. // import UIKit import SWFKit class TestPresentViewController: UIViewController, UIViewControllerTransitioningDelegate { lazy var closeBtn: UIButton = { let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) btn.setTitle("Close", for: .normal) btn.setTitleColor(UIColor.purple, for: .normal) btn.addTarget(self, action: #selector(self.close), for: .touchUpInside) return btn }() lazy var contentView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) view.backgroundColor = UIColor.white view.center = self.view.center return view }() func close() { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.contentView.addSubview(closeBtn) self.view.addSubview(contentView) // Do any additional setup after loading the view. } func commonInit() { self.modalPresentationStyle = .custom self.transitioningDelegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.commonInit() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { if presented == self { return SWFPresentationController(presentedViewController: presented, presenting: presenting) } return nil } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { if presented == self { return SWFControllerAnimatedTransitioning(isPresenting: true) } return nil } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { if dismissed == self { return SWFControllerAnimatedTransitioning(isPresenting: false) } return nil } }
c2cc249a3f9dbcf4c14130ef5789bb2f
31.825
170
0.66032
false
false
false
false
XeresRazor/SwiftRaytracer
refs/heads/master
src/pathtracer/Traceable.swift
mit
1
// // Traceable.swift // Raytracer // // Created by David Green on 4/6/16. // Copyright © 2016 David Green. All rights reserved. // import simd public struct HitRecord { var time: Double var point: double4 var normal: double4 var u: Double var v: Double var material: Material? init() { time = 0 point = double4() normal = double4() u = 0.0 v = 0.0 } init(_ t: Double, _ p: double4, _ n: double4, u newU: Double = 0.0, v newV: Double = 0.0) { time = t point = p normal = n u = newU v = newV } } public class Traceable { public func trace(r: Ray, minimumT tMin: Double, maximumT tMax: Double) -> HitRecord? { fatalError("trace() must be overridden") } public func boundingBox(t0: Double, t1: Double) -> AABB? { fatalError("boundingBox() must be overridden") } }
3901606c5fe3f3fd3164eecc1d257691
17.454545
92
0.635468
false
false
false
false
iWeslie/Ant
refs/heads/master
Ant/Ant/LunTan/SendOutVC/Photo/PicPickerViewCell.swift
apache-2.0
2
// // PicPickerViewCell.swift // Ant // // Created by LiuXinQiang on 2017/7/12. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit class PicPickerViewCell: UICollectionViewCell { //MARK: - 控件的属性 @IBOutlet weak var addPhotoBtn: UIButton! @IBOutlet weak var removePhotoBtn: UIButton! @IBOutlet weak var imageView: UIImageView! // MARK:- 定义属性 var image : UIImage? { didSet { if image != nil { imageView.image = image addPhotoBtn.isUserInteractionEnabled = false removePhotoBtn.isHidden = false } else { imageView.image = nil addPhotoBtn.isUserInteractionEnabled = true removePhotoBtn.isHidden = true } } } // 事件监听 @IBAction func addPhotoClick(_ sender: Any) { print("addPhotoClic") NotificationCenter.default.post(name: PicPickerAddPhotoNote , object: nil) } @IBAction func removePhotoClick(_ sender: Any) { NotificationCenter.default.post(name: PicPickerRemovePhotoNote, object: sender) } }
6c4d8ccde423dab48211c341f3062aa2
23.520833
87
0.593883
false
false
false
false
AxziplinLib/TabNavigations
refs/heads/master
TabNavigations/Classes/Generals/ViewControllers/TableViewController.swift
apache-2.0
1
// // TableViewController.swift // AxReminder // // Created by devedbox on 2017/6/28. // Copyright © 2017年 devedbox. All rights reserved. // import UIKit class TableViewController: UITableViewController { fileprivate lazy var _backgroundFilterView: UIView = UIView() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() viewDidLoadSetup() print(String(describing: type(of: self)) + " " + #function) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() _backgroundFilterView.frame = CGRect(x: 0.0, y: min(0.0, tableView.contentOffset.y), width: tabNavigationController?.tabNavigationBar.bounds.width ?? 0.0, height: tabNavigationController?.tabNavigationBar.bounds.height ?? 0.0) } public func viewDidLoadSetup() { tableView.insertSubview(_backgroundFilterView, at: 0) _backgroundFilterView.backgroundColor = .white tabNavigationController?.tabNavigationBar.isTranslucent = true } #if swift(>=4.0) #else override func viewWillBeginInteractiveTransition() { print(String(describing: type(of: self)) + " " + #function) } override func viewDidEndInteractiveTransition(appearing: Bool) { print(String(describing: type(of: self)) + " " + #function + " " + String(describing: appearing)) } #endif override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated)) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated)) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print(String(describing: type(of: self)) + " " + #function + " " + String(describing: animated)) } deinit { print(String(describing: type(of: self)) + " " + #function) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - UITableViewDelegate. extension TableViewController { override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20.0 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 10.0 } } // MARK: - Status Bar Supporting. extension TableViewController { override var prefersStatusBarHidden: Bool { return true } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } }
f1eadb61bfef15eb48f942ec8e965567
34.831579
234
0.658637
false
false
false
false
iyubinest/Encicla
refs/heads/master
encicla/location/Location.swift
mit
1
import CoreLocation import RxSwift protocol GPS { func locate() -> Observable<CLLocation> } class DefaultGPS: NSObject, GPS, CLLocationManagerDelegate { private var observer: AnyObserver<CLLocation>? internal func locate() -> Observable<CLLocation> { return Observable.create { observer in self.observer = observer let locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() return Disposables.create { locationManager.delegate = nil } } } internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: Array<CLLocation>) { observer?.on(.next(locations.first!)) observer?.on(.completed) } internal func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse || status == .authorizedAlways { manager.startUpdatingLocation() } else if status == .denied { observer?.on(.error(CLError(.denied))) } } }
d4060bfce3e94d342d8df4dbd07e3ce1
28.027027
70
0.716946
false
false
false
false
TG908/iOS
refs/heads/master
TUM Campus App/SearchViewController.swift
gpl-3.0
1
// // SearchViewController.swift // TUM Campus App // // Created by Mathias Quintero on 10/28/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import UIKit class SearchViewController: UITableViewController, DetailView { @IBOutlet weak var searchTextField: UITextField! { didSet { searchTextField.delegate = self } } var delegate: DetailViewDelegate? var elements = [DataElement]() var currentElement: DataElement? var searchManagers: [TumDataItems]? } extension SearchViewController: DetailViewDelegate { func dataManager() -> TumDataManager { return delegate?.dataManager() ?? TumDataManager(user: nil) } } extension SearchViewController: TumDataReceiver, ImageDownloadSubscriber { func receiveData(_ data: [DataElement]) { elements = data for element in elements { if let downloader = element as? ImageDownloader { downloader.subscribeToImage(self) } } tableView.reloadData() } func updateImageView() { tableView.reloadData() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension SearchViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string != " " { for element in elements { if let downloader = element as? ImageDownloader { downloader.clearSubscribers() } } let replaced = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string) if replaced != "" { delegate?.dataManager().search(self, query: replaced, searchIn: searchManagers) // searchManager might be set during a segue. Otherwise it defaults to all searchManagers, defined in the TumDataManager } else { elements = [] tableView.reloadData() } } return true } } extension SearchViewController { override func viewDidLoad() { searchTextField.becomeFirstResponder() tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = 102 } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) searchTextField.resignFirstResponder() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if var mvc = segue.destination as? DetailView { mvc.delegate = self } if let mvc = segue.destination as? RoomFinderViewController { mvc.room = currentElement } if let mvc = segue.destination as? PersonDetailTableViewController { mvc.user = currentElement } if let mvc = segue.destination as? LectureDetailsTableViewController { mvc.lecture = currentElement } } } extension SearchViewController { override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { currentElement = elements[indexPath.row] return indexPath } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return elements.count } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: elements[indexPath.row].getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell() cell.setElement(elements[indexPath.row]) return cell } }
8a06d2df76227a079d1045745de2712b
29.074627
216
0.634491
false
false
false
false
epv44/TwitchAPIWrapper
refs/heads/master
Sources/TwitchAPIWrapper/Models/CodeStatus.swift
mit
1
// // CodeStatus.swift // TwitchAPIWrapper // // Created by Eric Vennaro on 5/8/21. // import Foundation /// Code status response: https://dev.twitch.tv/docs/api/reference/#get-code-status public struct CodeStatusResponse: Codable { public let codeStatuses: [CodeStatus] private enum CodingKeys: String, CodingKey { case codeStatuses = "data" } } /// Code status options mirroring: https://dev.twitch.tv/docs/api/reference/#get-code-status public enum CodeSuccessStatus: String, Codable { case successfullyRedeemed = "SUCCESSFULLY_REDEEMED" case alreadyClaimed = "ALREADY_CLAIMED" case expired = "EXPIRED" case userNotEligible = "USER_NOT_ELIGIBLE" case notFound = "NOT_FOUND" case inactive = "INACTIVE" case unused = "UNUSED" case incorrectFormat = "INCORRECT_FORMAT" case internalError = "INTERNAL_ERROR" } /// Code status object returned from the server as part of the `CodeStatusResponse` https://dev.twitch.tv/docs/api/reference/#get-code-status public struct CodeStatus: Codable, Equatable { public let code: String public let status: CodeSuccessStatus }
ea9b4e86595a54ce1602052e88c9ea5e
30.472222
141
0.72286
false
false
false
false
hayasilin/Crack-the-term
refs/heads/master
SignUpViewController.swift
mit
1
// // SignUpViewController.swift // CrackTheTerm_review // // Created by Kuan-Wei Lin on 8/20/15. // Copyright (c) 2015 Kuan-Wei Lin. All rights reserved. // import UIKit class SignUpViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var signUpBtn: UIButton! @IBAction func signUp(sender: UIButton) { signUp() } func signUp(){ let user = PFUser(); user.username = usernameTextField.text user.password = passwordTextField.text user.email = emailTextField.text user.signUpInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in if error == nil{ print("Sign up successfully") //UIImagePickerController section let imagePicker: UIImagePickerController = UIImagePickerController() imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.delegate = self self.presentViewController(imagePicker, animated: true, completion: nil) let successAlertController: UIAlertController = UIAlertController(title: "註冊成功", message: "您已經成功註冊,請按下確定選擇大頭圖像", preferredStyle: UIAlertControllerStyle.Alert) let alertAction: UIAlertAction = UIAlertAction(title: "開始選擇大頭圖像", style: UIAlertActionStyle.Default, handler: nil) successAlertController.addAction(alertAction) self.presentViewController(successAlertController, animated: true, completion: nil) }else{ print("Sign up failed") print(error?.localizedDescription) let failAlertController: UIAlertController = UIAlertController(title: "註冊失敗", message: "該帳號已經有人使用了,請重新輸入", preferredStyle: UIAlertControllerStyle.Alert) let alertAction: UIAlertAction = UIAlertAction(title: "我知道了", style: UIAlertActionStyle.Default, handler: nil) failAlertController.addAction(alertAction) self.presentViewController(failAlertController, animated: true, completion: nil) } }) } //Sign Up image function func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let pickedImage: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage; //SCale down image let scaledImage = self.scaleImageWith(pickedImage, and: CGSizeMake(80, 80)) let imageData = UIImagePNGRepresentation(scaledImage) let imageFile: PFFile = PFFile(data: imageData!) PFUser.currentUser()?.setObject(imageFile, forKey: "profileImage") PFUser.currentUser()?.save() picker.dismissViewControllerAnimated(true, completion: nil) dispatch_async(dispatch_get_main_queue()){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let timelineViewController: UINavigationController = storyboard.instantiateViewControllerWithIdentifier("timelineVC") as! UINavigationController self.presentViewController(timelineViewController, animated: true, completion: nil) } } func scaleImageWith(image: UIImage, and newSize: CGSize) -> UIImage{ UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } override func viewDidLoad() { super.viewDidLoad() signUpBtn.layer.cornerRadius = 5 usernameTextField.delegate = self passwordTextField.delegate = self emailTextField.delegate = self } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
728665adac4f1a292c7ba0820a7fdf89
39.637168
174
0.660061
false
false
false
false
webventil/Kroekln
refs/heads/master
Kroekln/Kroekln/MainTableViewController.swift
mit
1
// // MainTableViewController.swift // Kroekln // // Created by Arne Tempelhof on 07.11.14. // Copyright (c) 2014 webventil. All rights reserved. // import UIKit class MainTableViewController: UITableViewController { var headerView: UIView! var headerViewMaskLayer: CAShapeLayer! var player: Player? let kTableHeaderHeight: CGFloat = 270.0 @IBOutlet weak var avatarBlurImage: UIImageView! @IBOutlet weak var avatar: UIButton! @IBOutlet weak var userName: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var winLabel: UILabel! @IBOutlet weak var losesLabel: UILabel! @IBOutlet weak var totalCount: UILabel! @IBOutlet weak var winCount: UILabel! @IBOutlet weak var losesCount: UILabel! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension headerView = tableView.tableHeaderView tableView.tableHeaderView = nil tableView.addSubview(headerView) tableView.contentInset = UIEdgeInsets(top: kTableHeaderHeight, left: 0, bottom: 0, right: 0) tableView.contentOffset = CGPoint(x: 0, y: -kTableHeaderHeight) updateHeaderView() avatar.layer.cornerRadius = 10.0 avatar.layer.borderWidth = 3.0 avatar.layer.borderColor = UIColor.whiteColor().CGColor avatar.layer.masksToBounds = false avatar.clipsToBounds = true // 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() } func updatePlayer() { player = DatabaseManager.shared().getPlayer() if let userAvatar = player?.avatar { avatar.setImage(UIImage(data: userAvatar), forState: UIControlState.Normal) var blurredImage = UIImage(data: userAvatar)?.applyLightEffect() avatarBlurImage.image = blurredImage } if let name = player?.name { userName.text = "Hallo \(name)!" } } func updateHeaderView(){ var headerRect = CGRect(x: 0, y: -kTableHeaderHeight, width: tableView.bounds.width, height: kTableHeaderHeight) if tableView.contentOffset.y < -kTableHeaderHeight { headerRect.origin.y = tableView.contentOffset.y headerRect.size.height = -tableView.contentOffset.y } headerView.frame = headerRect } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition({ (context) -> Void in [self] self.updateHeaderView() self.tableView.reloadData() }, completion: { (context) -> Void in }) } override func scrollViewDidScroll(scrollView: UIScrollView) { updateHeaderView() } override func viewWillAppear(animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) updatePlayer() } override func viewWillDisappear(animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: true) } 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 Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 NO 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. } */ }
4e2af6ec2c9c2a1450c0441705e33d35
33.091954
156
0.696224
false
false
false
false
CNKCQ/oschina
refs/heads/master
OSCHINA/Extensions/UIViewController+Preparation.swift
mit
1
// // UIViewController+Preparation.swift // OSCHINA // // Created by KingCQ on 2017/3/31. // Copyright © 2017年 KingCQ. All rights reserved. // private func swizzle(_ cls: UIViewController.Type) { [ (#selector(cls.viewDidLoad), #selector(cls.os_viewDidLoad)), (#selector(cls.viewWillAppear(_:)), #selector(cls.os_viewWillAppear(_:))) ].forEach { original, swizzled in let originalMethod = class_getInstanceMethod(cls, original) let swizzledMethod = class_getInstanceMethod(cls, swizzled) let didAddswizzledMethod = class_addMethod(cls, original, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) if didAddswizzledMethod { class_replaceMethod(cls, swizzled, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) } else { method_exchangeImplementations(originalMethod, swizzledMethod) } } } extension UIViewController { open override class func initialize() { guard self === UIViewController.self else { return } swizzle(self) } internal func os_viewDidLoad() { os_viewDidLoad() print("你好,\(#function)") } internal func os_viewWillAppear(_ animated: Bool) { os_viewWillAppear(animated) print("你好,\(#function)") } }
eb2732c5091a454ccb688d12e44a7240
32
147
0.669623
false
false
false
false
downie/swift-daily-programmer
refs/heads/master
SwiftDailyChallenge.playground/Pages/267 - Places.xcplaygroundpage/Contents.swift
mit
1
/*: # [2016-05-16] Challenge #267 [Easy] All the places your dog didn't win Published on: 2016-05-16\ Difficulty: Easy\ [reddit link](https://www.reddit.com/r/dailyprogrammer/comments/4jom3a/20160516_challenge_267_easy_all_the_places_your/) */ func suffix(place : Int) -> String { switch place { case 11, 12, 13: // These are the weird little exceptions. return "th" case 0..<100 where place % 10 == 1: return "st" case 0..<100 where place % 10 == 2: return "nd" case 0..<100 where place % 10 == 3: return "rd" case place where place >= 100: return suffix(place-100) default: // This is by far the most common return "th" } } func namePlace(place: Int) -> String { return "\(place)\(suffix(place))" } func allPlaces(to to: Int, from: Int = 1, except : Int? = nil) -> String { var range = Array(from...to) if let exceptPlace = except { range = range.filter { $0 != exceptPlace } } return range.map(namePlace).joinWithSeparator(", ") } // Testing allPlaces(to: 10) == "1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th" allPlaces(to: 10, except: 3) == "1st, 2nd, 4th, 5th, 6th, 7th, 8th, 9th, 10th" allPlaces(to: 20, from: 10) == "10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th" allPlaces(to: 110, from: 100) == "100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th" allPlaces(to: 116, from: 110, except: 115) == "110th, 111th, 112th, 113th, 114th, 116th" //: [Table of Contents](Table%20of%20Contents)
1085919180ad126f06129b3200afb64e
30.72
121
0.611602
false
false
false
false
anyflow/Jonsnow
refs/heads/master
Jonsnow/ViewController/ChattingTableViewController.swift
apache-2.0
1
// // ChattingTableViewController.swift // Jonsnow // // Created by Park Hyunjeong on 12/15/15. // Copyright © 2015 Anyflow. All rights reserved. // import UIKit class ChattingTableViewController: UITableViewController { let logger: Logger = Logger(className: ChattingTableViewController.self.description()) override func viewDidLoad() { super.viewDidLoad() self.clearsSelectionOnViewWillAppear = false self.navigationItem.leftBarButtonItem = self.editButtonItem() self.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor() } 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. } */ }
645f7b86f36cbdb3dd7bbadf9724ea7a
32.863158
157
0.689462
false
false
false
false
juliangrosshauser/MapsPlayground
refs/heads/master
Maps.playground/Contents.swift
mit
1
import CoreLocation import MapKit import XCPlayground /*: # Get current location Based on Apple's ["Getting the User’s Location"](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW1) */ class LocationManager: NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() var currentLocation: CLLocation? override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyKilometer locationManager.distanceFilter = 500 locationManager.startUpdatingLocation() } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) { let location = locations.last as! CLLocation let eventDate = location.timestamp let timeSinceEvent = eventDate.timeIntervalSinceNow if abs(timeSinceEvent) < 15 { print("Current location: latitude = \(location.coordinate.latitude), longitude = \(location.coordinate.longitude)") currentLocation = location } } } let locationManager = LocationManager() /*: # Display location in map view Based on Apple's ["Displaying Maps"](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/MapKit/MapKit.html#//apple_ref/doc/uid/TP40009497-CH3-SW1) */ let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) // show New York in map view mapView.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: 40.7141667, longitude: -74.0063889), 5000, 5000) XCPShowView("Map View", view: mapView)
59c3dbd1019e3611c75792866ee9fe8d
34.12
219
0.735763
false
false
false
false
ismailgulek/IGPagerView
refs/heads/master
IGPagerViewDemo/ViewController.swift
mit
1
// // ViewController.swift // IGPagerViewDemo // // Created by Ismail GULEK on 19/03/2017. // Copyright © 2017 Ismail Gulek. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var pagerView: IGPagerView! { didSet { pagerView.dataSource = self pagerView.delegate = self } } @IBOutlet weak var segmentedControl: UISegmentedControl! @IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) { pagerView.goToPage(sender.selectedSegmentIndex) } } extension ViewController: IGPagerViewDataSource { func pagerViewNumberOfPages(_ pager: IGPagerView) -> Int { return 3 } func pagerView(_ pager: IGPagerView, viewAt index: Int) -> UIView { if index == 0 { let view = UIView() view.backgroundColor = UIColor.red return view } else if index == 1 { let view = UIView() view.backgroundColor = UIColor.green return view } else { let view = UIView() view.backgroundColor = UIColor.blue return view } } } extension ViewController: IGPagerViewDelegate { func pagerView(_ pager: IGPagerView, didScrollToPageAt index: Int) { print("Index: \(index)") segmentedControl.selectedSegmentIndex = index } }
dcbeacaedfce66143d07db30c37e97bc
20.438596
76
0.713584
false
false
false
false
arbitur/Func
refs/heads/master
source/UI/Dialogs/SheetDialog.swift
mit
1
// // SheetDialog.swift // Pods // // Created by Philip Fryklund on 24/Apr/17. // // import UIKit public typealias SheetDialog = SheetDialogController // For backwards compatibility open class SheetDialogController: ActionDialogController { private let contentStackView = UIStackView(axis: .vertical) open override var contentView: UIView { return contentStackView } fileprivate var cancelActionView: UIView? override open class func makeTitleLabel() -> UILabel { let font = UIFont.boldSystemFont(ofSize: 13) let color = UIColor(white: 0.56, alpha: 1) return UILabel(font: font , color: color, alignment: .center, lines: 0) } override open class func makeSubtitleLabel() -> UILabel { let font = UIFont.systemFont(ofSize: 13) let color = UIColor(white: 0.56, alpha: 1) return UILabel(font: font, color: color, alignment: .center, lines: 0) } open override class func makeActionButton(for type: DialogActionType) -> UIButton { let color: UIColor let font: UIFont switch type { case .normal: color = UIColor(red: 0.0, green: 0.48, blue: 1.00, alpha: 1.0) ; font = UIFont.systemFont(ofSize: 20) case .delete: color = UIColor(red: 1.0, green: 0.23, blue: 0.19, alpha: 1.0) ; font = UIFont.systemFont(ofSize: 20) case .cancel: color = UIColor(red: 0.0, green: 0.48, blue: 1.00, alpha: 1.0) ; font = UIFont.boldSystemFont(ofSize: 20) } let button = UIButton(type: .system) button.setTitleColor(color, for: .normal) button.titleLabel!.font = font button.titleLabel!.textAlignment = .center button.lac.height.equalTo(57) return button } private func makeBorder() -> UIView { UIView(backgroundColor: UIColor.lightGray.alpha(0.4)) } override open func addAction(_ action: DialogAction) { if action.type == .cancel, actions.contains(where: { $0.type == .cancel }) { fatalError("There can only be one cancel action") } super.addAction(action) } @objc func dismissSheet() { self.dismiss(animated: true, completion: nil) } open override func drawBackgroundHole(bezier: UIBezierPath) { guard !self.isBeingPresented && !self.isBeingDismissed else { return } let frame1 = contentStackView.convert(contentBlurView.frame, to: self.view) bezier.append(UIBezierPath(roundedRect: frame1, cornerRadius: contentBlurView.cornerRadius)) if let cancelActionView = cancelActionView { let frame2 = contentStackView.convert(cancelActionView.frame, to: self.view) bezier.append(UIBezierPath(roundedRect: frame2, cornerRadius: cancelActionView.cornerRadius)) } } open override func loadView() { super.loadView() contentStackView.spacing = 8 contentView.lac.make { $0.left.equalToSuperview(10) $0.right.equalToSuperview(-10) //TODO: Check still works $0.top.greaterThan(self.topLayoutGuide.lac.bottom, constant: 10) // iPhone X $0.bottom.equalTo(self.bottomLayoutGuide.lac.top, priority: .defaultHigh) $0.bottom.lessThanSuperview(-10) } contentBlurView.cornerRadius = 13.5 contentBlurView.clipsToBounds = true contentStackView.add(arrangedView: contentBlurView) promptContentView?.layoutMargins = UIEdgeInsets(horizontal: 16, top: 14, bottom: (promptSubtitle == nil) ? 14 : 25) promptContentView?.spacing = 12 if actions.isNotEmpty { var actionButtons = self.actionButtons let cancelButton = actions.firstIndex(where: { $0.type == .cancel }).map { actionButtons.remove(at: $0) } let buttonContentView = UIStackView(axis: .vertical) if promptContentView != nil || customViews.isNotEmpty { mainContentStack.add(arrangedView: makeBorder()) { $0.height.equalTo(points(pixels: 1)) } } var previousButton: UIButton? for button in actionButtons { if previousButton != nil { buttonContentView.add(arrangedView: makeBorder()) { $0.height.equalTo(points(pixels: 1)) } } buttonContentView.add(arrangedView: button) previousButton = button } mainContentStack.addArrangedSubview(buttonContentView) if let button = cancelButton { let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) blurView.cornerRadius = contentBlurView.cornerRadius blurView.clipsToBounds = true blurView.contentView.add(view: button) { $0.edges.equalToSuperview() } contentStackView.add(arrangedView: blurView) cancelActionView = blurView } } } open override func viewDidLoad() { super.viewDidLoad() // Dont dismiss when tapping background if there is no cancel option if actions.contains(where: { $0.type == .cancel }) { self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissSheet))) } self.modalPresentationStyle = .custom self.transitioningDelegate = self } } extension SheetDialog: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SheetAnimator(dismissing: false, duration: 1.0/3.0, controlPoints: (CGPoint(0.1, 1), CGPoint(0.85, 1))) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SheetAnimator(dismissing: true, duration: 1.0/3.0, controlPoints: (CGPoint(0.1, 1), CGPoint(0.85, 1))) } } private class SheetAnimator: DialogAnimator<SheetDialog> { override func prepareAnimation(_ viewController: SheetDialog) { viewController.contentBlurView.backgroundColor = .white viewController.cancelActionView?.backgroundColor = .white if !dismissing { viewController.contentView.layoutIfNeeded() viewController.contentView.transform(moveX: 0, y: viewController.contentView.frame.height) viewController.view.alpha = 0.0 } } override func animation(_ viewController: SheetDialog) { if dismissing { viewController.view.alpha = 0.0 viewController.contentView.transform(moveX: 0, y: viewController.contentView.frame.height) viewController.view.setNeedsDisplay() } else { viewController.view.alpha = 1.0 viewController.contentView.transform(moveX: 0, y: 0) } } override func completion(_ viewController: SheetDialog, finished: Bool) { if !dismissing { viewController.view.setNeedsDisplay() viewController.contentBlurView.backgroundColor = nil viewController.cancelActionView?.backgroundColor = nil } } }
d297e73ae9fd816c817cd4500c037d7a
30.412621
174
0.729408
false
false
false
false
boxcast/boxcast-sdk-apple
refs/heads/master
Tests/MockedClientTestCase.swift
mit
1
// // MockedClientTestCase.swift // BoxCast // // Created by Camden Fullmer on 8/22/17. // Copyright © 2017 BoxCast, Inc. All rights reserved. // import XCTest @testable import BoxCast class MockedClientTestCase: XCTestCase { var client: BoxCastClient! override func setUp() { super.setUp() // Set up mocking of the responses. let configuration = URLSessionConfiguration.default configuration.protocolClasses?.insert(MockedURLProtocol.self, at: 0) client = BoxCastClient(scope: PublicScope(), configuration: configuration) } func fixtureData(for name: String) -> Data? { let bundle = Bundle(for: MockedClientTestCase.self) guard let resourceURL = bundle.resourceURL else { return nil } let fileManager = FileManager.default let fileURL = resourceURL.appendingPathComponent("\(name).json") guard fileManager.fileExists(atPath: fileURL.path) else { return nil } do { let data = try Data(contentsOf: fileURL) return data } catch { return nil } } }
3806fab0d5a3f6cee193f2a733fa58fd
25.711111
82
0.605657
false
true
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/Cells/Feed/FeedCellLayout.swift
mit
1
// // FeedCellLayout.swift // Yep // // Created by nixzhu on 15/12/17. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit private let screenWidth: CGFloat = UIScreen.mainScreen().bounds.width struct FeedCellLayout { typealias Update = (layout: FeedCellLayout) -> Void typealias Cache = (layout: FeedCellLayout?, update: Update) let height: CGFloat struct BasicLayout { func nicknameLabelFrameWhen(hasLogo hasLogo: Bool, hasSkill: Bool) -> CGRect { var frame = nicknameLabelFrame frame.size.width -= hasLogo ? (18 + 10) : 0 frame.size.width -= hasSkill ? (skillButtonFrame.width + 10) : 0 return frame } let avatarImageViewFrame: CGRect private let nicknameLabelFrame: CGRect let skillButtonFrame: CGRect let messageTextViewFrame: CGRect let leftBottomLabelFrame: CGRect let messageCountLabelFrame: CGRect let discussionImageViewFrame: CGRect init(avatarImageViewFrame: CGRect, nicknameLabelFrame: CGRect, skillButtonFrame: CGRect, messageTextViewFrame: CGRect, leftBottomLabelFrame: CGRect, messageCountLabelFrame: CGRect, discussionImageViewFrame: CGRect) { self.avatarImageViewFrame = avatarImageViewFrame self.nicknameLabelFrame = nicknameLabelFrame self.skillButtonFrame = skillButtonFrame self.messageTextViewFrame = messageTextViewFrame self.leftBottomLabelFrame = leftBottomLabelFrame self.messageCountLabelFrame = messageCountLabelFrame self.discussionImageViewFrame = discussionImageViewFrame } } let basicLayout: BasicLayout struct BiggerImageLayout { let biggerImageViewFrame: CGRect init(biggerImageViewFrame: CGRect) { self.biggerImageViewFrame = biggerImageViewFrame } } var biggerImageLayout: BiggerImageLayout? struct NormalImagesLayout { let imageView1Frame: CGRect let imageView2Frame: CGRect let imageView3Frame: CGRect let imageView4Frame: CGRect init(imageView1Frame: CGRect, imageView2Frame: CGRect, imageView3Frame: CGRect, imageView4Frame: CGRect) { self.imageView1Frame = imageView1Frame self.imageView2Frame = imageView2Frame self.imageView3Frame = imageView3Frame self.imageView4Frame = imageView4Frame } } var normalImagesLayout: NormalImagesLayout? struct AnyImagesLayout { let mediaCollectionViewFrame: CGRect init(mediaCollectionViewFrame: CGRect) { self.mediaCollectionViewFrame = mediaCollectionViewFrame } } var anyImagesLayout: AnyImagesLayout? struct GithubRepoLayout { let githubRepoContainerViewFrame: CGRect } var githubRepoLayout: GithubRepoLayout? struct DribbbleShotLayout { let dribbbleShotContainerViewFrame: CGRect } var dribbbleShotLayout: DribbbleShotLayout? struct AudioLayout { let voiceContainerViewFrame: CGRect } var audioLayout: AudioLayout? struct LocationLayout { let locationContainerViewFrame: CGRect } var locationLayout: LocationLayout? struct URLLayout { let URLContainerViewFrame: CGRect } var _URLLayout: URLLayout? // MARK: - Init init(height: CGFloat, basicLayout: BasicLayout) { self.height = height self.basicLayout = basicLayout } init(feed: DiscoveredFeed) { let height: CGFloat switch feed.kind { case .Text: height = FeedBasicCell.heightOfFeed(feed) case .URL: height = FeedURLCell.heightOfFeed(feed) case .Image: if feed.imageAttachmentsCount == 1 { height = FeedBiggerImageCell.heightOfFeed(feed) } else if feed.imageAttachmentsCount <= FeedsViewController.feedNormalImagesCountThreshold { height = FeedNormalImagesCell.heightOfFeed(feed) } else { height = FeedAnyImagesCell.heightOfFeed(feed) } case .GithubRepo: height = FeedGithubRepoCell.heightOfFeed(feed) case .DribbbleShot: height = FeedDribbbleShotCell.heightOfFeed(feed) case .Audio: height = FeedVoiceCell.heightOfFeed(feed) case .Location: height = FeedLocationCell.heightOfFeed(feed) default: height = FeedBasicCell.heightOfFeed(feed) } self.height = height let avatarImageViewFrame = CGRect(x: 15, y: 10, width: 40, height: 40) let nicknameLabelFrame: CGRect let skillButtonFrame: CGRect if let skill = feed.skill { let rect = skill.localName.boundingRectWithSize(CGSize(width: 320, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: YepConfig.FeedBasicCell.skillTextAttributes, context: nil) let skillButtonWidth = ceil(rect.width) + 20 skillButtonFrame = CGRect(x: screenWidth - skillButtonWidth - 15, y: 19, width: skillButtonWidth, height: 22) let nicknameLabelWidth = screenWidth - 65 - 15 nicknameLabelFrame = CGRect(x: 65, y: 21, width: nicknameLabelWidth, height: 18) } else { let nicknameLabelWidth = screenWidth - 65 - 15 nicknameLabelFrame = CGRect(x: 65, y: 21, width: nicknameLabelWidth, height: 18) skillButtonFrame = CGRectZero } let _rect1 = feed.body.boundingRectWithSize(CGSize(width: FeedBasicCell.messageTextViewMaxWidth, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: YepConfig.FeedBasicCell.textAttributes, context: nil) let messageTextViewHeight = ceil(_rect1.height) let messageTextViewFrame = CGRect(x: 65, y: 54, width: screenWidth - 65 - 15, height: messageTextViewHeight) let leftBottomLabelOriginY = height - 17 - 15 let leftBottomLabelFrame = CGRect(x: 65, y: leftBottomLabelOriginY, width: screenWidth - 65 - 85, height: 17) //let messagesCountString = feed.messagesCount > 99 ? "99+" : "\(feed.messagesCount)" //let _rect2 = messagesCountString.boundingRectWithSize(CGSize(width: 320, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: YepConfig.FeedBasicCell.bottomLabelsTextAttributes, context: nil) //let _width = ceil(_rect2.width) let _width: CGFloat = 30 let messageCountLabelFrame = CGRect(x: screenWidth - _width - 45 - 8, y: leftBottomLabelOriginY, width: _width, height: 19) let discussionImageViewFrame = CGRect(x: screenWidth - 30 - 15, y: leftBottomLabelOriginY - 1, width: 30, height: 19) let basicLayout = FeedCellLayout.BasicLayout( avatarImageViewFrame: avatarImageViewFrame, nicknameLabelFrame: nicknameLabelFrame, skillButtonFrame: skillButtonFrame, messageTextViewFrame: messageTextViewFrame, leftBottomLabelFrame: leftBottomLabelFrame, messageCountLabelFrame: messageCountLabelFrame, discussionImageViewFrame: discussionImageViewFrame ) self.basicLayout = basicLayout let beginY = messageTextViewFrame.origin.y + messageTextViewFrame.height + 15 switch feed.kind { case .Text: break case .URL: let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15 let URLContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height) let _URLLayout = FeedCellLayout.URLLayout(URLContainerViewFrame: URLContainerViewFrame) self._URLLayout = _URLLayout case .Image: if feed.imageAttachmentsCount == 1 { let biggerImageViewFrame = CGRect(origin: CGPoint(x: 65, y: beginY), size: YepConfig.FeedBiggerImageCell.imageSize) let biggerImageLayout = FeedCellLayout.BiggerImageLayout(biggerImageViewFrame: biggerImageViewFrame) self.biggerImageLayout = biggerImageLayout } else if feed.imageAttachmentsCount <= FeedsViewController.feedNormalImagesCountThreshold { let x1 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 0 let imageView1Frame = CGRect(origin: CGPoint(x: x1, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize) let x2 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 1 let imageView2Frame = CGRect(origin: CGPoint(x: x2, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize) let x3 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 2 let imageView3Frame = CGRect(origin: CGPoint(x: x3, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize) let x4 = 65 + (YepConfig.FeedNormalImagesCell.imageSize.width + 5) * 3 let imageView4Frame = CGRect(origin: CGPoint(x: x4, y: beginY), size: YepConfig.FeedNormalImagesCell.imageSize) let normalImagesLayout = FeedCellLayout.NormalImagesLayout(imageView1Frame: imageView1Frame, imageView2Frame: imageView2Frame, imageView3Frame: imageView3Frame, imageView4Frame: imageView4Frame) self.normalImagesLayout = normalImagesLayout } else { let height = YepConfig.FeedNormalImagesCell.imageSize.height let mediaCollectionViewFrame = CGRect(x: 0, y: beginY, width: screenWidth, height: height) let anyImagesLayout = FeedCellLayout.AnyImagesLayout(mediaCollectionViewFrame: mediaCollectionViewFrame) self.anyImagesLayout = anyImagesLayout } case .GithubRepo: let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15 let githubRepoContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height) let githubRepoLayout = FeedCellLayout.GithubRepoLayout(githubRepoContainerViewFrame: githubRepoContainerViewFrame) self.githubRepoLayout = githubRepoLayout case .DribbbleShot: let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15 let dribbbleShotContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height) let dribbbleShotLayout = FeedCellLayout.DribbbleShotLayout(dribbbleShotContainerViewFrame: dribbbleShotContainerViewFrame) self.dribbbleShotLayout = dribbbleShotLayout case .Audio: if let attachment = feed.attachment { if case let .Audio(audioInfo) = attachment { let timeLengthString = audioInfo.duration.yep_feedAudioTimeLengthString let width = FeedVoiceContainerView.fullWidthWithSampleValuesCount(audioInfo.sampleValues.count, timeLengthString: timeLengthString) let y = beginY + 2 let voiceContainerViewFrame = CGRect(x: 65, y: y, width: width, height: 50) let audioLayout = FeedCellLayout.AudioLayout(voiceContainerViewFrame: voiceContainerViewFrame) self.audioLayout = audioLayout } } case .Location: let height: CGFloat = leftBottomLabelFrame.origin.y - beginY - 15 let locationContainerViewFrame = CGRect(x: 65, y: beginY, width: screenWidth - 65 - 60, height: height) let locationLayout = FeedCellLayout.LocationLayout(locationContainerViewFrame: locationContainerViewFrame) self.locationLayout = locationLayout default: break } } }
babd9f2b105810423dfcf030a0363140
36.319876
251
0.662561
false
false
false
false
firebase/firebase-ios-sdk
refs/heads/master
FirebaseStorage/Tests/Integration/StorageIntegrationCommon.swift
apache-2.0
1
// Copyright 2021 Google LLC // // 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 FirebaseAuth import FirebaseCore import FirebaseStorage import XCTest class StorageIntegrationCommon: XCTestCase { var app: FirebaseApp! var auth: Auth! var storage: Storage! static var configured = false static var once = false static var signedIn = false override class func setUp() { if !StorageIntegrationCommon.configured { StorageIntegrationCommon.configured = true FirebaseApp.configure() } } override func setUp() { super.setUp() app = FirebaseApp.app() auth = Auth.auth(app: app) storage = Storage.storage(app: app!) if !StorageIntegrationCommon.signedIn { signInAndWait() } if !StorageIntegrationCommon.once { StorageIntegrationCommon.once = true let setupExpectation = expectation(description: "setUp") let largeFiles = ["ios/public/1mb", "ios/public/1mb2"] let emptyFiles = ["ios/public/empty", "ios/public/list/a", "ios/public/list/b", "ios/public/list/prefix/c"] setupExpectation.expectedFulfillmentCount = largeFiles.count + emptyFiles.count do { let bundle = Bundle(for: StorageIntegrationCommon.self) let filePath = try XCTUnwrap(bundle.path(forResource: "1mb", ofType: "dat"), "Failed to get filePath") let data = try XCTUnwrap(try Data(contentsOf: URL(fileURLWithPath: filePath)), "Failed to load file") for largeFile in largeFiles { let ref = storage.reference().child(largeFile) ref.putData(data) { result in self.assertResultSuccess(result) setupExpectation.fulfill() } } for emptyFile in emptyFiles { let ref = storage.reference().child(emptyFile) ref.putData(Data()) { result in self.assertResultSuccess(result) setupExpectation.fulfill() } } waitForExpectations() } catch { XCTFail("Error thrown setting up files in setUp") } } } override func tearDown() { app = nil storage = nil super.tearDown() } private func signInAndWait() { let expectation = self.expectation(description: #function) auth.signIn(withEmail: Credentials.kUserName, password: Credentials.kPassword) { result, error in XCTAssertNil(error) StorageIntegrationCommon.signedIn = true print("Successfully signed in") expectation.fulfill() } waitForExpectations() } private func waitForExpectations() { let kTestTimeout = 60.0 waitForExpectations(timeout: kTestTimeout, handler: { error in if let error = error { print(error) } }) } private func assertResultSuccess<T>(_ result: Result<T, Error>, file: StaticString = #file, line: UInt = #line) { switch result { case let .success(value): XCTAssertNotNil(value, file: file, line: line) case let .failure(error): XCTFail("Unexpected error \(error)") } } }
e262697dbe9ed59d34276edd6397028a
30.689076
98
0.627155
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/What's New/Data store/AnnouncementsDataSource.swift
gpl-2.0
1
protocol AnnouncementsDataSource: UITableViewDataSource { func registerCells(for tableView: UITableView) var dataDidChange: (() -> Void)? { get set } } class FeatureAnnouncementsDataSource: NSObject, AnnouncementsDataSource { private let store: AnnouncementsStore private let cellTypes: [String: UITableViewCell.Type] private var features: [WordPressKit.Feature] { store.announcements.reduce(into: [WordPressKit.Feature](), { $0.append(contentsOf: $1.features) }) } var dataDidChange: (() -> Void)? init(store: AnnouncementsStore, cellTypes: [String: UITableViewCell.Type]) { self.store = store self.cellTypes = cellTypes super.init() } func registerCells(for tableView: UITableView) { cellTypes.forEach { tableView.register($0.value, forCellReuseIdentifier: $0.key) } } func numberOfSections(in: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return features.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard indexPath.row <= features.count - 1 else { let cell = tableView.dequeueReusableCell(withIdentifier: "findOutMoreCell", for: indexPath) as? FindOutMoreCell ?? FindOutMoreCell() cell.configure(with: URL(string: store.announcements.first?.detailsUrl ?? "")) return cell } let cell = tableView.dequeueReusableCell(withIdentifier: "announcementCell", for: indexPath) as? AnnouncementCell ?? AnnouncementCell() cell.configure(feature: features[indexPath.row]) return cell } }
2fe0084b96d74481c80b2e15910ccd1d
32.396226
144
0.668362
false
false
false
false
aktowns/swen
refs/heads/master
Sources/Swen/Util/XPathDocument.swift
apache-2.0
1
// // XPathDocument.swift created on 29/12/15 // Swen project // // Copyright 2015 Ashley Towns <[email protected]> // // 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. // /* This is a light wrapper around libxml2 to read xml based formats this is being used mainly because NSXML lacks linux support at the moment. This is really crude and only does what i need it to.. */ import CXML2 enum XMLElementType: UInt32 { case ElementNode = 1 case AttributeNode = 2 case TextNode = 3 case CDATASectionNode = 4 case EntityRefNode = 5 case EntityNode = 6 case PINode = 7 case CommentNode = 8 case DocumentNode = 9 case DocumentTypeNode = 10 case DocumentFragNode = 11 case NotationNode = 12 case HTMLDocumentNode = 13 case DTDNode = 14 case ElementDecl = 15 case AttributeDecl = 16 case EntityDecl = 17 case NamespaceDecl = 18 case XIncludeStart = 19 case XIncludeEnd = 20 } public class XMLNode: CustomStringConvertible { let handle: xmlNodePtr public init(withHandle handle: xmlNodePtr) { self.handle = handle } public func getProp(property: String) -> String? { let prop = xmlGetProp(self.handle, property) return String.fromCString(UnsafePointer<Int8>(prop)) } var type: XMLElementType? { return XMLElementType(rawValue: self.handle.memory.type.rawValue) } var name: String? { let convName = UnsafePointer<Int8>(self.handle.memory.name) return String.fromCString(convName) } var content: String? { let convContent = UnsafePointer<Int8>(self.handle.memory.content) return String.fromCString(convContent) } public var description: String { return "#\(self.dynamicType)(name:\(name), type:\(type), content:\(content))" } } public class XPathDocument { let doc: xmlDocPtr let ctx: xmlXPathContextPtr public init(withPath path: String) { let docptr = xmlParseFile(path) assert(docptr != nil, "xmlParseFile failed, returned a null pointer.") let ctxptr = xmlXPathNewContext(docptr) assert(ctxptr != nil, "xmlXPathNewContext failed, returned a null pointer.") self.doc = docptr self.ctx = ctxptr } public func search(withXPath xpath: String) -> [XMLNode] { let exprptr = xmlXPathEvalExpression(xpath, self.ctx) assert(exprptr != nil, "xmlXPathEvalExpression failed, returned a null pointer.") return getNodes(exprptr.memory.nodesetval) } private func getNodes(nodes: xmlNodeSetPtr) -> [XMLNode] { let size: Int = (nodes != nil) ? Int(nodes.memory.nodeNr) : Int(0) var outNodes = Array<XMLNode>() for i in Range(start: Int(0), end: size) { let node = XMLNode(withHandle: nodes.memory.nodeTab[i]) outNodes.append(node) } return outNodes } }
b3659cf4496086bb23454df5f6c7d71b
26.788136
85
0.703263
false
false
false
false
sungkipyung/CodeSample
refs/heads/master
SimpleCameraApp/SimpleCameraApp/CollageCell.swift
apache-2.0
1
// // CollageCell.swift // SimpleCameraApp // // Created by 성기평 on 2016. 4. 14.. // Copyright © 2016년 hothead. All rights reserved. // import UIKit protocol CollageCellDelegate { func collageCellDidSelect(_ cell: CollageCell) } class CollageCell: UIView, UIScrollViewDelegate { @IBOutlet weak var cameraPreview: CameraPreview! @IBOutlet weak var imageScrollView: UIScrollView! weak var imageView: UIImageView! var delegate: CollageCellDelegate? var enableMask: Bool? = true @IBOutlet weak var lineView: UIView! fileprivate static let BORDER_WIDTH:CGFloat = 0 var polygon: Polygon! { didSet { if let p = polygon { let path = p.path() self.frame = CGRect(origin: p.origin, size: path.bounds.size) self.imageScrollView.frame = self.bounds // self.imageView.sizeThatFit(self.imageScrollView) self.cameraPreview.frame = self.bounds self.shapeLayerPath = path } } } internal fileprivate(set) var shapeLayerPath : UIBezierPath? { didSet (newLayer) { let shapeLayerPath = self.shapeLayerPath! let path = shapeLayerPath.cgPath if self.enableMask! { let mask: CAShapeLayer = CAShapeLayer() mask.path = path self.layer.mask = mask } self.lineView.layer.sublayers?.forEach({ (sublayer) in sublayer.removeFromSuperlayer() }) if (self.imageView.image == nil) { let line = CAShapeLayer.init() line.path = path line.lineDashPattern = [8, 8] line.lineWidth = 2 line.fillColor = UIColor.clear.cgColor line.strokeColor = UIColor.white.cgColor self.lineView.layer.addSublayer(line) } } } func pointInside(_ point: CGPoint) -> Bool { if let path:UIBezierPath = self.shapeLayerPath { return path.contains(point) } return false } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if let path:UIBezierPath = self.shapeLayerPath { return path.contains(point) } else { return super.point(inside: point, with: event) } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { self.imageScrollView.delegate = self let imageView = UIImageView(frame: self.bounds) imageView.contentMode = UIViewContentMode.scaleToFill self.imageScrollView.addSubview(imageView) self.imageView = imageView } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.imageView } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) // self.superview?.bringSubviewToFront(self) } @IBAction func imageScrollViewTapped(_ sender: AnyObject) { delegate?.collageCellDidSelect(self) } }
9bc6a143ef9fea3f0a1459931d72aa4c
29.364407
79
0.588334
false
false
false
false
JohnSansoucie/MyProject2
refs/heads/master
BlueCapKit/External/SimpleFutures/Future.swift
mit
1
// // Future.swift // SimpleFutures // // Created by Troy Stribling on 7/5/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import Foundation public struct SimpleFuturesError { static let domain = "SimpleFutures" static let futureCompleted = NSError(domain:domain, code:1, userInfo:[NSLocalizedDescriptionKey:"Future has been completed"]) static let futureNotCompleted = NSError(domain:domain, code:2, userInfo:[NSLocalizedDescriptionKey:"Future has not been completed"]) } public struct SimpleFuturesException { static let futureCompleted = NSException(name:"Future complete error", reason: "Future previously completed.", userInfo:nil) } // Promise public class Promise<T> { public let future = Future<T>() public init() { } public func completeWith(future:Future<T>) { self.completeWith(self.future.defaultExecutionContext, future:future) } public func completeWith(executionContext:ExecutionContext, future:Future<T>) { self.future.completeWith(executionContext, future:future) } public func complete(result:Try<T>) { self.future.complete(result) } public func success(value:T) { self.future.success(value) } public func failure(error:NSError) { self.future.failure(error) } } // Future public class Future<T> { private var result:Try<T>? internal let defaultExecutionContext: ExecutionContext = QueueContext.main typealias OnComplete = Try<T> -> Void private var saveCompletes = [OnComplete]() public init() { } // should be Futureable protocol public func onComplete(executionContext:ExecutionContext, complete:Try<T> -> Void) -> Void { Queue.simpleFutures.sync { let savedCompletion : OnComplete = {result in executionContext.execute { complete(result) } } if let result = self.result { savedCompletion(result) } else { self.saveCompletes.append(savedCompletion) } } } // should be future mixin internal func complete(result:Try<T>) { Queue.simpleFutures.sync { if self.result != nil { SimpleFuturesException.futureCompleted.raise() } self.result = result for complete in self.saveCompletes { complete(result) } self.saveCompletes.removeAll() } } public func onComplete(complete:Try<T> -> Void) { self.onComplete(self.defaultExecutionContext, complete) } public func onSuccess(success:T -> Void) { self.onSuccess(self.defaultExecutionContext, success) } public func onSuccess(executionContext:ExecutionContext, success:T -> Void){ self.onComplete(executionContext) {result in switch result { case .Success(let valueBox): success(valueBox.value) default: break } } } public func onFailure(failure:NSError -> Void) -> Void { return self.onFailure(self.defaultExecutionContext, failure) } public func onFailure(executionContext:ExecutionContext, failure:NSError -> Void) { self.onComplete(executionContext) {result in switch result { case .Failure(let error): failure(error) default: break } } } public func map<M>(mapping:T -> Try<M>) -> Future<M> { return map(self.defaultExecutionContext, mapping:mapping) } public func map<M>(executionContext:ExecutionContext, mapping:T -> Try<M>) -> Future<M> { let future = Future<M>() self.onComplete(executionContext) {result in future.complete(result.flatmap(mapping)) } return future } public func flatmap<M>(mapping:T -> Future<M>) -> Future<M> { return self.flatmap(self.defaultExecutionContext, mapping:mapping) } public func flatmap<M>(executionContext:ExecutionContext, mapping:T -> Future<M>) -> Future<M> { let future = Future<M>() self.onComplete(executionContext) {result in switch result { case .Success(let resultBox): future.completeWith(executionContext, future:mapping(resultBox.value)) case .Failure(let error): future.failure(error) } } return future } public func andThen(complete:Try<T> -> Void) -> Future<T> { return self.andThen(self.defaultExecutionContext, complete:complete) } public func andThen(executionContext:ExecutionContext, complete:Try<T> -> Void) -> Future<T> { let future = Future<T>() future.onComplete(executionContext, complete) self.onComplete(executionContext) {result in future.complete(result) } return future } public func recover(recovery: NSError -> Try<T>) -> Future<T> { return self.recover(self.defaultExecutionContext, recovery:recovery) } public func recover(executionContext:ExecutionContext, recovery:NSError -> Try<T>) -> Future<T> { let future = Future<T>() self.onComplete(executionContext) {result in future.complete(result.recoverWith(recovery)) } return future } public func recoverWith(recovery:NSError -> Future<T>) -> Future<T> { return self.recoverWith(self.defaultExecutionContext, recovery:recovery) } public func recoverWith(executionContext:ExecutionContext, recovery:NSError -> Future<T>) -> Future<T> { let future = Future<T>() self.onComplete(executionContext) {result in switch result { case .Success(let resultBox): future.success(resultBox.value) case .Failure(let error): future.completeWith(executionContext, future:recovery(error)) } } return future } public func withFilter(filter:T -> Bool) -> Future<T> { return self.withFilter(self.defaultExecutionContext, filter:filter) } public func withFilter(executionContext:ExecutionContext, filter:T -> Bool) -> Future<T> { let future = Future<T>() self.onComplete(executionContext) {result in future.complete(result.filter(filter)) } return future } public func foreach(apply:T -> Void) { self.foreach(self.defaultExecutionContext, apply:apply) } public func foreach(executionContext:ExecutionContext, apply:T -> Void) { self.onComplete(executionContext) {result in result.foreach(apply) } } internal func completeWith(future:Future<T>) { self.completeWith(self.defaultExecutionContext, future:future) } internal func completeWith(executionContext:ExecutionContext, future:Future<T>) { let isCompleted = Queue.simpleFutures.sync {Void -> Bool in return self.result != nil } if isCompleted == false { future.onComplete(executionContext) {result in self.complete(result) } } } internal func success(value:T) { self.complete(Try(value)) } internal func failure(error:NSError) { self.complete(Try<T>(error)) } } // create futures public func future<T>(computeResult:Void -> Try<T>) -> Future<T> { return future(QueueContext.global, computeResult) } public func future<T>(executionContext:ExecutionContext, calculateResult:Void -> Try<T>) -> Future<T> { let promise = Promise<T>() executionContext.execute { promise.complete(calculateResult()) } return promise.future } public func forcomp<T,U>(f:Future<T>, g:Future<U>, #apply:(T,U) -> Void) -> Void { return forcomp(f.defaultExecutionContext, f, g, apply:apply) } public func forcomp<T,U>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #apply:(T,U) -> Void) -> Void { f.foreach(executionContext) {fvalue in g.foreach(executionContext) {gvalue in apply(fvalue, gvalue) } } } // for comprehensions public func forcomp<T,U>(f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #apply:(T,U) -> Void) -> Void { return forcomp(f.defaultExecutionContext, f, g, filter:filter, apply:apply) } public func forcomp<T,U>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #apply:(T,U) -> Void) -> Void { f.foreach(executionContext) {fvalue in g.withFilter(executionContext) {gvalue in filter(fvalue, gvalue) }.foreach(executionContext) {gvalue in apply(fvalue, gvalue) } } } public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, h:Future<V>, #apply:(T,U,V) -> Void) -> Void { return forcomp(f.defaultExecutionContext, f, g, h, apply:apply) } public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #apply:(T,U,V) -> Void) -> Void { f.foreach(executionContext) {fvalue in g.foreach(executionContext) {gvalue in h.foreach(executionContext) {hvalue in apply(fvalue, gvalue, hvalue) } } } } public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #apply:(T,U,V) -> Void) -> Void { return forcomp(f.defaultExecutionContext, f, g, h, filter:filter, apply:apply) } public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #apply:(T,U,V) -> Void) -> Void { f.foreach(executionContext) {fvalue in g.foreach(executionContext) {gvalue in h.withFilter(executionContext) {hvalue in filter(fvalue, gvalue, hvalue) }.foreach(executionContext) {hvalue in apply(fvalue, gvalue, hvalue) } } } } public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, #yield:(T,U) -> Try<V>) -> Future<V> { return forcomp(f.defaultExecutionContext, f, g, yield:yield) } public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #yield:(T,U) -> Try<V>) -> Future<V> { return f.flatmap(executionContext) {fvalue in g.map(executionContext) {gvalue in yield(fvalue, gvalue) } } } public func forcomp<T,U,V>(f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #yield:(T,U) -> Try<V>) -> Future<V> { return forcomp(f.defaultExecutionContext, f, g, filter:filter, yield:yield) } public func forcomp<T,U,V>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, #filter:(T,U) -> Bool, #yield:(T,U) -> Try<V>) -> Future<V> { return f.flatmap(executionContext) {fvalue in g.withFilter(executionContext) {gvalue in filter(fvalue, gvalue) }.map(executionContext) {gvalue in yield(fvalue, gvalue) } } } public func forcomp<T,U,V,W>(f:Future<T>, g:Future<U>, h:Future<V>, #yield:(T,U,V) -> Try<W>) -> Future<W> { return forcomp(f.defaultExecutionContext, f, g, h, yield:yield) } public func forcomp<T,U,V,W>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #yield:(T,U,V) -> Try<W>) -> Future<W> { return f.flatmap(executionContext) {fvalue in g.flatmap(executionContext) {gvalue in h.map(executionContext) {hvalue in yield(fvalue, gvalue, hvalue) } } } } public func forcomp<T,U, V, W>(f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #yield:(T,U,V) -> Try<W>) -> Future<W> { return forcomp(f.defaultExecutionContext, f, g, h, filter:filter, yield:yield) } public func forcomp<T,U, V, W>(executionContext:ExecutionContext, f:Future<T>, g:Future<U>, h:Future<V>, #filter:(T,U,V) -> Bool, #yield:(T,U,V) -> Try<W>) -> Future<W> { return f.flatmap(executionContext) {fvalue in g.flatmap(executionContext) {gvalue in h.withFilter(executionContext) {hvalue in filter(fvalue, gvalue, hvalue) }.map(executionContext) {hvalue in yield(fvalue, gvalue, hvalue) } } } }
23389ca82d526f866ca42b77aeb9e457
32.83558
170
0.610213
false
false
false
false
DrabWeb/Sudachi
refs/heads/master
Sudachi/Sudachi/SCPlaylistTableView.swift
gpl-3.0
1
// // SCPlaylistTableView.swift // Sudachi // // Created by Seth on 2016-04-02. // import Cocoa class SCPlaylistTableView: NSTableView { override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. } override func awakeFromNib() { // Add the observer for the playlist table view's selection change notification NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("selectionChanged:"), name: NSTableViewSelectionDidChangeNotification, object: nil); } /// The timer so playlist items get deselected after the selection doesnt change for 5 seconds var deselectTimer : NSTimer = NSTimer(); /// When the playlist table view's selection changes... func selectionChanged(notification : NSNotification) { // If the notification object was this table view... if((notification.object as? SCPlaylistTableView) == self) { // Invalidate the current timer deselectTimer.invalidate(); // Start a new timer for the deselect wait deselectTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(5), target: self, selector: Selector("deselectAllItems"), userInfo: nil, repeats: false); } } /// Deselects all the items for this table view func deselectAllItems() { // Deselect all the items self.deselectAll(self); } override func rightMouseDown(theEvent: NSEvent) { /// The index of the row that was right clicked let row : Int = self.rowAtPoint(self.convertPoint(theEvent.locationInWindow, fromView: nil)); // Select the row the mouse is over self.selectRowIndexes(NSIndexSet(index: row), byExtendingSelection: false); // If the playlist has any items selected... if(self.selectedRow != -1) { /// The SCPlaylistTableCellView at the right clicked row index let cellAtSelectedRow : SCPlaylistTableCellView = (self.rowViewAtRow(row, makeIfNecessary: false)!.subviews[0] as! SCPlaylistTableCellView); // Display the right click menu for the row NSMenu.popUpContextMenu(cellAtSelectedRow.menuForEvent(theEvent)!, withEvent: theEvent, forView: cellAtSelectedRow); } } override func mouseDown(theEvent: NSEvent) { super.mouseDown(theEvent); /// The index of the row that was clicked let row : Int = self.rowAtPoint(self.convertPoint(theEvent.locationInWindow, fromView: nil)); // Click the row the cursor is above (self.rowViewAtRow(row, makeIfNecessary: false)?.subviews[0] as! SCPlaylistTableCellView).mouseDown(theEvent); } // Override the alternate row colors private func alternateBackgroundColor() -> NSColor? { self.superview?.superview?.superview?.layer?.backgroundColor = SCThemingEngine().defaultEngine().playlistSecondAlternatingColor.CGColor; return SCThemingEngine().defaultEngine().playlistFirstAlternatingColor; } internal override func drawBackgroundInClipRect(clipRect: NSRect) { // http://stackoverflow.com/questions/3973841/change-nstableview-alternate-row-colors // Refactored if(alternateBackgroundColor() == nil) { // If we didn't set the alternate color, fall back to the default behaviour super.drawBackgroundInClipRect(clipRect); } else { // Fill in the background color self.backgroundColor.set(); NSRectFill(clipRect); // Check if we should be drawing alternating colored rows if(usesAlternatingRowBackgroundColors) { // Set the alternating background color alternateBackgroundColor()!.set(); // Go through all of the intersected rows and draw their rects var checkRect = bounds; checkRect.origin.y = clipRect.origin.y; checkRect.size.height = clipRect.size.height; let rowsToDraw = rowsInRect(checkRect); var curRow = rowsToDraw.location; repeat { if curRow % 2 != 0 { // This is an alternate row var rowRect = rectOfRow(curRow); rowRect.origin.x = clipRect.origin.x; rowRect.size.width = clipRect.size.width; NSRectFill(rowRect); } curRow++; } while curRow < rowsToDraw.location + rowsToDraw.length; // Figure out the height of "off the table" rows var thisRowHeight = rowHeight; if gridStyleMask.contains(NSTableViewGridLineStyle.SolidHorizontalGridLineMask) || gridStyleMask.contains(NSTableViewGridLineStyle.DashedHorizontalGridLineMask) { thisRowHeight += 2.0; // Compensate for a grid } // Draw fake rows below the table's last row var virtualRowOrigin = 0.0 as CGFloat; var virtualRowNumber = numberOfRows; if(numberOfRows > 0) { let finalRect = rectOfRow(numberOfRows-1); virtualRowOrigin = finalRect.origin.y + finalRect.size.height; } repeat { if virtualRowNumber % 2 != 0 { // This is an alternate row let virtualRowRect = NSRect(x: clipRect.origin.x, y: virtualRowOrigin, width: clipRect.size.width, height: thisRowHeight); NSRectFill(virtualRowRect); } virtualRowNumber++; virtualRowOrigin += thisRowHeight; } while virtualRowOrigin < clipRect.origin.y + clipRect.size.height; // Draw fake rows above the table's first row virtualRowOrigin = -1 * thisRowHeight; virtualRowNumber = -1; repeat { if(abs(virtualRowNumber) % 2 != 0) { // This is an alternate row let virtualRowRect = NSRect(x: clipRect.origin.x, y: virtualRowOrigin, width: clipRect.size.width, height: thisRowHeight); NSRectFill(virtualRowRect); } virtualRowNumber--; virtualRowOrigin -= thisRowHeight; } while virtualRowOrigin + thisRowHeight > clipRect.origin.y; } } } }
c8e9e837d3e7c70143d82d9540556628
43.816993
171
0.582847
false
false
false
false
kharrison/CodeExamples
refs/heads/master
Container/Container-SB/Container/Location.swift
bsd-3-clause
2
// // Location.swift // Container // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2017 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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 CoreLocation /// A structure representing the location of a point on /// the map. struct Location { /// The name of the location. let name: String /// The latitude of the location in degrees. let latitude: CLLocationDegrees /// The longitude of the location in degrees. let longitude: CLLocationDegrees /// A read-only `CLLocationCoordinate2D` value for the /// geographic coordinate of the location. var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2DMake(latitude, longitude) } } extension Location { /// A failable initializer that builds a `Location` from /// a dictionary of String keys and values. The dictionary /// must contain at least "name", "latitude" and "longitude" /// items. /// /// The values must all be `String` and the `latitude` /// and `longitude` must convert to a `CLLocationDegrees` /// value (Double) and specify a valid coordinate. A valid /// latitude is from -90 to +90 and a valid longitude is /// from -180 to +180. /// /// - Parameter dictionary: A dictionary containing the /// details to initialize the location. /// /// - Returns: A `Location` structure or `nil` if the /// dictionary was invalid, init?(dictionary: Dictionary<String,String>) { guard let name = dictionary["name"], let latitudeItem = dictionary["latitude"], let latitude = CLLocationDegrees(latitudeItem), let longitudeItem = dictionary["longitude"], let longitude = CLLocationDegrees(longitudeItem) else { return nil } self.name = name self.latitude = latitude self.longitude = longitude if !CLLocationCoordinate2DIsValid(coordinate) { return nil } } }
d4f3b754af200d427626952b6364c2e8
35.760417
79
0.696515
false
false
false
false
huangboju/QMUI.swift
refs/heads/master
QMUI.swift/QMUIKit/UIComponents/QMUINavigationTitleView.swift
mit
1
// // QMUINavigationTitleView.swift // QMUI.swift // // Created by 伯驹 黄 on 2017/1/17. // Copyright © 2017年 伯驹 黄. All rights reserved. // @objc protocol QMUINavigationTitleViewDelegate { /** 点击 titleView 后的回调,只需设置 titleView.userInteractionEnabled = YES 后即可使用。不过一般都用于配合 QMUINavigationTitleViewAccessoryTypeDisclosureIndicator。 @param titleView 被点击的 titleView @param isActive titleView 是否处于活跃状态(所谓的活跃,对应右边的箭头而言,就是点击后箭头向上的状态) */ @objc optional func didTouch(_ titleView: QMUINavigationTitleView, isActive: Bool) /** titleView 的活跃状态发生变化时会被调用,也即 [titleView setActive:] 被调用时。 @param active 是否处于活跃状态 @param titleView 变换状态的 titleView */ @objc optional func didChanged(_ active: Bool, for titleView: QMUINavigationTitleView) } /// 设置title和subTitle的布局方式,默认是水平布局。 enum QMUINavigationTitleViewStyle { case `default` // 水平 case subTitleVertical // 垂直 } /// 设置titleView的样式,默认没有任何修饰 enum QMUINavigationTitleViewAccessoryType { case none // 默认 case disclosureIndicator // 有下拉箭头 } /** * 可作为navgationItem.titleView 的标题控件。 * * 支持主副标题,且可控制主副标题的布局方式(水平或垂直);支持在左边显示loading,在右边显示accessoryView(如箭头)。 * * 默认情况下 titleView 是不支持点击的,需要支持点击的情况下,请把 `userInteractionEnabled` 设为 `YES`。 * * 若要监听 titleView 的点击事件,有两种方法: * * 1. 使用 UIControl 默认的 addTarget:action:forControlEvents: 方式。这种适用于单纯的点击,不需要涉及到状态切换等。 * 2. 使用 QMUINavigationTitleViewDelegate 提供的接口。这种一般配合 titleView.accessoryType 来使用,这样就不用自己去做 accessoryView 的旋转、active 状态的维护等。 */ class QMUINavigationTitleView: UIControl { weak var delegate: QMUINavigationTitleViewDelegate? var style: QMUINavigationTitleViewStyle { didSet { if style == .subTitleVertical { titleLabel.font = verticalTitleFont updateTitleLabelSize() subtitleLabel.font = verticalSubtitleFont updateSubtitleLabelSize() } else { titleLabel.font = horizontalTitleFont updateTitleLabelSize() subtitleLabel.font = horizontalSubtitleFont updateSubtitleLabelSize() } refreshLayout() } } var isActive = false { didSet { delegate?.didChanged?(isActive, for: self) guard accessoryType == .disclosureIndicator else { return } let angle: CGFloat = isActive ? -180 : 0.1 UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { self.accessoryTypeView?.transform = CGAffineTransform(rotationAngle: AngleWithDegrees(angle)) }, completion: { _ in }) } } @objc dynamic var maximumWidth: CGFloat = 0 { didSet { refreshLayout() } } // MARK: - Titles private(set) var titleLabel: UILabel! var title: String? { didSet { titleLabel.text = title updateTitleLabelSize() refreshLayout() } } private(set) var subtitleLabel: UILabel! var subtitle: String? { didSet { subtitleLabel.text = subtitle updateSubtitleLabelSize() refreshLayout() } } /// 水平布局下的标题字体,默认为 NavBarTitleFont @objc dynamic var horizontalTitleFont = NavBarTitleFont { didSet { if style == .default { titleLabel.font = horizontalTitleFont updateTitleLabelSize() refreshLayout() } } } /// 水平布局下的副标题的字体,默认为 NavBarTitleFont @objc dynamic var horizontalSubtitleFont = NavBarTitleFont { didSet { if style == .default { subtitleLabel.font = horizontalSubtitleFont updateSubtitleLabelSize() refreshLayout() } } } /// 垂直布局下的标题字体,默认为 UIFontMake(15) @objc dynamic var verticalTitleFont = UIFontMake(15) { didSet { if style == .subTitleVertical { titleLabel.font = verticalTitleFont updateTitleLabelSize() refreshLayout() } } } /// 垂直布局下的副标题字体,默认为 UIFontLightMake(12) @objc dynamic var verticalSubtitleFont = UIFontLightMake(12) { didSet { if style == .subTitleVertical { subtitleLabel.font = verticalSubtitleFont updateSubtitleLabelSize() refreshLayout() } } } /// 标题的上下左右间距,当标题不显示时,计算大小及布局时也不考虑这个间距,默认为 UIEdgeInsetsZero @objc dynamic var titleEdgeInsets = UIEdgeInsets.zero { didSet { refreshLayout() } } /// 副标题的上下左右间距,当副标题不显示时,计算大小及布局时也不考虑这个间距,默认为 UIEdgeInsetsZero @objc dynamic var subtitleEdgeInsets = UIEdgeInsets.zero { didSet { refreshLayout() } } // MARK: - Loading private(set) var loadingView: UIActivityIndicatorView? /* * 设置是否需要loading,只有开启了这个属性,loading才有可能显示出来。默认值为false。 */ var needsLoadingView = false { didSet { if needsLoadingView { if loadingView == nil { loadingView = UIActivityIndicatorView(activityIndicatorStyle: NavBarActivityIndicatorViewStyle, size: loadingViewSize) loadingView!.color = tintColor loadingView!.stopAnimating() addSubview(loadingView!) } } else { if let loadingView = loadingView { loadingView.stopAnimating() loadingView.removeFromSuperview() self.loadingView = nil } } refreshLayout() } } /* * `needsLoadingView`开启之后,通过这个属性来控制loading的显示和隐藏,默认值为YES * * @see needsLoadingView */ var loadingViewHidden = true { didSet { if needsLoadingView { loadingViewHidden ? loadingView?.stopAnimating() : loadingView?.startAnimating() } refreshLayout() } } /* * 如果为true则title居中,loading放在title的左边,title右边有一个跟左边loading一样大的占位空间;如果为false,loading和title整体居中。默认值为true。 */ var needsLoadingPlaceholderSpace = true { didSet { refreshLayout() } } @objc dynamic var loadingViewSize = CGSize(width: 18, height: 18) /* * 控制loading距离右边的距离 */ @objc dynamic var loadingViewMarginRight: CGFloat = 3 { didSet { refreshLayout() } } // MARK: - Accessory /* * 当accessoryView不为空时,QMUINavigationTitleViewAccessoryType设置无效,一直都是None */ private var _accessoryView: UIView? var accessoryView: UIView? { get { return _accessoryView } set { if _accessoryView != accessoryView { _accessoryView?.removeFromSuperview() _accessoryView = nil } if let accessoryView = accessoryView { accessoryType = .none accessoryView.sizeToFit() addSubview(accessoryView) } refreshLayout() } } /* * 只有当accessoryView为空时才有效 */ var accessoryType: QMUINavigationTitleViewAccessoryType = .none { didSet { if accessoryType == .none { accessoryTypeView?.removeFromSuperview() accessoryTypeView = nil refreshLayout() return } if accessoryTypeView == nil { accessoryTypeView = UIImageView() accessoryTypeView!.contentMode = .center addSubview(accessoryTypeView!) } var accessoryImage: UIImage? if accessoryType == .disclosureIndicator { accessoryImage = NavBarAccessoryViewTypeDisclosureIndicatorImage?.qmui_image(orientation: .up) } accessoryTypeView!.image = accessoryImage accessoryTypeView!.sizeToFit() // 经过上面的 setImage 和 sizeToFit 之后再 addSubview,因为 addSubview 会触发系统来询问你的 sizeThatFits: if accessoryTypeView!.superview != self { addSubview(accessoryTypeView!) } refreshLayout() } } /* * 用于微调accessoryView的位置 */ @objc dynamic var accessoryViewOffset: CGPoint = CGPoint(x: 3, y: 0) { didSet { refreshLayout() } } /* * 如果为true则title居中,`accessoryView`放在title的左边或右边;如果为false,`accessoryView`和title整体居中。默认值为false。 */ var needsAccessoryPlaceholderSpace = false { didSet { refreshLayout() } } private var titleLabelSize: CGSize = .zero private var subtitleLabelSize: CGSize = .zero private var accessoryTypeView: UIImageView? convenience override init(frame: CGRect) { self.init(style: .default, frame: frame) } convenience init(style: QMUINavigationTitleViewStyle) { self.init(style: style, frame: .zero) } init(style: QMUINavigationTitleViewStyle, frame: CGRect) { self.style = .default super.init(frame: frame) addTarget(self, action: #selector(handleTouchTitleViewEvent), for: .touchUpInside) titleLabel = UILabel() titleLabel.textAlignment = .center titleLabel.lineBreakMode = .byTruncatingTail addSubview(titleLabel) subtitleLabel = UILabel() subtitleLabel.textAlignment = .center subtitleLabel.lineBreakMode = .byTruncatingTail addSubview(subtitleLabel) isUserInteractionEnabled = false contentHorizontalAlignment = .center let appearance = QMUINavigationTitleView.appearance() maximumWidth = appearance.maximumWidth loadingViewSize = appearance.loadingViewSize loadingViewMarginRight = appearance.loadingViewMarginRight horizontalTitleFont = appearance.horizontalTitleFont horizontalSubtitleFont = appearance.horizontalSubtitleFont verticalTitleFont = appearance.verticalTitleFont verticalSubtitleFont = appearance.verticalSubtitleFont accessoryViewOffset = appearance.accessoryViewOffset tintColor = NavBarTitleColor didInitialized(style) } private static let _onceToken = UUID().uuidString fileprivate func didInitialized(_ style: QMUINavigationTitleViewStyle) { self.style = style DispatchQueue.once(token: QMUINavigationTitleView._onceToken) { QMUINavigationTitleView.setDefaultAppearance() } } override var description: String { return "\(super.description), title = \(title ?? ""), subtitle = \(subtitle ?? "")" } // MARK: - 布局 fileprivate func refreshLayout() { if let navigationBar = navigationBarSuperview(for: self) { navigationBar.setNeedsLayout() } setNeedsLayout() } /// 找到 titleView 所在的 navigationBar(iOS 11 及以后,titleView.superview.superview == navigationBar,iOS 10 及以前,titleView.superview == navigationBar) /// /// - Parameter subview: titleView /// - Returns: navigationBar fileprivate func navigationBarSuperview(for subview: UIView) -> UINavigationBar? { guard let superview = subview.superview else { return nil } if superview is UINavigationBar { return superview as? UINavigationBar } return navigationBarSuperview(for: superview) } fileprivate func updateTitleLabelSize() { if !(titleLabel.text?.isEmpty ?? true) { // 这里用 CGSizeCeil 是特地保证 titleView 的 sizeThatFits 计算出来宽度是 pt 取整,这样在 layoutSubviews 我们以 px 取整时,才能保证不会出现水平居中时出现半像素的问题,然后由于我们对半像素会认为一像素,所以导致总体宽度多了一像素,从而导致文字布局可能出现缩略... titleLabelSize = titleLabel.sizeThatFits(CGSize.max).sizeCeil } else { titleLabelSize = .zero } } fileprivate func updateSubtitleLabelSize() { if !(subtitleLabel.text?.isEmpty ?? true) { // 这里用 CGSizeCeil 是特地保证 titleView 的 sizeThatFits 计算出来宽度是 pt 取整,这样在 layoutSubviews 我们以 px 取整时,才能保证不会出现水平居中时出现半像素的问题,然后由于我们对半像素会认为一像素,所以导致总体宽度多了一像素,从而导致文字布局可能出现缩略... subtitleLabelSize = subtitleLabel.sizeThatFits(CGSize.max).sizeCeil } else { subtitleLabelSize = .zero } } fileprivate var loadingViewSpacingSize: CGSize { if needsLoadingView { return CGSize(width: loadingViewSize.width + loadingViewMarginRight, height: loadingViewSize.height) } return .zero } fileprivate var loadingViewSpacingSizeIfNeedsPlaceholder: CGSize { return CGSize(width: loadingViewSpacingSize.width * (needsLoadingPlaceholderSpace ? 2 : 1), height: loadingViewSpacingSize.height) } fileprivate var accessorySpacingSize: CGSize { if accessoryView != nil || accessoryTypeView != nil { let view = accessoryView ?? accessoryTypeView return CGSize(width: view!.bounds.width + accessoryViewOffset.x, height: view!.bounds.height) } return .zero } fileprivate var accessorySpacingSizeIfNeedesPlaceholder: CGSize { return CGSize(width: accessorySpacingSize.width * (needsAccessoryPlaceholderSpace ? 2 : 1), height: accessorySpacingSize.height) } fileprivate var titleEdgeInsetsIfShowingTitleLabel: UIEdgeInsets { return titleLabelSize.isEmpty ? .zero : titleEdgeInsets } fileprivate var subtitleEdgeInsetsIfShowingSubtitleLabel: UIEdgeInsets { return subtitleLabelSize.isEmpty ? .zero : subtitleEdgeInsets } private var contentSize: CGSize { if style == .subTitleVertical { var size = CGSize.zero // 垂直排列的情况下,loading和accessory与titleLabel同一行 var firstLineWidth = titleLabelSize.width + titleEdgeInsetsIfShowingTitleLabel.horizontalValue firstLineWidth += loadingViewSpacingSizeIfNeedsPlaceholder.width firstLineWidth += accessorySpacingSizeIfNeedesPlaceholder.width let secondLineWidth = subtitleLabelSize.width + subtitleEdgeInsetsIfShowingSubtitleLabel.horizontalValue size.width = fmax(firstLineWidth, secondLineWidth) size.height = titleLabelSize.height + titleEdgeInsetsIfShowingTitleLabel.verticalValue + subtitleLabelSize.height + subtitleEdgeInsetsIfShowingSubtitleLabel.verticalValue return size.flatted } else { var size = CGSize.zero size.width = titleLabelSize.width + titleEdgeInsetsIfShowingTitleLabel.horizontalValue + subtitleLabelSize.width + subtitleEdgeInsetsIfShowingSubtitleLabel.horizontalValue size.width += loadingViewSpacingSizeIfNeedsPlaceholder.width + accessorySpacingSizeIfNeedesPlaceholder.width size.height = fmax(titleLabelSize.height + titleEdgeInsetsIfShowingTitleLabel.verticalValue, subtitleLabelSize.height + subtitleEdgeInsetsIfShowingSubtitleLabel.verticalValue) size.height = fmax(size.height, loadingViewSpacingSizeIfNeedsPlaceholder.height) size.height = fmax(size.height, accessorySpacingSizeIfNeedesPlaceholder.height) return size.flatted } } override func sizeThatFits(_ : CGSize) -> CGSize { var resultSize = contentSize resultSize.width = fmin(resultSize.width, maximumWidth) return resultSize } override func layoutSubviews() { if bounds.size.isEmpty { // print("\(classForCoder), layoutSubviews, size = \(bounds.size)") return } super.layoutSubviews() let alignLeft = contentHorizontalAlignment == .left let alignRight = contentHorizontalAlignment == .right // 通过sizeThatFit计算出来的size,如果大于可使用的最大宽度,则会被系统改为最大限制的最大宽度 let maxSize = bounds.size // 实际内容的size,小于等于maxSize var contentSize = self.contentSize contentSize.width = fmin(maxSize.width, contentSize.width) contentSize.height = fmin(maxSize.height, contentSize.height) // 计算左右两边的偏移值 var offsetLeft: CGFloat = 0 var offsetRight: CGFloat = 0 if alignLeft { offsetLeft = 0 offsetRight = maxSize.width - contentSize.width } else if alignRight { offsetLeft = maxSize.width - contentSize.width offsetRight = 0 } else { offsetLeft = floorInPixel((maxSize.width - contentSize.width) / 2.0) offsetRight = offsetLeft } // 计算loading占的单边宽度 let loadingViewSpace = loadingViewSpacingSize.width // 获取当前accessoryView let accessoryView = self.accessoryView ?? accessoryTypeView // 计算accessoryView占的单边宽度 let accessoryViewSpace = accessorySpacingSize.width let isTitleLabelShowing = !(titleLabel.text?.isEmpty ?? true) let isSubtitleLabelShowing = !(subtitleLabel.text?.isEmpty ?? true) let titleEdgeInsets = titleEdgeInsetsIfShowingTitleLabel let subtitleEdgeInsets = subtitleEdgeInsetsIfShowingSubtitleLabel var minX = offsetLeft + (needsAccessoryPlaceholderSpace ? accessoryViewSpace : 0) var maxX = maxSize.width - offsetRight - (needsLoadingPlaceholderSpace ? loadingViewSpace : 0) if style == .subTitleVertical { if let loadingView = loadingView { loadingView.frame = loadingView.frame.setXY(minX, titleLabelSize.height.center(loadingViewSize.height) + titleEdgeInsets.top) minX = loadingView.frame.maxX + loadingViewMarginRight } if let accessoryView = accessoryView { accessoryView.frame = accessoryView.frame.setXY(maxX - accessoryView.bounds.width, titleLabelSize.height.center(accessoryView.bounds.height) + titleEdgeInsets.top + accessoryViewOffset.y) maxX = accessoryView.frame.minX - accessoryViewOffset.x } if isTitleLabelShowing { minX += titleEdgeInsets.left maxX -= titleEdgeInsets.right titleLabel.frame = CGRect(x: minX, y: titleEdgeInsets.top, width: maxX - minX, height: titleLabelSize.height).flatted } else { titleLabel.frame = .zero } if isSubtitleLabelShowing { subtitleLabel.frame = CGRect(x: subtitleEdgeInsets.left, y: (isTitleLabelShowing ? titleLabel.frame.maxY + titleEdgeInsets.bottom : 0) + subtitleEdgeInsets.top, width: maxSize.width - subtitleEdgeInsets.horizontalValue, height: subtitleLabelSize.height) } else { subtitleLabel.frame = .zero } } else { if let loadingView = loadingView { loadingView.frame = loadingView.frame.setXY(minX, maxSize.height.center(loadingViewSize.height)) minX = loadingView.frame.maxX + loadingViewMarginRight } if let accessoryView = accessoryView { accessoryView.frame = accessoryView.frame.setXY(maxX - accessoryView.bounds.width, maxSize.height.center(accessoryView.bounds.height) + accessoryViewOffset.y) maxX = accessoryView.frame.minX - accessoryViewOffset.x } if isSubtitleLabelShowing { maxX -= subtitleEdgeInsets.right // 如果当前的 contentSize 就是以这个 label 的最大占位计算出来的,那么就不应该先计算 center 再计算偏移 let shouldSubtitleLabelCenterVertically = subtitleLabelSize.height + subtitleEdgeInsets.verticalValue < contentSize.height let subtitleMinY = shouldSubtitleLabelCenterVertically ? maxSize.height.center(subtitleLabelSize.height) + subtitleEdgeInsets.top - subtitleEdgeInsets.bottom : subtitleEdgeInsets.top subtitleLabel.frame = CGRect(x: maxX - subtitleLabelSize.width, y: subtitleMinY, width: subtitleLabelSize.width, height: subtitleLabelSize.height) maxX = subtitleLabel.frame.minX - subtitleEdgeInsets.left } else { subtitleLabel.frame = .zero } if isTitleLabelShowing { minX += titleEdgeInsets.left maxX -= titleEdgeInsets.right // 如果当前的 contentSize 就是以这个 label 的最大占位计算出来的,那么就不应该先计算 center 再计算偏移 let shouldTitleLabelCenterVertically = titleLabelSize.height + titleEdgeInsets.verticalValue < contentSize.height let titleLabelMinY = shouldTitleLabelCenterVertically ? maxSize.height.center(titleLabelSize.height) + titleEdgeInsets.top - titleEdgeInsets.bottom : titleEdgeInsets.top titleLabel.frame = CGRect(x: minX, y: titleLabelMinY, width: maxX - minX, height: titleLabelSize.height) } else { titleLabel.frame = .zero } } } // MARK: - setter / getter override var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment { didSet { refreshLayout() } } override func tintColorDidChange() { super.tintColorDidChange() titleLabel.textColor = tintColor subtitleLabel.textColor = tintColor loadingView?.color = tintColor } // MARK: - Events override var isHighlighted: Bool { didSet { alpha = isHighlighted ? UIControlHighlightedAlpha : 1 } } @objc func handleTouchTitleViewEvent() { let active = !isActive delegate?.didTouch?(self, isActive: active) isActive = active refreshLayout() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension QMUINavigationTitleView { static func setDefaultAppearance() { let appearance = QMUINavigationTitleView.appearance() appearance.maximumWidth = CGFloat.greatestFiniteMagnitude appearance.loadingViewSize = CGSize(width: 18, height: 18) appearance.loadingViewMarginRight = 3 appearance.horizontalTitleFont = NavBarTitleFont appearance.horizontalSubtitleFont = NavBarTitleFont appearance.verticalTitleFont = UIFontMake(15) appearance.verticalSubtitleFont = UIFontLightMake(12) appearance.accessoryViewOffset = CGPoint(x: 3, y: 0) appearance.titleEdgeInsets = UIEdgeInsets.zero appearance.subtitleEdgeInsets = UIEdgeInsets.zero } }
3eb25930f65e81084c582b4058018b05
34.977707
269
0.637913
false
false
false
false
sigmonky/hearthechanges
refs/heads/master
iHearChangesSwift/User Interface/MainDisplayCollectionViewExtensions.swift
mit
1
// // MainDisplayCollectionViewExtensions.swift // iHearChangesSwift // // Created by Randy Weinstein on 6/30/17. // Copyright © 2017 fakeancient. All rights reserved. // import UIKit // MARK: Collection View Delegates and Helper Methods extension MainDisplay : UICollectionViewDataSource,UICollectionViewDelegate { func initializeCollectionView() -> Void { self.containerView.backgroundColor = UIColor.black collectionView!.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if progression != nil { return progression!.chordProgression.count } else { return 0; } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "measure", for: indexPath) as! MeasureCell var borderColor: CGColor! = UIColor.clear.cgColor var borderWidth: CGFloat = 0 cell.chordId.text = measureStates[(indexPath as NSIndexPath).row].display var textColor:UIColor print(measureStates[(indexPath as NSIndexPath).row].answerStatus) switch measureStates[(indexPath as NSIndexPath).row].answerStatus { case .unanswered: textColor = UIColor.white case .correct: textColor = UIColor.green case.wrong: textColor = UIColor.red } cell.chordId.textColor = textColor if measureStates[(indexPath as NSIndexPath).row].selected == true { borderColor = UIColor.orange.cgColor borderWidth = 5 } else { borderColor = UIColor.clear.cgColor borderWidth = 0 } cell.image.layer.borderWidth = borderWidth cell.image.layer.borderColor = borderColor if (indexPath as NSIndexPath).row == currentMeasure { cell.image.backgroundColor = UIColor.yellow cell.chordId.textColor = UIColor.black } else { cell.image.backgroundColor = UIColor.black } return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let lastPath = lastSelectedIndexPath { measureStates[lastPath.row].selected = false collectionView.reloadItems(at: [lastPath]) } selectedIndexPath = indexPath measureStates[(selectedIndexPath?.row)!].selected = true collectionView.reloadItems(at: [selectedIndexPath!]) lastSelectedIndexPath = indexPath } } extension MainDisplay : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = Int(view.bounds.size.width/5.0) // each image has a ratio of 4:3 let height = Int( Double(width) * 0.75 ) return CGSize(width: width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 2.0, left: 2.0, bottom: 0.0, right: 0.0) } }
5c208752a3fb721de65a6b4b2b0462ae
28.852713
160
0.61101
false
false
false
false
samwyndham/DictateSRS
refs/heads/master
Pods/CSV.swift/Sources/CSV.swift
mit
1
// // CSV.swift // CSV // // Created by Yasuhiro Hatta on 2016/06/11. // Copyright © 2016 yaslab. All rights reserved. // import Foundation private let LF = UnicodeScalar("\n")! private let CR = UnicodeScalar("\r")! private let DQUOTE = UnicodeScalar("\"")! internal let defaultHasHeaderRow = false internal let defaultTrimFields = false internal let defaultDelimiter = UnicodeScalar(",")! extension CSV: Sequence { } extension CSV: IteratorProtocol { // TODO: Documentation /// No overview available. public mutating func next() -> [String]? { return readRow() } } // TODO: Documentation /// No overview available. public struct CSV { private var iterator: AnyIterator<UnicodeScalar> private let trimFields: Bool private let delimiter: UnicodeScalar private var back: UnicodeScalar? = nil internal var currentRow: [String]? = nil /// CSV header row. To set a value for this property, you set `true` to `hasHeaerRow` in initializer. public var headerRow: [String]? { return _headerRow } private var _headerRow: [String]? = nil private let whitespaces: CharacterSet internal init<T: IteratorProtocol>( iterator: T, hasHeaderRow: Bool, trimFields: Bool, delimiter: UnicodeScalar) throws where T.Element == UnicodeScalar { self.iterator = AnyIterator(iterator) self.trimFields = trimFields self.delimiter = delimiter var whitespaces = CharacterSet.whitespaces whitespaces.remove(delimiter) self.whitespaces = whitespaces if hasHeaderRow { guard let headerRow = next() else { throw CSVError.cannotReadHeaderRow } _headerRow = headerRow } } /// Create an instance with `InputStream`. /// /// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically. /// - parameter codecType: A `UnicodeCodec` type for `stream`. /// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`. /// - parameter delimiter: Default: `","`. public init<T: UnicodeCodec>( stream: InputStream, codecType: T.Type, hasHeaderRow: Bool = defaultHasHeaderRow, trimFields: Bool = defaultTrimFields, delimiter: UnicodeScalar = defaultDelimiter) throws where T.CodeUnit == UInt8 { let reader = try BinaryReader(stream: stream, endian: .unknown, closeOnDeinit: true) let iterator = UnicodeIterator(input: reader.makeUInt8Iterator(), inputEncodingType: codecType) try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter) } /// Create an instance with `InputStream`. /// /// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically. /// - parameter codecType: A `UnicodeCodec` type for `stream`. /// - parameter endian: Endian to use when reading a stream. Default: `.big`. /// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`. /// - parameter delimiter: Default: `","`. public init<T: UnicodeCodec>( stream: InputStream, codecType: T.Type, endian: Endian = .big, hasHeaderRow: Bool = defaultHasHeaderRow, trimFields: Bool = defaultTrimFields, delimiter: UnicodeScalar = defaultDelimiter) throws where T.CodeUnit == UInt16 { let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true) let iterator = UnicodeIterator(input: reader.makeUInt16Iterator(), inputEncodingType: codecType) try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter) } /// Create an instance with `InputStream`. /// /// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically. /// - parameter codecType: A `UnicodeCodec` type for `stream`. /// - parameter endian: Endian to use when reading a stream. Default: `.big`. /// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`. /// - parameter delimiter: Default: `","`. public init<T: UnicodeCodec>( stream: InputStream, codecType: T.Type, endian: Endian = .big, hasHeaderRow: Bool = defaultHasHeaderRow, trimFields: Bool = defaultTrimFields, delimiter: UnicodeScalar = defaultDelimiter) throws where T.CodeUnit == UInt32 { let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true) let iterator = UnicodeIterator(input: reader.makeUInt32Iterator(), inputEncodingType: codecType) try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter) } fileprivate mutating func readRow() -> [String]? { currentRow = nil var next = moveNext() if next == nil { return nil } var row = [String]() var field: String var end: Bool while true { if trimFields { // Trim the leading spaces while next != nil && whitespaces.contains(next!) { next = moveNext() } } if next == nil { (field, end) = ("", true) } else if next == DQUOTE { (field, end) = readField(quoted: true) } else { back = next (field, end) = readField(quoted: false) if trimFields { // Trim the trailing spaces field = field.trimmingCharacters(in: whitespaces) } } row.append(field) if end { break } next = moveNext() } currentRow = row return row } private mutating func readField(quoted: Bool) -> (String, Bool) { var field = "" var next = moveNext() while let c = next { if quoted { if c == DQUOTE { var cNext = moveNext() if trimFields { // Trim the trailing spaces while cNext != nil && whitespaces.contains(cNext!) { cNext = moveNext() } } if cNext == nil || cNext == CR || cNext == LF { if cNext == CR { let cNextNext = moveNext() if cNextNext != LF { back = cNextNext } } // END ROW return (field, true) } else if cNext == delimiter { // END FIELD return (field, false) } else if cNext == DQUOTE { // ESC field.append(String(DQUOTE)) } else { // ERROR? field.append(String(c)) } } else { field.append(String(c)) } } else { if c == CR || c == LF { if c == CR { let cNext = moveNext() if cNext != LF { back = cNext } } // END ROW return (field, true) } else if c == delimiter { // END FIELD return (field, false) } else { field.append(String(c)) } } next = moveNext() } // END FILE return (field, true) } private mutating func moveNext() -> UnicodeScalar? { if back != nil { defer { back = nil } return back } return iterator.next() } }
89ef881fff7dde6bd3e5fc7100d45449
32.280769
115
0.515775
false
false
false
false
Skyvive/JsonSerializer
refs/heads/master
JsonSerializer/JsonSerializer+Deserialization.swift
mit
2
// // JsonSerializer+Deserialization.swift // JsonSerializer // // Created by Bradley Hilton on 4/18/15. // Copyright (c) 2015 Skyvive. All rights reserved. // import Foundation // MARK: JsonObject+Initialization extension JsonSerializer { class func loadJsonDictionary(dictionary: NSDictionary, intoObject object: NSObject) { for (key, value) in dictionary { if let key = key as? String, let mappedKey = propertyKeyForDictionaryKey(key, object: object), let mappedValue: AnyObject = valueForValue(value, key: mappedKey, object: object) { object.setValue(mappedValue, forKey: mappedKey) } } } private class func valueForValue(value: AnyObject, key: String, object: NSObject) -> AnyObject? { for (propertyName, mirrorType) in properties(object) { if propertyName == key { if let mapper = mapperForType(mirrorType.valueType), let jsonValue = JsonValue(value: value) { return mapper.propertyValueFromJsonValue(jsonValue) } } } return nil } class func properties(object: Any) -> [(String, MirrorType)] { var properties = [(String, MirrorType)]() for i in 1..<reflect(object).count { properties.append(reflect(object)[i]) } return properties } }
0e9fef5ac412e55986d9d61c85242998
31.454545
110
0.606167
false
false
false
false
cornerstonecollege/402
refs/heads/master
Digby/class_3/SwiftMovingThingsAround/SwiftMovingThingsAround/ViewController.swift
gpl-3.0
1
// // ViewController.swift // SwiftMovingThingsAround // // Created by Digby Andrews on 2016-06-15. // Copyright © 2016 Digby Andrews. All rights reserved. // import UIKit class ViewController: UIViewController { var label:UILabel = UILabel() var isTouching = Bool() override func viewDidLoad() { super.viewDidLoad() self.label.text = "My Beautiful Label" self.label.sizeToFit() self.label.center = self.view.center self.label.backgroundColor = UIColor.redColor() self.view.addSubview(self.label) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! let location = touch.locationInView(self.view) self.isTouching = CGRectContainsPoint(self.label.frame, location); } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if self.isTouching { let touch = touches.first! let location = touch.locationInView(self.view) self.label.center = location } } }
7cde9f2f35144ce9645515a9e96e8e0b
23.88
80
0.625402
false
false
false
false
pennlabs/penn-mobile-ios
refs/heads/main
PennMobile/Home/Cells/News/HomeNewsCellItem.swift
mit
1
// // HomeNewsCellItem.swift // PennMobile // // Created by Josh Doman on 2/7/19. // Copyright © 2019 PennLabs. All rights reserved. // import Foundation final class HomeNewsCellItem: HomeCellItem { static var jsonKey = "news" static var associatedCell: ModularTableViewCell.Type = HomeNewsCell.self let article: NewsArticle var showSubtitle = true init(for article: NewsArticle) { self.article = article } static func getHomeCellItem(_ completion: @escaping (([HomeCellItem]) -> Void)) { let task = URLSession.shared.dataTask(with: URL(string: "https://labs-graphql-295919.ue.r.appspot.com/graphql?query=%7BlabsArticle%7Bslug,headline,abstract,published_at,authors%7Bname%7D,dominantMedia%7BimageUrl,authors%7Bname%7D%7D,tag,content%7D%7D")!) { data, _, _ in guard let data = data else { completion([]); return } if let article = try? JSONDecoder().decode(NewsArticle.self, from: data) { completion([HomeNewsCellItem(for: article)]) } else { completion([]) } } task.resume() } func equals(item: ModularTableViewItem) -> Bool { guard let item = item as? HomeNewsCellItem else { return false } return article.data.labsArticle.headline == item.article.data.labsArticle.headline } } // MARK: - Logging ID extension HomeNewsCellItem: LoggingIdentifiable { var id: String { return article.data.labsArticle.slug } }
a3052085ee117c54daed5adedc1664a2
32.444444
278
0.659136
false
false
false
false
leejayID/Linkage-Swift
refs/heads/master
Linkage/CollectionView/CollectionCategoryModel.swift
apache-2.0
1
// // CollectionCategoryModel.swift // Linkage // // Created by LeeJay on 2017/3/10. // Copyright © 2017年 LeeJay. All rights reserved. // import UIKit class CollectionCategoryModel: NSObject { var name : String? var subcategories : [SubCategoryModel]? init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "subcategories" { subcategories = Array() guard let datas = value as? [[String : Any]] else { return } for dict in datas { let subModel = SubCategoryModel(dict: dict) subcategories?.append(subModel) } } else { super.setValue(value, forKey: key) } } override func setValue(_ value: Any?, forUndefinedKey key: String) { } } class SubCategoryModel: NSObject { var iconUrl : String? var name : String? init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "icon_url" { guard let icon = value as? String else { return } iconUrl = icon } else { super.setValue(value, forKey: key) } } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
6cf4cbc6f047887469dc0f51e30b0224
22.078125
72
0.540961
false
false
false
false
stormpath/stormpath-sdk-swift
refs/heads/develop
Stormpath/Networking/ResetPasswordAPIRequestManager.swift
apache-2.0
1
// // ResetPasswordAPIRequestManager.swift // Stormpath // // Created by Edward Jiang on 2/8/16. // Copyright © 2016 Stormpath. All rights reserved. // import Foundation typealias ResetPasswordAPIRequestCallback = ((NSError?) -> Void) class ResetPasswordAPIRequestManager: APIRequestManager { var email: String var callback: ResetPasswordAPIRequestCallback init(withURL url: URL, email: String, callback: @escaping ResetPasswordAPIRequestCallback) { self.email = email self.callback = callback super.init(withURL: url) } override func prepareForRequest() { request.httpMethod = "POST" request.httpBody = try? JSONSerialization.data(withJSONObject: ["email": email], options: []) } override func requestDidFinish(_ data: Data, response: HTTPURLResponse) { performCallback(nil) } override func performCallback(_ error: NSError?) { DispatchQueue.main.async { self.callback(error) } } }
9395fd46c774f0ad5cef723270614be9
26.052632
101
0.668288
false
false
false
false
vasilyjp/tech_salon_ios_twitter_client
refs/heads/master
TwitterClient/TwitterFeedTableViewController.swift
mit
1
// // TwitterFeedTableViewController.swift // TwitterClient // // Created by Nicholas Maccharoli on 2016/09/26. // Copyright © 2016 Vasily inc. All rights reserved. // import UIKit import Accounts import SVProgressHUD final class TwitterFeedTableViewController: UITableViewController { fileprivate var tweets: [Tweet] = [] fileprivate var isLoading: Bool = false override func viewDidLoad() { super.viewDidLoad() setupTableView() requestAccountPermision() } } // MARK: - UITableViewDataSource extension TwitterFeedTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { loadNextTweetsIfNeeded(indexPath: indexPath) let cellId = String(describing: TweetCell.self) let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TweetCell if tweets.count > indexPath.row { cell.tweet = tweets[indexPath.row] } return cell } } // MARK: - Private private extension TwitterFeedTableViewController { func setupTableView() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100.0 } func requestAccountPermision() { TweetsRequest.requestPermission() { [weak self] _, _ in guard let twitterAccount = TweetsRequest.firstAccount() else { return } DispatchQueue.main.async { if let username = twitterAccount.username { self?.title = "@\(username)" } self?.loadNextTweets() } } } private func loadNextTweets() { if isLoading { return } let isRefreshFromRefreshControl = tableView.refreshControl?.isRefreshing ?? false if !isRefreshFromRefreshControl { SVProgressHUD.show() } isLoading = true let maxId = maxTweetId() TweetsRequest.timeline(maxId: maxId) { [weak self] tweets, _ in guard let _self = self else { return } _self.isLoading = false if let tweets = tweets { _self.tweets += tweets _self.tableView.reloadData() } SVProgressHUD.dismiss() if isRefreshFromRefreshControl { _self.tableView.refreshControl?.endRefreshing() } } } private func refreshRequest() { isLoading = true tableView.refreshControl?.beginRefreshing() TweetsRequest.timeline(maxId: nil) { [weak self] tweets, _ in guard let _self = self else { return } _self.isLoading = false if let tweets = tweets { _self.tweets = tweets _self.tableView.reloadData() } _self.tableView.refreshControl?.endRefreshing() } } private func maxTweetId() -> Int64? { let oldestTweet: Tweet? = tweets.sorted(by: { $0.id < $1.id }).first return oldestTweet.flatMap { if $0.id > 0 { return $0.id - 1 } return nil } } func loadNextTweetsIfNeeded(indexPath: IndexPath) { let threshold: Int = TweetsRequest.requestMaxTweetCount let shouldLoad = (tweets.count - indexPath.row) < threshold if shouldLoad { loadNextTweets() } } @IBAction private func refresh() { tweets = [] refreshRequest() } }
e0a56b71c6e311597e18b8beee613a7c
25.568345
109
0.597076
false
false
false
false
gkaimakas/SwiftyForms
refs/heads/master
SwiftyForms/Classes/Inputs/SwitchInput.swift
mit
1
// // SwitchInput.swift // Pods // // Created by Γιώργος Καϊμακάς on 25/05/16. // // import Foundation open class SwitchInput: Input { open static let OnValue = String(true) open static let OffValue = String(false) public convenience init(name: String) { self.init(name: name, enabled: true, hidden: true) } public override init(name: String, enabled: Bool, hidden: Bool) { super.init(name: name, enabled: enabled, hidden: hidden) } open var isOn: Bool { return value == SwitchInput.OnValue } open func on() { self.value = SwitchInput.OnValue } open func off() { self.value = SwitchInput.OffValue } open func toogle() { self.value = (isOn) ? SwitchInput.OffValue : SwitchInput.OnValue } }
86f2e0f184692268915ddff913b477ab
17.820513
66
0.679837
false
false
false
false
BelledonneCommunications/linphone-iphone
refs/heads/master
Classes/Swift/Voip/Widgets/CallControlButton.swift
gpl-3.0
1
/* * Copyright (c) 2010-2020 Belledonne Communications SARL. * * This file is part of linphone-iphone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import UIKit import SwiftUI class CallControlButton : ButtonWithStateBackgrounds { // Layout constants static let default_size = 50 static let hungup_width = 65 var showActivityIndicatorDataSource : MutableLiveData<Bool>? = nil { didSet { if let showActivityIndicatorDataSource = self.showActivityIndicatorDataSource { let spinner = UIActivityIndicatorView(style: .white) spinner.color = VoipTheme.primary_color self.addSubview(spinner) spinner.matchParentDimmensions().center().done() showActivityIndicatorDataSource.readCurrentAndObserve { (show) in if (show == true) { spinner.startAnimating() spinner.isHidden = false self.isEnabled = false } else { spinner.stopAnimating() spinner.isHidden = true self.isEnabled = true } } } } } var onClickAction : (()->Void)? = nil required init?(coder: NSCoder) { super.init(coder: coder) } init (width:Int = CallControlButton.default_size, height:Int = CallControlButton.default_size, imageInset:UIEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2), buttonTheme: ButtonTheme, onClickAction : (()->Void)? = nil ) { super.init(backgroundStateColors: buttonTheme.backgroundStateColors) layer.cornerRadius = CGFloat(height/2) clipsToBounds = true contentMode = .scaleAspectFit applyTintedIcons(tintedIcons: buttonTheme.tintableStateIcons) imageView?.contentMode = .scaleAspectFit imageEdgeInsets = imageInset size(w: CGFloat(width), h: CGFloat(height)).done() self.onClickAction = onClickAction onClick { self.onClickAction?() } } }
eeab81331d3724f7651fabc4aa7d99f0
27.588235
238
0.718107
false
false
false
false
XWebView/XWebView
refs/heads/master
XWebView/XWVJson.swift
apache-2.0
2
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation // JSON Array public func jsonify<T: Collection>(_ array: T) -> String? where T.Index: BinaryInteger { // TODO: filter out values with negative index return "[" + array.map{jsonify($0) ?? ""}.joined(separator: ",") + "]" } // JSON Object public func jsonify<T: Collection, V>(_ object: T) -> String? where T.Iterator.Element == (key: String, value: V) { return "{" + object.flatMap(jsonify).joined(separator: ",") + "}" } private func jsonify<T>(_ pair: (key: String, value: T)) -> String? { guard let val = jsonify(pair.value) else { return nil } return jsonify(pair.key)! + ":" + val } // JSON Number public func jsonify<T: BinaryInteger>(_ integer: T) -> String? { return String(describing: integer) } public func jsonify<T: FloatingPoint>(_ float: T) -> String? { return String(describing: float) } // JSON Boolean public func jsonify(_ bool: Bool) -> String? { return String(describing: bool) } // JSON String public func jsonify<T: StringProtocol>(_ string: T) -> String? { return string.unicodeScalars.reduce("\"") { $0 + $1.jsonEscaped } + "\"" } private extension UnicodeScalar { var jsonEscaped: String { switch value { case 0...7: fallthrough case 11, 14, 15: return "\\u000" + String(value, radix: 16) case 16...31: fallthrough case 127...159: return "\\u00" + String(value, radix: 16) case 8: return "\\b" case 12: return "\\f" case 39: return "'" default: return escaped(asASCII: false) } } } @objc public protocol ObjCJSONStringable { var jsonString: String? { get } } public protocol CustomJSONStringable { var jsonString: String? { get } } extension CustomJSONStringable where Self: RawRepresentable { public var jsonString: String? { return jsonify(rawValue) } } public func jsonify(_ value: Any?) -> String? { guard let value = value else { return "null" } switch (value) { case is Void: return "undefined" case is NSNull: return "null" case let s as String: return jsonify(s) case let n as NSNumber: if CFGetTypeID(n) == CFBooleanGetTypeID() { return n.boolValue.description } return n.stringValue case let a as Array<Any?>: return jsonify(a) case let d as Dictionary<String, Any?>: return jsonify(d) case let s as CustomJSONStringable: return s.jsonString case let o as ObjCJSONStringable: return o.jsonString case let d as Data: return d.withUnsafeBytes { (base: UnsafePointer<UInt8>) -> String? in jsonify(UnsafeBufferPointer<UInt8>(start: base, count: d.count)) } default: let mirror = Mirror(reflecting: value) guard let style = mirror.displayStyle else { return nil } switch style { case .optional: // nested optional return jsonify(mirror.children.first?.value) case .collection, .set, .tuple: // array-like type return jsonify(mirror.children.map{$0.value}) case .class, .dictionary, .struct: return "{" + mirror.children.flatMap(jsonify).joined(separator: ",") + "}" case .enum: return jsonify(String(describing: value)) } } } private func jsonify(_ child: Mirror.Child) -> String? { if let key = child.label { return jsonify((key: key, value: child.value)) } let m = Mirror(reflecting: child.value) guard m.children.count == 2, m.displayStyle == .tuple, let key = m.children.first!.value as? String else { return nil } let val = m.children[m.children.index(after: m.children.startIndex)].value return jsonify((key: key, value: val)) }
9a445998fa9ebbb413e49ca529bd8e17
31.20438
86
0.62874
false
false
false
false
FabioTacke/RingSig
refs/heads/master
Sources/RingSig/RSA.swift
mit
1
// // RSA.swift // RingSig // // Created by Fabio Tacke on 14.06.17. // // import Foundation import BigInt public class RSA { public static func generateKeyPair(length: Int = 128) -> KeyPair { // Choose two distinct prime numbers let p = BigUInt.randomPrime(length: length) var q = BigUInt.randomPrime(length: length) while p == q { q = BigUInt.randomPrime(length: length) } // Calculate modulus and private key d let n = p * q let phi = (p-1) * (q-1) let d = PublicKey.e.inverse(phi)! return KeyPair(privateKey: d, publicKey: PublicKey(n: n)) } public static func sign(message: BigUInt, privateKey: PrivateKey, publicKey: PublicKey) -> Signature { return message.power(privateKey, modulus: publicKey.n) } public static func verify(message: BigUInt, signature: Signature, publicKey: PublicKey) -> Bool { return signature.power(PublicKey.e, modulus: publicKey.n) == message } public struct KeyPair { public let privateKey: PrivateKey public let publicKey: PublicKey } public struct PublicKey: Hashable { public let n: BigUInt public static let e = BigUInt(65537) public var hashValue: Int { return n.hashValue } public static func ==(lhs: RSA.PublicKey, rhs: RSA.PublicKey) -> Bool { return lhs.n == rhs.n } } public typealias PrivateKey = BigUInt public typealias Signature = BigUInt }
4b2a974f67ca3753015b0d079ceb68d2
24.051724
104
0.655196
false
false
false
false
jisudong555/swift
refs/heads/master
weibo/weibo/Classes/Home/StatusNormalCell.swift
mit
1
// // StatusNormalCell.swift // weibo // // Created by jisudong on 16/5/20. // Copyright © 2016年 jisudong. All rights reserved. // import UIKit class StatusNormalCell: StatusCell { override var status: Status? { didSet { pictureView.status = status let size = pictureView.calculateImageSize() makeConstraints(size) } } private func makeConstraints(pictureSize: CGSize) { let topSpace = pictureSize.height == 0 ? 0 : 10 pictureView.snp_updateConstraints { (make) in make.top.equalTo(contentLabel.snp_bottom).offset(topSpace) make.size.equalTo(pictureSize) } } static let fakeCell = StatusNormalCell() class func cellHeightWithModel(model: Status) -> CGFloat { if (fabs(model.cellHeight - 0.0) < 0.00000001) { fakeCell.status = model model.cellHeight = fakeCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height } return model.cellHeight } }
6ab0a63d70583a0855d04a1cf69f97c0
23.466667
105
0.600363
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Layers/Stretch renderer/StretchRendererViewController.swift
apache-2.0
1
// // Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class StretchRendererViewController: UIViewController, StretchRendererSettingsViewControllerDelegate { @IBOutlet var mapView: AGSMapView! private weak var rasterLayer: AGSRasterLayer? override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["StretchRendererViewController", "StretchRendererSettingsViewController", "StretchRendererInputCell", "OptionsTableViewController"] // create raster let raster = AGSRaster(name: "ShastaBW", extension: "tif") // create raster layer using the raster let rasterLayer = AGSRasterLayer(raster: raster) self.rasterLayer = rasterLayer // initialize a map with raster layer as the basemap let map = AGSMap(basemap: AGSBasemap(baseLayer: rasterLayer)) // assign map to the map view mapView.map = map } // MARK: - StretchRendererSettingsViewControllerDelegate func stretchRendererSettingsViewController(_ stretchRendererSettingsViewController: StretchRendererSettingsViewController, didSelectStretchParameters parameters: AGSStretchParameters) { let renderer = AGSStretchRenderer(stretchParameters: parameters, gammas: [], estimateStatistics: true, colorRamp: AGSColorRamp(type: .none, size: 1)) rasterLayer?.renderer = renderer } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? StretchRendererSettingsViewController { controller.delegate = self controller.preferredContentSize = CGSize(width: 375, height: 135) navController.presentationController?.delegate = self } } } extension StretchRendererViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
29902a111a32e7ad28b57b1794a14852
42.30303
216
0.724983
false
false
false
false
SeptAi/Cooperate
refs/heads/master
Cooperate/Cooperate/Class/ViewModel/MessageViewModel.swift
mit
1
// // MessageViewModel.swift // Cooperate // // Created by J on 2017/1/17. // Copyright © 2017年 J. All rights reserved. // import UIKit class MessageViewModel: CustomStringConvertible { // 项目模型 var notice:Notice // 标题 var title:String? // 作者 var author:String? // 内容 var content:String? // 正文的属性文本 var normalAttrText:NSAttributedString? // 结束时间 var endAt:Date? // 行高 -- 预留 var rowHeight:CGFloat = 0 init(model:Notice) { self.notice = model title = model.title author = model.author content = model.content endAt = model.endAt // 字体 let normalFont = UIFont.systemFont(ofSize:15) // FIXME: - 表情 normalAttrText = NSAttributedString(string: model.content ?? " ", attributes: [NSFontAttributeName:normalFont,NSForegroundColorAttributeName:UIColor.darkGray]) // 计算行高 updateRowHeight() } // 根据当前模型内容计算行高 func updateRowHeight(){ rowHeight = 100 } var description: String{ return notice.description } }
c0752fbb64c66ce68246eba6056ccb87
19.642857
167
0.57872
false
false
false
false
DouKing/WYListView
refs/heads/master
WYListViewController/ListViewController/Views/WYSegmentCell.swift
mit
1
// // WYSegmentCell.swift // WYListViewController // // Created by iosci on 2016/10/20. // Copyright © 2016年 secoo. All rights reserved. // import UIKit class WYSegmentCell: UICollectionViewCell { @IBOutlet weak var titleButton: UIButton! static let contentInsert: CGFloat = 40 class func width(withTitle title: String?) -> CGFloat { let t = NSString(string: (title == nil) ? "请选择" : title!) let width = t.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), options: [.usesFontLeading, .usesLineFragmentOrigin, .truncatesLastVisibleLine], attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 13)], context: nil).size.width return width + WYSegmentCell.contentInsert * 2 } func setup(withTitle title: String?) { if let text = title { titleButton.setTitleColor(UIColor.black, for: .normal) titleButton.setTitle(text, for: .normal) } else { titleButton.setTitleColor(UIColor.lightGray, for: .normal) titleButton.setTitle("请选择", for: .normal) } } }
723b81adea83fb676ea1b6f8479fac7c
34.028571
115
0.60522
false
false
false
false
darkzero/SimplePlayer
refs/heads/master
SimplePlayer/Player/MusicPlayer.swift
mit
1
// // MusicPlayer.swift // SimplePlayer // // Created by Lihua Hu on 2014/06/16. // Copyright (c) 2014 darkzero. All rights reserved. // import UIKit import AVFoundation import MediaPlayer // propeties protocol EnumProtocol { var simpleDescription: String { get } mutating func adjust() } enum RepeatType : EnumProtocol{ case Off, On, One; var simpleDescription: String { get { return self.getDescription() } } func getDescription() -> String{ switch self{ case .Off: return "No Repeat" case .On: return "Repeat is On" case .One: return "Repeat one song" default: return "Nothing" } } mutating func adjust() -> Void{ self = RepeatType.Off; } } enum ShuffleMode { case Off, On; } class MusicPlayer: NSObject { var currectTime = 0.0; var repeat = RepeatType.Off; var shuffle = ShuffleMode.Off; var player:MPMusicPlayerController = MPMusicPlayerController.iPodMusicPlayer(); required override init() { super.init(); // add notifications lisener self.player.beginGeneratingPlaybackNotifications(); self.registeriPodPlayerNotifications(); } deinit { NSNotificationCenter.defaultCenter().removeObserver(self); } class func defaultPlayer() -> MusicPlayer { struct Static { static var instance: MusicPlayer? = nil static var onceToken: dispatch_once_t = 0 } dispatch_once(&Static.onceToken) { Static.instance = self() } return Static.instance! } func registeriPodPlayerNotifications() { let notiCenter:NSNotificationCenter = NSNotificationCenter.defaultCenter(); notiCenter.addObserver(self, selector: "onRecivePlaybackStateDidChangeNotification:", name : MPMusicPlayerControllerPlaybackStateDidChangeNotification, object : player); notiCenter.addObserver(self, selector: "onReciveNowPlayingItemDidChangeNotification:", name : MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object : nil); notiCenter.addObserver(self, selector: "onReciveVolumeDidChangeNotification:", name : MPMusicPlayerControllerVolumeDidChangeNotification, object : nil); } var currentPlaybackTime : CGFloat { get { return CGFloat(self.player.currentPlaybackTime); } } var nowPlayingTitle : NSString { get { if (( self.player.nowPlayingItem ) != nil) { //NSLog("title : %s", self.player.nowPlayingItem.title); return self.player.nowPlayingItem.title; } else { return ""; } } } var nowPlayingArtist : NSString { get { if (( self.player.nowPlayingItem ) != nil) { return self.player.nowPlayingItem.artist; } else { return ""; } } } var nowPlayingArtwork : UIImage { get { if (( self.player.nowPlayingItem ) != nil) { var pler:MPMusicPlayerController = MPMusicPlayerController.iPodMusicPlayer(); var item:MPMediaItem = self.player.nowPlayingItem; var image:UIImage = item.artwork.imageWithSize(CGSizeMake(200, 200)); return image; //return MusicPlayer.defaultPlayer().player.nowPlayingItem.artwork.imageWithSize(CGSizeMake(200, 200)); //return UIImage(named: "defaultArtwork"); } else { return UIImage(named: "defaultArtwork"); } } } var playbackDuration : CGFloat { get { if (( self.player.nowPlayingItem ) != nil) { return CGFloat(self.player.nowPlayingItem.playbackDuration); } else { return 0.0; } } } // on playback state changed func onRecivePlaybackStateDidChangeNotification(noti:NSNotification) { var userInfo:NSDictionary = NSDictionary(object: noti.name, forKey: "NotificationName"); NSNotificationCenter.defaultCenter().postNotificationName("needRefreshPlayerViewNotification", object: self, userInfo: userInfo); } // on playing item changed func onReciveNowPlayingItemDidChangeNotification(noti:NSNotification) { var userInfo:NSDictionary = NSDictionary(object: noti.name, forKey: "NotificationName"); NSNotificationCenter.defaultCenter().postNotificationName("needRefreshPlayerViewNotification", object: self, userInfo: userInfo); } // on volume changed func onReciveVolumeDidChangeNotification(noti:NSNotification) { var userInfo:NSDictionary = NSDictionary(object: noti.name, forKey: "NotificationName"); NSNotificationCenter.defaultCenter().postNotificationName("needRefreshPlayerViewNotification", object: self, userInfo: userInfo); } }
340448c5a2acd478e844efc730c638f1
28.958824
137
0.621245
false
false
false
false
keyacid/keyacid-iOS
refs/heads/master
keyacid/SignViewController.swift
bsd-3-clause
1
// // SignViewController.swift // keyacid // // Created by Yuan Zhou on 6/24/17. // Copyright © 2017 yvbbrjdr. All rights reserved. // import UIKit class SignViewController: UIViewController { @IBOutlet weak var signature: UITextField! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() textView.inputAccessoryView = DoneView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 40), textBox: textView) } func getSelectedRemoteProfile() -> RemoteProfile? { if ProfilesTableViewController.selectedRemoteProfileIndex == -1 { let remoteProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a remote profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.performSegue(withIdentifier: "ShowProfiles", sender: self) }) remoteProfileNotSelected.addAction(OKAction) self.present(remoteProfileNotSelected, animated: true, completion: nil) return nil } return ProfilesTableViewController.remoteProfiles[ProfilesTableViewController.selectedRemoteProfileIndex] } func getSelectedLocalProfile() -> LocalProfile? { if ProfilesTableViewController.selectedLocalProfileIndex == -1 { let localProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a local profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.performSegue(withIdentifier: "ShowProfiles", sender: self) }) localProfileNotSelected.addAction(OKAction) self.present(localProfileNotSelected, animated: true, completion: nil) return nil } return ProfilesTableViewController.localProfiles[ProfilesTableViewController.selectedLocalProfileIndex] } @IBAction func signClicked() { let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } let sig: String = Crypto.sign(data: textView.text.data(using: String.Encoding.utf8)!, from: localProfile!).base64EncodedString() if sig == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrupted profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } signature.text = sig UIPasteboard.general.string = sig } @IBAction func verifyClicked() { let sig: Data? = Data.init(base64Encoded: signature.text!) if sig == nil { let notBase64: UIAlertController = UIAlertController.init(title: "Error", message: "Invalid signature!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) notBase64.addAction(OKAction) self.present(notBase64, animated: true, completion: nil) return } let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } if Crypto.verify(data: textView.text.data(using: String.Encoding.utf8)!, signature: sig!, from: remoteProfile!) { let success: UIAlertController = UIAlertController.init(title: "Success", message: "This message is signed by " + remoteProfile!.name + "!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) success.addAction(OKAction) self.present(success, animated: true, completion: nil) } else { let error: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) error.addAction(OKAction) self.present(error, animated: true, completion: nil) } } @IBAction func signatureDone() { signature.resignFirstResponder() } }
e7b1d7180c87b24b54b5a0cbac893728
47.795699
176
0.663508
false
false
false
false
ghodeaniket/CityList_IOS
refs/heads/master
CityList_IOS/CityList_IOS/City.swift
apache-2.0
1
// // City.swift // CityList_IOS // // Created by Aniket Ghode on 24/06/17. // Copyright © 2017 Aniket Ghode. All rights reserved. // import Foundation // Structure to hold the information for city from cities.json struct City{ let name: String let country: String let id: Int let location: Location init(json: [String: Any]) { name = json["name"] as? String ?? "Unknown City" country = json["country"] as? String ?? "Unknown Country" id = json["_id"] as? Int ?? 0 location = Location(json: json["coord"] as! [String : Any]) } } //MARK: - Protocols extension City : Equatable{ public static func ==(lhs: City, rhs: City) -> Bool{ return (lhs.name == rhs.name) && (lhs.country == rhs.country) } }
de144161932562d12543eddfef673ecc
21.714286
67
0.593711
false
false
false
false
greycats/Greycats.swift
refs/heads/master
Greycats/Graphics/Graphics.swift
mit
1
// // Graphics.swift // Greycats // // Created by Rex Sheng on 8/1/16. // Copyright (c) 2016 Interactive Labs. All rights reserved. // import UIKit private var _bitmapInfo: UInt32 = { var bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue bitmapInfo &= ~CGBitmapInfo.alphaInfoMask.rawValue bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue return bitmapInfo }() extension CGImage { public func op(_ closure: (CGContext?, CGRect) -> Void) -> CGImage? { let width = self.width let height = self.height let colourSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 8, space: colourSpace, bitmapInfo: bitmapInfo.rawValue) let rect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) closure(context, rect) return context!.makeImage() } public static func op(_ width: Int, _ height: Int, closure: (CGContext?) -> Void) -> CGImage? { let scale = UIScreen.main.scale let w = width * Int(scale) let h = height * Int(scale) let colourSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 8, space: colourSpace, bitmapInfo: _bitmapInfo) context!.translateBy(x: 0, y: CGFloat(h)) context!.scaleBy(x: scale, y: -scale) closure(context) return context!.makeImage() } }
975faacaa431f44770959c5cb0a1a758
37.075
170
0.659225
false
false
false
false
BelledonneCommunications/linphone-iphone
refs/heads/master
Classes/Swift/Voip/ViewModels/CallsViewModel.swift
gpl-3.0
1
/* * Copyright (c) 2010-2020 Belledonne Communications SARL. * * This file is part of linhome * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import linphonesw import AVFoundation class CallsViewModel { let currentCallData = MutableLiveData<CallData?>(nil) let callsData = MutableLiveData<[CallData]>([]) let inactiveCallsCount = MutableLiveData(0) let currentCallUnreadChatMessageCount = MutableLiveData(0) let chatAndCallsCount = MutableLiveData(0) let callConnectedEvent = MutableLiveData<Call>() let callUpdateEvent = MutableLiveData<Call>() let noMoreCallEvent = MutableLiveData(false) var core : Core { get { Core.get() } } static let shared = CallsViewModel() private var coreDelegate : CoreDelegateStub? init () { coreDelegate = CoreDelegateStub( onCallStateChanged : { (core: Core, call: Call, state: Call.State, message:String) -> Void in Log.i("[Calls] Call state changed: \(call) : \(state)") let currentCall = core.currentCall if (currentCall != nil && self.currentCallData.value??.call.getCobject != currentCall?.getCobject) { self.updateCurrentCallData(currentCall: currentCall) } else if (currentCall == nil && core.callsNb > 0) { self.updateCurrentCallData(currentCall: currentCall) } if ([.End,.Released,.Error].contains(state)) { self.removeCallFromList(call: call) } else if ([.OutgoingInit].contains(state)) { self.addCallToList(call:call) } else if ([.IncomingReceived].contains(state)) { self.addCallToList(call:call) } else if (state == .UpdatedByRemote) { let remoteVideo = call.remoteParams?.videoEnabled == true let localVideo = call.currentParams?.videoEnabled == true let autoAccept = call.core?.videoActivationPolicy?.automaticallyAccept == true if (remoteVideo && !localVideo && !autoAccept) { if (core.videoCaptureEnabled || core.videoDisplayEnabled) { try?call.deferUpdate() self.callUpdateEvent.value = call } else { call.answerVideoUpdateRequest(accept: false) } } }else if (state == Call.State.Connected) { self.callConnectedEvent.value = call } else if (state == Call.State.StreamsRunning) { self.callUpdateEvent.value = call } self.updateInactiveCallsCount() self.callsData.notifyValue() }, onMessageReceived : { (core: Core, room: ChatRoom, message: ChatMessage) -> Void in self.updateUnreadChatCount() }, onChatRoomRead : { (core: Core, room: ChatRoom) -> Void in self.updateUnreadChatCount() }, onLastCallEnded: { (core: Core) -> Void in self.currentCallData.value??.destroy() self.currentCallData.value = nil self.noMoreCallEvent.value = true } ) Core.get().addDelegate(delegate: coreDelegate!) if let currentCall = core.currentCall { currentCallData.value??.destroy() currentCallData.value = CallData(call:currentCall) } chatAndCallsCount.value = 0 inactiveCallsCount.readCurrentAndObserve { (_) in self.updateCallsAndChatCount() } currentCallUnreadChatMessageCount.readCurrentAndObserve { (_) in self.updateCallsAndChatCount() } initCallList() updateInactiveCallsCount() updateUnreadChatCount() } private func initCallList() { core.calls.forEach { addCallToList(call: $0) } } private func removeCallFromList(call: Call) { Log.i("[Calls] Removing call \(call) from calls list") if let removeCandidate = callsData.value?.filter{$0.call.getCobject == call.getCobject}.first { removeCandidate.destroy() } callsData.value = callsData.value?.filter(){$0.call.getCobject != call.getCobject} callsData.notifyValue() } private func addCallToList(call: Call) { Log.i("[Calls] Adding call \(call) to calls list") callsData.value?.append(CallData(call: call)) callsData.notifyValue() } private func updateUnreadChatCount() { guard let unread = currentCallData.value??.chatRoom?.unreadMessagesCount else { currentCallUnreadChatMessageCount.value = 0 return } currentCallUnreadChatMessageCount.value = unread } private func updateInactiveCallsCount() { inactiveCallsCount.value = core.callsNb - 1 } private func updateCallsAndChatCount() { var value = 0 if let calls = inactiveCallsCount.value { value += calls } if let chats = currentCallUnreadChatMessageCount.value { value += chats } chatAndCallsCount.value = value } func mergeCallsIntoLocalConference() { CallManager.instance().startLocalConference() } private func updateCurrentCallData(currentCall: Call?) { var callToUse = currentCall if (currentCall == nil) { Log.w("[Calls] Current call is now null") let firstCall = core.calls.first if (firstCall != nil && currentCallData.value??.call.getCobject != firstCall?.getCobject) { Log.i("[Calls] Using first call as \"current\" call") callToUse = firstCall } } guard let callToUse = callToUse else { Log.w("[Calls] No call found to be used as \"current\"") return } let firstToUse = callsData.value?.filter{$0.call.getCobject != callToUse.getCobject}.first if (firstToUse != nil) { currentCallData.value = firstToUse } else { Log.w("[Calls] Call not found in calls data list, shouldn't happen!") currentCallData.value = CallData(call: callToUse) } updateUnreadChatCount() } }
603462e27404da8c1db5824e82069e05
30.426316
104
0.709094
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_fixed/00216-swift-unqualifiedlookup-unqualifiedlookup.swift
apache-2.0
65
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck ({}) var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ } } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) - = b =b as c=b func q(v: h) -> <r>(() -> r) -> h { n { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } protocol p { } protocol m : p { } protocol v : p { } protocol m { v = m } func s<s : m, v : m u v.v == s> (m: v) { } func s<v : m u v.v == v> (m: v) { } s( { ({}) } t func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> fu ^(a: Bo } }
176cd3480586c6464111a1607dda9e3f
15.776316
79
0.49098
false
false
false
false
malcommac/Hydra
refs/heads/master
Sources/Hydra/Promise+Timeout.swift
mit
1
/* * Hydra * Fullfeatured lightweight Promise & Await Library for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation public extension Promise { /// Reject the receiving Promise if it does not resolve or reject after a given number of seconds /// /// - Parameters: /// - context: context in which the nextPromise will be executed (if not specified `background` is used) /// - timeout: timeout expressed in seconds /// - error: error to report, if nil `PromiseError.timeout` is used instead /// - Returns: promise func timeout(in context: Context? = nil, timeout: TimeInterval, error: Error? = nil) -> Promise<Value> { let ctx = context ?? .background let nextPromise = Promise<Value>(in: ctx, token: self.invalidationToken) { resolve, reject, operation in // Dispatch the result of self promise to the nextPromise // If self promise does not resolve or reject in given amount of time // nextPromise is rejected with passed error or generic timeout error // and any other result of the self promise is ignored let timer = DispatchTimerWrapper(queue: ctx.queue) timer.setEventHandler { let errorToPass = (error ?? PromiseError.timeout) reject(errorToPass) } timer.scheduleOneShot(deadline: .now() + timeout) timer.resume() // Observe resolve self.add(onResolve: { v in resolve(v) // resolve with value timer.cancel() // cancel timeout timer and release promise }, onReject: reject, onCancel: operation.cancel) } nextPromise.runBody() self.runBody() return nextPromise } }
8970be790dd6a734dbcbbb430deff56e
38.084507
107
0.736577
false
false
false
false
ruipfcosta/AutoLayoutPlus
refs/heads/master
AutoLayoutPlus/NSLayoutConstraint.swift
mit
1
// // NSLayoutConstraint.swift // AutoLayoutPlus // // Created by Rui Costa on 17/11/15. // Copyright © 2015 Rui Costa. All rights reserved. // import Foundation import UIKit public extension NSLayoutConstraint { public convenience init(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute) { self.init(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attr2, multiplier: 1, constant: 0) } public class func constraints(items views: [AnyObject], attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view: AnyObject?, attribute attr2: NSLayoutAttribute, multiplier: CGFloat = 1, constant c: CGFloat = 0) -> [NSLayoutConstraint] { return views.map { NSLayoutConstraint(item: $0, attribute: attr1, relatedBy: relation, toItem: view, attribute: attr2, multiplier: multiplier, constant: c) } } public class func withFormat(_ format: String, options: NSLayoutFormatOptions = NSLayoutFormatOptions(rawValue: 0), metrics: [String : AnyObject]? = nil, views: [String : AnyObject]) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views) } public class func withFormat(_ format: [String], metrics: [String : AnyObject]? = nil, views: [String : AnyObject]) -> [NSLayoutConstraint] { return format.flatMap { NSLayoutConstraint.constraints(withVisualFormat: $0, options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views) } } }
21996062e060c77c9380db9cca942532
54.6
270
0.730815
false
false
false
false
hacktoolkit/hacktoolkit-ios_lib
refs/heads/master
Hacktoolkit/lib/GitHub/models/GitHubUser.swift
mit
1
// // GitHubUser.swift // // Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai) // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import Foundation class GitHubUser: GitHubResource { // User attributes var login: String! var id: Int! var avatar_url: String! var gravatar_id: String! var url: String! var html_url: String! var followers_url: String! var following_url: String! var gists_url: String! var starred_url: String! var subscriptions_url: String! var organizations_url: String! var name: String! var company: String! var blog: String! var location: String! var email: String! var bio: String! var public_repos: Int! var public_gists: Int! var followers: Int! var following: Int! init() { } init(fromDict userDict: NSDictionary) { self.login = userDict["login"] as? String self.id = userDict["id"] as? Int self.avatar_url = userDict["avatar_url"] as? String self.gravatar_id = userDict["gravatar_id"] as? String self.url = userDict["url"] as? String self.html_url = userDict["html_url"] as? String self.followers_url = userDict["followers_url"] as? String self.following_url = userDict["following_url"] as? String self.gists_url = userDict["gists_url"] as? String self.starred_url = userDict["starred_url"] as? String self.subscriptions_url = userDict["subscriptions_url"] as? String self.organizations_url = userDict["organizations_url"] as? String self.name = userDict["name"] as? String self.company = userDict["company"] as? String self.blog = userDict["blog"] as? String self.location = userDict["location"] as? String self.email = userDict["email"] as? String self.bio = userDict["bio"] as? String self.public_repos = userDict["public_repos"] as? Int self.public_gists = userDict["public_gists"] as? Int self.followers = userDict["followers"] as? Int self.following = userDict["following"] as? Int } } //{ // "login": "octocat", // "id": 1, // "avatar_url": "https://github.com/images/error/octocat_happy.gif", // "gravatar_id": "somehexcode", // "url": "https://api.github.com/users/octocat", // "html_url": "https://github.com/octocat", // "followers_url": "https://api.github.com/users/octocat/followers", // "following_url": "https://api.github.com/users/octocat/following{/other_user}", // "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", // "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", // "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", // "organizations_url": "https://api.github.com/users/octocat/orgs", // "repos_url": "https://api.github.com/users/octocat/repos", // "events_url": "https://api.github.com/users/octocat/events{/privacy}", // "received_events_url": "https://api.github.com/users/octocat/received_events", // "type": "User", // "site_admin": false, // "name": "monalisa octocat", // "company": "GitHub", // "blog": "https://github.com/blog", // "location": "San Francisco", // "email": "[email protected]", // "hireable": false, // "bio": "There once was...", // "public_repos": 2, // "public_gists": 1, // "followers": 20, // "following": 0, // "created_at": "2008-01-14T04:33:35Z", // "updated_at": "2008-01-14T04:33:35Z" //}
5bf923b60b46a4138471076dc6598123
36.104167
85
0.62128
false
false
false
false
matsprea/omim
refs/heads/master
iphone/Maps/UI/PlacePage/Components/TaxiViewController.swift
apache-2.0
1
protocol TaxiViewControllerDelegate: AnyObject { func didPressOrder() } class TaxiViewController: UIViewController { @IBOutlet var taxiImageView: UIImageView! @IBOutlet var taxiNameLabel: UILabel! var taxiProvider: PlacePageTaxiProvider = .none weak var delegate: TaxiViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() switch taxiProvider { case .none: assertionFailure() case .uber: taxiImageView.image = UIImage(named: "icTaxiUber") taxiNameLabel.text = L("uber") case .yandex: taxiImageView.image = UIImage(named: "ic_taxi_logo_yandex") taxiNameLabel.text = L("yandex_taxi_title") case .maxim: taxiImageView.image = UIImage(named: "ic_taxi_logo_maksim") taxiNameLabel.text = L("maxim_taxi_title") case .rutaxi: taxiImageView.image = UIImage(named: "ic_taxi_logo_vezet") taxiNameLabel.text = L("vezet_taxi") case .freenow: taxiImageView.image = UIImage(named: "ic_logo_freenow") taxiNameLabel.text = L("freenow_taxi_title") @unknown default: fatalError() } } @IBAction func onOrder(_ sender: UIButton) { delegate?.didPressOrder() } }
92f8db302753074c8534fbf16722d0e5
28.219512
65
0.685309
false
false
false
false
devios1/Gravity
refs/heads/master
Plugins/Appearance.swift
mit
1
// // Appearance.swift // Gravity // // Created by Logan Murray on 2016-02-19. // Copyright © 2016 Logan Murray. All rights reserved. // import Foundation @available(iOS 9.0, *) extension Gravity { @objc public class Appearance: GravityPlugin { // public override var registeredElements: [String]? { // get { // return nil // } // } public override var handledAttributes: [String]? { get { return ["color", "font"] } } // public override func processValue(value: GravityNode) -> GravityResult { // // TODO: convert things like "font" and "color" here (?) // return .NotHandled // } override public func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult { // this avoids annoying warnings on the console (perhaps find a better way to more accurately determine if the layer is a transform-only layer) if node.view.isKindOfClass(UIStackView.self) { return .NotHandled } if attribute == "borderColor" || attribute == nil { if let borderColor = value?.convert() as UIColor? { node.view.layer.borderColor = borderColor.CGColor return .Handled } else { node.view.layer.borderColor = node.color.CGColor } } if attribute == "borderSize" || attribute == nil { if let borderSize = value?.floatValue { node.view.layer.borderWidth = CGFloat(borderSize) return .Handled } else { node.view.layer.borderWidth = 0 } } if attribute == "cornerRadius" || attribute == nil { if let cornerRadius = value?.floatValue { // TODO: add support for multiple radii, e.g. "5 10", "8 4 10 4" node.view.layer.cornerRadius = CGFloat(cornerRadius) node.view.clipsToBounds = true // assume this is still needed return .Handled } else { node.view.layer.cornerRadius = 0 node.view.clipsToBounds = true // false is a bad idea; true seems to work as a default } } return .NotHandled } } } @available(iOS 9.0, *) extension GravityNode { public var color: UIColor { get { return getAttribute("color", scope: .Global)?.convert() as UIColor? ?? UIColor.blackColor() } } public var font: UIFont { get { return getAttribute("font", scope: .Global)?.convert() as UIFont? ?? UIFont.systemFontOfSize(17) // same as UILabel default font } } }
a14f9e608249cb378bfe38bcc9dbfc60
26.406977
146
0.654924
false
false
false
false
CodaFi/PersistentStructure.swift
refs/heads/master
Persistent/PersistentTreeSet.swift
mit
1
// // PersistentTreeSet.swift // Persistent // // Created by Robert Widmann on 12/23/15. // Copyright © 2015 TypeLift. All rights reserved. // private let EMPTY : PersistentTreeSet = PersistentTreeSet(meta: nil, implementation: PersistentTreeMap.empty()) public class PersistentTreeSet: AbstractPersistentSet, IObj, IReversible, ISorted { private var _meta: IPersistentMap? class func create(items: ISeq) -> PersistentTreeSet { var ret: PersistentTreeSet = EMPTY for entry in items.generate() { ret = ret.cons(entry) as! PersistentTreeSet } return ret } class func create(comparator: (AnyObject?, AnyObject?) -> NSComparisonResult, items: ISeq) -> PersistentTreeSet { let impl: PersistentTreeMap = PersistentTreeMap(meta: nil, comparator: comparator) var ret: PersistentTreeSet = PersistentTreeSet(meta: nil, implementation: impl) for entry in items.generate() { ret = ret.cons(entry) as! PersistentTreeSet } return ret } init(meta: IPersistentMap?, implementation impl: IPersistentMap) { super.init(impl: impl) _meta = meta } public override func disjoin(key: AnyObject) -> IPersistentSet { if self.containsObject(key) { return PersistentTreeSet(meta: self.meta, implementation: _impl.without(key)) } return self } public override func cons(other : AnyObject) -> IPersistentCollection { if self.containsObject(other) { return self } return PersistentTreeSet(meta: self.meta, implementation: _impl.associateKey(other, withValue: other) as! IPersistentMap) } public override var empty : IPersistentCollection { return PersistentTreeSet(meta: self.meta, implementation: PersistentTreeMap.empty()) } public var reversedSeq : ISeq { return KeySeq(seq: (_impl as! IReversible).reversedSeq) } public func withMeta(meta: IPersistentMap?) -> IObj { return PersistentTreeSet(meta: meta, implementation: _impl) } public var comparator : (AnyObject?, AnyObject?) -> NSComparisonResult { return (_impl as! ISorted).comparator } public func entryKey(entry: AnyObject) -> AnyObject? { return entry } public func seq(ascending: Bool) -> ISeq? { let m: PersistentTreeMap = _impl as! PersistentTreeMap return Utils.keys(m.seq(ascending)!) } public func seqFrom(key: AnyObject, ascending: Bool) -> ISeq? { let m: PersistentTreeMap = _impl as! PersistentTreeMap return Utils.keys(m.seqFrom(key, ascending: ascending)!) } var meta : IPersistentMap? { return _meta } }
adffdea1cbad0d7392646b3198479bcf
28.638554
123
0.732927
false
false
false
false
suifengqjn/CatLive
refs/heads/master
CatLive/CatLive/Classes/Tools/Emitterable.swift
apache-2.0
1
// // Emitterable.swift // CatLive // // Created by qianjn on 2017/6/29. // Copyright © 2017年 SF. All rights reserved. // import UIKit //面向协议开发,类似于多继承,遵守某个协议,就拥有协议中的方法 protocol Emitterable { } // 对协议进行约束, 只有是UIViewController 的子类 才能 遵守这个协议 extension Emitterable where Self: UIViewController { func startEmitter() { // 1.创建发射器 let emitter = CAEmitterLayer() // 2.设置发射器的位置 emitter.emitterPosition = CGPoint(x: view.bounds.width - 50, y: view.bounds.height - 60) // 3.开启三维效果 emitter.preservesDepth = true // 4.创建例子, 并且设置例子相关的属性 // 4.1.创建例子Cell let cell = CAEmitterCell() // 4.2.设置粒子速度 cell.velocity = 150 cell.velocityRange = 100 // 4.3.设置例子的大小 cell.scale = 0.7 cell.scaleRange = 0.3 // 4.4.设置粒子方向 cell.emissionLongitude = CGFloat(-Double.pi / 2) cell.emissionRange = CGFloat(Double.pi / 2 / 6) // 4.5.设置例子的存活时间 cell.lifetime = 6 cell.lifetimeRange = 1.5 // 4.6.设置粒子旋转 cell.spin = CGFloat(Double.pi / 2) cell.spinRange = CGFloat(Double.pi / 2 / 2) // 4.6.设置例子每秒弹出的个数 cell.birthRate = 20 // 4.7.设置粒子展示的图片 cell.contents = UIImage(named: "good6_30x30")?.cgImage // 5.将粒子设置到发射器中 emitter.emitterCells = [cell] // 6.将发射器的layer添加到父layer中 view.layer.addSublayer(emitter) } func stopEmittering() { /* for layer in view.layer.sublayers! { if layer.isKind(of: CAEmitterLayer.self) { layer.removeFromSuperlayer() } } */ view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer() } }
9bcb0922b7f8284c8e391be855328d01
23.115385
105
0.54386
false
false
false
false
edx/edx-app-ios
refs/heads/master
Source/CourseHandoutsViewController.swift
apache-2.0
1
// // CourseHandoutsViewController.swift // edX // // Created by Ehmad Zubair Chughtai on 26/06/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit import WebKit public class CourseHandoutsViewController: OfflineSupportViewController, LoadStateViewReloadSupport, InterfaceOrientationOverriding { public typealias Environment = DataManagerProvider & NetworkManagerProvider & ReachabilityProvider & OEXAnalyticsProvider & OEXStylesProvider & OEXConfigProvider let courseID : String let environment : Environment let webView : WKWebView let loadController : LoadStateViewController let handouts : BackedStream<String> = BackedStream() init(environment : Environment, courseID : String) { self.environment = environment self.courseID = courseID self.webView = WKWebView(frame: .zero, configuration: environment.config.webViewConfiguration()) self.loadController = LoadStateViewController() super.init(env: environment) addListener() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() loadController.setupInController(controller: self, contentView: webView) addSubviews() setConstraints() setStyles() webView.navigationDelegate = self view.backgroundColor = environment.styles.standardBackgroundColor() setAccessibilityIdentifiers() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) environment.analytics.trackScreen(withName: OEXAnalyticsScreenHandouts, courseID: courseID, value: nil) loadHandouts() } override func reloadViewData() { loadHandouts() } override public var shouldAutorotate: Bool { return true } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .allButUpsideDown } private func setAccessibilityIdentifiers() { view.accessibilityIdentifier = "CourseHandoutsViewController:view" webView.accessibilityIdentifier = "CourseHandoutsViewController:web-view" } private func addSubviews() { view.addSubview(webView) } private func setConstraints() { webView.snp.makeConstraints { make in make.edges.equalTo(safeEdges) } } private func setStyles() { self.navigationItem.title = Strings.courseHandouts } private func streamForCourse(course : OEXCourse) -> OEXStream<String>? { if let access = course.courseware_access, !access.has_access { return OEXStream<String>(error: OEXCoursewareAccessError(coursewareAccess: access, displayInfo: course.start_display_info)) } else { let request = CourseInfoAPI.getHandoutsForCourseWithID(courseID: courseID, overrideURL: course.course_handouts) let loader = self.environment.networkManager.streamForRequest(request, persistResponse: true) return loader } } private func loadHandouts() { if !handouts.active { loadController.state = .Initial let courseStream = self.environment.dataManager.enrollmentManager.streamForCourseWithID(courseID: courseID) let handoutStream = courseStream.transform {[weak self] enrollment in return self?.streamForCourse(course: enrollment.course) ?? OEXStream<String>(error : NSError.oex_courseContentLoadError()) } self.handouts.backWithStream((courseStream.value != nil) ? handoutStream : OEXStream<String>(error : NSError.oex_courseContentLoadError())) } } private func addListener() { handouts.listen(self, success: { [weak self] courseHandouts in if let displayHTML = OEXStyles.shared().styleHTMLContent(courseHandouts, stylesheet: "handouts-announcements"), let apiHostUrl = OEXConfig.shared().apiHostURL() { self?.webView.loadHTMLString(displayHTML, baseURL: apiHostUrl) self?.loadController.state = .Loaded } else { self?.loadController.state = LoadState.failed() } }, failure: {[weak self] error in self?.loadController.state = LoadState.failed(error: error) } ) } override public func updateViewConstraints() { loadController.insets = UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: view.safeAreaInsets.bottom, right: 0) super.updateViewConstraints() } //MARK:- LoadStateViewReloadSupport method func loadStateViewReload() { loadHandouts() } } extension CourseHandoutsViewController: WKNavigationDelegate { public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { switch navigationAction.navigationType { case .linkActivated, .formSubmitted, .formResubmitted: if let URL = navigationAction.request.url, UIApplication.shared.canOpenURL(URL){ UIApplication.shared.open(URL, options: [:], completionHandler: nil) } decisionHandler(.cancel) default: decisionHandler(.allow) } } }
90b2797e5d73baccda09f3cb3a893e37
35.907285
165
0.665351
false
false
false
false
ftxbird/NetEaseMoive
refs/heads/master
NetEaseMoive/NetEaseMoive/Movie/Controller/MovieViewController.swift
mit
1
// // MovieViewController.swift // NetEaseMoive // // Created by ftxbird on 15/11/28. // Copyright © 2015年 swiftMe. All rights reserved. // import UIKit import Alamofire import AlamofireObjectMapper class MovieViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var swipeVC = SESwipeMovieViewController() var movies:[SEMoiveModel]? = [] { didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() configUI() requestDataSource() } // MARK: -数据源获取 func requestDataSource() { //待整理 let url = "http://piao.163.com/m/movie/list.html?app_id=2&mobileType=iPhone&ver=3.7.1&channel=lede&deviceId=694045B8-1E5F-4237-BE59-929C5A5922A2&apiVer=21&city=110000" Alamofire.request(.GET, url).responseObject { (response: Response<SEMoiveList, NSError>) in let movieList = response.result.value if let list : [SEMoiveModel] = movieList?.movies { self.movies = list } } } // MARK: -UI设置 --后期加入UI配置中心 func configUI() { //设置tableView tableView.backgroundColor = UIColor.whiteColor() tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .None let nib: UINib = UINib(nibName: "SEMovieTableViewCell", bundle: NSBundle.mainBundle()) tableView.registerNib(nib, forCellReuseIdentifier: "SEMovieTableViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: -tableview delegate & datasource extension MovieViewController :UITableViewDataSource,UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (movies?.count)! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SEMovieTableViewCell") as? SEMovieTableViewCell cell!.configCellForModel((movies?[indexPath.row])!) return cell! } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 110 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
166fa8744df3e49caa8a82ddb28064bf
26.623762
175
0.634409
false
false
false
false
certificate-helper/TLS-Inspector
refs/heads/master
TLS Inspector/View Controllers/AdvancedOptionsTableViewController.swift
gpl-3.0
1
import UIKit class AdvancedOptionsTableViewController: UITableViewController { var segmentControl: UISegmentedControl? override func viewDidLoad() { super.viewDidLoad() if !UserOptions.advancedSettingsNagDismissed { UIHelper(self).presentAlert(title: lang(key: "Warning"), body: lang(key: "advanced_settings_nag"), dismissed: nil) UserOptions.advancedSettingsNagDismissed = true } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return UserOptions.useOpenSSL ? 2 : 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == 0 { return lang(key: "crypto_engine_footer") } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: "Segment", for: indexPath) if let label = cell.viewWithTag(1) as? UILabel { label.text = lang(key: "Crypto Engine") } self.segmentControl = cell.viewWithTag(2) as? UISegmentedControl self.segmentControl?.setTitle("iOS", forSegmentAt: 0) self.segmentControl?.setTitle("OpenSSL", forSegmentAt: 1) self.segmentControl?.selectedSegmentIndex = UserOptions.useOpenSSL ? 1 : 0 self.segmentControl?.addTarget(self, action: #selector(self.changeCryptoEngine(sender:)), for: .valueChanged) } else if indexPath.section == 1 { cell = tableView.dequeueReusableCell(withIdentifier: "Input", for: indexPath) if let label = cell.viewWithTag(1) as? UILabel { label.text = lang(key: "Ciphers") } if let input = cell.viewWithTag(2) as? UITextField { input.placeholder = "HIGH:!aNULL:!MD5:!RC4" input.text = UserOptions.preferredCiphers input.addTarget(self, action: #selector(changeCiphers(_:)), for: .editingChanged) } } return cell } @objc func changeCryptoEngine(sender: UISegmentedControl) { UserOptions.useOpenSSL = sender.selectedSegmentIndex == 1 if sender.selectedSegmentIndex == 1 { self.tableView.insertSections(IndexSet(arrayLiteral: 1), with: .fade) } else { self.tableView.deleteSections(IndexSet(arrayLiteral: 1), with: .fade) } } @objc func changeCiphers(_ sender: UITextField) { UserOptions.preferredCiphers = sender.text ?? "" } }
dbfac1aa71b0eef62dce0ed1a9e24b0a
38.246575
126
0.634206
false
false
false
false
xplorld/WordOuroboros
refs/heads/master
WordOuroboros/WordView.swift
mit
1
// // WordView.swift // WordOuroboros // // Created by Xplorld on 2015/6/10. // Copyright (c) 2015年 Xplorld. All rights reserved. // import UIKit class WordView: UIView { @IBOutlet var label:UILabel! @IBOutlet weak var detailLabel: UILabel! weak var word:WordType! { didSet { if word != nil { label.text = word.string detailLabel.text = word.detailedString backgroundColor = word.color self.setNeedsUpdateConstraints() } } } override func awakeFromNib() { super.awakeFromNib() label.textColor = WOColor.textColor detailLabel.textColor = WOColor.textColor label.adjustsFontSizeToFitWidth = true } }
e040789aeac1b2813462bc26bfbcc975
23.1875
54
0.589147
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Widgets/Announcements/View Model/AnnouncementWidgetContent.swift
mit
1
public enum AnnouncementWidgetContent<ViewModel>: Equatable where ViewModel: NewsAnnouncementViewModel { public static func == (lhs: AnnouncementWidgetContent, rhs: AnnouncementWidgetContent) -> Bool { switch (lhs, rhs) { case (.showMoreAnnouncements, .showMoreAnnouncements): return true case (.announcement(let lhs), .announcement(let rhs)): return lhs === rhs default: return false } } case showMoreAnnouncements case announcement(ViewModel) public var viewModel: ViewModel? { if case .announcement(let viewModel) = self { return viewModel } else { return nil } } }
9eb743a98bc83a74aa6baa67a25efeb5
27.259259
104
0.583224
false
false
false
false
BlueTatami/Angle
refs/heads/master
Angle/Angle.swift
mit
1
// // Angle.swift // Angle // // Created by Alexandre Lopoukhine on 09/12/2015. // Copyright © 2015 bluetatami. All rights reserved. // /// Struct acts as a wrapper for an angle value in degrees. public struct Angle { /// Always in the range 0 ..< 360.0 public var degrees: Double { didSet { guard degrees < 0 || 360 <= degrees else { return } degrees.formTruncatingRemainder(dividingBy: 360) if degrees < 0 { degrees += 360 } } } public init(degrees: Double) { self.degrees = degrees guard degrees < 0 || 360 <= degrees else { return } self.degrees.formTruncatingRemainder(dividingBy: 360) if degrees < 0 { self.degrees += 360 } } public static func degreesToRadians(_ degrees: Double) -> Double { return degrees * Double.pi / 180 } public static func radiansToDegrees(_ radians: Double) -> Double { return radians * 180 / Double.pi } } extension Angle { public var radians: Double { get { return Angle.degreesToRadians(degrees) } set { degrees = Angle.radiansToDegrees(newValue) } } public init(radians: Double) { self = Angle(degrees: Angle.radiansToDegrees(radians)) } } // MARK: Equatable extension Angle: Equatable {} public func ==(lhs: Angle, rhs: Angle) -> Bool { return lhs.degrees == rhs.degrees } // MARK: CustomStringConvertible extension Angle: CustomStringConvertible { public var description: String { return "\(degrees)°" } }
76c57f569570f2d1a75ce453614b4115
22.424658
70
0.566082
false
false
false
false
garygriswold/Bible.js
refs/heads/master
OBSOLETE/YourBible/plugins/com-shortsands-utility/src/ios/Utility/DeviceSettings.swift
mit
1
// // DeviceSettings.swift // TempDevice // // Created by Gary Griswold on 1/8/18. // Copyright © 2018 ShortSands. All rights reserved. // import UIKit public class DeviceSettings { static func modelName() -> String { #if (arch(i386) || arch(x86_64)) && os(iOS) let DEVICE_IS_SIMULATOR = true #else let DEVICE_IS_SIMULATOR = false #endif var machineString : String = "" if DEVICE_IS_SIMULATOR == true { if let dir = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { machineString = dir } } else { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) machineString = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } } switch machineString { case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch" case "i386", "x86_64": return "Simulator" default: return machineString } } static func deviceSize() -> String { let height = UIScreen.main.nativeBounds.height let width = UIScreen.main.nativeBounds.width let bigger = max(height, width) switch bigger { case 1136: return "iPhone 5/5s/5c/SE" case 1334: return "iPhone 6/6s/7/8" case 2048: return "iPad 5/Air/Air 2/Pro 9.7 Inch" case 2208: return "iPhone 6+/6s+/7+/8+" case 2224: return "iPad Pro 10.5 Inch" case 2436: return "iPhone X" case 2732: return "iPad Pro 12.9 Inch" default: return "type Unknown \(width) \(height)" } } }
36122ebb3578e52b3b39d2b45b88bd59
43.589474
97
0.475449
false
false
false
false
zhoujihang/SwiftNetworkAgent
refs/heads/master
SwiftNetworkAgent/SwiftNetworkAgent/Extension/UIViewControllerExtension.swift
mit
1
// // UIViewControllerExtension.swift // SwiftNetworkAgent // // Created by 周际航 on 2017/3/15. // Copyright © 2017年 com.zjh. All rights reserved. // import UIKit // MARK: - 扩展 hierarchy extension UIViewController { // 该 vc 下,最后一个 presented 的vc func ext_lastPresentedViewController() -> UIViewController? { guard var vc = self.presentedViewController else {return nil} while vc.presentedViewController != nil { vc = vc.presentedViewController! } return vc } // 该 vc 下,显示在最上层的 vc func ext_topShowViewController() -> UIViewController { if let topPresentVC = self.ext_lastPresentedViewController() { return topPresentVC.ext_topShowViewController() } if let tabBarVC = self as? UITabBarController { guard let selectedVC = tabBarVC.selectedViewController else {return self} return selectedVC.ext_topShowViewController() } if let navVC = self as? UINavigationController { guard let topVC = navVC.topViewController else {return self} return topVC.ext_topShowViewController() } return self } }
9600621aa69da4c4768363da1c3cd5c1
31.611111
85
0.651618
false
false
false
false
SuPair/firefox-ios
refs/heads/master
Shared/LaunchArguments.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public struct LaunchArguments { public static let Test = "FIREFOX_TEST" public static let SkipIntro = "FIREFOX_SKIP_INTRO" public static let SkipWhatsNew = "FIREFOX_SKIP_WHATS_NEW" public static let ClearProfile = "FIREFOX_CLEAR_PROFILE" public static let StageServer = "FIREFOX_USE_STAGE_SERVER" public static let DeviceName = "DEVICE_NAME" // After the colon, put the name of the file to load from test bundle public static let LoadDatabasePrefix = "FIREFOX_LOAD_DB_NAMED:" }
048f083f22926e3087108ac23999092e
42.294118
73
0.726902
false
true
false
false
rain2540/Play-with-Algorithms-in-Swift
refs/heads/master
LeetCode/01-Array.playground/Pages/Pascal Triangle.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation //: ## Pascal's Triangle //: //: Given numRows, generate the first numRows of Pascal's triangle. //: //: For example, given numRows = 5, Return //: //: [ //: //: [1], //: //: [1,1], //: //: [1,2,1], //: //: [1,3,3,1], //: //:[1,4,6,4,1] //: //: ] //: 分析 //: //: 帕斯卡三角有如下的规律 //: //: * 第 k 层有 k 个元素 //: //: * 每层第一个以及最后一个元素值为 1 //: //: * 对于第 k (k > 2) 层第 n (n > 1 && n < k) 个元素 A[k][n], A[k][n] = A[k - 1][n - 1] + A[k - 1][n] func generate(numRows: Int) -> Array<[Int]> { var vals = Array<[Int]>(repeating: [], count: numRows) for i in 0 ..< numRows { vals[i] = [Int](repeating: 0, count: i + 1) vals[i][0] = 1 vals[i][vals[i].count - 1] = 1 if i > 0 { for j in 1 ..< vals[i].count - 1 { vals[i][j] = vals[i - 1][j - 1] + vals[i - 1][j] } } } return vals } print(generate(numRows: 5)) //: [Next](@next)
254387b41d5676cf3ccc49f1d909724f
16.381818
94
0.441423
false
false
false
false
mattdeckard/Lilliput
refs/heads/master
Lilliput/ArgumentBinder.swift
mit
1
import Foundation class ArgumentBinder<T: Equatable> { let arg: T init(_ arg: T) { self.arg = arg } } func ==<T: Equatable>(lhs: ArgumentBinder<T>, rhs: T) -> Bool { return lhs.arg == rhs }
49c16c22fdfdb7446af7fae2e43a905d
17
63
0.581395
false
false
false
false
dunkelstern/unchained
refs/heads/master
Unchained/router.swift
bsd-3-clause
1
// // router.swift // unchained // // Created by Johannes Schriewer on 30/11/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // import TwoHundred import UnchainedString import UnchainedLogger import SwiftyRegex /// Unchained route entry public struct Route { /// Router errors public enum Error: ErrorType { /// No route with that name exists case NoRouteWithThatName(name: String) /// Route contains mix of numbered and named parameters case MixedNumberedAndNamedParameters /// Missing parameter of `name` to call that route case MissingParameterForRoute(name: String) /// Wrong parameter count for a route with unnamed parameters case WrongParameterCountForRoute } /// A route request handler, takes `request`, numbered `parameters` and `namedParameters`, returns `HTTPResponseBase` public typealias RequestHandler = ((request: HTTPRequest, parameters: [String], namedParameters: [String:String]) -> HTTPResponseBase) /// Name of the route (used for route reversing) public var name: String private var re: RegEx? private var handler:RequestHandler /// Initialize a route /// /// - parameter regex: Regex to match /// - parameter handler: handler callback to run if route matches /// - parameter name: (optional) name of this route to `reverse` public init(_ regex: String, handler:RequestHandler, name: String? = nil) { do { self.re = try RegEx(pattern: regex) } catch RegEx.Error.InvalidPattern(let offset, let message) { Log.error("Route: Pattern parse error for pattern \(regex) at character \(offset): \(message)") } catch { // unused } self.handler = handler if let name = name { self.name = name } else { self.name = "r'\(regex)'" } } /// execute a route on a request /// /// - parameter request: the request on which to execute this route /// - returns: response to the request or nil if the route does not match public func execute(request: HTTPRequest) -> HTTPResponseBase? { guard let re = self.re else { return nil } let matches = re.match(request.header.url) if matches.numberedParams.count > 0 { return self.handler(request: request, parameters: matches.numberedParams, namedParameters: matches.namedParams) } return nil } // MARK: - Internal enum RouteComponentType { case Text(String) case NamedPattern(String) case NumberedPattern(Int) } /// split a route regex into components for route reversal /// /// - returns: Array of route components func splitIntoComponents() -> [RouteComponentType]? { guard let pattern = self.re?.pattern else { return nil } var patternNum = 0 var openBrackets = 0 var components = [RouteComponentType]() var currentComponent = "" currentComponent.reserveCapacity(pattern.characters.count) var gen = pattern.characters.generate() while let c = gen.next() { switch c { case "(": if openBrackets == 0 { // split point if currentComponent.characters.count > 0 { patternNum += 1 components.append(.Text(currentComponent)) currentComponent.removeAll() } } break case ")": if openBrackets == 0 { // split point if currentComponent.characters.count > 0 { var found = false for (name, idx) in self.re!.namedCaptureGroups { if idx == patternNum { components.append(.NamedPattern(name)) currentComponent.removeAll() found = true break } } if !found { components.append(.NumberedPattern(patternNum)) } } } case "[": openBrackets += 1 case "]": openBrackets -= 1 case "\\": // skip next char gen.next() default: currentComponent.append(c) } } if currentComponent.characters.count > 0 { components.append(.Text(currentComponent)) } // strip ^ on start if case .Text(let text) = components.first! { if text.characters.first! == "^" { components[0] = .Text(text.subString(fromIndex: text.startIndex.advancedBy(1))) } } // strip $ on end if case .Text(let text) = components.last! { if text.characters.last! == "$" { components.removeLast() if text.characters.count > 1 { components.append(.Text(text.subString(toIndex: text.startIndex.advancedBy(text.characters.count - 2)))) } } } return components } } /// Route reversion public extension UnchainedResponseHandler { /// reverse a route with named parameters /// /// - parameter name: the name of the route URL to produce /// - parameter parameters: the parameters to substitute /// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname /// - returns: URL of route with parameters /// /// - throws: Throws errors if route could not be reversed public func reverseRoute(name: String, parameters:[String:String], absolute: Bool = false) throws -> String { guard let route = self.fetchRoute(name) else { throw Route.Error.NoRouteWithThatName(name: name) } var result = "" if absolute { result.appendContentsOf(self.request.config.externalServerURL) } // Build route string for item in route { switch item { case .NumberedPattern: throw Route.Error.MixedNumberedAndNamedParameters case .NamedPattern(let name): if let param = parameters[name] { result.appendContentsOf(param) } else { throw Route.Error.MissingParameterForRoute(name: name) } case .Text(let text): result.appendContentsOf(text) } } return result } /// reverse a route with numbered parameters /// /// - parameter name: the name of the route URL to produce /// - parameter parameters: the parameters to substitute /// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname /// - returns: URL of route with parameters /// /// - throws: Throws errors if route could not be reversed public func reverseRoute(name: String, parameters:[String], absolute: Bool = false) throws -> String { guard let route = self.fetchRoute(name) else { throw Route.Error.NoRouteWithThatName(name: name) } var result = "" if absolute { result.appendContentsOf(self.request.config.externalServerURL) } // Build route string for item in route { switch item { case .NumberedPattern(let num): if parameters.count > num - 1 { result.appendContentsOf(parameters[num - 1]) } else { throw Route.Error.WrongParameterCountForRoute } case .NamedPattern: throw Route.Error.MixedNumberedAndNamedParameters case .Text(let text): result.appendContentsOf(text) } } return result } /// reverse a route without parameters /// /// - parameter name: the name of the route URL to produce /// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname /// - returns: URL of route with parameters /// /// - throws: Throws errors if route could not be reversed public func reverseRoute(name: String, absolute: Bool = false) throws -> String { guard let route = self.fetchRoute(name) else { throw Route.Error.NoRouteWithThatName(name: name) } var result = "" if absolute { result.appendContentsOf(self.request.config.externalServerURL) } // Build route string for item in route { switch item { case .NumberedPattern: throw Route.Error.WrongParameterCountForRoute case .NamedPattern(let name): throw Route.Error.MissingParameterForRoute(name: name) case .Text(let text): result.appendContentsOf(text) } } return result } /// Fetch a route by name /// /// - parameter name: Name to search /// - returns: Route instance or nil if not found private func fetchRoute(name: String) -> [Route.RouteComponentType]? { for route in self.request.config.routes { if route.name == name { return route.splitIntoComponents() } } return nil } }
6451e300d99497dc30943dc5fd38284d
32.608247
138
0.557362
false
false
false
false
toggl/superday
refs/heads/develop
teferi/Services/Implementations/Persistency/DefaultTimeSlotService.swift
bsd-3-clause
1
import CoreData import RxSwift import Foundation class DefaultTimeSlotService : TimeSlotService { // MARK: Private Properties private let timeService : TimeService private let loggingService : LoggingService private let locationService : LocationService private let persistencyService : BasePersistencyService<TimeSlot> private let timeSlotCreatedSubject = PublishSubject<TimeSlot>() private let timeSlotsUpdatedSubject = PublishSubject<[TimeSlot]>() // MARK: Initializer init(timeService: TimeService, loggingService: LoggingService, locationService: LocationService, persistencyService: BasePersistencyService<TimeSlot>) { self.timeService = timeService self.loggingService = loggingService self.locationService = locationService self.persistencyService = persistencyService } // MARK: Public Methods @discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, categoryWasSetByUser: Bool, tryUsingLatestLocation: Bool) -> TimeSlot? { let location : Location? = tryUsingLatestLocation ? locationService.getLastKnownLocation() : nil return addTimeSlot(withStartTime: startTime, category: category, categoryWasSetByUser: categoryWasSetByUser, location: location) } @discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, categoryWasSetByUser: Bool, location: Location?) -> TimeSlot? { let timeSlot = TimeSlot(startTime: startTime, category: category, categoryWasSetByUser: categoryWasSetByUser, categoryWasSmartGuessed: false, location: location) return tryAdd(timeSlot: timeSlot) } @discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, location: Location?) -> TimeSlot? { let timeSlot = TimeSlot(startTime: startTime, category: category, location: location) return tryAdd(timeSlot: timeSlot) } @discardableResult func addTimeSlot(fromTemporaryTimeslot temporaryTimeSlot: TemporaryTimeSlot) -> TimeSlot? { let timeSlot = TimeSlot(startTime: temporaryTimeSlot.start, endTime: temporaryTimeSlot.end, category: temporaryTimeSlot.category, location: temporaryTimeSlot.location, categoryWasSetByUser: false, categoryWasSmartGuessed: temporaryTimeSlot.isSmartGuessed, activity: temporaryTimeSlot.activity) return tryAdd(timeSlot: timeSlot) } func getTimeSlots(forDay day: Date) -> [TimeSlot] { return getTimeSlots(forDay: day, category: nil) } func getTimeSlots(forDay day: Date, category: Category?) -> [TimeSlot] { let startTime = day.ignoreTimeComponents() as NSDate let endTime = day.tomorrow.ignoreTimeComponents().addingTimeInterval(-1) as NSDate var timeSlots = [TimeSlot]() if let category = category { let predicates = [Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime), Predicate(parameter: "category", equals: category.rawValue as AnyObject)] timeSlots = persistencyService.get(withANDPredicates: predicates) } else { let predicate = Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime) timeSlots = persistencyService.get(withPredicate: predicate) } return timeSlots } func getTimeSlots(sinceDaysAgo days: Int) -> [TimeSlot] { let today = timeService.now.ignoreTimeComponents() let startTime = today.add(days: -days).ignoreTimeComponents() as NSDate let endTime = today.tomorrow.ignoreTimeComponents() as NSDate let predicate = Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime) let timeSlots = persistencyService.get(withPredicate: predicate) return timeSlots } func getTimeSlots(betweenDate firstDate: Date, andDate secondDate: Date) -> [TimeSlot] { let date1 = firstDate.ignoreTimeComponents() as NSDate let date2 = secondDate.add(days: 1).ignoreTimeComponents() as NSDate let predicate = Predicate(parameter: "startTime", rangesFromDate: date1, toDate: date2) let timeSlots = persistencyService.get(withPredicate: predicate) return timeSlots } func getLast() -> TimeSlot? { return persistencyService.getLast() } func calculateDuration(ofTimeSlot timeSlot: TimeSlot) -> TimeInterval { let endTime = getEndTime(ofTimeSlot: timeSlot) return endTime.timeIntervalSince(timeSlot.startTime) } // MARK: Private Methods private func tryAdd(timeSlot: TimeSlot) -> TimeSlot? { //The previous TimeSlot needs to be finished before a new one can start guard endPreviousTimeSlot(atDate: timeSlot.startTime) && persistencyService.create(timeSlot) else { loggingService.log(withLogLevel: .warning, message: "Failed to create new TimeSlot") return nil } loggingService.log(withLogLevel: .info, message: "New TimeSlot with category \"\(timeSlot.category)\" created") NotificationCenter.default.post(OnTimeSlotCreated(startTime: timeSlot.startTime)) timeSlotCreatedSubject.on(.next(timeSlot)) return timeSlot } private func getEndTime(ofTimeSlot timeSlot: TimeSlot) -> Date { if let endTime = timeSlot.endTime { return endTime} let date = timeService.now let timeEntryLimit = timeSlot.startTime.tomorrow.ignoreTimeComponents() let timeEntryLastedOverOneDay = date > timeEntryLimit //TimeSlots can't go past midnight let endTime = timeEntryLastedOverOneDay ? timeEntryLimit : date return endTime } private func endPreviousTimeSlot(atDate date: Date) -> Bool { guard let timeSlot = persistencyService.getLast() else { return true } let startDate = timeSlot.startTime var endDate = date guard endDate > startDate else { loggingService.log(withLogLevel: .warning, message: "Trying to create a negative duration TimeSlot") return false } //TimeSlot is going for over one day, we should end it at midnight if startDate.ignoreTimeComponents() != endDate.ignoreTimeComponents() { loggingService.log(withLogLevel: .info, message: "Early ending TimeSlot at midnight") endDate = startDate.tomorrow.ignoreTimeComponents() } let predicate = Predicate(parameter: "startTime", equals: timeSlot.startTime as AnyObject) let editFunction = { (timeSlot: TimeSlot) -> TimeSlot in return timeSlot.withEndDate(endDate) } guard let _ = persistencyService.singleUpdate(withPredicate: predicate, updateFunction: editFunction) else { loggingService.log(withLogLevel: .warning, message: "Failed to end TimeSlot started at \(timeSlot.startTime) with category \(timeSlot.category)") return false } return true } }
a6badb335cba3cf5c107f5fc539e7d05
38.80303
161
0.631011
false
false
false
false
testpress/ios-app
refs/heads/master
ios-app/UI/StartQuizExamViewController.swift
mit
1
// // StartQuizExamViewController.swift // ios-app // // Created by Karthik on 12/05/20. // Copyright © 2020 Testpress. All rights reserved. // import UIKit import RealmSwift class StartQuizExamViewController: UIViewController { @IBOutlet weak var examTitle: UILabel! @IBOutlet weak var questionsCount: UILabel! @IBOutlet weak var startEndDate: UILabel! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var examInfoLabel: UILabel! @IBOutlet weak var bottomShadowView: UIView! @IBOutlet weak var startButtonLayout: UIView! @IBOutlet weak var navigationBarItem: UINavigationItem! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var contentView: UIStackView! @IBOutlet weak var containerView: UIView! var content: Content! var viewModel: QuizExamViewModel! var emptyView: EmptyView! let alertController = UIUtils.initProgressDialog(message: "Please wait\n\n") override func viewDidLoad() { viewModel = QuizExamViewModel(content: content) bindData() UIUtils.setButtonDropShadow(startButton) addContentAttemptListViewController() initializeEmptyView() } func initializeEmptyView() { emptyView = EmptyView.getInstance(parentView: view) emptyView.frame = view.frame } func addContentAttemptListViewController() { let storyboard = UIStoryboard(name: Constants.CHAPTER_CONTENT_STORYBOARD, bundle: nil) let viewController = storyboard.instantiateViewController( withIdentifier: Constants.CONTENT_EXAM_ATTEMPS_TABLE_VIEW_CONTROLLER ) as! ContentExamAttemptsTableViewController viewController.content = content add(viewController) viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] viewController.view.frame = self.containerView.frame } func bindData() { examTitle.text = viewModel.title questionsCount.text = viewModel.noOfQuestions startEndDate.text = viewModel.startEndDate descriptionLabel.text = viewModel.description if viewModel.description.isEmpty { descriptionLabel.isHidden = true } startButtonLayout.isHidden = !viewModel.canStartExam && content.isLocked examInfoLabel.text = viewModel.examInfo if content != nil && content.isLocked { examInfoLabel.text = Strings.SCORE_GOOD_IN_PREVIOUS startButtonLayout.isHidden = true } if (examInfoLabel.text?.isEmpty == true) { examInfoLabel.isHidden = true } } @IBAction func startExam(_ sender: UIButton) { present(alertController, animated: false, completion: nil) viewModel.loadAttempt { contentAttempt, error in self.alertController.dismiss(animated: true, completion: nil) if let error = error { var retryButtonText: String? var retryHandler: (() -> Void)? if error.kind == .network { retryButtonText = Strings.TRY_AGAIN retryHandler = { self.startExam(sender) } } let (image, title, description) = error.getDisplayInfo() self.emptyView.show(image: image, title: title, description: description, retryButtonText: retryButtonText, retryHandler: retryHandler) return } try! Realm().write { self.content.attemptsCount += 1 } self.showQuestions(contentAttempt: contentAttempt!) } } func showQuestions(contentAttempt: ContentAttempt) { let storyboard = UIStoryboard(name: Constants.TEST_ENGINE, bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: Constants.QUIZ_EXAM_VIEW_CONTROLLER) as! QuizExamViewController viewController.contentAttempt = contentAttempt viewController.exam = content.exam present(viewController, animated: true, completion: nil) } override func viewDidLayoutSubviews() { // Add gradient shadow layer to the shadow container view if bottomShadowView != nil { let bottomGradient = CAGradientLayer() bottomGradient.frame = bottomShadowView.bounds bottomGradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor] bottomShadowView.layer.insertSublayer(bottomGradient, at: 0) } // Set scroll view content height to support the scroll scrollView.contentSize.height = contentView.frame.size.height } }
90d15031a6036a0a509ccf8898c15a35
37.188976
152
0.648866
false
false
false
false
See-Ku/SK4Toolkit
refs/heads/master
SK4Toolkit/core/SK4Interpolation.swift
mit
1
// // SK4Interpolation.swift // SK4Toolkit // // Created by See.Ku on 2016/03/30. // Copyright (c) 2016 AxeRoad. All rights reserved. // import UIKit // ///////////////////////////////////////////////////////////// // MARK: - 線形補間で使用するプロトコル public protocol SK4InterpolationType: SignedNumberType { func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self func %(lhs: Self, rhs: Self) -> Self } extension Double: SK4InterpolationType { } extension CGFloat: SK4InterpolationType { } extension Int: SK4InterpolationType { } // ///////////////////////////////////////////////////////////// // MARK: - 線形補間 /// 単純な線形補間 public func sk4Interpolation<T: SK4InterpolationType>(y0 y0: T, y1: T, x0: T, x1: T, x: T) -> T { if x0 == x1 { return (y0 + y1) / 2 } else { return (y0 * (x1 - x) + y1 * (x - x0)) / (x1 - x0) } } /// 上限/下限付きの線形補間 public func sk4InterpolationFloor<T: SK4InterpolationType>(y0 y0: T, y1: T, x0: T, x1: T, x: T) -> T { if x <= x0 { return y0 } if x >= x1 { return y1 } return sk4Interpolation(y0: y0, y1: y1, x0: x0, x1: x1, x: x) } /// 繰り返す形式の線形補間 public func sk4InterpolatioCycle<T: SK4InterpolationType>(y0: T, y1: T, x0: T, x1: T, x: T) -> T { if x0 == x1 { return (y0 + y1) / 2 } let max = abs(x1 - x0) let dif = abs(x - x0) let xn = dif % (max * 2) if xn < max { return sk4Interpolation(y0: y0, y1: y1, x0: 0, x1: max, x: xn) } else { return sk4Interpolation(y0: y0, y1: y1, x0: 0, x1: max, x: xn - max) } } // ///////////////////////////////////////////////////////////// /// 単純な線形補間(UIColor用) public func sk4Interpolation(y0 y0: UIColor, y1: UIColor, x0: CGFloat, x1: CGFloat, x: CGFloat) -> UIColor { let c0 = y0.colors let c1 = y1.colors var cn: [CGFloat] = [1, 1, 1, 1] for i in 0..<4 { cn[i] = sk4Interpolation(y0: c0[i], y1: c1[i], x0: x0, x1: x1, x: x) } return UIColor(colors: cn) } // eof
34a9a6c81f5cd09e3d6fd63d012c2712
21.191011
108
0.549367
false
false
false
false
coderwhy/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Home/View/RecommendGameView.swift
mit
1
// // RecommendGameView.swift // DYZB // // Created by 1 on 16/9/21. // Copyright © 2016年 小码哥. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { // MARK: 定义数据的属性 var groups : [BaseGameModel]? { didSet { // 刷新表格 collectionView.reloadData() } } // MARK: 控件属性 @IBOutlet weak var collectionView: UICollectionView! // MARK: 系统回调 override func awakeFromNib() { super.awakeFromNib() // 让控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() // 注册Cell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) // 给collectionView添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } // MARK:- 提供快速创建的类方法 extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = groups![(indexPath as NSIndexPath).item] return cell } }
76e4eec7cfe0a328e6df6dd5943e6c3b
27.5
126
0.669408
false
false
false
false
groue/GRDB.swift
refs/heads/master
GRDB/QueryInterface/SQL/Column.swift
mit
1
/// A type that represents a column in a database table. /// /// ## Topics /// /// ### Standard Columns /// /// - ``rowID`` /// /// ### Deriving SQL Expressions /// /// - ``detached`` /// - ``match(_:)`` /// /// ### Creating Column Assignments /// /// - ``noOverwrite`` /// - ``set(to:)`` public protocol ColumnExpression: SQLSpecificExpressible { /// The column name. /// /// The column name is never qualified with a table name. /// /// For example, the name of a column can be `"score"`, but /// not `"player.score"`. var name: String { get } } extension ColumnExpression { public var sqlExpression: SQLExpression { .column(name) } /// An SQL expression that refers to an aliased column /// (`expression AS alias`). /// /// Once detached, a column is never qualified with any table name in the /// SQL generated by the query interface. /// /// For example, see how `Column("total").detached` makes it possible to /// sort this query, when a raw `Column("total")` could not: /// /// ```swift /// // SELECT player.*, /// // (player.score + player.bonus) AS total, /// // team.* /// // FROM player /// // JOIN team ON team.id = player.teamID /// // ORDER BY total, player.name /// // ~~~~~ /// let request = Player /// .annotated(with: (Column("score") + Column("bonus")).forKey("total")) /// .including(required: Player.team) /// .order(Column("total").detached, Column("name")) /// ``` public var detached: SQLExpression { SQL(sql: name.quotedDatabaseIdentifier).sqlExpression } } extension ColumnExpression where Self == Column { /// The hidden rowID column. public static var rowID: Self { Column.rowID } } /// A column in a database table. /// /// ## Topics /// /// ### Standard Columns /// /// - ``rowID-3bn70`` /// /// ### Creating A Column /// /// - ``init(_:)-5grmu`` /// - ``init(_:)-7xc4z`` public struct Column { /// The hidden rowID column. public static let rowID = Column("rowid") public var name: String /// Creates a `Column` given its name. /// /// The name should be unqualified, such as `"score"`. Qualified name such /// as `"player.score"` are unsupported. public init(_ name: String) { self.name = name } /// Creates a `Column` given a `CodingKey`. public init(_ codingKey: some CodingKey) { self.name = codingKey.stringValue } } extension Column: ColumnExpression { } /// Support for column enums: /// /// struct Player { /// enum Columns: String, ColumnExpression { /// case id, name, score /// } /// } extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String { public var name: String { rawValue } }
dede64efff0b934cf574627c0584a0a9
25.574074
82
0.572822
false
false
false
false
tbaranes/SwiftyUtils
refs/heads/master
Sources/PropertyWrappers/UserDefaultsBacked.swift
mit
1
// // UserDefaultsBacked.swift // SwiftyUtils // // Created by Tom Baranes on 25/04/2020. // Copyright © 2020 Tom Baranes. All rights reserved. // // Inspiration from: https://www.swiftbysundell.com/articles/property-wrappers-in-swift/ // import Foundation /// A property wrapper to get or set values in a user's defaults database. @propertyWrapper public struct UserDefaultsBacked<Value> { private let key: String private let defaultValue: Value private var storage: UserDefaults /// Initialize a `UserDefaultsBacked` with a default value. /// - Parameters: /// - key: The name of one of the receiver's properties. /// - defaultValue: The default value to use if there's none in the database. /// - storage: The `UserDefaults` database to use. The default value is `.standard`. public init(key: String, defaultValue: Value, storage: UserDefaults = .standard) { self.key = key self.defaultValue = defaultValue self.storage = storage } public var wrappedValue: Value { get { let value = storage.value(forKey: key) as? Value return value ?? defaultValue } set { if let optional = newValue as? AnyOptional, optional.isNil { storage.removeObject(forKey: key) } else { storage.setValue(newValue, forKey: key) } } } } extension UserDefaultsBacked where Value: ExpressibleByNilLiteral { /// Initialize a `UserDefaultsBacked` without default value. /// - Parameters: /// - key: The name of one of the receiver's properties. /// - storage: The `UserDefaults` database to use. The default value is `.standard`. public init(key: String, storage: UserDefaults = .standard) { self.init(key: key, defaultValue: nil, storage: storage) } }
f86ecceaf83d609be51d5b7c43746efd
32.446429
90
0.646022
false
false
false
false