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
solszl/Shrimp500px
refs/heads/master
Shrimp500px/ViewControllers/My/OAuth/WebViewController.swift
mit
1
// // OAuthWebViewController.swift // Shrimp500px // // Created by 振亮 孙 on 16/2/29. // Copyright © 2016年 papa.studio. All rights reserved. // import OAuthSwift import UIKit let oauthswift = OAuth1Swift( consumerKey: CustomKey, consumerSecret: CustomSecret, requestTokenUrl: "https://api.500px.com/v1/oauth/request_token", authorizeUrl:"https://api.500px.com/v1/oauth/authorize", accessTokenUrl:"https://api.500px.com/v1/oauth/access_token" ) /// 登陆界面,进行OAuth验证 <li/>网页.这样可以不跳转到safari class WebViewController: OAuthWebViewController { var targetURL : NSURL = NSURL() // web 容器 let webView = UIWebView() override func viewDidLoad() { super.viewDidLoad() // 根据web容器大小对网页是否进行缩放 self.webView.scalesPageToFit = true // 设置webview的代理 self.webView.delegate = self self.webView.frame = ScreenBounds self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(cancel)) let url = NSBundle.mainBundle().URLForResource("about", withExtension:"html") let myRequest = NSURLRequest(URL: url!); webView.loadRequest(myRequest); self.view.addSubview(self.webView) } override func handle(url: NSURL) { self.targetURL = url super.handle(url) loadAddress() } func loadAddress() { let req = NSURLRequest(URL: self.targetURL) // 请求登陆 self.webView.loadRequest(req) } func cancel() { dismissViewControllerAnimated(true, completion: nil) } } extension WebViewController: UIWebViewDelegate { func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.URL where (url.scheme == "shrimp500px"){ self.dismissWebViewController() } return true } }
da757a020cc1cea2aebff340b0e6e9da
27.366197
137
0.644489
false
false
false
false
heshamsalman/OctoViewer
refs/heads/master
OctoViewerTests/LoginCoordinatorSpec.swift
apache-2.0
1
// // LoginCoordinatorSpec.swift // OctoViewer // // Created by Hesham Salman on 5/26/17. // Copyright © 2017 Hesham Salman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Quick import Nimble @testable import OctoViewer class LoginCoordinatorSpec: QuickSpec { override func spec() { var coordinator: LoginCoordinator! var app: MockUIApplication! var vc: MockUIViewController! beforeEach { vc = MockUIViewController() app = MockUIApplication() coordinator = LoginCoordinator(navigationController: nil) coordinator.application = app app.keyWindow?.rootViewController = vc app.keyWindow?.makeKeyAndVisible() } it("presents a view on the application") { coordinator.start() expect(vc.presentedController).toNot(beNil()) expect(vc.didPresent).to(beTruthy()) } it("presents a view on the application, alternate call") { coordinator.presentLoginViewController() expect(vc.presentedController).toNot(beNil()) expect(vc.didPresent).to(beTruthy()) } describe("Generic coordinator functionality") { it("can add and remove a child") { let secondaryCoordinator = AppCoordinator() coordinator.addChild(coordinator: secondaryCoordinator) expect(coordinator.childCoordinators.contains(where: { $0 === secondaryCoordinator })).to(beTruthy()) coordinator.removeChild(coordinator: secondaryCoordinator) expect(coordinator.childCoordinators.contains(where: { $0 === secondaryCoordinator })).to(beFalsy()) } it("doesn't blow up trying to remove something that doesn't exit") { let secondaryCoordinator = AppCoordinator() coordinator.removeChild(coordinator: secondaryCoordinator) } } } }
2b18258b07ce37d1ce350ea59c4f98d3
31.263889
109
0.705553
false
false
false
false
scotlandyard/expocity
refs/heads/master
expocity/Controller/Main/CController.swift
mit
1
import UIKit class CController:UIViewController { weak var layoutLeft:NSLayoutConstraint! weak var layoutRight:NSLayoutConstraint! weak var shadow:VMainShadow? override var title:String? { didSet { parentController.viewParent.bar.label.text = title } } override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge() extendedLayoutIncludesOpaqueBars = false automaticallyAdjustsScrollViewInsets = false } override var preferredStatusBarStyle:UIStatusBarStyle { return UIStatusBarStyle.lightContent } override var prefersStatusBarHidden:Bool { return false } //MARK: public func addShadow() { let shadow:VMainShadow = VMainShadow() self.shadow = shadow view.addSubview(shadow) let views:[String:UIView] = [ "shadow":shadow] let metrics:[String:CGFloat] = [:] view.addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[shadow]-0-|", options:[], metrics:metrics, views:views)) view.addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[shadow]-0-|", options:[], metrics:metrics, views:views)) view.layoutIfNeeded() } }
9ab556e3df093098e3651a79b634ef32
22.698413
62
0.575352
false
false
false
false
curiousurick/Rye
refs/heads/master
Login/LogViewController.swift
mit
1
// // LoginViewController.swift // Login // // Created by Jason Kwok on 2/7/15. // Copyright (c) 2015 Jason Kwok. All rights reserved. // import UIKit import Parse class LogViewController: UIViewController, UITextFieldDelegate { @IBOutlet var loginButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var facebookButton: UIButton! @IBOutlet var signupButton: UIButton! @IBOutlet weak var Email: UITextField! @IBOutlet weak var Password: UITextField! func checkInput() -> Bool{ var u = setUsername(Email.text) var p = setPassword(Password.text) var ErrorAlert: UIAlertView = UIAlertView() var isGood: Bool if u == "Good" && p == "Good" { isGood = true } else { if u == "Bad" { ErrorAlert.title = "Invalid Email! 😫" ErrorAlert.message = "Please enter a valid email address" isGood = false } else if p == "Short" { ErrorAlert.title = "Too Short! 😫" ErrorAlert.message = "Password requires 8 or more characters." isGood = false } else if p == "Letters" { ErrorAlert.title = "No Letters! 😫" ErrorAlert.message = "Password requires a letter." isGood = false } else if p == "Numbers" { ErrorAlert.title = "No Numbers! 😫" ErrorAlert.message = "Password requires a number." isGood = false } else { ErrorAlert.title = "I have no idea what happened" ErrorAlert.message = "I guess try again?" isGood = false } ErrorAlert.delegate = self ErrorAlert.addButtonWithTitle("OK") ErrorAlert.show() } return isGood } @IBAction func loginButtonClicked(sender: AnyObject) { PFUser.logInWithUsernameInBackground(Email.text, password:Password.text) { (user: PFUser!, error: NSError!) -> Void in if user != nil { let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } else { // The login failed. Check error to see why. } } } @IBAction func facebookButtonClicked(sender: AnyObject) { var permissions = ["email"] PFFacebookUtils.logInWithPermissions(permissions, { (user: PFUser!, error: NSError!) -> Void in if user == nil { NSLog("Uh oh. The user cancelled the Facebook login.") } else if user.isNew { NSLog("User signed up and logged in through Facebook!") let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } else { NSLog("User logged in through Facebook!") let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) //NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } }) } @IBAction func signupButtonClicked(sender: AnyObject) { var user = PFUser() if(checkInput()) { user.username = Email.text user.password = Password.text user.email = Email.text // other fields can be set just like with PFObject var ErrorAlert: UIAlertView = UIAlertView() user.signUpInBackgroundWithBlock { (succeeded: Bool!, error: NSError!) -> Void in if error == nil { let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") //self.performSegueWithIdentifier("main", sender: nil) // Hooray! Let them use the app now. } else { ErrorAlert.title = "You already have an account!" ErrorAlert.message = "Try signing in!" // Show the errorString somewhere and let the user try again. ErrorAlert.delegate = self ErrorAlert.addButtonWithTitle("OK") ErrorAlert.show() } } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } func setUsername(newValue: String) -> String { var hasAt: Bool = false var hasDot: Bool = false for letter in newValue { if letter == "@" { hasAt = true } if letter == "." { hasDot = true } } if hasAt && hasDot { return "Good" } else { return "Bad" } } func addDoneButtonOnKeyboard() { var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50)) doneToolbar.barStyle = UIBarStyle.BlackTranslucent var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction")) var items = NSMutableArray() items.addObject(flexSpace) items.addObject(done) doneToolbar.items = items doneToolbar.sizeToFit() self.Email.inputAccessoryView = doneToolbar self.Password.inputAccessoryView = doneToolbar } func doneButtonAction() { self.view.endEditing(true) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true) } func setPassword(newValue: String) -> String { let letters = NSCharacterSet.letterCharacterSet() let digits = NSCharacterSet.decimalDigitCharacterSet() //Password Constraint Variables var hasLetters: Bool = false var hasNumb: Bool = false let length = countElements(newValue) //Check Password Constraints for letter in newValue.unicodeScalars { if letters.longCharacterIsMember(letter.value) { hasLetters = true } if digits.longCharacterIsMember(letter.value) { hasNumb = true } } if length >= 8 && hasLetters && hasNumb { return "Good" } else if length < 8 { return "Short" } else if !hasLetters { return "Letters" } else { return "Numbers" } } override func viewDidLoad() { super.viewDidLoad() Email.delegate = self Password.delegate = self loginButton.layer.masksToBounds = true loginButton.layer.cornerRadius = 10 cancelButton.layer.masksToBounds = true cancelButton.layer.cornerRadius = 10 facebookButton.layer.masksToBounds = true facebookButton.layer.cornerRadius = 10 signupButton.layer.masksToBounds = true signupButton.layer.cornerRadius = 10 addDoneButtonOnKeyboard() // Do any additional setup after loading the view. } func loginViewShowingLoggedInUser(loginView: FBLoginView!) { } func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!) { } func loginViewShowingLoggedOutUser(loginView: FBLoginView!) { } func loginView(loginView: FBLoginView!, handleError error: NSError!) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { if(textField == self.Email) { self.Password.becomeFirstResponder() } else if(textField == self.Password) { self.loginButtonClicked(loginButton) } 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. } */ }
bde37128d0baf2be1e885fdfd65f43ed
31.979381
152
0.563509
false
false
false
false
embryoconcepts/TIY-Assignments
refs/heads/master
19 -- Forecaster/Forecaster/Forecaster/Weather.swift
cc0-1.0
1
// // Weather.swift // Forecaster // // Created by Jennifer Hamilton on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation struct Weather { let location: [String: Double] let latitude: Double let longitude: Double let summary: String let icon: String let precipProbability: Double let precipIntensity: Double let temperature: Double let apparentTemperature: Double let dewpoint: Double let humidity: Double // let windSpeed: Double // let windBearing: Double // let visibility: Double // let cloudCover: Double let pressure: Double init(latitude: Double, longitude: Double, summary: String, icon: String, temperature: Double, precipProb: Double, precipIntensity: Double, apparentTemp: Double, dewpoint: Double, humidity: Double, pressure: Double) { self.latitude = latitude self.longitude = longitude self.location = ["lat": latitude, "lng": longitude] self.summary = summary self.icon = icon self.precipProbability = precipProb self.precipIntensity = precipIntensity self.temperature = temperature self.apparentTemperature = apparentTemp self.dewpoint = dewpoint self.humidity = humidity self.pressure = pressure } static func weatherWithJSON(weatherDictionaryResults: NSDictionary) -> Weather { var weather: Weather! let currentWeatherDictionary = weatherDictionaryResults.valueForKey("currently") if currentWeatherDictionary!.count > 0 { // let name = currentWeatherDictionary!.valueForKey("name") as? String ?? "" let latitude = weatherDictionaryResults.valueForKey("latitude") as! Double let longitude = weatherDictionaryResults.valueForKey("longitude") as! Double let summary = currentWeatherDictionary!.valueForKey("summary") as! String let icon = currentWeatherDictionary!.valueForKey("icon") as! String let precipProbability = currentWeatherDictionary!.valueForKey("precipProbability") as! Double let precipIntensity = currentWeatherDictionary!.valueForKey("precipIntensity") as! Double let temperature = currentWeatherDictionary!.valueForKey("temperature") as! Double let apparentTemperature = currentWeatherDictionary!.valueForKey("apparentTemperature") as! Double let dewpoint = currentWeatherDictionary!.valueForKey("dewPoint") as! Double let humidity = currentWeatherDictionary!.valueForKey("humidity") as! Double let pressure = currentWeatherDictionary!.valueForKey("pressure") as! Double weather = Weather(latitude: latitude, longitude: longitude, summary: summary, icon: icon, temperature: temperature, precipProb: precipProbability, precipIntensity: precipIntensity, apparentTemp: apparentTemperature, dewpoint: dewpoint, humidity: humidity, pressure: pressure) } return weather } }
d573decc2012194f066f48445943fbcb
40.053333
287
0.687561
false
false
false
false
lntotherain/huacaizhibo
refs/heads/master
huacaizhibo/huacaizhibo/Classes/Tools/UIBarButtonItem+Extention.swift
apache-2.0
1
// // UIBarButtonItem+Extention.swift // huacaizhibo // // Created by mac on 2016/10/29. // Copyright © 2016年 julia. All rights reserved. // import UIKit extension UIBarButtonItem { /* class func creatItem(imgname: String,highLightImgName: String, size:CGSize) -> UIBarButtonItem{ let img = UIImage(named: imgname) let imgHighLight = UIImage(named: highLightImgName) let btn = UIButton() btn.frame = CGRect(origin: CGPoint.zero, size: size) btn.setImage(img, for: .normal) btn.setImage(imgHighLight, for: .highlighted) let barButtonItem = UIBarButtonItem(customView: btn) return barButtonItem } */ //便利构造函数 convenience init(imgname: String,highLightImgName: String = "", size:CGSize = CGSize.zero) { let img = UIImage(named: imgname) let btn = UIButton() btn.setImage(img, for: .normal) if highLightImgName != "" { let imgHighLight = UIImage(named: highLightImgName) btn.setImage(imgHighLight, for: .highlighted) } if size != CGSize.zero { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView: btn) } }
d53008de81ab24bbe21a3579a53e5906
25.309091
101
0.530062
false
false
false
false
IAskWind/IAWExtensionTool
refs/heads/master
Pods/Easy/Easy/Classes/Core/EasyListView.swift
mit
1
// // EasyListView.swift // Easy // // Created by OctMon on 2018/11/8. // import UIKit public extension Easy { typealias ListView = EasyListView } open class EasyListView: UIView { deinit { EasyLog.debug(toDeinit) } /// 第一页 public lazy var firstPage: Int = EasyGlobal.listViewFirstPage /// 当前页 public lazy var currentPage: Int = EasyGlobal.listViewCurrentPage /// 分页数量 public lazy var pageSize: Int? = EasyGlobal.listViewPageSize /// 大于等于多少条数据提示没有更多的数据 public lazy var noMoreDataSize: Int = EasyGlobal.listViewNoMoreDataSize /// 下一页增量(跳过的页数) public lazy var incrementPage: Int = EasyGlobal.listViewIncrementPage /// 自动判断总页数 public lazy var autoTotalPage: Bool = EasyGlobal.listViewAutoTotalPage /// 忽略总页数判断 public lazy var ignoreTotalPage: Bool = EasyGlobal.listViewIgnoreTotalPage public var tableViewBackgroundColor: UIColor = EasyGlobal.tableViewBackgroundColor public var collectionViewBackgroundColor: UIColor = EasyGlobal.collectionViewBackgroundColor open lazy var model: Any? = nil open lazy var list: [Any] = [Any]() lazy var requestHandler: (() -> Void)? = { return nil }() open func configure() { } public func model<T>(_ class: T.Type) -> T? { return model as? T ?? nil } public func listTo<T>(_ class: T.Type) -> [T] { return list as? [T] ?? [] } public func list<T>(_ class: T.Type) -> [T]? { return list as? [T] } public var placeholders: [EasyPlaceholder]? public var placeholderBackgroundColor: UIColor = EasyGlobal.placeholderBackgroundColor, placeholderOffset: CGFloat = 0, placeholderBringSubviews: [UIView]? = nil public var placeholderIsUserInteractionEnabled: Bool = EasyGlobal.placeholderIsUserInteractionEnabled func getAny<T>(_ dataSource: [Any], indexPath: IndexPath, numberOfSections: Int, numberOfRowsInSectionHandler: ((T, Int) -> Int)?) -> Any? { if let model = model { return model } var rowsInSection = 0 if let `self` = self as? T, let rows = numberOfRowsInSectionHandler?(self, indexPath.section) { rowsInSection = rows } if numberOfSections == 1 && rowsInSection < 1 { if let row = dataSource[indexPath.section] as? [Any], indexPath.section < dataSource.count { return row[indexPath.row] } if indexPath.row < dataSource.count { return dataSource[indexPath.row] } } else if numberOfSections > 0 { if indexPath.section < dataSource.count { if let any = dataSource[indexPath.section] as? [Any] { if indexPath.row < any.count { return any[indexPath.row] } } else if rowsInSection > 0 && numberOfSections == dataSource.count { return dataSource[indexPath.section] } else if indexPath.row < dataSource.count { return dataSource[indexPath.row] } } } else if indexPath.row < dataSource.count { return dataSource[indexPath.row] } return nil } } public extension EasyListView { func requestFirst() { currentPage = firstPage requestHandler?() } func addPlaceholder(_ placeholder: EasyPlaceholder) { var existing = placeholders ?? [] existing.append(placeholder) placeholders = existing } func addPlaceholders(_ placeholder: [EasyPlaceholder]) { var existing = placeholders ?? [] existing.append(contentsOf: placeholder) placeholders = existing } }
433d4e0c1c8e68178935cd5c819dc85e
30.891667
165
0.609093
false
false
false
false
MoooveOn/Advanced-Frameworks
refs/heads/master
SideMenu/SideMenu/SideMenu/SideMenu.swift
mit
1
// // SideMenu.swift // SideMenu // // Created by Pavel Selivanov on 03.07.17. // Copyright © 2017 Pavel Selivanov. All rights reserved. // import UIKit protocol SideMenuDelegate { func didSelectMenuItem(withTitle title: String, index: Int) } class SideMenu: UIView, UITableViewDelegate, UITableViewDataSource { var backgroundView: UIView! var menuTable: UITableView! var animator: UIDynamicAnimator! var menuWidth: CGFloat = 0 var menuItemTitles = [String]() var menuDelegate: SideMenuDelegate? var parentViewController = UIViewController() //Universal view controller required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(menuWidth: CGFloat, menuItemTitles: [String], parentViewController: UIViewController) { super.init(frame: CGRect(x: -menuWidth, y: 20, width: menuWidth, height: parentViewController.view.frame.height)) print("init SideMenu...") self.menuWidth = menuWidth self.menuItemTitles = menuItemTitles self.parentViewController = parentViewController self.backgroundColor = UIColor.darkGray parentViewController.view.addSubview(self) setupMenuView() animator = UIDynamicAnimator(referenceView: parentViewController.view) let showMenuRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(SideMenu.handleGestures(recognizer:))) showMenuRecognizer.direction = .right parentViewController.view.addGestureRecognizer(showMenuRecognizer) //for closing let hideMenuRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(SideMenu.handleGestures(recognizer:))) hideMenuRecognizer.direction = .left parentViewController.view.addGestureRecognizer(hideMenuRecognizer) } func handleGestures(recognizer: UISwipeGestureRecognizer) { if recognizer.direction == .right { toggleMenu(open: true) } else { toggleMenu(open: false) } } func toggleMenu(open: Bool) { animator.removeAllBehaviors() //We need do it because we call this function many times let gravityX: CGFloat = open ? 2 : -1 let pushMagnitude: CGFloat = open ? 2 : -20 let boundaryX: CGFloat = open ? menuWidth : -menuWidth - 5 let gravity = UIGravityBehavior(items: [self]) gravity.gravityDirection = CGVector(dx: gravityX, dy: 0) //The direction and magnitude of the gravitational force, expressed as a vector animator.addBehavior(gravity) let collision = UICollisionBehavior(items: [self]) collision.addBoundary(withIdentifier: 1 as NSCopying, from: CGPoint(x: boundaryX, y: 20), to: CGPoint(x: boundaryX, y: parentViewController.view.bounds.height)) animator.addBehavior(collision) let push = UIPushBehavior(items: [self], mode: .continuous) push.magnitude = pushMagnitude animator.addBehavior(push) let menuBehaviour = UIDynamicItemBehavior(items: [self]) menuBehaviour.elasticity = 0.4 animator.addBehavior(menuBehaviour) UIView.animate(withDuration: 0.2) { self.backgroundView.alpha = open ? 0.5 : 0 } } func setupMenuView() { backgroundView = UIView(frame: parentViewController.view.bounds) backgroundView.backgroundColor = UIColor.lightGray backgroundView.alpha = 0 parentViewController.view.insertSubview(backgroundView, belowSubview: self) // backgroundView is below SideMenu menuTable = UITableView(frame: self.bounds, style: .plain) menuTable.backgroundColor = UIColor.clear menuTable.separatorStyle = .none //Our table will be without separators menuTable.isScrollEnabled = false menuTable.alpha = 1 menuTable.delegate = self menuTable.dataSource = self menuTable.reloadData() self.addSubview(menuTable) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItemTitles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { print("Cell \(indexPath.row) is nil...") cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } cell?.textLabel?.text = menuItemTitles[indexPath.row] cell?.textLabel?.textColor = UIColor.lightGray cell?.textLabel?.font = UIFont(name: "Cochin", size: 20) cell?.textLabel?.textAlignment = .center cell?.backgroundColor = UIColor.clear return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.cellForRow(at: indexPath)?.setSelected(false, animated: true) if let delegate = menuDelegate { delegate.didSelectMenuItem(withTitle: menuItemTitles[indexPath.row], index: indexPath.row) } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
321383c5c5b13cbe6fd8d6f2e0c47f6d
35.0625
168
0.653206
false
false
false
false
artursDerkintis/YouTube
refs/heads/master
YouTube/DataHelper.swift
mit
1
// // DataHelper.swift // YouTube // // Created by Arturs Derkintis on 1/4/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit import CoreData class DataHelper: NSObject { static let sharedInstance = DataHelper() private override init(){} lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.nealceffrey.Starfly" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Youtube", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Youtube.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } func favorited(id : String, completion:(Bool)-> Void){ let request = NSFetchRequest(entityName: "Favorites") request.predicate = NSPredicate(format: "id == %@", id) do{ let array = try self.managedObjectContext.executeFetchRequest(request) print("Favorited ?? \(array.count)") array.count > 0 ? completion(true) : completion(false) }catch _{ completion(false) } } func saveFavorite(videoDetails : VideoDetails){ let newEntity = NSEntityDescription.insertNewObjectForEntityForName("Favorites", inManagedObjectContext: self.managedObjectContext) as! Favorites newEntity.title = videoDetails.title newEntity.id = videoDetails.id newEntity.imageUrl = videoDetails.thumbnail newEntity.channelID = videoDetails.channelId newEntity.channelTitle = videoDetails.channelTitle newEntity.duration = videoDetails.duration self.saveContext() } }
5441b1335715696260435d5ef1f2aa64
51.272727
291
0.690435
false
false
false
false
toshi0383/TruncatingTextView
refs/heads/master
Sources/TruncatingTextView.swift
mit
1
// // TruncatingTextView.swift // TruncatingTextView // // Created by toshi0383 on 2017/01/27. // // import UIKit extension UITextView { /// Calculated text size is smaller than UITextView's size. /// Change margin size until you get "..." at correct position. /// /// This is what NSString.boundingRect's document says. /// > This method returns fractional sizes (in the size component of the returned CGRect); /// > to use a returned size to size views, you must raise its value to the nearest higher /// > integer using the ceil function. /// /// - parameter text: /// - parameter margin: public func setTextAfterTruncatingIfNeeded (text: String?, lineBreakMode: NSLineBreakMode, margin: CGFloat = 0.0) { guard let text = text else { self.text = nil return } guard let font = self.font else { self.text = text return } let size = getExpectedContainerSize(with: margin) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byCharWrapping let attributes: [String: Any] = [ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle ] self.text = text.truncate(maxSize: size, attributes: attributes) } func getExpectedContainerSize(with margin: CGFloat) -> CGSize { let width = frame.width - margin let height = frame.height return CGSize( width: width, height: height ) } } extension String { func truncate(maxSize: CGSize, attributes: [String: Any]) -> String { if fits(in: maxSize, attributes: attributes) { return self } var result = "".characters for c in self.characters { let previous = String(result) result.append(c) let current = String(result) if !current.fits(in: maxSize, attributes: attributes) { return previous.replaceLastCharacter(with: ".", count: 3) } } #if DEBUG assertionFailure("Shouldn't reach here.") #endif return String(result) } func fits(in size: CGSize, attributes: [String: Any]) -> Bool { let height = self.getHeight(for: size.width, attributes: attributes) return height <= size.height } func getHeight(for width: CGFloat, attributes: [String: Any]) -> CGFloat { return getHeightUsingNSString(for: width, attributes: attributes) } func getHeightUsingNSString(for width: CGFloat, attributes: [String: Any]) -> CGFloat { let nsstring = self as NSString let calculated = nsstring.boundingRect( with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil ).size return calculated.height } // - Deprecated: Do not use this API for production use. func getHeightUsingNSLayoutManager(with width: CGFloat, attributes: [String: Any]) -> CGFloat { let textStorage = NSTextStorage(string: self) let textContainer = NSTextContainer( size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) ) let layoutManager = NSLayoutManager() layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) textStorage.addAttributes(attributes, range: NSRange(location: 0, length: textStorage.length)) textContainer.lineFragmentPadding = 0.0 layoutManager.glyphRange(for: textContainer) let height = layoutManager.usedRect(for: textContainer).size.height return height } func replaceLastCharacter(with string: String, count: UInt) -> String { var s = self.characters for _ in (0..<count) { s = s.dropLast() } for _ in (0..<count) { if let c = string.characters.first { s.append(c) } } return String(s) } }
bd4f1add8c3bc24158f5b5b01c2626e0
33.254098
102
0.612826
false
false
false
false
lemberg/connfa-ios
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/Supports/Commons.swift
apache-2.0
1
// // DateFormatter.swift // SwiftDate // // Created by Daniele Margutti on 06/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public extension DateFormatter { /// Return the local thread shared formatter initialized with the configuration of the region passed. /// /// - Parameters: /// - region: region used to pre-configure the cell. /// - format: optional format used to set the `dateFormat` property. /// - Returns: date formatter instance public static func sharedFormatter(forRegion region: Region?, format: String? = nil) -> DateFormatter { let name = "SwiftDate_\(NSStringFromClass(DateFormatter.self))" let formatter: DateFormatter = threadSharedObject(key: name, create: { return DateFormatter() }) if let region = region { formatter.timeZone = region.timeZone formatter.calendar = region.calendar formatter.locale = region.locale } formatter.dateFormat = (format ?? DateFormats.iso8601) return formatter } /// Returned number formatter instance shared along calling thread to format ordinal numbers. /// /// - Parameter locale: locale to set /// - Returns: number formatter instance @available(iOS 9.0, macOS 10.11, *) public static func sharedOrdinalNumberFormatter(locale: LocaleConvertible) -> NumberFormatter { var formatter: NumberFormatter? = nil let name = "SwiftDate_\(NSStringFromClass(NumberFormatter.self))" formatter = threadSharedObject(key: name, create: { return NumberFormatter() }) formatter!.numberStyle = .ordinal formatter!.locale = locale.toLocale() return formatter! } } /// This function create (if necessary) and return a thread singleton instance of the /// object you want. /// /// - Parameters: /// - key: identifier of the object. /// - create: create routine used the first time you are about to create the object in thread. /// - Returns: instance of the object for caller's thread. internal func threadSharedObject<T: AnyObject>(key: String, create: () -> T) -> T { if let cachedObj = Thread.current.threadDictionary[key] as? T { return cachedObj } else { let newObject = create() Thread.current .threadDictionary[key] = newObject return newObject } } /// Style used to format month, weekday, quarter symbols. /// Stand-alone properties are for use in places like calendar headers. /// Non-stand-alone properties are for use in context (for example, “Saturday, November 12th”). /// /// - `default`: Default formatter (ie. `4th quarter` for quarter, `April` for months and `Wednesday` for weekdays) /// - defaultStandalone: See `default`; See `short`; stand-alone properties are for use in places like calendar headers. /// - short: Short symbols (ie. `Jun` for months, `Fri` for weekdays, `Q1` for quarters). /// - veryShort: Very short symbols (ie. `J` for months, `F` for weekdays, for quarter it just return `short` variant). /// - standaloneShort: See `short`; stand-alone properties are for use in places like calendar headers. /// - standaloneVeryShort: See `veryShort`; stand-alone properties are for use in places like calendar headers. public enum SymbolFormatStyle { case `default` case defaultStandalone case short case veryShort case standaloneShort case standaloneVeryShort } /// Encapsulate the logic to use date format strings public struct DateFormats { /// This is the built-in list of all supported formats for auto-parsing of a string to a date. internal static let builtInAutoFormat: [String] = [ DateFormats.iso8601, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "h:mm:ss A", "h:mm A", "MM/dd/yyyy", "MMMM d, yyyy", "MMMM d, yyyy LT", "dddd, MMMM D, yyyy LT", "yyyyyy-MM-dd", "yyyy-MM-dd", "GGGG-[W]WW-E", "GGGG-[W]WW", "yyyy-ddd", "HH:mm:ss.SSSS", "HH:mm:ss", "HH:mm", "HH" ] /// This is the ordered list of all formats SwiftDate can use in order to attempt parsing a passaed /// date expressed as string. Evaluation is made in order; you can add or remove new formats as you wish. /// In order to reset the list call `resetAutoFormats()` function. public static var autoFormats: [String] = DateFormats.builtInAutoFormat /// Default ISO8601 format string public static let iso8601: String = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" /// Extended format public static let extended: String = "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz" /// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200" public static let altRSS: String = "d MMM yyyy HH:mm:ss ZZZ" /// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200" public static let rss: String = "EEE, d MMM yyyy HH:mm:ss ZZZ" /// The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT" public static let httpHeader: String = "EEE, dd MM yyyy HH:mm:ss ZZZ" /// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy" public static let standard: String = "EEE MMM dd HH:mm:ss Z yyyy" /// SQL date format public static let sql: String = "yyyy-MM-dd'T'HH:mm:ss.SSSX" /// Reset the list of auto formats to the initial settings. public static func resetAutoFormats() { self.autoFormats = DateFormats.builtInAutoFormat } /// Parse a new string optionally passing the format in which is encoded. If no format is passed /// an attempt is made by cycling all the formats set in `autoFormats` property. /// /// - Parameters: /// - string: date expressed as string. /// - suggestedFormat: optional format of the date expressed by the string (set it if you can in order to optimize the parse task). /// - region: region in which the date is expressed. /// - Returns: parsed absolute `Date`, `nil` if parse fails. public static func parse(string: String, format: String?, region: Region) -> Date? { let formats = (format != nil ? [format!] : DateFormats.autoFormats) return DateFormats.parse(string: string, formats: formats, region: region) } public static func parse(string: String, formats: [String], region: Region) -> Date? { let formatter = DateFormatter.sharedFormatter(forRegion: region) var parsedDate: Date? = nil for format in formats { formatter.dateFormat = format formatter.locale = region.locale if let date = formatter.date(from: string) { parsedDate = date break } } return parsedDate } } // MARK: - Calendar Extension public extension Calendar.Component { internal static func toSet(_ src: [Calendar.Component]) -> Set<Calendar.Component> { var l: Set<Calendar.Component> = [] src.forEach { l.insert($0) } return l } internal var nsCalendarUnit: NSCalendar.Unit { switch self { case .era: return NSCalendar.Unit.era case .year: return NSCalendar.Unit.year case .month: return NSCalendar.Unit.month case .day: return NSCalendar.Unit.day case .hour: return NSCalendar.Unit.hour case .minute: return NSCalendar.Unit.minute case .second: return NSCalendar.Unit.second case .weekday: return NSCalendar.Unit.weekday case .weekdayOrdinal: return NSCalendar.Unit.weekdayOrdinal case .quarter: return NSCalendar.Unit.quarter case .weekOfMonth: return NSCalendar.Unit.weekOfMonth case .weekOfYear: return NSCalendar.Unit.weekOfYear case .yearForWeekOfYear: return NSCalendar.Unit.yearForWeekOfYear case .nanosecond: return NSCalendar.Unit.nanosecond case .calendar: return NSCalendar.Unit.calendar case .timeZone: return NSCalendar.Unit.timeZone } } } /// This define the weekdays for some functions. public enum WeekDay: Int { case sunday = 1 case monday = 2 case tuesday = 3 case wednesday = 4 case thursday = 5 case friday = 6 case saturday = 7 } /// Rounding mode for dates. /// Round off/up (ceil) or down (floor) target date. public enum RoundDateMode { case to5Mins case to10Mins case to30Mins case toMins(_: Int) case toCeil5Mins case toCeil10Mins case toCeil30Mins case toCeilMins(_: Int) case toFloor5Mins case toFloor10Mins case toFloor30Mins case toFloorMins(_: Int) } /// Related type enum to get derivated date from a receiver date. public enum DateRelatedType { case startOfDay case endOfDay case startOfWeek case endOfWeek case startOfMonth case endOfMonth case tomorrow case tomorrowAtStart case yesterday case yesterdayAtStart case nearestMinute(minute:Int) case nearestHour(hour:Int) case nextWeekday(_: WeekDay) case nextDSTDate case prevMonth case nextMonth case prevWeek case nextWeek case nextYear case prevYear case nextDSTTransition } public struct TimeCalculationOptions { /// Specifies the technique the search algorithm uses to find result public var matchingPolicy: Calendar.MatchingPolicy /// Specifies the behavior when multiple matches are found public var repeatedTimePolicy: Calendar.RepeatedTimePolicy /// Specifies the direction in time to search public var direction: Calendar.SearchDirection public init(matching: Calendar.MatchingPolicy = .nextTime, timePolicy: Calendar.RepeatedTimePolicy = .first, direction: Calendar.SearchDirection = .forward) { self.matchingPolicy = matching self.repeatedTimePolicy = timePolicy self.direction = direction } } //MARK: - compactMap for Swift 4.0 (not necessary > 4.0) #if swift(>=4.1) #else extension Collection { func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try flatMap(transform) } } #endif
08c1d2d0793295e5581a69942a60a431
32.38676
134
0.723649
false
false
false
false
lpniuniu/bookmark
refs/heads/master
bookmark/bookmark/BookListViewController/BookListTableView.swift
mit
1
// // BookListTableView.swift // bookmark // // Created by FanFamily on 16/12/14. // Copyright © 2016年 niuniu. All rights reserved. // import UIKit import SnapKit import Bulb import SWTableViewCell import RealmSwift import Crashlytics // what she say class BookListDidSelectSignal: BulbBoolSignal { override class func description() -> String { return "BookList is selected"; } } class BookListDidDeselectSignal: BulbBoolSignal { override class func description() -> String { return "BookList is not selected"; } } class BookListTableView: UITableView, UITableViewDelegate, UITableViewDataSource, SWTableViewCellDelegate { let cellIdentifier:String = "book_list_cellIdentifier" var selectIndexPath:IndexPath? = nil override init(frame:CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) delegate = self dataSource = self separatorStyle = .none register(BookCell.self, forCellReuseIdentifier: cellIdentifier) showsVerticalScrollIndicator = false weak var weakSelf = self Bulb.bulbGlobal().register(BookSavedSignal.signalDefault()) { (data:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in weakSelf?.isHidden = false weakSelf?.reloadData() if weakSelf?.selectIndexPath != nil { weakSelf?.selectRow(at: weakSelf?.selectIndexPath, animated: true, scrollPosition: .none) } if let book = data as? BookData { Answers.logCustomEvent(withName: "addbook", customAttributes: ["name" : book.name]) } return true } Bulb.bulbGlobal().register(BookChangePageValue.signalDefault()) { (book:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in weakSelf?.reloadData() if weakSelf?.selectIndexPath != nil { weakSelf?.selectRow(at: weakSelf?.selectIndexPath, animated: true, scrollPosition: .none) } return true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let realm = try! Realm() return realm.objects(BookData.self).filter("done == false").count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:BookCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! BookCell cell.configureFlatCell(with: UIColor.white, selectedColor: UIColor.greenSea(), roundingCorners:.allCorners) cell.cornerRadius = 5.0 cell.separatorHeight = 20.0 cell.backgroundColor = backgroundColor cell.rightUtilityButtons = rightButton() as NSArray as? [Any] cell.delegate = self let realm = try! Realm() if let imageUrl = realm.objects(BookData.self).filter("done == false")[indexPath.row].photoUrl { let url = URL(string: imageUrl) if (url?.scheme == "http" || url?.scheme == "https") { cell.bookImageView.kf.setImage(with: url) } else { let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let photoPath = doc?.appendingPathComponent("photos") cell.bookImageView.image = UIImage(contentsOfFile: (photoPath?.appendingPathComponent((url?.path)!).path)!) } } cell.nameLabel.text = realm.objects(BookData.self).filter("done == false")[indexPath.row].name cell.pageLabel.text = "\(realm.objects(BookData.self).filter("done == false")[indexPath.row].pageCurrent)/\(realm.objects(BookData.self).filter("done == false")[indexPath.row].pageTotal)" return cell } func swipeableTableViewCell(_ cell: SWTableViewCell!, didTriggerRightUtilityButtonWith index: Int) { if index == 0 { let realm = try! Realm() let bookData = realm.objects(BookData.self).filter("done == false")[(indexPath(for: cell)?.row)!] try! realm.write({ bookData.done = true bookData.doneDate = Date() }) deleteRows(at:[indexPath(for: cell)!], with: .fade) Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data:nil) // 加入日历 let now = Date() let result = realm.objects(BookReadDateData.self).filter("date == %@", now.zeroOfDate) guard result.count == 0 else { return } let readDate = BookReadDateData() readDate.date = now.zeroOfDate try! realm.write({ realm.add(readDate) }) } else if index == 1 { let deleteConfirmAlert = UIAlertController(title: "即将删除这本书,是否确认", message: "", preferredStyle: .alert) deleteConfirmAlert.view.tintColor = UIColor.greenSea() let confirmAction = UIAlertAction(title: "确认", style: .default, handler: { (action:UIAlertAction) in let realm = try! Realm() let object = realm.objects(BookData.self)[(self.indexPath(for: cell)?.row)!] let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let photoPath = doc?.appendingPathComponent("photos") try! FileManager.default.removeItem(at: (photoPath?.appendingPathComponent(object.photoUrl!))!) try! realm.write({ realm.delete(object) }) self.deleteRows(at:[self.indexPath(for: cell)!], with: .fade) Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data:nil) }) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action:UIAlertAction) in }) deleteConfirmAlert.addAction(confirmAction) deleteConfirmAlert.addAction(cancelAction) UIApplication.shared.keyWindow?.rootViewController?.present(deleteConfirmAlert, animated: true, completion: { }) } } func rightButton() -> NSMutableArray { let buttons:NSMutableArray = [] buttons.sw_addUtilityButton(with: UIColor.turquoise(), title: "阅完") buttons.sw_addUtilityButton(with: UIColor.red, title: "删除") return buttons } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectIndexPath = indexPath let realm = try! Realm() Bulb.bulbGlobal().fire(BookListDidSelectSignal.signalDefault(), data: realm.objects(BookData.self).filter("done == false")[indexPath.row]) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { selectIndexPath = nil let realm = try! Realm() Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data: realm.objects(BookData.self).filter("done == false")[indexPath.row]) } }
7fceba932715dd7a6e8be0b6b8eae449
41.016667
195
0.614306
false
false
false
false
blstream/AugmentedSzczecin_iOS
refs/heads/master
AugmentedSzczecin/AugmentedSzczecin/ASSearchViewController.swift
apache-2.0
1
// // ASSearchViewController.swift // AugmentedSzczecin // // Created by Patronage on 16.04.2015. // Copyright (c) 2015 BLStream. All rights reserved. // import UIKit import CoreData class ASSearchViewController: UITableViewController, UISearchResultsUpdating, NSFetchedResultsControllerDelegate { var resultSearchController = UISearchController() lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "ASPOI") let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] let frc = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: ASData.sharedInstance.mainContext!, sectionNameKeyPath: "ASPOI.id", cacheName: nil) frc.delegate = self return frc }() override func viewDidLoad() { super.viewDidLoad() self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() self.tableView.tableHeaderView = controller.searchBar return controller })() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: Selector("dismissViewController")) self.tableView.reloadData() } func dismissViewController() { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidAppear(animated: Bool) { } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let currentSection = sections[section] as! NSFetchedResultsSectionInfo return currentSection.numberOfObjects } return 0 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let sections = fetchedResultsController.sections { let currentSection = sections[section] as! NSFetchedResultsSectionInfo return currentSection.name } return nil } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ASSearchCell", forIndexPath: indexPath) as! UITableViewCell let poi = fetchedResultsController.objectAtIndexPath(indexPath) as! ASPOI cell.textLabel?.text = poi.name cell.detailTextLabel?.text = poi.tag return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("ShowDetailSegue", sender: fetchedResultsController.objectAtIndexPath(indexPath)) } func updateSearchResultsForSearchController(searchController: UISearchController) { if (searchController.searchBar.text != "") { var predicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text) fetchedResultsController.fetchRequest.predicate = predicate fetchedResultsController.fetchRequest.fetchLimit = 25 } else { fetchedResultsController.fetchRequest.predicate = nil } self.tableView.reloadData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ShowDetailSegue") { var destination = segue.destinationViewController as! ASPointDetailViewController destination.POI = sender as? ASPOI } } }
0a6bffa01b11506b8f4c6dd540db311e
34.825
171
0.662168
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Blog/Blog Dashboard/ViewModel/DashboardCardModel.swift
gpl-2.0
1
import Foundation /// Represents a card in the dashboard collection view struct DashboardCardModel: Hashable { let cardType: DashboardCard let dotComID: Int let apiResponse: BlogDashboardRemoteEntity? /** Initializes a new DashboardCardModel, used as a model for each dashboard card. - Parameters: - id: The `DashboardCard` id of this card - dotComID: The blog id for the blog associated with this card - entity: A `BlogDashboardRemoteEntity?` property - Returns: A `DashboardCardModel` that is used by the dashboard diffable collection view. The `id`, `dotComID` and the `entity` is used to differentiate one card from the other. */ init(cardType: DashboardCard, dotComID: Int, entity: BlogDashboardRemoteEntity? = nil) { self.cardType = cardType self.dotComID = dotComID self.apiResponse = entity } static func == (lhs: DashboardCardModel, rhs: DashboardCardModel) -> Bool { lhs.cardType == rhs.cardType && lhs.dotComID == rhs.dotComID && lhs.apiResponse == rhs.apiResponse } func hash(into hasher: inout Hasher) { hasher.combine(cardType) hasher.combine(dotComID) hasher.combine(apiResponse) } }
44de9c436aba0d26c387f8068bf182e3
32.763158
92
0.664848
false
false
false
false
Sweebi/tvProgress
refs/heads/master
tvProgress/Error/tvProgress+Error.swift
mit
1
// // tvProgress+Error.swift // tvProgress // // Created by Cédric Eugeni on 05/05/2016. // Copyright © 2016 tvProgress. All rights reserved. // import Foundation extension tvProgress { //MARK: - Methods /** If your loading fails, you can display a message that gives information about what happened to the user - Parameters: - status: specify a text to display - successImage: specify an image to be displayed instead of the default image - style: specify a style using tvProgressStyle enum - action: it's a tuple that contains a label and a closure. If you specify this parameter, the label will be use to generate a button while the closure will be executed when the user presses the button - menuButtonDidPress: specify a closure to be executed when the user press the Menu button while tvProgress is displayed - playButtonDidPress: specify a closure to be executed when the user press the Play/Pause button while tvProgress is displayed - marge: marging size for status label (right and left) */ public static func showErrorWithStatus(_ status: String? = .none, andErrorImage errorImage: UIImage? = .none, andStyle style: tvProgressStyle? = .none, andAction action: (label: String, closure: ((Void) -> Void))? = .none, menuButtonDidPress: (() -> Void)? = .none, playButtonDidPress: (() -> Void)? = .none, andWithMarginTextSize marge: CGFloat = 400, completion: (() -> Void)? = .none) -> Void { let instance: tvProgress = tvProgress.sharedInstance let f: () -> Void = { () -> Void in var views: [UIView] = [] let ei: UIImage = errorImage ?? instance.errorImage let errorImageView: UIImageView = UIImageView(frame: CGRect(x: instance.center.x - ei.size.width / 2, y: instance.center.y - ei.size.height / 2, width: ei.size.width, height: ei.size.height)) errorImageView.image = ei errorImageView.tintColor = (style ?? instance.style).mainColor views.insert(errorImageView, at: 0) if let s = status { let sLabel: UILabel = tvProgress.generateStatusLabelWithInstance(instance, andStatus: s, andStyle: style ?? instance.style, andWithMaxWidth: UIScreen.main.bounds.width - marge) let v: UIView = views[views.count - 1] sLabel.frame = CGRect(x: instance.center.x - (sLabel.frame.width / 2), y: v.frame.origin.y + v.frame.height + 30, width: sLabel.frame.width, height: sLabel.frame.height) sLabel.sizeToFit() views.insert(sLabel, at: views.count) } if let act = action { let button: UIButton = UIButton(type: .system) button.setTitle(act.label, for: UIControlState()) button.sizeToFit() button.actionHandleWithAction(act.closure) let v: UIView = views[views.count - 1] button.frame = CGRect(x: instance.center.x - (button.frame.width / 2), y: v.frame.origin.y + v.frame.height + 50, width: button.frame.width, height: button.frame.height) views.insert(button, at: views.count) } tvProgress.showWithInstance(instance, andVisibleType: visibleType.error(), andViews: views, andStyle: style, menuButtonDidPress: menuButtonDidPress, playButtonDidPress: playButtonDidPress, completion: completion) if let s = status , action == nil { Timer.scheduledTimer(timeInterval: tvProgress.displayDurationForString(s), target: self, selector: #selector(sdismiss), userInfo: nil, repeats: false) } } OperationQueue.main.addOperation() { () -> Void in if instance.isVisible { tvProgress.dismiss { () -> Void in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.25 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in f() } } } else { f() } } } }
8a155b7d240134b42e0cb513ed3a356c
55.891892
401
0.613539
false
false
false
false
Hamuko/Nullpo
refs/heads/master
Nullpo/FileListData.swift
apache-2.0
1
import Cocoa class FileListData: NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet weak var fileTable: NSTableView! var fileList = [UploadFile]() /// Pushes a new URL onto the file list. /// - parameter file: File URL string. func addFile(file: UploadFile) { fileList.append(file) fileTable.reloadData() } /// Clear the entire file list. func clearFiles() { fileList = [UploadFile]() fileTable.reloadData() } var count: Int { return fileList.count } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return fileList.count } func remove(index: Int) { fileList.removeAtIndex(index) fileTable.reloadData() } func sort(numberOfItems: Int) { let sortRange: Range<Int> = fileList.count - numberOfItems...fileList.count - 1 let sorted = fileList[sortRange].sort { $0.index < $1.index } fileList.replaceRange(sortRange, with: sorted) fileTable.reloadData() } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell: FileListCell = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! FileListCell cell.fileURL.stringValue = fileList[row].url! return cell } }
36e13aa1e95fb60586ee246a2c2fdfee
28.297872
120
0.655047
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/CoreData/Object/DVitaItemElementExport.swift
mit
1
import Foundation extension DVitaItemElement:DVitaItemExportProtocol { var hasheableItem:[String:Any] { get { let dateCreated:Date = Date( timeIntervalSince1970:self.dateCreated) let dateModified:Date = Date( timeIntervalSince1970:self.dateModified) let dateCreatedString:String = MVitaPtpDate.factoryString( date:dateCreated) let dateModifiedString:String = MVitaPtpDate.factoryString( date:dateModified) let name:String = self.name! let root:[String:Any] = [ "statusType":1, "name":name, "title":name, // "index":0, "ohfiParent":directory!.category.rawValue, "ohfi":directory!.category.rawValue, "size":size, "dateTimeCreated":dateCreatedString, "dateTimeUpdated":dateModifiedString] return root } } }
82f5f5f721ef30b0998bd42a8c6231ed
32.272727
71
0.51184
false
false
false
false
rtocd/NotificationObservers
refs/heads/master
NotificationObservers/Source/NotificationObservers/NotificationObserver.swift
mit
1
// // NotificationObserver.swift // Notification // // Created by rtocd on 7/4/17. // Copyright © 2017 RTOCD. All rights reserved. // import Foundation /// This handles most of the boilerplate code needed for creating a NotificationCenter observer. public class NotificationObserver<A: Adaptable>: NSObject { typealias callbackType = (A) -> () private let name: Notification.Name private var observer: NSObjectProtocol? private var callback: callbackType? = nil private var queue: OperationQueue? /// Call this when you want to start observer a notification. /// If you call the method multiple times it will stop and replace the previously created observer. public func start(queue: OperationQueue = .main, object: AnyObject? = nil, callback: @escaping (A) -> Void) { if self.callback != nil { self.stop() } self.callback = callback self.queue = queue self.observer = NotificationCenter.default.addObserver(key: self.name, object: object, queue: queue, callback: { (adaptor) in callback(adaptor) }) } public func stop() { if let observer = self.observer { NotificationCenter.default.removeObserver(observer) } self.callback = nil } public init(name: Notification.Name) { self.name = name super.init() } deinit { if let observer = self.observer { NotificationCenter.default.removeObserver(observer) } } }
50201cf19ab499ce291b3498c37a227e
28.037037
133
0.63074
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/KeyBoard/EmojiKeyboard.swift
mit
1
// // EmojiKeyboard.swift // 小礼品 // // Created by 李莎鑫 on 2017/5/6. // Copyright © 2017年 李莎鑫. All rights reserved. // 表情键盘 import UIKit import SnapKit import QorumLogs fileprivate let pageTintColor = UIColor(white: 0.5, alpha: 0.3) class EmojiKeyboard: BaseKeyboard { //MARK: 单例 static let shared = EmojiKeyboard() //MARK: 属性 weak var delegate:EmojiKeyboardDelegate? //MARK: 懒加载 //: 表情显示页面 lazy var emojiView:EmojiGroupView = { () -> EmojiGroupView in let view = EmojiGroupView() view.delegate = self return view }() //: 页控制器 lazy var pageControl:UIPageControl = { () -> UIPageControl in let control = UIPageControl() control.pageIndicatorTintColor = pageTintColor control.currentPageIndicatorTintColor = UIColor.gray control.numberOfPages = 0 control.addTarget(self, action: #selector(pageControlChanged), for: .valueChanged) return control }() //: 组控制器 lazy var groupControl:EmojiCroupControl = { () -> EmojiCroupControl in let control = EmojiCroupControl() control.delegate = self return control }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupEmojiKeyboard() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupEmojiKeyboardSubView() } //MARK: 私有方法 private func setupEmojiKeyboard() { backgroundColor = SystemGlobalBackgroundColor addSubview(pageControl) addSubview(groupControl) addSubview(emojiView) } private func setupEmojiKeyboardSubView() { emojiView.snp.remakeConstraints { (make) in make.top.left.right.equalToSuperview() make.bottom.equalTo(pageControl.snp.top) } pageControl.snp.remakeConstraints { (make) in make.left.right.equalToSuperview() make.bottom.equalTo(groupControl.snp.top) make.height.equalTo(margin*2.0) } groupControl.snp.remakeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(margin*3.8) } } //MARK: 内部响应 @objc private func pageControlChanged() { } } //MARK: 代理方法 -> EmojiGroupViewDelegate extension EmojiKeyboard:EmojiGroupViewDelegate { func emojiGroupViewGroupChanged(withGroupIndex index: Int, withGroupPages pages: Int) { pageControl.numberOfPages = pages } //: 发送表情 func emojiGroupViewDidSelectedEmoji(withItem item: Int, withEmojiName text: String?, isDelete delete: Bool) { QL1(text) delegate?.emojiKeyboardDidSelectdEmoji(withEmojiName: text, isDelete: delete) } func emojiGroupViewDidScrollToPage(withPage page: Int) { pageControl.currentPage = page } } //MARK: 代理方法 -> EmojiGroupControlDelegate extension EmojiKeyboard:EmojiGroupControlDelegate { func emojiGroupControlDidSelectGroupItem(GroupItem item: Int) { emojiView.groupIndex = item pageControl.currentPage = 0 emojiView.emojiGroupViewDidScrollTo(Pages: pageControl.currentPage) } func emojiGroupControlDidClickSendButton() { delegate?.emojiKeyboardDidClickSendButton() } } protocol EmojiKeyboardDelegate:NSObjectProtocol { func emojiKeyboardDidSelectdEmoji(withEmojiName text:String?,isDelete delete:Bool) func emojiKeyboardDidClickSendButton() }
b9bbcc31c0697fd4f2e8e6342075f16c
27.849206
113
0.661348
false
false
false
false
mobilabsolutions/jenkins-ios
refs/heads/master
JenkinsiOSTests/TestExtensions.swift
mit
1
// // TestExtensions.swift // JenkinsiOS // // Created by Robert on 18.10.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation import XCTest func AssertEmpty<T>(_ value: [T]) { XCTAssertTrue(value.isEmpty) } func AssertNotEmpty<T>(_ value: [T]) { XCTAssertFalse(value.isEmpty) } func assertArraysAreEqual(array1: [Any?], array2: [Any?]) { guard array1.count == array2.count else { XCTFail("Arrays do not have the same length: first: \(array1.count) second: \(array2.count)"); return } for (index, element) in array1.enumerated() { guard element != nil && array2[index] != nil else { if !(element == nil && array2[index] == nil) { XCTFail("\(String(describing: element)) is not the same as \(String(describing: array2[index]))") }; continue } if (element as? NSObject) != (array2[index] as? NSObject) { XCTFail("\(String(describing: element)) is not the same as \(String(describing: array2[index]))") } } }
b6be54a7e85bbea6a27cf5fb3d92de83
30.75
173
0.642717
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Blog/QuickStartChecklistCell.swift
gpl-2.0
1
import Gridicons class QuickStartChecklistCell: UITableViewCell { @IBOutlet private var titleLabel: UILabel! { didSet { WPStyleGuide.configureLabel(titleLabel, textStyle: .headline) } } @IBOutlet private var descriptionLabel: UILabel! { didSet { WPStyleGuide.configureLabel(descriptionLabel, textStyle: .subheadline) } } @IBOutlet private var iconView: UIImageView? @IBOutlet private var stroke: UIView? { didSet { stroke?.backgroundColor = .divider } } @IBOutlet private var topSeparator: UIView? { didSet { topSeparator?.backgroundColor = .divider } } private var bottomStrokeLeading: NSLayoutConstraint? private var contentViewLeadingAnchor: NSLayoutXAxisAnchor { return WPDeviceIdentification.isiPhone() ? contentView.leadingAnchor : contentView.readableContentGuide.leadingAnchor } private var contentViewTrailingAnchor: NSLayoutXAxisAnchor { return WPDeviceIdentification.isiPhone() ? contentView.trailingAnchor : contentView.readableContentGuide.trailingAnchor } public var completed = false { didSet { if completed { guard let titleText = tour?.title else { return } titleLabel.attributedText = NSAttributedString(string: titleText, attributes: [.strikethroughStyle: 1, .foregroundColor: UIColor.neutral(.shade30)]) // Overrides the existing accessibility hint in the tour property observer, // because users don't need the hint repeated to them after a task is completed. accessibilityHint = nil accessibilityLabel = tour?.titleMarkedCompleted descriptionLabel.textColor = .neutral(.shade30) iconView?.tintColor = .neutral(.shade30) } else { titleLabel.textColor = .text descriptionLabel.textColor = .textSubtle iconView?.tintColor = .listIcon } } } public var tour: QuickStartTour? { didSet { titleLabel.text = tour?.title descriptionLabel.text = tour?.description iconView?.image = tour?.icon.withRenderingMode(.alwaysTemplate) if let hint = tour?.accessibilityHintText, !hint.isEmpty { accessibilityHint = hint } } } public var lastRow: Bool = false { didSet { bottomStrokeLeading?.isActive = !lastRow } } public var topSeparatorIsHidden: Bool = false { didSet { topSeparator?.isHidden = topSeparatorIsHidden } } override func awakeFromNib() { super.awakeFromNib() contentView.backgroundColor = .listForeground setupConstraints() } static let reuseIdentifier = "QuickStartChecklistCell" } private extension QuickStartChecklistCell { func setupConstraints() { guard let stroke = stroke, let topSeparator = topSeparator else { return } bottomStrokeLeading = stroke.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor) bottomStrokeLeading?.isActive = true let strokeSuperviewLeading = stroke.leadingAnchor.constraint(equalTo: contentViewLeadingAnchor) strokeSuperviewLeading.priority = UILayoutPriority(999.0) strokeSuperviewLeading.isActive = true stroke.trailingAnchor.constraint(equalTo: contentViewTrailingAnchor).isActive = true topSeparator.leadingAnchor.constraint(equalTo: contentViewLeadingAnchor).isActive = true topSeparator.trailingAnchor.constraint(equalTo: contentViewTrailingAnchor).isActive = true } }
4edc60f77a3c45345811245274e36447
36.018692
127
0.623832
false
false
false
false
superman-coder/pakr
refs/heads/master
pakr/pakr/UserInterface/PostParking/AddressPicker/AddressPickerController.swift
apache-2.0
1
// // AddressPickerController.swift // pakr // // Created by Tien on 4/16/16. // Copyright © 2016 Pakr. All rights reserved. // import UIKit import MapKit import CoreLocation protocol AddressPickerDelegate { func addressPickerControllerDidCancel(addressPicker:AddressPickerController); func addressPickerController(addressPicker:AddressPickerController, didFinishPickingLocationWithLatlng latlng:CLLocationCoordinate2D!, address:String?, image:UIImage?) } let searchCellReuseId = "GMPlaceCell" class AddressPickerController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var searchControllerView: UIView! @IBOutlet weak var searchResultContainerView: UIView! @IBOutlet weak var searchResultTableView: UITableView! @IBOutlet weak var searchIconButton: UIButton! @IBOutlet weak var bottomBarView: UIView! var delegate: AddressPickerDelegate? var isQuerying = false var currentSearchQuery:String? var latestSearchQuery:String? var selectedLocation:CLLocationCoordinate2D? var selectedAddress:String? private var reverseGeoCodeRequestTimer:NSTimer? private var placeSearchRequestTimer:NSTimer? private let centerPinLayer = CALayer() // Search functions var searchResult: [GMPlace]! = [] // A boolean indicates if we should perform a search when text changes. var shouldSearch = true // End of search functions override func viewDidLoad() { super.viewDidLoad() initMapView() initSearchController() } private func initMapView() { mapView.delegate = self if let initialLocation = selectedLocation { centerMapToCoordinate(initialLocation) } centerPinLayer.contents = UIImage(named: "pin-orange")?.CGImage centerPinLayer.bounds = CGRectMake(0, 0, 29, 42) let bounds = mapView.bounds centerPinLayer.position = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) centerPinLayer.anchorPoint = CGPointMake(0.5, 1) centerPinLayer.hidden = true mapView.layer.addSublayer(centerPinLayer) } private func initSearchController() { LayoutUtils.dropShadowView(searchControllerView) searchTextField.delegate = self searchTextField.placeholder = "Search nearby address" searchResultTableView.registerNib(UINib(nibName: "GMPlaceCell", bundle: nil), forCellReuseIdentifier: searchCellReuseId) searchResultTableView.dataSource = self searchResultTableView.delegate = self bottomBarView.layer.masksToBounds = false bottomBarView.layer.shadowColor = UIColor.blackColor().CGColor bottomBarView.layer.shadowOffset = CGSize(width: 0, height: 2) bottomBarView.layer.shadowOpacity = 0.4 } override func viewDidLayoutSubviews() { let bounds = mapView.bounds centerPinLayer.position = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) centerPinLayer.hidden = false } @IBAction func buttonCancelDidClick(sender: UIBarButtonItem) { delegate?.addressPickerControllerDidCancel(self) } @IBAction func buttonDoneDidClick(sender: UIBarButtonItem) { snapshotMapViewWithComplete { (snapshot, error) in self.delegate?.addressPickerController(self, didFinishPickingLocationWithLatlng: self.selectedLocation!, address: self.selectedAddress, image: snapshot) } } private func showSearchResultContainer(show:Bool) { if (show != self.searchResultContainerView.hidden) { return } // show true, hidden = false -> return // show false hidden = true -> return // show true, hidden = true -> do // show false, hidden = false -> do let initialAlpha:CGFloat = show ? 0 : 1 self.searchResultContainerView.alpha = initialAlpha self.searchResultContainerView.hidden = false if (show) { self.searchTextField.becomeFirstResponder() } else { self.searchTextField.resignFirstResponder() } // self.searchTextField.text = nil self.searchResult.removeAll() self.searchResultTableView.reloadData() UIView.animateWithDuration(0.3, animations: { self.searchResultContainerView.alpha = 1 - initialAlpha }) { (finished) in self.searchResultContainerView.hidden = !show } let targetImage = show ? UIImage(named: "back-gray") : UIImage(named: "search-gray") UIView.transitionWithView(self.searchIconButton, duration: 0.3, options: .TransitionCrossDissolve, animations: { self.searchIconButton .setImage(targetImage, forState: .Normal) }) { (finished) in } } @IBAction func searchTextFieldTextChanged(sender: UITextField) { latestSearchQuery = sender.text if sender.text == nil || sender.text!.characters.count == 0 { searchResult.removeAll() searchResultTableView.reloadData() return } let searchText = sender.text! if (!isQuerying) { requestSearchPlaces(searchText); } } @IBAction func searchControllerBackButtonDidClick(sender: UIButton) { self.showSearchResultContainer(false) } func requestSearchPlaces(searchText: String) { isQuerying = true currentSearchQuery = searchText UIApplication.sharedApplication().networkActivityIndicatorVisible = true GMServices.requestAddressSearchWithAddress(searchText) { (success, location) in self.isQuerying = false UIApplication.sharedApplication().networkActivityIndicatorVisible = false self.onQueryFinished() self.handleSearchResult(success, locations: location) } } private func handleSearchResult(success:Bool, locations:[GMPlace]?) { self.searchResult.removeAll() if success { self.searchResult.appendContentsOf(locations!) } else { // TODO: Handle search error } self.searchResultTableView.reloadData() } private func onQueryFinished() { if currentSearchQuery != nil && latestSearchQuery != nil && currentSearchQuery != latestSearchQuery { requestSearchPlaces(latestSearchQuery!) } } private func centerMapToCoordinate(latlng:CLLocationCoordinate2D) { let region = MKCoordinateRegionMakeWithDistance(latlng, MAP_DEFAULT_RADIUS, MAP_DEFAULT_RADIUS) mapView.setRegion(region, animated: true) } private func snapshotMapViewWithComplete(completion:(snapshot:UIImage?, error:NSError?)->()) { let snapshotOption = MKMapSnapshotOptions() snapshotOption.region = mapView.region snapshotOption.size = CGSizeMake(mapView.frame.size.width, mapView.frame.size.height / 2) snapshotOption.scale = UIScreen.mainScreen().scale let snapshoter = MKMapSnapshotter(options: snapshotOption) snapshoter.startWithQueue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { (snapshot:MKMapSnapshot?, error:NSError?) in guard let snapshot = snapshot else { completion(snapshot: nil, error: error) return } let pin = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil) let mapImage = snapshot.image UIGraphicsBeginImageContextWithOptions(mapImage.size, true, mapImage.scale) mapImage.drawAtPoint(CGPoint.zero) var point = snapshot.pointForCoordinate(self.selectedLocation!) point.x = point.x + pin.centerOffset.x - (pin.bounds.size.width / 2) point.y = point.y + pin.centerOffset.y - (pin.bounds.size.height / 2) pin.image?.drawAtPoint(point) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() dispatch_async(dispatch_get_main_queue(), { completion(snapshot: image, error: nil) }) } } } extension AddressPickerController: MKMapViewDelegate { func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) { self.addressLabel.text = "Moving" } func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { self.addressLabel.text = "Loading" selectedLocation = mapView.region.center reverseGeoCodeRequestTimer?.invalidate() reverseGeoCodeRequestTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(AddressPickerController.reverseGeoCodeRequest), userInfo: nil, repeats: false) } func reverseGeoCodeRequest() { guard let _ = selectedLocation else { return } GMServices.reverseGeocodeRequest(selectedLocation!.latitude, longitude: selectedLocation!.longitude) { (success, address) in if success { self.addressLabel.text = address self.selectedAddress = address } else { self.addressLabel.text = "Error" } } } } extension AddressPickerController: UITextFieldDelegate { func textFieldShouldBeginEditing(textField: UITextField) -> Bool { self.shouldSearch = true textField.text = "" self.showSearchResultContainer(true) return true } func textFieldDidEndEditing(textField: UITextField) { self.shouldSearch = false } } extension AddressPickerController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(searchCellReuseId) as! GMPlaceCell let gmPlace = searchResult[indexPath.row] cell.configWithName(gmPlace.name, address: gmPlace.address) return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResult.count } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let gmPlace = searchResult[indexPath.row] searchTextField.text = gmPlace.name centerMapToCoordinate(CLLocationCoordinate2D(latitude: gmPlace.geometry.latitude, longitude: gmPlace.geometry.longitude)) self.showSearchResultContainer(false) } }
bf83a96ad70837af595dee81a53f0d7c
36.397394
191
0.664663
false
false
false
false
InsectQY/HelloSVU_Swift
refs/heads/master
HelloSVU_Swift/Classes/Expand/Extension/UIBarButtonItem-Extension.swift
apache-2.0
1
// // UIBarButtonItem-Extension.swift // DouYuLive // // Created by Insect on 2017/4/8. // Copyright © 2017年 Insect. All rights reserved. // import UIKit extension UIBarButtonItem { convenience init(normalImg: String, highlightedImg: String? = "",title: String? = nil ,size: CGSize? = CGSize.zero,target: Any,action:Selector) { let btn = UIButton(type: .custom) btn.setImage(UIImage(named:normalImg ), for: .normal) btn.setTitleColor(.black, for: .normal) btn.titleLabel?.font = PFM16Font btn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, -10) btn.addTarget(target, action: action, for: .touchUpInside) if let highlightedImg = highlightedImg { btn.setImage(UIImage(named:highlightedImg), for: .highlighted) } if let title = title { btn.setTitle(title, for: .normal) } if let size = size { btn.frame = CGRect(origin:CGPoint.zero, size: size) }else { btn.sizeToFit() } self.init(customView: btn) } }
5bfed10d5b787564bf46f5e64b84c1cc
27.948718
149
0.58636
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 4 - Alien Adventure 2/Dictionaries/Dictionaries.playground/Pages/Operations_insert, count, remove, update.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) //: ### Dictionary operations: insert, count, remove, update, retrieve var animalGroupsDict = ["whales":"pod", "geese":"flock", "lions": "pride"] // Adding items to a dictionary animalGroupsDict["crows"] = "murder" animalGroupsDict["monkeys"] = "troop" // The count method is available to all collections. animalGroupsDict.count print(animalGroupsDict) // Removing items from a dictionary animalGroupsDict["crows"] = nil animalGroupsDict // Updating a value animalGroupsDict["monkeys"] = "barrel" var group = animalGroupsDict.updateValue("gaggle", forKey: "geese") type(of: group) animalGroupsDict.updateValue("crash", forKey:"rhinoceroses") print(animalGroupsDict) //: [Next](@next)
fa531171b36ded4f8888370fdc1690ff
26.576923
74
0.739191
false
false
false
false
chicio/Exploring-SceneKit
refs/heads/master
ExploringSceneKit/Model/Scenes/BlinnPhong/BlinnPhongScene.swift
mit
1
// // BlinnPhongScene.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 26.08.17. // import SceneKit @objc class BlinnPhongScene: SCNScene, Scene { private var camera: Camera! private var poolSphere: DynamicSphere! override init() { super.init() createCamera() createLight() createObjects() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Camera private func createCamera() { camera = Camera( position: SCNVector3Make(0, 80.0, 100.0), rotation: SCNVector4Make(1.0, 0, 0, -1.0 * Float(CGFloat.pi / 4.0)) ) rootNode.addChildNode(camera.node) } //MARK: Light private func createLight() { rootNode.addChildNode(createOmniDirectionalLight().node) rootNode.addChildNode(createAmbientLight().node) } private func createOmniDirectionalLight() -> OmniDirectionalLight { let lightFeatures = LightFeatures( position: SCNVector3Make(0, 50, 10), orientation: SCNVector3Make(0, 0, 0), color: UIColor.white ) let light = OmniDirectionalLight(lightFeatures: lightFeatures) return light } private func createAmbientLight() -> AmbientLight { let lightFeatures = LightFeatures( position: SCNVector3Make(0, 0, 0), orientation: SCNVector3Make(0, 0, 0), color: UIColor.darkGray ) let light = AmbientLight(lightFeatures: lightFeatures) return light } //MARK: Objects private func createObjects() { addFloor() addWhiteMarbleBox() addBlueMarbleBox() addDarkBlueMarbleBox() addPoolSphere() } private func addFloor() { let floor = KinematicFloor( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "floor.jpg", textureWrapMode: .repeat), specular: 0.0 ), position: SCNVector3Make(0, 0, 0), rotation: SCNVector4Make(0, 0, 0, 0) ) rootNode.addChildNode(floor.node) } private func addWhiteMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble1.jpg"), specular: 0.3 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(0, 5, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addBlueMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble2.jpg"), specular: 0.2 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(-5, 5, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addDarkBlueMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble3.jpg"), specular: 0.3 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(-5, 10, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addPoolSphere() { self.poolSphere = DynamicSphere( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "pool.jpg"), specular: 0.9 ), physicsBodyFeature: PhysicsBodyFeatures(mass: 1.5, rollingFriction: 0.1), radius: 10.0, position: SCNVector3Make(20, 10, 20), rotation: SCNVector4Make(0, 0, 0, 0) ) rootNode.addChildNode(self.poolSphere.node) } func actionForOnefingerGesture(withLocation location: CGPoint, andHitResult hitResult: [Any]!) { if isThereAHitIn(hitResult: hitResult) { movePoolSphereUsing(hitResult: hitResult) } } private func isThereAHitIn(hitResult: [Any]!) -> Bool { return hitResult.count > 0 } private func movePoolSphereUsing(hitResult: [Any]!) { if let firstHit: SCNHitTestResult = hitResult[0] as? SCNHitTestResult { let force = SCNVector3Make( firstHit.worldCoordinates.x - self.poolSphere.node.position.x, 0, firstHit.worldCoordinates.z - self.poolSphere.node.position.z ) self.poolSphere.node.physicsBody?.applyForce(force, asImpulse: true) } } func actionForTwofingerGesture() { let randomX = CGFloat.randomIn(minRange: 0.0, maxRange: 50.0) let randomZ = CGFloat.randomIn(minRange: 0.0, maxRange: 50.0) let randomRadius = CGFloat.randomIn(minRange: 0.0, maxRange: 15.0) let randomTexture = String(format: "checked%d.jpg", Int.randomIn(minRange: 1, maxRange: 2)) let sphere = DynamicSphere( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: randomTexture), specular: CGFloat.randomIn(minRange: 0.0, maxRange: 2.0) ), physicsBodyFeature: PhysicsBodyFeatures(mass: randomRadius * 10.0, rollingFriction: 0.2), radius: randomRadius, position: SCNVector3(randomX, 120, randomZ), rotation: SCNVector4(0, 0, 0, 0) ) rootNode.addChildNode(sphere.node) } }
8f362584bbb5cd0307ab98370bf37e62
33.563536
106
0.586797
false
false
false
false
TryFetch/PutioKit
refs/heads/master
Sources/Router.swift
gpl-3.0
1
// // Router.swift // Fetch // // Created by Stephen Radford on 22/06/2016. // Copyright © 2016 Cocoon Development Ltd. All rights reserved. // import Foundation import Alamofire /// The router used for requests to the API. enum Router: URLRequestConvertible { static let base = "https://api.put.io/v2" /// MARK: - Cases case files(Int) case deleteFiles([Int]) case renameFile(Int, String) case file(Int) case moveFiles([Int], Int) case createFolder(String, Int) case convertToMp4(Int) case getMp4Status(Int) case shareFiles([Int], [String]) case getSharedWith(Int) case unshareFile(Int, [Int]) case getSubtitles(Int) case setVideoPosition(Int, Int) case deleteVideoPosition(Int) case getEvents case deleteEvents case transfers case cleanTransfers case addTransfer(String, Int, Bool) case retryTransfer(Int) case cancelTransfers([Int]) case getAccountInfo case getSettings var result: (method: HTTPMethod, path: String, parameters: Parameters) { switch self { case .files(let parent): return (.get, "/files/list", ["parent_id": parent, "start_from": 1]) case .file(let id): return (.get, "/files/\(id)", [:]) case .deleteFiles(let files): return (.post, "/files/delete", ["file_ids": files.map { String($0) }.joined(separator: ",")]) case .renameFile(let id, let name): return (.post, "/files/rename", ["file_id": id, "name": name]) case .moveFiles(let files, let parent): return (.post, "/files/move", ["file_ids": files.map { String($0) }.joined(separator: ","), "parent": parent]) case .createFolder(let name, let parent): return (.post, "/files/create-folder", ["name": name, "parent_id": parent]) case .convertToMp4(let id): return (.post, "/files/\(id)/mp4", [:]) case .getMp4Status(let id): return (.get, "/files/\(id)/mp4", [:]) case .shareFiles(let files, let friends): return (.post, "/files/share", ["file_ids": files.map { String($0) }.joined(separator: ","), "friends": friends.joined(separator: ",")]) case .getSharedWith(let id): return (.get, "/files/\(id)/shared-with", [:]) case .unshareFile(let id, let friends): return (.post, "/files/\(id)/unshare", ["shares": friends.map { String($0) }.joined(separator: ",")]) case .getSubtitles(let id): return (.get, "/files/\(id)/subtitles", [:]) case .setVideoPosition(let id, let position): return (.post, "/files/\(id)/start-from", ["time": position]) case .deleteVideoPosition(let id): return (.post, "/files/\(id)/start-from/delete", [:]) case .getEvents: return (.get, "/events/list", [:]) case .deleteEvents: return (.post, "/events/delete", [:]) case .transfers: return (.get, "/transfers/list", [:]) case .cleanTransfers: return (.post, "/transfers/clean", [:]) case .addTransfer(let url, let parent, let extract): return (.post, "/transfers/add", ["url": url, "parent": parent, "extract": extract]) case .retryTransfer(let id): return (.post, "/transfers/retry", ["id": id]) case .cancelTransfers(let transfers): return (.post, "/transfers/cancel", ["transfer_ids": transfers.map { String($0) }.joined(separator: ",")]) case .getAccountInfo: return (.get, "/account/info", [:]) case .getSettings: return (.get, "/account/settings", [:]) } } /// Returns a URL request or throws if an `Error` was encountered. /// /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// /// - returns: A URL request. public func asURLRequest() throws -> URLRequest { let url = try Router.base.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) urlRequest.httpMethod = result.method.rawValue var parameters = result.parameters if let token = Putio.accessToken { parameters["oauth_token"] = token } return try URLEncoding.default.encode(urlRequest, with: parameters) } }
36b6b86845ecd3214417fb5b806c881e
36.91453
148
0.574617
false
false
false
false
grandiere/box
refs/heads/master
box/Firebase/Database/Model/FDbAlgoHostileVirus.swift
mit
1
import Foundation class FDbAlgoHostileVirus:FDbProtocol { let items:[String:FDbAlgoHostileVirusItem] required init?(snapshot:Any) { var items:[String:FDbAlgoHostileVirusItem] = [:] if let snapshotDict:[String:Any] = snapshot as? [String:Any] { let snapshotKeys:[String] = Array(snapshotDict.keys) for virusId:String in snapshotKeys { guard let snapshotVirus:Any = snapshotDict[virusId], let virusItem:FDbAlgoHostileVirusItem = FDbAlgoHostileVirusItem( snapshot:snapshotVirus) else { continue } items[virusId] = virusItem } } self.items = items } func json() -> Any? { return nil } }
6f4fbe7e1c35b10fea152523dfec32bd
23.923077
84
0.467078
false
false
false
false
Miguel-Herrero/Swift
refs/heads/master
Rainy Shiny Cloudy/Rainy Shiny Cloudy/WeatherVC.swift
gpl-3.0
1
// // WeatherVC.swift // Rainy Shiny Cloudy // // Created by Miguel Herrero on 13/12/16. // Copyright © 2016 Miguel Herrero. All rights reserved. // import UIKit import Alamofire import CoreLocation class WeatherVC: UIViewController { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var currentTempLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var currentTempImage: UIImageView! @IBOutlet weak var currentTempTypeLabel: UILabel! @IBOutlet weak var tableView: UITableView! var currentWeather: CurrentWeather! var forecast: Forecast! var forecasts = [Forecast]() let locationManager = CLLocationManager() var currentLocation: CLLocation! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startMonitoringSignificantLocationChanges() locationManager.startUpdatingLocation() //Step-1 Requesting location updates currentWeather = CurrentWeather() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) locationAuthStatus() } func updateMainUI() { dateLabel.text = currentWeather.date currentTempLabel.text = "\(currentWeather.currentTemp) ºC" currentTempTypeLabel.text = currentWeather.weatherType locationLabel.text = currentWeather.cityName currentTempImage.image = UIImage(named: currentWeather.weatherType) tableView.reloadData() } func downloadForecastData(completed: @escaping DownloadComplete) { // DOwnload forecast weather data for TableView let forecastURL = URL(string: FORECAST_URL)! Alamofire.request(forecastURL).responseJSON { (response) in let result = response.result if let dict = result.value as? Dictionary<String, AnyObject> { if let list = dict["list"] as? [Dictionary<String, AnyObject>] { for obj in list { let forecast = Forecast(weatherDict: obj) self.forecasts.append(forecast) } self.forecasts.remove(at: 0) //Remove today from forecast! } } completed() } } } extension WeatherVC: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return forecasts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "weatherCell", for: indexPath) as? WeatherCell { let forecast = forecasts[indexPath.row] cell.configureCell(forecast: forecast) return cell } else { return WeatherCell() } } } extension WeatherVC: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { locationAuthStatus() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { currentLocation = locationManager.location if currentLocation != nil { locationManager.stopUpdatingLocation() } Location.sharedInstance.latitude = currentLocation.coordinate.latitude Location.sharedInstance.longitude = currentLocation.coordinate.longitude print(Location.sharedInstance.latitude ?? "nada", Location.sharedInstance.longitude ?? "nada") currentWeather.downloadWeatherDetails { //Setup UI to load downloaded data self.downloadForecastData { self.updateMainUI() } } } else { locationManager.requestWhenInUseAuthorization() } } /* * If CLLocation is not authorized, we cannot show any weather info */ func locationAuthStatus() { if CLLocationManager.authorizationStatus() != .authorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } } }
9ea66e9f205b7dfa766373e1be540c60
32.076389
116
0.624606
false
false
false
false
brokenseal/iOS-exercises
refs/heads/master
FaceSnap/FaceSnap/PhotoListController.swift
mit
1
// // ViewController.swift // FaceSnap // // Created by Davide Callegari on 25/06/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import UIKit class PhotoListController: UIViewController { lazy var cameraButton: UIButton = { let button = UIButton(type: .system) // Camera Button Customization button.setTitle("Camera", for: []) button.tintColor = .white button.backgroundColor = UIColor(red: 254/255.0, green: 123/255.0, blue: 135/255.0, alpha: 1.0) button.addTarget(self, action: #selector(PhotoListController.presentImagePickerController), for: .touchUpInside) return button }() lazy var mediaPickerManager: MediaPickerManager = { let manager = MediaPickerManager(self) manager.delegate = self return manager }() override func viewDidLoad() { super.viewDidLoad() } override func viewWillLayoutSubviews(){ super.viewWillLayoutSubviews() // Camera Button Layout view.addSubview(cameraButton) cameraButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ cameraButton.leftAnchor.constraint(equalTo: view.leftAnchor), cameraButton.bottomAnchor.constraint(equalTo: view.bottomAnchor), cameraButton.rightAnchor.constraint(equalTo: view.rightAnchor), cameraButton.heightAnchor.constraint(equalToConstant: 56.0) ]) } @objc private func presentImagePickerController(){ mediaPickerManager.presentImagePickerController(true) } } extension PhotoListController: MediaPickerManagerDelegate { func mediaPickerManager(manager: MediaPickerManager, didFinishPickingImage image: UIImage) { // TODO } }
d40faf71ff0f5b672c17c8b7f80621aa
30.220339
120
0.67101
false
false
false
false
wesj/firefox-ios-1
refs/heads/master
Sync/Record.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 Shared let ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60; /** * Immutable representation for Sync records. * * Envelopes consist of: * Required: "id", "collection", "payload". * Optional: "modified", "sortindex", "ttl". * * Deletedness is a property of the payload. */ public class Record<T: CleartextPayloadJSON> { public let id: String public let payload: T public let modified: UInt64 public let sortindex: Int public let ttl: Int // Seconds. // This is a hook for decryption. // Right now it only parses the string. In subclasses, it'll parse the // string, decrypt the contents, and return the data as a JSON object. // From the docs: // // payload none string 256k // A string containing a JSON structure encapsulating the data of the record. // This structure is defined separately for each WBO type. // Parts of the structure may be encrypted, in which case the structure // should also specify a record for decryption. // // @seealso EncryptedRecord. public class func payloadFromPayloadString(envelope: EnvelopeJSON, payload: String) -> T? { return T(payload) } // TODO: consider using error tuples. public class func fromEnvelope(envelope: EnvelopeJSON, payloadFactory: (String) -> T?) -> Record<T>? { if !(envelope.isValid()) { println("Invalid envelope.") return nil } let payload = payloadFactory(envelope.payload) if (payload == nil) { println("Unable to parse payload.") return nil } if payload!.isValid() { return Record<T>(envelope: envelope, payload: payload!) } println("Invalid payload \(payload!.toString(pretty: true)).") return nil } /** * Accepts an envelope and a decrypted payload. * Inputs are not validated. Use `fromEnvelope` above. */ convenience init(envelope: EnvelopeJSON, payload: T) { // TODO: modified, sortindex, ttl self.init(id: envelope.id, payload: payload, modified: envelope.modified, sortindex: envelope.sortindex) } init(id: String, payload: T, modified: UInt64 = UInt64(time(nil)), sortindex: Int = 0, ttl: Int = ONE_YEAR_IN_SECONDS) { self.id = id self.payload = payload; self.modified = modified self.sortindex = sortindex self.ttl = ttl } func equalIdentifiers(rec: Record) -> Bool { return rec.id == self.id } // Override me. func equalPayloads(rec: Record) -> Bool { return equalIdentifiers(rec) && rec.payload.deleted == self.payload.deleted } func equals(rec: Record) -> Bool { return rec.sortindex == self.sortindex && rec.modified == self.modified && equalPayloads(rec) } }
97d1e1653c6105c98d6e62efdc4a866f
31.051546
124
0.623874
false
false
false
false
vvusu/LogAnalysis
refs/heads/master
Log Analysis/DropView.swift
lgpl-3.0
1
// // DropView.swift // Log Analysis // // Created by vvusu on 10/26/15. // Copyright © 2015 vvusu. All rights reserved. // import Cocoa import AppKit class DropView: NSView { var image: NSImage! override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) if (image == nil) { NSColor.orangeColor().set() NSRectFill(dirtyRect) } else { image.drawInRect(dirtyRect, fromRect: NSZeroRect, operation: NSCompositingOperation.CompositeSourceOver, fraction: 1) } // Drawing code here. } convenience init() { self.init(frame: CGRectZero) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) // let theArray = NSImage.imageTypes() self.registerForDraggedTypes([NSFilenamesPboardType]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { // let sourceDragMask = sender.draggingSourceOperationMask() // let pboard = sender.draggingPasteboard() // if pboard.availableTypeFromArray([NSFilenamesPboardType]) == NSFilenamesPboardType { // if sourceDragMask.rawValue & NSDragOperation.Generic.rawValue != 0 { // return NSDragOperation.Generic // } // } // return NSDragOperation.None //加载immage 能否加载上去 if NSImage.canInitWithPasteboard(sender.draggingPasteboard()) && sender.draggingSourceOperationMask().rawValue & NSDragOperation.Copy.rawValue != 0 { return NSDragOperation.Copy } else { return NSDragOperation.None } } override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation { self.print("UPDATED") return NSDragOperation.Copy } override func draggingExited(sender: NSDraggingInfo?) { self.print("ENDED") } override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool { return true } override func performDragOperation(sender: NSDraggingInfo) -> Bool { // ... perform your magic // return true/false depending on success if NSImage.canInitWithPasteboard(sender.draggingPasteboard()) { self.image = NSImage.init(pasteboard: sender.draggingPasteboard()) } return true } override func concludeDragOperation(sender: NSDraggingInfo?) { self.needsDisplay = true } }
c9e18e3cce01b0282c0016ee85658fbe
28.931818
157
0.626424
false
false
false
false
ryan-boder/path-of-least-resistance
refs/heads/master
PathOfLeastResistance/Grid.swift
apache-2.0
1
import Foundation /** * Provides a navigateable grid. */ class Grid { var matrix: Array<Array<Int>>! init(_ matrix: Array<Array<Int>>) { self.matrix = matrix } var rows: Int { return matrix.count } var columns: Int { return matrix[0].count } /** * Returns the resistance at the given coordinates. */ func get(coords: (Int, Int)) -> Int! { let (r, c) = coords if r <= 0 || r > matrix.count || c <= 0 || c > matrix[0].count { return nil } return matrix[r - 1][c - 1] } /** * Navigates straight to the right and returns the new point. */ func right(coords: (Int, Int)) -> (Int, Int)! { let (r, c) = coords if c >= matrix[0].count { return nil } return (r, c + 1) } /** * Navigates up and to the right and returns the new point. */ func up(coords: (Int, Int)) -> (Int, Int)! { let (r, c) = coords if c >= matrix[0].count { return nil } return (r == 1 ? matrix.count : r - 1, c + 1) } /** * Navigates down and to the right and returns the new point. */ func down(coords: (Int, Int)) -> (Int, Int)! { let (r, c) = coords if c >= matrix[0].count { return nil } return (r == matrix.count ? 1 : r + 1, c + 1) } }
a5b3d35cb5f56ec80564e40f0dde6fc5
21.242424
72
0.46049
false
false
false
false
Gitliming/Demoes
refs/heads/master
Demoes/Demoes/QRScan/QRScanController.swift
apache-2.0
1
// // QRScanController.swift // Dispersive switch // // Created by xpming on 16/6/23. // Copyright © 2016年 xpming. All rights reserved. // import UIKit import AVFoundation class QRScanController: BaseViewController, AVCaptureMetadataOutputObjectsDelegate ,UIAlertViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate{ var scanView:ScanView? var guideLabel:UILabel? var openPhoto:UIButton? var openLight:UIButton? var imagePicker:UIImagePickerController? var session:AVCaptureSession? var input:AVCaptureDeviceInput? var output:AVCaptureMetadataOutput? var preLayer:AVCaptureVideoPreviewLayer? var avplayer:AVAudioPlayer? var isLightOn = false override func viewDidLoad() { super.viewDidLoad() setupUI() scanQR() } override func viewWillAppear(_ animated: Bool) { } override func viewWillDisappear(_ animated: Bool) { session?.stopRunning() } func setupUI(){ title = "扫描中。。。" view.layer.contents = UIImage(named: "i")?.cgImage let scanW:CGFloat = 200 let point = CGPoint(x: view.center.x - scanW/2, y: view.center.y - scanW/2) scanView = ScanView(frame: CGRect(origin: point, size: CGSize(width: scanW, height: scanW))) let y = scanView?.frame.maxY guideLabel = UILabel(frame: CGRect(x: (scanView?.frame.origin.x)!, y: y! + 20, width: scanView!.bounds.width, height: 60)) guideLabel?.text = "请将二维码置于窗口中,将会自动扫描" guideLabel?.textColor = UIColor.white guideLabel?.numberOfLines = 0 let yp = guideLabel?.frame.maxY let xp = guideLabel?.frame.minX let wp = guideLabel?.bounds.width openPhoto = UIButton(frame: CGRect(x: xp!, y: yp!, width: wp!/2 - 2, height: 30)) openPhoto?.setBackgroundImage(UIImage(named: "l"), for: UIControlState()) openPhoto?.setTitle("打开相册", for: UIControlState()) openPhoto?.addTarget(self, action: #selector(QRScanController.openPhotoAction), for: .touchUpInside) openLight = UIButton(frame: CGRect(x: xp! + wp!/2 + 2, y: yp!, width: wp!/2 - 2, height: 30)) openLight?.setTitle("打开灯光", for: UIControlState()) openLight?.setBackgroundImage(UIImage(named: "l"), for: UIControlState()) openLight?.addTarget(self, action: #selector(QRScanController.openLightAction), for: .touchUpInside) view.addSubview(scanView!) view.addSubview(guideLabel!) view.addSubview(openPhoto!) view.addSubview(openLight!) } //扫描成功声音提示 func scanedSound(){ let path = Bundle.main.path(forResource: "qrcode_found.wav", ofType: nil) let url = URL(fileURLWithPath: path!) do{ avplayer = try AVAudioPlayer(contentsOf: url) avplayer!.play() }catch{ print(error) } } func openPhotoAction(){ imagePicker = UIImagePickerController() imagePicker!.allowsEditing = true imagePicker?.delegate = self self.present(imagePicker!, animated: true, completion: nil) } ///mark:--UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { picker.dismiss(animated: true, completion: nil) let imageData = UIImageJPEGRepresentation(image, 1) //软件渲染消除警告修改Gpu渲染优先级提高渲染效率 let context = CIContext(options: [kCIContextUseSoftwareRenderer:true, kCIContextPriorityRequestLow:false]) let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: nil) let ciImage = CIImage(data: imageData!) let array = detector!.features(in: ciImage!) let feature = array.first as? CIQRCodeFeature var message = "" if feature != nil { print(feature!.messageString!) message = (feature?.messageString)! }else{ message = "没有扫描到内容" } scanedSound() let alertCtrl = UIAlertController(title: "扫描结果", message: message, preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .cancel) { (alertAction) in self.session?.startRunning() } alertCtrl.addAction(alertAction) self.present(alertCtrl, animated: true, completion: nil) } ///mark:--UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func openLightAction(){ let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) if (device?.hasTorch)! { do{ try device?.lockForConfiguration() if isLightOn == false { device?.torchMode = AVCaptureTorchMode.on isLightOn = true }else{ device?.torchMode = AVCaptureTorchMode.off isLightOn = false } }catch{ print(error) } }else{ let alertCtrl = UIAlertController(title: "提示", message: "sorry!你的设备不支持!", preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .cancel, handler: nil) alertCtrl.addAction(alertAction) self.present(alertCtrl, animated: true, completion: nil) } } func scanQR(){ //创建设备对象 let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { input = try AVCaptureDeviceInput.init(device: device) }catch{ print(error) } output = AVCaptureMetadataOutput() session = AVCaptureSession() preLayer = AVCaptureVideoPreviewLayer(session: session) preLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill preLayer?.frame = (scanView?.frame)! view.layer.insertSublayer(preLayer!, at: 0) if session?.canAddInput(input) == true && input != nil { session?.addInput(input) }else{ let alertVc = UIAlertController(title: "提示", message: "对不起!您的设备无法启动相机", preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .default, handler: nil) let alertAction2 = UIAlertAction(title: "返回", style: .cancel, handler: nil) alertVc.addAction(alertAction) alertVc.addAction(alertAction2) self.present(alertVc, animated: true, completion: nil) return} if session?.canAddOutput(output) == true && output != nil{ session?.addOutput(output) }else{return} //设置数据源为二维码数据源 output?.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) output?.metadataObjectTypes = [AVMetadataObjectTypeQRCode] let screenHeight = UIScreen.main.bounds.height let screenWidth = UIScreen.main.bounds.width let bounds = scanView?.bounds let origin = scanView?.frame.origin output?.rectOfInterest = CGRect(x: (origin?.y)!/screenHeight, y: (origin?.x)!/screenWidth, width: 2*(bounds?.height)!/screenHeight , height: 2*(bounds?.width)!/screenWidth); //启动扫描 session?.sessionPreset = AVCaptureSessionPresetHigh session?.startRunning() } //--mark AVCaptureMetadataOutputObjectsDelegate func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { scanedSound() session?.stopRunning() scanView?.stopAnimating() if metadataObjects != nil { let obj = metadataObjects.first let str = (obj as AnyObject).absoluteString if (str??.hasPrefix("http"))! { let web = UIWebView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64)) let url = URL(string: str!!) web.loadHTMLString("您扫描到的内容是\(String(describing: str))", baseURL: url) view.addSubview(web) }else{ let alertCtrl = UIAlertController(title: "扫描结果", message: str!, preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .cancel, handler: { (alertAction) in self.session?.startRunning() self.scanView?.startAnimating() }) alertCtrl.addAction(alertAction) self.present(alertCtrl, animated: true, completion: nil) } } } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
6cd0042be3e50eb880b044ccce64184b
40.119816
181
0.62535
false
false
false
false
tzef/BunbunuCustom
refs/heads/master
BunbunuCustom/BunbunuCustom/ImageView/ImageViewGroupViewController.swift
mit
1
// // ImageViewGroupViewController.swift // BunbunuCustom // // Created by LEE ZHE YU on 2016/7/7. // Copyright © 2016年 LEE ZHE YU. All rights reserved. // import UIKit private let reuseIdentifier = "customCell" class ImageViewGroupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let items = ["CircleImageView", "CircleProgressImageView"] override func viewDidLoad() { super.viewDidLoad() } // MARK: - TableView func numberOfSectionsInTableView(tableView: UITableView) -> Int { return items.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return NSStringFromClass(CircleImageView) case 1: return NSStringFromClass(CircleProgressImageView) default: return "" } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let cellName = items[indexPath.section] if let view = NSBundle.mainBundle().loadNibNamed(cellName, owner: nil, options: nil)[0] as? UIView { return view.frame.height } else { return tableView.estimatedRowHeight } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as? ViewCell { let cellName = items[indexPath.section] if let view = NSBundle.mainBundle().loadNibNamed(cellName, owner: nil, options: nil)[0] as? UIView { cell.configureCell(view) } return cell } else { return UITableViewCell() } } }
e08669254795e49d6662d6c5093476eb
34.535714
122
0.657789
false
false
false
false
luiswdy/HowLoud
refs/heads/master
HowLoud/MainPresenter.swift
mit
1
// // MainPresenter.swift // HowLoud // // Created by Luis Wu on 6/2/16. // Copyright © 2016 Luis Wu. All rights reserved. // import UIKit class MainPresenter { private var _decibelMeterMinValue = DecibelMeter.MinValue private var _decibelMeterMaxValue = DecibelMeter.MaxValue private var decibelInfoClosure: ((CGFloat, String, String) -> Void)? = nil var decibelMeterMinValue: String? { get { return String(format: NSLocalizedString("gauge_range_format_string", comment: "format string"), _decibelMeterMinValue) } } var decibelMeterMaxValue: String? { get { return String(format: NSLocalizedString("gauge_range_format_string", comment: "format string"), _decibelMeterMaxValue) } } lazy var decibelMeter: DecibelMeter = DecibelMeter(dBHandler: { [weak self] (avgSpl, peakSpl) in let avgInfo = String(format: NSLocalizedString("avg_format_string",comment: "format string"), avgSpl) let peakInfo = String(format: NSLocalizedString("peak_format_string",comment: "format string"), peakSpl) self?.decibelInfoClosure?(CGFloat(avgSpl), avgInfo, peakInfo) }) func subscribeDecibelInfo(closure: (CGFloat, String, String) -> Void) { decibelInfoClosure = closure } func allowMic() -> Bool { return decibelMeter.isMicGranted } func toggleMeasuring() -> Bool { if decibelMeter.isMeasuring() { decibelMeter.stopMeasuring() } else { decibelMeter.startMeasuring() } return decibelMeter.isMeasuring() } }
f5deb0f91ea3a77a1514e3cff683f46b
31.8
130
0.64878
false
false
false
false
Ivacker/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00360-swift-parser-parseexprlist.swift
apache-2.0
12
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import h } func e<l { enum e { func e j { } class l: j{ k() -> ()) } func j<o : BooleanType>(l: o) { } func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) { return { (p: (Any, Any) -> Any) -> Any in func n<n : l,) { } n(e()) struct d<f : e, g: e where g.h == f.h> {{ } struct B<T : A> { } protocol C { ty } } protocol a { } protocol h : a { } protocol k : a { } protocol g { } struct n : g { } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } protoc { } protocol f { protocol c : b { func b class A { class func a() -> String { let d: String = { }() } class d<c>: NSObject { init(b: c) { } } protocol A { } class C<D> { init <A: A where A.B == D>(e: A.B) { } } class A { class func a { return static let d: String = { }() func x } ) T} protocol A { } struct B<T : A> { lett D : C { func g<T where T.E == F>(f: B<T>) { } } struct d<f : e, g: e where g.h == f.h> { col P { } } } i struct c { c a(b: Int0) { } class A { class func a() -> Self { return b(self.dy
36a57fe64b3138c032ca33e38b71f145
12.727273
87
0.540563
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_301_SellMainController.swift
mit
1
// // SLV_301_SellMainController.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 판매 메인 컨트롤러 */ import Foundation import UIKit import SnapKit import RealmSwift class SLV_301_SellMainController: SLVBaseStatusHiddenController { var tr_presentTransition: TRViewControllerTransitionDelegate? @IBOutlet weak var directButton: UIButton! @IBOutlet weak var balletButton: UIButton! @IBOutlet weak var sellGuideButton: UIButton! @IBOutlet weak var saveListButton: UIButton! @IBOutlet weak var callKakaoButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var saveView: UIView! @IBOutlet weak var kakaoView: UIView! @IBOutlet weak var saveLabel: UILabel! @IBOutlet weak var kakaoLabel: UILabel! @IBOutlet weak var topForLogo: NSLayoutConstraint! @IBOutlet weak var topForTitle: NSLayoutConstraint! @IBOutlet weak var topForDirectButton: NSLayoutConstraint! @IBOutlet weak var topForGuide: NSLayoutConstraint! var aniObjects: [AnyObject]? override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } func settupLayout() { let height = UIScreen.main.bounds.size.height self.topForLogo.constant = height * 0.131 self.topForTitle.constant = height * 0.042 self.topForDirectButton.constant = height * 0.057 self.topForGuide.constant = height * 0.028 self.closeButton.translatesAutoresizingMaskIntoConstraints = false self.kakaoView.translatesAutoresizingMaskIntoConstraints = false self.saveView.translatesAutoresizingMaskIntoConstraints = false self.resetAppearLayout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(false) tabController.hideFab() // self.setupAppearAnimation() self.resetSellerData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.isNavigationBarHidden = true self.navigationBar?.barHeight = 0 self.playAppearAnimation() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.resetAppearLayout() } override func viewDidLoad() { super.viewDidLoad() self.settupLayout() self.readyInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func resetSellerData() { TempInputInfoModel.shared.isGenderPass = false } func readyInfo() { let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height let closeHidePoint = CGPoint(x: w, y: h) //46, 16 //65, 85 let w_spacing = CGFloat(16 + 32) let h_spacing = CGFloat(46 + 42) let h_spacing_close = CGFloat(16 + 16) let v_height = h - h_spacing let v_height_close = h - h_spacing_close let tempPoint = CGPoint(x: w_spacing, y: v_height) let kakaoPoint = CGPoint(x: (w*2) - w_spacing, y: v_height) let closePoint = CGPoint(x: w, y: v_height_close) let views = [ [self.saveView, tempPoint, closeHidePoint], [self.kakaoView, kakaoPoint, closeHidePoint], [self.closeButton, closePoint, closeHidePoint]] self.aniObjects = views as [AnyObject]? } func resetAppearLayout() { //46, 16 //65, 85 self.kakaoLabel.isHidden = true self.saveLabel.isHidden = true self.kakaoView.isHidden = true self.saveView.isHidden = true self.closeButton.isHidden = true let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height let views = [self.saveView, self.kakaoView, self.closeButton] _ = views.map() { let view = $0! as UIView // view.cheetah.move(w, h).run() // RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) view.snp.remakeConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } } } func setupAppearAnimation() { let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height self.closeButton.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } self.kakaoView.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } self.saveView.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } // _ = self.aniObjects!.map() { // let list = $0 as! [AnyObject] // let hide = list.last as! CGPoint // let view = list.first as! UIView // view.isHidden = true // let point = list[1] as! CGPoint // let x = hide.x - point.x // let y = hide.y - point.y //// view.cheetah.move(x, y).delay(0.01).wait(0.02).run().remove() //// RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) // } } func playAppearAnimation() { // RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1)) _ = self.aniObjects!.map() { let list = $0 as! [AnyObject] (list.first as! UIView).isHidden = false let point = list[1] as! CGPoint let hide = list.last as! CGPoint let x = point.x - hide.x let y = point.y - hide.y let view = list.first as! UIView view.cheetah.move(x, y).duration(0.2).delay(0.01).easeInBack.wait(0.02).run() RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) } self.kakaoLabel.isHidden = false self.saveLabel.isHidden = false } @IBAction func touchDirectSell(_ sender: Any) { TempInputInfoModel.shared.isDirectInput = true TempInputInfoModel.shared.isNewCase = true } @IBAction func touchBalletSell(_ sender: Any) { TempInputInfoModel.shared.isDirectInput = false TempInputInfoModel.shared.isNewCase = true } @IBAction func touchPopupGuide(_ sender: Any) { } @IBAction func touchTempList(_ sender: Any) { let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "saveListNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLV_3a2_SellTempSaveListController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.twitter) { print("Present finished.") } } @IBAction func touchKakao(_ sender: Any) { // let board = UIStoryboard(name:"Sell", bundle: nil) // let controller = board.instantiateViewController(withIdentifier: "SLV_361_SellDirectFinalSNSShareController") as! SLV_361_SellDirectFinalSNSShareController // self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { // } let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "addrNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLVAddressSearchController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.fade) { print("Present finished.") } } @IBAction func touchSellClose(_ sender: Any) { TempInputInfoModel.shared.saveCurrentModel() tabController.closePresent() { } } } extension SLV_301_SellMainController: ModalTransitionDelegate { func modalViewControllerDismiss(callbackData data:AnyObject?) { log.debug("SLV_301_SellMainController.modalViewControllerDismiss(callbackData:)") tr_dismissViewController(completion: { if let back = data { let cb = back as! [String: AnyObject] let key = cb["command"] as! String if key != nil { if key == "next" { let step = cb["step"] as! Int let board = UIStoryboard(name:"Sell", bundle: nil) switch step { case 1: self.delay(time: 0.2) { let controller = board.instantiateViewController(withIdentifier: "SLV_380_SellBallet1SellerInfoController") as! SLV_380_SellBallet1SellerInfoController self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 2: self.delay(time: 0.2) { let step2Controller = board.instantiateViewController(withIdentifier: "SLV_320_SellDirectStep2ItemInfoController") as! SLV_320_SellDirectStep2ItemInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 3: self.delay(time: 0.2) { let step2Controller = board.instantiateViewController(withIdentifier: "SLV_330_SellDirectStep3AdditionalInfoController") as! SLV_330_SellDirectStep3AdditionalInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 4: self.delay(time: 0.2) { let stepController = board.instantiateViewController(withIdentifier: "SLV_340_SellDirectStep4PriceController") as! SLV_340_SellDirectStep4PriceController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 5: self.delay(time: 0.2) { let stepController = board.instantiateViewController(withIdentifier: "SLV_350_SellDirectStep5SellerInfoController") as! SLV_350_SellDirectStep5SellerInfoController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break default: break } } } } }) } }
0fb55202a12d02acce0e6ff032f14259
40.363636
204
0.592646
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/LinearEquations/Solution/Strategy/MLinearEquationsSolutionStrategyRowAddition.swift
mit
1
import Foundation class MLinearEquationsSolutionStrategyRowAddition:MLinearEquationsSolutionStrategy { class func samePivot(step:MLinearEquationsSolutionStep) -> MLinearEquationsSolutionStrategyRowAddition? { var indexEquation:Int = 0 let countEquations:Int = step.equations.count let maxEquation:Int = countEquations - 1 for equation:MLinearEquationsSolutionEquation in step.equations { if indexEquation < maxEquation { let nextIndex:Int = indexEquation + 1 let equationBelow:MLinearEquationsSolutionEquation = step.equations[nextIndex] let pivotIndex:Int = equation.pivotIndex() let pivotIndexBelow:Int = equationBelow.pivotIndex() if pivotIndex == pivotIndexBelow { guard let topPolynomial:MLinearEquationsSolutionEquationItemPolynomial = equation.items[pivotIndex] as? MLinearEquationsSolutionEquationItemPolynomial, let bottomPolynomial:MLinearEquationsSolutionEquationItemPolynomial = equationBelow.items[pivotIndex] as? MLinearEquationsSolutionEquationItemPolynomial else { return nil } let topCoefficient:Double = topPolynomial.coefficient let bottomCoefficient:Double = bottomPolynomial.coefficient var scalar:Double = abs(bottomCoefficient / topCoefficient) if topCoefficient > 0 { if bottomCoefficient > 0 { scalar = -scalar } } else { if bottomCoefficient < 0 { scalar = -scalar } } let strategy:MLinearEquationsSolutionStrategyRowAddition = MLinearEquationsSolutionStrategyRowAddition( step:step, indexRow:nextIndex, scalar:scalar) return strategy } } indexEquation += 1 } return nil } private let indexRow:Int private let scalar:Double private init( step:MLinearEquationsSolutionStep, indexRow:Int, scalar:Double) { self.indexRow = indexRow self.scalar = scalar super.init(step:step) } override func process(delegate:MLinearEquationsSolutionStrategyDelegate) { super.process(delegate:delegate) addRows() } //MARK: private private func addRows() { var equations:[MLinearEquationsSolutionEquation] = [] let scalarString:String = MSession.sharedInstance.stringFrom(number:scalar) let descr:String = String( format:NSLocalizedString("MLinearEquationsSolutionStrategyRowAddition_descr", comment:""), "\(indexRow + 1)", "\(indexRow + 1)", "\((indexRow))", scalarString) var indexEquation:Int = 0 for equation:MLinearEquationsSolutionEquation in self.step.equations { let newEquation:MLinearEquationsSolutionEquation if indexEquation == indexRow { let previousEquation:MLinearEquationsSolutionEquation = self.step.equations[indexEquation - 1] let scaledPrevious:MLinearEquationsSolutionEquation = previousEquation.multiplyScalar( scalar:scalar) newEquation = equation.addEquation( equation:scaledPrevious) } else { newEquation = equation } equations.append(newEquation) indexEquation += 1 } let step:MLinearEquationsSolutionStepProcess = MLinearEquationsSolutionStepProcess( equations:equations, descr:descr) completed(step:step) } }
208fa653e07538bc1e656269eb6e85d7
33.829457
176
0.525929
false
false
false
false
rrunfa/StreamRun
refs/heads/master
StreamRun/AppDelegate.swift
mit
1
// // AppDelegate.swift // StreamRun // // Created by Nikita Nagajnik on 18/10/14. // Copyright (c) 2014 rrunfa. All rights reserved. // import Foundation import Cocoa import AppKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate, NSUserNotificationCenterDelegate, NSMenuDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var addChannelWindow: NSPanel! @IBOutlet var channelsText: NSTextView! @IBOutlet weak var table: NSTableView! @IBOutlet weak var showOfflineCheckmark: NSButton! @IBOutlet weak var preferencesWindow: NSPanel! var streamConnector = StreamConnector() var streamers: [String: StreamerData]! var visibleStreams: [StreamData]! var settings: Settings! var refreshTime: Double! var refreshTimer: RefreshTimer! var linkLoader: StreamLinkLoader! var statusBar: NSStatusItem! var streamsOpened: Bool = false override func awakeFromNib() { statusBar = NSStatusBar.systemStatusBar().statusItemWithLength(-2) statusBar.highlightMode = true statusBar.title = "S" statusBar.menu = NSMenu() statusBar.menu?.autoenablesItems = false statusBar.menu?.delegate = self; } func menuWillOpen(menu: NSMenu) { menu.removeAllItems() if NSEvent.pressedMouseButtons() == 2 { menu.addItem(NSMenuItem(title: "Show from clipboard", action: "onPaste:", keyEquivalent: "")) } else { streamsOpened = true; updateMenuToStreams(menu); } } func menuDidClose(menu: NSMenu) { streamsOpened = false; } func updateMenuToStreams(menu: NSMenu) { menu.removeAllItems() if visibleStreams == nil || visibleStreams.count == 0 { let item = NSMenuItem(title: "All offline", action: nil, keyEquivalent: "") item.enabled = false menu.addItem(item) } else { for (index, stream) in enumerate(visibleStreams) { let item = NSMenuItem(title: getVisibleName(index), action: "menuItemClicked:", keyEquivalent: "") item.enabled = true item.tag = index menu.addItem(item); } } } func menuItemClicked(sender: NSMenuItem) { streamConnector.startTaskForUrl(visibleStreams[sender.tag].stremUrl(), quality: "best") } func applicationDidFinishLaunching(aNotification: NSNotification) { NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self table.doubleAction = "doubleClick" let reachability = Reachability.reachabilityForInternetConnection() reachability.whenReachable = { reachability in self.scanForOnlineWithNotification(false) } reachability.startNotifier() linkLoader = StreamLinkLoader(); linkLoader.loadStreams { (json) -> Void in self.loadStreams(json!) self.refreshTimer.start() } } @IBAction func onPaste(sender: AnyObject) { let pasteboard = NSPasteboard.generalPasteboard() let url = pasteboard.stringForType(NSPasteboardTypeString) if let url = url { streamConnector.startTaskForUrl(url, quality: "best") } } func loadStreams(json: JSON) { if let streamers = StoreService.parseStreams(json) { self.streamers = streamers } if let settings = StoreService.parseSettings() { self.settings = settings self.showOfflineCheckmark.state = self.settings.showOffline refreshTimer = RefreshTimer(refreshTime: settings.refreshTime) { self.scanForOnlineWithNotification(true) } } self.setupServiceClients() self.scanForOnlineWithNotification(false) } func sortByOnline() { refreshVisibleStreams() visibleStreams.sort { $0 > $1 } } func refreshVisibleStreams() { self.visibleStreams = [] for streamer in streamers { for stream in streamer.1.streams { if self.showOfflineCheckmark.state == 0 { if stream.status == .Online { visibleStreams.append(stream) } } else { visibleStreams.append(stream) } } } } func applicationShouldHandleReopen(theApplication: NSApplication, hasVisibleWindows flag: Bool) -> Bool { window.setIsVisible(true) return true } @IBAction func addChannelClick(sender: AnyObject) { self.populateChannelsText() window.beginSheet(addChannelWindow) { (let response) in } } @IBAction func preferencesClick(sender: AnyObject) { window.beginSheet(preferencesWindow) { (let response) in } } @IBAction func donePreferencesClick(sender: AnyObject) { window.endSheet(preferencesWindow) self.settings.showOffline = self.showOfflineCheckmark.state StoreService.storeSettings(self.settings) scanForOnlineWithNotification(true) } func populateChannelsText() { let streamsContent = StoreService.readFile("streams", fileType: "json") if let text = streamsContent { channelsText.string = text } } @IBAction func doneAddChannelsClick(sender: AnyObject) { window.endSheet(addChannelWindow) } @IBAction func saveChannelsClick(sender: AnyObject) { StoreService.saveFile("streams", fileType: "json", content: channelsText.string!) } func setupServiceClients() { for streamer in streamers { for streamData in streamer.1.streams { switch streamData.service { case "twitch.tv": streamData.serviceClient = TwitchClient() case "cybergame.tv": streamData.serviceClient = CybergameClient() case "goodgame.ru": streamData.serviceClient = GoodgameClient() streamData.streamUrlGen = { (service, channel) in return service + "/channel/" + channel + "/" } default: println("No service client for: \(streamData.service)") } } } } func scanForOnlineWithNotification(useNotification: Bool) { for streamer in streamers { for streamData in streamer.1.streams { if let client = streamData.serviceClient { client.checkOnlineChannel(streamData.channel, result: { online, ignore in if ignore { return } if useNotification && streamData.status == .Offline && online { self.showNotificationByTitle(streamData.name) } streamData.status = online ? .Online: .Offline self.sortByOnline() self.table.reloadData() if self.streamsOpened { self.updateMenuToStreams(self.statusBar.menu!) } }) } } } } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } func showNotificationByTitle(title: String) { let not = NSUserNotification() not.title = title; not.informativeText = String(format: "%@ %@", title, "stream is online"); not.soundName = nil; NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(not); } func doubleClick() { let row = table.selectedRow if row < visibleStreams.count { streamConnector.startTaskForUrl(visibleStreams[row].stremUrl(), quality: "best") } } //MARK: - TableDataSource func numberOfRowsInTableView(tableView: NSTableView) -> Int { if let count = visibleStreams?.count { return count } return 0 } func tableView( tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return getVisibleName(row) } func getVisibleName(row: Int) -> String { let streamData = visibleStreams[row] let streamer = streamers[streamData.name] if streamer?.streams.filter({ $0.status == StreamStatus.Online }).count > 1 { return "\(streamData.name) (\(streamData.service))" } return streamData.name } func tableView(tableView: NSTableView, willDisplayCell cell: AnyObject, forTableColumn tableColumn: NSTableColumn?, row: Int) { let cell = cell as! NSTextFieldCell let service = visibleStreams[row].service let channel = visibleStreams[row].channel let status = visibleStreams[row].status if status == .Online { cell.textColor = NSColor.colorByHex("10A83F") } else if status == .Offline { cell.textColor = NSColor.colorByHex("C40E14") } else { cell.textColor = NSColor.darkGrayColor() } } }
e5a592649a5d537fc2f9e6cd6c2c9f2b
32.42268
131
0.586572
false
false
false
false
CoBug92/MyRestaurant
refs/heads/master
MyRestraunts/MyRestaurantTableViewController.swift
gpl-3.0
1
// // MyRestaurantTableViewController.swift // MyRestaurant // // Created by Богдан Костюченко on 03/10/16. // Copyright © 2016 Bogdan Kostyuchenko. All rights reserved. // import UIKit import CoreData class MyRestaurantTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { @IBAction func unwindSegue(segue: UIStoryboardSegue) { } var restaurants: [Restaurant] = [] var searchController: UISearchController! //Объект который занимается поиском var filterResultArray: [Restaurant] = [] //массив в который будет помещаться все результаты которые удовлетворяют поиску var fetchResultsController: NSFetchedResultsController<Restaurant>! override func viewDidLoad() { super.viewDidLoad() //Work with searchBar searchController = UISearchController(searchResultsController: nil) //Nil because we want that point of entry blocked main list searchController.searchResultsUpdater = self //какой котроллер будет обновлять результаты searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false //if true the controller dims tableView.tableHeaderView = searchController.searchBar //SearchBar located in the header of table definesPresentationContext = true //SearchBar works only on the mainPage (doesn't save in detailView) //Create query let fetchRequest: NSFetchRequest<Restaurant> = Restaurant.fetchRequest() //Create descriptor let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) //For getting data fetchRequest.sortDescriptors = [sortDescriptor] //Create context if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext { fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) fetchResultsController.delegate = self //try to take data do { try fetchResultsController.performFetch() //all data write in restaurants restaurants = fetchResultsController.fetchedObjects! } catch let error as NSError { print("Couldn't save data \(error.localizedDescription)") } //reload table tableView.reloadData() } //Clear unnecessary dividers self.tableView.tableFooterView = UIView(frame: CGRect.zero) //Change the interface of BACK button self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil) //Autosizing cell self.tableView.estimatedRowHeight = 85 //default height of cell (for increase capacity) self.tableView.rowHeight = UITableViewAutomaticDimension //Height is calculated automatically } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.searchController.hidesNavigationBarDuringPresentation = false //NavigationBar hides self.navigationController?.hidesBarsOnSwipe = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let userDefaults = UserDefaults.standard let wasInWatched = userDefaults.bool(forKey: "wasInWatched") guard !wasInWatched else { return } //Вызов PageViewController по его идентификатору if let PageViewController = storyboard?.instantiateViewController(withIdentifier: "pageViewController") as? PageViewController { //отображаем контроллер present(PageViewController, animated: true, completion: nil) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 //Count of sections in TableView } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive && searchController.searchBar.text != "" { return filterResultArray.count } else { return restaurants.count //Count of rows in Section } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyRestaurantTableViewCell let restaurant = restaurantToDisplayAt(indexPath: indexPath) //Configurate the cell: //Writes the value of MyRestaurant.name in nameLabel cell.nameLabel.text = restaurant.name //Writes the value of MyRestaurant.type in typeLabel cell.typeLabel.text = restaurant.type //Writes the value of MyRestaurant.location in locationLabel cell.locationLabel.text = restaurant.location cell.checkImageView.isHidden = !restaurant.wasVisited //Write the value of MyRestaurant.image in thumbnailImageView cell.thumbnailImageView.image = UIImage(data: restaurant .image as! Data) //Create the round pictures //The side of square is equal the diameter of circle, that why /2 cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.height/2 cell.thumbnailImageView.clipsToBounds = true //Give access to change the ImageView return cell } //Function creates swipe menu with additional buttons override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //Create variable which will responsible for delete button let deleteAction = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in let context = (UIApplication.shared.delegate as! AppDelegate).coreDataStack.persistentContainer.viewContext let objectToDelete = self.fetchResultsController.object(at: indexPath) context.delete(objectToDelete) do { try context.save() } catch { print(error.localizedDescription) } tableView.reloadData() } //Create action menu when user clicks "Share" let shareAction = UITableViewRowAction(style: .default, title: "Share") { (action, indexPath) in // Share item by indexPath let defaultText = "I am in \(self.restaurants[indexPath.row].name) now" if let image = UIImage(data: self.restaurants[indexPath.row].image as! Data) { let activityController = UIActivityViewController(activityItems: [defaultText, image], applicationActivities: nil) self.present(activityController, animated: true, completion: nil) } } //Change the color of Share button shareAction.backgroundColor = UIColor(red: 63 / 255, green: 84 / 255, blue: 242 / 255, alpha: 1) //return 2 possible button in action menu return [deleteAction, shareAction] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //Delete selecting of row tableView.deselectRow(at: indexPath, animated: true) } //MARK: - Fetch results controller delegate //вызывается перед тем как контроллер поменяет свой контент func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: guard let indexPath = newIndexPath else { break } tableView.insertRows(at: [indexPath], with: .fade) case .delete: guard let indexPath = indexPath else { break } tableView.deleteRows(at: [indexPath], with: .fade) case .update: guard let indexPath = indexPath else { break } tableView.reloadRows(at: [indexPath], with: .fade) default: tableView.reloadData() } restaurants = controller.fetchedObjects as! [Restaurant] } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } //MARK: - Functions //метод для отфильтровки результатов для filterResultArray func filterContentSearch(searchText text: String){ filterResultArray = restaurants.filter{ (restaurant) -> Bool in //в наш массив попадают элементы restaurant с маленькой буквы return (restaurant.name?.lowercased().contains(text.lowercased()))! } } func restaurantToDisplayAt(indexPath: IndexPath) -> Restaurant{ let restaurant: Restaurant if searchController.isActive && searchController.searchBar.text != "" { restaurant = filterResultArray[indexPath.row] } else { restaurant = restaurants[indexPath.row] } return restaurant } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DetailsSegue" { if let indexPath = self.tableView.indexPathForSelectedRow{ let destinationVC = segue.destination as! DetailsViewController destinationVC.restaurant = restaurantToDisplayAt(indexPath: indexPath) } } } // //The massive responsible for Restaurant objects // var MyRestaurant: [Restaurant] = [ // Restaurant(name: "Barrafina", type: "Bar", image: "Barrafina", location: "10 Adelaide Street, Covent Garden, London", wasVisited: false), // Restaurant(name: "Bourkestreetbakery", type: "Bakery", image: "Bourkestreetbakery", location: "480 Bourke St, Melbourne VIC 3000, Australia", wasVisited: false), // Restaurant(name: "Cafe Deadend", type: "Cafe", image: "Cafedeadend", location: "72 Po Hing Fong, Hong Kong", wasVisited: false), // Restaurant(name: "Cafe Lore", type: "Cafe", image: "Cafelore", location: "4601 4th Ave, Brooklyn, NY 11220, United States", wasVisited: false), // Restaurant(name: "Confessional", type: "Restaurant", image: "Confessional", location: "308 E 6th St, New York, NY 10003, USA", wasVisited: false), // Restaurant(name: "Donostia", type: "Restaurant", image: "Donostia", location: " 10 Seymour Pl, London W1H 7ND, United Kingdom", wasVisited: false), // Restaurant(name: "Five Leaves", type: "Bar", image: "Fiveleaves", location: "18 Bedford Ave, Brooklyn, NY 11222, United States", wasVisited: false), // Restaurant(name: "For Kee", type: "Restaurant", image: "Forkeerestaurant", location: "200 Hollywood Rd, Sheung Wan, Hong Kong", wasVisited: false), // Restaurant(name: "Graham avenue meats", type: "Restaurant", image: "Grahamavenuemeats", location: "445 Graham Ave, Brooklyn, NY 11211, United States", wasVisited: false), // Restaurant(name: "Haigh's chocolate", type: "Chocolate shope", image: "Haighschocolate", location: "The Strand Arcade, 1/412-414 George St, Sydney NSW 2000, Australia", wasVisited: false), // Restaurant(name: "Homei", type: "Restaurant", image: "Homei", location: "Shop 8/38-52 Waterloo St, Surry Hills NSW 2010, Australia", wasVisited: false), // Restaurant(name: "Palomino Espresso", type: "Espresso Bar", image: "Palominoespresso", location: "1/61 York St, Sydney NSW 2000, Australia", wasVisited: false), // Restaurant(name: "Po's Atelier", type: "Bakery", image: "Posatelier", location: "70 Po Hing Fong, Hong Kong", wasVisited: false), // Restaurant(name: "Teakha", type: "Cafe", image: "Teakha", location: "18 Tai Ping Shan St, Hong Kong", wasVisited: false), // Restaurant(name: "Traif", type: "Restaurant", image: "Traif", location: "229 S 4th St, Brooklyn, NY 11211, United States", wasVisited: false), // Restaurant(name: "Upstate", type: "Seafood Restaurant", image: "Upstate", location: "95 1st Avenue, New York, NY 10003, United States", wasVisited: false), // Restaurant(name: "Waffle & Wolf", type: "Sandwich Shop", image: "Wafflewolf", location: "413 Graham Ave, Brooklyn, NY 11211, United States", wasVisited: false) // ] } extension MyRestaurantTableViewController: UISearchResultsUpdating { //метод автоматически срабатывает когда мы что либо меняем в поисковой строке func updateSearchResults(for searchController: UISearchController) { filterContentSearch(searchText: searchController.searchBar.text!) tableView.reloadData() //заново срабатывае cellForRowAtIndexPath } } extension MyRestaurantTableViewController: UISearchBarDelegate { //когда мы щелкнули на поисковую строку func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { if searchBar.text == "" { navigationController?.hidesBarsOnSwipe = false } } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { navigationController?.hidesBarsOnSwipe = true } }
88a791502b026bd451dfc1d72d5f516d
51.378378
202
0.674775
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Module/Me/Views/MeFooterView.swift
mit
1
// // MeFooterView.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/25. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit fileprivate let LabelColor = UIColor(red: 180.0/255.0, green: 180.0/255.0, blue: 180.0/255.0, alpha: 1.0) class MeFooterView: UIView { //MARK: 属性 var viewModel:MeFooterViewModel? { didSet{ tipLabel.text = viewModel?.tipLabelText if let image = viewModel?.iconImage { iconView.image = image iconView.isHidden = false } else{ iconView.isHidden = true } } } weak var delegate:MeFooterViewDelegate? //MARK 懒加载 lazy var iconView:UIImageView = UIImageView(image: #imageLiteral(resourceName: "me_blank")) lazy var tipLabel:UILabel = { () -> UILabel in let label = UILabel() label.textColor = LabelColor label.font = fontSize16 return label }() lazy var loginButton:UIButton = { let button = UIButton(type: .custom) button.backgroundColor = UIColor.clear return button }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupMeFooterView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupMeFooterViewSubView() } //MARK: 私有方法 private func setupMeFooterView() { backgroundColor = UIColor.white addSubview(iconView) addSubview(tipLabel) addSubview(loginButton) loginButton.addTarget(self, action: #selector(loginButtonClick), for: .touchUpInside) } private func setupMeFooterViewSubView() { iconView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(80) make.centerX.equalToSuperview() } tipLabel.snp.makeConstraints { (make) in make.top.equalTo(iconView.snp.bottom).offset(margin) make.centerX.equalToSuperview() } loginButton.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } //MARK: 内部响应 @objc private func loginButtonClick() { delegate?.meFooterViewLoginButtonClick() } } //MARK: 协议 protocol MeFooterViewDelegate:NSObjectProtocol { func meFooterViewLoginButtonClick() }
9a30310af9211115a5eca1b093618ae2
25.882979
105
0.603087
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/Converters/StringAttributesToAttributes/Implementations/SuperscriptStringAttributeConverter.swift
gpl-2.0
2
import Foundation import UIKit /// Converts the superscript style information from string attributes and aggregates it into an /// existing array of element nodes. /// open class SuperscriptStringAttributeConverter: StringAttributeConverter { private let toggler = HTMLStyleToggler(defaultElement: .sup, cssAttributeMatcher: NeverCSSAttributeMatcher()) public func convert( attributes: [NSAttributedString.Key: Any], andAggregateWith elementNodes: [ElementNode]) -> [ElementNode] { var elementNodes = elementNodes // We add the representation right away, if it exists... as it could contain attributes beyond just this // style. The enable and disable methods below can modify this as necessary. // if let representation = attributes[NSAttributedString.Key.supHtmlRepresentation] as? HTMLRepresentation, case let .element(representationElement) = representation.kind { elementNodes.append(representationElement.toElementNode()) } if shouldEnable(for: attributes) { return toggler.enable(in: elementNodes) } else { return toggler.disable(in: elementNodes) } } // MARK: - Style Detection func shouldEnable(for attributes: [NSAttributedString.Key : Any]) -> Bool { return hasTraits(for: attributes) } func hasTraits(for attributes: [NSAttributedString.Key : Any]) -> Bool { guard let baselineOffset = attributes[.baselineOffset] as? NSNumber else { return false } return baselineOffset.intValue > 0; } }
eab7776b813a6f7fc7ab2f2c237bfe05
34.166667
113
0.659953
false
false
false
false
bluesnap/bluesnap-ios
refs/heads/develop
BluesnapSDK/BluesnapSDK/BSStartViewController.swift
mit
1
// // StartViewController.swift // BluesnapSDK // // Created by Shevie Chen on 17/05/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import UIKit import PassKit class BSStartViewController: UIViewController { // MARK: - private properties internal var supportedPaymentMethods: [String]? var paymentSummaryItems: [PKPaymentSummaryItem] = []; internal var activityIndicator: UIActivityIndicatorView? internal var payPalPurchaseDetails: BSPayPalSdkResult! internal var existingCardViews: [BSExistingCcUIView] = [] internal var showPayPal: Bool = false internal var showApplePay: Bool = false internal var bottomOfLastIcon: CGFloat = 0 // MARK: Outlets @IBOutlet weak var centeredView: UIView! @IBOutlet weak var ccnButton: BSPaymentTypeView! @IBOutlet weak var applePayButton: BSPaymentTypeView! @IBOutlet weak var payPalButton: BSPaymentTypeView! // MARK: init func initScreen() { self.supportedPaymentMethods = BSApiManager.supportedPaymentMethods } // MARK: UIViewController functions override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController!.isNavigationBarHidden = false // Hide/show the buttons and position them automatically showPayPal = BSApiManager.isSupportedPaymentMethod(paymentType: BSPaymentType.PayPal, supportedPaymentMethods: supportedPaymentMethods) && !(BlueSnapSDK.sdkRequestBase is BSSdkRequestSubscriptionCharge) showApplePay = BlueSnapSDK.applePaySupported(supportedPaymentMethods: supportedPaymentMethods, supportedNetworks: BlueSnapSDK.applePaySupportedNetworks).canMakePayments //self.hideShowElements() // Localize strings self.title = BSLocalizedStrings.getString(BSLocalizedString.Title_Payment_Type) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopActivityIndicator() } // MARK: button functions @IBAction func applePayClick(_ sender: Any) { let applePaySupported = BlueSnapSDK.applePaySupported(supportedPaymentMethods: supportedPaymentMethods, supportedNetworks: BlueSnapSDK.applePaySupportedNetworks) if (!applePaySupported.canMakePayments) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_Not_available_on_this_device) present(alert, animated: true, completion: nil) return; } if (!applePaySupported.canSetupCards) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_No_cards_set) present(alert, animated: true, completion: nil) return; } if BSApplePayConfiguration.getIdentifier() == nil { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_Setup_error) NSLog("Missing merchant identifier for apple pay") present(alert, animated: true, completion: nil) return; } if BlueSnapSDK.sdkRequestBase is BSSdkRequestShopperRequirements { BSApiManager.shopper?.chosenPaymentMethod = BSChosenPaymentMethod(chosenPaymentMethodType: BSPaymentType.ApplePay.rawValue) BlueSnapSDK.updateShopper(completion: { (isSuccess, message) in DispatchQueue.main.async { if (!isSuccess) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: message!) self.present(alert, animated: true, completion: nil) return } else { _ = self.navigationController?.popViewController(animated: false) // execute callback let applePayPurchaseDetails = BSApplePaySdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) BlueSnapSDK.sdkRequestBase?.purchaseFunc(applePayPurchaseDetails) } } }) } else { applePayPressed(sender, completion: { (error) in DispatchQueue.main.async { NSLog("Apple pay completion") if error == BSErrors.applePayCanceled { NSLog("Apple Pay operation canceled") return } else if error != nil { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_General_ApplePay_error) self.present(alert, animated: true, completion: nil) return } else { _ = self.navigationController?.popViewController(animated: false) // execute callback let applePayPurchaseDetails = BSApplePaySdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) BlueSnapSDK.sdkRequestBase?.purchaseFunc(applePayPurchaseDetails) } } } ) } } @IBAction func ccDetailsClick(_ sender: Any) { let backItem = UIBarButtonItem() backItem.title = BSLocalizedStrings.getString(BSLocalizedString.Navigate_Back_to_payment_type_screen) navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed animateToPaymentScreen(startY: bottomOfLastIcon, completion: { animate in _ = BSViewsManager.showCCDetailsScreen(existingCcPurchaseDetails: nil, inNavigationController: self.navigationController, animated: animate) }) } @IBAction func payPalClicked(_ sender: Any) { payPalPurchaseDetails = BSPayPalSdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) if BlueSnapSDK.sdkRequestBase is BSSdkRequestShopperRequirements { BSApiManager.shopper?.chosenPaymentMethod = BSChosenPaymentMethod(chosenPaymentMethodType: BSPaymentType.PayPal.rawValue) BlueSnapSDK.updateShopper(completion: { (isSuccess, message) in DispatchQueue.main.async { if (!isSuccess) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_PayPal, message: message!) self.present(alert, animated: true, completion: nil) return } else { _ = self.navigationController?.popViewController(animated: false) // execute callback let payPalPurchaseDetails = BSPayPalSdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) BlueSnapSDK.sdkRequestBase?.purchaseFunc(payPalPurchaseDetails) } } }) } else { DispatchQueue.main.async { self.startActivityIndicator() } DispatchQueue.main.async { BSApiManager.createPayPalToken(purchaseDetails: self.payPalPurchaseDetails, withShipping: BlueSnapSDK.sdkRequestBase!.shopperConfiguration.withShipping, completion: { resultToken, resultError in if let resultToken = resultToken { self.stopActivityIndicator() DispatchQueue.main.async { BSViewsManager.showBrowserScreen(inNavigationController: (nil != self.navigationController) ? self.navigationController : sender as! UINavigationController, url: resultToken, shouldGoToUrlFunc: self.paypalUrlListener) } } else { let errMsg = resultError == .paypalUnsupportedCurrency ? BSLocalizedString.Error_PayPal_Currency_Not_Supported : BSLocalizedString.Error_General_PayPal_error let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_PayPal, message: errMsg) self.stopActivityIndicator() self.present(alert, animated: true, completion: nil) } }) } } } // Mark: private functions private func isShowPayPal() -> Bool { var showPayPal = false showPayPal = !(BlueSnapSDK.sdkRequestBase is BSSdkRequestSubscriptionCharge) && BSApiManager.isSupportedPaymentMethod(paymentType: BSPaymentType.PayPal, supportedPaymentMethods: supportedPaymentMethods) return showPayPal } private func hideShowElements() { var existingCreditCards: [BSCreditCardInfo] = [] if let shopper = BSApiManager.shopper { existingCreditCards = shopper.existingCreditCards } let numSections = existingCreditCards.count + ((showPayPal && showApplePay) ? 3 : (!showPayPal && !showApplePay) ? 1 : 2) var sectionNum: CGFloat = 0 let sectionY: CGFloat = (centeredView.frame.height / CGFloat(numSections + 1)).rounded() if showApplePay { applePayButton.isHidden = false sectionNum = sectionNum + 1 applePayButton.center.y = sectionY * sectionNum bottomOfLastIcon = applePayButton.frame.maxY } else { applePayButton.isHidden = true } sectionNum = sectionNum + 1 ccnButton.center.y = sectionY * sectionNum bottomOfLastIcon = ccnButton.frame.maxY if showPayPal { sectionNum = sectionNum + 1 payPalButton.isHidden = false payPalButton.center.y = sectionY * sectionNum } else { payPalButton.isHidden = true } bottomOfLastIcon = payPalButton.frame.maxY let newCcRect = self.ccnButton.frame if existingCreditCards.count > 0 && existingCardViews.count == 0 { var tag: Int = 0 for existingCreditCard in existingCreditCards { let cardView = BSExistingCcUIView() self.centeredView.addSubview(cardView) cardView.frame = CGRect(x: newCcRect.minX, y: newCcRect.minY, width: newCcRect.width, height: newCcRect.height) sectionNum = sectionNum + 1 cardView.center.y = sectionY * sectionNum bottomOfLastIcon = cardView.frame.maxY cardView.setCc( ccType: existingCreditCard.creditCard.ccType ?? "", last4Digits: existingCreditCard.creditCard.last4Digits ?? "", expiration: existingCreditCard.creditCard.getExpiration()) cardView.resizeElements() cardView.addTarget(self, action: #selector(BSStartViewController.existingCCTouchUpInside(_:)), for: .touchUpInside) cardView.tag = tag // cardView.isAccessibilityElement = true let accessibilityIdentifier = "existingCc\(tag)" cardView.accessibilityIdentifier = accessibilityIdentifier cardView.isUserInteractionEnabled = true cardView.accessibilityTraits = UIAccessibilityTraits.button tag = tag + 1 } } } @objc func existingCCTouchUpInside(_ sender: Any) { if let existingCcUIView = sender as? BSExistingCcUIView, let existingCreditCards = BSApiManager.shopper?.existingCreditCards { let ccIdx = existingCcUIView.tag let cc = existingCreditCards[ccIdx] animateToPaymentScreen(startY: existingCcUIView.frame.minY, completion: { animate in let purchaseDetails = BSExistingCcSdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!, shopper: BSApiManager.shopper, existingCcDetails: cc) _ = BSViewsManager.showExistingCCDetailsScreen(purchaseDetails: purchaseDetails, inNavigationController: self.navigationController, animated: animate) }) } } private func animateToPaymentScreen(startY: CGFloat, completion: ((Bool) -> Void)!) { let moveUpBy = self.centeredView.frame.minY + startY - 48 UIView.animate(withDuration: 0.3, animations: { self.centeredView.center.y = self.centeredView.center.y - moveUpBy }, completion: { animate in completion(false) self.centeredView.center.y = self.centeredView.center.y + moveUpBy }) } func paypalUrlListener(url: String) -> Bool { if BSPaypalHandler.isPayPalProceedUrl(url: url) { // paypal success! BSPaypalHandler.parsePayPalResultDetails(url: url, purchaseDetails: self.payPalPurchaseDetails) // return to merchant screen if let viewControllers = navigationController?.viewControllers { let merchantControllerIndex = viewControllers.count - 3 _ = navigationController?.popToViewController(viewControllers[merchantControllerIndex], animated: false) } // execute callback BlueSnapSDK.sdkRequestBase?.purchaseFunc(self.payPalPurchaseDetails) return false } else if BSPaypalHandler.isPayPalCancelUrl(url: url) { // PayPal cancel URL detected - close web screen _ = navigationController?.popViewController(animated: false) return false } return true } // MARK: Prevent rotation, support only Portrait mode override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return UIInterfaceOrientation.portrait } // Activity indicator func startActivityIndicator() { if self.activityIndicator == nil { activityIndicator = BSViewsManager.createActivityIndicator(view: self.view) } BSViewsManager.startActivityIndicator(activityIndicator: activityIndicator!, blockEvents: true) } func stopActivityIndicator() { if let activityIndicator = activityIndicator { BSViewsManager.stopActivityIndicator(activityIndicator: activityIndicator) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.hideShowElements() } }
5144d164a4909b7314c00733a21d084a
42.181818
245
0.644211
false
false
false
false
BabyShung/SplashWindow
refs/heads/master
SplashWindow/Views/SWShadowView.swift
mit
1
import UIKit public class SWShadowView: UIView { @IBInspectable var cornerRadius: CGFloat = 4.0 { didSet { updateProperties() } } @IBInspectable var shadowColor: UIColor = UIColor.black { didSet { updateProperties() } } @IBInspectable var shadowOffset: CGSize = CGSize(width: 0.0, height: 2) { didSet { updateProperties() } } @IBInspectable var shadowRadius: CGFloat = 2.5 { didSet { updateProperties() } } @IBInspectable var shadowOpacity: Float = 0.3 { didSet { updateProperties() } } public override func awakeFromNib() { super.awakeFromNib() layer.masksToBounds = false updateProperties() updateShadowPath() } public override func layoutSubviews() { super.layoutSubviews() updateShadowPath() } fileprivate func updateProperties() { layer.cornerRadius = cornerRadius layer.shadowColor = shadowColor.cgColor layer.shadowOffset = shadowOffset layer.shadowRadius = shadowRadius layer.shadowOpacity = shadowOpacity } fileprivate func updateShadowPath() { layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath } }
5984e4d9e4afd808e6087f053b9fabbb
22.196721
107
0.584452
false
false
false
false
igerard/Genesis
refs/heads/master
Genesis/Pages/BoardPageView.swift
mit
1
// // BoardPageView.swift // Genesis // // Created by Gerard Iglesias on 01/10/2017. // Copyright © 2017 Gerard Iglesias. All rights reserved. // import UIKit import Metal import MetalKit import simd /// The Vertex structure struct SimpleVertex { var position : float4 var color : float4 } struct Uniforms { var modelViewProjectionMatrix : matrix_float4x4 }; class BoardPageView: MTKView { var pageFormat = A4 { didSet { camera = BoardPageCamera(center: CGPoint(x: pageFormat.width/2.0, y: pageFormat.height/2.0), up: CGVector(dx: 0, dy: 1), extend: CGSize(width: pageFormat.width, height: pageFormat.height)) setNeedsDisplay() } } var showGrid = false { didSet { setNeedsDisplay() NotificationCenter.default.post(name: InfoEventGeneric, object: self, userInfo: ["message":showGrid ? "Show Grid" : "Hide Grid"]) } } // viewing of the world var camera = BoardPageCamera(); var mlLayer : CAMetalLayer { get { return self.layer as! CAMetalLayer } } var commandQueue: MTLCommandQueue? // MARK Data structure let pageGrid: GeoPageGrid! let axes: GeoAxes! var axePosition = float2(0,0) var viewingBuffer : MTLBuffer? var library : MTLLibrary? var vertexFunction : MTLFunction? var fragmentFunction : MTLFunction? var pipelineState : MTLRenderPipelineState? // the struc to pass transformation to the shader var uniforms = Uniforms(modelViewProjectionMatrix: matrix_identity_float4x4) // overrides // MARK: Init Phase override init(frame frameRect: CGRect, device: MTLDevice?) { camera = BoardPageCamera(center: CGPoint(x: pageFormat.width/2.0, y: pageFormat.height/2.0), up: CGVector(dx: 0, dy: 1), extend: CGSize(width: pageFormat.width, height: pageFormat.height)) axes = GeoAxes(size: float2(1,1), device: device) pageGrid = device.flatMap{GeoPageGrid(pageFormat: A4, device: $0)} super.init(frame: frameRect, device: device) isOpaque = false mlLayer.isOpaque = false preferredFramesPerSecond = 60 let value = 1.0 clearColor = MTLClearColor(red: value, green: value, blue: value, alpha: 1) clearDepth = 1.0 clearStencil = 0 colorPixelFormat = .bgra8Unorm sampleCount = 4 commandQueue = self.device?.makeCommandQueue() makeBuffers() makePipeline() } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func makeBuffers(){ // the viewing buffer let viewingBufferSize = MemoryLayout<Uniforms>.size viewingBuffer = self.device?.makeBuffer(length: viewingBufferSize, options: .cpuCacheModeWriteCombined) } func makePipeline(){ library = self.device?.makeDefaultLibrary() vertexFunction = library?.makeFunction(name : "vertex_main") fragmentFunction = library?.makeFunction(name : "fragment_main") let pipelineDescr = MTLRenderPipelineDescriptor() pipelineDescr.vertexFunction = vertexFunction pipelineDescr.fragmentFunction = fragmentFunction pipelineDescr.colorAttachments[0].pixelFormat = mlLayer.pixelFormat pipelineDescr.sampleCount = sampleCount do { pipelineState = try device!.makeRenderPipelineState(descriptor: pipelineDescr) } catch { board_log_error("%@", error.localizedDescription) } } // refresh the viewing transformation func updateViewBuffer(){ uniforms.modelViewProjectionMatrix = camera.metalProjectionToViewport(bounds.size) memcpy(viewingBuffer?.contents(), &uniforms, MemoryLayout<Uniforms>.size) } // MARK: Display override func draw(_ rect : CGRect) { guard self.device != nil else{ board_log_error("%@", "No Metal device") return } guard self.commandQueue != nil else{ board_log_error("%@", "No Command Queue") return } guard self.pipelineState != nil else{ board_log_error("%@", "No pipeline") return } if let drawable = self.currentDrawable, let commandBuffer = commandQueue!.makeCommandBuffer(), let passDescr = self.currentRenderPassDescriptor, let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescr){ commandEncoder.setRenderPipelineState(pipelineState!) let nativeScale = Double(UIScreen.main.nativeScale) let viewport = MTLViewport(originX: 0, originY: 0, width: nativeScale*Double(bounds.width), height: nativeScale*Double(bounds.height), znear: 0, zfar: 1) commandEncoder.setViewport(viewport) updateViewBuffer() drawGeometry(commandEncoder) commandEncoder.endEncoding() commandBuffer.present(drawable) commandBuffer.commit() } } fileprivate func drawGeometry(_ commandEncoder: MTLRenderCommandEncoder) { if let viewBuffer = viewingBuffer { axes.drawAt(position: axePosition, encoder: commandEncoder, viewingBuffer: viewBuffer) if showGrid { pageGrid?.draw(encoder: commandEncoder, viewingBuffer: viewBuffer) } } } // MARK: Events // MARK: Layouts // MARK: Archive override func awakeFromNib() { board_log_debug("%@", self.mlLayer.debugDescription) } }
1daf061c82ccc2989d2f710ae5697fd0
27.861878
194
0.69219
false
false
false
false
nthery/SwiftForth
refs/heads/master
SwiftForthKit/evaluator.swift
mit
1
// // Top-level class coordinating compiler and virtual machine. // import Foundation // A context for interpreting Forth code. // Main entry point for clients. public class ForthEvaluator { let compiler = Compiler() let vm = VM() public init() { // Compile builtins implemented in Forth. evalOrDie(": CR 13 EMIT ;") } // Evaluate Forth source code. // Passing incomplete code fragments is supported. For example eval(": foo") followed // by eval("42 ;"). // Return true on success. // Report an error through handler passed to setErrorHandler() and return false on failure. public func eval(input: String) -> Bool { if let phrase = compiler.compile(input) { debug(.Evaluator, "compiled: \(phrase)") return vm.execPhrase(phrase) } else { return false } } public func setErrorHandler(handler: ForthErrorHandler) { compiler.errorHandler = handler vm.errorHandler = handler } // Return accumulated content generated by '.', EMIT, CR and co and reset it afterward. public func getAndResetOutput() -> String { let o = vm.output vm.output = "" return o } // Allow clients to manipulate argument stack directly. public var argStack : ForthStack<Int> { return vm.argStack } func evalOrDie(input: String) { if !eval(input) { println("failed to evaluate '\(input)'") exit(1) } } }
05750424d381a31cc33e32849318d674
27.145455
95
0.601164
false
false
false
false
NorthernRealities/ColorSenseRainbow
refs/heads/master
ColorSenseRainbow/WhiteSeeker.swift
mit
1
// // WhiteSeeker.swift // ColorSenseRainbow // // Created by Reid Gravelle on 2015-08-05. // Copyright (c) 2015 Northern Realities Inc. All rights reserved. // import AppKit class WhiteSeeker: Seeker { override init () { super.init() var error : NSError? var regex: NSRegularExpression? // Swift let commonSwiftRegex = "hite:\\s*" + swiftFloatColourConst + "\\s*,\\s*alpha:\\s*" + swiftAlphaConst + "\\s*\\)" do { regex = try NSRegularExpression ( pattern: "(?:NS|UI)Color" + swiftInit + "\\s*\\(\\s*w" + commonSwiftRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift White float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { regex = try NSRegularExpression ( pattern: "NSColor" + swiftInit + "\\s*\\(\\s*(?:calibrated|device|genericGamma22)W" + commonSwiftRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift NSColor calibrated, device, genericGamma22 white float regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } // Objective-C - Only functions with alpha defined let commonObjCRegex = "White:\\s*" + objcFloatColourConst + "\\s*alpha:\\s*" + objcAlphaConst + "\\s*\\]" do { regex = try NSRegularExpression ( pattern: "\\[\\s*(?:NS|UI)Color\\s*colorWith" + commonObjCRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Objective-C White float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { // Don't care about saving the Calibrated, Device, or genericGamma22 since we assume that any function that // replace the values will do so selectively instead of overwriting the whole string. regex = try NSRegularExpression ( pattern: "\\[\\s*NSColor\\s*colorWith(?:Calibrated|Device|GenericGamma22)" + commonObjCRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Objective-C calibrated, device, genericGamma22 white float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } } override func processMatch ( match : NSTextCheckingResult, line : String ) -> SearchResult? { // We'll always have two matches right now but if ever the alpha becomes optional // then it will be either one or two and this function will have to look like // the others. if ( match.numberOfRanges == 3 ) { let matchString = stringFromRange( match.range, line: line ) let whiteString = stringFromRange( match.rangeAtIndex( 1 ), line: line ) let alphaString = stringFromRange( match.rangeAtIndex( 2 ), line: line ) let capturedStrings = [ matchString, whiteString, alphaString ] let whiteValue = CGFloat ( ( whiteString as NSString).doubleValue ) let alphaValue = CGFloat ( ( alphaString as NSString).doubleValue ) let whiteColor = NSColor ( calibratedWhite: whiteValue, alpha: alphaValue ) if let color = whiteColor.colorUsingColorSpace( NSColorSpace.genericRGBColorSpace() ) { var searchResult = SearchResult ( color: color, textCheckingResult: match, capturedStrings: capturedStrings ) searchResult.creationType = .DefaultWhite return searchResult } } return nil } }
253fdbed778b59e469eb6e569098771b
35.466102
162
0.555891
false
false
false
false
gerardogrisolini/Webretail
refs/heads/master
Sources/Webretail/Models/MwsRequest.swift
apache-2.0
1
// // MwsRequest.swift // Webretail // // Created by Gerardo Grisolini on 22/04/18. // import Foundation import PerfectLogger import StORM class MwsRequest : PostgresSqlORM, Codable { public var id: Int = 0 public var requestSku : String = "" public var requestXml : String = "" public var requestId: Int = 0 public var requestParentId: Int = 0 public var requestSubmissionId: String = "" public var requestCreatedAt: Int = Int.now() public var requestSubmittedAt: Int = 0 public var requestCompletedAt: Int = 0 public var messagesProcessed: Int = 0 public var messagesSuccessful: Int = 0 public var messagesWithError: Int = 0 public var messagesWithWarning: Int = 0 public var errorDescription: String = "" open override func table() -> String { return "mwsrequests" } override init() { super.init() } open override func to(_ this: StORMRow) { id = this.data["id"] as? Int ?? 0 requestSku = this.data["requestsku"] as? String ?? "" requestXml = this.data["requestxml"] as? String ?? "" requestId = this.data["requestid"] as? Int ?? 0 requestParentId = this.data["requestparentid"] as? Int ?? 0 requestSubmissionId = this.data["requestsubmissionid"] as? String ?? "" requestCreatedAt = this.data["requestcreatedat"] as? Int ?? 0 requestSubmittedAt = this.data["requestsubmittedat"] as? Int ?? 0 requestCompletedAt = this.data["requestcompletedat"] as? Int ?? 0 messagesProcessed = this.data["messagesprocessed"] as? Int ?? 0 messagesSuccessful = this.data["messagessuccessful"] as? Int ?? 0 messagesWithError = this.data["messageswitherror"] as? Int ?? 0 messagesWithWarning = this.data["messageswithwarning"] as? Int ?? 0 errorDescription = this.data["errordescription"] as? String ?? "" } func rows() -> [MwsRequest] { var rows = [MwsRequest]() for i in 0..<self.results.rows.count { let row = MwsRequest() row.to(self.results.rows[i]) rows.append(row) } return rows } public func currentRequests() throws -> [MwsRequest] { // try self.query(whereclause: "requestcompletedat = $1", params: [0]) try self.query(orderby: ["requestcreatedat DESC", "requestid"]) return self.rows() } public func rangeRequests(startDate: Int, finishDate: Int) throws -> [MwsRequest] { try self.query( whereclause: "requestcreatedat >= $1 && requestcreatedat <= $2 ", params: [startDate, finishDate], orderby: ["requestcreatedat DESC", "requestid"] ) return self.rows() } public func lastRequest() throws -> Int { let sql = "SELECT MAX(requestcreatedat) AS counter FROM \(table())"; let getCount = try self.sqlRows(sql, params: []) return getCount.first?.data["counter"] as? Int ?? 0 } }
54a64377db487ffca15b6f12b707e318
34.348837
87
0.613158
false
false
false
false
stevehe-campray/BSBDJ
refs/heads/master
BSBDJ/BSBDJ/FriendTrends(关注)/Controllers/BSBFriendTrendsViewController.swift
mit
1
// // BSBFriendTrendsViewController.swift // BSBDJ // // Created by hejingjin on 16/3/15. // Copyright © 2016年 baisibudejie. All rights reserved. // import UIKit class BSBFriendTrendsViewController: UIViewController { @IBOutlet weak var loginregiterButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setUpNavgation() setupMainInterface() self.view.backgroundColor = UIColor.lightGrayColor() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupMainInterface(){ loginregiterButton.addTarget(self, action: #selector(BSBFriendTrendsViewController.login), forControlEvents: UIControlEvents.TouchUpInside) } @IBAction func LoginButtonPressed(sender: AnyObject) { let loginvc = BSBLoginRegisterViewController(nibName:"BSBLoginRegisterViewController", bundle:nil) self .presentViewController(loginvc, animated: true, completion: nil) } func setUpNavgation(){ self.navigationItem.title = "我的关注" let leftButton = UIButton() leftButton.setBackgroundImage(UIImage(named: "friendsRecommentIcon"), forState: UIControlState.Normal) leftButton.setBackgroundImage(UIImage(named: "cellFollowClickIcon"), forState: UIControlState.Highlighted) leftButton.bounds = CGRectMake(0, 0, (leftButton.currentBackgroundImage?.size.width)!, (leftButton.currentBackgroundImage?.size.height)!) leftButton.addTarget(self, action: #selector(BSBFriendTrendsViewController.myrecomment), forControlEvents: UIControlEvents.TouchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton) } func myrecomment(){ let recomendvc = BSBrecomendViewController(nibName:"BSBrecomendViewController" ,bundle:nil) self.navigationController?.pushViewController(recomendvc, animated: true) } func login(){ print("login") } }
9a42b0a9224b2f64e6df31c44713644b
34.483333
147
0.715359
false
false
false
false
4taras4/totp-auth
refs/heads/master
TOTP/ViperModules/MainList/Module/Interactor/MainListInteractor.swift
mit
1
// // MainListMainListInteractor.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import OneTimePassword import Base32 final class MainListInteractor: MainListInteractorInput { weak var output: MainListInteractorOutput? func converUserData(users: [User]) { var codes = [Code]() var favouritesArray = [Code]() for u in users { if let c = convertUser(user: u) { if u.isFavourite == true { favouritesArray.append(c) } codes.append(c) } } output?.listOfCodes(codes: codes, favourites: favouritesArray) } func convertUser(user: User) -> Code? { guard let secretData = MF_Base32Codec.data(fromBase32String: user.token), !secretData.isEmpty else { print("Invalid secret") return nil } guard let generator = Generator( factor: .timer(period: 30), secret: secretData, algorithm: .sha1, digits: 6) else { print("Invalid generator parameters") return nil } let token = Token(name: user.name ?? "", issuer: user.issuer ?? "", generator: generator) guard let currentCode = token.currentPassword else { print("Invalid generator parameters") return nil } return Code(name: user.name, issuer: user.issuer, code: currentCode, token: user.token) } func deleteRow(with token: String?) { let alertController = UIAlertController(title: Constants.text.removeBackupAlertTitle, message: Constants.text.removeBackupAlertDescription, preferredStyle: .alert) let cancelAction = UIAlertAction(title: Constants.text.cancelAlertButton, style: .cancel) let okAction = UIAlertAction(title: Constants.text.removeAlertButton, style: .destructive, handler: { _ in guard let item = RealmManager.shared.getUserBy(token: token) else { return } RealmManager.shared.removeObject(user: item, completionHandler: { success in if success { self.output?.dataBaseOperationFinished() } }) }) alertController.addAction(cancelAction) alertController.addAction(okAction) if let topController = UIApplication.topViewController() { topController.present(alertController, animated: true, completion: nil) } } func updateRow(with token: String?, isFavourite: Bool) { guard let item = RealmManager.shared.getUserBy(token: token) else { return } RealmManager.shared.saveNewUser(name: item.name, issuer: item.issuer, token: item.token ?? "", isFav: isFavourite, completionHandler: { completed in if completed { self.output?.dataBaseOperationFinished() } }) } func getFolders() { output?.listOfFolders(array: RealmManager.shared.fetchFolders() ?? []) } }
1c381c83dfd5850a0e37e0ef45d8b937
35.022989
171
0.60402
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPosix/SelectorEpoll.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore #if !SWIFTNIO_USE_IO_URING #if os(Linux) || os(Android) /// Represents the `epoll` filters/events we might use: /// /// - `hangup` corresponds to `EPOLLHUP` /// - `readHangup` corresponds to `EPOLLRDHUP` /// - `input` corresponds to `EPOLLIN` /// - `output` corresponds to `EPOLLOUT` /// - `error` corresponds to `EPOLLERR` private struct EpollFilterSet: OptionSet, Equatable { typealias RawValue = UInt8 let rawValue: RawValue static let _none = EpollFilterSet([]) static let hangup = EpollFilterSet(rawValue: 1 << 0) static let readHangup = EpollFilterSet(rawValue: 1 << 1) static let input = EpollFilterSet(rawValue: 1 << 2) static let output = EpollFilterSet(rawValue: 1 << 3) static let error = EpollFilterSet(rawValue: 1 << 4) init(rawValue: RawValue) { self.rawValue = rawValue } } extension EpollFilterSet { /// Convert NIO's `SelectorEventSet` set to a `EpollFilterSet` init(selectorEventSet: SelectorEventSet) { var thing: EpollFilterSet = [.error, .hangup] if selectorEventSet.contains(.read) { thing.formUnion(.input) } if selectorEventSet.contains(.write) { thing.formUnion(.output) } if selectorEventSet.contains(.readEOF) { thing.formUnion(.readHangup) } self = thing } } extension SelectorEventSet { var epollEventSet: UInt32 { assert(self != ._none) // EPOLLERR | EPOLLHUP is always set unconditionally anyway but it's easier to understand if we explicitly ask. var filter: UInt32 = Epoll.EPOLLERR | Epoll.EPOLLHUP let epollFilters = EpollFilterSet(selectorEventSet: self) if epollFilters.contains(.input) { filter |= Epoll.EPOLLIN } if epollFilters.contains(.output) { filter |= Epoll.EPOLLOUT } if epollFilters.contains(.readHangup) { filter |= Epoll.EPOLLRDHUP } assert(filter & Epoll.EPOLLHUP != 0) // both of these are reported assert(filter & Epoll.EPOLLERR != 0) // always and can't be masked. return filter } fileprivate init(epollEvent: Epoll.epoll_event) { var selectorEventSet: SelectorEventSet = ._none if epollEvent.events & Epoll.EPOLLIN != 0 { selectorEventSet.formUnion(.read) } if epollEvent.events & Epoll.EPOLLOUT != 0 { selectorEventSet.formUnion(.write) } if epollEvent.events & Epoll.EPOLLRDHUP != 0 { selectorEventSet.formUnion(.readEOF) } if epollEvent.events & Epoll.EPOLLHUP != 0 || epollEvent.events & Epoll.EPOLLERR != 0 { selectorEventSet.formUnion(.reset) } self = selectorEventSet } } // EPollUserData supports (un)packing into an `UInt64` because epoll has a user info field that we can attach which is // up to 64 bits wide. We're using all of those 64 bits, 32 for a "registration ID" and 32 for the file descriptor. @usableFromInline struct EPollUserData { @usableFromInline var registrationID: SelectorRegistrationID @usableFromInline var fileDescriptor: CInt @inlinable init(registrationID: SelectorRegistrationID, fileDescriptor: CInt) { assert(MemoryLayout<UInt64>.size == MemoryLayout<EPollUserData>.size) self.registrationID = registrationID self.fileDescriptor = fileDescriptor } @inlinable init(rawValue: UInt64) { let unpacked = IntegerBitPacking.unpackUInt32CInt(rawValue) self = .init(registrationID: SelectorRegistrationID(rawValue: unpacked.0), fileDescriptor: unpacked.1) } } extension UInt64 { @inlinable init(_ epollUserData: EPollUserData) { let fd = epollUserData.fileDescriptor assert(fd >= 0, "\(fd) is not a valid file descriptor") self = IntegerBitPacking.packUInt32CInt(epollUserData.registrationID.rawValue, fd) } } extension Selector: _SelectorBackendProtocol { func initialiseState0() throws { self.selectorFD = try Epoll.epoll_create(size: 128) self.eventFD = try EventFd.eventfd(initval: 0, flags: Int32(EventFd.EFD_CLOEXEC | EventFd.EFD_NONBLOCK)) self.timerFD = try TimerFd.timerfd_create(clockId: CLOCK_MONOTONIC, flags: Int32(TimerFd.TFD_CLOEXEC | TimerFd.TFD_NONBLOCK)) self.lifecycleState = .open var ev = Epoll.epoll_event() ev.events = SelectorEventSet.read.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: .initialRegistrationID, fileDescriptor: self.eventFD)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: self.eventFD, event: &ev) var timerev = Epoll.epoll_event() timerev.events = Epoll.EPOLLIN | Epoll.EPOLLERR | Epoll.EPOLLRDHUP timerev.data.u64 = UInt64(EPollUserData(registrationID: .initialRegistrationID, fileDescriptor: self.timerFD)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: self.timerFD, event: &timerev) } func deinitAssertions0() { assert(self.eventFD == -1, "self.eventFD == \(self.eventFD) in deinitAssertions0, forgot close?") assert(self.timerFD == -1, "self.timerFD == \(self.timerFD) in deinitAssertions0, forgot close?") } func register0<S: Selectable>(selectable: S, fileDescriptor: CInt, interested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() ev.events = interested.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: registrationID, fileDescriptor: fileDescriptor)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: fileDescriptor, event: &ev) } func reregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, newInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() ev.events = newInterested.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: registrationID, fileDescriptor: fileDescriptor)) _ = try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_MOD, fd: fileDescriptor, event: &ev) } func deregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() _ = try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_DEL, fd: fileDescriptor, event: &ev) } /// Apply the given `SelectorStrategy` and execute `body` once it's complete (which may produce `SelectorEvent`s to handle). /// /// - parameters: /// - strategy: The `SelectorStrategy` to apply /// - body: The function to execute for each `SelectorEvent` that was produced. func whenReady0(strategy: SelectorStrategy, onLoopBegin loopStart: () -> Void, _ body: (SelectorEvent<R>) throws -> Void) throws -> Void { assert(self.myThread == NIOThread.current) guard self.lifecycleState == .open else { throw IOError(errnoCode: EBADF, reason: "can't call whenReady for selector as it's \(self.lifecycleState).") } let ready: Int switch strategy { case .now: ready = Int(try Epoll.epoll_wait(epfd: self.selectorFD, events: events, maxevents: Int32(eventsCapacity), timeout: 0)) case .blockUntilTimeout(let timeAmount): // Only call timerfd_settime if we're not already scheduled one that will cover it. // This guards against calling timerfd_settime if not needed as this is generally speaking // expensive. let next = NIODeadline.now() + timeAmount if next < self.earliestTimer { self.earliestTimer = next var ts = itimerspec() ts.it_value = timespec(timeAmount: timeAmount) try TimerFd.timerfd_settime(fd: self.timerFD, flags: 0, newValue: &ts, oldValue: nil) } fallthrough case .block: ready = Int(try Epoll.epoll_wait(epfd: self.selectorFD, events: events, maxevents: Int32(eventsCapacity), timeout: -1)) } loopStart() for i in 0..<ready { let ev = events[i] let epollUserData = EPollUserData(rawValue: ev.data.u64) let fd = epollUserData.fileDescriptor let eventRegistrationID = epollUserData.registrationID switch fd { case self.eventFD: var val = EventFd.eventfd_t() // Consume event _ = try EventFd.eventfd_read(fd: self.eventFD, value: &val) case self.timerFD: // Consume event var val: UInt64 = 0 // We are not interested in the result _ = try! Posix.read(descriptor: self.timerFD, pointer: &val, size: MemoryLayout.size(ofValue: val)) // Processed the earliest set timer so reset it. self.earliestTimer = .distantFuture default: // If the registration is not in the Map anymore we deregistered it during the processing of whenReady(...). In this case just skip it. if let registration = registrations[Int(fd)] { guard eventRegistrationID == registration.registrationID else { continue } var selectorEvent = SelectorEventSet(epollEvent: ev) // we can only verify the events for i == 0 as for i > 0 the user might have changed the registrations since then. assert(i != 0 || selectorEvent.isSubset(of: registration.interested), "selectorEvent: \(selectorEvent), registration: \(registration)") // in any case we only want what the user is currently registered for & what we got selectorEvent = selectorEvent.intersection(registration.interested) guard selectorEvent != ._none else { continue } try body((SelectorEvent(io: selectorEvent, registration: registration))) } } } growEventArrayIfNeeded(ready: ready) } /// Close the `Selector`. /// /// After closing the `Selector` it's no longer possible to use it. public func close0() throws { self.externalSelectorFDLock.withLock { // We try! all of the closes because close can only fail in the following ways: // - EINTR, which we eat in Posix.close // - EIO, which can only happen for on-disk files // - EBADF, which can't happen here because we would crash as EBADF is marked unacceptable // Therefore, we assert here that close will always succeed and if not, that's a NIO bug we need to know // about. try! Posix.close(descriptor: self.timerFD) self.timerFD = -1 try! Posix.close(descriptor: self.eventFD) self.eventFD = -1 try! Posix.close(descriptor: self.selectorFD) self.selectorFD = -1 } } /* attention, this may (will!) be called from outside the event loop, ie. can't access mutable shared state (such as `self.open`) */ func wakeup0() throws { assert(NIOThread.current != self.myThread) try self.externalSelectorFDLock.withLock { guard self.eventFD >= 0 else { throw EventLoopError.shutdown } _ = try EventFd.eventfd_write(fd: self.eventFD, value: 1) } } } #endif #endif
ba5d3b99a69373d7235b6216ad3456b8
41.800676
155
0.611019
false
false
false
false
daehn/Counted-Set
refs/heads/develop
CountedSet/CountedSet.swift
mit
1
// // The MIT License (MIT) // Copyright 2016 Silvan Dähn // // 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. // public struct CountedSet<Element: Hashable>: ExpressibleByArrayLiteral { public typealias ElementWithCount = (element: Element, count: Int) public typealias Index = SetIndex<Element> fileprivate var backing = Set<Element>() fileprivate var countByElement = [Element: Int]() public mutating func insert(_ member: Element) { backing.insert(member) let count = countByElement[member] ?? 0 countByElement[member] = count + 1 } @discardableResult public mutating func remove(_ member: Element) -> Element? { guard var count = countByElement[member], count > 0 else { return nil } count -= 1 countByElement[member] = Swift.max(count, 0) if count <= 0 { backing.remove(member) } return member } public func count(for member: Element) -> Int { return countByElement[member] ?? 0 } public init(arrayLiteral elements: Element...) { elements.forEach { insert($0) } } public subscript(member: Element) -> Int { return count(for: member) } @discardableResult public mutating func setCount(_ count: Int, for element: Element) -> Bool { precondition(count >= 0, "Count has to be positive") guard count != countByElement[element] else { return false } if count > 0 && !contains(element) { backing.insert(element) } countByElement[element] = count if count <= 0 { backing.remove(element) } return true } public func mostFrequent() -> ElementWithCount? { guard !backing.isEmpty else { return nil } return reduce((backing[backing.startIndex], 0)) { max, current in let currentCount = count(for: current) guard currentCount > max.1 else { return max } return (current, currentCount) } } } // MARK: - Collection extension CountedSet: Collection { public var startIndex: SetIndex<Element> { return backing.startIndex } public var endIndex: SetIndex<Element> { return backing.endIndex } public func index(after i: SetIndex<Element>) -> SetIndex<Element> { return backing.index(after: i) } public subscript(position: SetIndex<Element>) -> Element { return backing[position] } public func makeIterator() -> SetIterator<Element> { return backing.makeIterator() } } // MARK: - Hashable extension CountedSet: Hashable { public var hashValue: Int { return backing.hashValue ^ Int(countByElement.values.reduce(0, ^)) } } // MARK: - Equatable Operator public func ==<Element>(lhs: CountedSet<Element>, rhs: CountedSet<Element>) -> Bool { return lhs.backing == rhs.backing && lhs.countByElement == rhs.countByElement } // MARK: - CustomStringConvertible extension CountedSet: CustomStringConvertible { public var description: String { return backing.reduce("<CountedSet>:\n") { sum, element in sum + "\t- \(element): \(count(for: element))\n" } } }
42459b3a96fc09093c59e1a81e9cf9a3
30.58209
98
0.663043
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/MusicComposition.swift
mit
1
import Foundation /// A musical composition. public class MusicComposition: CreativeWork { /// The person or organization who wrote a composition, or who is the /// composer of a work performed at some event. public var composer: OrganizationOrPerson? /// The date and place the work was first performed. public var firstPerformance: Event? /// Smaller compositions included in this work (e.g. a movement in a symphony). public var includedComposition: MusicComposition? /// The International Standard Musical Work Code for the composition. public var iswcCode: String? /// The person who wrote the words. public var lyricist: Person? /// The words in the song. public var lyrics: CreativeWork? /// An arrangement derived from the composition. public var musicArrangement: MusicComposition? /// The type of composition (e.g. overture, sonata, symphony, etc.). public var musicCompositionForm: String? /// The key, mode, or scale this composition uses. public var musicalKey: String? /// An audio recording of the work. /// - Inverse property: recordingOf. public var recordedAs: MusicRecording? internal enum MusicCompositionCodingKeys: String, CodingKey { case composer case firstPerformance case includedComposition case iswcCode case lyricist case lyrics case musicArrangement case musicCompositionForm case musicalKey case recordedAs } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: MusicCompositionCodingKeys.self) composer = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .composer) firstPerformance = try container.decodeIfPresent(Event.self, forKey: .firstPerformance) includedComposition = try container.decodeIfPresent(MusicComposition.self, forKey: .includedComposition) iswcCode = try container.decodeIfPresent(String.self, forKey: .iswcCode) lyricist = try container.decodeIfPresent(Person.self, forKey: .lyricist) lyrics = try container.decodeIfPresent(CreativeWork.self, forKey: .lyrics) musicArrangement = try container.decodeIfPresent(MusicComposition.self, forKey: .musicArrangement) musicCompositionForm = try container.decodeIfPresent(String.self, forKey: .musicCompositionForm) musicalKey = try container.decodeIfPresent(String.self, forKey: .musicalKey) recordedAs = try container.decodeIfPresent(MusicRecording.self, forKey: .recordedAs) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: MusicCompositionCodingKeys.self) try container.encodeIfPresent(composer, forKey: .composer) try container.encodeIfPresent(firstPerformance, forKey: .firstPerformance) try container.encodeIfPresent(includedComposition, forKey: .includedComposition) try container.encodeIfPresent(iswcCode, forKey: .iswcCode) try container.encodeIfPresent(lyricist, forKey: .lyricist) try container.encodeIfPresent(lyrics, forKey: .lyrics) try container.encodeIfPresent(musicArrangement, forKey: .musicArrangement) try container.encodeIfPresent(musicCompositionForm, forKey: .musicCompositionForm) try container.encodeIfPresent(musicalKey, forKey: .musicalKey) try container.encodeIfPresent(recordedAs, forKey: .recordedAs) try super.encode(to: encoder) } }
dd5d441aab44f7144da56a327676550b
41.625
112
0.705678
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/Service/Service+Login.swift
mit
1
// // PcHTTPService+Login.swift // Train12306 // // Created by fancymax on 15/11/7. // Copyright © 2015年 fancy. All rights reserved. // import JavaScriptCore import Foundation import Alamofire import PromiseKit import SwiftyJSON extension Service { // MARK: - Request Flow func preLoginFlow(success:@escaping (NSImage)->Void,failure:@escaping (NSError)->Void){ let cookie1 = HTTPCookie(properties: [.name:"RAIL_DEVICEID",.domain:"kyfw.12306.cn",.value:"CyeQGv5X_Y9BsIIkxXGf8s_wPmVs2yH4idlQo3d4KxgeY10nAnXWcm72qwxLLd_xqQm-v8UaFAVL7elDx_KFZw1FN3MkwJcbQAGtPIFEWfWPsdsOr5_jgjV-HSn7t-2u2fZgGrTOSCpfoYMOF41I1qWmNkGkObIX",.path:"/"]) let cookie2 = HTTPCookie(properties: [.name:"RAIL_EXPIRATION",.domain:"kyfw.12306.cn",.value:"1516426090658",.path:"/"]) Service.Manager.session.configuration.httpCookieStorage?.setCookie(cookie1!) Service.Manager.session.configuration.httpCookieStorage?.setCookie(cookie2!) loginInit().then{(dynamicJs) -> Promise<Void> in return self.requestDynamicJs(dynamicJs, referHeader: ["refer": "https://kyfw.12306.cn/otn/login/init"]) }.then{_ -> Promise<NSImage> in return self.getPassCodeNewForLogin() }.then{ image in success(image) }.catch { error in failure(error as NSError) } } func loginFlow(user:String,passWord:String,randCodeStr:String,success:@escaping ()->Void,failure:@escaping (NSError)->Void){ after(interval: 2).then{ self.checkRandCodeForLogin(randCodeStr) }.then{() -> Promise<Void> in return self.loginUserWith(user, passWord: passWord, randCodeStr: randCodeStr) }.then{ () -> Promise<(Bool,String)> in return self.checkUAM() }.then{ (hasLogin,tk) -> Promise<Bool> in return self.uampassport(tk: tk) }.then{ (_) -> Promise<Void> in return self.initMy12306() }.then{ () -> Promise<Void> in return self.getPassengerDTOs(isSubmit: false) }.then{_ in success() }.catch { error in failure(error as NSError) } } // MARK: - Chainable Request func loginInit()->Promise<String>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/login/init" let headers = ["refer": "https://kyfw.12306.cn/otn/leftTicket/init"] Service.Manager.request(url, headers:headers).responseString(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let content): var dynamicJs = "" if let matches = Regex("src=\"/otn/dynamicJs/([^\"]+)\"").getMatches(content){ dynamicJs = matches[0][0] } else{ logger.error("fail to get dynamicJs:\(content)") } self.getConfigFromInitContent(content) fulfill(dynamicJs) }}) } } func loginOut() { let url = "https://kyfw.12306.cn/otn/login/loginOut" Service.Manager.request(url).responseString(completionHandler:{response in }) } func getPassCodeNewForLogin()->Promise<NSImage>{ return Promise{ fulfill, reject in let param = CaptchaImageParam().ToGetParams() let url = "\(passport_captcha)?\(param)" let headers = ["refer": "https://kyfw.12306.cn/otn/login/init"] Service.Manager.request(url, headers:headers).responseData{ response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let image = NSImage(data: data){ fulfill(image) } else{ let error = ServiceError.errorWithCode(.getRandCodeFailed) reject(error) } }} } } func checkUAM() ->Promise<(Bool,String)> { return Promise{ fulfill, reject in let url = passport_authuam //TODO //$.jc_getcookie("tk"); let params = ["appid":passport_appId] var headers:[String:String] = [:] headers[referKey] = referValueForLoginInit Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let result_code = JSON(data)["result_code"].int { var hasLogin = false var tk = "" if result_code == 0 { if let apptk = JSON(data)["apptk"].string { tk = apptk } if let newapptk = JSON(data)["newapptk"].string { tk = newapptk } hasLogin = true } else { hasLogin = false } fulfill((hasLogin,tk)) } else{ let error = ServiceError.errorWithCode(.loginFailed, failureReason: "checkUAM") reject(error) } }}) } } func uampassport(tk:String) ->Promise<Bool> { return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/" + passport_authclient //TODO //$.jc_getcookie("tk"); let params = ["tk":tk] var headers:[String:String] = [:] headers[referKey] = referValueForLoginInit Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let result_code = JSON(data)["result_code"].int { var hasLogin = false if result_code == 0 { hasLogin = true if let userName = JSON(data)["username"].string { MainModel.userName = userName } } else { hasLogin = false } fulfill(hasLogin) } else{ let error = ServiceError.errorWithCode(.loginFailed, failureReason: "uampassport") reject(error) } }}) } } func checkRandCodeForLogin(_ randCodeStr:String)->Promise<Void>{ return Promise{ fulfill, reject in let url = passport_captcha_check let params = ["answer":randCodeStr,"login_site":"E","rand":"sjrand"] let headers = ["Referer": "https://kyfw.12306.cn/otn/login/init", "X-Requested-With":"XMLHttpRequest"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let msg = JSON(data)["result_code"].string , msg == "4"{ fulfill() } else{ let error = ServiceError.errorWithCode(.checkRandCodeFailed) reject(error) } }}) } } func loginUserWith(_ user:String, passWord:String, randCodeStr:String)->Promise<Void>{ return Promise{ fulfill, reject in let url = passport_login let params = ["username":user,"password":passWord,"appid":passport_appId] let headers = ["Referer": "https://kyfw.12306.cn/otn/login/init", "Origin":"https://kyfw.12306.cn", "X-Requested-With":"XMLHttpRequest"] Service.Manager.request(url, method:.post, parameters: params,encoding: URLEncoding.default, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let result_code = JSON(data)["result_code"].int ,result_code == 0{ fulfill() } else{ let error:NSError if let errorStr = JSON(data)["result_message"].string{ error = ServiceError.errorWithCode(.loginUserFailed, failureReason: errorStr) } else{ error = ServiceError.errorWithCode(.loginUserFailed) } reject(error) } }}) } } func initMy12306()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/index/initMy12306" let headers = ["refer": "https://kyfw.12306.cn/otn/login/init"] Service.Manager.request(url, headers:headers).responseString(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let matches = Regex("(var user_name='[^']+')").getMatches(data){ //for javascript let context = JSContext()! context.evaluateScript(matches[0][0]) MainModel.realName = context.objectForKeyedSubscript("user_name").toString() } else{ logger.error("can't get user_name") } fulfill() }}) } } }
11914e9105bda21809afd2e57946507d
40.726236
273
0.487334
false
false
false
false
swift102016team5/mefocus
refs/heads/master
MeFocus/MeFocus/Session.swift
mit
1
// // Session.swift // MeFocus // // Created by Hao on 11/20/16. // Copyright © 2016 Group5. All rights reserved. // import Foundation import CoreData import AVFoundation import UIKit import SwiftWebSocket extension Session { func isExceedMaxiumPause() -> Bool { return SessionsManager.isExceedMaxiumPause(session:self) } func isOver() -> Bool { let now = Int64(NSDate().timeIntervalSince1970) if start_at + duration > now { return false } return true } func finish(){ end_at = Int64(NSDate().timeIntervalSince1970) is_success = isOver() && !isExceedMaxiumPause() SessionsManager.reset() Storage.shared.save() } } enum SessionsManagerError:Error { case Unfinished case MaximumPauseDurationMustGreaterThanZero } class SessionsManager:NSObject { // Start new session , doing implicit checking if there is any unfinished session // If satisfied , it will start new session and persisted to storage // Reset manager pauses count static func start( goal:String, duration:Int, maximPauseDuration:Int ) throws -> Session { if maximPauseDuration == 0 { throw SessionsManagerError.MaximumPauseDurationMustGreaterThanZero } if SessionsManager.unfinished == nil { SessionsManager.reset() let session = Session(data:[ "goal":goal, "duration":duration, "maximum_pause_duration":maximPauseDuration, "start_at":Int64(NSDate().timeIntervalSince1970) ]) Storage.shared.save() return session } throw SessionsManagerError.Unfinished } static var pauses:Int64 = 0 static func reset(){ SessionsManager.pauses = 0 } static func notify(){ } static func alert() -> AVAudioPlayer?{ if let asset = NSDataAsset(name:"cohangxom") { var player:AVAudioPlayer do { try player = AVAudioPlayer(data: asset.data, fileTypeHint:"mp3") player.volume = 1 return player } catch { print("Cannot play notification \(error)") } } return nil } static func isExceedMaxiumPause(session:Session) -> Bool { return SessionsManager.pauses > session.maximum_pause_duration } static func all() -> [Session]{ let request = Storage.shared.request(entityName: "Session") let sessions = Storage.shared.fetch(request: request) as! [Session] return sessions.reversed() } // Get unfinished session , usefull for navigation static var unfinished:Session? { get { let request = Storage.shared.request(entityName: "Session") request.fetchLimit = 1 request.predicate = NSPredicate(format: "end_at = 0") let sessions = Storage.shared.fetch(request: request) as! [Session] if sessions.count == 1 { if let unfinish = sessions.first { if unfinish.isExceedMaxiumPause() || unfinish.isOver() { unfinish.finish() return nil } return unfinish } } return nil } } }
17cef56894a5b4897489255ae0e3de01
25.304348
86
0.546832
false
false
false
false
kazedayo/GaldenApp
refs/heads/master
GaldenApp/View Controllers/PageSelectTableViewController.swift
mit
1
// // PageSelectTableViewController.swift // GaldenApp // // Created by Kin Wa Lam on 16/10/2017. // Copyright © 2017年 1080@galden. All rights reserved. // import UIKit class PageSelectTableViewController: UITableViewController { var pageCount: Double = 0.0 var pageSelected: Int = 0 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 self.tableView.tableFooterView = UIView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return Int(pageCount) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PageSelectTableViewCell", for: indexPath) as! PageSelectTableViewCell // Configure the cell... cell.pageNo.text = "第" + String(indexPath.row + 1) + "頁" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { pageSelected = (indexPath.row + 1) performSegue(withIdentifier: "unwindToPage", sender: self) } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation /* // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
fc96becf7b00780d9fb17eaa435f1782
33.247619
136
0.670467
false
false
false
false
mzp/OctoEye
refs/heads/master
Tests/Unit/GithubAPI/FetchBlobSpec.swift
mit
1
// // FetchTextSpec.swift // Tests // // Created by mzp on 2017/07/07. // Copyright © 2017 mzp. All rights reserved. // import JetToTheFuture import Nimble import Quick import Result internal class FetchBlobSpec: QuickSpec { override func spec() { let github = GithubClient( token: "-", httpRequest: MockHttpRequest(response: fixture(name: "content", ofType: "txt"))) let data = forcedFuture { _ in FetchBlob(github: github).call(owner: "octocat", name: "example", oid: "-") }.value // swiftlint:disable:next force_unwrapping let text = String(data: data!, encoding: String.Encoding.utf8) describe("text") { it("returns file content") { expect(text) == "Content of the blob\n" } } } }
e8dd0f14e7c091c751a5058dc99d3f21
25.83871
92
0.58774
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureOnboarding/Sources/FeatureOnboardingUI/OnboardingRouter.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import Combine import CombineSchedulers import DIKit import Errors import SwiftUI import ToolKit import UIKit public protocol KYCRouterAPI { func presentEmailVerification(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> func presentKYCUpgradePrompt(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> } public protocol TransactionsRouterAPI { func presentBuyFlow(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> func navigateToBuyCryptoFlow(from presenter: UIViewController) func navigateToReceiveCryptoFlow(from presenter: UIViewController) } public final class OnboardingRouter: OnboardingRouterAPI { // MARK: - Properties let app: AppProtocol let kycRouter: KYCRouterAPI let transactionsRouter: TransactionsRouterAPI let featureFlagsService: FeatureFlagsServiceAPI let mainQueue: AnySchedulerOf<DispatchQueue> // MARK: - Init public init( app: AppProtocol = resolve(), kycRouter: KYCRouterAPI = resolve(), transactionsRouter: TransactionsRouterAPI = resolve(), featureFlagsService: FeatureFlagsServiceAPI = resolve(), mainQueue: AnySchedulerOf<DispatchQueue> = .main ) { self.app = app self.kycRouter = kycRouter self.transactionsRouter = transactionsRouter self.featureFlagsService = featureFlagsService self.mainQueue = mainQueue } // MARK: - Onboarding Routing public func presentPostSignUpOnboarding(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { // Step 1: present email verification presentEmailVerification(from: presenter) .flatMap { [weak self] result -> AnyPublisher<OnboardingResult, Never> in guard let self = self else { return .just(.abandoned) } let app = self.app if app.remoteConfiguration.yes(if: blockchain.ux.onboarding.promotion.cowboys.is.enabled), app.state.yes(if: blockchain.user.is.cowboy.fan) { if result == .completed { return Task<OnboardingResult, Error>.Publisher(priority: .userInitiated) { try await self.presentCowboyPromotion(from: presenter) } .replaceError(with: .abandoned) .eraseToAnyPublisher() } else { return .just(.abandoned) } } return self.presentUITour(from: presenter) } .eraseToAnyPublisher() } public func presentPostSignInOnboarding(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { kycRouter.presentKYCUpgradePrompt(from: presenter) } public func presentRequiredCryptoBalanceView( from presenter: UIViewController ) -> AnyPublisher<OnboardingResult, Never> { let subject = PassthroughSubject<OnboardingResult, Never>() let view = CryptoBalanceRequiredView( store: .init( initialState: (), reducer: CryptoBalanceRequired.reducer, environment: CryptoBalanceRequired.Environment( close: { presenter.dismiss(animated: true) { subject.send(.abandoned) subject.send(completion: .finished) } }, presentBuyFlow: { [transactionsRouter] in presenter.dismiss(animated: true) { transactionsRouter.navigateToBuyCryptoFlow(from: presenter) } }, presentRequestCryptoFlow: { [transactionsRouter] in presenter.dismiss(animated: true) { transactionsRouter.navigateToReceiveCryptoFlow(from: presenter) } } ) ) ) presenter.present(view) return subject.eraseToAnyPublisher() } // MARK: - Helper Methods private func presentUITour(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { let subject = PassthroughSubject<OnboardingResult, Never>() let view = UITourView( close: { subject.send(.abandoned) subject.send(completion: .finished) }, completion: { subject.send(.completed) subject.send(completion: .finished) } ) let hostingController = UIHostingController(rootView: view) hostingController.modalTransitionStyle = .crossDissolve hostingController.modalPresentationStyle = .overFullScreen presenter.present(hostingController, animated: true, completion: nil) return subject .flatMap { [transactionsRouter] result -> AnyPublisher<OnboardingResult, Never> in guard case .completed = result else { return .just(.abandoned) } return Deferred { Future { completion in presenter.dismiss(animated: true) { completion(.success(())) } } } .flatMap { transactionsRouter.presentBuyFlow(from: presenter) } .eraseToAnyPublisher() } .eraseToAnyPublisher() } private func presentEmailVerification(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { featureFlagsService.isEnabled(.showEmailVerificationInOnboarding) .receive(on: mainQueue) .flatMap { [kycRouter] shouldShowEmailVerification -> AnyPublisher<OnboardingResult, Never> in guard shouldShowEmailVerification else { return .just(.completed) } return kycRouter.presentEmailVerification(from: presenter) } .eraseToAnyPublisher() } private func presentCowboyPromotion(from presenter: UIViewController) async throws -> OnboardingResult { if try app.state.get(blockchain.user.account.tier) == blockchain.user.account.tier.none[] { guard case .completed = await present( promotion: blockchain.ux.onboarding.promotion.cowboys.welcome, from: presenter ) else { return .abandoned } let kyc = try await app .on(blockchain.ux.kyc.event.did.finish, blockchain.ux.kyc.event.did.stop, blockchain.ux.kyc.event.did.cancel) .stream() .next() guard kyc.origin ~= blockchain.ux.kyc.event.did.finish else { return .abandoned } try await Task.sleep(nanoseconds: NSEC_PER_SEC / 2) guard case .completed = await present( promotion: blockchain.ux.onboarding.promotion.cowboys.raffle, from: presenter ) else { return .abandoned } let transaction = try await app .on(blockchain.ux.transaction["buy"].event.did.finish, blockchain.ux.transaction["buy"].event.execution.status.completed) .stream() .next() guard transaction.origin ~= blockchain.ux.transaction.event.execution.status.completed else { return .abandoned } try await Task.sleep(nanoseconds: NSEC_PER_SEC / 2) } return await present( promotion: blockchain.ux.onboarding.promotion.cowboys.verify.identity, from: presenter ) } @MainActor private func present( promotion: L & I_blockchain_ux_onboarding_type_promotion, from presenter: UIViewController ) async -> OnboardingResult { do { let story = promotion.story let view = try await PromotionView(promotion, ux: app.get(story)) .app(app) await MainActor.run { presenter.present(UIHostingController(rootView: view), animated: true) } let event = try await app.on(story.action.then.launch.url, story.action.then.close).stream().next() switch event.tag { case story.action.then.launch.url: return .completed default: return .abandoned } } catch { return .abandoned } } }
ca192e8cc28f4a70d254423a13a61a40
38.19469
137
0.588959
false
false
false
false
antonio081014/LeetCode-CodeBase
refs/heads/main
Swift/min-cost-to-connect-all-points.swift
mit
1
// // Heap.swift // // Created by Yi Ding on 9/30/19. // Copyright © 2019 Yi Ding. All rights reserved. // import Foundation public struct Heap<T> { /** The array that stores the heap's nodes. */ private(set) var nodes: [T] /** * Determines how to compare two nodes in the heap. * Use '>' for a max-heap or '<' for a min-heap, * or provide a comparing method if the heap is made * of custom elements, for example tuples. */ fileprivate let sortingComparator: (T, T) -> Bool /** * Creates an empty heap. * The sort function determines whether this is a min-heap or max-heap. * For comparable data types, > makes a max-heap, < makes a min-heap. */ public init(sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator } /** * Creates a heap from an array. The order of the array does not matter; * the elements are inserted into the heap in the order determined by the * sort function. For comparable data types, '>' makes a max-heap, * '<' makes a min-heap. */ public init(array: [T], sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator self.buildHeap(from: array) } /** * Configures the max-heap or min-heap from an array, in a bottom-up manner. * Performance: This runs pretty much in O(n). */ private mutating func buildHeap(from array: [T]) { // self.insert(array) self.nodes = array for index in stride(from: array.count / 2 - 1, through: 0, by: -1) { self.shiftDown(from: index) } } } // MARK: - Peek, Insert, Remove, Replace extension Heap { public var isEmpty: Bool { return self.nodes.isEmpty } public var count: Int { return self.nodes.count } /** * Returns the maximum value in the heap (for a max-heap) or the minimum * value (for a min-heap). * Performance: O(1) */ public func peek() -> T? { return self.nodes.first } /** * Adds a new value to the heap. This reorders the heap so that the max-heap * or min-heap property still holds. * Performance: O(log n). */ public mutating func insert(element: T) { self.nodes.append(element) self.shiftUp(from: self.nodes.count - 1) } /** * Adds a sequence of values to the heap. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n). */ public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T { for value in sequence { insert(element: value) } } /** * Allows you to change an element. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n) */ public mutating func replace(at index: Int, value: T) { guard index < nodes.count else { return } remove(at: index) insert(element: value) } /** * Removes the root node from the heap. For a max-heap, this is the maximum * value; for a min-heap it is the minimum value. * Performance: O(log n). */ @discardableResult public mutating func remove() -> T? { guard self.nodes.count > 0 else { return nil } if self.nodes.count == 1 { return self.nodes.removeLast() } else { let value = self.nodes.first self.nodes[0] = self.nodes.removeLast() self.shiftDown(from: 0) return value } } /** * Removes an arbitrary node from the heap. * Note that you need to know the node's index. * Performance: O(log n) */ @discardableResult public mutating func remove(at index: Int) -> T? { guard index < self.count else { return nil } self.nodes.swapAt(index, self.nodes.count - 1) let value = self.nodes.removeLast() self.shiftDown(from: index) self.shiftUp(from: index) return value } } // MARK: - Index extension Heap { /** * Returns the index of the parent of the element at index i. * The element at index 0 is the root of the tree and has no parent. * Performance: O(1) */ func parentIndex(ofIndex i: Int) -> Int { return (i - 1) / 2 } /** * Returns the index of the left child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no left child. * Performance: O(1) */ func leftChildIndex(ofIndex index: Int) -> Int { return index * 2 + 1 } /** * Returns the index of the right child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no right child. * Performance: O(1) */ func rightChildIndex(ofIndex index: Int) -> Int { return index * 2 + 2 } } // MARK: - Shift Up / Down extension Heap { /** * Takes a child node and looks at its parents; if a parent is not larger * (max-heap) or not smaller (min-heap) than the child, we exchange them. * Performance: O(log n) */ mutating func shiftUp(from index: Int) { var childIndex = index var parentIndex = self.parentIndex(ofIndex: childIndex) while parentIndex < childIndex, !self.sortingComparator(self.nodes[parentIndex], self.nodes[childIndex]) { self.nodes.swapAt(childIndex, parentIndex) childIndex = parentIndex parentIndex = self.parentIndex(ofIndex: childIndex) } } /** * Looks at a parent node and makes sure it is still larger (max-heap) or * smaller (min-heap) than its childeren. * Performance: O(log n) */ mutating func shiftDown(from index: Int) { let parentIndex = index let leftChildIndex = self.leftChildIndex(ofIndex: parentIndex) let rightChildIndex = self.rightChildIndex(ofIndex: parentIndex) var subIndex = parentIndex if leftChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[leftChildIndex]) == false { subIndex = leftChildIndex } if rightChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[rightChildIndex]) == false { subIndex = rightChildIndex } if parentIndex == subIndex { return } self.nodes.swapAt(subIndex, index) self.shiftDown(from: subIndex) } } extension Heap where T: Equatable { /** * Get the index of a node in the heap. * Performance: O(n). */ public func index(of node: T) -> Int? { return self.nodes.firstIndex(of: node) } /** * Removes the first occurrence of a node from the heap. * Performance: O(n + log n) => O(n). */ @discardableResult public mutating func remove(node: T) -> T? { if let index = self.index(of: node) { return self.remove(at: index) } return nil } } class Solution { struct Edge: Comparable { let from: Int let to: Int let distance: Int // init(from: Int, to: Int, distance: Int) { // self.from = min(from, to) // self.to = max(from, to) // self.distance = distance // } static func < (lhs: Solution.Edge, rhs: Solution.Edge) -> Bool { return lhs.distance < rhs.distance } } func minCostConnectPoints(_ points: [[Int]]) -> Int { let n = points.count var notVisited = Set(0 ..< n) var currentIndex = 0 var minHeap = Heap<Edge>(sortingComparator: { $0 < $1 }) var result = 0 while notVisited.isEmpty == false { // print(currentIndex) notVisited.remove(currentIndex) for p in 0 ..< n { if notVisited.contains(p) { minHeap.insert(element: Edge(from: currentIndex, to: p, distance: self.dist(points[currentIndex], points[p]))) } } while let node = minHeap.peek(), notVisited.contains(node.to) == false { minHeap.remove() } if let node = minHeap.remove() { result += node.distance currentIndex = node.to } else { return result } } return result } private func dist(_ a: [Int], _ b: [Int]) -> Int { return abs(a[0] - b[0]) + abs(a[1] - b[1]) } }
4b65e413fb36cc38ad3bf8c02f3cf2cf
29.387755
131
0.5666
false
false
false
false
lyimin/iOS-Animation-Demo
refs/heads/master
iOS-Animation学习笔记/iOS-Animation学习笔记/ViewController.swift
mit
1
// // ViewController.swift // iOS-Animation学习笔记 // // Created by 梁亦明 on 15/12/22. // Copyright © 2015年 xiaoming. All rights reserved. // import UIKit class ViewController: UITableViewController { var titleArray : Array<String> = ["雪花粒子Demo","弹簧效果Demo","Twitter启动Demo","登陆动画Demo","引导页卡片Demo","扩大背景转场","SlidingPanels", "简书转场动画","进度条动画","音符加载动画"] var nameArray : Array<String> = Array() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.tableView.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.titleArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cellId") } cell?.textLabel?.text = titleArray[indexPath.row] return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var nextController : UIViewController! switch indexPath.row { case 0 : // 雪花demo nextController = EmitterViewController() case 1: // 弹簧Demo nextController = SpringAnimationViewController() case 2: // Twitter启动Demo nextController = SplashAnimiationController() case 3: // 登陆动画Demo nextController = LoginViewController() case 4: // 引导页卡片Demo nextController = TipFirstViewController() case 5: // 扩大背景转场 nextController = PingFirstController() case 6: // SlidingPanels nextController = RoomsViewController() nextController.view.backgroundColor = UIColor.orange nextController.title = titleArray[indexPath.row] self.present(nextController, animated: true, completion: nil) return case 7: // 简书转场动画 nextController = JSFirstViewController() case 8: // 进度条动画 nextController = ProgressAnimationController() case 9: // 音符加载 nextController = MusicIndicatorViewController() default: break; } nextController.view.backgroundColor = UIColor.orange nextController.title = titleArray[indexPath.row] self.navigationController?.pushViewController(nextController, animated: true) } }
e7f52bf192502459f5b87d0c24890dbe
34.308642
151
0.584965
false
false
false
false
evgenyneu/walk-to-circle-ios
refs/heads/master
walk to circle/Utils/iiDate.swift
mit
1
import Foundation public class iiDate { public class func toStringAsYearMonthDay(date: NSDate) -> String { let components = NSCalendar.currentCalendar().components( [NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date) return "\(components.year).\(components.month).\(components.day)" } public class func fromYearMonthDay(year: Int, month: Int, day: Int) -> NSDate? { let dateComponents = NSDateComponents() dateComponents.year = year dateComponents.month = month dateComponents.day = day return NSCalendar.currentCalendar().dateFromComponents(dateComponents) } }
c3aaf7b7131e7c55e355ac00820fd6bb
29.666667
82
0.726708
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Models/SofaWrappers/SofaPaymentRequest.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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 final class SofaPaymentRequest: SofaWrapper { override var type: SofaType { return .paymentRequest } lazy var body: String = { self.json["body"] as? String ?? "" }() var fiatValueString: String { guard let string = self.json["fiatValueString"] as? String else { return "" } return string } var value: NSDecimalNumber { guard let hexValue = self.json["value"] as? String else { return NSDecimalNumber.zero } return NSDecimalNumber(hexadecimalString: hexValue) } var destinationAddress: String { return json["destinationAddress"] as? String ?? "" } convenience init(valueInWei: NSDecimalNumber) { let request: [String: Any] = [ "value": valueInWei.toHexString, "destinationAddress": Cereal.shared.paymentAddress ] self.init(content: request) } override init(content: String) { guard let sofaContent = SofaWrapper.addFiatStringIfNecessary(to: content, for: SofaType.paymentRequest) else { fatalError("Could not add fiat string if necessary") } super.init(content: sofaContent) } override init(content: [String: Any]) { guard let sofaContent = SofaWrapper.addFiatStringIfNecessary(to: content, for: SofaType.paymentRequest) else { fatalError("Could not add fiat string if necessary") } super.init(content: sofaContent) } }
7ef2963cf6f42da4d7edb41c171d2902
32.46875
173
0.68394
false
false
false
false
zoeyzhong520/InformationTechnology
refs/heads/master
InformationTechnology/InformationTechnology/Classes/GuideViewController.swift
mit
1
// // GuideViewController.swift // InformationTechnology // // Created by qianfeng on 16/11/14. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class GuideViewController: UIViewController { //创建分页控件 var pageCtrl:UIPageControl? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() //创建界面 configView() } //创建界面 func configView() { //添加滚动视图 let scrollView = UIScrollView(frame: self.view.bounds) scrollView.delegate = self scrollView.pagingEnabled = true view.addSubview(scrollView) //循环添加图片 let imgArray = ["IMG_0169_New.jpg","IMG_0172_New.jpg","IMG_0170.jpg"] for i in 0..<imgArray.count { //背景图片 let frame:CGRect = CGRectMake(kScreenWidth*CGFloat(i), 0, kScreenWidth, kScreenHeight) let imageView = UIImageView(frame: frame) imageView.image = UIImage(named: "guideView_bg@2x") scrollView.addSubview(imageView) //图片 let tmpImgView = UIImageView(frame: imageView.bounds) tmpImgView.image = UIImage(named: imgArray[i]) imageView.addSubview(tmpImgView) if i == imgArray.count-1 { imageView.userInteractionEnabled = true //按钮 let btn = UIButton(frame: CGRect(x: 110, y: kScreenHeight-120, width: kScreenWidth-2*110, height: 40)) btn.setTitle("进入应用", forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Normal) btn.layer.masksToBounds = true btn.layer.cornerRadius = 20 btn.backgroundColor = UIColor.whiteColor() btn.addTarget(self, action: #selector(clickBtn), forControlEvents: .TouchUpInside) imageView.addSubview(btn) } //分页控件 pageCtrl = UIPageControl(frame: CGRect(x: 50, y: kScreenHeight-60, width: kScreenWidth-2*50, height: 30)) pageCtrl?.numberOfPages = imgArray.count pageCtrl?.currentPageIndicatorTintColor = UIColor.whiteColor() pageCtrl?.pageIndicatorTintColor = UIColor.lightGrayColor() view.addSubview(pageCtrl!) } scrollView.contentSize = CGSizeMake(kScreenWidth*CGFloat(imgArray.count), 0) } func clickBtn() { self.view.window?.rootViewController = CreateTabBarController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } //MARK: UIScrollView代理方法 extension GuideViewController:UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = scrollView.contentOffset.x/scrollView.bounds.size.width pageCtrl?.currentPage = Int(index) } }
50b43de711fa5aab8a93d5d2ed0a693a
28.016949
118
0.611565
false
false
false
false
troystribling/BlueCap
refs/heads/master
BlueCapKit/Injectables.swift
mit
1
// // Injectables.swift // BlueCapKit // // Created by Troy Stribling on 4/20/16. // Copyright © 2016 Troy Stribling. All rights reserved. // import Foundation import CoreBluetooth // MARK: - ManagerState - public enum ManagerState: CustomStringConvertible { case unauthorized, unknown, unsupported, resetting, poweredOff, poweredOn public var description: String { switch self { case .unauthorized: return "unauthorized" case .unknown: return "unknown" case .unsupported: return "unsupported" case .resetting: return "resetting" case .poweredOff: return "poweredOff" case .poweredOn: return "poweredOn" } } } // MARK: - CBCentralManagerInjectable - protocol CBCentralManagerInjectable: class { var managerState : ManagerState { get } var delegate: CBCentralManagerDelegate? { get set } func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String : Any]?) func stopScan() func connect(_ peripheral: CBPeripheralInjectable, options: [String : Any]?) func cancelPeripheralConnection(_ peripheral: CBPeripheralInjectable) func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [CBPeripheralInjectable] func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [CBPeripheralInjectable] } extension CBCentralManager : CBCentralManagerInjectable { var managerState: ManagerState { switch state { case .unauthorized: return .unauthorized case .unknown: return .unknown case .unsupported: return .unsupported case .resetting: return .resetting case .poweredOff: return .poweredOff case .poweredOn: return .poweredOn @unknown default: fatalError() } } func connect(_ peripheral: CBPeripheralInjectable, options: [String : Any]?) { self.connect(peripheral as! CBPeripheral, options: options) } func cancelPeripheralConnection(_ peripheral: CBPeripheralInjectable) { self.cancelPeripheralConnection(peripheral as! CBPeripheral) } func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [CBPeripheralInjectable] { let peripherals = self.retrieveConnectedPeripherals(withServices: serviceUUIDs) as [CBPeripheral] return peripherals.map { $0 as CBPeripheralInjectable } } func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [CBPeripheralInjectable] { let peripherals = self.retrievePeripherals(withIdentifiers: identifiers) as [CBPeripheral] return peripherals.map { $0 as CBPeripheralInjectable } } } // MARK: - CBPeripheralInjectable - protocol CBPeripheralInjectable: class { var name: String? { get } var state: CBPeripheralState { get } var identifier: UUID { get } var delegate: CBPeripheralDelegate? { get set } func readRSSI() func discoverServices(_ services: [CBUUID]?) func discoverCharacteristics(_ characteristics: [CBUUID]?, forService service: CBServiceInjectable) func setNotifyValue(_ enabled:Bool, forCharacteristic characteristic: CBCharacteristicInjectable) func readValueForCharacteristic(_ characteristic: CBCharacteristicInjectable) func writeValue(_ data:Data, forCharacteristic characteristic: CBCharacteristicInjectable, type: CBCharacteristicWriteType) func getServices() -> [CBServiceInjectable]? } extension CBPeripheral: CBPeripheralInjectable { func discoverCharacteristics(_ characteristics:[CBUUID]?, forService service: CBServiceInjectable) { self.discoverCharacteristics(characteristics, for: service as! CBService) } func setNotifyValue(_ enabled: Bool, forCharacteristic characteristic: CBCharacteristicInjectable) { self.setNotifyValue(enabled, for: characteristic as! CBCharacteristic) } func readValueForCharacteristic(_ characteristic: CBCharacteristicInjectable) { self.readValue(for: characteristic as! CBCharacteristic) } func writeValue(_ data: Data, forCharacteristic characteristic: CBCharacteristicInjectable, type: CBCharacteristicWriteType) { self.writeValue(data, for: characteristic as! CBCharacteristic, type: type) } func getServices() -> [CBServiceInjectable]? { guard let services = services else { return nil } return services.map{ $0 as CBServiceInjectable } } } // MARK: - CBServiceInjectable - protocol CBServiceInjectable: class { var uuid: CBUUID { get } func getCharacteristics() -> [CBCharacteristicInjectable]? } extension CBService : CBServiceInjectable { func getCharacteristics() -> [CBCharacteristicInjectable]? { guard let characteristics = self.characteristics else { return nil } return characteristics.map{ $0 as CBCharacteristicInjectable } } } // MARK: - CBCharacteristicInjectable - public protocol CBCharacteristicInjectable: class { var uuid: CBUUID { get } var value: Data? { get } var properties: CBCharacteristicProperties { get } var isNotifying: Bool { get } } extension CBCharacteristic : CBCharacteristicInjectable {} // MARK: - CBPeripheralManagerInjectable - protocol CBPeripheralManagerInjectable { var delegate: CBPeripheralManagerDelegate? { get set } var isAdvertising: Bool { get } var managerState: ManagerState { get } func startAdvertising(_ advertisementData : [String : Any]?) func stopAdvertising() func add(_ service: CBMutableServiceInjectable) func remove(_ service: CBMutableServiceInjectable) func removeAllServices() func respondToRequest(_ request: CBATTRequestInjectable, withResult result: CBATTError.Code) func updateValue(_ value: Data, forCharacteristic characteristic: CBMutableCharacteristicInjectable, onSubscribedCentrals centrals: [CBCentralInjectable]?) -> Bool } extension CBPeripheralManager: CBPeripheralManagerInjectable { var managerState: ManagerState { switch state { case .unauthorized: return .unauthorized case .unknown: return .unknown case .unsupported: return .unsupported case .resetting: return .resetting case .poweredOff: return .poweredOff case .poweredOn: return .poweredOn @unknown default: fatalError() } } func add(_ service: CBMutableServiceInjectable) { self.add(service as! CBMutableService) } func remove(_ service: CBMutableServiceInjectable) { self.remove(service as! CBMutableService) } func respondToRequest(_ request: CBATTRequestInjectable, withResult result: CBATTError.Code) { self.respond(to: request as! CBATTRequest, withResult: result) } func updateValue(_ value: Data, forCharacteristic characteristic: CBMutableCharacteristicInjectable, onSubscribedCentrals centrals: [CBCentralInjectable]?) -> Bool { return self.updateValue(value, for: characteristic as! CBMutableCharacteristic, onSubscribedCentrals: centrals as! [CBCentral]?) } } // MARK: - CBMutableServiceInjectable - protocol CBMutableServiceInjectable: CBServiceInjectable { func setCharacteristics(_ characteristics: [CBCharacteristicInjectable]?) } extension CBMutableService: CBMutableServiceInjectable { func setCharacteristics(_ characteristics: [CBCharacteristicInjectable]?) { self.characteristics = characteristics?.map { $0 as! CBCharacteristic } } } // MARK: - CBMutableCharacteristicInjectable - protocol CBMutableCharacteristicInjectable: CBCharacteristicInjectable { var permissions: CBAttributePermissions { get } } extension CBMutableCharacteristic : CBMutableCharacteristicInjectable {} // MARK: - CBATTRequestInjectable - public protocol CBATTRequestInjectable { var offset: Int { get } var value: Data? { get set } func getCharacteristic() -> CBCharacteristicInjectable } extension CBATTRequest: CBATTRequestInjectable { public func getCharacteristic() -> CBCharacteristicInjectable { return self.characteristic } } // MARK: - CBCentralInjectable - public protocol CBCentralInjectable { var identifier: UUID { get } var maximumUpdateValueLength: Int { get } } extension CBCentral: CBCentralInjectable {}
c34fbe89797f055a191dc8571debdb34
33.909465
169
0.713427
false
false
false
false
a412657308/kkvapor
refs/heads/master
Sources/App/Models/SQFriend.swift
apache-2.0
2
import Foundation import Vapor struct SQFriend: Model { var exists: Bool = false var id: Node? var username: String let sex: String var headimgurl: String let rcuserid: String let deviceno: String let way: String let account: String let pwd: String var aboutme:String var zannum: Int var photos: String var tags: String var activities: String // var sqrctoken_id: Int init(username: String,sex: String, headimgurl: String, rcuserid: String, deviceno: String, way: String, account: String, pwd: String, aboutme:String, zannum:Int ,photos:String, tags:String, activities: String) { self.id = nil self.username = username self.sex = sex self.headimgurl = headimgurl self.rcuserid = rcuserid self.deviceno = deviceno self.way = way self.account = account self.pwd = pwd self.aboutme = aboutme self.zannum = zannum; self.photos = photos; self.tags = tags; self.activities = activities; // self.sqrctoken_id = sqrctoken_id } // Node Initializable init(node: Node, in context: Context) throws { id = try node.extract("id") username = try node.extract("username") sex = try node.extract("sex") headimgurl = try node.extract("headimgurl") rcuserid = try node.extract("rcuserid") deviceno = try node.extract("deviceno") way = try node.extract("way") account = try node.extract("account") pwd = try node.extract("pwd") aboutme = try node.extract("aboutme") zannum = try node.extract("zannum") photos = try node.extract("photos") tags = try node.extract("tags") activities = try node.extract("activities") // sqrctoken_id = try node.extract("id") } // Node Represen table func makeNode(context: Context) throws -> Node { return try Node(node: ["id": id, "username": username, "sex": sex, "headimgurl": headimgurl, "rcuserid": rcuserid, "deviceno": deviceno, "way": way, "account": account, "pwd": pwd, "aboutme":aboutme, "zannum":zannum, "photos":photos, "tags":tags, "activities":activities, // "sqrctoken_id":sqrctoken_id ]) } // Preparation static func prepare(_ database: Database) throws { try database.create("SQFriends") { friends in friends.id() friends.string("username") friends.string("sex") friends.string("headimgurl") friends.string("rcuserid") friends.string("deviceno") friends.string("way") friends.string("account") friends.string("pwd") friends.string("aboutme") friends.int("zannum") friends.string("photos") friends.string("tags") friends.string("activities") // friends.int("sqrctoken_id") } } static func revert(_ database: Database) throws { try database.delete("SQFriends") } } import Auth extension SQFriend: Auth.User { static func authenticate(credentials: Credentials) throws -> Auth.User { let user: SQFriend? switch credentials { case let id as Identifier: user = try SQFriend.find(id.id) case let accessToken as AccessToken: user = try SQFriend.query().filter("access_token", accessToken.string).first() case let apiKey as APIKey: user = try SQFriend.query().filter("email", apiKey.id).filter("password", apiKey.secret).first() default: throw Abort.custom(status: .badRequest, message: "Invalid credentials.") } guard let u = user else { throw Abort.custom(status: .badRequest, message: "User not found") } return u } static func register(credentials: Credentials) throws -> Auth.User { throw Abort.custom(status: .badRequest, message: "Register not supported.") } } import HTTP extension Request { func user() throws -> SQFriend { guard let user = try auth.user() as? SQFriend else { throw Abort.custom(status: .badRequest, message: "Invalid user type.") } return user } }
98134a4f822983559d0fec1c001b910b
30.741935
215
0.525813
false
false
false
false
zimcherDev/ios
refs/heads/master
Zimcher/UIKit Objects/UI Helpers/Cell/TextPromptCell.swift
apache-2.0
1
import UIKit class TextPromptEntryFieldCell: BaseEntryCell { let promptTextLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func setup() { contentView.addSubview(promptTextLabel) setupPrompt(promptTextLabel) promptTextLabel.translatesAutoresizingMaskIntoConstraints = false promptTextLabel.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor, constant: UI.ENTRY_FIELD.CELL_INDENT).active = true promptTextLabel.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true promptTextLabel.bottomAnchor.constraintEqualToAnchor(separator.topAnchor).active = true //default promptTextLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) promptTextLabel.setContentHuggingPriority(1000, forAxis: .Horizontal) } private func setupPrompt(prompt: UILabel) { prompt.textColor = COLORSCHEME.ENTRY_FIELD.PROMPT_TEXT_FG prompt.font = FONTS.SF_SEMIBOLD.fontWithSize(18) } }
3828c06c23ffc070660b35e74446b3a0
33.289474
140
0.704528
false
false
false
false
PiXeL16/BudgetShare
refs/heads/master
BudgetShareTests/Services/Mocks/Firebase/MockFirebaseBudgetService.swift
mit
1
// // Created by Chris Jimenez on 8/26/18. // Copyright (c) 2018 Chris Jimenez. All rights reserved. // import Foundation import FirebaseDatabase import RxSwift @testable import BudgetShare internal class MockFirebaseBudgetService: FirebaseBudgetService { var invokedObserveBudget = false var invokedObserveBudgetCount = 0 var invokedObserveBudgetParameters: (budgetId: String, Void)? var invokedObserveBudgetParametersList = [(budgetId: String, Void)]() var stubbedObserveBudgetResult: Observable<DataSnapshot>! func observeBudget(budgetId: String) -> Observable<DataSnapshot> { invokedObserveBudget = true invokedObserveBudgetCount += 1 invokedObserveBudgetParameters = (budgetId, ()) invokedObserveBudgetParametersList.append((budgetId, ())) return stubbedObserveBudgetResult } var invokedCreateBudget = false var invokedCreateBudgetCount = 0 var invokedCreateBudgetParameters: (data: BudgetServiceCreateData, Void)? var invokedCreateBudgetParametersList = [(data: BudgetServiceCreateData, Void)]() var stubbedCreateBudgetCallbackResult: BudgetServiceResult? func createBudget(data: BudgetServiceCreateData, callback: ((BudgetServiceResult) -> Void)?) { invokedCreateBudget = true invokedCreateBudgetCount += 1 invokedCreateBudgetParameters = (data, ()) invokedCreateBudgetParametersList.append((data, ())) if let result = stubbedCreateBudgetCallbackResult { callback?(result) } } var invokedFetchBudgetInfo = false var invokedFetchBudgetInfoCount = 0 var invokedFetchBudgetInfoParameters: (budgetId: String, Void)? var invokedFetchBudgetInfoParametersList = [(budgetId: String, Void)]() var stubbedFetchBudgetInfoCallbackResult: BudgetServiceResult? func fetchBudgetInfo(budgetId: String, callback: ((BudgetServiceResult) -> Void)?) { invokedFetchBudgetInfo = true invokedFetchBudgetInfoCount += 1 invokedFetchBudgetInfoParameters = (budgetId, ()) invokedFetchBudgetInfoParametersList.append((budgetId, ())) if let result = stubbedFetchBudgetInfoCallbackResult { callback?(result) } } }
4e97d14fc2d1b6b7729e69797dd05b00
37.672414
98
0.728934
false
false
false
false
wasm3/wasm3
refs/heads/main
platforms/ios/wasm3/ViewController.swift
mit
1
// // ViewController.swift // wasm3 // // Created by Volodymyr Shymanskyy on 1/10/20. // Copyright © 2020 wasm3. All rights reserved. // import UIKit var gLog: UITextView! class ViewController: UIViewController { // MARK: Properties @IBOutlet var log: UITextView! override func viewDidLoad() { super.viewDidLoad() gLog = log redirect_output({ if let ptr = $0 { let data = Data(bytes: ptr, count: Int($1)) if let str = String(data: data, encoding: String.Encoding.utf8) { DispatchQueue.main.async { gLog.text += str } } } }) run_app() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
f76acd06d6788c608d99d4f90a48610c
19.390244
81
0.528708
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Utility/UserActivities/NSUserActivity+Extensions.swift
lgpl-2.1
2
// // NSUserActivity+Extensions.swift // Neocom // // Created by Artem Shimanski on 4/23/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import UIKit import CoreData enum NSUserActivityType { static let fitting = "\(bundleID).fitting.activity" } extension NSUserActivity { static let isMainWindowKey = "isMainWindow" static let loadoutKey = "loadout" } // // // extension NSUserActivity { convenience init(fitting: FittingProject) throws { self.init(activityType: NSUserActivityType.fitting) // let data = try JSONEncoder().encode(fitting) // addUserInfoEntries(from: ["fitting": data]) } func fitting(from managedObjectContext: NSManagedObjectContext) throws -> FittingProject { let project = FittingProject(fileURL: FittingProject.documentsDirectoryURL.appendingPathComponent(UUID().uuidString).appendingPathExtension(Config.current.loadoutPathExtension), managedObjectContext: AppDelegate.sharedDelegate.storage.persistentContainer.viewContext) project.restoreUserActivityState(self) guard project.gang != nil || project.structure != nil else {throw RuntimeError.invalidLoadoutFormat} return project // guard let data = userInfo?["fitting"] as? Data else {throw RuntimeError.invalidActivityType} // let decoder = JSONDecoder() // decoder.userInfo[FittingProject.managedObjectContextKey] = managedObjectContext // return try decoder.decode(FittingProject.self, from: data) } }
c887f1a5d449fedaa6dd16c01a3b55ba
36.926829
185
0.716399
false
false
false
false
zdima/ZDComboBox
refs/heads/master
ZDComboBox/ZDPopupWindowManager.swift
mit
1
// // ZDPopupWindowManager.swift // MyFina // // Created by Dmitriy Zakharkin on 3/7/15. // Copyright (c) 2015 ZDima. All rights reserved. // import Cocoa extension NSView { func flippedRect( rect: NSRect ) -> NSRect { var rectRet: NSRect = rect if self.superview != nil { if !self.superview!.flipped { rectRet.origin.y = self.superview!.frame.size.height - rectRet.origin.y - rectRet.size.height } } return rectRet } } class ZDPopupWindowManager: NSObject { private var control: NSControl? = nil private var popupWindow: ZDPopupWindow? = nil private var dropDownButtonObject: NSButton? private var originalHeight: CGFloat = 0 static var popupManager = ZDPopupWindowManager() override init() { super.init() var contentRect: NSRect = NSZeroRect contentRect.size.height = 200 popupWindow = ZDPopupWindow(contentRect: contentRect, styleMask: NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false, screen: nil) popupWindow!.movableByWindowBackground = false popupWindow!.excludedFromWindowsMenu = true popupWindow!.hasShadow = true popupWindow!.titleVisibility = NSWindowTitleVisibility.Hidden } func showPopupForControl(userControl: NSControl?, withContent content: NSView?) -> Bool { if control == userControl { return true } if control != nil { hidePopup() } control = userControl if let ctrl = control as? ZDComboBox, let pWindow = popupWindow, let window = ctrl.window { originalHeight = content!.bounds.size.height pWindow.contentView = content! layoutPopupWindow() window.addChildWindow(pWindow, ordered: NSWindowOrderingMode.Above) NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidResize:", name: NSApplicationDidResignActiveNotification, object: ctrl.window ) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidResignActive:", name: NSWindowDidResizeNotification, object: NSApplication.sharedApplication() ) ctrl.buttonState = NSOnState return true } return false } func hidePopup() { if let ctrl = control as? ZDComboBox, let window = ctrl.window, let pWindow = popupWindow { if popupWindow!.visible { popupWindow!.orderOut(self) ctrl.window!.removeChildWindow(popupWindow!) NSNotificationCenter.defaultCenter().removeObserver(self) } ctrl.buttonState = NSOffState } control = nil } func applicationDidResignActive(node: NSNotification?) { hidePopup() } func layoutPopupWindow() { if let ctrl = control, let pWindow = popupWindow { var screenFrame: NSRect if let screen = pWindow.screen { screenFrame = screen.visibleFrame } else if let screen = NSScreen.mainScreen() { screenFrame = screen.visibleFrame } else { NSException(name: "runtime", reason: "no screen", userInfo: nil) return } let contentRect: NSRect = ctrl.bounds let controlRect: NSRect = ctrl.flippedRect(ctrl.frame) var frame = NSRect( x: controlRect.origin.x, y: controlRect.origin.y + controlRect.size.height-2, width: contentRect.size.width, height: originalHeight) var parentView: NSView? = ctrl.superview while parentView != nil { let parentFrame: NSRect = parentView!.flippedRect(parentView!.frame) frame = NSOffsetRect(frame, parentFrame.origin.x - parentView!.bounds.origin.x, parentFrame.origin.y - parentView!.bounds.origin.y) parentView = parentView!.superview } frame = adjustToScreen(frame,screenFrame,ctrl) pWindow.setFrame(frame, display: false) } } func adjustToScreen(srcFrame: NSRect, _ screenFrame: NSRect, _ ctrl: NSControl) -> NSRect { let screenRect = ctrl.window!.frame let contentRect: NSRect = ctrl.bounds var frame = srcFrame frame.origin.x = frame.origin.x + screenRect.origin.x frame.origin.y = screenRect.origin.y+screenRect.size.height-frame.origin.y - originalHeight let x2: CGFloat = frame.origin.x + frame.size.width if frame.origin.x < screenFrame.origin.x { frame.origin.x = screenFrame.origin.x } if frame.origin.y < screenFrame.origin.y { frame.origin.y = frame.origin.y + frame.size.height + contentRect.size.height } if x2 > screenFrame.size.width { frame.origin.x -= (x2 - screenFrame.size.width) } return frame } func windowDidResignKey(note: NSNotification?) { hidePopup() } func windowDidResize(note: NSNotification?) { layoutPopupWindow() } } @objc(ZDPopupWindow) class ZDPopupWindow: NSWindow { override var canBecomeKeyWindow: Bool { get { return false } } } @objc protocol ZDPopupContentDelegate { func selectionDidChange( selector: AnyObject?, fromUpDown updown: Bool ); func updateBindingProperty(); func showPopupForControl(control: NSControl?) -> Bool; var combo: ZDComboBox? { get set } } class ZDPopupContent: NSViewController { var delegate: ZDPopupContentDelegate? var rootNodes: [AnyObject]? { didSet { convertUserObjectToItems() } } var items: [ZDComboBoxItem] = [] var filter: String = "" { didSet { if oldValue != filter { invalidateFilter() } } } /// filter items again func invalidateFilter() {} func moveSelectionUp(up: Bool) {} func moveSelectionTo(string: String?, filtered: Bool ) -> NSString? { return nil } func convertUserObjectToItems() { items = [] if let nodes = rootNodes as? [NSObject], let comboBox = delegate!.combo { for child in nodes { if let treeNode = child as? NSTreeNode, let obj = treeNode.representedObject as? NSObject, let item = ZDComboBoxItem.itemWith( obj, hierarchical: comboBox.isHierarchical, displayKey: comboBox.displayKey, childsKey: comboBox.childsKey) { items.append(item) } else { if let item = ZDComboBoxItem.itemWith( child, hierarchical: false, displayKey: comboBox.displayKey, childsKey: comboBox.childsKey) { items.append(item) } } } } } }
0886957e259acfa513e02716be9e3b86
27.382883
97
0.674337
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/WidthSelectionTableViewCell.swift
apache-2.0
3
// // WidthSelectionTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/25/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit class WidthSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Width" descriptionValue = "Describes the entry's width inside the screen. It can be stretched to the margins, it can have an offset, can a constant or have a ratio to the screen" insertSegments(by: ["Stretch", "20pts Offset", "90% Screen"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.positionConstraints.size.width { case .offset(value: let value): if value == 0 { segmentedControl.selectedSegmentIndex = 0 } else { segmentedControl.selectedSegmentIndex = 1 } case .ratio(value: _): segmentedControl.selectedSegmentIndex = 2 default: break } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 0) case 1: attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 20) case 2: attributesWrapper.attributes.positionConstraints.size.width = .ratio(value: 0.9) default: break } } }
fa256a432bc79b4192f7183ef2405c09
34.042553
179
0.64238
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/ArticleTableOfContentsDisplayController.swift
mit
1
// Handles hide/display of article table of contents // Manages a stack view and the associated constraints protocol ArticleTableOfContentsDisplayControllerDelegate : TableOfContentsViewControllerDelegate { func tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() func getVisibleSection(with: @escaping (Int, String) -> Void) func stashOffsetPercentage() } class ArticleTableOfContentsDisplayController: Themeable { weak var delegate: ArticleTableOfContentsDisplayControllerDelegate? lazy var viewController: TableOfContentsViewController = { return recreateTableOfContentsViewController() }() var theme: Theme = .standard let articleView: WKWebView func apply(theme: Theme) { self.theme = theme separatorView.backgroundColor = theme.colors.baseBackground stackView.backgroundColor = theme.colors.paperBackground inlineContainerView.backgroundColor = theme.colors.midBackground viewController.apply(theme: theme) } func recreateTableOfContentsViewController() -> TableOfContentsViewController { let displaySide: TableOfContentsDisplaySide = stackView.semanticContentAttribute == .forceRightToLeft ? .right : .left return TableOfContentsViewController(delegate: delegate, theme: theme, displaySide: displaySide) } init (articleView: WKWebView, delegate: ArticleTableOfContentsDisplayControllerDelegate, theme: Theme) { self.delegate = delegate self.theme = theme self.articleView = articleView stackView.semanticContentAttribute = delegate.tableOfContentsSemanticContentAttribute stackView.addArrangedSubview(inlineContainerView) stackView.addArrangedSubview(separatorView) stackView.addArrangedSubview(articleView) NSLayoutConstraint.activate([separatorWidthConstraint]) } lazy var stackView: UIStackView = { let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) stackView.axis = .horizontal stackView.distribution = .fill stackView.alignment = .fill return stackView }() lazy var separatorView: UIView = { let sv = UIView(frame: .zero) sv.isHidden = true return sv }() lazy var inlineContainerView: UIView = { let cv = UIView(frame: .zero) cv.isHidden = true return cv }() lazy var separatorWidthConstraint: NSLayoutConstraint = { return separatorView.widthAnchor.constraint(equalToConstant: 1) }() func show(animated: Bool) { switch viewController.displayMode { case .inline: showInline() case .modal: showModal(animated: animated) } } func hide(animated: Bool) { switch viewController.displayMode { case .inline: hideInline() case .modal: hideModal(animated: animated) } } func showModal(animated: Bool) { guard delegate?.presentedViewController == nil else { return } delegate?.getVisibleSection(with: { (sectionId, _) in self.viewController.isVisible = true self.selectAndScroll(to: sectionId, animated: false) self.delegate?.present(self.viewController, animated: animated) }) } func hideModal(animated: Bool) { viewController.isVisible = false delegate?.dismiss(animated: animated) } func showInline() { delegate?.stashOffsetPercentage() viewController.isVisible = true UserDefaults.standard.wmf_setTableOfContentsIsVisibleInline(true) inlineContainerView.isHidden = false separatorView.isHidden = false } func hideInline() { delegate?.stashOffsetPercentage() viewController.isVisible = false UserDefaults.standard.wmf_setTableOfContentsIsVisibleInline(false) inlineContainerView.isHidden = true separatorView.isHidden = true } func setup(with traitCollection:UITraitCollection) { update(with: traitCollection) guard viewController.displayMode == .inline, UserDefaults.standard.wmf_isTableOfContentsVisibleInline() else { return } showInline() } func update(with traitCollection: UITraitCollection) { let isCompact = traitCollection.horizontalSizeClass == .compact viewController.displayMode = isCompact ? .modal : .inline setupTableOfContentsViewController() } func setupTableOfContentsViewController() { switch viewController.displayMode { case .inline: guard viewController.parent != delegate else { return } let wasVisible = viewController.isVisible if wasVisible { hideModal(animated: false) } viewController = recreateTableOfContentsViewController() viewController.displayMode = .inline delegate?.addChild(viewController) inlineContainerView.wmf_addSubviewWithConstraintsToEdges(viewController.view) viewController.didMove(toParent: delegate) if wasVisible { showInline() } delegate?.tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() case .modal: guard viewController.parent == delegate else { return } let wasVisible = viewController.isVisible viewController.displayMode = .modal viewController.willMove(toParent: nil) viewController.view.removeFromSuperview() viewController.removeFromParent() viewController = recreateTableOfContentsViewController() if wasVisible { hideInline() showModal(animated: false) } delegate?.tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() } } func selectAndScroll(to sectionId: Int, animated: Bool) { guard let index = delegate?.tableOfContentsItems.firstIndex(where: { $0.id == sectionId }) else { return } viewController.selectItem(at: index) viewController.scrollToItem(at: index) } }
2a1bed9652545182588178cad9492d0e
35.050562
126
0.658719
false
false
false
false
GlebRadchenko/AdvertServer
refs/heads/master
Sources/App/Models/Advertisment.swift
mit
1
// // Advertisment.swift // AdvertServer // // Created by GlebRadchenko on 11/23/16. // // import Foundation import Vapor import Fluent final class Advertisment: Model { static let databaseName = "advertisments" var id: Node? var title: String var description: String var media: String? var parentId: Node? var exists: Bool = false init(title: String, description: String) { self.title = title self.description = description } init(node: Node, in context: Context) throws { id = try node.extract("id") title = try node.extract("title") description = try node.extract("description") media = try node.extract("media") parentId = try node.extract("parentId") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "_id": id, "title": title, "description": description, "media": media, "parentId": parentId ]) } static func prepare(_ database: Database) throws { try database.create(self.databaseName) { advertisments in advertisments.id() advertisments.string("title") advertisments.string("description") advertisments.string("media", length: nil, optional: true) advertisments.id("parentId", optional: false) } } static func revert(_ database: Database) throws { try database.delete(self.databaseName) } } extension Advertisment { func beacon() throws -> Parent<Beacon> { return try parent(parentId) } }
c2db24577149ae2937f2eb7eb8c1f9d1
24.953125
70
0.59121
false
false
false
false
Bluthwort/Bluthwort
refs/heads/master
Sources/Classes/Style/UIScrollViewStyle.swift
mit
1
// // UIScrollViewStyle.swift // // Copyright (c) 2018 Bluthwort // // 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. // extension Bluthwort where Base: UIScrollView { @discardableResult public func delegate(_ delegate: UIScrollViewDelegate?) -> Bluthwort { // The delegate of the scroll-view object. base.delegate = delegate return self } @discardableResult public func contentSize(_ size: CGSize) -> Bluthwort { // The size of the content view. base.contentSize = size return self } @discardableResult public func contentOffset(_ offset: CGPoint, animated: Bool? = nil) -> Bluthwort { if let animated = animated { // Sets the offset from the content view’s origin that corresponds to the receiver’s // origin. base.setContentOffset(offset, animated: animated) } else { // The point at which the origin of the content view is offset from the origin of the // scroll view. base.contentOffset = offset } return self } @discardableResult public func contentInset(_ inset: UIEdgeInsets) -> Bluthwort { // The insets derived from the content insets and the safe area of the scroll view. base.contentInset = inset return self } @available(iOS 11.0, *) @discardableResult public func contentInsetAdjustmentBehavior(_ behavior: UIScrollViewContentInsetAdjustmentBehavior) -> Bluthwort { // The behavior for determining the adjusted content offsets. base.contentInsetAdjustmentBehavior = behavior return self } @discardableResult public func isScrollEnabled(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether scrolling is enabled. base.isScrollEnabled = flag return self } @discardableResult public func isDirectionalLockEnabled(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether scrolling is disabled in a particular direction. base.isDirectionalLockEnabled = flag return self } @discardableResult public func isPagingEnabled(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether paging is enabled for the scroll view. base.isPagingEnabled = flag return self } @discardableResult public func scrollsToTop(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the scroll-to-top gesture is enabled. base.scrollsToTop = flag return self } @discardableResult public func bounces(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the scroll view bounces past the edge of content // and back again. base.bounces = flag return self } @discardableResult public func alwaysBounceVertical(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether bouncing always occurs when vertical scrolling // reaches the end of the content. base.alwaysBounceVertical = flag return self } @discardableResult public func alwaysBounceHorizontal(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether bouncing always occurs when horizontal scrolling // reaches the end of the content view. base.alwaysBounceHorizontal = flag return self } @discardableResult public func decelerationRate(_ rate: CGFloat) -> Bluthwort { // A floating-point value that determines the rate of deceleration after the user lifts their finger. base.decelerationRate = rate return self } @discardableResult public func indicatorStyle(_ style: UIScrollViewIndicatorStyle) -> Bluthwort { // The style of the scroll indicators. base.indicatorStyle = style return self } @discardableResult public func scrollIndicatorInsets(_ insets: UIEdgeInsets) -> Bluthwort { // The distance the scroll indicators are inset from the edge of the scroll view. base.scrollIndicatorInsets = insets return self } @discardableResult public func showsHorizontalScrollIndicator(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the horizontal scroll indicator is visible. base.showsHorizontalScrollIndicator = flag return self } @discardableResult public func showsVerticalScrollIndicator(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the vertical scroll indicator is visible. base.showsVerticalScrollIndicator = flag return self } @available(iOS 10.0, *) @discardableResult public func refreshControl(_ refreshControl: UIRefreshControl?) -> Bluthwort { // The refresh control associated with the scroll view. base.refreshControl = refreshControl return self } @discardableResult public func canCancelContentTouches(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether touches in the content view always lead to tracking. base.canCancelContentTouches = flag return self } @discardableResult public func delaysContentTouches(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether the scroll view delays the handling of touch-down // gestures. base.delaysContentTouches = flag return self } @discardableResult public func zoomScale(_ scale: CGFloat) -> Bluthwort { // A floating-point value that specifies the current scale factor applied to the scroll // view's content. base.zoomScale = scale return self } @discardableResult public func maximumZoomScale(_ scale: CGFloat) -> Bluthwort { // A floating-point value that specifies the maximum scale factor that can be applied to the // scroll view's content. base.maximumZoomScale = scale return self } @discardableResult public func minimumZoomScale(_ scale: CGFloat) -> Bluthwort { // A floating-point value that specifies the current scale factor applied to the scroll // view's content. base.minimumZoomScale = scale return self } @discardableResult public func bouncesZoom(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether the scroll view animates the content scaling when // the scaling exceeds the maximum or minimum limits. base.bouncesZoom = flag return self } @discardableResult public func keyboardDismissMode(_ mode: UIScrollViewKeyboardDismissMode) -> Bluthwort { // The manner in which the keyboard is dismissed when a drag begins in the scroll view. base.keyboardDismissMode = mode return self } @discardableResult public func indexDisplayMode(_ mode: UIScrollViewIndexDisplayMode) -> Bluthwort { // The manner in which the index is shown while the user is scrolling. base.indexDisplayMode = mode return self } }
a0384b4d3979b508f435186a546e3e0e
35.619469
117
0.67883
false
false
false
false
auth0/native-mobile-samples
refs/heads/master
iOS/basic-sample-swift/SwiftSample/HomeViewController.swift
mit
1
// HomeViewController.swift // // Copyright (c) 2014 Auth0 (http://auth0.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 UIKit import JWTDecode import MBProgressHUD import Lock class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let keychain = MyApplication.sharedInstance.keychain if let idToken = keychain.stringForKey("id_token"), let jwt = try? JWTDecode.decode(idToken) { if jwt.expired, let refreshToken = keychain.stringForKey("refresh_token") { MBProgressHUD.showHUDAddedTo(self.view, animated: true) let success = {(token:A0Token!) -> () in keychain.setString(token.idToken, forKey: "id_token") MBProgressHUD.hideHUDForView(self.view, animated: true) self.performSegueWithIdentifier("showProfile", sender: self) } let failure = {(error:NSError!) -> () in keychain.clearAll() MBProgressHUD.hideHUDForView(self.view, animated: true) } let client = MyApplication.sharedInstance.lock.apiClient() client.fetchNewIdTokenWithRefreshToken(refreshToken, parameters: nil, success: success, failure: failure) } else { self.performSegueWithIdentifier("showProfile", sender: self) } } } @IBAction func showSignIn(sender: AnyObject) { let lock = MyApplication.sharedInstance.lock let authController = lock.newLockViewController() authController.closable = true authController.onAuthenticationBlock = { (profile, token) -> () in switch (profile, token) { case (.Some(let profile), .Some(let token)): let keychain = MyApplication.sharedInstance.keychain keychain.setString(token.idToken, forKey: "id_token") if let refreshToken = token.refreshToken { keychain.setString(refreshToken, forKey: "refresh_token") } keychain.setData(NSKeyedArchiver.archivedDataWithRootObject(profile), forKey: "profile") self.dismissViewControllerAnimated(true, completion: nil) self.performSegueWithIdentifier("showProfile", sender: self) default: print("User signed up without logging in") } } self.presentViewController(authController, animated: true, completion: nil) } }
4bba0dd50ac71770c03362c9f96fdae4
46.263158
121
0.6598
false
false
false
false
SereivoanYong/Charts
refs/heads/master
Source/Charts/Data/Implementations/Standard/RadarDataSet.swift
apache-2.0
1
// // RadarDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import UIKit open class RadarDataSet: LineRadarDataSet, IRadarChartDataSet { fileprivate func initialize() { valueFont = .systemFont(ofSize: 13.0) } public required init() { super.init() initialize() } public required override init(values: [Entry], label: String?) { super.init(values: values, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// flag indicating whether highlight circle should be drawn or not /// **default**: false open var isDrawHighlightCircleEnabled: Bool = false open var highlightCircleFillColor: UIColor? = .white /// The stroke color for highlight circle. /// If `nil`, the color of the dataset is taken. open var highlightCircleStrokeColor: UIColor? open var highlightCircleStrokeAlpha: CGFloat = 0.3 open var highlightCircleInnerRadius: CGFloat = 3.0 open var highlightCircleOuterRadius: CGFloat = 4.0 open var highlightCircleStrokeWidth: CGFloat = 2.0 }
605c90e7ac31c879be0426dd602bf2ee
23.288462
69
0.698337
false
false
false
false
testpress/ios-app
refs/heads/master
ios-app/Utils/VideoPlayerUtils.swift
mit
1
// // VideoPlayerUtils.swift // ios-app // // Created by Karthik raja on 12/6/19. // Copyright © 2019 Testpress. All rights reserved. // import Foundation enum PlaybackSpeed:String { case verySlow = "0.5x" case slow = "0.75x" case normal = "Normal" case fast = "1.25x" case veryFast = "1.5x" case double = "2x" var value: Float { switch self { case .verySlow: return 0.5 case .slow: return 0.75 case .normal: return 1.00 case .fast: return 1.25 case .veryFast: return 1.5 case .double: return 2.00 } } var label: String { switch self { case .normal: return "1x" default: return self.rawValue } } } extension PlaybackSpeed: CaseIterable {} enum PlayerStatus { case readyToPlay case playing case paused case finished } enum VideoDurationType { case remainingTime case totalTime func getDurationString (seconds : Double) -> String { if seconds.isNaN || seconds.isInfinite { return "00:00" } let hour = Int(seconds) / 3600 let minute = Int(seconds) / 60 % 60 let second = Int(seconds) % 60 let time = hour > 0 ? String(format: "%02i:%02i:%02i", hour, minute, second) :String(format: "%02i:%02i", minute, second) return time } func value(seconds:Double, total:Double) -> String { switch self { case .remainingTime: return "-\(getDurationString(seconds: total-seconds))" case .totalTime: return getDurationString(seconds: total) } } } struct VideoQuality { var resolution: String var bitrate: Int }
e40decc0eba39c194dd3a4d26a7fc1fe
20.27907
129
0.549727
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/SyntaxManager.swift
apache-2.0
1
// // SyntaxManager.swift // // CotEditor // https://coteditor.com // // Created by nakamuxu on 2004-12-24. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Combine import Foundation import UniformTypeIdentifiers import Yams @objc protocol SyntaxHolder: AnyObject { func changeSyntaxStyle(_ sender: AnyObject?) func recolorAll(_ sender: Any?) } enum BundledStyleName { static let none: SyntaxManager.SettingName = "None".localized(comment: "syntax style name") static let xml: SyntaxManager.SettingName = "XML" static let markdown: SyntaxManager.SettingName = "Markdown" } // MARK: - final class SyntaxManager: SettingFileManaging { typealias Setting = SyntaxStyle typealias SettingName = String typealias StyleDictionary = [String: Any] // MARK: Public Properties static let shared = SyntaxManager() // MARK: Setting File Managing Properties let didUpdateSetting: PassthroughSubject<SettingChange, Never> = .init() static let directoryName: String = "Syntaxes" let fileType: UTType = .yaml @Published var settingNames: [SettingName] = [] let bundledSettingNames: [SettingName] @Atomic var cachedSettings: [SettingName: Setting] = [:] // MARK: Private Properties private let bundledMap: [SettingName: [String: [String]]] @Atomic private var mappingTables: [SyntaxKey: [String: [SettingName]]] = [.extensions: [:], .filenames: [:], .interpreters: [:]] // MARK: - // MARK: Lifecycle private init() { // load bundled style list let url = Bundle.main.url(forResource: "SyntaxMap", withExtension: "json")! let data = try! Data(contentsOf: url) let map = try! JSONDecoder().decode([SettingName: [String: [String]]].self, from: data) self.bundledMap = map self.bundledSettingNames = map.keys.sorted(options: [.localized, .caseInsensitive]) // sanitize user setting file extensions try? self.sanitizeUserSettings() // cache user styles self.checkUserSettings() } // MARK: Public Methods /// return style name corresponding to given variables func settingName(documentFileName fileName: String, content: String) -> SettingName { return self.settingName(documentFileName: fileName) ?? self.settingName(documentContent: content) ?? BundledStyleName.none } /// return style name corresponding to file name func settingName(documentFileName fileName: String) -> SettingName? { let mappingTables = self.mappingTables if let settingName = mappingTables[.filenames]?[fileName]?.first { return settingName } if let pathExtension = fileName.components(separatedBy: ".").last, let extentionTable = mappingTables[.extensions] { if let settingName = extentionTable[pathExtension]?.first { return settingName } // check case-insensitively let lowerPathExtension = pathExtension.lowercased() if let sttingName = extentionTable .first(where: { $0.key.lowercased() == lowerPathExtension })? .value.first { return sttingName } } return nil } /// return style name scanning shebang in document content func settingName(documentContent content: String) -> SettingName? { if let interpreter = content.scanInterpreterInShebang(), let settingName = self.mappingTables[.interpreters]?[interpreter]?.first { return settingName } // check XML declaration if content.hasPrefix("<?xml ") { return BundledStyleName.xml } return nil } /// style dictionary list corresponding to style name func settingDictionary(name: SettingName) -> StyleDictionary? { if name == BundledStyleName.none { return self.blankSettingDictionary } guard let url = self.urlForUsedSetting(name: name), let dictionary = try? self.loadSettingDictionary(at: url) else { return nil } return dictionary.cocoaBindable } /// return bundled version style dictionary or nil if not exists func bundledSettingDictionary(name: SettingName) -> StyleDictionary? { guard let url = self.urlForBundledSetting(name: name), let dictionary = try? self.loadSettingDictionary(at: url) else { return nil } return dictionary.cocoaBindable } /// save setting file func save(settingDictionary: StyleDictionary, name: SettingName, oldName: SettingName?) throws { // create directory to save in user domain if not yet exist try self.prepareUserSettingDirectory() // sort items let beginStringSort = NSSortDescriptor(key: SyntaxDefinitionKey.beginString.rawValue, ascending: true, selector: #selector(NSString.caseInsensitiveCompare)) for key in SyntaxType.allCases { (settingDictionary[key.rawValue] as? NSMutableArray)?.sort(using: [beginStringSort]) } let keyStringSort = NSSortDescriptor(key: SyntaxDefinitionKey.keyString.rawValue, ascending: true, selector: #selector(NSString.caseInsensitiveCompare)) for key in [SyntaxKey.outlineMenu, .completions] { (settingDictionary[key.rawValue] as? NSMutableArray)?.sort(using: [keyStringSort]) } // save let saveURL = self.preparedURLForUserSetting(name: name) // move old file to new place to overwrite when style name is also changed if let oldName = oldName, name != oldName { try self.renameSetting(name: oldName, to: name) } // just remove the current custom setting file in the user domain if new style is just the same as bundled one // so that application uses bundled one if self.isEqualToBundledSetting(settingDictionary, name: name) { if saveURL.isReachable { try FileManager.default.removeItem(at: saveURL) } } else { // save file to user domain let yamlString = try Yams.dump(object: settingDictionary.yamlEncodable, allowUnicode: true) try yamlString.write(to: saveURL, atomically: true, encoding: .utf8) } // invalidate current cache self.$cachedSettings.mutate { $0[name] = nil } if let oldName = oldName { self.$cachedSettings.mutate { $0[oldName] = nil } } // update internal cache let change: SettingChange = oldName.flatMap { .updated(from: $0, to: name) } ?? .added(name) self.updateSettingList(change: change) self.didUpdateSetting.send(change) } /// conflicted maps var mappingConflicts: [SyntaxKey: [String: [SettingName]]] { return self.mappingTables.mapValues { $0.filter { $0.value.count > 1 } } } /// empty style dictionary var blankSettingDictionary: StyleDictionary { return [ SyntaxKey.metadata.rawValue: NSMutableDictionary(), SyntaxKey.extensions.rawValue: NSMutableArray(), SyntaxKey.filenames.rawValue: NSMutableArray(), SyntaxKey.interpreters.rawValue: NSMutableArray(), SyntaxType.keywords.rawValue: NSMutableArray(), SyntaxType.commands.rawValue: NSMutableArray(), SyntaxType.types.rawValue: NSMutableArray(), SyntaxType.attributes.rawValue: NSMutableArray(), SyntaxType.variables.rawValue: NSMutableArray(), SyntaxType.values.rawValue: NSMutableArray(), SyntaxType.numbers.rawValue: NSMutableArray(), SyntaxType.strings.rawValue: NSMutableArray(), SyntaxType.characters.rawValue: NSMutableArray(), SyntaxType.comments.rawValue: NSMutableArray(), SyntaxKey.outlineMenu.rawValue: NSMutableArray(), SyntaxKey.completions.rawValue: NSMutableArray(), SyntaxKey.commentDelimiters.rawValue: NSMutableDictionary(), ] } // MARK: Setting File Managing /// return setting instance corresponding to the given setting name func setting(name: SettingName) -> Setting? { if name == BundledStyleName.none { return SyntaxStyle() } guard let setting: Setting = { if let setting = self.cachedSettings[name] { return setting } guard let url = self.urlForUsedSetting(name: name) else { return nil } let setting = try? self.loadSetting(at: url) self.$cachedSettings.mutate { $0[name] = setting } return setting }() else { return nil } // add to recent styles list let maximumRecentStyleCount = max(0, UserDefaults.standard[.maximumRecentStyleCount]) var recentStyleNames = UserDefaults.standard[.recentStyleNames] recentStyleNames.removeFirst(name) recentStyleNames.insert(name, at: 0) UserDefaults.standard[.recentStyleNames] = Array(recentStyleNames.prefix(maximumRecentStyleCount)) return setting } /// load setting from the file at given URL func loadSetting(at fileURL: URL) throws -> Setting { let dictionary = try self.loadSettingDictionary(at: fileURL) let name = self.settingName(from: fileURL) return SyntaxStyle(dictionary: dictionary, name: name) } /// load settings in the user domain func checkUserSettings() { // load mapping definitions from style files in user domain let mappingKeys = SyntaxKey.mappingKeys.map(\.rawValue) let userMap: [SettingName: [String: [String]]] = self.userSettingFileURLs.reduce(into: [:]) { (dict, url) in guard let style = try? self.loadSettingDictionary(at: url) else { return } let settingName = self.settingName(from: url) // create file mapping data dict[settingName] = style.filter { mappingKeys.contains($0.key) } .mapValues { $0 as? [[String: String]] ?? [] } .mapValues { $0.compactMap { $0[SyntaxDefinitionKey.keyString] } } } let map = self.bundledMap.merging(userMap) { (_, new) in new } // sort styles alphabetically self.settingNames = map.keys.sorted(options: [.localized, .caseInsensitive]) // remove styles not exist UserDefaults.standard[.recentStyleNames].removeAll { !self.settingNames.contains($0) } // update file mapping tables let settingNames = self.settingNames.filter { !self.bundledSettingNames.contains($0) } + self.bundledSettingNames // postpone bundled styles self.mappingTables = SyntaxKey.mappingKeys.reduce(into: [:]) { (tables, key) in tables[key] = settingNames.reduce(into: [String: [SettingName]]()) { (table, settingName) in guard let items = map[settingName]?[key.rawValue] else { return } for item in items { table[item, default: []].append(settingName) } } } } // MARK: Private Methods /// Standardize the file extensions of user setting files. /// /// - Note: The file extension for syntax definition files are changed from `.yaml` to `.yml` in CotEditor 4.2.0 released in 2022. private func sanitizeUserSettings() throws { let urls = self.userSettingFileURLs.filter { $0.pathExtension == "yaml" } guard !urls.isEmpty else { return } for url in urls { let newURL = url.deletingPathExtension().appendingPathExtension(for: .yaml) try FileManager.default.moveItem(at: url, to: newURL) } } /// Load StyleDictionary at file URL. /// /// - Parameter fileURL: URL to a setting file. /// - Throws: `CocoaError` private func loadSettingDictionary(at fileURL: URL) throws -> StyleDictionary { let string = try String(contentsOf: fileURL) let yaml = try Yams.load(yaml: string) guard let styleDictionary = yaml as? StyleDictionary else { throw CocoaError.error(.fileReadCorruptFile, url: fileURL) } return styleDictionary } /// return whether contents of given highlight definition is the same as bundled one private func isEqualToBundledSetting(_ style: StyleDictionary, name: SettingName) -> Bool { guard let bundledStyle = self.bundledSettingDictionary(name: name) else { return false } return style == bundledStyle } } private extension StringProtocol where Self.Index == String.Index { /// Extract interepreter from the shebang line. func scanInterpreterInShebang() -> String? { guard self.hasPrefix("#!") else { return nil } // get first line let firstLineRange = self.lineContentsRange(at: self.startIndex) let shebang = self[firstLineRange] .dropFirst("#!".count) .trimmingCharacters(in: .whitespacesAndNewlines) // find interpreter let components = shebang.components(separatedBy: " ") let interpreter = components.first?.components(separatedBy: "/").last // use first arg if the path targets env if interpreter == "env" { return components[safe: 1] } return interpreter } } // MARK: - Cocoa Bindings Support private extension SyntaxManager.StyleDictionary { /// Convert to NSObject-based collection for Cocoa-Bindings recursively. var cocoaBindable: Self { return self.mapValues(Self.convertToCocoaBindable) } /// Convert to YAML serialization comaptible colletion recursively. var yamlEncodable: Self { return self.mapValues(Self.convertToYAMLEncodable) } // MARK: Private Methods private static func convertToYAMLEncodable(_ item: Any) -> Any { switch item { case let dictionary as NSDictionary: return (dictionary as! Dictionary).mapValues(Self.convertToYAMLEncodable) case let array as NSArray: return (array as Array).map(Self.convertToYAMLEncodable) case let bool as Bool: return bool case let string as String: return string default: assertionFailure("\(type(of: item))") return item } } private static func convertToCocoaBindable(_ item: Any) -> Any { switch item { case let dictionary as Dictionary: return NSMutableDictionary(dictionary: dictionary.mapValues(convertToCocoaBindable)) case let array as [Any]: return NSMutableArray(array: array.map(convertToCocoaBindable)) case let date as Date: return ISO8601DateFormatter.string(from: date, timeZone: .current, formatOptions: [.withFullDate, .withDashSeparatorInDate]) default: return item } } } // MARK: - Equitability Support private extension SyntaxManager.StyleDictionary { static func == (lhs: Self, rhs: Self) -> Bool { return areEqual(lhs, rhs) } // MARK: Private Methods /// Check the equitability recursively. /// /// This comparison is designed and valid only for StyleDictionary. private static func areEqual(_ lhs: Any, _ rhs: Any) -> Bool { switch (lhs, rhs) { case let (lhs, rhs) as (Dictionary, Dictionary): guard lhs.count == rhs.count else { return false } return lhs.allSatisfy { (key, lhsValue) -> Bool in guard let rhsValue = rhs[key] else { return false } return areEqual(lhsValue, rhsValue) } case let (lhs, rhs) as ([Any], [Any]): guard lhs.count == rhs.count else { return false } // check elements equitability by ignoring the order var rhs = rhs for lhsValue in lhs { guard let rhsIndex = rhs.firstIndex(where: { areEqual(lhsValue, $0) }) else { return false } rhs.remove(at: rhsIndex) } return true default: return type(of: lhs) == type(of: rhs) && String(describing: lhs) == String(describing: rhs) } } }
5aa570520a4178b580f7ace327c91ceb
33.66855
149
0.589005
false
false
false
false
t4thswm/Course
refs/heads/master
Course/TimeSettingsViewController.swift
gpl-3.0
1
// // TimeSettingsViewController.swift // Course // // Created by Archie Yu on 2017/1/14. // Copyright © 2017年 Archie Yu. All rights reserved. // import UIKit class TimeSettingsViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() (self.view as! UITableView).separatorColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3) } override func viewDidAppear(_ animated: Bool) { tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.isUserInteractionEnabled = (sunday != 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section) { case 0: return 2 case 1: return 1 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TimeSettingsCell", for: indexPath) cell.backgroundColor = UIColor(white: 1, alpha: 0.1) cell.textLabel?.textColor = .white let selectedColor = UIColor(white: 1, alpha: 0.3) let selectedBackground = UIView() selectedBackground.backgroundColor = selectedColor cell.selectedBackgroundView = selectedBackground switch indexPath.section { case 0: switch indexPath.row { case 0: if saturday == 0 { cell.accessoryType = .none } else { cell.accessoryType = .checkmark } cell.textLabel?.text = "周六" case 1: if sunday == 0 { cell.accessoryType = .none } else { cell.accessoryType = .checkmark } cell.textLabel?.text = "周日" default: break } case 1: cell.accessoryType = .none cell.textLabel?.text = "总周数" default: break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 取消选中 tableView.deselectRow(at: indexPath, animated: true) let userDefault = UserDefaults(suiteName: "group.studio.sloth.Course") // 跳转 switch indexPath.section { case 0: switch indexPath.row { case 0: if saturday == 1 { tableView.cellForRow(at: indexPath)?.accessoryType = .none saturday = 0 userDefault?.set(0, forKey: "Saturday") } else { tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark saturday = 1 userDefault?.set(1, forKey: "Saturday") } case 1: let saturdayCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) if sunday == 1 { saturdayCell?.isUserInteractionEnabled = true tableView.cellForRow(at: indexPath)?.accessoryType = .none sunday = 0 userDefault?.set(0, forKey: "Sunday") } else { saturdayCell?.accessoryType = .checkmark saturdayCell?.isUserInteractionEnabled = false saturday = 1 userDefault?.set(1, forKey: "Saturday") tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark sunday = 1 userDefault?.set(1, forKey: "Sunday") } default: break } weekdayNum = 5 + saturday + sunday needReload = true case 2: break default: break } userDefault?.synchronize() } }
557935773928f7849c6683ef86539bf0
31.944882
109
0.52892
false
false
false
false
wangchong321/tucao
refs/heads/master
WCWeiBo/WCWeiBo/Classes/Model/Home/HomeRefresh.swift
mit
1
// // HomeRefresh.swift // WCWeiBo // // Created by 王充 on 15/5/21. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class HomeRefresh: UIRefreshControl { override init() { super.init() prepareView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // 准备子视图 var refreshView : RefreshView? // 准备 UIRefreshControl private func prepareView(){ let rView = NSBundle.mainBundle().loadNibNamed("HomeRefresh", owner: nil, options: nil).last as! RefreshView addSubview(rView) rView.setTranslatesAutoresizingMaskIntoConstraints(false) /// 添加约束数组 var cons = [AnyObject]() cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[rView(136)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView":rView]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rView(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView":rView]) cons.append( NSLayoutConstraint(item: rView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) self.addConstraints(cons) self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) self.refreshView = rView } deinit{ self.removeObserver(self, forKeyPath: "frame") } override func endRefreshing() { super.endRefreshing() // 停止动画 refreshView?.stopLoading() // isLoadingFlag = false } // 显示箭头标记 var shouTipFlag = false // 显示正在加载标记 var isLoadingFlag = false override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if self.frame.origin.y >= 0 { return } // 如果正在刷新 并且还没有转圈显示 if refreshing && !isLoadingFlag{ // 根据给的动画时长来结束动画 println("正在加载") self.refreshView?.startLoding() isLoadingFlag = true return } if self.frame.origin.y > -50 && shouTipFlag{ shouTipFlag = false refreshView?.rotateTipIcon(shouTipFlag) }else if self.frame.origin.y <= -50 && !shouTipFlag{ shouTipFlag = true refreshView?.rotateTipIcon(shouTipFlag) // 箭头转向上边 } } } class RefreshView: UIView { /// load视图(转圈图标) @IBOutlet weak var loadImgView: UIImageView! /// 箭头图标 @IBOutlet weak var tipIcon: UIImageView! /// 提示视图 @IBOutlet weak var tipView: UIView! /// 旋转箭头 private func rotateTipIcon(whatDirection : Bool){ var angel = CGFloat(M_PI) as CGFloat angel += whatDirection ? -0.01 : 0.01 UIView.animateWithDuration(0.5) { self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(M_PI)) } } /// 开始加载 func startLoding(){ tipView.hidden = true let anim = CABasicAnimation(keyPath: "transform.rotation") anim.duration = 0.5 anim.repeatCount = MAXFLOAT anim.toValue = M_PI * 2 loadImgView.layer.addAnimation(anim, forKey: nil) } /// 结束加载 func stopLoading(){ loadImgView.layer.removeAllAnimations() tipView.hidden = false } }
c9ac48df77a49d235841e04a850d043a
28.991597
208
0.607343
false
false
false
false
richard92m/three.bar
refs/heads/master
ThreeBar/ThreeBar/GameScene.swift
gpl-3.0
1
// // GameScene.swift // ThreeBar // // Created by Marquez, Richard A on 12/13/14. // Copyright (c) 2014 Richard Marquez. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var lives: Int = 0 let hero = Hero() let hive = Hive() var mobs = [Mob]() let door = Door() var locks = [Lock]() var score: Int = 0 let scoreLabel = SKLabelNode() let livesLabel = SKLabelNode() var startTime = NSDate() override func didMoveToView(view: SKView) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "onMotionShake:", name:"MotionShake", object: nil) physicsWorld.contactDelegate = self physicsWorld.gravity = CGVectorMake(0, 0) addLivesLabel() addScoreLabel() addHero() addMoveControl() addHive() populateWithMobs() addDoor() populateWithLocks() } func addLivesLabel() { livesLabel.fontName = _magic.get("livesFont") as String livesLabel.name = "livesLabel" livesLabel.text = "" for var i = 0; i < lives; ++i { livesLabel.text = "\(livesLabel.text)_" } livesLabel.fontSize = _magic.get("livesSize") as CGFloat livesLabel.position = CGPoint(x: size.width - 100, y: 15) livesLabel.zPosition = CGFloat(ZIndex.HUD.rawValue) self.addChild(livesLabel) } func addScoreLabel() { var bgSize = CGSize() bgSize.width = _magic.get("scoreBgWidth") as CGFloat bgSize.height = _magic.get("scoreBgHeight") as CGFloat let bgColor = UIColor(hex: _magic.get("scoreBgColor") as String) let scoreBg = SKSpriteNode(color: bgColor, size: bgSize) scoreBg.position = CGPoint(x: CGRectGetMidX(self.frame), y: size.height - 10) scoreBg.zRotation = DEGREES_TO_RADIANS(_magic.get("scoreBgRotation") as CGFloat) scoreBg.zPosition = CGFloat(ZIndex.HUD.rawValue - 1) self.addChild(scoreBg) scoreLabel.fontName = _magic.get("scoreFont") as String scoreLabel.name = "scoreLabel" scoreLabel.text = String(score) scoreLabel.fontSize = _magic.get("scoreSize") as CGFloat scoreLabel.fontColor = UIColor(hex: _magic.get("scoreColor") as String) scoreLabel.position = CGPoint(x: CGRectGetMidX(self.frame), y: size.height - 50) scoreLabel.zPosition = CGFloat(ZIndex.HUD.rawValue) self.addChild(scoreLabel) } func changeScore(changeBy: Int) { score += changeBy scoreLabel.text = String(score) } func addHero() { hero.position = getRandomPosition() addChild(hero) } func killHero() { hero.killLaser() hero.removeFromParent() } func addHive() { hive.position = CGPoint(x: size.width / 2, y: size.height / 2) addChild(hive) } func populateWithMobs() { for i in 1...3 { spawnMob() } } func spawnMob(spawnPosition: CGPoint) { let mob = Mob(position: spawnPosition) mobs.append(mob) addChild(mob) } func spawnMob() { spawnMob(getValidMobPosition()) } func getValidMobPosition() -> CGPoint { var possiblePosition: CGPoint var valid = true var distance:CGFloat = 0 do { possiblePosition = getRandomPosition(fromPoint: hero.position, minDistance: _magic.get("mobMinDistance") as CGFloat) valid = true for mob in mobs { distance = (mob.position - possiblePosition).length() if (distance <= (_magic.get("mobMinDistance") as CGFloat)) { valid = false } } } while !valid return possiblePosition } func respawnMob(spawnPosition: CGPoint) { let beforeSpawnAction = SKAction.runBlock({ self.hive.color = UIColor.whiteColor() }) let spawnAction = SKAction.runBlock({ self.spawnMob(spawnPosition) }) let afterSpawnAction = SKAction.runBlock({ self.hive.color = UIColor.blackColor() }) let waitAction = SKAction.waitForDuration(NSTimeInterval(_magic.get("mobRespawnTime") as Float)) runAction(SKAction.sequence([ beforeSpawnAction, waitAction, spawnAction, afterSpawnAction ])) } func killMob(mob: Mob) { mob.removeFromParent() var i = 0 for inArray in mobs { if inArray == mob { mobs.removeAtIndex(i) changeScore(100) } ++i } } func addDoor() { door.position = CGPoint(x: size.width / 2, y: size.height) addChild(door) } func populateWithLocks() { for i in 1...2 { addLock() } } func addLock() { let lock = Lock(position: getValidLockPosition()) locks.append(lock) addChild(lock) } func getValidLockPosition() -> CGPoint { var possiblePosition: CGPoint var valid = true var distance:CGFloat = 0 do { possiblePosition = getPossibleLockPosition() valid = true for lock in locks { distance = (lock.position - possiblePosition).length() if (distance <= (_magic.get("lockMinDistance") as CGFloat)) { valid = false } } } while !valid return possiblePosition } func getPossibleLockPosition() -> CGPoint { let randomPosition = getRandomPosition() var possiblePosition = CGPoint() let random = arc4random_uniform(4) + 1 if random == 1 { // Place on top possiblePosition = CGPoint(x: randomPosition.x, y: size.height) } else if random == 2 { // Place on right possiblePosition = CGPoint(x: size.width, y: randomPosition.y) } else if random == 3 { // Place on bottom possiblePosition = CGPoint(x: randomPosition.x, y: 0) } else { // Place on left possiblePosition = CGPoint(x: 0, y: randomPosition.y) } if checkIfInCorner(possiblePosition) || checkIfNearDoor(possiblePosition) { possiblePosition = getPossibleLockPosition() } return possiblePosition } func checkIfInCorner(possiblePosition: CGPoint) -> Bool { var inCorner = false let lockSize = _magic.get("lockWidth") as CGFloat let leftSide = (possiblePosition.x < lockSize) && ((possiblePosition.y > (size.height - lockSize)) || (possiblePosition.y < lockSize)) let rightSide = (possiblePosition.x > size.width - lockSize) && ((possiblePosition.y > (size.height - lockSize)) || (possiblePosition.y < lockSize)) if leftSide || rightSide { inCorner = true } return inCorner } func checkIfNearDoor(possiblePosition: CGPoint) -> Bool { var nearDoor = false let distance = (door.position - possiblePosition).length() if (distance <= (_magic.get("doorMinDistance") as CGFloat)) { nearDoor = true } return nearDoor } func checkLocksAreOpen() -> Bool { for lock in locks { if !lock.open { return false } } return true } func addMoveControl() { let moveControl = SKSpriteNode(texture: SKTexture(imageNamed: _magic.get("controlImage") as String), color: UIColor.yellowColor(), size: CGSize(width: _magic.get("controlSize") as CGFloat, height: _magic.get("controlSize") as CGFloat)) moveControl.position = CGPoint(x: _magic.get("controlCenter") as CGFloat, y: _magic.get("controlCenter") as CGFloat) moveControl.zPosition = CGFloat(ZIndex.MoveControl.rawValue) addChild(moveControl) } func getControlRelativeDirection(touchLocation: CGPoint) -> CGPoint { let controlCenter = CGPoint(x: _magic.get("controlCenter") as CGFloat, y: _magic.get("controlCenter") as CGFloat) return getRelativeDirection(controlCenter, destination: touchLocation) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { for touch in touches { let location = touch.locationInNode(self) // Move if left side touched if location.x < size.width / 2 { hero.facing = getControlRelativeDirection(location) hero.startMoving() } else { // Shoot if right side touched hero.shoot(self) } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { for touch in touches { let location = touch.locationInNode(self) // Stop moving hero when control no longer held if location.x < size.width / 2 { hero.stopMoving() } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { for touch in touches { let location = touch.locationInNode(self) // Continuously move hero if touch is held on left side if location.x < size.width / 2 { hero.facing = getControlRelativeDirection(location) } } } // Teleport hero on shake func onMotionShake(notification: NSNotification) { hero.teleport(self) } func heroDidCollideWithMob(mob: Mob) { let explosion = Explosion(node: hero) killHero() addChild(explosion) let endAction = SKAction.runBlock({ explosion.removeFromParent() --self.lives self.endgame() }) explosion.runAction(SKAction.sequence([ explosion.getAnimation(), endAction ])) } func heroDidCollideWithDoor() { if door.open { endgame() } } func laserDidCollideWithHero() { hero.killLaser() } func laserDidCollideWithMob(laser: Laser, mob: Mob) { laser.comeBack(hero) let explosion = Explosion(node: mob) killMob(mob) addChild(explosion) let endExplosionAction = SKAction.runBlock({ explosion.removeFromParent() }) explosion.runAction(SKAction.sequence([ explosion.getAnimation(), endExplosionAction ])) respawnMob(hive.position) } func laserDidCollideWithWall(laser: Laser) { laser.comeBack(hero) } func laserDidCollideWithLock(laser: Laser, lock: Lock) { laser.comeBack(hero) lock.unlock() if checkLocksAreOpen() { door.unlock() } } func laserDidCollideWithDoor(laser: Laser, door: Door) { if !checkLocksAreOpen() { door.blink() } } func didBeginContact(contact: SKPhysicsContact) { // Put bodies in ascending PhysicsCategory order var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // First, ensure both nodes are valid switch (firstBody.node?, secondBody.node?) { case let (.Some(firstNode), .Some(secondNode)): switch firstBody.categoryBitMask { case PhysicsCategory.Hero: switch secondBody.categoryBitMask { case PhysicsCategory.Mob: heroDidCollideWithMob(secondNode as Mob) case PhysicsCategory.ReturnLaser: laserDidCollideWithHero() case PhysicsCategory.Door: heroDidCollideWithDoor() default: break } case PhysicsCategory.Mob: switch secondBody.categoryBitMask { case PhysicsCategory.Laser: laserDidCollideWithMob(secondNode as Laser, mob: firstNode as Mob) default: break } case PhysicsCategory.Wall: switch secondBody.categoryBitMask { case PhysicsCategory.Laser: laserDidCollideWithWall(secondNode as Laser) default: break } case PhysicsCategory.Laser: switch secondBody.categoryBitMask { case PhysicsCategory.Lock: laserDidCollideWithLock(firstNode as Laser, lock: secondNode as Lock) case PhysicsCategory.Door: laserDidCollideWithDoor(firstNode as Laser, door: secondNode as Door) default: break } default: break } default: break } } override func update(currentTime: CFTimeInterval) { for mob in mobs { mob.nextAction(self) } if hero.moving { hero.move() } if let heroLaser = hero.laser { switch heroLaser.physicsBody!.categoryBitMask { case PhysicsCategory.Laser: heroLaser.move() case PhysicsCategory.ReturnLaser: heroLaser.moveBack(hero) default: break } } } func endgame() { hero.kill() if lives >= 0 { if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { if let skView = self.view { scene.score = score scene.lives = lives scene.startTime = startTime skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill skView.presentScene(scene) } } } else { if let scene = EndgameScene.unarchiveFromFile("EndgameScene") as? EndgameScene { if let skView = self.view { scene.score = score scene.startTime = startTime skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill skView.presentScene(scene) } } } } }
3b5d42ee83feac3c9e72243de1b313e5
28.977186
156
0.525051
false
false
false
false
proxpero/Endgame
refs/heads/master
Sources/Bitboard+Attacks.swift
mit
1
// // Bitboard+Attacks.swift // Endgame // // Created by Todd Olsen on 3/15/17. // // extension Bitboard { /// Returns the pawn pushes available for `color` in `self`. public func pawnPushes(for color: Color, empty: Bitboard) -> Bitboard { return (color.isWhite ? shifted(toward: .north) : shifted(toward: .south)) & empty } /// Returns moves available to `piece` in `self`. public func moves(for piece: Piece, obstacles: Bitboard = 0) -> Bitboard { var pawns: Bitboard = 0 if piece.kind.isPawn { pawns |= pawnPushes(for: piece.color, empty: ~obstacles) if Rank.pawnRank(for: piece.color).contains(bitboard: self) { pawns |= pawns.pawnPushes(for: piece.color, empty: ~obstacles) } } return pawns | attacks(for: piece, obstacles: obstacles) } /// Returns the attacks available to `piece` in `self`. public func attacks(for piece: Piece, obstacles: Bitboard = 0) -> Bitboard { let diagonalSquares: Bitboard = { let ne = self .filled(toward: .northeast, until: obstacles) .shifted(toward: .northeast) let nw = self .filled(toward: .northwest, until: obstacles) .shifted(toward: .northwest) let se = self .filled(toward: .southeast, until: obstacles) .shifted(toward: .southeast) let sw = self .filled(toward: .southwest, until: obstacles) .shifted(toward: .southwest) return ne | nw | se | sw }() let orthogonalSquares: Bitboard = { let n = self .filled(toward: .north, until: obstacles) .shifted(toward: .north) let s = self .filled(toward: .south, until: obstacles) .shifted(toward: .south) let e = self .filled(toward: .east, until: obstacles) .shifted(toward: .east) let w = self .filled(toward: .west, until: obstacles) .shifted(toward: .west) return n | s | e | w }() switch piece.kind { case .pawn: switch piece.color { case .white: return shifted(toward: .northeast) | shifted(toward: .northwest) case .black: return shifted(toward: .southeast) | shifted(toward: .southwest) } case .knight: return (((self << 17) | (self >> 15)) & ~File.a) | (((self << 10) | (self >> 06)) & ~(File.a | File.b)) | (((self << 15) | (self >> 17)) & ~File.h) | (((self << 06) | (self >> 10)) & ~(File.g | File.h)) case .bishop: return diagonalSquares case .rook: return orthogonalSquares case .queen: return diagonalSquares | orthogonalSquares case .king: let row = shifted(toward: .east) | shifted(toward: .west) let bitboard = self | row return row | bitboard.shifted(toward: .north) | bitboard.shifted(toward: .south) } } }
a5ff67b8c1adfb64c04cde68e0f0403b
32.252525
90
0.508809
false
false
false
false
enbaya/WebyclipSDK
refs/heads/master
WebyclipSDK/Classes/WebyclipPlayerCell.swift
mit
1
import youtube_ios_player_helper class WebyclipPlayerCell: UICollectionViewCell { // MARK: - IBOtlets @IBOutlet var mediaPlayer: YTPlayerView! @IBOutlet var mediaTitle: UILabel! @IBOutlet var mediaAuthor: UILabel! @IBOutlet var mediaProvider: UILabel! // MARK: - Private fileprivate var playerVars = [ "playsinline": 1, "showinfo": 0, "modestbranding": 1, "rel": 0, "fs": 0, "theme": "light", "color": "white" ] as [String : Any] fileprivate func updateUI() { self.mediaPlayer.isUserInteractionEnabled = false self.mediaPlayer.load(withVideoId: self.media.mediaId, playerVars: self.playerVars) self.mediaTitle.text = self.media.title self.mediaAuthor.text = self.media.author self.mediaProvider.text = formatProvider(self.media.provider) } fileprivate func formatProvider(_ provider: String) -> String { let prv: String switch(provider) { case "youtube": prv = "YouTube" break; default: prv = "Unknown provider" } return prv; } fileprivate func getMediaThumbnail(_ mediaId: String) -> UIImage { let url = URL(string: "https://img.youtube.com/vi/" + mediaId + "/mqdefault.jpg")! let data = try! Data(contentsOf: url) return UIImage(data: data)! } // MARK: - Public var media: WebyclipPlayerItem! { didSet { updateUI(); } } }
8b950ec857397d4e23cc3e4be622667c
27.375
91
0.571429
false
false
false
false
dnevera/IMProcessing
refs/heads/master
IMProcessing/Classes/Adjustments/IMPHSVFilter.swift
mit
1
// // IMPHSVFilter.swift // IMProcessing // // Created by denis svinarchuk on 22.12.15. // Copyright © 2015 Dehancer.photo. All rights reserved. // import Foundation import Metal import simd public extension IMProcessing{ public struct hsv { /// Ramps of HSV hextants in the HSV color wheel with overlaping levels public static let hueRamps:[float4] = [kIMP_Reds, kIMP_Yellows, kIMP_Greens, kIMP_Cyans, kIMP_Blues, kIMP_Magentas] /// Hextants aliases public static let reds = hueRamps[0] public static let yellows = hueRamps[1] public static let greens = hueRamps[2] public static let cyans = hueRamps[3] public static let blues = hueRamps[4] public static let magentas = hueRamps[5] /// Overlap factor public static var hueOverlapFactor:Float = 1.4 /// Hue range of the HSV color wheel private static let hueRange = Range<Int>(0..<360) } } public extension Float32{ // // Get HSV weight which uses to define how two close colors interfer between ech others // func overlapWeight(ramp ramp:float4, overlap:Float = IMProcessing.hsv.hueOverlapFactor) -> Float32 { var sigma = (ramp.z-ramp.y) var mu = (ramp.w+ramp.x)/2.0 if ramp.y>ramp.z { sigma = (IMProcessing.hsv.hueRange.endIndex.float-ramp.y+ramp.z) if (self >= 0.float) && (self <= IMProcessing.hsv.hueRange.endIndex.float/2.0) { mu = (IMProcessing.hsv.hueRange.endIndex.float-ramp.y-ramp.z) / 2.0 }else{ mu = (ramp.y+ramp.z) } } return self.gaussianPoint(fi: 1, mu: mu, sigma: sigma * overlap) } } public extension SequenceType where Generator.Element == Float32 { public func overlapWeightsDistribution(ramp ramp:float4, overlap:Float = IMProcessing.hsv.hueOverlapFactor) -> [Float32]{ var a = [Float32]() for i in self{ a.append(i.overlapWeight(ramp: ramp, overlap: overlap)) } return a } public func overlapWeightsDistribution(ramp ramp:float4, overlap:Float = IMProcessing.hsv.hueOverlapFactor) -> NSData { let f:[Float32] = overlapWeightsDistribution(ramp: ramp, overlap: overlap) as [Float32] return NSData(bytes: f, length: f.count) } } public func * (left:IMPHSVLevel,right:Float) -> IMPHSVLevel { return IMPHSVLevel(hue: left.hue * right, saturation: left.saturation * right, value: left.value * right) } public extension IMPHSVAdjustment{ public var reds: IMPHSVLevel{ get { return levels.0 } set{ levels.0 = newValue }} public var yellows: IMPHSVLevel{ get { return levels.1 } set{ levels.1 = newValue }} public var greens: IMPHSVLevel{ get { return levels.2 } set{ levels.2 = newValue }} public var cyans: IMPHSVLevel{ get { return levels.3 } set{ levels.3 = newValue }} public var blues: IMPHSVLevel{ get { return levels.4 } set{ levels.4 = newValue }} public var magentas:IMPHSVLevel{ get { return levels.5 } set{ levels.5 = newValue }} public subscript(index:Int) -> IMPHSVLevel { switch(index){ case 0: return levels.0 case 1: return levels.1 case 2: return levels.2 case 3: return levels.3 case 4: return levels.4 case 5: return levels.5 default: return master } } public mutating func hue(index index:Int, value newValue:Float){ switch(index){ case 0: levels.0.hue = newValue case 1: levels.1.hue = newValue case 2: levels.2.hue = newValue case 3: levels.3.hue = newValue case 4: levels.4.hue = newValue case 5: levels.5.hue = newValue default: master.hue = newValue } } public mutating func saturation(index index:Int, value newValue:Float){ switch(index){ case 0: levels.0.saturation = newValue case 1: levels.1.saturation = newValue case 2: levels.2.saturation = newValue case 3: levels.3.saturation = newValue case 4: levels.4.saturation = newValue case 5: levels.5.saturation = newValue default: master.saturation = newValue } } public mutating func value(index index:Int, value newValue:Float){ switch(index){ case 0: levels.0.value = newValue case 1: levels.1.value = newValue case 2: levels.2.value = newValue case 3: levels.3.value = newValue case 4: levels.4.value = newValue case 5: levels.5.value = newValue default: master.value = newValue } } } /// /// HSV adjustment filter /// public class IMPHSVFilter:IMPFilter,IMPAdjustmentProtocol{ /// Optimization level description /// /// - HIGH: default optimization uses when you need to accelerate hsv adjustment /// - NORMAL: hsv adjustments application without interpolation public enum optimizationLevel{ case HIGH case NORMAL } /// /// Default HSV adjustment /// public static let defaultAdjustment = IMPHSVAdjustment( master: IMPHSVFilter.level, levels: (IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level), blending: IMPBlending(mode: IMPBlendingMode.NORMAL, opacity: 1) ) /// HSV adjustment levels public var adjustment:IMPHSVAdjustment!{ didSet{ if self.optimization == .HIGH { adjustmentLut.blending = adjustment.blending updateBuffer(&adjustmentLutBuffer, context:context, adjustment:&adjustmentLut, size:sizeof(IMPAdjustment)) updateBuffer(&adjustmentBuffer, context:context_hsv3DLut, adjustment:&adjustment, size:sizeof(IMPHSVAdjustment)) applyHsv3DLut() } else { updateBuffer(&adjustmentBuffer, context:context, adjustment:&adjustment, size:sizeof(IMPHSVAdjustment)) } dirty = true } } /// /// Overlap colors in the HSV color wheel. Define the width of color overlaping. /// public var overlap:Float = IMProcessing.hsv.hueOverlapFactor { didSet{ hueWeights = IMPHSVFilter.defaultHueWeights(self.context, overlap: overlap) if self.optimization == .HIGH { applyHsv3DLut() } dirty = true } } /// Create HSV adjustment filter. /// /// - .HIGH optimization level uses to reduce HSV adjustment computation per pixel. /// only defult 64x64x64 LUT creates and then applies to final image. With this /// option an image modification can lead to the appearance of artifacts in the image. /// .HIGH level can use for live-view mode of image processing /// /// - .Normal uses for more precise HSV adjustments /// /// - parameter context: execution context /// - parameter optimization: optimization level /// public required init(context: IMPContext, optimization:optimizationLevel) { super.init(context: context) self.optimization = optimization if self.optimization == .HIGH { hsv3DlutTexture = hsv3DLut(self.rgbCubeSize) kernel_hsv3DLut = IMPFunction(context: self.context_hsv3DLut, name: "kernel_adjustHSV3DLut") kernel = IMPFunction(context: self.context, name: "kernel_adjustLutD3D") } else{ kernel = IMPFunction(context: self.context, name: "kernel_adjustHSV") } addFunction(kernel) defer{ adjustment = IMPHSVFilter.defaultAdjustment } //NSLog("\(self): \(self.optimization )") } /// Create HSV adjustment filter with default optimization level .NORMAL /// /// - parameter context: device execution context /// public convenience required init(context: IMPContext) { self.init(context: context, optimization:context.isLazy ? .HIGH : .NORMAL) } public override func configure(function: IMPFunction, command: MTLComputeCommandEncoder) { if kernel == function { if self.optimization == .HIGH { command.setTexture(hsv3DlutTexture, atIndex: 2) command.setBuffer(adjustmentLutBuffer, offset: 0, atIndex: 0) } else{ command.setTexture(hueWeights, atIndex: 2) command.setBuffer(adjustmentBuffer, offset: 0, atIndex: 0) } } } /// Create new hue color overlaping weights for the HSV color wheel /// /// - parameter context: device execution context /// /// - returns: new overlaping weights public static func defaultHueWeights(context:IMPContext, overlap:Float) -> MTLTexture { let width = IMProcessing.hsv.hueRange.endIndex let textureDescriptor = MTLTextureDescriptor() textureDescriptor.textureType = .Type1DArray; textureDescriptor.width = width; textureDescriptor.height = 1; textureDescriptor.depth = 1; textureDescriptor.pixelFormat = .R32Float; textureDescriptor.arrayLength = IMProcessing.hsv.hueRamps.count; textureDescriptor.mipmapLevelCount = 1; let region = MTLRegionMake2D(0, 0, width, 1); let hueWeights = context.device.newTextureWithDescriptor(textureDescriptor) let hues = Float.range(0..<width) for i in 0..<IMProcessing.hsv.hueRamps.count{ let ramp = IMProcessing.hsv.hueRamps[i] var data = hues.overlapWeightsDistribution(ramp: ramp, overlap: overlap) as [Float32] hueWeights.replaceRegion(region, mipmapLevel:0, slice:i, withBytes:&data, bytesPerRow:sizeof(Float32) * width, bytesPerImage:0) } return hueWeights; } public var adjustmentBuffer:MTLBuffer? public var kernel:IMPFunction! public var rgbCube:MTLTexture? { return hsv3DlutTexture } public var rgbCubeSize = 64 { didSet{ if self.optimization == .HIGH { adjustmentLut.blending = adjustment.blending updateBuffer(&adjustmentLutBuffer, context:context, adjustment:&adjustmentLut, size:sizeof(IMPAdjustment)) updateBuffer(&adjustmentBuffer, context:context_hsv3DLut, adjustment:&adjustment, size:sizeof(IMPHSVAdjustment)) applyHsv3DLut() dirty = true } } } internal static let level:IMPHSVLevel = IMPHSVLevel(hue: 0.0, saturation: 0, value: 0) internal lazy var hueWeights:MTLTexture = { return IMPHSVFilter.defaultHueWeights(self.context, overlap: IMProcessing.hsv.hueOverlapFactor) }() private var adjustmentLut = IMPAdjustment(blending: IMPBlending(mode: IMPBlendingMode.NORMAL, opacity: 1)) internal var adjustmentLutBuffer:MTLBuffer? private var optimization:optimizationLevel! // // Convert HSV transformation to 3D-rgb lut-cube // // private var kernel_hsv3DLut:IMPFunction! private lazy var context_hsv3DLut:IMPContext = {return self.context }() private func applyHsv3DLut(){ context_hsv3DLut.execute{ (commandBuffer) -> Void in let width = self.hsv3DlutTexture!.width let height = self.hsv3DlutTexture!.height let depth = self.hsv3DlutTexture!.depth let threadgroupCounts = MTLSizeMake(4, 4, 4) let threadgroups = MTLSizeMake(width/4, height/4, depth/4) let commandEncoder = commandBuffer.computeCommandEncoder() commandEncoder.setComputePipelineState(self.kernel_hsv3DLut.pipeline!) commandEncoder.setTexture(self.hsv3DlutTexture, atIndex:0) commandEncoder.setTexture(self.hueWeights, atIndex:1) commandEncoder.setBuffer(self.adjustmentBuffer, offset: 0, atIndex: 0) commandEncoder.dispatchThreadgroups(threadgroups, threadsPerThreadgroup:threadgroupCounts) commandEncoder.endEncoding() #if os(OSX) let blitEncoder = commandBuffer.blitCommandEncoder() blitEncoder.synchronizeResource(self.hsv3DlutTexture!) blitEncoder.endEncoding() #endif } } private var hsv3DlutTexture:MTLTexture? private func hsv3DLut(dimention:Int) -> MTLTexture { let textureDescriptor = MTLTextureDescriptor() textureDescriptor.textureType = .Type3D textureDescriptor.width = dimention textureDescriptor.height = dimention textureDescriptor.depth = dimention textureDescriptor.pixelFormat = .RGBA8Unorm textureDescriptor.arrayLength = 1; textureDescriptor.mipmapLevelCount = 1; let texture = context_hsv3DLut.device.newTextureWithDescriptor(textureDescriptor) return texture } }
08aece461483dffa233eb2a06c5a6283
33.855696
139
0.606741
false
false
false
false
jindulys/Leetcode_Solutions_Swift
refs/heads/master
Sources/LinkedList/86_PartitionList.swift
mit
1
// // 83_PartitionList.swift // LeetcodeSwift // // Created by yansong li on 2016-11-07. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:86 Partition List URL: https://leetcode.com/problems/partition-list/ Space: O(1) Time: O(N) */ class PartitionList_Solution { func partition(_ head: ListNode?, _ x: Int) -> ListNode? { let prevDummy = ListNode(0) var prev: ListNode? = prevDummy let postDummy = ListNode(0) var post: ListNode? = postDummy var checkingNode = head while let validCheckingNode = checkingNode { checkingNode = validCheckingNode.next if validCheckingNode.val < x { prev?.next = validCheckingNode prev = prev?.next } else { post?.next = validCheckingNode post = post?.next } } post?.next = nil prev?.next = postDummy.next return prevDummy.next } }
f713f61b220516b8587a693b00f85bb0
22.333333
60
0.640659
false
false
false
false
daxiangfei/RTSwiftUtils
refs/heads/master
RTSwiftUtils/Extension/NSAttributedStringExtension.swift
mit
1
// // NSAttributedStringExtension.swift // RongTeng // // Created by rongteng on 16/5/17. // Copyright © 2016年 Mike. All rights reserved. // import Foundation import UIKit extension NSAttributedString { ///二部分 色值和字体都不同 public class func attributedOfTwoPart(onePartTitle:String,onePartForegroundColor:UIColor,onePartFontSize:CGFloat,twoPartTitle:String,twoPartForegroundColor:UIColor,twoPartFontSize:CGFloat) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.foregroundColor:onePartForegroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: onePartFontSize)] let oneAtt = NSAttributedString(string: onePartTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:twoPartForegroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: twoPartFontSize)] let twoAtt = NSAttributedString(string: twoPartTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } ///二部分 色值相同 字体不同 public class func attributedOfTwoPartWithSameColor(foregroundColor:UIColor,onePartTitle:String,onePartFontSize:CGFloat,twoPartTitle:String,twoPartFontSize:CGFloat) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.foregroundColor:foregroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: onePartFontSize)] let oneAtt = NSAttributedString(string: onePartTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:foregroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: twoPartFontSize)] let twoAtt = NSAttributedString(string: twoPartTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } ///创建一个 有下划线的文字 public class func attributedOfUnderLine(title:String,titleColor:UIColor) -> NSAttributedString { let oneAttDic = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor:titleColor, NSAttributedStringKey.foregroundColor:titleColor] as [NSAttributedStringKey : Any] let oneAtt = NSAttributedString(string: title, attributes: oneAttDic) return oneAtt } ///下划线和正常类型 public class func attributedForUnderLineAndNormal(oneTitle:String,oneTitleColor:UIColor,twoTitle:String,twoTitleColor:UIColor) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor:oneTitleColor, NSAttributedStringKey.foregroundColor:oneTitleColor] as [NSAttributedStringKey : Any] let oneAtt = NSAttributedString(string: oneTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:twoTitleColor] let twoAtt = NSAttributedString(string: twoTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } }
6165063dd0d47c71158b22e0541dec9e
33.297872
214
0.766439
false
false
false
false
FrainL/FxJSON
refs/heads/master
FxJSONTests/ProtocolTests.swift
mit
1
// // SerializeTests.swift // SweeftyJSON // // Created by Frain on 8/27/16. // // The MIT License (MIT) // // Copyright (c) 2016 Frain // // 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 class ProtocolTests: XCTestCase { func testCodable() { struct A: JSONDecodable, JSONEncodable { let name: String let age: Int let gender: Gender // init(decode json: JSON) throws { // name = try json["name"]< // age = try json["age"]< // gender = try json["gender"]< // } enum Gender: Int, JSONCodable { case boy case girl } } let json = ["name": "name", "age": 10, "gender": 0] as JSON guard let a = A.init(json) else { XCTFail(); return } XCTAssertEqual(a.age, 10) XCTAssertEqual(a.name, "name") XCTAssertEqual(a.gender.rawValue, A.Gender.boy.rawValue) XCTAssertEqual(a.json, json) XCTAssertThrowsError(try A.init(decode: ["name": "", "age": "10"])) { (error) in guard case JSON.Error.typeMismatch = error else { XCTFail(); return } } } func testError() { } }
4a2e95e265b20f639ce070853585f68a
30.913043
84
0.655313
false
true
false
false
burla69/PayDay
refs/heads/master
PayDay/QRScanningViewController.swift
mit
1
// // QRScanningViewController.swift // PayDay // // Created by Oleksandr Burla on 3/15/16. // Copyright © 2016 Oleksandr Burla. All rights reserved. // import UIKit import AVFoundation protocol QRScanningViewControllerDelegate { func qrCodeFromQRViewController(string: String) func goFromQRCode() } class QRScanningViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { @IBOutlet weak var cameraView: UIView! var delegate: QRScanningViewControllerDelegate! var captureSession: AVCaptureSession? var videoPreviewLayer: AVCaptureVideoPreviewLayer? var qrCodeFrameView: UIView? var isFrontCamera = true override func viewDidLoad() { super.viewDidLoad() guard let captureDevice = (AVCaptureDevice.devices() .filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Back}) .first as? AVCaptureDevice else { return } do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) cameraView.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor qrCodeFrameView.layer.borderWidth = 3 cameraView.addSubview(qrCodeFrameView) cameraView.bringSubviewToFront(qrCodeFrameView) } } catch { print(error) return } isFrontCamera = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if metadataObjects == nil || metadataObjects.count == 0 { qrCodeFrameView?.frame = CGRectZero print("QR Code is not detected") return } let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj) qrCodeFrameView?.frame = barCodeObject!.bounds var token: dispatch_once_t = 0 dispatch_once(&token) { if metadataObj.stringValue != nil { print("QR code\(metadataObj.stringValue)") self.delegate.qrCodeFromQRViewController(metadataObj.stringValue) } self.dismissViewControllerAnimated(true, completion: { self.delegate.goFromQRCode() }) } } @IBAction func useKeyPadPressed(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func changeCamera(sender: AnyObject) { if isFrontCamera { guard let captureDevice = (AVCaptureDevice.devices() .filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Back}) .first as? AVCaptureDevice else { return } do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) cameraView.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor qrCodeFrameView.layer.borderWidth = 3 cameraView.addSubview(qrCodeFrameView) cameraView.bringSubviewToFront(qrCodeFrameView) } } catch { print(error) return } isFrontCamera = false } else { guard let captureDevice = (AVCaptureDevice.devices() .filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Front}) .first as? AVCaptureDevice else { return } do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) cameraView.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor qrCodeFrameView.layer.borderWidth = 3 cameraView.addSubview(qrCodeFrameView) cameraView.bringSubviewToFront(qrCodeFrameView) } } catch { print(error) return } isFrontCamera = true } } }
9c2e8e94b35040cce5a49c25ac115c60
35.33945
162
0.577001
false
false
false
false
cuappdev/eatery
refs/heads/master
Eatery/Onboarding/Controllers/OnboardingInfoViewController.swift
mit
1
// // OnboardingInfoViewController.swift // Eatery // // Created by Reade Plunkett on 11/15/19. // Copyright © 2019 CUAppDev. All rights reserved. // import Lottie import UIKit class OnboardingInfoViewController: OnboardingViewController { private let stackView = UIStackView() private let animationView = AnimationView() private let nextButton = UIButton() private let animation: String init(title: String, subtitle: String, animation: String) { self.animation = animation super.init(title: title, subtitle: subtitle) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setUpStackView() setUpAnimationView() setUpButton() contentView.snp.makeConstraints { make in make.width.equalToSuperview() make.height.equalTo(stackView) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.async { self.animationView.play() } } private func setUpStackView() { stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .center stackView.spacing = 40 contentView.addSubview(stackView) stackView.snp.makeConstraints { make in make.center.width.equalToSuperview() } } private func setUpAnimationView() { animationView.animation = Animation.named(animation) animationView.contentMode = .scaleAspectFit animationView.transform = CGAffineTransform(scaleX: 2, y: 2) stackView.addArrangedSubview(animationView) animationView.snp.makeConstraints { make in make.height.equalTo(128) } } private func setUpButton() { nextButton.layer.borderWidth = 2 nextButton.layer.borderColor = UIColor.white.cgColor nextButton.layer.cornerRadius = 30 nextButton.setTitle("NEXT", for: .normal) nextButton.titleLabel?.font = .systemFont(ofSize: 17, weight: .heavy) nextButton.titleLabel?.textColor = .white nextButton.addTarget(self, action: #selector(didTapNextButton), for: .touchUpInside) stackView.addArrangedSubview(nextButton) nextButton.snp.makeConstraints { make in make.width.equalTo(240) make.height.equalTo(60) } } @objc private func didTapNextButton(sender: UIButton) { delegate?.onboardingViewControllerDidTapNext(self) } }
1f0abc7480f15e73aff9d8333132360d
27.376344
92
0.654415
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Views/Common/Data Rows/Callouts/CalloutsNib.swift
mit
1
// // CalloutsNib.swift // MEGameTracker // // Created by Emily Ivie on 6/9/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit @IBDesignable open class CalloutsNib: SimpleArrayDataRowNib { override open class func loadNib(heading: String? = nil, cellNibs: [String] = []) -> CalloutsNib? { let bundle = Bundle(for: CalloutsNib.self) if let view = bundle.loadNibNamed("CalloutsNib", owner: self, options: nil)?.first as? CalloutsNib { let bundle = Bundle(for: CalloutsNib.self) for nib in cellNibs { view.tableView?.register(UINib(nibName: nib, bundle: bundle), forCellReuseIdentifier: nib) } return view } return nil } }
59ee69a4a7b22dd5c45fafd8db8fe2a3
27.291667
103
0.698085
false
false
false
false
marchinram/SwiftChip-8
refs/heads/master
SwiftChip-8/SettingsManager.swift
mit
1
// // SettingsManager.swift // SwiftChip-8 // // Created by Brian Rojas on 8/24/17. // Copyright © 2017 Brian Rojas. All rights reserved. // import Foundation import GLKit class SettingsManager { public static let instance = SettingsManager() public static let yellowishPixelColor = #colorLiteral(red: 1, green: 0.768627451, blue: 0, alpha: 1) public static let orangeBackgroundColor = #colorLiteral(red: 0.6901960784, green: 0.2901960784, blue: 0, alpha: 1) private init() { let pixelRGBA: (Float, Float, Float, Float) = SettingsManager.yellowishPixelColor.separate() let bgRGBA: (Float, Float, Float, Float) = SettingsManager.orangeBackgroundColor.separate() UserDefaults.standard.register(defaults:[ "pixelColorR": pixelRGBA.0, "pixelColorG": pixelRGBA.1, "pixelColorB": pixelRGBA.2, "pixelColorA": pixelRGBA.3, "backgroundColorR": bgRGBA.0, "backgroundColorG": bgRGBA.1, "backgroundColorB": bgRGBA.2, "backgroundColorA": bgRGBA.3, "buzzerNote": Buzzer.Frequency.C4.rawValue, "buzzerVolume": 1.0 ]) } public var pixelColor: UIColor { get { let r = CGFloat(UserDefaults.standard.float(forKey: "pixelColorR")) let g = CGFloat(UserDefaults.standard.float(forKey: "pixelColorG")) let b = CGFloat(UserDefaults.standard.float(forKey: "pixelColorB")) let a = CGFloat(UserDefaults.standard.float(forKey: "pixelColorA")) return UIColor(red: r, green: g, blue: b, alpha: a) } set { let rgba: (CGFloat, CGFloat, CGFloat, CGFloat) = newValue.separate() UserDefaults.standard.set(rgba.0, forKey: "pixelColorR") UserDefaults.standard.set(rgba.1, forKey: "pixelColorG") UserDefaults.standard.set(rgba.2, forKey: "pixelColorB") UserDefaults.standard.set(rgba.3, forKey: "pixelColorA") } } public var backgroundColor: UIColor { get { let r = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorR")) let g = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorG")) let b = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorB")) let a = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorA")) return UIColor(red: r, green: g, blue: b, alpha: a) } set { let rgba: (CGFloat, CGFloat, CGFloat, CGFloat) = newValue.separate() UserDefaults.standard.set(rgba.0, forKey: "backgroundColorR") UserDefaults.standard.set(rgba.1, forKey: "backgroundColorG") UserDefaults.standard.set(rgba.2, forKey: "backgroundColorB") UserDefaults.standard.set(rgba.3, forKey: "backgroundColorA") } } public var buzzerNote: Buzzer.Frequency { get { let rawValue = UserDefaults.standard.float(forKey: "buzzerNote") return Buzzer.Frequency(rawValue: rawValue) ?? Buzzer.Frequency.C4 } set { UserDefaults.standard.set(newValue.rawValue, forKey: "buzzerNote") } } public var buzzerVolume: Float { get { return UserDefaults.standard.float(forKey: "buzzerVolume") } set { UserDefaults.standard.set(newValue, forKey: "buzzerVolume") } } } extension UIColor { var glkVector4: GLKVector4 { let rgba: (Float, Float, Float, Float) = separate() return GLKVector4Make(rgba.0, rgba.1, rgba.2, rgba.3) } var floatTuple: (Float, Float, Float, Float) { return separate() } fileprivate func separate<T: BinaryFloatingPoint>() -> (T, T, T, T) { var r: CGFloat = 0.0 var g: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 getRed(&r, green: &g, blue: &b, alpha: &a) return (T(Float(r)), T(Float(g)), T(Float(b)), T(Float(a))) } }
f9b125172ac197fd7e8013b6be7f5b89
35.6875
118
0.602823
false
false
false
false
steelwheels/Canary
refs/heads/master
Source/CNEdge.swift
gpl-2.0
1
/** * @file CNEdge.swift * @brief Define CNEdge class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import Foundation public typealias CNWeakEdgeReference = CNWeakReference<CNEdge> /* * Note: The owner of the edge is a CNGraph */ public class CNEdge: Equatable { private var mUniqueId: Int public var uniqueId: Int { get { return mUniqueId }} public weak var fromNode: CNNode? public weak var toNode: CNNode? public var didVisited: Bool public init(uniqueId uid: Int){ mUniqueId = uid fromNode = nil toNode = nil didVisited = false } } public func == (left : CNEdge, right : CNEdge) -> Bool { return left.uniqueId == right.uniqueId }
c6a7cc9250e3cb1a8255f24217587e1a
18.571429
62
0.70219
false
false
false
false
hsuanan/Mr-Ride-iOS
refs/heads/master
Mr-Ride/Model/StationDataManagement.swift
mit
1
// // StationDataManagement.swift // Mr-Ride // // Created by Hsin An Hsu on 7/11/16. // Copyright © 2016 AppWorks School HsinAn Hsu. All rights reserved. // import Foundation import Alamofire import CoreData import CoreLocation protocol JSONDataDelegation: class { func didReceiveDataFromServer() } struct StationModel{ var station: String = "" var district: String = "" var location: String = "" var availableBikesNumber: Int = 0 var availableDocks: Int = 0 var latitude: Double = 0.0 var longitude: Double = 0.0 } class StationDataManager { static let sharedDataManager = StationDataManager() var stationArray = [StationModel]() weak var delegate: JSONDataDelegation? func getBikeDataFromServer(){ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0)){ Alamofire.request( .GET, "http://data.taipei/youbike") .validate() .responseJSON { response in guard let json = response.result.value as? [String: AnyObject] else{ print (response.response) return } self.stationArray.removeAll() self.readJSONObject(json) dispatch_async(dispatch_get_main_queue()) { [weak self] in self?.delegate?.didReceiveDataFromServer() } print (response.response) } } } func readJSONObject(json: [String: AnyObject]){ guard let data = json["retVal"] as? [String:AnyObject] else { print("readJSONObject error") return } for value in data.values { guard let station = value["snaen"] as? String, let district = value["sareaen"] as? String, let location = value["aren"] as? String, let availableBikesNumber = value["sbi"] as? String, let availableDocks = value["bemp"] as? String, let latitude = value["lat"] as? String, let longitude = value["lng"] as? String else { print ("transJSONtype error") continue } stationArray.append( StationModel( station: station, district: district, location: location, availableBikesNumber: Int(availableBikesNumber)!, availableDocks: Int(availableDocks)!, latitude: Double(latitude)!, longitude: Double(longitude)!)) } } }
ef97547da981388888f1818fd17ea5cf
28.356436
82
0.496964
false
false
false
false
SequencingDOTcom/oAuth2-Code-Example-.NET
refs/heads/master
swift/Pods/sequencing-oauth-api-swift/Pod/SQToken.swift
mit
4
// // SQToken.swift // Copyright © 2015-2016 Sequencing.com. All rights reserved // import Foundation public class SQToken: NSObject { public var accessToken = String() public var expirationDate = NSDate() public var tokenType = String() public var scope = String() public var refreshToken = String() }
fa1f72ab2351021a0b7106e135bbb463
21.3125
61
0.635854
false
false
false
false
chernyog/CYWeibo
refs/heads/master
CYWeibo/CYWeibo/CYWeibo/Classes/UI/Home/StatusCell.swift
mit
1
// // StatusCell.swift // CYWeibo // // Created by 陈勇 on 15/3/6. // Copyright (c) 2015年 zhssit. All rights reserved. // import UIKit class StatusCell: UITableViewCell { // MARK: - 控件列表 /// 头像 @IBOutlet weak var iconImageView: UIImageView! /// 姓名 @IBOutlet weak var nameLabel: UILabel! /// 会员图标 @IBOutlet weak var memberImageView: UIImageView! /// 认证图标 @IBOutlet weak var vipImageView: UIImageView! /// 微博发表时间 @IBOutlet weak var timeLabel: UILabel! /// 微博来源 @IBOutlet weak var sourceLabel: UILabel! /// 微博正文 @IBOutlet weak var contentLabel: UILabel! /// 微博配图 @IBOutlet weak var pictureView: UICollectionView! /// 配图视图的布局 @IBOutlet weak var pictureLayout: UICollectionViewFlowLayout! /// 配图视图的宽 @IBOutlet weak var pictureViewWidth: NSLayoutConstraint! /// 配图视图的高 @IBOutlet weak var pictureViewHeight: NSLayoutConstraint! /// 底部的工具条 @IBOutlet weak var bottomView: UIView! /// 转发微博文字 @IBOutlet weak var forwardContentLabel: UILabel! // MARK: - 成员变量 /// 微博模型 - 设置微博数据 var status: Status? { didSet{ self.nameLabel.text = status!.user!.name self.timeLabel.text = status!.created_at self.sourceLabel.text = status!.source?.getHrefText() // self.contentLabel.text = status!.text self.contentLabel.attributedText = status!.text?.emotionString() ?? NSAttributedString(string: status!.text ?? "") if let iconUrl = status?.user?.profile_image_url { NetworkManager.sharedManager.requestImage(iconUrl) { (result, error) -> () in if let image = result as? UIImage { self.iconImageView.image = image } } } // 计算微博配图的尺寸 let result = self.calcPictureViewSize(status!) self.pictureLayout.itemSize = result.itemSize self.pictureViewWidth.constant = result.viewSize.width self.pictureViewHeight.constant = result.viewSize.height // 强制刷新界面 self.pictureView.reloadData() // 设置转发微博文字 if status?.retweeted_status != nil { forwardContentLabel.text = status!.retweeted_status!.user!.name! + ":" + status!.retweeted_status!.text! } } } override func awakeFromNib() { super.awakeFromNib() self.contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 30 self.forwardContentLabel?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 30 } /// 计算微博配图的尺寸 /// /// :param: status 微博实体 /// /// :returns: (itemSize,viewSize) func calcPictureViewSize(status: Status) -> (itemSize: CGSize, viewSize: CGSize) { let defaultWH: CGFloat = 90 // 默认的图片大小 var itemSize = CGSize(width: defaultWH, height: defaultWH) // 默认PictureView大小 var viewSize = CGSizeZero // 计算微博配图的个数 var count = status.pictureUrls?.count ?? 0 // 图片间的间距 let margin: CGFloat = 10 if count == 0 { return (itemSize, viewSize) } if count == 1 { // 如果只有一张图,则按照默认的尺寸显示 let path = NetworkManager.sharedManager.fullImageCachePathByMD5(status.pictureUrls![0].thumbnail_pic!) if let image = UIImage(contentsOfFile: path) { return (image.size, image.size) } else { return (itemSize, viewSize) } } if count == 4 { viewSize = CGSize(width: defaultWH * 2, height: defaultWH * 2) return (itemSize, viewSize) } else { // 行下标 let row = (count - 1) / 3 viewSize = CGSize(width: defaultWH * 3 + margin * 2, height: defaultWH * (CGFloat(row) + 1) + margin * CGFloat(row)) } return (itemSize, viewSize) } /// 返回可重用标识符 class func cellIdentifier(status: Status) -> String { if status.retweeted_status != nil { // 转发微博 return "ForwardCell" } else { // 原创微博 return "HomeCell" } } func cellHeight(status: Status) -> CGFloat { // 设置微博数据 self.status = status // 强制刷新布局 layoutIfNeeded() // 返回cell的高度 return CGRectGetMaxY(self.bottomView.frame) } /// 选中图片的闭包回调 var photoDidSelected: ((status: Status, photoIndex: Int) -> ())? } extension StatusCell: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 配图的数量 // println("配图的数量 count=\(status?.pictureUrls?.count)") return status?.pictureUrls?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureCell", forIndexPath: indexPath) as! PictureCell // 设置配图的图像路径 cell.urlString = status!.pictureUrls![indexPath.item].thumbnail_pic return cell } // 选中行事件 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if self.photoDidSelected != nil { self.photoDidSelected!(status: status!, photoIndex: indexPath.item) } } } /// 配图cell class PictureCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! /// 图像的 url 字符串 var urlString: String? { didSet { // 1. 图像缓存路径 let path = NetworkManager.sharedManager.fullImageCachePathByMD5(urlString!) // println("path=\(path)") // 2. 实例化图像 let image = UIImage(contentsOfFile: path) imageView.image = image } } }
2a84144f5b4f7bc33e9376d88d99ee62
28.519417
130
0.586581
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Mocks/MockSystemInfo.swift
mit
1
// // MockSystemInfo.swift // PurchasesTests // // Created by Andrés Boedo on 7/20/20. // Copyright © 2020 Purchases. All rights reserved. // import Foundation @testable import RevenueCat // Note: this class is implicitly `@unchecked Sendable` through its parent // even though it's not actually thread safe. class MockSystemInfo: SystemInfo { var stubbedIsApplicationBackgrounded: Bool? var stubbedIsSandbox: Bool? convenience init(finishTransactions: Bool, storeKit2Setting: StoreKit2Setting = .default) { // swiftlint:disable:next force_try try! self.init(platformInfo: nil, finishTransactions: finishTransactions, storeKit2Setting: storeKit2Setting) } override func isApplicationBackgrounded(completion: @escaping (Bool) -> Void) { completion(stubbedIsApplicationBackgrounded ?? false) } var stubbedIsOperatingSystemAtLeastVersion: Bool? var stubbedCurrentOperatingSystemVersion: OperatingSystemVersion? override public func isOperatingSystemAtLeast(_ version: OperatingSystemVersion) -> Bool { if let stubbedIsOperatingSystemAtLeastVersion = self.stubbedIsOperatingSystemAtLeastVersion { return stubbedIsOperatingSystemAtLeastVersion } if let currentVersion = self.stubbedCurrentOperatingSystemVersion { return currentVersion >= version } return true } override var isSandbox: Bool { return self.stubbedIsSandbox ?? super.isSandbox } } extension OperatingSystemVersion: Comparable { public static func < (lhs: OperatingSystemVersion, rhs: OperatingSystemVersion) -> Bool { if lhs.majorVersion == rhs.majorVersion { if lhs.minorVersion == rhs.minorVersion { return lhs.patchVersion < rhs.patchVersion } else { return lhs.minorVersion < rhs.minorVersion } } else { return lhs.majorVersion < rhs.majorVersion } } public static func == (lhs: OperatingSystemVersion, rhs: OperatingSystemVersion) -> Bool { return ( lhs.majorVersion == rhs.majorVersion && lhs.minorVersion == rhs.minorVersion && lhs.patchVersion == rhs.patchVersion ) } }
da5c29d47ccc9901f1ca1f5a48f6036e
31.472222
101
0.665954
false
false
false
false
pkrawat1/TravelApp-ios
refs/heads/master
TravelApp/View/SearchTripCell.swift
mit
1
// // SearchTripCell.swift // TravelApp // // Created by Nitesh on 03/02/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class SearchTripCell: BaseCell { var trip: Trip? { didSet { print(trip!) userNameLabel.text = trip?.user?.name durationLabel.text = trip?.created_at?.relativeDate() tripNameLabel.text = trip?.name setupThumbnailImage() setupProfileImage() } } func setupThumbnailImage() { if let thumbnailImageUrl = trip?.thumbnail_image_url { thumbnailImageView.loadImageUsingUrlString(urlString: thumbnailImageUrl, width: Float(thumbnailImageView.frame.width)) } let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(showTripDetail)) thumbnailImageView.isUserInteractionEnabled = true thumbnailImageView.addGestureRecognizer(tapGestureRecognizer) } func showTripDetail() { let tripDetailViewCtrl = TripDetailViewController() store.dispatch(SelectTrip(tripId: (trip?.id!)!)) SharedData.sharedInstance.homeController?.present(tripDetailViewCtrl, animated: true, completion: nil) } func setupProfileImage() { if let profileImageURL = trip?.user?.profile_pic?.url { userProfileImageView.loadImageUsingUrlString(urlString: profileImageURL, width: Float(userProfileImageView.frame.width)) } } let thumbnailImageView: CustomImageView = { let imageView = CustomImageView() imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.image = UIImage(named: "") imageView.backgroundColor = UIColor.black imageView.alpha = 0.5 return imageView }() let userProfileImageView: CustomImageView = { let imageView = CustomImageView() imageView.image = UIImage(named: "") imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = 22 imageView.layer.masksToBounds = true // imageView.backgroundColor = UIColor.blue return imageView }() let likeButton: UIButton = { let ub = UIButton(type: .system) ub.setImage(UIImage(named: "like"), for: .normal) ub.tintColor = UIColor.gray ub.translatesAutoresizingMaskIntoConstraints = false // ub.backgroundColor = UIColor.red return ub }() let userNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.font = label.font.withSize(14) label.textColor = UIColor.white // label.backgroundColor = UIColor.green return label }() let durationLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.textColor = UIColor.white // label.backgroundColor = UIColor.yellow label.font = label.font.withSize(10) return label }() let tripNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.font = label.font.withSize(25) label.numberOfLines = 2 label.textColor = UIColor.white label.textAlignment = .center // label.backgroundColor = UIColor.green return label }() override func setupViews() { addSubview(thumbnailImageView) addSubview(userProfileImageView) addSubview(userNameLabel) addSubview(durationLabel) addSubview(likeButton) addSubview(tripNameLabel) thumbnailImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true thumbnailImageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true thumbnailImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true userProfileImageView.bottomAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: -10).isActive = true userProfileImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true userProfileImageView.leftAnchor.constraint(equalTo: thumbnailImageView.leftAnchor, constant: 10).isActive = true userProfileImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true userNameLabel.topAnchor.constraint(equalTo: userProfileImageView.topAnchor).isActive = true userNameLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true userNameLabel.rightAnchor.constraint(equalTo: likeButton.leftAnchor, constant: -10).isActive = true userNameLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true durationLabel.topAnchor.constraint(equalTo: userNameLabel.bottomAnchor, constant: 4).isActive = true durationLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true durationLabel.rightAnchor.constraint(equalTo: likeButton.leftAnchor, constant: -10).isActive = true durationLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true likeButton.bottomAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: -10).isActive = true likeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true likeButton.rightAnchor.constraint(equalTo: thumbnailImageView.rightAnchor, constant: -10).isActive = true likeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true tripNameLabel.widthAnchor.constraint(equalTo: thumbnailImageView.widthAnchor, constant: -20).isActive = true tripNameLabel.centerYAnchor.constraint(equalTo: thumbnailImageView.centerYAnchor).isActive = true tripNameLabel.centerXAnchor.constraint(equalTo: thumbnailImageView.centerXAnchor).isActive = true tripNameLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true } }
274b78d90a0bef12e0ed7a32655a9c48
40.056962
132
0.683675
false
false
false
false
russbishop/swift
refs/heads/master
stdlib/public/SDK/UIKit/UIKit_FoundationExtensions.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation @_exported import UIKit // UITableView extensions public extension IndexPath { /// Initialize for use with `UITableView` or `UICollectionView`. public init(row: Int, section: Int) { self.init(indexes: [section, row]) } /// The section of this index path, when used with `UITableView`. /// /// - precondition: The index path must have exactly two elements. public var section: Int { get { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") return self[0] } set { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") self[0] = newValue } } /// The row of this index path, when used with `UITableView`. /// /// - precondition: The index path must have exactly two elements. public var row: Int { get { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") return self[1] } set { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") self[1] = newValue } } } // UICollectionView extensions public extension IndexPath { /// Initialize for use with `UITableView` or `UICollectionView`. public init(item: Int, section: Int) { self.init(indexes: [section, item]) } /// The item of this index path, when used with `UICollectionView`. /// /// - precondition: The index path must have exactly two elements. public var item: Int { get { precondition(count == 2, "Invalid index path for use with UICollectionView. This index path must contain exactly two indices specifying the section and item.") return self[1] } set { precondition(count == 2, "Invalid index path for use with UICollectionView. This index path must contain exactly two indices specifying the section and item.") self[1] = newValue } }} public extension URLResourceValues { /// Returns a dictionary of UIImage objects keyed by size. @available(iOS 8.0, *) public var thumbnailDictionary : [URLThumbnailSizeKey : UIImage]? { return allValues[URLResourceKey.thumbnailDictionaryKey] as? [URLThumbnailSizeKey : UIImage] } }
13ce6d46e6a1ad784d191cad2c37beea
37.662651
171
0.622001
false
false
false
false
dibaicongyouwangzi/QQMusic
refs/heads/master
QQMusic/QQMusic/Classes/QQDetail/Controller/QQLrcTVC.swift
mit
1
// // QQLrcTVC.swift // QQMusic // // Created by 迪拜葱油王子 on 2016/11/14. // Copyright © 2016年 迪拜葱油王子. All rights reserved. // import UIKit class QQLrcTVC: UITableViewController { // 提供给外界赋值的进度 var progress : CGFloat = 0{ didSet{ // 拿到当前正在播放的cell let indexPath = NSIndexPath(row: scrollRow, section: 0) let cell = tableView.cellForRow(at: indexPath as IndexPath) as? QQLrcCell // 给cell里面的label的进度赋值 cell?.progress = progress } } // 提供给外界的数值,代表需要滚动的行数 var scrollRow = -1{ didSet{ // 过滤值,降低滚动频率 // 如果两个值相等,代表滚动的是同一行,没有必要滚动很多次 if scrollRow == oldValue{ return } let indexPaths = tableView.indexPathsForVisibleRows tableView.reloadRows(at: indexPaths!, with: .fade) let indexPath = NSIndexPath(row: scrollRow, section: 0) tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.middle, animated: true) } } var lrcMs : [QQLrcModel] = [QQLrcModel]() { didSet{ tableView.reloadData() } } override func viewDidLoad() { tableView.separatorStyle = .none tableView.allowsSelection = false } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.contentInset = UIEdgeInsetsMake(tableView.frame.size.height * 0.5, 0, tableView.frame.size.height * 0.5, 0) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lrcMs.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = QQLrcCell.cellWithTableView(tableView: tableView) // 取出歌词模型 let model = lrcMs[indexPath.row] if indexPath.row == scrollRow{ cell.progress = progress }else{ cell.progress = 0 } cell.lrcContent = model.lrcContent return cell } }
eaf67de57318b74fb4134f165155221e
24.632184
125
0.568161
false
false
false
false
frankcjw/CJWLib
refs/heads/master
UI/CJWBaseViewController.swift
mit
1
// // YGBaseViewController.swift // YuanGuangProject // // Created by Frank on 6/26/15. // Copyright (c) 2015 YG. All rights reserved. // import UIKit class CJWBaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.setBackTitle("") } } extension UIViewController { func pushViewController(viewController: UIViewController){ if self.navigationController != nil { viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) } } func popViewController(){ if self.navigationController != nil { self.navigationController?.popViewControllerAnimated(true) } } func setBackTitle(title:String){ let back = UIBarButtonItem() back.title = title self.navigationItem.backBarButtonItem = back } func setBackAction(action:Selector){ let back = UIBarButtonItem() // back.title = title back.action = action self.navigationItem.backBarButtonItem = back } }
b4c7e34636661a8256876a2d69b32d67
22.24
89
0.641997
false
false
false
false