repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
xusader/firefox-ios
Utils/ExtensionUtils.swift
3
3791
/* 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 UIKit import MobileCoreServices import Storage struct ExtensionUtils { /// Small structure to encapsulate all the possible data that we can get from an application sharing a web page or a url. /// Look through the extensionContext for a url and title. Walks over all inputItems and then over all the attachments. /// Has a completionHandler because ultimately an XPC call to the sharing application is done. /// We can always extract a URL and sometimes a title. The favicon is currently just a placeholder, but future code can possibly interact with a web page to find a proper icon. static func extractSharedItemFromExtensionContext(extensionContext: NSExtensionContext?, completionHandler: (ShareItem?, NSError!) -> Void) { if extensionContext != nil { if let inputItems : [NSExtensionItem] = extensionContext!.inputItems as? [NSExtensionItem] { for inputItem in inputItems { if let attachments = inputItem.attachments as? [NSItemProvider] { for attachment in attachments { if attachment.hasItemConformingToTypeIdentifier(kUTTypeURL as String) { attachment.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil, completionHandler: { (obj, err) -> Void in if err != nil { completionHandler(nil, err) } else { let title = inputItem.attributedContentText?.string as String? if let url = obj as? NSURL { completionHandler(ShareItem(url: url.absoluteString!, title: title, favicon: nil), nil) } else { completionHandler(nil, NSError(domain: "org.mozilla.fennec", code: 999, userInfo: ["Problem": "Non-URL result."])) } } }) return } } } } } } completionHandler(nil, nil) } /// Return the shared container identifier (also known as the app group) to be used with for example background http requests. /// /// This function is smart enough to find out if it is being called from an extension or the main application. In case of the /// former, it will chop off the extension identifier from the bundle since that is a suffix not used in the app group. /// /// :returns: the shared container identifier (app group) or the string "group.unknown" if it cannot find the group static func sharedContainerIdentifier() -> String { let bundle = NSBundle.mainBundle() if let packageType = bundle.objectForInfoDictionaryKey("CFBundlePackageType") as? NSString { switch packageType { case "XPC!": let identifier = bundle.bundleIdentifier! let components = identifier.componentsSeparatedByString(".") let baseIdentifier = ".".join(components[0..<components.count-1]) return "group.\(baseIdentifier)" case "APPL": return "group.\(bundle.bundleIdentifier!)" default: return "group.unknown" } } return "group.unknown" } }
mpl-2.0
8cad28b9a3e52f0e23cc0a22626ea060
54.75
180
0.570826
5.850309
false
false
false
false
kaideyi/KDYSample
KYWebo/KYWebo/Bizs/Home/ViewModel/WbStatuesHelper.swift
1
1535
// // WbStatuesHelper.swift // KYWebo // // Created by KYCoder on 2017/8/16. // Copyright © 2017年 mac. All rights reserved. // import UIKit import YYKit class WbStatuesHelper: NSObject { class func getImageCache() -> YYMemoryCache { let sharedInstance = YYMemoryCache() sharedInstance.shouldRemoveAllObjectsOnMemoryWarning = false sharedInstance.shouldRemoveAllObjectsWhenEnteringBackground = false sharedInstance.name = "WeboImageCache" return sharedInstance } class func getImage(fromPath path: String) -> UIImage? { guard let image = getImageCache().object(forKey: path) as? UIImage else { var _image: UIImage? let newPath = path as NSString if newPath.pathScale() == 1 { // 查找 @2x @3x 的图片 let scales = Bundle.preferredScales() for scale in scales { guard let image = UIImage(contentsOfFile: newPath.appendingPathScale(CGFloat(scale.floatValue))) else { return nil } _image = image } } else { guard let image = UIImage(contentsOfFile: path) else { return nil } _image = image } if _image != nil { _image = _image?.byDecoded() getImageCache().setObject(_image, forKey: path) } return _image } return image } }
mit
61be272c17c95262ab909815c277c363
28.843137
136
0.550591
4.957655
false
false
false
false
Jerry0523/JWIntent
Intent/Internal/_ScreenEdgeDetectorViewController.swift
1
2632
// // _ScreenEdgeDetectorViewController.swift // // Copyright (c) 2015 Jerry Wong // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class _ScreenEdgeDetectorViewController : UIViewController, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() addChildViewIfNeeded() let gesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleScreenEdgeGesture(_:))) gesture.edges = UIRectEdge.left gesture.delegate = self view.addGestureRecognizer(gesture) } override func addChild(_ childController: UIViewController) { if isViewLoaded { for subView in view.subviews { subView.removeFromSuperview() } } for subVC in children { subVC.removeFromParent() } super.addChild(childController) addChildViewIfNeeded() } private func addChildViewIfNeeded() { if !isViewLoaded { return } if let childController = children.first { childController.view.frame = view.bounds childController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(childController.view) childController.didMove(toParent: self) } } @objc private func handleScreenEdgeGesture(_ sender: UIScreenEdgePanGestureRecognizer) { presentTransition?.handle(sender, gestureDidBegin: { dismiss(animated: true, completion: nil) }) } }
mit
bcbaec6da681842b86d97a1600d93ab4
36.6
116
0.68465
5.243028
false
false
false
false
emericspiroux/Open42
correct42/Controllers/UserViewController.swift
1
10266
// // UserViewController.swift // correct42 // // Created by larry on 30/04/2016. // Copyright © 2016 42. All rights reserved. // import UIKit import MessageUI /** Container content of an displayed user Display all public informations Implementation of click on `mobileLabel` and `emailLabel` to interpret and do the correspondant action */ class UserViewController: UIViewController, UIGestureRecognizerDelegate, MFMessageComposeViewControllerDelegate{ // MARK: - Singletons /// Singleton of `UserManager` var user = UserManager.Shared() /// Singleton of `ApiRequester` var apiRequester = ApiRequester.Shared() /// Use to display test information for appStore screenshots let testAppStore = false /// Circular transition animation lazy var transition:CircularTransition = { return (CircularTransition(transitionDelegate: self)) }() // MARK: - IBOutlets /// Image view of the `userManager.currentUser`. @IBOutlet weak var userImage: UIImageView! /// Login label of the `userManager.currentUser`. @IBOutlet weak var pseudoLabel: UILabel! /// Mobile TextView of the `userManager.currentUser`. @IBOutlet weak var mobileLabel: UILabel! /// Email label of the `userManager.currentUser`. @IBOutlet weak var emailLabel: UILabel! /// Level label of the `userManager.currentUser`. @IBOutlet weak var levelLabel: UILabel! /// Wallet label of the `userManager.currentUser`. @IBOutlet weak var walletsLabel: UILabel! /// Correction points label of the `userManager.currentUser`. @IBOutlet weak var pointsLabel: UILabel! /// Location in 42 School label of the `userManager.currentUser`. @IBOutlet weak var locationLabel: UILabel! /// Name of the first cursus displayed @IBOutlet weak var cursusNameLabel: UILabel! /// Stack View who displaying information of an user @IBOutlet weak var detailsStackView: UIStackView! /// Button details stack View @IBOutlet weak var detailsButtonStackView: UIStackView! /// Global stack view @IBOutlet weak var globalStackView: UIStackView! // MARK: - IBActions /// Perform segue with id: `goToProjects`. @IBAction func ClickButtonProjects(sender: UIButton) { let center = globalStackView.displayCenterOf([detailsButtonStackView, sender], offset: CGPoint(x: 0, y: detailsButtonStackView.frame.height + 8)) transition.performSegueWithIdentifier("goToProjectsUser", sender: self, startAtCenterOf: sender, atCenter: center) } /// Perform segue with id: `goToSkills`. @IBAction func ClickButtonSkills(sender: UIButton) { let center = globalStackView.displayCenterOf([detailsButtonStackView, sender], offset: CGPoint(x: 0, y: detailsButtonStackView.frame.height + 8)) transition.performSegueWithIdentifier("goToSkills", sender: self, startAtCenterOf: sender, atCenter: center) } // MARK: - View life cycle /// Define cornerRadius of the image. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. defineDefaultDesign() appendDefaultGestureReconizer() } /// Ask to fill information from `userManager.currentUser`. override func viewWillAppear(animated: Bool) { fillUser() } // MARK: - MFMessage Compose View Controller Delegate /// Message compose handler. func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) { switch (result) { case MessageComposeResultCancelled: self.dismissViewControllerAnimated(true, completion: nil) case MessageComposeResultFailed: self.dismissViewControllerAnimated(true, completion: nil) case MessageComposeResultSent: self.dismissViewControllerAnimated(true, completion: nil) default: break; } } // MARK: - Private methods /** If Fill information from `userManager.currentUser` else if he's optionnal fill view with defaults values. */ private func fillUser(){ if let currentUser = user.currentUser{ fillImage(currentUser.imageUrl) emailLabel.text = currentUser.email if let cursus = currentUser.currentCursus { pseudoLabel.text = "\(cursus.grade)\((cursus.grade.isEmpty) ? "" : " ")\(currentUser.login)" cursusNameLabel.text = cursus.name levelLabel.text = "\(cursus.level)%" } if let loginUser = user.loginUser where currentUser.id == loginUser.id { if let cursus = user.selectedCursus { pseudoLabel.text = "\(cursus.grade)\((cursus.grade.isEmpty) ? "" : " ")\(currentUser.login)" cursusNameLabel.text = cursus.name if !testAppStore { levelLabel.text = "\(cursus.level)%" } } } if !testAppStore { mobileLabel.text = currentUser.phone walletsLabel.text = "\(currentUser.wallet) ₳" pointsLabel.text = "\(currentUser.correctionPoint)" if currentUser.location != "" { locationLabel.text = currentUser.location } else { locationLabel.text = "-" } } else { walletsLabel.text = "100000 ₳" pointsLabel.text = "21" levelLabel.text = "42%" locationLabel.text = "e0r12p10" } } else { userImage.image = nil pseudoLabel.text = NSLocalizedString("unknown", comment: "unknown value") emailLabel.text = NSLocalizedString("unknown", comment: "unknown value") mobileLabel.text = NSLocalizedString("unknown", comment: "unknown value") walletsLabel.text = "0 ₳" pointsLabel.text = "0" locationLabel.text = "-" levelLabel.text = "0%" } } /** Take an imageUrl and downloadImage with `apiRequester.downloadImage` and fill `userImage` with result on success. */ private func fillImage(imageUrl:String){ apiRequester.downloadImage(imageUrl, success: { (image) in self.userImage.image = image }, failure: { (error) in print(error.domain) }) } /** Purpose two choice with action sheet: 1. Call the phone number inside `mobileLabel` if exist else nothing happen. 2. */ @objc private func clicPhoneNumber(){ if (!user.currentIsProfil){ if var phoneNumber = self.mobileLabel.text { phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString("(", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString(")", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString("-", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString(".", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString(" ", withString: "") let alert = UIAlertController(title: String(format: NSLocalizedString("popOverAlertTitleAlert", comment: "Title with name owner"), self.user.currentUser!.firstName), message: String(format: NSLocalizedString("popOverAlertMessageAlert", comment: "Title with name owner"), self.user.currentUser!.firstName), preferredStyle: .ActionSheet) alert.addAction(UIAlertAction(title: NSLocalizedString("callChoice", comment: "call title choice"), style: .Default, handler: { (alertAction) in if let phoneNumberURL = NSURL(string: "tel://\(phoneNumber)"){ UIApplication.sharedApplication().openURL(phoneNumberURL) } })) alert.addAction(UIAlertAction(title: NSLocalizedString("smsChoice", comment: "sms title choice"), style: .Default, handler: { (alertAction) in let messageVC = MFMessageComposeViewController() if MFMessageComposeViewController.canSendText() { messageVC.body = String(format: NSLocalizedString("smsBeginMessage", comment: "firstname of the receiver"), self.user.currentUser!.firstName); messageVC.recipients = [phoneNumber] messageVC.messageComposeDelegate = self; self.presentViewController(messageVC, animated: false, completion: nil) } })) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel Choice"), style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } } /** Call the phone number inside `mobileLabel` if exist else nothing happen. */ @objc private func clicEmail(){ if (!user.currentIsProfil){ if let email = emailLabel.text { if email.containsString("@student.42.fr") { if let email = NSURL(string: "mailto://\(email)"){ UIApplication.sharedApplication().openURL(email) } } } } } /** Append default Gesture reconizer. Need to add interpretation of label inside an profil user. Follow actions happens : - `mobileLabel` tap gesture do the `clicPhoneNumber` action method - `emailLabel` tap gesture do the `clicEmail` action method */ private func appendDefaultGestureReconizer() { /// For `mobileLabel` let tapPhone = UITapGestureRecognizer(target: self, action: #selector(self.clicPhoneNumber)) mobileLabel.addGestureRecognizer(tapPhone) /// For `emailLabel` let tapEmail = UITapGestureRecognizer(target: self, action: #selector(self.clicEmail)) emailLabel.addGestureRecognizer(tapEmail) } /** Define the default design of `UserViewController` Follow designs will be set : - `userImage` will draw inside a circle */ private func defineDefaultDesign() { // Define userImage circle userImage.layer.cornerRadius = userImage.frame.size.width/2 userImage.clipsToBounds = true } // MARK: - Navigation // Give the destination controller to transition override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { transition.defineTransitionDestination(segue.destinationViewController) } } // MARK: - Extensions // Extension for UIViewControllerTransitioningDelegate extension UserViewController:UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.prepareAnimationFor(.present) return transition } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.prepareAnimationFor(.dismiss) return transition } func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return transition.interactive ? transition : nil } }
apache-2.0
d16c50aea2c077325ada402b7e97c797
35.254417
214
0.737694
4.306885
false
false
false
false
muhasturk/smart-citizen-ios
Smart Citizen/Controller/Presenter/LoginVC.swift
1
5386
/** * Copyright (c) 2016 Mustafa Hastürk * * 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 Alamofire import SwiftyJSON class LoginVC: AppVC { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var resultLabel: UILabel! fileprivate let requestBaseURL = AppAPI.serviceDomain + AppAPI.loginServiceURL override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Login" } @IBAction func loginButtonAction(_ sender: AnyObject) { self.view.endEditing(true) let email = self.emailField.text! let password = self.passwordField.text! if email.isEmpty || password.isEmpty { self.createAlertController(title: AppAlertMessages.missingFieldTitle, message: AppAlertMessages.loginMissingFieldMessage, controllerStyle: .alert, actionStyle: .default) } else if email.isNotEmail { self.createAlertController(title: AppAlertMessages.emailFieldNotValidatedTitle, message: AppAlertMessages.emailFieldNotValidatedMessage, controllerStyle: .alert, actionStyle: .default) } else { let parameters = [ "email": email, "password": password, "deviceToken": UserDefaults.standard.string(forKey: AppConstants.DefaultKeys.DEVICE_TOKEN) ?? "5005" ] self.loginNetworking(networkingParameters: parameters as [String : AnyObject]) } } // MARK: - Model fileprivate func writeUserDataToModel(dataJsonFromNetworking data: JSON) { let user = User() user.id = data["id"].intValue user.email = data["email"].stringValue user.fullName = data["fullName"].stringValue user.password = data["password"].stringValue user.roleId = data["roleId"].intValue user.roleName = data["roleName"].stringValue super.reflectAttributes(reflectingObject: user) self.saveLocalSession(user) } fileprivate func saveLocalSession(_ user: User) { UserDefaults.standard.set(true, forKey: AppConstants.DefaultKeys.APP_ALIVE) let encodedUser = NSKeyedArchiver.archivedData(withRootObject: user) UserDefaults.standard.set(encodedUser, forKey: AppConstants.DefaultKeys.APP_USER) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.emailField { self.passwordField.becomeFirstResponder() } else { self.loginButtonAction(textField) } return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } } // MARK: - Networking extension LoginVC { fileprivate func loginNetworking(networkingParameters params: [String: AnyObject]) { self.startIndicator() Alamofire.request(self.requestBaseURL, method: .post, parameters: params, encoding: JSONEncoding.default) .responseJSON { response in self.stopIndicator() switch response.result { case .success(let value): print(AppDebugMessages.serviceConnectionLoginIsOk, self.requestBaseURL, separator: "\n") let json = JSON(value) let serviceCode = json["serviceCode"].intValue if serviceCode == 0 { let data = json["data"] self.loginNetworkingSuccessful(data) } else { let exception = json["exception"] self.loginNetworkingUnsuccessful(exception) } case .failure(let error): self.createAlertController(title: AppAlertMessages.networkingFailuredTitle, message: AppAlertMessages.networkingFailuredMessage, controllerStyle: .alert, actionStyle: .destructive) debugPrint(error) } } } private func loginNetworkingSuccessful(_ data: JSON) { self.writeUserDataToModel(dataJsonFromNetworking: data) self.performSegue(withIdentifier: AppSegues.doLoginSegue, sender: nil) } fileprivate func loginNetworkingUnsuccessful(_ exception: JSON) { let c = exception["exceptionCode"].intValue let m = exception["exceptionMessage"].stringValue let (title, message) = self.getHandledExceptionDebug(exceptionCode: c, elseMessage: m) self.createAlertController(title: title, message: message, controllerStyle: .alert, actionStyle: .default) } }
mit
e1f1bfa7dd7980f4ff06c34f5551667f
36.395833
190
0.706592
4.634251
false
false
false
false
drawRect/Instagram_Stories
InstagramStories/Modules/Home/IGHomeView.swift
1
1936
// // IGHomeView.swift // InstagramStories // // Created by Boominadha Prakash on 01/11/17. // Copyright © 2017 DrawRect. All rights reserved. // import Foundation import UIKit class IGHomeView: UIView { //MARK: - iVars lazy var layout: UICollectionViewFlowLayout = { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal flowLayout.itemSize = CGSize(width: 100, height: 100) return flowLayout }() lazy var collectionView: UICollectionView = { let cv = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout) cv.backgroundColor = .white cv.showsVerticalScrollIndicator = false cv.showsHorizontalScrollIndicator = false cv.register(IGStoryListCell.self, forCellWithReuseIdentifier: IGStoryListCell.reuseIdentifier) cv.register(IGAddStoryCell.self, forCellWithReuseIdentifier: IGAddStoryCell.reuseIdentifier) cv.translatesAutoresizingMaskIntoConstraints = false return cv }() //MARK: - Overridden functions override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.rgb(from: 0xEFEFF4) createUIElements() installLayoutConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } //MARK: - Private functions private func createUIElements(){ addSubview(collectionView) } private func installLayoutConstraints(){ NSLayoutConstraint.activate([ igLeftAnchor.constraint(equalTo: collectionView.igLeftAnchor), igTopAnchor.constraint(equalTo: collectionView.igTopAnchor), collectionView.igRightAnchor.constraint(equalTo: igRightAnchor), collectionView.heightAnchor.constraint(equalToConstant: 100)]) } }
mit
4c7ef8c9caf02a55ef541d0bbe2f2d55
34.181818
102
0.691473
5.092105
false
false
false
false
pourhadi/DynUI
Pod/Classes/Popover.swift
1
7679
// // Popover.swift // Pods // // Created by Dan Pourhadi on 1/29/16. // // import Foundation import UIKit let CAP_INSET:CGFloat = 25 let ARROW_BASE:CGFloat = 38 let ARROW_HEIGHT:CGFloat = 20 extension UIPopoverController { public static var dyn_popoverStyle:ViewStyle? public static var dyn_contentInset:UIEdgeInsets? } public class PopoverStyleClass: UIPopoverBackgroundView { let borderImageView:UIImageView = UIImageView(frame: CGRectZero) override public init(frame: CGRect) { super.init(frame: frame) self.borderImageView.frame = self.bounds self.backgroundColor = UIColor.clearColor() self.addSubview(self.borderImageView) } override public class func wantsDefaultContentAppearance() -> Bool { return false } public override static func contentViewInsets() -> UIEdgeInsets { return UIPopoverController.dyn_contentInset ?? UIEdgeInsetsMake(10, 10, 10, 10) } private var _arrowDirection:UIPopoverArrowDirection = .Any override public var arrowDirection: UIPopoverArrowDirection { get { return _arrowDirection } set { _arrowDirection = newValue } } private var _arrowOffset:CGFloat = 0 override public var arrowOffset: CGFloat { get { return _arrowOffset } set { _arrowOffset = newValue } } public override static func arrowHeight() -> CGFloat { return ARROW_HEIGHT } public override static func arrowBase() -> CGFloat { return ARROW_BASE } public override func layoutSubviews() { super.layoutSubviews() var _height = self.frame.size.height var _width = self.frame.size.width var _left:CGFloat = 0 var _top:CGFloat = 0 var _coordinate:CGFloat = 0 let offset:CGFloat = 0 var arrowRect:CGRect = CGRectZero switch self.arrowDirection { case UIPopoverArrowDirection.Up: _top += ARROW_HEIGHT _height -= ARROW_HEIGHT _coordinate = ((self.frame.size.width / 2) + self.arrowOffset) - (ARROW_BASE / 2) arrowRect = CGRectMake(_coordinate, 0 + offset, ARROW_BASE, ARROW_HEIGHT) case UIPopoverArrowDirection.Down: _height -= ARROW_HEIGHT _coordinate = ((self.frame.size.width / 2) + self.arrowOffset) - (ARROW_BASE / 2) arrowRect = CGRectMake(_coordinate, _height - offset, ARROW_BASE, ARROW_HEIGHT) case UIPopoverArrowDirection.Left: _left += ARROW_HEIGHT _width -= ARROW_HEIGHT _coordinate = ((self.frame.size.height / 2) + self.arrowOffset) - (ARROW_BASE / 2) arrowRect = CGRectMake(offset, _coordinate, ARROW_HEIGHT, ARROW_BASE) case UIPopoverArrowDirection.Right: _width -= ARROW_HEIGHT _coordinate = ((self.frame.size.height / 2) + self.arrowOffset) - (ARROW_BASE / 2) arrowRect = CGRectMake(_width - offset, _coordinate, ARROW_HEIGHT, ARROW_BASE) default: break } self.borderImageView.frame = self.bounds self.borderImageView.image = self.getBgImage(self.bounds.size, arrowRect: arrowRect, bgRect: CGRectMake(_left + 1, _top + 1, _width - 2, _height - 2))?.stretchableImageWithLeftCapWidth(Int(self.bounds.size.width) / 2 - (1), topCapHeight: Int(self.bounds.size.height) / 2 - 1) } func getBgImage(size:CGSize, arrowRect:CGRect, bgRect:CGRect) -> UIImage? { guard let style = UIPopoverController.dyn_popoverStyle else { return nil } let path = UIBezierPath() let radius = CGSizeMake(style.cornerRadius, style.cornerRadius) path.moveToPoint(CGPointMake(bgRect.origin.x, bgRect.origin.y + radius.height)) if style.roundedCorners.contains(.TopLeft) { path.addArcWithCenter(CGPointMake(path.currentPoint.x + radius.width, path.currentPoint.y), radius: radius.width, startAngle: CGFloat(M_PI), endAngle: CGFloat(3 * M_PI) / 2, clockwise: true) } else { path.addLineToPoint(bgRect.origin) } if (self.arrowDirection == .Up) { path.addLineToPoint(CGPointMake(arrowRect.origin.x, bgRect.origin.y)) path.addLineToPoint(CGPointMake(arrowRect.origin.x + (arrowRect.size.width / 2), 1)) path.addLineToPoint(CGPointMake(arrowRect.origin.x + arrowRect.size.width, bgRect.origin.y)) } path.addLineToPoint(CGPointMake((bgRect.origin.x + bgRect.size.width) - radius.width, bgRect.origin.y)) if (style.roundedCorners.contains(.TopRight)) { path.addArcWithCenter(CGPointMake(path.currentPoint.x, path.currentPoint.y + radius.height), radius:radius.width, startAngle:CGFloat(3 * M_PI) / 2, endAngle:0, clockwise:true) } else { path.addLineToPoint(CGPointMake(bgRect.origin.x + bgRect.size.width, bgRect.origin.y)) } if (self.arrowDirection == .Right) { path.addLineToPoint(CGPointMake(bgRect.origin.x + bgRect.size.width, arrowRect.origin.y)) path.addLineToPoint(CGPointMake(arrowRect.origin.x + arrowRect.size.width, arrowRect.origin.y + (arrowRect.size.height / 2))) path.addLineToPoint(CGPointMake(bgRect.origin.x + bgRect.size.width, arrowRect.origin.y + arrowRect.size.height)) } path.addLineToPoint(CGPointMake(bgRect.origin.x + bgRect.size.width, (bgRect.origin.y + bgRect.size.height) - radius.height)) if (style.roundedCorners.contains(.BottomRight)) { path.addArcWithCenter(CGPointMake(path.currentPoint.x - radius.width, path.currentPoint.y), radius:radius.width, startAngle:0, endAngle:CGFloat(M_PI / 2), clockwise:true) } else { path.addLineToPoint(CGPointMake(CGRectGetMaxX(bgRect), CGRectGetMaxY(bgRect))) } if (self.arrowDirection == .Down) { path.addLineToPoint(CGPointMake(arrowRect.origin.x + arrowRect.size.width, bgRect.origin.y + bgRect.size.height)) path.addLineToPoint(CGPointMake(arrowRect.origin.x + (arrowRect.size.width / 2), arrowRect.origin.y + arrowRect.size.height)) path.addLineToPoint(CGPointMake(arrowRect.origin.x, bgRect.origin.y + bgRect.size.height)) } path.addLineToPoint(CGPointMake(bgRect.origin.x + radius.width, bgRect.origin.y + bgRect.size.height)) // bottom left if (style.roundedCorners.contains(.BottomLeft)) { path.addArcWithCenter(CGPointMake(path.currentPoint.x, path.currentPoint.y - radius.height), radius:radius.width, startAngle:CGFloat(M_PI / 2), endAngle:CGFloat(M_PI), clockwise:true) } else { path.addLineToPoint(CGPointMake(bgRect.origin.x, CGRectGetMaxY(bgRect))) } if (self.arrowDirection == .Left) { path.addLineToPoint(CGPointMake(bgRect.origin.x, arrowRect.origin.y + arrowRect.size.height)) path.addLineToPoint(CGPointMake(arrowRect.origin.x, arrowRect.origin.y + (arrowRect.size.height / 2))) path.addLineToPoint(CGPointMake(bgRect.origin.x, arrowRect.origin.y)) } path.closePath() let image = UIImage.drawImage(size) { (rect) -> Void in style.render(RenderContext(path: path, view: self)) } return image } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
73ab659ae95981c2354141314883d369
41.666667
283
0.638234
4.184741
false
false
false
false
apple/swift-tools-support-core
Sources/TSCUtility/Context.swift
1
1125
/* This source file is part of the Swift.org open source project Copyright (c) 2020 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 Swift project authors */ import Foundation /// Typealias for an any typed dictionary for arbitrary usage to store context. public typealias Context = [ObjectIdentifier: Any] extension Context { /// Get the value for the given type. public func get<T>(_ type: T.Type = T.self) -> T { guard let value = getOptional(type) else { fatalError("no type \(T.self) in context") } return value } /// Get the value for the given type, if present. public func getOptional<T>(_ type: T.Type = T.self) -> T? { guard let value = self[ObjectIdentifier(T.self)] else { return nil } return value as? T } /// Set a context value for a type. public mutating func set<T>(_ value: T) { self[ObjectIdentifier(T.self)] = value } }
apache-2.0
63a938724b399323d1691ebbd557c096
29.405405
79
0.652444
4.166667
false
false
false
false
avinassh/Calculator-Swift
Calculator/ViewController.swift
1
3567
// // ViewController.swift // Calculator // // Created by avi on 07/02/15. // Copyright (c) 2015 avi. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var display: UILabel! @IBOutlet weak var history: UILabel! var userIsInTheMiddleOfTypingANumber = false var userHasEnteredADot = false var brain = CalculatorBrain() var displayValue: Double? { get { let text = display.text! if text == "π" { return M_PI } return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { display.text = "\(newValue!)" userIsInTheMiddleOfTypingANumber = false } } @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if digit == "π" { if userIsInTheMiddleOfTypingANumber { return } else { display.text = digit enter() return } } if digit == "." { if userHasEnteredADot { return } else { userHasEnteredADot = true } } if userIsInTheMiddleOfTypingANumber { display.text = display.text! + digit } else { display.text = digit userIsInTheMiddleOfTypingANumber = true } } @IBAction func operrate(sender: UIButton) { if userIsInTheMiddleOfTypingANumber { enter() } if let operation = sender.currentTitle { // history needs to be improved // for example, it enters operations into display even though // they are not getting evaluated // enter 9 enter + enter + enter 3 etc. history.text! += operation + "|" if let result = brain.performOperation(operation) { displayValue = result } else { displayValue = 0 } } } @IBAction func enter() { userIsInTheMiddleOfTypingANumber = false userHasEnteredADot = false history.text! += display.text! + "|" // needs unwrapping of optional displayValue! and a if block? // change it later if let result = brain.pushOperand(displayValue!) { displayValue = result } else { displayValue = 0 } } @IBAction func clear() { history.text = "history: " display.text = "0" userIsInTheMiddleOfTypingANumber = false userHasEnteredADot = false println("Calculator has been reset") brain = CalculatorBrain() } @IBAction func backspace() { if countElements(display.text!) > 0 { display.text = dropLast(display.text!) if display.text!.isEmpty { userIsInTheMiddleOfTypingANumber = false display.text = "0" } } } @IBAction func changeSign() { displayValue = -(displayValue!) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
cd5be593a8842ee7e1c3481a50696459
25.604478
83
0.526508
5.518576
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFRotationRespectingTabBarController.swift
1
1395
import UIKit public class WMFRotationRespectingTabBarController: WMFTabBarController { public override func shouldAutorotate() -> Bool { if let vc = self.presentedViewController where !vc.isKindOfClass(UIAlertController) { return vc.shouldAutorotate() } else if let vc = self.selectedViewController { return vc.shouldAutorotate() }else{ return super.shouldAutorotate() } } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if let vc = self.presentedViewController where !vc.isKindOfClass(UIAlertController) { return vc.supportedInterfaceOrientations() } else if let vc = self.selectedViewController { return vc.supportedInterfaceOrientations() }else{ return super.supportedInterfaceOrientations() } } public override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation { if let vc = self.presentedViewController where !vc.isKindOfClass(UIAlertController) { return vc.preferredInterfaceOrientationForPresentation() } else if let vc = self.selectedViewController { return vc.preferredInterfaceOrientationForPresentation() }else{ return super.preferredInterfaceOrientationForPresentation() } } }
mit
03208abdb4e6ce1aaeedadc823baad51
40.029412
99
0.688889
6.706731
false
false
false
false
iMac239/CoreDataRelationshipDemo
CoreDataRelationshipDemo/TaskViewController.swift
2
4134
// // TaskViewController.swift // CoreDataRelationshipDemo // // Created by Ian MacCallum on 1/31/15. // Copyright (c) 2015 MacCDevTeam. All rights reserved. // import Foundation import UIKit import Foundation import UIKit import CoreData class TaskViewController: UITableViewController { let managedObjectContext: NSManagedObjectContext? = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext var fetchedResultsController: NSFetchedResultsController? var category: Category? override func viewDidLoad() { super.viewDidLoad() fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController?.delegate = self do { try fetchedResultsController?.performFetch() } catch _ { } } func fetchRequest() -> NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: "Task") let sortDescriptor = NSSortDescriptor(key: "title", ascending: true) let predicate = NSPredicate(format: "category == %@", category ?? Category()) fetchRequest.predicate = predicate fetchRequest.sortDescriptors = [sortDescriptor] fetchRequest.fetchBatchSize = 20 return fetchRequest } } // MARK: UITableView Data Source & Delegate extension TaskViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController?.sections?[section].numberOfObjects ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as UITableViewCell let task = fetchedResultsController?.objectAtIndexPath(indexPath) as? Task cell.textLabel?.text = task?.title cell.detailTextLabel?.text = task?.category.name return cell } } // MARK: NSFetchedResultsController Delegate extension TaskViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: managedObjectContext?.deleteObject(fetchedResultsController?.objectAtIndexPath(indexPath) as! Task) do { try managedObjectContext?.save() } catch _ { } case .Insert: break case .None: break } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case NSFetchedResultsChangeType.Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case NSFetchedResultsChangeType.Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case NSFetchedResultsChangeType.Move: break case NSFetchedResultsChangeType.Update: tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) } } }
mit
11cf2472d84c0cf10239953d9ce51f27
35.263158
211
0.698355
6.541139
false
false
false
false
richardpiazza/SOSwift
Sources/SOSwift/ImageObject.swift
1
1767
import Foundation /// An image file. public class ImageObject: MediaObject { /// The caption for this object. public var caption: String? /// exif data for this object. public var exifData: PropertyValueOrText? /// Indicates whether this image is representative of the content of the page. public var representativeOfPage: Bool? /// Thumbnail image for an image or video. public var thumbnail: ImageObject? internal enum ImageObjectCodingKeys: String, CodingKey { case caption case exifData case representativeOfPage case thumbnail } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: ImageObjectCodingKeys.self) caption = try container.decodeIfPresent(String.self, forKey: .caption) exifData = try container.decodeIfPresent(PropertyValueOrText.self, forKey: .exifData) representativeOfPage = try container.decodeIfPresent(Bool.self, forKey: .representativeOfPage) thumbnail = try container.decodeIfPresent(ImageObject.self, forKey: .thumbnail) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: ImageObjectCodingKeys.self) try container.encodeIfPresent(caption, forKey: .caption) try container.encodeIfPresent(exifData, forKey: .exifData) try container.encodeIfPresent(representativeOfPage, forKey: .representativeOfPage) try container.encodeIfPresent(thumbnail, forKey: .thumbnail) try super.encode(to: encoder) } }
mit
f4856afd306b0e64686aea323ee4b4e7
33.647059
102
0.681947
5.034188
false
false
false
false
rymir/ConfidoIOS
ConfidoIOS/Keychain.swift
1
10704
// // Keychain.swift // ExpendSecurity // // Created by Rudolph van Graan on 18/08/2015. // Copyright (c) 2015 Curoo Limited. All rights reserved. // import Foundation public typealias SecItemAttributes = [ String : AnyObject] public typealias ItemReference = AnyObject public typealias KeyChainPropertiesData = [ String : AnyObject] public typealias KeychainItemData = [ String : AnyObject] func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) { for (k, v) in right { left.updateValue(v, forKey: k) } } public enum KeychainError : ErrorType, CustomStringConvertible { case NoSecIdentityReference, NoSecCertificateReference, NoSecKeyReference, UnimplementedSecurityClass, MismatchedResultType(returnedType: AnyClass, declaredType: Any), InvalidCertificateData, TrustError(trustResult: TrustResult, reason: String?) public var description : String { switch self { case NoSecIdentityReference: return "NoSecIdentityReference" case NoSecCertificateReference: return "NoSecCertificateReference" case NoSecKeyReference: return "NoSecKeyReference" case UnimplementedSecurityClass: return "UnimplementedSecurityClass" case MismatchedResultType(let returnedType, let declaredType) : return "MismatchedResultType (returned \(returnedType)) declared \(declaredType)" case InvalidCertificateData: return "InvalidCertificateData" case TrustError(_, let reason) : return "TrustError \(reason)" } } } /** Wraps the raw secXYZ APIs */ public class SecurityWrapper { /** A typical query consists of: * a kSecClass key, whose value is a constant from the Class Constants section that specifies the class of item(s) to be searched * one or more keys from the "Attribute Key Constants" section, whose value is the attribute data to be matched * one or more keys from the "Search Constants" section, whose value is used to further refine the search * a key from the "Return Type Key Constants" section, specifying the type of results desired Result types are specified as follows: * To obtain the data of a matching item (CFDataRef), specify kSecReturnData with a value of kCFBooleanTrue. * To obtain the attributes of a matching item (CFDictionaryRef), specify kSecReturnAttributes with a value of kCFBooleanTrue. * To obtain a reference to a matching item (SecKeychainItemRef, SecKeyRef, SecCertificateRef, or SecIdentityRef), specify kSecReturnRef with a value of kCFBooleanTrue. * To obtain a persistent reference to a matching item (CFDataRef), specify kSecReturnPersistentRef with a value of kCFBooleanTrue. Note that unlike normal references, a persistent reference may be stored on disk or passed between processes. * If more than one of these result types is specified, the result is returned as a CFDictionaryRef containing all the requested data. * If a result type is not specified, no results are returned. By default, this function returns only the first match found. To obtain more than one matching item at a time, specify kSecMatchLimit with a value greater than 1. The result will be a CFArrayRef containing up to that number of matching items; the items' types are described above. To filter a provided list of items down to those matching the query, specify a kSecMatchItemList whose value is a CFArray of SecKeychainItemRef, SecKeyRef, SecCertificateRef, or SecIdentityRef items. The objects in the provided array must be of the same type. To convert from a persistent item reference to a normal item reference, specify a kSecValuePersistentRef whose value a CFDataRef (the persistent reference), and a kSecReturnRef whose value is kCFBooleanTrue. */ public class func secItemCopyMatching<T>(query: KeyChainPropertiesData) throws -> T { var result: AnyObject? let status = KeychainStatus.statusFromOSStatus( withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } ) if status == .OK, let returnValue = result as? T { return returnValue } else if status == .OK, let returnValue = result { throw KeychainError.MismatchedResultType(returnedType: returnValue.dynamicType, declaredType: T.self) } else if status == .OK { throw KeychainStatus.ItemNotFoundError } throw status } public class func secItemAdd(attributes: KeychainItemData) throws -> AnyObject? { var persistedRef: AnyObject? let status = KeychainStatus.statusFromOSStatus( withUnsafeMutablePointer(&persistedRef) { SecItemAdd(attributes, UnsafeMutablePointer($0)) } ) if status == .OK { print(persistedRef) if let data = persistedRef as? NSData { print(data) } } return [] } public class func secItemDelete(query: KeyChainPropertiesData) throws { let dictionary = NSMutableDictionary() dictionary.addEntriesFromDictionary(query) let status = KeychainStatus.statusFromOSStatus(SecItemDelete(dictionary)) if status == .OK { return } throw status } public class func secPKCS12Import(pkcs12Data: NSData, options: KeyChainPropertiesData) throws -> [SecItemAttributes] { var result: NSArray? let status = KeychainStatus.statusFromOSStatus( withUnsafeMutablePointer(&result) { SecPKCS12Import(pkcs12Data, options, UnsafeMutablePointer($0)) } ) if status == .OK, let items = result as? [SecItemAttributes] { return items } else if status == .OK { return [] } throw status } } public enum KeychainReturnLimit { case One, All } public class Keychain { public class func keyChainItems(securityClass: SecurityClass) throws -> [KeychainItem] { return try fetchItems(matchingDescriptor: KeychainDescriptor(securityClass: securityClass), returning: .All) } public class func fetchItems(matchingDescriptor attributes: KeychainMatchable, returning: KeychainReturnLimit, returnData: Bool = false, returnRef: Bool = true) throws -> [KeychainItem] { var query : KeyChainPropertiesData = [ : ] query[String(kSecClass)] = SecurityClass.kSecClass(attributes.securityClass) // kSecReturnAttributes true to ensure we don't get a raw SecKeychainItemRef or NSData back, this function can't handle it // This means we should get either a Dictionary or [Dictionary] query[String(kSecReturnAttributes)] = kCFBooleanTrue query[String(kSecReturnData)] = returnData ? kCFBooleanTrue : kCFBooleanFalse query[String(kSecReturnRef)] = returnRef ? kCFBooleanTrue : kCFBooleanFalse query[String(kSecMatchLimit)] = returning == .One ? kSecMatchLimitOne : kSecMatchLimitAll query[String(kSecReturnData)] = kCFBooleanTrue query += attributes.keychainMatchPropertyValues() do { var keychainItemDicts : [SecItemAttributes] = [] let itemDictOrDicts : NSObject = try SecurityWrapper.secItemCopyMatching(query) if let itemDicts = itemDictOrDicts as? [SecItemAttributes] { keychainItemDicts = itemDicts } else if let itemDict = itemDictOrDicts as? SecItemAttributes { keychainItemDicts.append(itemDict) } return try keychainItemDicts.flatMap { try makeKeyChainItem(attributes.securityClass, keychainItemAttributes: $0) } } catch KeychainStatus.ItemNotFoundError { return [] } } public class func fetchItem(matchingDescriptor attributes: KeychainMatchable, returnData: Bool = false, returnRef: Bool = true) throws -> KeychainItem { let results = try self.fetchItems(matchingDescriptor: attributes, returning: .One, returnData: returnData, returnRef: returnRef) if results.count == 1 { return results[0] } throw KeychainStatus.ItemNotFoundError } public class func deleteKeyChainItem(itemDescriptor descriptor: KeychainMatchable) throws { try SecurityWrapper.secItemDelete(descriptor.keychainMatchPropertyValues()) } class func makeKeyChainItem(securityClass: SecurityClass, keychainItemAttributes attributes: SecItemAttributes) throws -> KeychainItem? { return try KeychainItem.itemFromAttributes(securityClass, SecItemAttributes: attributes) } // public class func addIdentity(identity: IdentityImportSpecifier) throws -> (KeychainStatus, Identity?) { // var item : KeyChainPropertiesData = [ : ] // item[String(kSecReturnPersistentRef)] = NSNumber(bool: true); // // item += identity.keychainMatchPropertyValues() // // //There seems to be a bug in the keychain that causes the SecItemAdd for Identities to fail silently when kSecClass is specified :S // item.removeValueForKey(String(kSecClass)) // // let itemRefs: AnyObject? = try SecurityWrapper.secItemAdd(item) // // } public class func keyData(key: KeychainPublicKey) throws -> NSData { var query : KeyChainPropertiesData = [ : ] let descriptor = key.keychainMatchPropertyValues() query[String(kSecClass)] = SecurityClass.kSecClass(key.securityClass) query[String(kSecReturnData)] = kCFBooleanTrue query[String(kSecMatchLimit)] = kSecMatchLimitOne query += descriptor.keychainMatchPropertyValues() let keyData: NSData = try SecurityWrapper.secItemCopyMatching(query) return keyData } /** Attempts to delete all items of a specific security class :param: securityClass the class of item to delete :returns: (successCount:Int, failureCount:Int) */ public class func deleteAllItemsOfClass(securityClass: SecurityClass) -> (Int,Int) { do { let items = try Keychain.keyChainItems(securityClass) var successCount = 0 var failCount = 0 for item in items { do { try Keychain.deleteKeyChainItem(itemDescriptor: item.keychainMatchPropertyValues()) successCount++ } catch { failCount++ } } return (successCount, failCount) } catch { return (0,0) } } }
mit
4c98e6e24d3aeebbfbc60fa31f636239
40.169231
191
0.687126
5.022994
false
false
false
false
vanyaland/Popular-Movies
iOS/PopularMovies/PopularMovies/TMDbConstants.swift
1
2294
/** * Copyright (c) 2016 Ivan Magda * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation // MARK: TMDbConstants struct TMDbConstants { // MARK: - TMDB - struct TMDB { static let apiScheme = "https" static let apiHost = "api.themoviedb.org" static let apiPath = "/3" } // MARK: - TMDB Parameter Keys - struct TMDBParameterKeys { static let apiKey = "api_key" static let requestToken = "request_token" static let sessionId = "session_id" static let username = "username" static let password = "password" static let page = "page" static let language = "language" } // MARK: - TMDB Parameter Values - struct TMDBParameterValues { static let apiKey = "REPLACE_WITH_YOUR_OWN_API_KEY" static let languageUS = "en-US" } // MARK: - TMDB Response Keys - struct TMDBResponseKeys { static let title = "title" static let id = "id" static let posterPath = "poster_path" static let statusCode = "status_code" static let statusMessage = "status_message" static let sessionId = "session_id" static let userId = "id" static let requestToken = "request_token" static let success = "success" static let results = "results" } }
mit
049277949b861f4ef6fb506ab497544e
31.309859
80
0.700959
4.30394
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/GonzalezEsparzaLuisManuel/5.swift
1
794
// Write some awesome Swift code, or import libraries like "Foundation", // "Dispatch", or "Glibc" // link de donde los hice en linea http://swift.sandbox.bluemix.net/#/repl/58b7d995cb7993767588ce10 import Glibc print("5) "); print("9.11 Un trabajo x dura 30 dias y se paga por el $10 diarios y otro dura tambien 30 dias y se paga como sigue: $1 el primer dia, 2 el segundo, 3 el tercero y asi sucesivamente. Cual trabajo esta mejor pagado?"); var trabajo1: Double var trabajo2: Double var contador: Double trabajo1 = 10*30; trabajo2 = 1; contador = 1; while contador <= 30{ trabajo2=trabajo2+contador; contador=contador+1; } print("trabajo1",trabajo1); print("trabajo2",trabajo2); if trabajo1>trabajo2{ print("Trabajo 1 es mejor") } if trabajo2>trabajo1{ print("Trabajo 2 es mejor") }
gpl-3.0
2a342a6ae0d8a6c2a84276621aecc88e
30.8
217
0.735516
2.536741
false
false
false
false
grokify/glip-sdk-swift
GlipKit/Sources/PosterOptions.swift
1
1836
/// PosterOptions represents message options to be sent via a Glip webhook. public class PosterOptions { public var body: String public var activity, icon, title: String? init(body: String, activity: String?=nil, icon: String?=nil, title :String?=nil) { self.body = body self.activity = activity self.icon = icon self.title = title } func merge(options:PosterOptions) { if (!options.body.isEmpty) { self.body = options.body } if (!(options.activity ?? "").isEmpty) { activity = options.activity } if (!(options.icon ?? "").isEmpty) { icon = options.icon } if (!(options.title ?? "").isEmpty) { title = options.title } } /** - returns: a `String` representing the JSON request payload. */ public func toJSON() -> String { let dict = toDictionary() let jsonString: String? do { let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0)) jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) } catch { jsonString = "{}" } return jsonString! } /** - returns: a `Dictionary<String, String>` representing the options dictionary. */ public func toDictionary() -> Dictionary<String, String> { var data:Dictionary<String, String> = ["body": body] if (!(activity ?? "").isEmpty) { data["activity"] = activity } if (!(icon ?? "").isEmpty) { data["icon"] = icon } if (!(title ?? "").isEmpty) { data["title"] = title } return data } }
mit
21bda2ff1b53436a772b5ac36ee36eef
28.15873
119
0.527778
4.793734
false
false
false
false
Danappelxx/MuttonChop
Sources/MuttonChop/Helpers.swift
1
2300
extension Array { func last(_ n: Int) -> [Element] { let startIndex = self.index(endIndex, offsetBy: -n, limitedBy: self.startIndex) ?? 0 return Array(self[startIndex..<endIndex]) } func first(_ n: Int) -> [Element] { let endIndex = self.index(startIndex, offsetBy: n) return Array(self[startIndex..<endIndex]) } mutating func popFirst() -> Element? { guard !isEmpty else { return nil } return removeFirst() } } extension Array { func element(at index: Index) -> Element? { guard indices.contains(index) else { return nil } return self[index] } func elements(in range: CountableRange<Int>) -> [Element]? { guard indices.contains(range.lowerBound), indices.contains(range.upperBound - 1) else { return nil } return Array(self[range]) } } extension Dictionary { func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> [Key: T] { var dictionary: [Key: T] = [:] for (key, value) in self { dictionary[key] = try transform(value) } return dictionary } } extension String { static let newLineCharacterSet: [Character] = ["\n", "\r", "\r\n"] static let whitespaceCharacterSet: [Character] = [" ", "\t"] static let whitespaceAndNewLineCharacterSet: [Character] = whitespaceCharacterSet + newLineCharacterSet func trim(using characterSet: [Character]) -> String { return trimLeft(using: characterSet).trimRight(using: characterSet) } func trimLeft(using characterSet: [Character]) -> String { var start = 0 for (index, character) in self.enumerated() { if !characterSet.contains(character) { start = index break } } return String(self[index(startIndex, offsetBy: start) ..< endIndex]) } func trimRight(using characterSet: [Character]) -> String { var end = self.count for (index, character) in self.reversed().enumerated() { if !characterSet.contains(character) { end = index break } } return String(self[startIndex ..< index(endIndex, offsetBy: -end)]) } }
mit
47d4f18735d32547ab9317706fb17156
28.87013
107
0.582174
4.423077
false
false
false
false
thachpv91/loafwallet
BreadWallet/BRWebSocket.swift
1
25782
// // BRWebSocket.swift // BreadWallet // // Created by Samuel Sutch on 2/18/16. // Copyright (c) 2016 breadwallet LLC // Copyright © 2016 Litecoin Association <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation @objc public protocol BRWebSocket { var id: String { get } var request: BRHTTPRequest { get } var match: BRHTTPRouteMatch { get } func send(_ text: String) } @objc public protocol BRWebSocketClient { @objc optional func socketDidConnect(_ socket: BRWebSocket) @objc optional func socket(_ socket: BRWebSocket, didReceiveData data: Data) @objc optional func socket(_ socket: BRWebSocket, didReceiveText text: String) @objc optional func socketDidDisconnect(_ socket: BRWebSocket) } let GID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; enum SocketState { case headerb1 case headerb2 case lengthshort case lengthlong case mask case payload } enum SocketOpcode: UInt8, CustomStringConvertible { case stream = 0x0 case text = 0x1 case binary = 0x2 case close = 0x8 case ping = 0x9 case pong = 0xA var description: String { switch (self) { case .stream: return "STREAM" case .text: return "TEXT" case .binary: return "BINARY" case .close: return "CLOSE" case .ping: return "PING" case .pong: return "PONG" } } } let (MAXHEADER, MAXPAYLOAD) = (65536, 33554432) enum SocketCloseEventCode: UInt16 { case close_NORMAL = 1000 case close_GOING_AWAY = 1001 case close_PROTOCOL_ERROR = 1002 case close_UNSUPPORTED = 1003 case close_NO_STATUS = 1005 case close_ABNORMAL = 1004 case unsupportedData = 1006 case policyViolation = 1007 case close_TOO_LARGE = 1008 case missingExtension = 1009 case internalError = 1010 case serviceRestart = 1011 case tryAgainLater = 1012 case tlsHandshake = 1015 } class BRWebSocketServer { var sockets = [Int32: BRWebSocketImpl]() var thread: pthread_t? = nil var waiter: UnsafeMutablePointer<pthread_cond_t> var mutex: UnsafeMutablePointer<pthread_mutex_t> init() { mutex = UnsafeMutablePointer.allocate(capacity: MemoryLayout<pthread_mutex_t>.size) waiter = UnsafeMutablePointer.allocate(capacity: MemoryLayout<pthread_cond_t>.size) pthread_mutex_init(mutex, nil) pthread_cond_init(waiter, nil) } func add(_ socket: BRWebSocketImpl) { log("adding socket \(socket.fd)") pthread_mutex_lock(mutex) sockets[socket.fd] = socket socket.client.socketDidConnect?(socket) pthread_cond_broadcast(waiter) pthread_mutex_unlock(mutex) log("done adding socket \(socket.fd)") } func serveForever() { objc_sync_enter(self) if thread != nil { objc_sync_exit(self) return } let selfPointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) pthread_create(&thread, nil, { (sillySelf: UnsafeMutableRawPointer) in let localSelf = Unmanaged<BRWebSocketServer>.fromOpaque(sillySelf).takeUnretainedValue() localSelf.log("in server thread") localSelf._serveForever() return nil }, selfPointer) objc_sync_exit(self) } func _serveForever() { log("starting websocket poller") while true { pthread_mutex_lock(mutex) while sockets.count < 1 { log("awaiting clients") pthread_cond_wait(waiter, mutex) } pthread_mutex_unlock(mutex) // log("awaiting select") // all fds should be available for a read let readFds = sockets.map({ (ws) -> Int32 in return ws.0 }); // only fds which have items in the send queue are available for a write let writeFds = sockets.map({ (ws) -> Int32 in return ws.1.sendq.count > 0 ? ws.0 : -1 }).filter({ i in return i != -1 }) // build the select request and execute it, checking the result for an error let req = bw_select_request( write_fd_len: Int32(writeFds.count), read_fd_len: Int32(readFds.count), write_fds: UnsafeMutablePointer(mutating: writeFds), read_fds: UnsafeMutablePointer(mutating: readFds)); let resp = bw_select(req) if resp.error > 0 { let errstr = strerror(resp.error) log("error doing a select \(errstr) - removing all clients") sockets.removeAll() continue } // read for all readers that have data waiting for i in 0..<resp.read_fd_len { log("handle read fd \(sockets[resp.read_fds[Int(i)]]!.fd)") if let readSock = sockets[resp.read_fds[Int(i)]] { readSock.handleRead() } } // write for all writers for i in 0..<resp.write_fd_len { log("handle write fd=\(sockets[resp.write_fds[Int(i)]]!.fd)") if let writeSock = sockets[resp.write_fds[Int(i)]] { let (opcode, payload) = writeSock.sendq.removeFirst() do { let sentBytes = try sendBuffer(writeSock.fd, buffer: payload) if sentBytes != payload.count { let remaining = Array(payload.suffix(from: sentBytes - 1)) writeSock.sendq.insert((opcode, remaining), at: 0) break // terminate sends and continue sending on the next select } else { if opcode == .close { log("KILLING fd=\(writeSock.fd)") writeSock.response.kill() writeSock.client.socketDidDisconnect?(writeSock) sockets.removeValue(forKey: writeSock.fd) continue // go to the next select client } } } catch { // close... writeSock.response.kill() writeSock.client.socketDidDisconnect?(writeSock) sockets.removeValue(forKey: writeSock.fd) } } } // kill sockets that wrote out of bound data for i in 0..<resp.error_fd_len { if let errSock = sockets[resp.error_fds[Int(i)]] { errSock.response.kill() errSock.client.socketDidDisconnect?(errSock) sockets.removeValue(forKey: errSock.fd) } } } } // attempt to send a buffer, returning the number of sent bytes func sendBuffer(_ fd: Int32, buffer: [UInt8]) throws -> Int { log("send buffer fd=\(fd) buffer=\(buffer)") var sent = 0 try buffer.withUnsafeBufferPointer { pointer in while sent < buffer.count { let s = send(fd, pointer.baseAddress! + sent, Int(buffer.count - sent), 0) log("write result \(s)") if s <= 0 { let serr = Int32(s) // full buffer, should try again next iteration if Int32(serr) == EWOULDBLOCK || Int32(serr) == EAGAIN { return } else { self.log("socket write failed fd=\(fd) err=\(strerror(serr))") throw BRHTTPServerError.socketWriteFailed } } sent += s } } return sent } func log(_ s: String) { print("[BRWebSocketHost] \(s)") } } class BRWebSocketImpl: BRWebSocket { @objc var request: BRHTTPRequest var response: BRHTTPResponse @objc var match: BRHTTPRouteMatch var client: BRWebSocketClient var fd: Int32 var key: String! var version: String! @objc var id: String = UUID().uuidString var state = SocketState.headerb1 var fin: UInt8 = 0 var hasMask = false var opcode = SocketOpcode.stream var closed = false var index = 0 var length = 0 var lengtharray = [UInt8]() var lengtharrayWritten = 0 var data = [UInt8]() var dataWritten = 0 var maskarray = [UInt8]() var maskarrayWritten = 0 var fragStart = false var fragType = SocketOpcode.binary var fragBuffer = [UInt8]() var sendq = [(SocketOpcode, [UInt8])]() init(request: BRHTTPRequest, response: BRHTTPResponse, match: BRHTTPRouteMatch, client: BRWebSocketClient) { self.request = request self.match = match self.fd = request.fd self.response = response self.client = client } // MARK: - public interface impl @objc func send(_ text: String) { sendMessage(false, opcode: .text, data: [UInt8](text.utf8)) } // MARK: - private interface func handshake() -> Bool { log("handshake initiated") if let upgrades = request.headers["upgrade"] , upgrades.count > 0 { let upgrade = upgrades[0] if upgrade.lowercased() == "websocket" { if let ks = request.headers["sec-websocket-key"], let vs = request.headers["sec-websocket-version"] , ks.count > 0 && vs.count > 0 { key = ks[0] version = vs[0] do { let acceptStr = "\(key)\(GID)" as NSString // let acceptData = Data(bytes: UnsafePointer<UInt8>(acceptStr.utf8String!), // let acceptData = Data(bytes: acceptStr) // count: acceptStr.lengthOfBytes(using: String.Encoding.utf8.rawValue)); if var acceptStrBytes = acceptStr.utf8String { let acceptData = NSData( bytes: &acceptStrBytes, length: acceptStr.lengthOfBytes(using: String.Encoding.utf8.rawValue)) let acceptEncodedStr = NSData(uInt160: (acceptData as NSData).sha1()).base64EncodedString(options: []) try response.writeUTF8("HTTP/1.1 101 Switching Protocols\r\n") try response.writeUTF8("Upgrade: WebSocket\r\n") try response.writeUTF8("Connection: Upgrade\r\n") try response.writeUTF8("Sec-WebSocket-Accept: \(acceptEncodedStr)\r\n\r\n") } } catch let e { log("error writing handshake: \(e)") return false } log("handshake written to socket") // enter non-blocking mode if !setNonBlocking() { return false } return true } log("invalid handshake - missing sec-websocket-key or sec-websocket-version") } } log("invalid handshake - missing or malformed \"upgrade\" header") return false } func setNonBlocking() -> Bool { log("setting socket to non blocking") let nbResult = bw_nbioify(request.fd) if nbResult < 0 { log("unable to set socket to non blocking \(nbResult)") return false } return true } func handleRead() { var buf = [UInt8](repeating: 0, count: 1) let n = recv(fd, &buf, 1, 0) if n <= 0 { return // failed read - figure out what to do here i guess } parseMessage(buf[0]) } func parseMessage(_ byte: UInt8) { if state == .headerb1 { fin = byte & UInt8(0x80) guard let opc = SocketOpcode(rawValue: byte & UInt8(0x0F)) else { log("invalid opcode") return } opcode = opc log("parse HEADERB1 fin=\(fin) opcode=\(opcode)") state = .headerb2 index = 0 length = 0 let rsv = byte & 0x70 if rsv != 0 { // fail out here probably log("rsv bit is not zero! wat!") return } } else if state == .headerb2 { let mask = byte & 0x80 let length = byte & 0x7F if opcode == .ping { log("ping packet is too large! wat!") return } hasMask = mask == 128 if length <= 125 { self.length = Int(length) if hasMask { maskarray = [UInt8](repeating: 0, count: 4) maskarrayWritten = 0 state = .mask } else { // there is no mask and no payload then we're done if length <= 0 { handlePacket() data = [UInt8]() dataWritten = 0 state = .headerb1 } else { // there is no mask and some payload data = [UInt8](repeating: 0, count: self.length) dataWritten = 0 state = .payload } } } else if length == 126 { lengtharray = [UInt8](repeating: 0, count: 2) lengtharrayWritten = 0 state = .lengthshort } else if length == 127 { lengtharray = [UInt8](repeating: 0, count: 8) lengtharrayWritten = 0 state = .lengthlong } log("parse HEADERB2 hasMask=\(hasMask) opcode=\(opcode)") } else if state == .lengthshort { lengtharrayWritten += 1 if lengtharrayWritten > 2 { log("short length exceeded allowable size! wat!") return } lengtharray[lengtharrayWritten - 1] = byte if lengtharrayWritten == 2 { let ll = Data(bytes: lengtharray).withUnsafeBytes({ (p: UnsafePointer<UInt16>) -> UInt16 in if Int(OSHostByteOrder()) != OSBigEndian { return CFSwapInt16BigToHost(p.pointee) } return p.pointee }) length = Int(ll) if hasMask { maskarray = [UInt8](repeating: 0, count: 4) maskarrayWritten = 0 state = .mask } else { if length <= 0 { handlePacket() data = [UInt8]() dataWritten = 0 state = .headerb1 } else { data = [UInt8](repeating: 0, count: length) dataWritten = 0 state = .payload } } } log("parse LENGTHSHORT lengtharrayWritten=\(lengtharrayWritten) length=\(length) state=\(state) opcode=\(opcode)") } else if state == .lengthlong { lengtharrayWritten += 1 if lengtharrayWritten > 8 { log("long length exceeded allowable size! wat!") return } lengtharray[lengtharrayWritten - 1] = byte if lengtharrayWritten == 8 { let ll = Data(bytes: lengtharray).withUnsafeBytes({ (p: UnsafePointer<UInt64>) -> UInt64 in if Int(OSHostByteOrder()) != OSBigEndian { return CFSwapInt64BigToHost(p.pointee) } return p.pointee }) length = Int(ll) if hasMask { maskarray = [UInt8](repeating: 0, count: 4) maskarrayWritten = 0 state = .mask } else { if length <= 0 { handlePacket() data = [UInt8]() dataWritten = 0 state = .headerb1 } else { data = [UInt8](repeating: 0, count: length) dataWritten = 0 state = .payload } } } log("parse LENGTHLONG lengtharrayWritten=\(lengtharrayWritten) length=\(length) state=\(state) opcode=\(opcode)") } else if state == .mask { maskarrayWritten += 1 if lengtharrayWritten > 4 { log("mask exceeded allowable size! wat!") return } maskarray[maskarrayWritten - 1] = byte if maskarrayWritten == 4 { if length <= 0 { handlePacket() data = [UInt8]() dataWritten = 0 state = .headerb1 } else { data = [UInt8](repeating: 0, count: length) dataWritten = 0 state = .payload } } log("parse MASK maskarrayWritten=\(maskarrayWritten) state=\(state)") } else if state == .payload { dataWritten += 1 if dataWritten >= MAXPAYLOAD { log("payload exceed allowable size! wat!") return } if hasMask { log("payload byte length=\(length) mask=\(maskarray[index%4]) byte=\(byte)") data[dataWritten - 1] = byte ^ maskarray[index % 4] } else { log("payload byte length=\(length) \(byte)") data[dataWritten - 1] = byte } if index + 1 == length { log("payload done") handlePacket() data = [UInt8]() dataWritten = 0 state = .headerb1 } else { index += 1 } } } func handlePacket() { log("handle packet state=\(state) opcode=\(opcode)") // validate opcode if opcode == .close || opcode == .stream || opcode == .text || opcode == .binary { // valid } else if opcode == .pong || opcode == .ping { if dataWritten > 125 { log("control frame length can not be > 125") return } } else { log("unknown opcode") return } if opcode == .close { log("CLOSE") var status = SocketCloseEventCode.close_NORMAL var reason = "" if dataWritten >= 2 { let lt = Array(data.prefix(2)) let ll = Data(bytes: lt).withUnsafeBytes({ (p: UnsafePointer<UInt16>) -> UInt16 in return CFSwapInt16BigToHost(p.pointee) }) if let ss = SocketCloseEventCode(rawValue: ll) { status = ss } else { status = .close_PROTOCOL_ERROR } let lr = Array(data.suffix(from: 2)) if lr.count > 0 { if let rr = String(bytes: lr, encoding: String.Encoding.utf8) { reason = rr } else { log("bad utf8 data in close reason string...") status = .close_PROTOCOL_ERROR reason = "bad UTF8 data" } } } else { status = .close_PROTOCOL_ERROR } close(status, reason: reason) } else if fin == 0 { log("getting fragment \(fin)") if opcode != .stream { if opcode == .ping || opcode == .pong { log("error: control messages can not be fragmented") return } // start of fragments fragType = opcode fragStart = true fragBuffer = fragBuffer + data } else { if !fragStart { log("error: fragmentation protocol error y") return } fragBuffer = fragBuffer + data } } else { if opcode == .stream { if !fragStart { log("error: fragmentation protocol error x") return } if self.fragType == .text { if let str = String(bytes: data, encoding: String.Encoding.utf8) { self.client.socket?(self, didReceiveText: str) } else { log("error decoding utf8 data") } } else { let bin = Data(bytes: UnsafePointer<UInt8>(UnsafePointer(data)), count: data.count) self.client.socket?(self, didReceiveData: bin) } fragType = .binary fragStart = false fragBuffer = [UInt8]() } else if opcode == .ping { sendMessage(false, opcode: .pong, data: data) } else if opcode == .pong { // nothing to do } else { if fragStart { log("error: fragment protocol error z") return } if opcode == .text { if let str = String(bytes: data, encoding: String.Encoding.utf8) { self.client.socket?(self, didReceiveText: str) } else { log("error decoding uft8 data") } } } } } func close(_ status: SocketCloseEventCode = .close_NORMAL, reason: String = "") { if !closed { log("sending close") sendMessage(false, opcode: .close, data: status.rawValue.toNetwork() + [UInt8](reason.utf8)) } else { log("socket is already closed") } closed = true } func sendMessage(_ fin: Bool, opcode: SocketOpcode, data: [UInt8]) { log("send message opcode=\(opcode)") var b1: UInt8 = 0 var b2: UInt8 = 0 if !fin { b1 |= 0x80 } var payload = [UInt8]() // todo: pick the right size for this b1 |= opcode.rawValue payload.append(b1) if data.count <= 125 { b2 |= UInt8(data.count) payload.append(b2) } else if data.count >= 126 && data.count <= 65535 { b2 |= 126 payload.append(b2) payload.append(contentsOf: UInt16(data.count).toNetwork()) } else { b2 |= 127 payload.append(b2) payload.append(contentsOf: UInt64(data.count).toNetwork()) } payload.append(contentsOf: data) sendq.append((opcode, payload)) } func log(_ s: String) { print("[BRWebSocket \(fd)] \(s)") } } extension UInt16 { func toNetwork() -> [UInt8] { var selfBig = CFSwapInt16HostToBig(self) let size = MemoryLayout<UInt16>.size return Data(bytes: &selfBig, count: size).withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> [UInt8] in return Array(UnsafeBufferPointer(start: p, count: size)) }) } } extension UInt64 { func toNetwork() -> [UInt8] { var selfBig = CFSwapInt64HostToBig(self) let size = MemoryLayout<UInt64>.size return Data(bytes: &selfBig, count: size).withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> [UInt8] in return Array(UnsafeBufferPointer(start: p, count: size)) }) } }
mit
45e028cdeae88b403c780e833648147b
36.969072
134
0.490943
4.827903
false
false
false
false
slavapestov/swift
stdlib/public/core/Sequence.swift
1
21268
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Encapsulates iteration state and interface for iteration over a /// *sequence*. /// /// - Note: While it is safe to copy a *generator*, advancing one /// copy may invalidate the others. /// /// Any code that uses multiple generators (or `for`...`in` loops) /// over a single *sequence* should have static knowledge that the /// specific *sequence* is multi-pass, either because its concrete /// type is known or because it is constrained to `CollectionType`. /// Also, the generators must be obtained by distinct calls to the /// *sequence's* `generate()` method, rather than by copying. public protocol GeneratorType { /// The type of element generated by `self`. associatedtype Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. Specific implementations of this protocol /// are encouraged to respond to violations of this requirement by /// calling `preconditionFailure("...")`. @warn_unused_result mutating func next() -> Element? } /// A type that can be iterated with a `for`...`in` loop. /// /// `SequenceType` makes no requirement on conforming types regarding /// whether they will be destructively "consumed" by iteration. To /// ensure non-destructive iteration, constrain your *sequence* to /// `CollectionType`. /// /// As a consequence, it is not possible to run multiple `for` loops /// on a sequence to "resume" iteration: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // Not guaranteed to continue from the next element. /// } /// /// `SequenceType` makes no requirement about the behavior in that /// case. It is not correct to assume that a sequence will either be /// "consumable" and will resume iteration, or that a sequence is a /// collection and will restart iteration from the first element. /// A conforming sequence that is not a collection is allowed to /// produce an arbitrary sequence of elements from the second generator. public protocol SequenceType { /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. associatedtype Generator : GeneratorType // FIXME: should be constrained to SequenceType // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A type that represents a subsequence of some of the elements. associatedtype SubSequence /// Return a *generator* over the elements of this *sequence*. /// /// - Complexity: O(1). @warn_unused_result func generate() -> Generator /// Return a value less than or equal to the number of elements in /// `self`, **nondestructively**. /// /// - Complexity: O(N). @warn_unused_result func underestimateCount() -> Int /// Return an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] /// Return an `Array` containing the elements of `self`, /// in order, that satisfy the predicate `includeElement`. @warn_unused_result func filter( @noescape includeElement: (Generator.Element) throws -> Bool ) rethrows -> [Generator.Element] /// Call `body` on each element in `self` in the same order as a /// *for-in loop.* /// /// sequence.forEach { /// // body code /// } /// /// is similar to: /// /// for element in sequence { /// // body code /// } /// /// - Note: You cannot use the `break` or `continue` statement to exit the /// current call of the `body` closure or skip subsequent calls. /// - Note: Using the `return` statement in the `body` closure will only /// exit from the current call to `body`, not any outer scope, and won't /// skip subsequent calls. /// /// - Complexity: O(`self.count`) func forEach(@noescape body: (Generator.Element) throws -> Void) rethrows /// Returns a subsequence containing all but the first `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result func dropFirst(n: Int) -> SubSequence /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `self` is a finite sequence. /// - Requires: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result func dropLast(n: Int) -> SubSequence /// Returns a subsequence, up to `maxLength` in length, containing the /// initial elements. /// /// If `maxLength` exceeds `self.count`, the result contains all /// the elements of `self`. /// /// - Requires: `maxLength >= 0` @warn_unused_result func prefix(maxLength: Int) -> SubSequence /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `s`. /// /// - Requires: `self` is a finite sequence. /// - Requires: `maxLength >= 0` @warn_unused_result func suffix(maxLength: Int) -> SubSequence /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: (Generator.Element) throws -> Bool ) rethrows -> [SubSequence] @warn_unused_result func _customContainsEquatableElement( element: Generator.Element ) -> Bool? /// If `self` is multi-pass (i.e., a `CollectionType`), invoke /// `preprocess` and return its result. Otherwise, return `nil`. func _preprocessingPass<R>(@noescape preprocess: () -> R) -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Generator.Element> /// Copy a Sequence into an array, returning one past the last /// element initialized. func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>) -> UnsafeMutablePointer<Generator.Element> } /// A default generate() function for `GeneratorType` instances that /// are declared to conform to `SequenceType` extension SequenceType where Self.Generator == Self, Self : GeneratorType { public func generate() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` generator before possibly returning the first available element. /// /// The underlying generator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already dropped from the underlying sequence. internal class _DropFirstSequence<Base : GeneratorType> : SequenceType, GeneratorType { internal var generator: Base internal let limit: Int internal var dropped: Int internal init(_ generator: Base, limit: Int, dropped: Int = 0) { self.generator = generator self.limit = limit self.dropped = dropped } internal func generate() -> _DropFirstSequence<Base> { return self } internal func next() -> Base.Element? { while dropped < limit { if generator.next() == nil { dropped = limit return nil } dropped += 1 } return generator.next() } internal func dropFirst(n: Int) -> AnySequence<Base.Element> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return AnySequence( _DropFirstSequence(generator, limit: limit + n, dropped: dropped)) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` generator. /// /// The underlying generator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already taken from the underlying sequence. internal class _PrefixSequence<Base : GeneratorType> : SequenceType, GeneratorType { internal let maxLength: Int internal var generator: Base internal var taken: Int internal init(_ generator: Base, maxLength: Int, taken: Int = 0) { self.generator = generator self.maxLength = maxLength self.taken = taken } internal func generate() -> _PrefixSequence<Base> { return self } internal func next() -> Base.Element? { if taken >= maxLength { return nil } taken += 1 if let next = generator.next() { return next } taken = maxLength return nil } internal func prefix(maxLength: Int) -> AnySequence<Base.Element> { return AnySequence( _PrefixSequence(generator, maxLength: min(maxLength, self.maxLength), taken: taken)) } } //===----------------------------------------------------------------------===// // Default implementations for SequenceType //===----------------------------------------------------------------------===// extension SequenceType { /// Return an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result public func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimateCount() var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var generator = generate() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(generator.next()!)) } // Add remaining elements, if any. while let element = generator.next() { result.append(try transform(element)) } return Array(result) } /// Return an `Array` containing the elements of `self`, /// in order, that satisfy the predicate `includeElement`. @warn_unused_result public func filter( @noescape includeElement: (Generator.Element) throws -> Bool ) rethrows -> [Generator.Element] { var result = ContiguousArray<Generator.Element>() var generator = generate() while let element = generator.next() { if try includeElement(element) { result.append(element) } } return Array(result) } @warn_unused_result public func suffix(maxLength: Int) -> AnySequence<Generator.Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Generator.Element] = [] ringBuffer.reserveCapacity(min(maxLength, underestimateCount())) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i = i.successor() % maxLength } } if i != ringBuffer.startIndex { return AnySequence( [ringBuffer[i..<ringBuffer.endIndex], ringBuffer[0..<i]].flatten()) } return AnySequence(ringBuffer) } /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( maxSplit: Int = Int.max, allowEmptySlices: Bool = false, @noescape isSeparator: (Generator.Element) throws -> Bool ) rethrows -> [AnySequence<Generator.Element>] { _precondition(maxSplit >= 0, "Must take zero or more splits") var result: [AnySequence<Generator.Element>] = [] var subSequence: [Generator.Element] = [] func appendSubsequence() -> Bool { if subSequence.isEmpty && !allowEmptySlices { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplit == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var hitEnd = false var generator = self.generate() while true { guard let element = generator.next() else { hitEnd = true break } if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplit { break } } else { subSequence.append(element) } } if !hitEnd { while let element = generator.next() { subSequence.append(element) } } appendSubsequence() return result } /// Return a value less than or equal to the number of elements in /// `self`, **nondestructively**. /// /// - Complexity: O(N). @warn_unused_result public func underestimateCount() -> Int { return 0 } public func _preprocessingPass<R>(@noescape preprocess: () -> R) -> R? { return nil } @warn_unused_result public func _customContainsEquatableElement( element: Generator.Element ) -> Bool? { return nil } /// Call `body` on each element in `self` in the same order as a /// *for-in loop.* /// /// sequence.forEach { /// // body code /// } /// /// is similar to: /// /// for element in sequence { /// // body code /// } /// /// - Note: You cannot use the `break` or `continue` statement to exit the /// current call of the `body` closure or skip subsequent calls. /// - Note: Using the `return` statement in the `body` closure will only /// exit from the current call to `body`, not any outer scope, and won't /// skip subsequent calls. /// /// - Complexity: O(`self.count`) public func forEach( @noescape body: (Generator.Element) throws -> Void ) rethrows { for element in self { try body(element) } } } extension SequenceType where Generator.Element : Equatable { /// Returns the maximal `SubSequence`s of `self`, in order, around elements /// equatable to `separator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( separator: Generator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [AnySequence<Generator.Element>] { return split(maxSplit, allowEmptySlices: allowEmptySlices, isSeparator: { $0 == separator }) } } extension SequenceType where SubSequence : SequenceType, SubSequence.Generator.Element == Generator.Element, SubSequence.SubSequence == SubSequence { /// Returns a subsequence containing all but the first `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropFirst(n: Int) -> AnySequence<Generator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } return AnySequence(_DropFirstSequence(generate(), limit: n)) } /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `self` is a finite collection. /// - Requires: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast(n: Int) -> AnySequence<Generator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Generator.Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Generator.Element] = [] var ringBuffer: [Generator.Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = i.successor() % n } } return AnySequence(result) } @warn_unused_result public func prefix(maxLength: Int) -> AnySequence<Generator.Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Generator.Element>()) } return AnySequence(_PrefixSequence(generate(), maxLength: maxLength)) } } extension SequenceType { /// Returns a subsequence containing all but the first element. /// /// - Complexity: O(1) @warn_unused_result public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element. /// /// - Requires: `self` is a finite sequence. /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast() -> SubSequence { return dropLast(1) } } /// Return an underestimate of the number of elements in the given /// sequence, without consuming the sequence. For Sequences that are /// actually Collections, this will return `x.count`. @available(*, unavailable, message="call the 'underestimateCount()' method on the sequence") public func underestimateCount<T : SequenceType>(x: T) -> Int { fatalError("unavailable function can't be called") } extension SequenceType { public func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>) -> UnsafeMutablePointer<Generator.Element> { var p = UnsafeMutablePointer<Generator.Element>(ptr) for x in GeneratorSequence(self.generate()) { p.initialize(x) p += 1 } return p } } // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass a GeneratorType through GeneratorSequence to give it "SequenceType-ness" /// A sequence built around a generator of type `G`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just a generator `g`: /// /// for x in GeneratorSequence(g) { ... } public struct GeneratorSequence< Base : GeneratorType > : GeneratorType, SequenceType { @available(*, unavailable, renamed="Base") public typealias G = Base /// Construct an instance whose generator is a copy of `base`. public init(_ base: Base) { _base = base } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. public mutating func next() -> Base.Element? { return _base.next() } internal var _base: Base }
apache-2.0
05535bec387aeb8957c011de36c35679
31.72
92
0.648533
4.28186
false
false
false
false
iot-spotted/spotted
AppMessage/AppMessage/Controlers/ChatViewController.swift
1
20675
// // ChatViewController.swift // // Created by Edwin Vermeer on 11/14/14. // Copyright (c) 2014. All rights reserved. // import Foundation import CloudKit import JSQMessagesViewController import VIPhotoView import MapKit import UIImage_Resize import Async import EVCloudKitDao import EVReflection class ChatViewController: JSQMessagesViewController, MKMapViewDelegate { var chatWithId: String = "" var groupChatName: String = "" var dataID: String = "" var senderFirstName: String = "" var senderLastName: String = "" var localData: [JSQMessage?] = [] var recordIdMeForConnection: String = "" var recordIdOtherForConnection: String = "" var viewAppeared = false var topBar: UINavigationBar = UINavigationBar() var gameController: GameController! // Start the conversation func setContact(_ recordId: String, fakeGroupChatName: String) { chatWithId = GLOBAL_GROUP_ID groupChatName = GLOBAL_GROUP_NAME senderFirstName = getMyFirstName() senderLastName = getMyLastName() dataID = "Message_\(chatWithId)" initializeCommunication() } // Setting up the components override func viewDidLoad() { super.viewDidLoad() self.title = groupChatName // configure JSQMessagesViewController let defaultAvatarSize: CGSize = CGSize(width: kJSQMessagesCollectionViewAvatarSizeDefault, height: kJSQMessagesCollectionViewAvatarSizeDefault) self.collectionView!.collectionViewLayout.incomingAvatarViewSize = defaultAvatarSize //CGSizeZero self.collectionView!.collectionViewLayout.outgoingAvatarViewSize = defaultAvatarSize //CGSizeZero self.collectionView!.collectionViewLayout.springinessEnabled = false self.showLoadEarlierMessagesHeader = false //self.inputToolbar.contentView.leftBarButtonItem self.senderId = "~" self.senderDisplayName = "~" topBar.barStyle = UIBarStyle.blackOpaque topBar.tintColor = UIColor.white self.view.addSubview(topBar) let barItem = UINavigationItem(title: groupChatName) let back = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.camera, target: nil, action: #selector(loadCamera)) barItem.leftBarButtonItem = back topBar.setItems([barItem], animated: false) } override func viewDidLayoutSubviews() { topBar.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 60) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.viewAppeared = true initializeCommunication() } func loadCamera() { NotificationCenter.default.post(name: Notification.Name(rawValue:"loadCamera"), object: nil) } // ------------------------------------------------------------------------ // MARK: - Handle Message data plus attached Assets // ------------------------------------------------------------------------ func initializeCommunication(_ retryCount: Double = 1) { let recordIdMe = getMyRecordID() if !viewAppeared || (recordIdMeForConnection == recordIdMe && recordIdOtherForConnection == chatWithId) { return //Already connected or not ready yet } // Setup conversation for recordIdMeForConnection = recordIdMe recordIdOtherForConnection = chatWithId // Sender settings for the component self.senderId = recordIdMe self.senderDisplayName = showNameFor(EVCloudData.publicDB.dao.activeUser) // The data connection to the conversation EVCloudData.publicDB.connect(Message(), predicate: NSPredicate(format: "To_ID in %@", [recordIdOtherForConnection], [recordIdOtherForConnection, recordIdMeForConnection]), filterId: dataID, configureNotificationInfo: { notificationInfo in }, completionHandler: { results, status in EVLog("Conversation message results = \(results.count)") self.localData = [JSQMessage?](repeating: nil, count: results.count) self.checkAttachedAssets(results) self.collectionView!.reloadData() self.scrollToBottom(animated: true) return status == CompletionStatus.partialResult && results.count < 500 // Continue reading if we have less than 500 records and if there are more. }, insertedHandler: { item in EVLog("Conversation message inserted") self.localData.insert(nil, at: 0) if item.MessageType == MessageTypeEnum.Picture.rawValue { self.getAttachment((item as Message).Asset_ID) } JSQSystemSoundPlayer.jsq_playMessageReceivedSound() self.finishReceivingMessage() }, updatedHandler: { item, dataIndex in EVLog("Conversation message updated") self.localData[dataIndex] = nil }, deletedHandler: { recordId, dataIndex in EVLog("Conversation message deleted : \(recordId)") self.localData.remove(at: dataIndex) }, dataChangedHandler : { EVLog("Some conversation data was changed") }, errorHandler: { error in switch EVCloudKitDao.handleCloudKitErrorAs(error, retryAttempt: retryCount) { case .retry(let timeToWait): Async.background(after: timeToWait) { self.initializeCommunication(retryCount + 1) } case .fail: Helper.showError("Could not load messages: \(error.localizedDescription)") default: // For here there is no need to handle the .Success, and .RecoverableError break } }) } // Disconnect from the conversation deinit { EVCloudData.publicDB.disconnect(dataID) } // Make sure that all Message attachments are saved in a local file func checkAttachedAssets(_ results: [Message]) { let filemanager = FileManager.default let docDirPaths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) if docDirPaths.count > 0 { for item in results { if item.MessageType == MessageTypeEnum.Picture.rawValue { let filePath = (docDirPaths[0] as NSString).appendingPathComponent("\(item.Asset_ID).png") if !filemanager.fileExists(atPath: filePath) { self.getAttachment(item.Asset_ID) } } } } } // Get an asset and save it as a file func getAttachment(_ id: String) { EVCloudData.publicDB.getItem(id, completionHandler: {item in let docDirPaths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) if docDirPaths.count > 0 { let filePath = (docDirPaths[0] as NSString).appendingPathComponent("\(id).png") if let asset = item as? Asset { if let image = asset.File?.image() { if let myData = UIImagePNGRepresentation(image) { try? myData.write(to: URL(fileURLWithPath: filePath), options: [.atomic]) } } } } EVLog("Image downloaded to \(id).png") for (index, _) in (self.localData).enumerated() { if let data: Message = EVCloudData.publicDB.data[self.dataID]![index] as? Message { if data.Asset_ID == id { self.localData[index] = nil self.collectionView!.reloadItems(at: [IndexPath(item: index as Int, section: 0 as Int)]) } } } }, errorHandler: { error in Helper.showError("Could not load Asset: \(error.localizedDescription)") }) } // ------------------------------------------------------------------------ // MARK: - User interaction // ------------------------------------------------------------------------ override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { JSQSystemSoundPlayer.jsq_playMessageSentSound() let message = Message() message.setFromFields(recordIdMeForConnection) message.FromFirstName = senderFirstName message.FromLastName = senderLastName message.setToFields(chatWithId) message.GroupChatName = groupChatName message.Text = text if (text == "++") { gameController.IncrementScore(10) } EVCloudData.publicDB.saveItem(message, completionHandler: { message in self.finishSendingMessage() }, errorHandler: { error in self.finishSendingMessage() Helper.showError("Could not send message! \(error.localizedDescription)") }) self.finishSendingMessage() } // ------------------------------------------------------------------------ // MARK: - Standard CollectionView handling // ------------------------------------------------------------------------ override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return localData.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: JSQMessagesCollectionViewCell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell let message = getMessageForId((indexPath as NSIndexPath).row) if !message.isMediaMessage { if message.senderId == self.senderId { cell.textView!.textColor = UIColor.black } else { cell.textView!.textColor = UIColor.white } cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName : cell.textView!.textColor!, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue] } return cell } // ------------------------------------------------------------------------ // MARK: - JSQMessagesCollectionView handling // ------------------------------------------------------------------------ override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { return getMessageForId(indexPath.row) } //CellTopLabel override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { let message = getMessageForId(indexPath.row) return JSQMessagesTimestampFormatter.shared().attributedTimestamp(for: message.date) } override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAt indexPath: IndexPath!) -> CGFloat { return kJSQMessagesCollectionViewCellLabelHeightDefault } //messageBubbleImageDataForItemAtIndexPath override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { let message = getMessageForId(indexPath.row) let bubbleFactory = JSQMessagesBubbleImageFactory() if message.senderId == self.senderId { return bubbleFactory!.outgoingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray()) } return bubbleFactory!.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleGreen()) } // MessageBubbleTopLabel override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { let message = getMessageForId(indexPath.row) if message.senderId == self.senderId { return nil } if indexPath.row > 1 { let previousMessage = getMessageForId(indexPath.row - 1) if previousMessage.senderId == message.senderId { return nil } } return NSAttributedString(string: message.senderDisplayName) } // MessageBubbleTopLabel height override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat { let message = getMessageForId(indexPath.row) if message.senderId == self.senderId { return 0 } if indexPath.row > 1 { let previousMessage = getMessageForId(indexPath.row - 1) if previousMessage.senderId == message.senderId { return 0 } } return kJSQMessagesCollectionViewCellLabelHeightDefault } override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! { let message = getMessageForId(indexPath.row) var initials: String = "" if message.senderId == self.senderId { var firstName: String = getMyFirstName() var lastName: String = getMyLastName() print("Me: " + firstName + "," + lastName); initials = String(describing: firstName.characters.first!) + String(describing: lastName.characters.first!) print(initials) //initials = "\(Array(arrayLiteral: firstName)[0]) \(Array(arrayLiteral: lastName)[0])" } else { //initials = "\(Array(arrayLiteral: chatWithFirstName)[0]) \(Array(arrayLiteral: chatWithLastName)[0])" print("Someone: " + message.senderDisplayName) print(message.senderDisplayName) // http://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array let firstLast : [String] = message.senderDisplayName.components(separatedBy: " ") let firstName : String = firstLast[0] let lastName : String = firstLast[1] initials = "\(firstName.characters.first!)\(lastName.characters.first!)" print(initials) } // initials = "RM" let size: CGFloat = 14 let avatar = JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: initials, backgroundColor: UIColor.lightGray, textColor: UIColor.white, font: UIFont.systemFont(ofSize: size), diameter: 30) return avatar } // CellBottomLabel override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAt indexPath: IndexPath!) -> NSAttributedString! { return nil } // CellBottomLabel height override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAt indexPath: IndexPath!) -> CGFloat { return 0 } // ------------------------------------------------------------------------ // MARK: - JSQMessagesCollectionView events // ------------------------------------------------------------------------ override func collectionView(_ collectionView: JSQMessagesCollectionView!, header headerView: JSQMessagesLoadEarlierHeaderView!, didTapLoadEarlierMessagesButton sender: UIButton!) { EVLog("Should load earlier messages.") } override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, at indexPath: IndexPath!) { EVLog("Tapped avatar!") } override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) { EVLog("Tapped message bubble!") let (data, _) = getDataForId(indexPath.row) let message = getMessageForId(indexPath.row) let viewController = UIViewController() viewController.view.backgroundColor = UIColor.white // if data.MessageType == MessageTypeEnum.Picture.rawValue { // viewController.title = "Photo" // let photoView = VIPhotoView(frame:self.navigationController!.view.bounds, andImage:(message.media as? JSQPhotoMediaItem)?.image) // photoView?.autoresizingMask = UIViewAutoresizing(rawValue:1 << 6 - 1) // viewController.view.addSubview(photoView!) // self.navigationController!.pushViewController(viewController, animated: true) // } } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { mapView.setRegion(MKCoordinateRegionMakeWithDistance(view.annotation!.coordinate, 1000, 1000), animated: true) } override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapCellAt indexPath: IndexPath!, touchLocation: CGPoint) { EVLog("Tapped cel at \(indexPath.row)") } // ------------------------------------------------------------------------ // MARK: - Data parsing: Message to JSQMessage // ------------------------------------------------------------------------ func getDataForId(_ id: Int) -> (Message, Int) { var data: Message! var count: Int = 0 let lockQueue = DispatchQueue(label: "nl.evict.AppMessage.ChatLockQueue", attributes: []) lockQueue.sync { count = EVCloudData.publicDB.data[self.dataID]!.count if self.localData.count != count { self.localData = [JSQMessage?](repeating: nil, count: count) } if id < count { data = EVCloudData.publicDB.data[self.dataID]![count - id - 1] as! Message } else { data = Message() } } return (data, count) } func getMessageForId(_ id: Int) -> JSQMessage { // Get the CloudKit Message data plus count let (data, count) = getDataForId(id) // Should never happen... just here to prevent a crash if it does happen. if count <= id { return JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, text: "") } // The JSQMessage was already created before if let localMessage = self.localData[count - id - 1] { return localMessage } // Create a JSQMessage based on the Message object from CloudKit var message: JSQMessage! // receiving or sending.. var sender = self.senderId var senderName = self.senderDisplayName if data.From_ID != self.senderId { sender = data.From_ID senderName = data.FromFirstName + " " + data.FromLastName } // normal, location or media message if data.MessageType == MessageTypeEnum.Text.rawValue { message = JSQMessage(senderId: sender, senderDisplayName: senderName, date: data.creationDate, text: data.Text) } else if data.MessageType == MessageTypeEnum.Picture.rawValue { let docDirPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as NSString let filePath = docDirPath.appendingPathComponent(data.Asset_ID + ".png") let url = URL(fileURLWithPath: filePath) if let mediaData = try? Data(contentsOf: url) { let image = UIImage(data: mediaData) let photoItem = JSQPhotoMediaItem(image: image) message = JSQMessage(senderId: sender, senderDisplayName: senderName, date:data.creationDate, media: photoItem) } else { //url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("image-not-available", ofType: "jpg")!) //mediaData = NSData(contentsOfURL: url!) message = JSQMessage(senderId: sender, senderDisplayName: senderName, date:data.creationDate, media: JSQPhotoMediaItem()) } } localData[count - id - 1] = message return message } }
bsd-3-clause
d2e30143b40fa09d111d2c7ca9d480c7
43.848156
246
0.619927
5.67371
false
false
false
false
tryswift/tryswiftdev
tryswiftdevtest/BeforeUpdate/testFindItOneLine.swift
6
303
private let xcodeBuildInitialSettings = [ "ENABLE_BITCODE=0", "SWIFT_DISABLE_REQUIRED_ARCLITE=1", "SWIFT_LINK_OBJC_RUNTIME=1", "TOOLCHAINS=org.swift.3020160503a", "XCODE_DEFAULT_TOOLCHAIN_OVERRIDE=/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2016-05-03-a.xctoolchain", ]
mit
fe3ecbc306f0f75092c637232c7e6728
42.285714
121
0.745875
3.404494
false
false
false
false
wangkai678/WKDouYuZB
WKDouYuZB/WKDouYuZB/Classes/Tools/NetworkTools.swift
1
744
// // NetworkTools.swift // WKDouYuZB // // Created by 王凯 on 17/5/11. // Copyright © 2017年 wk. All rights reserved. // import UIKit import Alamofire enum MethodType{ case GET case POST } class NetworkTools: NSObject { class func requestData(type:MethodType,URLString:String,parameters:[String:Any]? = nil,finishedCallback:@escaping (_ result : Any) -> ()){ let method = type == .GET ? HTTPMethod.get : HTTPMethod.post; Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default).responseJSON { (response) in guard let result = response.result.value else{ return; } finishedCallback(result); }; } }
mit
72fa2f2e08fc7e7d8674b5184bdc8c11
26.296296
142
0.643148
4.1875
false
false
false
false
Cloudage/XWebView
XWebView/XWVHttpServer.swift
1
8991
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation #if os(iOS) import UIKit import MobileCoreServices #else import CoreServices #endif class XWVHttpServer : NSObject { private var socket: CFSocketRef! private var connections = Set<XWVHttpConnection>() private let overlays: [NSURL] private(set) var port: in_port_t = 0 var rootURL: NSURL { return overlays.last! } var overlayURLs: [NSURL] { return overlays.dropLast().reverse() } init(rootURL: NSURL, overlayURLs: [NSURL]?) { precondition(rootURL.fileURL) var overlays = [rootURL] overlayURLs?.forEach { precondition($0.fileURL) overlays.append($0) } self.overlays = overlays.reverse() super.init() } convenience init(rootURL: NSURL) { self.init(rootURL: rootURL, overlayURLs: nil) } deinit { stop() } private func listenOnPort(port: in_port_t) -> Bool { guard socket == nil else { return false } let info = UnsafeMutablePointer<Void>(unsafeAddressOf(self)) var context = CFSocketContext(version: 0, info: info, retain: nil, release: nil, copyDescription: nil) let callbackType = CFSocketCallBackType.AcceptCallBack.rawValue socket = CFSocketCreate(nil, PF_INET, SOCK_STREAM, 0, callbackType, ServerAcceptCallBack, &context) guard socket != nil else { log("!Failed to create socket") return false } var yes = UInt32(1) setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, &yes, UInt32(sizeof(UInt32))) var sockaddr = sockaddr_in( sin_len: UInt8(sizeof(sockaddr_in)), sin_family: UInt8(AF_INET), sin_port: port.bigEndian, sin_addr: in_addr(s_addr: UInt32(0x7f000001).bigEndian), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) let data = NSData(bytes: &sockaddr, length: sizeof(sockaddr_in)) guard CFSocketSetAddress(socket, data) == CFSocketError.Success else { log("!Failed to listen on port \(port) \(String(UTF8String: strerror(errno))!)") CFSocketInvalidate(socket) return false } NSThread.detachNewThreadSelector(Selector("serverLoop:"), toTarget: self, withObject: nil) return true } private func close() { // Close all connections. connections.forEach { $0.close() } connections.removeAll() // Close server socket. if socket != nil { CFSocketInvalidate(socket) socket = nil } } func start(port: in_port_t = 0) -> Bool { if port == 0 { // Try to find a random port in registered ports range for _ in 0 ..< 100 { let port = in_port_t(arc4random() % (49152 - 1024) + 1024) if listenOnPort(port) { self.port = port break } } } else if listenOnPort(port) { self.port = port } guard self.port != 0 else { return false } #if os(iOS) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("suspend:"), name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("resume:"), name: UIApplicationWillEnterForegroundNotification, object: nil) #endif return true } func stop() { #if os(iOS) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil) #endif port = 0 close() } func suspend(_: NSNotification!) { close() log("+HTTP server is suspended") } func resume(_: NSNotification!) { if listenOnPort(port) { log("+HTTP server is resumed") } } func serverLoop(_: AnyObject) { let runLoop = CFRunLoopGetCurrent() let source = CFSocketCreateRunLoopSource(nil, socket, 0) CFRunLoopAddSource(runLoop, source, kCFRunLoopCommonModes) CFRunLoopRun() } } extension XWVHttpServer : XWVHttpConnectionDelegate { func didOpenConnection(connection: XWVHttpConnection) { connections.insert(connection) } func didCloseConnection(connection: XWVHttpConnection) { connections.remove(connection) } func handleRequest(request: NSURLRequest) -> NSHTTPURLResponse { // Date format, see section 7.1.1.1 of RFC7231 let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US") dateFormatter.timeZone = NSTimeZone(name: "GMT") dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss z" var headers: [String: String] = ["Date": dateFormatter.stringFromDate(NSDate())] var statusCode = 500 var fileURL = NSURL() if request.URL == nil { // Bad request statusCode = 400 log("?Bad request") } else if request.HTTPMethod == "GET" || request.HTTPMethod == "HEAD" { let fileManager = NSFileManager.defaultManager() let relativePath = String(request.URL!.path!.characters.dropFirst()) for baseURL in overlays { var isDirectory: ObjCBool = false var url = NSURL(string: relativePath, relativeToURL: baseURL)! if fileManager.fileExistsAtPath(url.path!, isDirectory: &isDirectory) { if isDirectory { url = url.URLByAppendingPathComponent("index.html") } if fileManager.isReadableFileAtPath(url.path!) { fileURL = url break } } } if fileURL.path != nil { statusCode = 200 let attrs = try! fileManager.attributesOfItemAtPath(fileURL.path!) headers["Content-Type"] = getMIMETypeByExtension(fileURL.pathExtension!) headers["Content-Length"] = String(attrs[NSFileSize]!) headers["Last-Modified"] = dateFormatter.stringFromDate(attrs[NSFileModificationDate] as! NSDate) log("+\(request.HTTPMethod!) \(fileURL.path!)") } else { // Not found statusCode = 404 fileURL = NSURL() log("-File NOT found for URL \(request.URL!)") } } else { // Method not allowed statusCode = 405 headers["Allow"] = "GET HEAD" } if statusCode != 200 { headers["Content-Length"] = "0" } return NSHTTPURLResponse(URL: fileURL, statusCode: statusCode, HTTPVersion: "HTTP/1.1", headerFields: headers)! } } private func ServerAcceptCallBack(socket: CFSocket!, type: CFSocketCallBackType, address: CFData!, data:UnsafePointer<Void>, info: UnsafeMutablePointer<Void>) { let server = unsafeBitCast(info, XWVHttpServer.self) let handle = UnsafePointer<CFSocketNativeHandle>(data).memory assert(socket === server.socket && type == CFSocketCallBackType.AcceptCallBack) let connection = XWVHttpConnection(handle: handle, delegate: server) connection.open() } private var mimeTypeCache = [ // MIME types which are unknown by system. "css" : "text/css" ] private func getMIMETypeByExtension(extensionName: String) -> String { var type: String! = mimeTypeCache[extensionName] if type == nil { // Get MIME type through system-declared uniform type identifier. if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extensionName, nil), let mt = UTTypeCopyPreferredTagWithClass(uti.takeRetainedValue(), kUTTagClassMIMEType) { type = mt.takeRetainedValue() as String } else { // Fall back to binary stream. type = "application/octet-stream" } mimeTypeCache[extensionName] = type } if type.lowercaseString.hasPrefix("text/") { // Assume text resource is UTF-8 encoding return type + "; charset=utf-8" } return type }
apache-2.0
c68d73bf109c35b338ddbafbcfe7b9a8
36.152893
160
0.614281
4.849515
false
false
false
false
theMedvedev/eduConnect
eduConnect/LoginViewController.swift
1
1830
// // LoginViewController.swift // eduConnect // // Created by Alexey Medvedev on 1/14/17. // Copyright © 2017 #nyc1-2devsandarussian. All rights reserved. // import UIKit import FirebaseAuth import FirebaseInstanceID import Firebase import GoogleSignIn class LoginViewController: UIViewController, GIDSignInUIDelegate { override func viewDidLoad() { super.viewDidLoad() configureGoogleButton() NotificationCenter.default.addObserver(self, selector: #selector(redirectFromGoogle(_:)), name: .closeSafariVC, object: nil) } // Mark: Google Authentication Sign In func configureGoogleButton() { let googleButton = GIDSignInButton() googleButton.frame = CGRect(x: 16, y: 116 + 66, width: view.frame.width - 32, height: 50) googleButton.colorScheme = .light googleButton.style = .wide self.view.addSubview(googleButton) googleButton.translatesAutoresizingMaskIntoConstraints = false googleButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true googleButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true view.layoutIfNeeded() GIDSignIn.sharedInstance().uiDelegate = self } func redirectFromGoogle(_ notification: Notification) { NotificationCenter.default.post(name: .closeLoginVC, object: nil) } } // MARK: - Google UI Delegate func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) { viewController.dismiss(animated: true, completion: { _ in }) } func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) { NotificationCenter.default.post(name: .closeLoginVC, object: nil) }
mit
5031e3a93efdc371d688eabab1a4e3dd
25.897059
132
0.6807
4.800525
false
false
false
false
livioso/cpib
Compiler/Compiler/context/context.swift
1
4337
import Foundation enum ContextError: ErrorType { case IdentifierAlreadyDeclared case Not_R_Value case Not_L_Value case NotInScope case IdentifierNotDeclared case NotAllowedType case VariableIsConstant case TypeErrorInOperator case RecordCanNotBeInitializedDirectly case IdentifierAlreadyInitialized case IdentifierNotInitialized case NotWriteable case RecordsNotSupportedAsRightValue case InitialisationInTheRightSide case RoutineDeclarationNotGlobal case RecordIsConstButNotTheirFields case ThisExpressionNotAllowedWithDebugin case SomethingWentWrong //shouldn't be called! } enum ValueType { case BOOL case INT32 case RECORD case Unknown //Has to be replaced at the end! } enum RoutineType { case FUN case PROC } enum Side { case LEFT case RIGHT } enum ExpressionType { case L_Value case R_Value } enum MechModeType { case COPY case REF } enum ChangeModeType { case VAR case CONST } class ContextParameter { let mechMode:MechModeType let changeMode:ChangeModeType let ident:String let type:ValueType init(mechMode:MechModeType, changeMode:ChangeModeType, ident:String, type:ValueType) { self.mechMode = mechMode self.changeMode = changeMode self.ident = ident self.type = type } } class Scope { var storeTable: [String:Store] var recordTable:[String:Record] = [:] init(storeTable:[String:Store]) { self.storeTable = storeTable } init() { storeTable = [:] } } class Symbol { var ident:String var type:ValueType init(ident:String, type:ValueType){ self.ident = ident self.type = type } } class Store : Symbol{ var initialized:Bool var isConst:Bool var adress:Int = Int.min var reference:Bool = false var relative:Bool = false init(ident:String, type:ValueType, isConst:Bool){ self.initialized = false self.isConst = isConst super.init(ident: ident, type: type) } func paramCode(let loc:Int, let mechMode:MechModeType) -> Int { var loc1:Int = loc AST.codeArray[loc1++] = buildCommand(.LoadImInt, param: "\(adress)") if(mechMode == MechModeType.COPY) { AST.codeArray[loc1++] = buildCommand(.Deref) } return loc1 } func code(let loc:Int) -> Int { var loc1 = codeReference(loc) AST.codeArray[loc1++] = buildCommand(.Deref) return loc1 } func codeReference(let loc:Int) -> Int { var loc1 = loc if(relative) { AST.codeArray[loc1++] = buildCommand(.LoadAddrRel, param: "\(adress)") } else { AST.codeArray[loc1++] = buildCommand(.LoadImInt, param: "\(adress)") } if(reference){ AST.codeArray[loc1++] = buildCommand(.Deref) } return loc1 } } class Routine { let scope:Scope let ident:String let routineType:RoutineType let returnValue:Store? var parameterList: [ContextParameter] = [] var adress:Int? var calls: [Int] = [] init(ident:String, routineType: RoutineType, returnValue:Store? = nil) { self.ident = ident self.routineType = routineType self.scope = Scope() self.returnValue = returnValue } } class Record { let ident:String let scope:Scope var recordFields: [Store] = [] init(ident:String) { self.ident = ident self.scope = Scope() } func setInitialized(identifier:String) { scope.storeTable[identifier]?.initialized = true scope.storeTable[identifier]?.isConst = false for store in recordFields { if(store.ident == (ident + "." + identifier)) { store.initialized = true } } } func setInitializedDot(identifier:String) { for store in recordFields { if(store.ident == identifier) { store.initialized = true } } let idList = identifier.characters.split{ $0 == "." }.map(String.init) scope.storeTable[idList[1]]?.initialized = true scope.storeTable[idList[1]]?.isConst = false } }
mit
59c3632f8cbff0f5aeb4faa3125b2cc8
22.576087
90
0.615172
4.049486
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift
6
3109
// // Buffer.swift // Rx // // Created by Krunoslav Zaher on 9/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class BufferTimeCount<Element> : Producer<[Element]> { fileprivate let _timeSpan: RxTimeInterval fileprivate let _count: Int fileprivate let _scheduler: SchedulerType fileprivate let _source: Observable<Element> init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { _source = source _timeSpan = timeSpan _count = count _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == [Element] { let sink = BufferTimeCountSink(parent: self, observer: observer) sink.disposable = sink.run() return sink } } class BufferTimeCountSink<Element, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType where O.E == [Element] { typealias Parent = BufferTimeCount<Element> typealias E = Element private let _parent: Parent let _lock = NSRecursiveLock() // state private let _timerD = SerialDisposable() private var _buffer = [Element]() private var _windowID = 0 init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func run() -> Disposable { createTimer(_windowID) return Disposables.create(_timerD, _parent._source.subscribe(self)) } func startNewWindowAndSendCurrentOne() { _windowID = _windowID &+ 1 let windowID = _windowID let buffer = _buffer _buffer = [] forwardOn(.next(buffer)) createTimer(windowID) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let element): _buffer.append(element) if _buffer.count == _parent._count { startNewWindowAndSendCurrentOne() } case .error(let error): _buffer = [] forwardOn(.error(error)) dispose() case .completed: forwardOn(.next(_buffer)) forwardOn(.completed) dispose() } } func createTimer(_ windowID: Int) { if _timerD.isDisposed { return } if _windowID != windowID { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer nextTimer.disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in self._lock.performLocked { if previousWindowID != self._windowID { return } self.startNewWindowAndSendCurrentOne() } return Disposables.create() } } }
mit
b4049db5f71c226f8ee28643897ebb7c
25.117647
126
0.560811
4.871473
false
false
false
false
LawrenceHan/iOS-project-playground
RanchForecast/RanchForecastTests/ScheduleFetcherTests.swift
1
1059
// // ScheduleFetcherTests.swift // RanchForecast // // Created by Hanguang on 1/3/16. // Copyright © 2016 Hanguang. All rights reserved. // import XCTest import RanchForecast class ScheduleFetcherTests: XCTestCase { var fetcher: ScheduleFetcher! override func setUp() { super.setUp() fetcher = ScheduleFetcher() } override func tearDown() { fetcher = nil super.tearDown() } func testResultFromValidHTTPResponseAndValidData() { let result = fetcher.resultFromData(Constants.jsonData, response: Constants.okResponse, error: nil) switch result { case .Success(let courses): XCTAssert(courses.count == 1) let theCourse = courses[0] XCTAssertEqual(theCourse.title, Constants.title) XCTAssertEqual(theCourse.url, Constants.url) XCTAssertEqual(theCourse.nextStartDate, Constants.date) default: XCTFail("Result contains Failure, but Success was expected.") } } }
mit
12bc3b90697214521d455db58986269c
26.128205
107
0.634216
4.681416
false
true
false
false
kaxilisi/DouYu
DYZB/DYZB/Classes/Home/View/PageTitleView.swift
1
5208
// // PageTitleView.swift // DYZB // // Created by apple on 2016/10/9. // Copyright © 2016年 apple. All rights reserved. // import UIKit // MARK:- protocol PageTitleViewDelegate : class { func pageTitleView(_ titleView : PageTitleView ,selectedIndex index: Int) } // MARK:- private let scrollLineH :CGFloat = 2 private let kNormalColor :(CGFloat, CGFloat,CGFloat) = (85,85,85) private let kSelectColor :(CGFloat, CGFloat,CGFloat) = (255,120,0) // MARK:- class PageTitleView: UIView { fileprivate var currentIndex : Int = 0 fileprivate var titles : [String] weak var delegate : PageTitleViewDelegate? fileprivate lazy var titleLabels :[UILabel] = [UILabel]() fileprivate lazy var scrollView :UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false // scrollView.backgroundColor = UIColor.blueColor() return scrollView }() fileprivate lazy var scrollLine:UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() init(frame: CGRect,titles: [String]) { self.titles = titles super.init(frame:frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been imlemented" ) } } extension PageTitleView{ fileprivate func setupUI(){ addSubview(scrollView) scrollView.frame = bounds setupTitleLebels() setupBottomLineAndScrollLine() } fileprivate func setupTitleLebels(){ let labelW :CGFloat = frame.width/CGFloat(titles.count) let labelH :CGFloat = frame.height - scrollLineH let labelY :CGFloat = 0 for (index,title) in titles.enumerated() { let label = UILabel() label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center let labelX :CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titleLabels.append(label) //添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_:))) label.addGestureRecognizer(tapGes) } } fileprivate func setupBottomLineAndScrollLine(){ let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) guard let firstLabel = titleLabels.first else {return} firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - scrollLineH, width: firstLabel.frame.width, height: scrollLineH) } } //MARK:- extension PageTitleView{ @objc fileprivate func titleLabelClick(_ tapGes: UITapGestureRecognizer){ guard let currentLabel = tapGes.view as? UILabel else {return} if currentLabel.tag == currentIndex {return} let oldLabel = titleLabels[currentIndex] oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) currentIndex = currentLabel.tag let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.3, animations: { self.scrollLine.frame.origin.x = scrollLineX }) delegate?.pageTitleView(self, selectedIndex: currentIndex) } } extension PageTitleView { func setTitleVWithProgress(_ progress : CGFloat ,sourceIndex : Int , targetIndex :Int){ let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX let colorDelta = (kSelectColor.0 - kNormalColor.0,kSelectColor.1 - kNormalColor.1,kSelectColor.2 - kNormalColor.2) sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g:kSelectColor.1 - colorDelta.1 * progress, b:kSelectColor.2 - colorDelta.2 * progress) targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g:kNormalColor.1 + colorDelta.1 * progress, b:kNormalColor.2 + colorDelta.2 * progress) currentIndex = targetIndex } }
mit
464f7014d01a62abf1471010cb0f8b27
33.417219
172
0.6396
4.829926
false
false
false
false
angu/SwiftyStorj
SwiftyStorj/StorjTestApp/ViewControllers/BucketListViewController.swift
1
2397
// // BucketListViewController.swift // SwiftyStorj // // Created by Andrea Tullis on 14/07/2017. // Copyright © 2017 angu2111. All rights reserved. // import Foundation import UIKit import SnapKit public class BucketListViewController: UIViewController, BucketListPresenter { public let tableView = UITableView() private let refreshControl = UIRefreshControl() private let viewModel: BucketListViewModel private let alertPresenter: AlertPresenterProtocol public init(with viewModel: BucketListViewModel) { self.viewModel = viewModel self.alertPresenter = AlertPresenter() super.init(nibName: nil, bundle: nil) self.viewModel.presenter = self title = "Buckets" refreshControl.addTarget(self, action: #selector(BucketListViewController.refresh), for: UIControlEvents.valueChanged) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.dataSource = self.viewModel tableView.delegate = self.viewModel tableView.addSubview(refreshControl) view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } let addBucket = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(BucketListViewController.addBucket)) navigationItem.rightBarButtonItem = addBucket } func addBucket(){ alertPresenter.presentInputAlert(from: self, title: "New bucket", message: "Insert bucket name", placeHolder: "Bucket name") {[unowned self] (text) in //Send the text to the viewModel guard let bucketName = text else { return } self.viewModel.createNewBucket(bucketName: bucketName) } } func refresh() { refreshControl.beginRefreshing() viewModel.loadBuckets() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func didLoadBuckets() { refreshControl.endRefreshing() tableView.reloadData() } public override func viewDidLoad() { viewModel.loadBuckets() } }
lgpl-2.1
38621cdc3bd2812f538c9832dd496c48
29.329114
158
0.627295
5.585082
false
false
false
false
shopgun/shopgun-ios-sdk
Sources/TjekPublicationViewer/IncitoPublication/IncitoOffer.swift
1
3782
/// /// Copyright (c) 2019 Tjek. All rights reserved. /// import Foundation import Incito import UIKit public struct IncitoOffer { public struct Product: Decodable { public var title: String } public struct Id: Decodable { public var type: String public var provider: String public var value: String } public struct Label { public var source: URL public var title: String? public var link: URL? } public var title: String public var description: String? = nil public var link: URL? = nil public var products: [Product] = [] public var ids: [Id] = [] public var labels: [Label] = [] public var featureLabels: [String] = [] } extension IncitoOffer: Decodable { enum CodingKeys: String, CodingKey { case title, description, link, products, ids, labels, featureLabels = "feature_labels" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) self.title = try c.decode(String.self, forKey: .title) self.description = try? c.decode(String.self, forKey: .description) self.link = try? c.decode(URL.self, forKey: .link) self.products = (try? c.decode([Product].self, forKey: .products)) ?? [] self.ids = (try? c.decode([Id].self, forKey: .ids)) ?? [] self.labels = (try? c.decode([Label].self, forKey: .labels)) ?? [] self.featureLabels = (try? c.decode([String].self, forKey: .featureLabels)) ?? [] } } extension IncitoOffer.Label: Decodable { enum CodingKeys: String, CodingKey { case source = "src", title, link } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) self.source = try c.decode(URL.self, forKey: .source) self.title = try? c.decode(String.self, forKey: .title) self.link = try? c.decode(URL.self, forKey: .link) } } extension IncitoOffer { public init?(element: IncitoDocument.Element) { guard element.isOffer, let jsonValue = element.meta[IncitoDocument.Element.offerMetaKey], let jsonData: Data = try? JSONEncoder().encode(jsonValue), var offer = try? JSONDecoder().decode(IncitoOffer.self, from: jsonData) else { return nil } // feature labels are not part of the meta, so add them separately offer.featureLabels = element.featureLabels self = offer } } extension IncitoOffer { /// Return the `id` for provider 'tjek' or 'shopgun' public var coreId: String? { return self.ids.firstId(forProvider: "tjek") ?? self.ids.firstId(forProvider: "shopgun") } } extension Array where Element == IncitoOffer.Id { /// Note: `provider` is case-insensitively compared. public func firstId(forProvider provider: String) -> String? { return self.first(where: { $0.type.lowercased() == "id" && $0.provider.lowercased() == provider.lowercased() } )?.value } } extension IncitoDocument.Element { public static let offerMetaKey = "tjek.offer.v1" public var isOffer: Bool { return self.role == "offer" } /// If this element is an offer, try to decode the IncitoOffer from the `meta`. public var offer: IncitoOffer? { return IncitoOffer(element: self) } } extension IncitoViewController { public func firstOffer(at point: CGPoint, completion: @escaping (IncitoDocument.Element?) -> Void) { self.getFirstElement(at: point, where: \.isOffer, completion: completion) } }
mit
f95eac31fa1aeab2f061109b49c6f137
29.256
104
0.611052
4.088649
false
false
false
false
askari01/DailySwift
loops.swift
1
1137
// Simple Loop // For Loop /* for i in (1...5) { print("Hello World!") } */ // factorial /* var fact = 1 let number = 5 for i in (1...number) { fact *= i } print (fact) */ // print stars in right angle triangle /* var n = 5 for i in (1...n) { for j in (1...i) { print ("*", terminator: "") } print("") }*/ // print stars in pyramid /* var n = 5 for i in (1...n) { for k in stride(from:5, to:i, by: -1) { print (" ", terminator: "") } for j in (1...i) { print ("*", terminator: "") } print("") }*/ // print stars asymmetrical, upside down 2(n-1) /* var n = 4 for i in (1...(n)){ for k in (1...i){ print (" ", terminator: "") } for j in stride (from: 2(n-i), to: 0, by: -1) { print ("* ", terminator: "") } print (); }*/ // While Loop //count number of digits /* var n = 1234998675 var count = 0 while n > 0 { //n % 10 n = n / 10 count += 1 } print (count)*/ // febonacci series /* var n = 7 var a = 0 var b = 1 var c = 0 while (a <= n){ print(a) c = a + b a = b b = c }*/ // looping var days = ["M", "T", "W", "T", "F", "S", "S"] for day in days { print(day) }
mit
6839e796ee2a03fb8869bba18bd9cae9
12.535714
49
0.489006
2.59589
false
false
false
false
Pstoppani/swipe
core/SwipeNode.swift
4
2817
// // SwipeNode.swift // // Created by Pete Stoppani on 5/19/16. // import Foundation class SwipeNode: NSObject { var children = [SwipeNode]() private(set) weak var parent:SwipeNode? let eventHandler = SwipeEventHandler() init(parent: SwipeNode? = nil) { self.parent = parent super.init() } func evaluate(_ info:[String:Any]) -> [String:Any] { var result = [String:Any]() for k in info.keys { var val = info[k] if let valInfo = val as? [String:Any], let valOfInfo = valInfo["valueOf"] as? [String:Any] { val = getValue(self, info: valOfInfo) if val == nil { val = "" } } result[k] = val } return result } func execute(_ originator: SwipeNode, actions:[SwipeAction]?) { if actions == nil { return } for action in actions! { executeAction(originator, action: action) } } func executeAction(_ originator: SwipeNode, action: SwipeAction) { if let getInfo = action.info["get"] as? [String:Any] { SwipeHttpGet.create(self, getInfo: getInfo) } else if let postInfo = action.info["post"] as? [String:Any] { SwipeHttpPost.create(self, postInfo: postInfo) } else if let timerInfo = action.info["timer"] as? [String:Any] { SwipeTimer.create(self, timerInfo: timerInfo) } else { parent?.executeAction(originator, action: action) } } func getPropertyValue(_ originator: SwipeNode, property: String) -> Any? { return self.parent?.getPropertyValue(originator, property: property) } func getPropertiesValue(_ originator: SwipeNode, info: [String:Any]) -> Any? { return self.parent?.getPropertiesValue(originator, info: info) } func getValue(_ originator: SwipeNode, info: [String:Any]) -> Any? { var up = true if let val = info["search"] as? String { up = val != "children" } if let property = info["property"] as? String { return getPropertyValue(originator, property: property) } else if let propertyInfo = info["property"] as? [String:Any] { return getPropertiesValue(originator, info: propertyInfo) } else { if up { return self.parent?.getValue(originator, info: info) } else { for c in self.children { let val = c.getValue(originator, info: info) if val != nil { return val } } } } return nil } }
mit
db9ecbf28542fec5ee23e9cb62bc4726
30.3
104
0.528222
4.450237
false
false
false
false
mxcl/swift-package-manager
Sources/Commands/Error.swift
1
3390
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ import Basic import PackageModel import enum Utility.ColorWrap import enum Utility.Stream import func POSIX.exit import func Utility.isTTY import var Utility.stderr import enum PackageLoading.ManifestParseError public enum Error: Swift.Error { case noManifestFound case invalidToolchain case buildYAMLNotFound(String) case repositoryHasChanges(String) } extension Error: FixableError { public var error: String { switch self { case .noManifestFound: return "no \(Manifest.filename) file found" case .invalidToolchain: return "invalid inferred toolchain" case .buildYAMLNotFound(let value): return "no build YAML found: \(value)" case .repositoryHasChanges(let value): return "repository has changes: \(value)" } } public var fix: String? { switch self { case .noManifestFound: return "create a file named \(Manifest.filename) or run `swift package init` to initialize a new package" case .repositoryHasChanges(_): return "stage the changes and reapply them after updating the repository" default: return nil } } } public func handle(error: Any, usage: ((String) -> Void) -> Void) -> Never { switch error { case OptionParserError.multipleModesSpecified(let modes): print(error: error) if isTTY(.stdErr) && (modes.contains{ ["--help", "-h"].contains($0) }) { print("", to: &stderr) usage { print($0, to: &stderr) } } case OptionParserError.noCommandProvided(let hint): if !hint.isEmpty { print(error: error) } if isTTY(.stdErr) { usage { print($0, to: &stderr) } } case is OptionParserError: print(error: error) if isTTY(.stdErr) { let argv0 = CommandLine.arguments.first ?? "swift package" print("enter `\(argv0) --help' for usage information", to: &stderr) } case let error as FixableError: print(error: error.error) if let fix = error.fix { print(fix: fix) } case ManifestParseError.invalidManifestFormat(let errors): var errorString = "invalid manifest format" if let errors = errors { errorString += "; " + errors.joined(separator: ", ") } print(error: errorString) default: print(error: error) } exit(1) } private func print(error: Any) { if ColorWrap.isAllowed(for: .stdErr) { print(ColorWrap.wrap("error:", with: .Red, for: .stdErr), error, to: &stderr) } else { let cmd = AbsolutePath(CommandLine.arguments.first!, relativeTo:currentWorkingDirectory).basename print("\(cmd): error:", error, to: &stderr) } } private func print(fix: String) { if ColorWrap.isAllowed(for: .stdErr) { print(ColorWrap.wrap("fix:", with: .Yellow, for: .stdErr), fix, to: &stderr) } else { print("fix:", fix, to: &stderr) } }
apache-2.0
1e08155663d06284fbb1f6863247d845
29.818182
117
0.623304
4.21118
false
false
false
false
nathawes/swift
test/SILGen/lazy_property_with_observers.swift
12
10021
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class Foo { lazy var bar: Int = 0 { didSet(oldValue) {} willSet {} } lazy var baz: Int = 0 { didSet {} willSet {} } lazy var observable1: Int = 0 { didSet(oldValue) {} } lazy var observable2: Int = 0 { didSet {} } lazy var observable3: Int = 0 { willSet {} } } struct Foo1 { lazy var bar = 1 { didSet(oldValue) {} } } var foo1 = Foo1() foo1.bar = 2 // Setter which calls willSet and didSet (which fetches the oldValue) // // CHECK-LABEL: sil hidden [ossa] @$s28lazy_property_with_observers3FooC3barSivs : $@convention(method) (Int, @guaranteed Foo) -> () { // CHECK: bb0([[VALUE:%.*]] : $Int, [[FOO:%.*]] : @guaranteed $Foo): // CHECK-NEXT: debug_value [[VALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value [[FOO]] : $Foo, let, name "self", argno 2 // CHECK-NEXT: [[GETTER:%.*]] = class_method [[FOO]] : $Foo, #Foo.bar!getter : (Foo) -> () -> Int, $@convention(method) (@guaranteed Foo) -> Int // CHECK-NEXT: [[OLDVALUE:%.*]] = apply [[GETTER]]([[FOO]]) : $@convention(method) (@guaranteed Foo) -> Int // CHECK-NEXT: debug_value [[OLDVALUE]] : $Int, let, name "tmp" // CHECK-NEXT: // function_ref Foo.bar.willset // CHECK-NEXT: [[WILLSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC3barSivw : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[WILLSET_RESULT:%.*]] = apply [[WILLSET]]([[VALUE]], [[FOO]]) : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[ENUM:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[VALUE]] : $Int // CHECK-NEXT: [[REF_ELEM:%.*]] = ref_element_addr [[FOO]] : $Foo, #Foo.$__lazy_storage_$_bar // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ELEM]] : $*Optional<Int> // CHECK-NEXT: assign [[ENUM]] to [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: // function_ref Foo.bar.didset // CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC3barSivW : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[DIDSET_RESULT:%.*]] = apply [[DIDSET]]([[OLDVALUE]], [[FOO]]) : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // Setter which calls willSet and simple didSet (which doesn't fetch the oldValue) // // CHECK-LABEL: sil hidden [ossa] @$s28lazy_property_with_observers3FooC3bazSivs : $@convention(method) (Int, @guaranteed Foo) -> () { // CHECK: bb0([[VALUE:%.*]] : $Int, [[FOO:%.*]] : @guaranteed $Foo): // CHECK-NEXT: debug_value [[VALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value [[FOO]] : $Foo, let, name "self", argno 2 // CHECK-NEXT: // function_ref Foo.baz.willset // CHECK-NEXT: [[WILLSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC3bazSivw : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[WILLSET_RESULT:%.*]] = apply [[WILLSET]]([[VALUE]], [[FOO]]) : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[ENUM:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[VALUE]] : $Int // CHECK-NEXT: [[REF_ELEM:%.*]] = ref_element_addr [[FOO]] : $Foo, #Foo.$__lazy_storage_$_baz // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ELEM]] : $*Optional<Int> // CHECK-NEXT: assign [[ENUM]] to [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: // function_ref Foo.baz.didset // CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC3bazSivW : $@convention(method) (@guaranteed Foo) -> () // CHECK-NEXT: [[DIDSET_RESULT:%.*]] = apply [[DIDSET]]([[FOO]]) : $@convention(method) (@guaranteed Foo) -> () // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // Setter which calls didSet (which fetches oldValue) only // // CHECK-LABEL: sil hidden [ossa] @$s28lazy_property_with_observers3FooC11observable1Sivs : $@convention(method) (Int, @guaranteed Foo) -> () { // CHECK: bb0([[VALUE:%.*]] : $Int, [[FOO:%.*]] : @guaranteed $Foo): // CHECK-NEXT: debug_value [[VALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value [[FOO]] : $Foo, let, name "self", argno 2 // CHECK-NEXT: [[GETTER:%.*]] = class_method [[FOO]] : $Foo, #Foo.observable1!getter : (Foo) -> () -> Int, $@convention(method) (@guaranteed Foo) -> Int // CHECK-NEXT: [[OLDVALUE:%.*]] = apply [[GETTER]]([[FOO]]) : $@convention(method) (@guaranteed Foo) -> Int // CHECK-NEXT: debug_value [[OLDVALUE]] : $Int, let, name "tmp" // CHECK-NEXT: [[ENUM:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[VALUE]] : $Int // CHECK-NEXT: [[REF_ELEM:%.*]] = ref_element_addr [[FOO]] : $Foo, #Foo.$__lazy_storage_$_observable1 // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ELEM]] : $*Optional<Int> // CHECK-NEXT: assign [[ENUM]] to [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: // function_ref Foo.observable1.didset // CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC11observable1SivW : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[DIDSET_RESULT:%.*]] = apply [[DIDSET]]([[OLDVALUE]], [[FOO]]) : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // Setter which calls simple didSet (which doesn't fetch the oldValue) only // // CHECK-LABEL: sil hidden [ossa] @$s28lazy_property_with_observers3FooC11observable2Sivs : $@convention(method) (Int, @guaranteed Foo) -> () { // CHECK: bb0([[VALUE:%.*]] : $Int, [[FOO:%.*]] : @guaranteed $Foo): // CHECK-NEXT: debug_value [[VALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value [[FOO]] : $Foo, let, name "self", argno 2 // CHECK-NEXT: [[ENUM:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[VALUE]] : $Int // CHECK-NEXT: [[REF_ELEM:%.*]] = ref_element_addr [[FOO]] : $Foo, #Foo.$__lazy_storage_$_observable2 // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ELEM]] : $*Optional<Int> // CHECK-NEXT: assign [[ENUM]] to [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: // function_ref Foo.observable2.didset // CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC11observable2SivW : $@convention(method) (@guaranteed Foo) -> () // CHECK-NEXT: [[DIDSET_RESULT:%.*]] = apply [[DIDSET]]([[FOO]]) : $@convention(method) (@guaranteed Foo) -> () // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // Setter which calls willSet only // // CHECK-LABEL: sil hidden [ossa] @$s28lazy_property_with_observers3FooC11observable3Sivs : $@convention(method) (Int, @guaranteed Foo) -> () { // CHECK: bb0([[VALUE:%.*]] : $Int, [[FOO:%.*]] : @guaranteed $Foo): // CHECK-NEXT: debug_value [[VALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value [[FOO]] : $Foo, let, name "self", argno 2 // CHECK-NEXT: // function_ref Foo.observable3.willset // CHECK-NEXT: [[WILLSET:%.*]] = function_ref @$s28lazy_property_with_observers3FooC11observable3Sivw : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[WILLSET_RESULT:%.*]] = apply [[WILLSET]]([[VALUE]], [[FOO]]) : $@convention(method) (Int, @guaranteed Foo) -> () // CHECK-NEXT: [[ENUM:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[VALUE]] : $Int // CHECK-NEXT: [[REF_ELEM:%.*]] = ref_element_addr [[FOO]] : $Foo, #Foo.$__lazy_storage_$_observable3 // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ELEM]] : $*Optional<Int> // CHECK-NEXT: assign [[ENUM]] to [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Optional<Int> // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // Setter which calls a didSet (which fetches the oldValue) and uses a mutating getter // CHECK-LABEL: sil hidden [ossa] @$s28lazy_property_with_observers4Foo1V3barSivs : $@convention(method) (Int, @inout Foo1) -> () { // CHECK: bb0([[VALUE:%.*]] : $Int, [[FOO1:%.*]] : $*Foo1): // CHECK-NEXT: debug_value [[VALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value_addr [[FOO1]] : $*Foo1, var, name "self", argno 2 // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [unknown] %1 : $*Foo1 // CHECK-NEXT: // function_ref Foo1.bar.getter // CHECK-NEXT: [[GETTER:%.*]] = function_ref @$s28lazy_property_with_observers4Foo1V3barSivg : $@convention(method) (@inout Foo1) -> Int // CHECK-NEXT: [[OLDVALUE:%.*]] = apply [[GETTER]]([[BEGIN_ACCESS]]) : $@convention(method) (@inout Foo1) -> Int // CHECK-NEXT: debug_value [[OLDVALUE]] : $Int, let, name "tmp" // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Foo1 // CHECK-NEXT: [[ENUM:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[VALUE]] : $Int // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [unknown] [[FOO1]] : $*Foo1 // CHECK-NEXT: [[REF_ELEM:%.*]] = struct_element_addr [[BEGIN_ACCESS]] : $*Foo1, #Foo1.$__lazy_storage_$_bar // CHECK-NEXT: assign [[ENUM]] to [[REF_ELEM]] : $*Optional<Int> // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Foo1 // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [unknown] [[FOO1]] : $*Foo1 // CHECK-NEXT: // function_ref Foo1.bar.didset // CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s28lazy_property_with_observers4Foo1V3barSivW : $@convention(method) (Int, @inout Foo1) -> () // CHECK-NEXT: [[DIDSET_RESULT:%.*]] = apply [[DIDSET]]([[OLDVALUE]], [[BEGIN_ACCESS]]) : $@convention(method) (Int, @inout Foo1) -> () // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*Foo1 // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: }
apache-2.0
33585412b5f6af495342ed99d8405141
60.858025
154
0.61441
3.132541
false
false
false
false
adelinofaria/Buildasaur
Buildasaur/SyncPair_Branch_Bot.swift
2
2088
// // SyncPair_Branch_Bot.swift // Buildasaur // // Created by Honza Dvorsky on 19/05/15. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import XcodeServerSDK import BuildaGitServer import BuildaUtils public class SyncPair_Branch_Bot: SyncPair { let branch: Branch let bot: Bot let resolver: SyncPairBranchResolver public init(branch: Branch, bot: Bot, resolver: SyncPairBranchResolver) { self.branch = branch self.bot = bot self.resolver = resolver super.init() } override func sync(completion: Completion) { //sync the branch with the bot self.syncBranchWithBot(completion) } override func syncPairName() -> String { return "Branch (\(self.branch.name)) + Bot (\(self.bot.name))" } //MARK: Internal private func syncBranchWithBot(completion: Completion) { let syncer = self.syncer let bot = self.bot let headCommit = self.branch.commit.sha let issue: Issue? = nil //TODO: only pull/create if we're failing self.getIntegrations(bot, completion: { (integrations, error) -> () in if let error = error { completion(error: error) return } let actions = self.resolver.resolveActionsForCommitAndIssueWithBotIntegrations( headCommit, issue: issue, bot: bot, integrations: integrations) //in case of branches, we also (optionally) want to add functionality for creating an issue if the branch starts failing and updating with comments the same way we do with PRs. //also, when the build is finally successful on the branch, the issue will be automatically closed. //TODO: add this functionality here and add it as another action available from a sync pair self.performActions(actions, completion: completion) }) } }
mit
5b291976235427eeec0da60b7ddde0fd
30.636364
188
0.606322
4.971429
false
false
false
false
fabiomassimo/eidolon
KioskTests/Bid Fulfillment/ConfirmYourBidPINViewControllerTests.swift
1
2897
import Quick import Nimble import Kiosk import Moya import ReactiveCocoa import Nimble_Snapshots class ConfirmYourBidPINViewControllerTests: QuickSpec { override func spec() { it("looks right by default") { let subject = testConfirmYourBidPINViewController() subject.loadViewProgrammatically() expect(subject) == snapshot() } it("reacts to keypad inputs with the string") { let customKeySubject = RACSubject() let subject = testConfirmYourBidPINViewController() subject.pinSignal = customKeySubject subject.loadViewProgrammatically() customKeySubject.sendNext("2344"); expect(subject.pinTextField.text) == "2344" } it("reacts to keypad inputs with the string") { let customKeySubject = RACSubject() let deleteSubject = RACSubject() let subject = testConfirmYourBidPINViewController() subject.pinSignal = customKeySubject subject.loadViewProgrammatically() customKeySubject.sendNext("2"); expect(subject.pinTextField.text) == "2" subject.keypadContainer.deleteCommand.execute(nil) expect(subject.pinTextField.text) == "" } it("reacts to keypad inputs with the string") { let customKeySubject = RACSubject() let clearSubject = RACSubject() let subject = testConfirmYourBidPINViewController() subject.pinSignal = customKeySubject; subject.loadViewProgrammatically() customKeySubject.sendNext("222"); expect(subject.pinTextField.text) == "222" subject.keypadContainer.resetCommand.execute(nil) expect(subject.pinTextField.text) == "" } it("adds the correct auth params to a PIN'd request") { let auctionID = "AUCTION" let pin = "PIN" let number = "NUMBER" let subject = ConfirmYourBidPINViewController() let nav = FulfillmentNavigationController(rootViewController:subject) nav.auctionID = auctionID let provider: ReactiveMoyaProvider<ArtsyAPI> = subject.providerForPIN(pin, number: number) let endpoint = provider.endpointsClosure(ArtsyAPI.Me) let request = provider.endpointResolver(endpoint: endpoint) let address = request.URL!.absoluteString! expect(address).to( contain(auctionID) ) expect(address).to( contain(pin) ) expect(address).to( contain(number) ) } } } func testConfirmYourBidPINViewController() -> ConfirmYourBidPINViewController { return ConfirmYourBidPINViewController.instantiateFromStoryboard(fulfillmentStoryboard).wrapInFulfillmentNav() as! ConfirmYourBidPINViewController }
mit
8e844786ee5023190b3b68aaf6b3cfed
33.903614
150
0.641353
5.528626
false
true
false
false
DrGo/LearningSwift
PLAYGROUNDS/LSB_D001_TypedNotificationObservers.playground/section-2.swift
2
1781
import UIKit /* // Typed Notification Observers // // Based on: // http://www.objc.io/snippets/16.html /===================================*/ /*------------------------------------/ // Box: A hack for self-reference // // Suggested Reading: // http://www.quora.com/How-can-enumerations-in-Swift-be-recursive /------------------------------------*/ class Box<T> { let unbox: T init(_ value: T) { self.unbox = value } } /*------------------------------------/ // Notifications /------------------------------------*/ struct Notification<A> { let name: String } func postNotification<A>(note: Notification<A>, value: A) { let userInfo = ["value": Box(value)] NSNotificationCenter.defaultCenter().postNotificationName(note.name, object: nil, userInfo: userInfo) } class NotificationObserver { let observer: NSObjectProtocol init<A>(notification: Notification<A>, block aBlock: A -> ()) { observer = NSNotificationCenter.defaultCenter().addObserverForName(notification.name, object: nil, queue: nil) { note in if let value = (note.userInfo?["value"] as? Box<A>)?.unbox { aBlock(value) } else { assert(false, "Bad user info value") } } } deinit { NSNotificationCenter.defaultCenter().removeObserver(observer) } } let globalPanicNotification: Notification<NSError> = Notification(name: "Super bad error") let myError: NSError = NSError(domain: "com.pasdechocolat.example", code: 42, userInfo: [:]) let panicObserver = NotificationObserver(notification: globalPanicNotification) { err in println(err.localizedDescription) } /*------------------------------------/ // Run it! // Uncomment this. /------------------------------------*/ //postNotification(globalPanicNotification, myError)
gpl-3.0
67c3ce0da770c95c43d4ff660cf0f458
24.084507
124
0.587872
4.17096
false
false
false
false
DrGo/LearningSwift
PLAYGROUNDS/LSB_B013_ExpressionParser.playground/section-2.swift
2
12471
import UIKit /* // Expression Parser // // Based on: // http://www.objc.io/books/ (Chapter 12, Parser Combinators) // (Functional Programming in Swift, by Chris Eidhof, Florian Kugler, and Wouter Swierstra) /===================================*/ /*---------------------------------------------------------/ // Extensions /---------------------------------------------------------*/ extension String { var characters: [Character] { var result: [Character] = [] for c in self { result += [c] } return result } var slice: Slice<Character> { let res = self.characters return res[0..<res.count] } } extension Slice { var head: T? { return self.isEmpty ? nil : self[0] } var tail: Slice<T> { if (self.isEmpty) { return self } return self[(self.startIndex+1)..<self.endIndex] } var decompose: (head: T, tail: Slice<T>)? { return self.isEmpty ? nil : (self.head!, self.tail) } } /*---------------------------------------------------------/ // Helpers /---------------------------------------------------------*/ func none<A>() -> SequenceOf<A> { return SequenceOf(GeneratorOf { nil } ) } func one<A>(x: A) -> SequenceOf<A> { return SequenceOf(GeneratorOfOne(x)) } /*---------------------------------------------------------------------/ // Parser Type // We use a struct because typealiases don't support generic types. // // “We define a parser as a function that takes a slice of tokens, // processes some of these tokens, and returns a tuple of the result // and the remainder of the tokens.” // - Excerpt From: Chris Eidhof. “Functional Programming in Swift.” iBooks. /---------------------------------------------------------------------*/ struct Parser<Token, Result> { let p: Slice<Token> -> SequenceOf<(Result, Slice<Token>)> } /*---------------------------------------------------------------------/ // Simple example: Just parse single character "a" /---------------------------------------------------------------------*/ func parseA() -> Parser<Character, Character> { let a: Character = "a" return Parser { x in if let (head, tail) = x.decompose { if head == a { return one((a, tail)) } } return none() } } // Let's automate Parser testing func testParser<A>(parser: Parser<Character, A>, input: String) -> String { var result: [String] = [] for (x, s) in parser.p(input.slice) { result += ["Success, found \(x), remainder: \(Array(s))"] } return result.isEmpty ? "Parsing failed." : join("\n", result) } /*---------------------------------------------------------------------/ // Make generic over any kind of token /---------------------------------------------------------------------*/ func satisfy<Token>(condition: Token -> Bool) -> Parser<Token, Token> { return Parser { x in if let (head, tail) = x.decompose { if condition(head) { return one((head, tail)) } } return none() } } // But we can make it shorter func token<Token: Equatable>(t: Token) -> Parser<Token, Token> { return satisfy { $0 == t } } /*---------------------------------------------------------------------/ // Allow adding sequences /---------------------------------------------------------------------*/ struct JoinedGenerator<A>: GeneratorType { typealias Element = A var generator: GeneratorOf<GeneratorOf<A>> var current: GeneratorOf<A>? init(_ g: GeneratorOf<GeneratorOf<A>>) { generator = g current = generator.next() } mutating func next() -> A? { if var c = current { if let x = c.next() { return x } else { current = generator.next() return next() } } return nil } } func map<A, B>(var g: GeneratorOf<A>, f: A -> B) -> GeneratorOf<B> { return GeneratorOf { map(g.next(), f) } } func join<A>(s: SequenceOf<SequenceOf<A>>) -> SequenceOf<A> { return SequenceOf { JoinedGenerator(map(s.generate()) { $0.generate() }) } } func +<A>(l: SequenceOf<A>, r: SequenceOf<A>) -> SequenceOf<A> { return join(SequenceOf([l, r])) } /*---------------------------------------------------------------------/ // Choice operator - Combining multiple parsers /---------------------------------------------------------------------*/ infix operator <|> { associativity right precedence 130 } func <|> <Token, A>(l: Parser<Token, A>, r: Parser<Token, A>) -> Parser<Token, A> { return Parser { input in return l.p(input) + r.p(input) } } /*---------------------------------------------------------------------/ // Sequence the Parsers: The hard way /---------------------------------------------------------------------*/ func map<A, B>(var s: SequenceOf<A>, f: A -> B) -> SequenceOf<B> { return SequenceOf { map(s.generate(), f) } } func flatMap<A, B>(ls: SequenceOf<A>, f: A -> SequenceOf<B>) -> SequenceOf<B> { return join(map(ls, f)) } // This is our first attempt. It's a little confusing, due to the nesting. func sequence<Token, A, B>(l: Parser<Token, A>, r: Parser<Token, B>) -> Parser<Token, (A, B)> { return Parser { input in let leftResults = l.p(input) return flatMap(leftResults) { a, leftRest in let rightResults = r.p(leftRest) return map(rightResults, { b, rightRest in ((a, b), rightRest) }) } } } /*---------------------------------------------------------------------/ // Sequence the Parsers: The refined way /---------------------------------------------------------------------*/ // The Combinator func combinator<Token, A, B>(l: Parser<Token, A -> B>, r: Parser<Token, A>) -> Parser<Token, B> { return Parser { input in let leftResults = l.p(input) return flatMap(leftResults) { f, leftRemainder in let rightResults = r.p(leftRemainder) return map(rightResults) { x, rightRemainder in (f(x), rightRemainder) } } } } /*---------------------------------------------------------------------/ // Pure - Returns a value in a default context // pure :: a -> f a /---------------------------------------------------------------------*/ func pure<Token, A>(value: A) -> Parser<Token, A> { return Parser { one((value, $0)) } } /*---------------------------------------------------------------------/ // <*> // // “for Maybe, <*> extracts the function from the left value if it’s // a Just and maps it over the right value. If any of the parameters // is Nothing, Nothing is the result.” // - Excerpt From: Miran Lipovaca. “Learn You a Haskell for Great Good!.” iBooks. /---------------------------------------------------------------------*/ infix operator <*> { associativity left precedence 150 } func <*><Token, A, B>(l: Parser<Token, A -> B>, r: Parser<Token, A>) -> Parser<Token, B> { return combinator(l, r) } /*---------------------------------------------------------------------/ // Combine several existing strings /---------------------------------------------------------------------*/ func string(characters: [Character]) -> String { var s = "" s.extend(characters) return s } func combine(a: Character)(b: Character)(c: Character) -> String { return string([a, b, c]) } /*---------------------------------------------------------------------/ // Any character from a set /---------------------------------------------------------------------*/ func member(set: NSCharacterSet, character: Character) -> Bool { let unichar = (String(character) as NSString).characterAtIndex(0) return set.characterIsMember(unichar) } func characterFromSet(set: NSCharacterSet) -> Parser<Character, Character> { return satisfy { return member(set, $0) } } let decimals = NSCharacterSet.decimalDigitCharacterSet() let decimalDigit = characterFromSet(decimals) // Since @autoclosure was discontinued in Swift 1.2, lazy won't work. // Attempting to use Box here will result in an infinite loop. ///*---------------------------------------------------------------------/ //// Zero or More ///---------------------------------------------------------------------*/ //func prepend<A>(l: A) -> [A] -> [A] { // return { (x: [A]) in [l] + x } //} // // //// So we use an autoclosure instead //func lazy<Token, A>(f: @autoclosure () -> Parser<Token, A>) -> Parser<Token, A> { // return Parser { x in f().p(x) } //} // // //func zeroOrMore<Token, A>(p: Parser<Token, A>) -> Parser<Token, [A]> { // return (pure(prepend) <*> p <*> lazy(zeroOrMore(p))) <|> pure([]) //} // // ///*---------------------------------------------------------------------/ //// One or More ///---------------------------------------------------------------------*/ //func oneOrMore<Token, A>(p: Parser<Token, A>) -> Parser<Token, [A]> { // return pure(prepend) <*> p <*> zeroOrMore(p) //} // // ///*---------------------------------------------------------------------/ //// </> ==> pure(l) <*> r //// //// a.k.a Haskell's <$> ///---------------------------------------------------------------------*/ //infix operator </> { precedence 170 } //func </> <Token, A, B>(l: A -> B, // r: Parser<Token, A>) -> Parser<Token, B> { // // return pure(l) <*> r //} // // ///*---------------------------------------------------------------------/ //// Add two integers with "+" //// //// We'll see an easier way to "skip" the operator below (<*) ///---------------------------------------------------------------------*/ //let plus: Character = "+" //func add(x: Int)(_: Character)(y: Int) -> Int { // return x + y //} // //let number = { characters in string(characters).toInt()! } </> oneOrMore(decimalDigit) // // ///*---------------------------------------------------------------------/ //// <* Throw away the right-hand result ///---------------------------------------------------------------------*/ //infix operator <* { associativity left precedence 150 } //func <* <Token, A, B>(p: Parser<Token, A>, q: Parser<Token, B>) // -> Parser<Token, A> { // // return {x in {_ in x} } </> p <*> q //} // // ///*---------------------------------------------------------------------/ //// *> Throw away the left-hand result ///---------------------------------------------------------------------*/ //infix operator *> { associativity left precedence 150 } //func *> <Token, A, B>(p: Parser<Token, A>, // q: Parser<Token, B>) -> Parser<Token, B> { // // return {_ in {y in y} } </> p <*> q //} // // //func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C { // return { x in { y in f(x, y) } } //} // // ///*=====================================================================/ //// Expression Parser ///=====================================================================*/ // // ///*---------------------------------------------------------------------/ //// </ Consumes, but doesn't use its right operand ///---------------------------------------------------------------------*/ //infix operator </ { precedence 170 } //func </ <Token, A, B>(l: A, r: Parser<Token, B>) -> Parser<Token, A> { // return pure(l) <* r //} // // //func optionallyFollowed<A>(l: Parser<Character, A>, // r: Parser<Character, A -> A>) // -> Parser<Character, A> { // // let apply: A -> (A -> A) -> A = { x in { f in f(x) } } // return apply </> l <*> (r <|> pure { $0 }) //} // // //func flip<A, B, C>(f: (B, A) -> C) -> (A, B) -> C { // return { (x, y) in f(y, x) } //} // // //typealias Calculator = Parser<Character, Int> //typealias Op = (Character, (Int, Int) -> Int) //let operatorTable: [Op] = [("*", *), ("/", /), ("+", +), ("-", -)] // // //func op(character: Character, // evaluate: (Int, Int) -> Int, // operand: Calculator) -> Calculator { // // let withOperator = curry(flip(evaluate)) </ token(character) <*> operand // return optionallyFollowed(operand, withOperator) //} // // //func eof<A>() -> Parser<A, ()> { // return Parser { stream in // if (stream.isEmpty) { // return one(((), stream)) // } // return none() // } //} // // //func pExpression() -> Calculator { // return operatorTable.reduce(number) { next, inOp in // op(inOp.0, inOp.1, next) // } //} //testParser(pExpression() <* eof(), "10-3*2")
gpl-3.0
763b3b888f24d7f13f10d5d81a4762d4
28.301176
94
0.432908
4.12761
false
false
false
false
jjcmwangxinyu/DouYuTV
DouYuTV/DouYuTV/Classes/Tools/UIBarButtonItemExtension.swift
1
1101
// // UIBarButtonItemExtension.swift // DouYuTV // // Created by 王新宇 on 2017/3/12. // Copyright © 2017年 王新宇. All rights reserved. // import UIKit extension UIBarButtonItem { // class func createItem(imageName:String,highImageName:String, size:CGSize) -> UIBarButtonItem { // let btn = UIButton() // btn.setImage(UIImage(named:imageName), for: UIControlState.normal) // btn.setImage(UIImage(named:highImageName), for: UIControlState.highlighted) // btn.frame.size = size // return UIBarButtonItem(customView: btn) // } convenience init(imageName:String,highImageName:String = "",size:CGSize = CGSize.zero) { let btn = UIButton() btn.setImage(UIImage(named:imageName), for: UIControlState.normal) if highImageName != "" { btn.setImage(UIImage(named:highImageName), for: UIControlState.highlighted) } if size == CGSize.zero { btn.sizeToFit() }else { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView:btn) } }
mit
558e04f538114c7db8b61c30fe75fcd2
34.032258
100
0.640884
4.145038
false
false
false
false
johnno1962d/swift
stdlib/public/core/Unmanaged.swift
1
6774
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// /// A type for propagating an unmanaged object reference. /// /// When you use this type, you become partially responsible for /// keeping the object alive. @_fixed_layout public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance @_versioned @_transparent internal init(_private: Instance) { _value = _private } /// Unsafely turn an opaque C pointer into an unmanaged /// class reference. /// /// This operation does not change reference counts. /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() @_transparent @warn_unused_result public static func fromOpaque(_ value: OpaquePointer) -> Unmanaged { return Unmanaged(_private: unsafeBitCast(value, to: Instance.self)) } /// Create an unmanaged reference with an unbalanced retain. /// The object will leak if nothing eventually balances the retain. /// /// This is useful when passing an object to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +1. @_transparent @warn_unused_result public static func passRetained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value).retain() } /// Create an unmanaged reference without performing an unbalanced /// retain. /// /// This is useful when passing a reference to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +0. /// /// CFArraySetValueAtIndex(.passUnretained(array), i, /// .passUnretained(object)) @_transparent @warn_unused_result public static func passUnretained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value) } /// Get the value of this unmanaged reference as a managed /// reference without consuming an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're not responsible for releasing the result. @warn_unused_result public func takeUnretainedValue() -> Instance { return _value } /// Get the value of this unmanaged reference as a managed /// reference and consume an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're responsible for releasing the result. @warn_unused_result public func takeRetainedValue() -> Instance { let result = _value release() return result } /// Get the value of the unmanaged referenced as a managed reference without /// consuming an unbalanced retain of it and pass it to the closure. Asserts /// that there is some other reference ('the owning reference') to the /// instance referenced by the unmanaged reference that guarantees the /// lifetime of the instance for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// NOTE: You are responsible for ensuring this by making the owning /// reference's lifetime fixed for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// Violation of this will incur undefined behavior. /// /// A lifetime of a reference 'the instance' is fixed over a point in the /// programm if: /// /// * There exists a global variable that references 'the instance'. /// /// import Foundation /// var globalReference = Instance() /// func aFunction() { /// point() /// } /// /// Or if: /// /// * There is another managed reference to 'the instance' whose life time is /// fixed over the point in the program by means of 'withExtendedLifetime' /// dynamically closing over this point. /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// point($0) /// } /// /// Or if: /// /// * There is a class, or struct instance ('owner') whose lifetime is fixed /// at the point and which has a stored property that references /// 'the instance' for the duration of the fixed lifetime of the 'owner'. /// /// class Owned { /// } /// /// class Owner { /// final var owned : Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(...) /// } // Assuming: No stores to owned occur for the dynamic lifetime of /// // the withExtendedLifetime invocation. /// } /// /// func doSomething() { /// // both 'self' and 'owned''s lifetime is fixed over this point. /// point(self, owned) /// } /// } /// /// The last rule applies transitively through a chains of stored references /// and nested structs. /// /// Examples: /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// let u = Unmanaged.passUnretained(owningReference) /// for i in 0 ..< 100 { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } /// /// class Owner { /// final var owned : Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(Unmanaged.passUnretained(owned)) /// } /// } /// /// func doSomething(_ u : Unmanaged<Owned>) { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } public func _withUnsafeGuaranteedRef<Result>( _ closure: @noescape (Instance) throws -> Result ) rethrows -> Result { let instance = _value let (guaranteedInstance, token) = Builtin.unsafeGuaranteed(instance) let result = try closure(guaranteedInstance) Builtin.unsafeGuaranteedEnd(token) return result } /// Perform an unbalanced retain of the object. @_transparent public func retain() -> Unmanaged { Builtin.retain(_value) return self } /// Perform an unbalanced release of the object. @_transparent public func release() { Builtin.release(_value) } #if _runtime(_ObjC) /// Perform an unbalanced autorelease of the object. @_transparent public func autorelease() -> Unmanaged { Builtin.autorelease(_value) return self } #endif }
apache-2.0
032807d06063bad1c3ccdacd970dd9ee
31.411483
80
0.627694
4.598778
false
false
false
false
phanviet/AppState
Example/AppState/AppWorkflow.swift
1
1667
// // AppWorkflow.swift // AppState // // Created by Phan Hong Viet on 11/30/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import AppState struct AppWorkflow { static var sharedInstance = AppState(initialState: "root", events: [ AppStateEvent(name: "showLandingPage", from: "root", to: "landingPage"), AppStateEvent(name: "backLandingPage", from: ["signInPage", "welcomePage"], to: "landingPage") ]) static var currentViewController = UIViewController() init() { // Init all sub workflow _ = SignInWorkflow() // Add delegate for root view controller AppWorkflow.sharedInstance.registerViewController(UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("viewController"), forState: "landingPage") } /** Check whether a view controller instance is in navigation stack */ static func isViewControllerInStack(view : UIViewController) -> Bool { for var index = 0; index < AppWorkflow.currentViewController.navigationController?.viewControllers.count; index++ { if ((AppWorkflow.currentViewController.navigationController?.viewControllers[index].isKindOfClass(view.dynamicType))! == true) { return true } } return false } static func currentViewControllerPushOrPopController(controller: UIViewController) { if AppWorkflow.isViewControllerInStack(controller) { AppWorkflow.currentViewController.navigationController?.popToViewController(controller, animated: true) } else { AppWorkflow.currentViewController.navigationController?.pushViewController(controller, animated: true) } } }
mit
1e1be486359358aa38931ba2b4fd713c
31.686275
177
0.729292
4.843023
false
false
false
false
HJliu1123/LearningNotes-LHJ
April/Xbook/Xbook/BookDetail/VIew/HJDiscussCell.swift
1
2123
// // HJDiscussCell.swift // Xbook // // Created by liuhj on 16/4/15. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit class HJDiscussCell: UITableViewCell { var avatarImage : UIImageView? var nameLabel : UILabel? var detailLabel : UILabel? var dateLabel : UILabel? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } func initFrame() { for view in self.contentView.subviews { view.removeFromSuperview() } self.avatarImage = UIImageView(frame: CGRectMake(8, 8, 40, 40)) self.avatarImage?.layer.cornerRadius = 20 self.avatarImage?.layer.masksToBounds = true self.contentView.addSubview(self.avatarImage!) self.nameLabel = UILabel(frame: CGRectMake(56, 8, SCREEN_WIDTH - 56 - 8, 15)) self.nameLabel?.font = UIFont(name: MY_FONT, size: 13) self.contentView.addSubview(self.nameLabel!) self.dateLabel = UILabel(frame: CGRectMake(56, self.frame.size.height - 8 - 10, SCREEN_WIDTH - 56 - 8, 10)) self.dateLabel?.font = UIFont(name: MY_FONT, size: 13) self.dateLabel?.textColor = UIColor.grayColor() self.contentView.addSubview(self.dateLabel!) self.detailLabel = UILabel(frame: CGRectMake(56, 30, SCREEN_WIDTH - 56 - 8, self.frame.size.height - 30 - 25)) self.detailLabel?.font = UIFont(name: MY_FONT, size: 15) self.detailLabel?.numberOfLines = 0 self.contentView.addSubview(self.detailLabel!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f8e276d58850b017068915dfe64c998d
23.941176
118
0.589623
4.608696
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/EmojiAnimationEffectView.swift
1
2191
// // EmojiAnimationEffect.swift // Telegram // // Created by Mikhail Filimonov on 14.09.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit import AppKit final class EmojiAnimationEffectView : View { enum Source { case builtin(LottieAnimation) case custom(CustomReactionEffectView) } private let player: NSView private let animation: Source let animationSize: NSSize private var animationPoint: CGPoint var index: Int? = nil init(animation: Source, animationSize: NSSize, animationPoint: CGPoint, frameRect: NSRect) { self.animation = animation self.animationSize = animationSize self.animationPoint = animationPoint let view: NSView switch animation { case let .builtin(animation): let player = LottiePlayerView(frame: .init(origin: animationPoint, size: animationSize)) player.set(animation) view = player player.isEventLess = true case let .custom(current): view = current } self.player = view super.init(frame: frameRect) addSubview(view) isEventLess = true updateLayout(size: frameRect.size, transition: .immediate) } override func layout() { super.layout() self.updateLayout(size: frame.size, transition: .immediate) } func updateLayout(size: NSSize, transition: ContainedViewLayoutTransition) { transition.updateFrame(view: self.player, frame: CGRect(origin: animationPoint, size: animationSize)) if let view = player as? LottiePlayerView { view.update(size: animationSize, transition: transition) } } func updatePoint(_ point: NSPoint, transition: ContainedViewLayoutTransition) { self.animationPoint = point self.updateLayout(size: frame.size, transition: transition) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } }
gpl-2.0
c141ee010be78afe3b47bafca581027c
30.285714
109
0.649315
4.834437
false
false
false
false
ZevEisenberg/Padiddle
Padiddle/Padiddle/Model/ImageIO.swift
1
4318
// // ImageIO.swift // Padiddle // // Created by Zev Eisenberg on 1/24/16. // Copyright © 2016 Zev Eisenberg. All rights reserved. // import UIKit.UIImage enum ImageIO { static func persistImageInBackground(_ image: UIImage, contextScale: CGFloat, contextSize: CGSize) { if !Defaults.snapshotMode { // no-op in screenshot mode let app = UIApplication.shared backgroundSaveTask = app.beginBackgroundTask { if let task = self.backgroundSaveTask { app.endBackgroundTask(task) self.backgroundSaveTask = .invalid } } DispatchQueue.global(qos: .default).async { defer { if let task = self.backgroundSaveTask { app.endBackgroundTask(task) } self.backgroundSaveTask = .invalid } guard let imageData = image.pngData() else { Log.error("Could not generate PNG to save image: \(image)") return } let imageURL = urlForPersistedImage(contextScale, contextSize: contextSize) do { try imageData.write(to: imageURL, options: [.atomic]) } catch { Log.error("Error writing to file: \(error)") } do { try addSkipBackupAttributeToItem(atUrl: imageURL) } catch { Log.error("Error adding do-not-back-up attribute to item at \(imageURL)") } } } } static func loadPersistedImage(contextScale: CGFloat, contextSize: CGSize, completion: (UIImage?) -> Void) { let imageURL = urlForPersistedImage(contextScale, contextSize: contextSize) if let imageData = try? Data(contentsOf: imageURL) { let image = loadPersistedImageData(imageData, contextScale: contextScale) completion(image) } } } private extension ImageIO { static let persistedImageExtension = "png" static let persistedImageName: String = { if Defaults.snapshotMode { return "ScreenshotPersistedImage" } else { return "PadiddlePersistedImage" } }() static var backgroundSaveTask: UIBackgroundTaskIdentifier? static func urlForPersistedImage(_ contextScale: CGFloat, contextSize: CGSize) -> URL { var scaledContextSize = contextSize scaledContextSize.width *= contextScale scaledContextSize.height *= contextScale let imageName = String(format: "%@-%.0f×%.0f", persistedImageName, scaledContextSize.width, scaledContextSize.height) guard !Defaults.snapshotMode else { return Bundle.main.url(forResource: imageName, withExtension: persistedImageExtension)! } let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsURL = paths.first! let path = documentsURL.path if !FileManager.default.fileExists(atPath: path) { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil) } catch { Log.error("Error creating directory at path \(path): \(error)") } } let fullURL = documentsURL.appendingPathComponent(imageName).appendingPathExtension(persistedImageExtension) return fullURL } static func loadPersistedImageData(_ imageData: Data, contextScale: CGFloat) -> UIImage? { guard let image = UIImage(data: imageData, scale: contextScale)?.imageFlippedVertically else { Log.error("Couldn't create image from data on disk") if Defaults.snapshotMode { fatalError("We must always have a screenshot in snapshot mode.") } return nil } return image } static func addSkipBackupAttributeToItem(atUrl url: URL) throws { var url = url var values = URLResourceValues() values.isExcludedFromBackup = true try url.setResourceValues(values) } }
mit
25361f13a4c6ca664b91f8737800a5b0
31.69697
125
0.588971
5.289216
false
false
false
false
zacwest/ZSWTaggedString
Example/Tests/Tests/ZSWTaggedStringOptionsSpec.swift
1
3277
// // ZSWTaggedStringOptionsSpec.swift // ZSWTaggedString // // Created by Zachary West on 12/12/15. // Copyright © 2015 Zachary West. All rights reserved. // import Quick import Nimble @testable import ZSWTaggedString class ZSWTaggedStringOptionsSpec: QuickSpec { override func spec() { describe("swift setters") { var options: ZSWTaggedStringOptions! var string: NSMutableAttributedString! var tags: [ZSWStringParserTag]! beforeEach { options = ZSWTaggedStringOptions() string = NSMutableAttributedString(string: "a string") let aTag = ZSWStringParserTag(tagName: "a", startLocation: 0) aTag.update(with: ZSWStringParserTag(tagName: "/a", startLocation: 1)) let stringTag = ZSWStringParserTag(tagName: "string", startLocation: 2) stringTag.update(with: ZSWStringParserTag(tagName: "/string", startLocation: 8)) tags = [aTag, stringTag] } context("setting a static attribute") { let testKey = NSAttributedString.Key(rawValue: "key") beforeEach { options["a"] = .static([ testKey: true ]) } it("should be retrievable") { guard let a = options["a"] else { fail("Could not retrieve after setting") return } switch a { case .static(let attributes): expect(attributes[testKey] as? Bool) == true case .dynamic(_): fail("Retrieved a dynamic when expecting static") } } it("should still be performed on text") { options._private_update(string, updatedWithTags: tags) expect(string.attribute(testKey, at: 0, effectiveRange: nil) as? Bool) == true } } context("setting a dynamic attribute") { let testKey = NSAttributedString.Key(rawValue: "key") beforeEach { options["a"] = .dynamic({ _, _, _ in return [ testKey: true ] }) } it("should be retrievable") { guard let a = options["a"] else { fail("Could not retrieve after setting") return } switch a { case .static(_): fail("Retrieved a static when expecting dynamic") case .dynamic(let block): let attributes = block("a", [String: Any](), [NSAttributedString.Key: Any]()) expect(attributes[testKey] as? Bool) == true } } it("should still be performed on text") { options._private_update(string, updatedWithTags: tags) expect(string.attribute(testKey, at: 0, effectiveRange: nil) as? Bool) == true } } } } }
mit
eceeba5edd3c9499b0be0a76c81d32f1
33.125
97
0.482601
5.335505
false
true
false
false
gerardogrisolini/Webretail
Sources/Webretail/Repositories/StoreRepository.swift
1
1216
// // StoreRepository.swift // Webretail // // Created by Gerardo Grisolini on 27/02/17. // // import StORM struct StoreRepository : StoreProtocol { func getAll() throws -> [Store] { let items = Store() try items.query() return items.rows() } func get(id: Int) throws -> Store? { let item = Store() try item.query(id: id) return item } func add(item: Store) throws { item.storeCreated = Int.now() item.storeUpdated = Int.now() try item.save { id in item.storeId = id as! Int } } func update(id: Int, item: Store) throws { guard let current = try get(id: id) else { throw StORMError.noRecordFound } current.storeName = item.storeName current.storeAddress = item.storeAddress current.storeCity = item.storeCity current.storeCountry = item.storeCountry current.storeZip = item.storeZip current.storeUpdated = Int.now() try current.save() } func delete(id: Int) throws { let item = Store() item.storeId = id try item.delete() } }
apache-2.0
0034cc69eda95069adf7e3bc69ce1ad6
21.109091
50
0.550164
4.080537
false
false
false
false
tinrobots/CoreDataPlus
Sources/Migration/LightweightMigrationManager.swift
1
6512
// CoreDataPlus import CoreData /// A `NSMigrationManager` proxy for lightweight migrations with a customizable faking `migrationProgress`. public final class LightweightMigrationManager: NSMigrationManager { /// An estimated interval (with a 10% tolerance) to carry out the migration (default: 60 seconds). public var estimatedTime: TimeInterval = 60 /// How often the progress is updated (default: 1 second). public var updateProgressInterval: TimeInterval = 1 private let manager: NSMigrationManager private let totalUnitCount: Int64 = 100 private lazy var fakeTotalUnitCount: Float = { Float(totalUnitCount) * 0.9 }() // 10% tolerance private var fakeProgress: Float = 0 // 0 to 1 public override var usesStoreSpecificMigrationManager: Bool { get { manager.usesStoreSpecificMigrationManager } // swiftlint:disable:next unused_setter_value set { fatalError("usesStoreSpecificMigrationManager can't be set for lightweight migrations.") } } public override var mappingModel: NSMappingModel { manager.mappingModel } public override var sourceModel: NSManagedObjectModel { manager.sourceModel } public override var destinationModel: NSManagedObjectModel { manager.destinationModel } public override var sourceContext: NSManagedObjectContext { manager.sourceContext } public override var destinationContext: NSManagedObjectContext { manager.destinationContext } public override init(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel) { self.manager = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel) self.manager.usesStoreSpecificMigrationManager = true // default super.init() } public override func migrateStore(from sourceURL: URL, sourceType sStoreType: String, options sOptions: [AnyHashable: Any]? = nil, with mappings: NSMappingModel?, toDestinationURL dURL: URL, destinationType dStoreType: String, destinationOptions dOptions: [AnyHashable: Any]? = nil) throws { let tick = Float(updateProgressInterval / estimatedTime) // progress increment tick let queue = DispatchQueue(label: "\(bundleIdentifier).\(String(describing: Self.self)).Progress", qos: .utility) var progressUpdater: () -> Void = {} progressUpdater = { [weak self] in guard let self = self else { return } guard self.fakeProgress < 1 else { return } if self.fakeProgress > 0 { let fakeCompletedUnitCount = self.fakeTotalUnitCount * self.fakeProgress self.migrationProgress = fakeCompletedUnitCount / self.fakeTotalUnitCount } self.fakeProgress += tick queue.asyncAfter(deadline: .now() + self.updateProgressInterval, execute: progressUpdater) } queue.async(execute: progressUpdater) do { try manager.migrateStore(from: sourceURL, sourceType: sStoreType, options: sOptions, with: mappings, toDestinationURL: dURL, destinationType: dStoreType, destinationOptions: dOptions) } catch { // stop the fake progress queue.sync { fakeProgress = 1 } // reset the migrationProgress (as expected for NSMigrationManager instances) // before throwing the error without firing KVO. // Although cancelling ligthweight migrations is ignored; // see comments in cancelMigrationWithError(_:) migrationProgress = 0 throw error } queue.sync { fakeProgress = 1 } migrationProgress = 1.0 // a NSMigrationManager instance may be used for multiple migrations; // the migrationProgress should be reset without firing KVO. migrationProgress = 0 } public override func sourceEntity(for mEntity: NSEntityMapping) -> NSEntityDescription? { manager.sourceEntity(for: mEntity) } public override func destinationEntity(for mEntity: NSEntityMapping) -> NSEntityDescription? { manager.destinationEntity(for: mEntity) } public override func reset() { manager.reset() } public override func associate(sourceInstance: NSManagedObject, withDestinationInstance destinationInstance: NSManagedObject, for entityMapping: NSEntityMapping) { manager.associate(sourceInstance: sourceInstance, withDestinationInstance: destinationInstance, for: entityMapping) } public override func destinationInstances(forEntityMappingName mappingName: String, sourceInstances: [NSManagedObject]?) -> [NSManagedObject] { manager.destinationInstances(forEntityMappingName: mappingName, sourceInstances: sourceInstances) } public override func sourceInstances(forEntityMappingName mappingName: String, destinationInstances: [NSManagedObject]?) -> [NSManagedObject] { manager.sourceInstances(forEntityMappingName: mappingName, destinationInstances: destinationInstances) } public override var currentEntityMapping: NSEntityMapping { manager.currentEntityMapping } public override class func automaticallyNotifiesObservers(forKey key: String) -> Bool { // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOCompliance.html#//apple_ref/doc/uid/20002178-SW3 if key == #keyPath(NSMigrationManager.migrationProgress) { return false } return super.automaticallyNotifiesObservers(forKey: key) } private var _migrationProgress: Float = 0.0 public override var migrationProgress: Float { get { _migrationProgress } set { guard _migrationProgress != newValue else { return } if newValue == 0 { // reset if manager is reused _migrationProgress = newValue } else { willChangeValue(forKey: #keyPath(NSMigrationManager.migrationProgress)) _migrationProgress = newValue didChangeValue(forKey: #keyPath(NSMigrationManager.migrationProgress)) } } } public override var userInfo: [AnyHashable: Any]? { get { manager.userInfo } set { manager.userInfo = newValue } } public override func cancelMigrationWithError(_ error: Error) { // During my tests, cancelling a lightweight migration doesn't work // probably due to performance optimizations manager.cancelMigrationWithError(error) } }
mit
45b97ef673d740d2a85218c012836618
43.60274
165
0.707002
5.176471
false
false
false
false
sarvex/SwiftRecepies
Networking/Handling Timeouts in Asynchronous Connections/Handling Timeouts in Asynchronous Connections/ViewController.swift
1
2204
// // ViewController.swift // Handling Timeouts in Asynchronous Connections // // Created by Vandad Nahavandipoor on 7/9/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /* We have a 15 second timeout for our connection */ let timeout = 15 /* You can choose your own URL here */ let urlAsString = "http://www.apple.com" let url = NSURL(string: urlAsString) /* Set the timeout on our request here */ let urlRequest = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0) let queue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(urlRequest, queue: queue, completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in /* Now we may have access to the data but check if an error came back first or not */ if data.length > 0 && error == nil{ let html = NSString(data: data, encoding: NSUTF8StringEncoding) println("html = \(html)") } else if data.length == 0 && error == nil{ println("Nothing was downloaded") } else if error != nil{ println("Error happened = \(error)") } } ) } }
isc
0ae8e7c8bf1668842996195b60430cb2
31.411765
83
0.651089
4.434608
false
false
false
false
krose67/codePath_iOS_app
SettingsViewController.swift
1
940
// // SettingsViewController.swift // TipApp // // Created by Kevin Rose on 3/13/17. // Copyright © 2017 Kevin Rose. All rights reserved. // import UIKit class SettingsViewController: UIViewController { let intDefaultPercConstant = "intDefPercIndex" @IBOutlet weak var defTipSegment: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() //Load the saved defaults let defaults = UserDefaults.standard defTipSegment.selectedSegmentIndex = defaults.integer(forKey: intDefaultPercConstant) } @IBAction func chgDefaultTip(_ sender: Any) { // Determine which segment was selected let defPercentIndex = defTipSegment.selectedSegmentIndex // Save selected percent index let defaults = UserDefaults.standard defaults.setValue(defPercentIndex, forKey: intDefaultPercConstant) } }
gpl-3.0
cf53cac688862bae8b5719ec052a8e0a
24.378378
93
0.675186
4.942105
false
false
false
false
TeamYYZ/DineApp
Dine/GroupMember.swift
1
4772
// // GroupMember.swift // Dine // // Created by YiHuang on 3/23/16. // Copyright © 2016 YYZ. All rights reserved. // import Foundation class GroupMember { var userId: String var joined: Bool var owner: Bool? var screenName: String? var avatar: PFFile? var location: PFGeoPoint? init(userId: String, joined: Bool) { self.userId = userId self.joined = joined } init(userId: String, joined: Bool, screenName: String, avatar: PFFile?) { self.userId = userId self.joined = joined self.screenName = screenName self.avatar = avatar } init(user: User) { self.userId = user.userId! self.joined = false self.screenName = user.screenName self.avatar = user.avatarImagePFFile } func setOwner() { owner = true } init(dict: NSDictionary) { self.userId = dict["userId"] as! String self.screenName = dict["screenName"] as? String self.avatar = dict["avatar"] as? PFFile self.joined = dict["joined"] as! Bool self.owner = dict["owner"] as? Bool } init(pfObject: PFObject) { self.userId = pfObject["userId"] as! String self.screenName = pfObject["screenName"] as? String self.avatar = pfObject["avatar"] as? PFFile self.joined = pfObject["joined"] as! Bool self.owner = pfObject["owner"] as? Bool self.location = pfObject["location"] as? PFGeoPoint } class func updateLocation(_activityId: String?, userId: String, location: PFGeoPoint, successHandler: (()->()), failureHandler: ((NSError?)->())?) { guard let activityId = _activityId else { failureHandler?(NSError(domain: "activityId is nil", code: 1, userInfo: nil)) return } let query = PFQuery(className:"GroupMember") query.whereKey("userId", equalTo: userId) query.whereKey("activityId", equalTo: activityId) query.getFirstObjectInBackgroundWithBlock({ (member:PFObject?, error:NSError?) in if error != nil { failureHandler?(error) } else if let member = member { member["location"] = location member.saveInBackgroundWithBlock({ (succeed: Bool, error: NSError?) in if (succeed) { successHandler() }else { failureHandler?(error) } }) } }) } class func getMembersLocation(_activityId: String?, successHandler: (([String: PFGeoPoint])->()), failureHandler: ((NSError?)->())?) { guard let activityId = _activityId else { failureHandler?(NSError(domain: "activityId not found", code: 1, userInfo: nil)) Log.error("activityId not found") return } let query = PFQuery(className:"GroupMember") query.whereKey("activityId", equalTo: activityId) query.findObjectsInBackgroundWithBlock { (members: [PFObject]?, error: NSError?) in if members != nil && error == nil { var dictionary = [String: PFGeoPoint]() for member in members! { guard let userId = member["userId"] as? String, location = member["location"] as? PFGeoPoint else { failureHandler?(NSError(domain: "stored info. is broken", code: 2, userInfo: nil)) return } dictionary[userId] = location } successHandler(dictionary) } else { failureHandler?(error) } } } func getLocation(_activityId: String?, successHandler: ((PFGeoPoint)->()), failureHandler: ((NSError?)->())?) { guard let activityId = _activityId else { failureHandler?(NSError(domain: "activityId not found", code: 1, userInfo: nil)) Log.error("activityId not found") return } let query = PFQuery(className:"GroupMember") query.whereKey("userId", equalTo: self.userId) query.whereKey("activityId", equalTo: activityId) query.getFirstObjectInBackgroundWithBlock({ (member:PFObject?, error:NSError?) in if error != nil { failureHandler?(error) } else if let member = member { if let loc = member["location"] as? PFGeoPoint { successHandler(loc) }else { failureHandler?(error) } } }) } }
gpl-3.0
98002bfb7594acc3c663fce59ca8bbfb
33.57971
152
0.542444
5.097222
false
false
false
false
malaonline/iOS
mala-ios/View/Profile/CouponRulesPopupWindow.swift
1
7444
// // CouponRulesPopupWindow.swift // mala-ios // // Created by 王新宇 on 16/5/12. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit open class CouponRulesPopupWindow: UIViewController, UITextViewDelegate { // MARK: - Property /// 自身强引用 var strongSelf: CouponRulesPopupWindow? /// 遮罩层透明度 let tBakcgroundTansperancy: CGFloat = 0.7 /// 布局容器(窗口) var window = UIView() /// 内容视图 var contentView: UIView? /// 单击背景close窗口 var closeWhenTap: Bool = false /// 弹窗高度 var windowHeight: CGFloat = 0 // MARK: - Components /// 描述 文字背景 private lazy var textBackground: UIImageView = { let textBackground = UIImageView(imageName: "aboutText_Background") return textBackground }() /// 描述标题 private lazy var titleView: AboutTitleView = { let titleView = AboutTitleView() return titleView }() /// 描述label private lazy var descTextView: UITextView = { let textView = UITextView() textView.font = UIFont.systemFont(ofSize: 13) textView.textColor = UIColor(named: .HeaderTitle) textView.isEditable = false return textView }() /// 提交按钮装饰线 private lazy var buttonSeparatorLine: UIView = { let view = UIView(UIColor(named: .ThemeBlue)) return view }() /// 提交按钮 private lazy var confirmButton: UIButton = { let button = UIButton() button.setTitle(L10n.later, for: UIControlState()) button.setTitleColor(UIColor(named: .ThemeBlue), for: UIControlState()) button.setTitleColor(UIColor(named: .DescGray), for: .disabled) button.setBackgroundImage(UIImage.withColor(UIColor(named: .WhiteTranslucent9)), for: UIControlState()) button.setBackgroundImage(UIImage.withColor(UIColor(named: .HighlightGray)), for: .highlighted) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) button.addTarget(self, action: #selector(CouponRulesPopupWindow.animateDismiss), for: .touchUpInside) return button }() // MARK: - Constructed init() { super.init(nibName: nil, bundle: nil) view.frame = UIScreen.main.bounds setupUserInterface() // 持有自己强引用,使自己在外界没有强引用时依然存在。 strongSelf = self } convenience init(title: String, desc: String) { self.init(contentView: UIView()) self.titleView.title = title self.descTextView.text = desc self.windowHeight = CGFloat((desc.characters.count / 16)+2)*14 + 90 + 14 + 44 self.windowHeight = windowHeight > MalaLayout_CouponRulesPopupWindowHeight ? MalaLayout_CouponRulesPopupWindowHeight : windowHeight self.window.snp.updateConstraints { (maker) in maker.height.equalTo(self.windowHeight) } } convenience init(contentView: UIView) { self.init() self.view.alpha = 0 // 显示Window let window: UIWindow = UIApplication.shared.keyWindow! window.addSubview(view) window.bringSubview(toFront: view) view.frame = window.bounds // 设置属性 self.contentView = contentView } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Life Cycle override open func viewDidLoad() { super.viewDidLoad() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Override open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if closeWhenTap { // 若触摸点不位于Window视图,关闭弹窗 if let point = touches.first?.location(in: window), !window.point(inside: point, with: nil) { closeAlert(0) } } } // MARK: - API open func show() { animateAlert() } open func close() { closeAlert(0) } // MARK: - Private Method private func setupUserInterface() { // Style view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: tBakcgroundTansperancy) window.backgroundColor = UIColor.white // SubViews view.addSubview(window) window.addSubview(confirmButton) confirmButton.addSubview(buttonSeparatorLine) window.addSubview(textBackground) window.addSubview(titleView) window.addSubview(descTextView) // Autolayout window.snp.makeConstraints { (maker) -> Void in maker.width.equalTo(MalaLayout_CommentPopupWindowWidth) maker.height.equalTo(windowHeight) maker.center.equalTo(view) } buttonSeparatorLine.snp.makeConstraints { (maker) in maker.height.equalTo(MalaScreenOnePixel) maker.left.equalTo(confirmButton) maker.right.equalTo(confirmButton) maker.top.equalTo(confirmButton) } confirmButton.snp.makeConstraints { (maker) in maker.bottom.equalTo(window) maker.left.equalTo(window) maker.right.equalTo(window) maker.height.equalTo(44) } textBackground.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(window).offset(18) maker.left.equalTo(window).offset(18) maker.right.equalTo(window).offset(-18) maker.bottom.equalTo(confirmButton.snp.top).offset(-18) } titleView.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(textBackground).offset(18) maker.left.equalTo(textBackground) maker.right.equalTo(textBackground) } descTextView.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(titleView.snp.bottom).offset(18) maker.left.equalTo(textBackground).offset(18) maker.right.equalTo(textBackground).offset(-18) maker.bottom.equalTo(textBackground).offset(-18) } } private func animateAlert() { view.alpha = 0; let originTransform = self.window.transform self.window.layer.transform = CATransform3DMakeScale(0.7, 0.7, 0.0); UIView.animate(withDuration: 0.35, animations: { () -> Void in self.view.alpha = 1.0 self.window.transform = originTransform }) } @objc private func animateDismiss() { UIView.animate(withDuration: 0.35, animations: { () -> Void in self.view.alpha = 0 self.window.transform = CGAffineTransform() }, completion: { (bool) -> Void in self.closeAlert(0) }) } private func closeAlert(_ buttonIndex: Int) { self.view.removeFromSuperview() // 释放自身强引用 self.strongSelf = nil } // MARK: - Event Response @objc private func pressed(_ sender: UIButton!) { self.closeAlert(sender.tag) } @objc private func closeButtonDidTap() { close() } }
mit
180c278b2c2c059a013053083aba0dbb
31.084444
139
0.607425
4.46444
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/Notification Service Extension/SimpleNotificationServiceExtension/JobTests.swift
1
7338
// // Wire // Copyright (C) 2022 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire_Notification_Service_Extension @available(iOS 15, *) class JobTests: XCTestCase { var mockNetworkSession: MockNetworkSession! var mockAccessAPIClient: MockAccessAPIClient! var mockNotificationsAPIClient: MockNotificationsAPIClient! var sut: Job! override func setUpWithError() throws { try super.setUpWithError() mockNetworkSession = MockNetworkSession() mockAccessAPIClient = MockAccessAPIClient() mockNotificationsAPIClient = MockNotificationsAPIClient() sut = try Job( request: notificationRequest, networkSession: mockNetworkSession, accessAPIClient: mockAccessAPIClient, notificationsAPIClient: mockNotificationsAPIClient ) } override func tearDown() { mockNetworkSession = nil mockAccessAPIClient = nil mockNotificationsAPIClient = nil super.tearDown() } let userID = UUID.create() let eventID = UUID.create() lazy var notificationRequest: UNNotificationRequest = { let content = UNMutableNotificationContent() content.userInfo["data"] = [ "user": userID.uuidString, "data": ["id": eventID.uuidString] ] return UNNotificationRequest( identifier: "request", content: content, trigger: nil ) }() // MARK: - Execute func test_Execute_NotAuthenticated() async throws { // Given mockNetworkSession.isAuthenticated = false // Then await assertThrows(expectedError: NotificationServiceError.userNotAuthenticated) { // When _ = try await self.sut.execute() } } func test_Execute_FetchAccessTokenFailed() async throws { // Given mockAccessAPIClient.mockFetchAccessToken = { throw AccessTokenEndpoint.Failure.authenticationError } // Then await assertThrows(expectedError: AccessTokenEndpoint.Failure.authenticationError) { // When _ = try await self.sut.execute() } } func test_Execute_FetchEventFailed() async throws { // Given mockAccessAPIClient.mockFetchAccessToken = { AccessToken(token: "12345", type: "Bearer", expiresInSeconds: 10) } mockNotificationsAPIClient.mockFetchEvent = { _ in throw NotificationByIDEndpoint.Failure.notifcationNotFound } // Then await assertThrows(expectedError: NotificationByIDEndpoint.Failure.notifcationNotFound) { // When _ = try await self.sut.execute() } } func test_Execute_NewMessageEvent_Content() async throws { // Given mockAccessAPIClient.mockFetchAccessToken = { AccessToken(token: "12345", type: "Bearer", expiresInSeconds: 10) } mockNotificationsAPIClient.mockFetchEvent = { eventID in XCTAssertEqual(eventID, self.eventID) let payload: [String: Any] = [ "id": "cf51e6b1-39a6-11ed-8005-520924331b82", "time": "2022-09-21T12:13:32.173Z", "type": "conversation.otr-message-add", "payload": [ "conversation": "c06684dd-2865-4ff8-aef5-e0b07ae3a4e0" ] ] return ZMUpdateEvent( uuid: eventID, payload: payload, transient: false, decrypted: false, source: .pushNotification )! } // When let result = try await sut.execute() // Then XCTAssertEqual(result.body, "You received a new message") } func test_Execute_NotNewMessageEvent_Content() async throws { // Given mockAccessAPIClient.mockFetchAccessToken = { AccessToken(token: "12345", type: "Bearer", expiresInSeconds: 10) } mockNotificationsAPIClient.mockFetchEvent = { eventID in XCTAssertEqual(eventID, self.eventID) let payload: [String: Any] = [ "id": "cf51e6b1-39a6-11ed-8005-520924331b82", "time": "2022-09-21T12:13:32.173Z", "type": "conversation.member-join", "payload": [ "conversation": "c06684dd-2865-4ff8-aef5-e0b07ae3a4e0" ] ] return ZMUpdateEvent( uuid: eventID, payload: payload, transient: false, decrypted: false, source: .pushNotification )! } // When let result = try await sut.execute() // Then XCTAssertEqual(result, .empty) } } class MockNetworkSession: NetworkSessionProtocol { var accessToken: AccessToken? var isAuthenticated = true var mockExecuteFetchAccessToken: ((AccessTokenEndpoint) async throws -> AccessTokenEndpoint.Result)? var mockExecuteFetchNotification: ((NotificationByIDEndpoint) async throws -> NotificationByIDEndpoint.Result)? func execute<E>(endpoint: E) async throws -> E.Result where E: Endpoint { switch endpoint { case let accessEndpoint as AccessTokenEndpoint: guard let mock = mockExecuteFetchAccessToken else { fatalError("no mock for `mockExecuteFetchAccessToken`") } return try await mock(accessEndpoint) as! E.Result case let notificationEndpoint as NotificationByIDEndpoint: guard let mock = mockExecuteFetchNotification else { fatalError("no mock for `mockExecuteFetchNotification`") } return try await mock(notificationEndpoint) as! E.Result default: fatalError("unexpected endpoint which isn't mocked") } } } class MockAccessAPIClient: AccessAPIClientProtocol { var mockFetchAccessToken: (() async throws -> AccessToken)? func fetchAccessToken() async throws -> AccessToken { guard let mock = mockFetchAccessToken else { fatalError("no mock for `fetchAccessToken`") } return try await mock() } } class MockNotificationsAPIClient: NotificationsAPIClientProtocol { var mockFetchEvent: ((UUID) async throws -> ZMUpdateEvent)? func fetchEvent(eventID: UUID) async throws -> ZMUpdateEvent { guard let mock = mockFetchEvent else { fatalError("no mock for `fetchEvent`") } return try await mock(eventID) } }
gpl-3.0
4e5c154bf07037e1bb2394cbe6f1662d
29.575
115
0.617743
4.901804
false
false
false
false
toggl/superday
teferi/Services/Implementations/Persistency/Adapters/TimeSlotModelAdapter.swift
1
3189
import Foundation import CoreData class TimeSlotModelAdapter : CoreDataModelAdapter<TimeSlot> { //MARK: Private Properties private let endTimeKey = "endTime" private let categoryKey = "category" private let startTimeKey = "startTime" private let locationTimeKey = "locationTime" private let locationLatitudeKey = "locationLatitude" private let locationLongitudeKey = "locationLongitude" private let categoryWasSetByUserKey = "categoryWasSetByUser" private let categoryWasSmartGuessedKey = "categoryWasSmartGuessed" private let activityKey = "activity" //MARK: Initializers override init() { super.init() sortDescriptorsForList = [ NSSortDescriptor(key: startTimeKey, ascending: true) ] sortDescriptorsForLast = [ NSSortDescriptor(key: startTimeKey, ascending: false) ] } //MARK: Public Methods override func getModel(fromManagedObject managedObject: NSManagedObject) -> TimeSlot { let startTime = managedObject.value(forKey: startTimeKey) as! Date let endTime = managedObject.value(forKey: endTimeKey) as? Date let category = Category(rawValue: managedObject.value(forKey: categoryKey) as! String)! let categoryWasSetByUser = managedObject.value(forKey: categoryWasSetByUserKey) as? Bool ?? false let categoryWasSmartGuessed = managedObject.value(forKey: categoryWasSmartGuessedKey) as? Bool ?? false var activity: MotionEventType? = nil if let activityString = managedObject.value(forKey: activityKey) as? String { activity = MotionEventType(rawValue: activityString) } let location = super.getLocation(managedObject, timeKey: locationTimeKey, latKey: locationLatitudeKey, lngKey: locationLongitudeKey) let timeSlot = TimeSlot(startTime: startTime, endTime: endTime, category: category, location: location, categoryWasSetByUser: categoryWasSetByUser, categoryWasSmartGuessed: categoryWasSmartGuessed, activity: activity) return timeSlot } override func setManagedElementProperties(fromModel model: TimeSlot, managedObject: NSManagedObject) { managedObject.setValue(model.endTime, forKey: endTimeKey) managedObject.setValue(model.startTime, forKey: startTimeKey) managedObject.setValue(model.category.rawValue, forKey: categoryKey) managedObject.setValue(model.categoryWasSetByUser, forKey: categoryWasSetByUserKey) managedObject.setValue(model.location?.timestamp, forKey: locationTimeKey) managedObject.setValue(model.location?.latitude, forKey: locationLatitudeKey) managedObject.setValue(model.location?.longitude, forKey: locationLongitudeKey) managedObject.setValue(model.activity?.rawValue, forKey: activityKey) } }
bsd-3-clause
016add6f57f63feb63569f99ab182211
45.217391
111
0.656946
5.460616
false
false
false
false
Msr-B/Msr.LibSwift
UI/MSRTextView.swift
2
2342
import UIKit @IBDesignable class MSRTextView: UITextView { override var text: String? { didSet { setNeedsDisplay() } } override var textContainerInset: UIEdgeInsets { didSet { setNeedsDisplay() } } @IBInspectable var placeholder: String? { get { return attributedPlaceholder?.string } set { if let string = newValue { let s = NSMutableParagraphStyle() s.alignment = textAlignment attributedPlaceholder = NSAttributedString( string: string, attributes: [ NSFontAttributeName: font!, NSForegroundColorAttributeName: UIColor(white: 0.7, alpha: 1), NSParagraphStyleAttributeName: s ]) } else { attributedPlaceholder = nil } } } @IBInspectable @NSCopying var attributedPlaceholder: NSAttributedString? { didSet { setNeedsDisplay() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) msr_initialize() } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) msr_initialize() } func msr_initialize() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self) } func textDidChange() { setNeedsDisplay() } override func drawRect(rect: CGRect) { super.drawRect(rect) if text ?? "" == "" { if let ap = attributedPlaceholder { var rect = CGRect(origin: CGPointZero, size: bounds.size) rect = UIEdgeInsetsInsetRect(rect, textContainerInset) rect = CGRectInset(rect, textContainer.lineFragmentPadding, 0) ap.drawInRect(rect) } } } override func layoutSubviews() { super.layoutSubviews() setNeedsDisplay() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
gpl-2.0
4561d919d5c530297c620afe25360768
26.880952
146
0.542699
6.163158
false
false
false
false
SocialObjects-Software/AMSlideMenu
AMSlideMenu/Animation/Animators/AMSlidingDimmedBackgroundAnimator.swift
1
2643
// // AMSlidingDimmedBackgroundAnimator.swift // AMSlideMenu // // The MIT License (MIT) // // Created by : arturdev // Copyright (c) 2020 arturdev. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE import UIKit open class AMSlidingDimmedBackgroundAnimator: AMSlidingAnimatorProtocol { open var duration: TimeInterval = 0.25 public let overlayView: UIView = { let view = UIView() view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.isUserInteractionEnabled = false view.backgroundColor = UIColor.black.withAlphaComponent(0.45) view.alpha = 0 return view }() open func animate(leftMenuView: UIView, contentView: UIView, progress: CGFloat, animated: Bool, completion: (() -> Void)?) { if overlayView.superview == nil { overlayView.frame = contentView.bounds contentView.addSubview(overlayView) } UIView.animate(withDuration: animated ? duration : 0, animations: { self.overlayView.alpha = progress }) { (_) in completion?() } } open func animate(rightMenuView: UIView, contentView: UIView, progress: CGFloat = 1, animated: Bool = true, completion: (() -> Void)? = nil) { if overlayView.superview == nil { overlayView.frame = contentView.bounds contentView.addSubview(overlayView) } UIView.animate(withDuration: animated ? duration : 0, animations: { self.overlayView.alpha = progress }) { (_) in completion?() } } public init() {} }
mit
bb11b8b05c2e3709a4a30c4ab0526e06
37.867647
143
0.685206
4.694494
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/功能/FunctionTableViewController.swift
1
4375
// // FunctionTableViewController.swift // NKU Helper // // Created by 陈乐天 on 15/3/1. // Copyright (c) 2015年 陈乐天. All rights reserved. // import UIKit class FunctionTableViewController: UITableViewController { /// 是否已经输入用户名和密码 var isLoggedIn:Bool { do { let _ = try UserAgent.sharedInstance.getUserInfo() return true } catch { return false } } override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 150 self.tableView.rowHeight = UITableViewAutomaticDimension } override func viewWillAppear(_ animated: Bool) { do { let _ = try UserAgent.sharedInstance.getUserInfo() self.tableView.reloadData() super.viewWillAppear(animated) } catch { self.present(ErrorHandler.alert(withError: ErrorHandler.NotLoggedIn()), animated: true, completion: nil) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let action = NKRouter.sharedInstance.action { if action["type2"]! as Int == 0 { self.performSegue(withIdentifier: R.segue.functionTableViewController.showNotiCenter.identifier, sender: nil) } NKRouter.sharedInstance.action = nil } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { switch indexPath.row { case 0: //查询成绩 cell.backgroundColor = UIColor(red: 131/255, green: 176/255, blue: 252/255, alpha: 1) case 1: //通知中心 cell.backgroundColor = UIColor(red: 173/255, green: 114/255, blue: 195/255, alpha: 1) // case 2: // 选课 // cell.backgroundColor = UIColor(red: 154/255, green: 202/255, blue: 39/255, alpha: 1) case 2: //评教 cell.backgroundColor = UIColor(red: 255/255, green: 110/255, blue: 0/255, alpha: 1) case 3: //查询考试时间 cell.backgroundColor = UIColor(red: 58/255, green: 153/255, blue: 216/255, alpha: 1) case 4: //更多 cell.backgroundColor = UIColor(red: 250/255, green: 191/255, blue: 131/255, alpha: 1) default: break } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: //查询成绩 let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.gradeShowerCell.identifier)! cell.isUserInteractionEnabled = isLoggedIn return cell case 1: //通知中心 let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.notiCenterCell.identifier)! cell.isUserInteractionEnabled = isLoggedIn return cell // case 2: // 选课 // let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(R.reuseIdentifier.selectCourseCenterCell.identifier)! // cell.userInteractionEnabled = isLoggedIn // return cell case 2: //评教 let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.evaluateCenterCell.identifier)! cell.isUserInteractionEnabled = isLoggedIn return cell case 3: //查询考试时间 let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.testTimeSearchCell.identifier)! cell.isUserInteractionEnabled = isLoggedIn return cell case 4: //更多 let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.moreFunctionCell.identifier)! cell.isUserInteractionEnabled = isLoggedIn return cell default:return UITableViewCell() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { segue.destination.hidesBottomBarWhenPushed = true } }
gpl-3.0
b18000bdf1d2e105444d092783faed45
37.351351
138
0.633545
4.910035
false
false
false
false
v2panda/DaysofSwift
swift2.3/My-ImageScrollerEffect/My-ImageScrollerEffect/ViewController.swift
1
2671
// // ViewController.swift // My-ImageScrollerEffect // // Created by Panda on 16/2/24. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { var imageView: UIImageView! var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(image: UIImage(named: "steve")) setUpScrollView() scrollView.delegate = self setZoomScaleFor(scrollView.bounds.size) scrollView.zoomScale = scrollView.minimumZoomScale recenterImage() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setZoomScaleFor(scrollView.bounds.size) if scrollView.zoomScale < scrollView.minimumZoomScale{ scrollView.zoomScale = scrollView.minimumZoomScale } recenterImage() } // set up scroll view private func setUpScrollView() { scrollView = UIScrollView(frame: view.bounds) scrollView.autoresizingMask = [.FlexibleWidth,.FlexibleHeight] scrollView.backgroundColor = UIColor.clearColor() scrollView.contentSize = imageView.bounds.size scrollView.addSubview(imageView) view.addSubview(scrollView) } private func setZoomScaleFor(scrollViewSize:CGSize) { let imageSize = imageView.bounds.size let widthScale = scrollViewSize.width / imageSize.width let heightScale = scrollViewSize.height / imageSize.height let minimunScale = min(widthScale, heightScale) scrollView.minimumZoomScale = minimunScale scrollView.maximumZoomScale = 3.0 } private func recenterImage() { let scrollViewSize = scrollView.bounds.size let imageViewSize = imageView.frame.size let horizontalSpace = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2.0:0 let verticalSpace = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.width) / 2.0 :0 scrollView.contentInset = UIEdgeInsetsMake(verticalSpace, horizontalSpace, verticalSpace, horizontalSpace) } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(scrollView: UIScrollView) { recenterImage() } }
mit
2f666a9be4b62cbf06d19c90c8211918
28.977528
129
0.66042
5.688699
false
false
false
false
Egibide-DAM/swift
02_ejemplos/03_estructuras_control/03_alternativa_multiple/02_switch_intervalos.playground/Contents.swift
1
422
let approximateCount = 62 let countedThings = "moons orbiting Saturn" var naturalCount: String switch approximateCount { case 0: naturalCount = "no" case 1..<5: naturalCount = "a few" case 5..<12: naturalCount = "several" case 12..<100: naturalCount = "dozens of" case 100..<1000: naturalCount = "hundreds of" default: naturalCount = "many" } print("There are \(naturalCount) \(countedThings).")
apache-2.0
ff69b6b61ea5c5a22ff7173ef90eca9d
20.1
52
0.684834
3.546218
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/InitFlow/InitFlow+Services.swift
1
5086
import Foundation extension InitFlow { func getInitSearch() { let cardIdsWithEsc = PXConfiguratorManager.escProtocol.getSavedCardIds(config: PXConfiguratorManager.escConfig) let discountParamsConfiguration = initFlowModel.properties.advancedConfig.discountParamsConfiguration let flowName: String? = MPXTracker.sharedInstance.getFlowName() let splitEnabled: Bool = initFlowModel.properties.paymentPlugin?.supportSplitPaymentMethodPayment(checkoutStore: PXCheckoutStore.sharedInstance) ?? false let serviceAdapter = initFlowModel.getService() // payment method search service should be performed using the processing modes designated by the preference object let pref = initFlowModel.properties.checkoutPreference serviceAdapter.update(processingModes: pref.processingModes, branchId: pref.branchId) let charges = self.initFlowModel.amountHelper.chargeRules ?? [] let paymentMethodRules = initFlowModel.properties.advancedConfig.paymentMethodRules ?? [] let paymentMethodBehaviours = self.initFlowModel.properties.advancedConfig.paymentMethodBehaviours // Add headers var headers: [String: String] = [:] if let prodId = initFlowModel.properties.productId { headers[HeaderFields.productId.rawValue] = prodId } if let prefId = pref.id, prefId.isNotEmpty { // CLOSED PREFERENCE serviceAdapter.getClosedPrefInitSearch(preferenceId: prefId, cardsWithEsc: cardIdsWithEsc, oneTapEnabled: true, splitEnabled: splitEnabled, discountParamsConfiguration: discountParamsConfiguration, flow: flowName, charges: charges, paymentMethodRules: paymentMethodRules, paymentMethodBehaviours: paymentMethodBehaviours, headers: headers, newCardId: newCardId, newAccountId: newAccountId, callback: callback(_:), failure: failure(_:)) } else { // OPEN PREFERENCE serviceAdapter.getOpenPrefInitSearch(pref: pref, cardsWithEsc: cardIdsWithEsc, oneTapEnabled: true, splitEnabled: splitEnabled, discountParamsConfiguration: discountParamsConfiguration, flow: flowName, charges: charges, paymentMethodRules: paymentMethodRules, headers: headers, newCardId: newCardId, newAccountId: newAccountId, callback: callback(_:), failure: failure(_:)) } } func callback(_ search: PXInitDTO) { /// Hack para corregir un issue cuando hay un descuento para un medio de pago particular /// El nodo coupons no trae el valor de generalCoupon y cuando usa MercadoPagoCheckoutViewModel.getPaymentOptionConfigurations /// se rompe todo al no encontrar el payer_costs correspondiente al coupon let generalCoupon = search.generalCoupon if !generalCoupon.isEmpty, !search.coupons.keys.contains(generalCoupon) { search.coupons[generalCoupon] = PXDiscountConfiguration(isAvailable: true) } if search.selectedDiscountConfiguration == nil, let selectedDiscountConfiguration = search.coupons[search.generalCoupon] { search.selectedDiscountConfiguration = selectedDiscountConfiguration } /// Fin del hack initFlowModel.updateInitModel(paymentMethodsResponse: search) // Tracking Experiments MPXTracker.sharedInstance.setExperiments(search.experiments) // Set site SiteManager.shared.setCurrency(currency: search.currency) SiteManager.shared.setSite(site: search.site) executeNextStep() } func failure(_ error: NSError) { let customError = InitFlowError(errorStep: .SERVICE_GET_INIT, shouldRetry: true, requestOrigin: .GET_INIT, apiException: MPSDKError.getApiException(error)) initFlowModel.setError(error: customError) executeNextStep() } }
mit
617197186bc16aa63f680dc6b7255ca3
53.106383
163
0.55348
6.135103
false
true
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/Brightness.swift
1
959
// // Brightness.swift // Pods // // Created by Mohssen Fathi on 4/1/16. // // struct BrightnessUniforms: Uniforms { var brightness: Float = 0.5; } public class Brightness: Filter { var uniforms = BrightnessUniforms() @objc public var brightness: Float = 0.5 { didSet { clamp(&brightness, low: 0, high: 1) needsUpdate = true } } public init() { super.init(functionName: "brightness") title = "Brightness" properties = [Property(key: "brightness", title: "Brightness")] // properties = [Property(keyPath: \Brightness.brightness, title: "Brightness")] update() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func update() { if self.input == nil { return } uniforms.brightness = brightness * 2.0 - 1.0 updateUniforms(uniforms: uniforms) } }
mit
4937c4e2d40f9eba779940f2d9d84916
21.302326
87
0.580813
4.151515
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/InteractiveNotifications/MessageAlert/AlertQueue.swift
1
5518
// // AlertQueue.swift // MobileMessaging // // Created by Andrey Kadochnikov on 26/04/2018. // import Foundation class AlertOperation: Foundation.Operation, NamedLogger { var semaphore: DispatchSemaphore = DispatchSemaphore(value: 0) var alert: InteractiveMessageAlertController? let message: MM_MTMessage let text: String init(with message: MM_MTMessage, text: String) { self.message = message self.text = text super.init() self.addObserver(self, forKeyPath: "isCancelled", options: NSKeyValueObservingOptions.new, context: nil) } deinit { self.removeObserver(self, forKeyPath: "isCancelled") } override func main() { guard shouldProceed else { cancelAlert() return } if self.message.contentUrl?.safeUrl != nil { logDebug("downloading image attachment \(String(describing: self.message.contentUrl?.safeUrl))...") self.message.downloadImageAttachment(completion: { (url, error) in let img: Image? if let url = url, let data = try? Data(contentsOf: url) { self.logDebug("image attachment downloaded") img = DefaultImageProcessor().process(item: ImageProcessItem.data(data), options: []) } else { self.logDebug("could not dowonload image attachment") img = nil } self.presentAlert(with: img) }) } else { self.presentAlert(with: nil) } waitUntilAlertDismissed() } private func waitUntilAlertDismissed() { semaphore.wait() } private func notifyAlertDismissed() { semaphore.signal() } private func presentAlert(with image: UIImage?) { guard shouldProceed else { self.cancelAlert() return } DispatchQueue.main.async() { let a = self.makeAlert(with: self.message, image: image, text: self.text) self.alert = a MobileMessaging.sharedInstance?.interactiveAlertManager?.delegate?.willDisplay(self.message) if let presentingVc = MobileMessaging.messageHandlingDelegate?.inAppPresentingViewController?(for: self.message) ?? MobileMessaging.application.visibleViewController { self.logDebug("presenting in-app alert, root vc: \(presentingVc)") presentingVc.present(a, animated: true, completion: nil) } else { self.logDebug("could not define root vc to present in-app alert") self.cancelAlert() } } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "isCancelled" { if (change?[NSKeyValueChangeKey.newKey] as? Bool ?? false) == true { cancelAlert() } } else { return } } private var shouldProceed: Bool { return !isCancelled && !message.isExpired } private func cancelAlert() { logDebug("canceled. Message expired?: \(message.isExpired.description)") DispatchQueue.main.async() { self.alert?.dismiss(animated: false) } notifyAlertDismissed() } private func makeAlert(with message: MM_MTMessage, image: Image?, text: String) -> InteractiveMessageAlertController { let alert : InteractiveMessageAlertController if let categoryId = message.category, let category = MobileMessaging.category(withId: categoryId), category.actions.first(where: { return $0 is MMTextInputNotificationAction } ) == nil { alert = InteractiveMessageAlertController( titleText: message.title, messageText: text, imageURL: nil, image: image, category: category, actionHandler: { action in MobileMessaging.handleAction( identifier: action.identifier, category: categoryId, message: message, notificationUserInfo: message.originalPayload, userText: nil, completionHandler: {} ) }) } else { alert = InteractiveMessageAlertController( titleText: message.title, messageText: text, imageURL: nil, image: image, dismissTitle: message.inAppDismissTitle, openTitle: message.inAppOpenTitle, actionHandler: { action in MobileMessaging.handleAction( identifier: action.identifier, category: nil, message: message, notificationUserInfo: message.originalPayload, userText: nil, completionHandler: {} ) }) } alert.dismissHandler = { self.cancelAlert() } return alert } } class AlertQueue { static let sharedInstace = AlertQueue() lazy var oq: Foundation.OperationQueue = { let ret = Foundation.OperationQueue() ret.maxConcurrentOperationCount = 1 return ret }() init() { setupObservers() // the queue must perform operations only in apps active state oq.isSuspended = !MobileMessaging.application.isInForegroundState } private func setupObservers() { guard !isTestingProcessRunning else { return } NotificationCenter.default.addObserver( self, selector: #selector(self.handleAppWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(self.handleDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func handleDidBecomeActive(notification: Notification) { oq.isSuspended = false } @objc private func handleAppWillResignActive(notification: Notification) { oq.isSuspended = true } func cancelAllAlerts() { oq.cancelAllOperations() } func enqueueAlert(message: MM_MTMessage, text: String) { oq.addOperation(AlertOperation(with: message, text: text)) } }
apache-2.0
4daff2af4ef13460abf63d64d3f9f34e
26.452736
188
0.717289
3.952722
false
false
false
false
gribozavr/swift
test/SourceKit/Refactoring/semantic-refactoring/extract-func-default.swift
1
421
func foo() -> Int { var a = 3 a = a + 1 return 1 } // RUN: %empty-directory(%t.result) // RUN: %sourcekitd-test -req=extract-func -pos=2:1 -end-pos 4:11 %s -- %s > %t.result/extract-func-default.swift.expected // RUN: diff -u %S/extract-func-default.swift.expected %t.result/extract-func-default.swift.expected // FIXME: Fails on linux with assertion: "!GlibcModuleMapPath.empty()"" failed // REQUIRES: OS=macosx
apache-2.0
79a1531737f6c8056cd6f6ecae07b230
34.083333
122
0.68171
2.923611
false
true
false
false
a5566baga/CrazyFlyBird
CrazyFlyBird/CrazyFlyBird/GameViewController.swift
1
1077
// // GameViewController.swift // CrazyFlyBird // // Created by ben on 16/10/28. // Copyright (c) 2016年 张增强. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let skView = self.view as? SKView { if skView.scene == nil { // 创建视图 let lenAndWidth = skView.bounds.size.height / skView.bounds.size.width let scence = GameScene(size: CGSize(width: 320, height: 320 * lenAndWidth)) skView.showsFPS = false //显示帧数 skView.showsPhysics = false //显示物理模型边框 skView.showsNodeCount = false //显示节点数 skView.ignoresSiblingOrder = true //忽略元素的添加顺序 scence.scaleMode = .AspectFill //scence的拉伸是等比例缩放 skView.presentScene(scence) //添加到视图中 } } } }
apache-2.0
37f1230e3db7c2f7fe11b2dbc577b345
30.580645
91
0.580184
4.370536
false
false
false
false
raymondCaptain/RefinedViewControllerDemo
global/View/InfoView.swift
1
4950
// // InfoView.swift // RefinedViewControllerDemo // // Created by zhiweimiao on 2017/8/28. // Copyright © 2017年 zhiweimiao. All rights reserved. // import Foundation import UIKit //import Then import RxSwift import RxCocoa import Result import RxGesture import NSObject_Rx class InfoView: UIView { // (语文,数学,英语) typealias AllScore = (String, String, String) var rowHeight = 40 var buttonTapForString: Observable<[String]>! var buttonTapForDouble: Observable<[Double?]>! // MARK: - life cycle init() { super.init(frame: CGRect()) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8) self.addSubview() self.creatObservable() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("deinit") } // MARK: - getter and setter lazy var bgView: UIView = { let view = UIView() return view }() lazy var topTitleLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.white return label }() lazy var subTitleOneLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.white return label }() lazy var subTitleTwoLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.white return label }() lazy var subTitleThreeLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.white return label }() lazy var subTitleStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [self.subTitleOneLabel, self.subTitleTwoLabel, self.subTitleThreeLabel]) stackView.axis = .vertical stackView.distribution = .fillEqually return stackView }() lazy var firstTextField: UITextField = { let textField = UITextField() textField.backgroundColor = UIColor.white return textField }() lazy var secondTextField: UITextField = { let textField = UITextField() textField.backgroundColor = UIColor.white return textField }() lazy var threeTextField: UITextField = { let textField = UITextField() textField.backgroundColor = UIColor.white return textField }() lazy var textFieldStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [self.firstTextField, self.secondTextField, self.threeTextField]) stackView.axis = .vertical stackView.distribution = .fillEqually return stackView }() lazy var button: UIButton = { let button = UIButton(type: .custom) button.backgroundColor = UIColor.orange return button }() } // MARK: - creatObservable extension InfoView { func creatObservable() { buttonTapForString = button.rx.tap.map({ [unowned self] in let textFields = [self.firstTextField, self.secondTextField, self.threeTextField] return textFields.map({ return $0.text! }) }) .takeUntil(rx.deallocated) buttonTapForDouble = buttonTapForString .map({ $0.map({ return Double($0) }) }) // self.rx.deallocated.subscribe({ // print($0) // }) // self.firstTextField.rx.text // .subscribe({ // print($0) // }) // .addDisposableTo(rx.disposeBag) // self.rx.tapGesture() // .subscribe({ // print($0) // }) // .disposed(by: rx.disposeBag) } } // MARK: - addSubview extension InfoView { func addSubview() { self.addSubview(bgView) bgView.snp.makeConstraints({ $0.center.equalToSuperview() $0.width.equalTo(200) $0.height.equalTo(rowHeight * 5) }) bgView.addSubview(topTitleLabel) topTitleLabel.snp.makeConstraints({ $0.top.right.left.equalToSuperview() $0.height.equalTo(rowHeight) }) bgView.addSubview(button) button.snp.makeConstraints({ $0.bottom.left.right.equalToSuperview() $0.height.equalTo(rowHeight) }) bgView.addSubview(subTitleStackView) subTitleStackView.snp.makeConstraints({ $0.top.equalTo(topTitleLabel.snp.bottom) $0.left.equalToSuperview() $0.width.equalToSuperview().dividedBy(2) $0.bottom.equalTo(button.snp.top) }) bgView.addSubview(textFieldStackView) textFieldStackView.snp.makeConstraints({ $0.right.equalToSuperview() $0.size.bottom.equalTo(subTitleStackView) }) } }
mit
1c0ab7a4cd441ff0164f48911db8b45a
26.093407
126
0.586899
4.700667
false
false
false
false
google/swift-structural
Sources/StructuralBenchmarks/MyComparableBenchmarks.swift
1
1940
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Benchmark import StructuralCore import StructuralExamples let myComparableBenchmarks = BenchmarkSuite(name: "MyComparable") { suite in suite.benchmark("Point1") { boolSink = p1_1.less(p1_2) } suite.benchmark("Point2") { boolSink = p2_1.less(p2_2) } suite.benchmark("Point3") { boolSink = p3_1.less(p3_2) } suite.benchmark("Point4") { boolSink = p4_1.less(p4_2) } suite.benchmark("Point5") { boolSink = p5_1.less(p5_2) } suite.benchmark("Point6") { boolSink = p6_1.less(p6_2) } suite.benchmark("Point7") { boolSink = p7_1.less(p7_2) } suite.benchmark("Point8") { boolSink = p8_1.less(p8_2) } suite.benchmark("Point9") { boolSink = p9_1.less(p9_2) } suite.benchmark("Point10") { boolSink = p10_1.less(p10_2) } suite.benchmark("Point11") { boolSink = p11_1.less(p11_2) } suite.benchmark("Point12") { boolSink = p12_1.less(p12_2) } suite.benchmark("Point13") { boolSink = p13_1.less(p13_2) } suite.benchmark("Point14") { boolSink = p14_1.less(p14_2) } suite.benchmark("Point15") { boolSink = p15_1.less(p15_2) } suite.benchmark("Point16") { boolSink = p16_1.less(p16_2) } }
apache-2.0
2143d6bbd29484357ecd303827a62773
21.823529
76
0.612371
3.217247
false
false
false
false
cemolcay/KeyboardLayoutEngine
Keyboard/CustomKeyboard/CustomKeyboard.swift
1
12802
// // CustomKeyboard.swift // KeyboardLayoutEngine // // Created by Cem Olcay on 11/05/16. // Copyright © 2016 Prototapp. All rights reserved. // import UIKit // MARK: - CustomKeyboardDelegate @objc public protocol CustomKeyboardDelegate { optional func customKeyboard(customKeyboard: CustomKeyboard, keyboardButtonPressed keyboardButton: KeyboardButton) optional func customKeyboard(customKeyboard: CustomKeyboard, keyButtonPressed key: String) optional func customKeyboardSpaceButtonPressed(customKeyboard: CustomKeyboard) optional func customKeyboardBackspaceButtonPressed(customKeyboard: CustomKeyboard) optional func customKeyboardGlobeButtonPressed(customKeyboard: CustomKeyboard) optional func customKeyboardReturnButtonPressed(customKeyboard: CustomKeyboard) } // MARK: - CustomKeyboard public class CustomKeyboard: UIView, KeyboardLayoutDelegate { public var keyboardLayout = CustomKeyboardLayout() public weak var delegate: CustomKeyboardDelegate? // MARK: CustomKeyobardShiftState public enum CustomKeyboardShiftState { case Once case Off case On } // MARK: CustomKeyboardLayoutState public enum CustomKeyboardLayoutState { case Letters(shiftState: CustomKeyboardShiftState) case Numbers case Symbols } public private(set) var keyboardLayoutState: CustomKeyboardLayoutState = .Letters(shiftState: CustomKeyboardShiftState.Once) { didSet { keyboardLayoutStateDidChange(oldState: oldValue, newState: keyboardLayoutState) } } // MARK: Shift public var shiftToggleInterval: NSTimeInterval = 0.5 private var shiftToggleTimer: NSTimer? // MARK: Backspace public var backspaceDeleteInterval: NSTimeInterval = 0.1 public var backspaceAutoDeleteModeInterval: NSTimeInterval = 0.5 private var backspaceDeleteTimer: NSTimer? private var backspaceAutoDeleteModeTimer: NSTimer? // MARK: KeyMenu public var keyMenuLocked: Bool = false public var keyMenuOpenTimer: NSTimer? public var keyMenuOpenTimeInterval: NSTimeInterval = 1 public var keyMenuShowingKeyboardButton: KeyboardButton? { didSet { oldValue?.showKeyPop(show: false) oldValue?.showKeyMenu(show: false) keyMenuShowingKeyboardButton?.showKeyPop(show: false) keyMenuShowingKeyboardButton?.showKeyMenu(show: true) dispatch_after( dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { [weak self] in self?.getCurrentKeyboardLayout().typingEnabled = self!.keyMenuShowingKeyboardButton == nil && self!.keyMenuLocked == false } } } // MARK: Init public init() { super.init(frame: CGRect.zero) defaultInit() } public override init(frame: CGRect) { super.init(frame: frame) defaultInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) defaultInit() } private func defaultInit() { keyboardLayout = CustomKeyboardLayout() keyboardLayoutStateDidChange(oldState: nil, newState: keyboardLayoutState) } // MARK: Layout public override func layoutSubviews() { super.layoutSubviews() getCurrentKeyboardLayout().frame = CGRect( x: 0, y: 0, width: frame.size.width, height: frame.size.height) } // MARK: KeyboardLayout public func getKeyboardLayout(ofState state: CustomKeyboardLayoutState) -> KeyboardLayout { switch state { case .Letters(let shiftState): switch shiftState { case .Once: return keyboardLayout.uppercase case .On: return keyboardLayout.uppercaseToggled case .Off: return keyboardLayout.lowercase } case .Numbers: return keyboardLayout.numbers case .Symbols: return keyboardLayout.symbols } } public func getCurrentKeyboardLayout() -> KeyboardLayout { return getKeyboardLayout(ofState: keyboardLayoutState) } public func enumerateKeyboardLayouts(enumerate: (KeyboardLayout) -> Void) { let layouts = [ keyboardLayout.uppercase, keyboardLayout.uppercaseToggled, keyboardLayout.lowercase, keyboardLayout.numbers, keyboardLayout.symbols, ] for layout in layouts { enumerate(layout) } } public func keyboardLayoutStateDidChange(oldState oldState: CustomKeyboardLayoutState?, newState: CustomKeyboardLayoutState) { // Remove old keyboard layout if let oldState = oldState { let oldKeyboardLayout = getKeyboardLayout(ofState: oldState) oldKeyboardLayout.delegate = nil oldKeyboardLayout.removeFromSuperview() } // Add new keyboard layout let newKeyboardLayout = getKeyboardLayout(ofState: newState) newKeyboardLayout.delegate = self addSubview(newKeyboardLayout) setNeedsLayout() } public func reload() { // Remove current let currentLayout = getCurrentKeyboardLayout() currentLayout.delegate = nil currentLayout.removeFromSuperview() // Reload layout keyboardLayout = CustomKeyboardLayout() keyboardLayoutStateDidChange(oldState: nil, newState: keyboardLayoutState) } // MARK: Capitalize public func switchToLetters(shiftState shift: CustomKeyboardShiftState) { keyboardLayoutState = .Letters(shiftState: shift) } public func capitalize() { switchToLetters(shiftState: .Once) } // MARK: Backspace Auto Delete private func startBackspaceAutoDeleteModeTimer() { backspaceAutoDeleteModeTimer = NSTimer.scheduledTimerWithTimeInterval( backspaceAutoDeleteModeInterval, target: self, selector: #selector(CustomKeyboard.startBackspaceAutoDeleteMode), userInfo: nil, repeats: false) } private func startBackspaceDeleteTimer() { backspaceDeleteTimer = NSTimer.scheduledTimerWithTimeInterval( backspaceDeleteInterval, target: self, selector: #selector(CustomKeyboard.autoDelete), userInfo: nil, repeats: true) } private func invalidateBackspaceAutoDeleteModeTimer() { backspaceAutoDeleteModeTimer?.invalidate() backspaceAutoDeleteModeTimer = nil } private func invalidateBackspaceDeleteTimer() { backspaceDeleteTimer?.invalidate() backspaceDeleteTimer = nil } internal func startBackspaceAutoDeleteMode() { invalidateBackspaceDeleteTimer() startBackspaceDeleteTimer() } internal func autoDelete() { delegate?.customKeyboardBackspaceButtonPressed?(self) } // MARK: Shift Toggle private func startShiftToggleTimer() { shiftToggleTimer = NSTimer.scheduledTimerWithTimeInterval( shiftToggleInterval, target: self, selector: #selector(CustomKeyboard.invalidateShiftToggleTimer), userInfo: nil, repeats: false) } internal func invalidateShiftToggleTimer() { shiftToggleTimer?.invalidate() shiftToggleTimer = nil } // MARK: KeyMenu Toggle private func startKeyMenuOpenTimer(forKeyboardButton keyboardButton: KeyboardButton) { keyMenuOpenTimer = NSTimer.scheduledTimerWithTimeInterval( keyMenuOpenTimeInterval, target: self, selector: #selector(CustomKeyboard.openKeyMenu(_:)), userInfo: keyboardButton, repeats: false) } private func invalidateKeyMenuOpenTimer() { keyMenuOpenTimer?.invalidate() keyMenuOpenTimer = nil } public func openKeyMenu(timer: NSTimer) { if let userInfo = timer.userInfo, keyboardButton = userInfo as? KeyboardButton { keyMenuShowingKeyboardButton = keyboardButton } } // MARK: KeyboardLayoutDelegate public func keyboardLayout(keyboardLayout: KeyboardLayout, didKeyPressStart keyboardButton: KeyboardButton) { invalidateBackspaceAutoDeleteModeTimer() invalidateBackspaceDeleteTimer() invalidateKeyMenuOpenTimer() // Backspace if keyboardButton.identifier == CustomKeyboardIdentifier.Backspace.rawValue { startBackspaceAutoDeleteModeTimer() } // KeyPop and KeyMenu if keyboardButton.style.keyPopType != nil { keyboardButton.showKeyPop(show: true) if keyboardButton.keyMenu != nil { startKeyMenuOpenTimer(forKeyboardButton: keyboardButton) } } else if keyboardButton.keyMenu != nil { keyMenuShowingKeyboardButton = keyboardButton keyMenuLocked = false } } public func keyboardLayout(keyboardLayout: KeyboardLayout, didKeyPressEnd keyboardButton: KeyboardButton) { delegate?.customKeyboard?(self, keyboardButtonPressed: keyboardButton) // If keyboard key is pressed notify no questions asked if case KeyboardButtonType.Key(let text) = keyboardButton.type { delegate?.customKeyboard?(self, keyButtonPressed: text) // If shift state was CustomKeyboardShiftState.Once then make keyboard layout lowercase if case CustomKeyboardLayoutState.Letters(let shiftState) = keyboardLayoutState where shiftState == CustomKeyboardShiftState.Once { keyboardLayoutState = CustomKeyboardLayoutState.Letters(shiftState: .Off) return } } // Chcek special keyboard buttons if let keyId = keyboardButton.identifier, identifier = CustomKeyboardIdentifier(rawValue: keyId) { switch identifier { // Notify special keys case .Backspace: delegate?.customKeyboardBackspaceButtonPressed?(self) case .Space: delegate?.customKeyboardSpaceButtonPressed?(self) case .Globe: delegate?.customKeyboardGlobeButtonPressed?(self) case .Return: delegate?.customKeyboardReturnButtonPressed?(self) // Update keyboard layout state case .Letters: keyboardLayoutState = .Letters(shiftState: .Off) case .Numbers: keyboardLayoutState = .Numbers case .Symbols: keyboardLayoutState = .Symbols // Update shift state case .ShiftOff: if shiftToggleTimer == nil { keyboardLayoutState = .Letters(shiftState: .Once) startShiftToggleTimer() } else { keyboardLayoutState = .Letters(shiftState: .On) invalidateShiftToggleTimer() } case .ShiftOnce: if shiftToggleTimer == nil { keyboardLayoutState = .Letters(shiftState: .Off) startShiftToggleTimer() } else { keyboardLayoutState = .Letters(shiftState: .On) invalidateShiftToggleTimer() } case .ShiftOn: if shiftToggleTimer == nil { keyboardLayoutState = .Letters(shiftState: .Off) } } } } public func keyboardLayout(keyboardLayout: KeyboardLayout, didTouchesBegin touches: Set<UITouch>) { // KeyMenu if let menu = keyMenuShowingKeyboardButton?.keyMenu, touch = touches.first { menu.updateSelection(touchLocation: touch.locationInView(self), inView: self) } } public func keyboardLayout(keyboardLayout: KeyboardLayout, didTouchesMove touches: Set<UITouch>) { // KeyMenu if let menu = keyMenuShowingKeyboardButton?.keyMenu, touch = touches.first { menu.updateSelection(touchLocation: touch.locationInView(self), inView: self) } } public func keyboardLayout(keyboardLayout: KeyboardLayout, didTouchesEnd touches: Set<UITouch>?) { invalidateBackspaceAutoDeleteModeTimer() invalidateBackspaceDeleteTimer() invalidateKeyMenuOpenTimer() // KeyMenu if let menu = keyMenuShowingKeyboardButton?.keyMenu, touch = touches?.first { menu.updateSelection(touchLocation: touch.locationInView(self), inView: self) // select item if menu.selectedIndex >= 0 { if let item = menu.items[safe: menu.selectedIndex] { item.action?(keyMenuItem: item) } keyMenuShowingKeyboardButton = nil keyMenuLocked = false } else { if keyMenuLocked { keyMenuShowingKeyboardButton = nil keyMenuLocked = false return } keyMenuLocked = true } } } public func keyboardLayout(keyboardLayout: KeyboardLayout, didTouchesCancel touches: Set<UITouch>?) { invalidateBackspaceAutoDeleteModeTimer() invalidateBackspaceDeleteTimer() invalidateKeyMenuOpenTimer() // KeyMenu if let menu = keyMenuShowingKeyboardButton?.keyMenu, touch = touches?.first { menu.updateSelection(touchLocation: touch.locationInView(self), inView: self) // select item if menu.selectedIndex >= 0 { if let item = menu.items[safe: menu.selectedIndex] { item.action?(keyMenuItem: item) } keyMenuShowingKeyboardButton = nil keyMenuLocked = false } else { if keyMenuLocked { keyMenuShowingKeyboardButton = nil keyMenuLocked = false getCurrentKeyboardLayout().typingEnabled = true return } keyMenuLocked = true } } } }
mit
febe020558bce1297727a50300b3a360
30.922693
137
0.713694
4.778275
false
false
false
false
takuran/CoreAnimationLesson
CoreAnimationLesson/Lesson1_2ViewController.swift
1
2143
// // Lesson1_2ViewController.swift // CoreAnimationLesson // // Created by Naoyuki Takura on 2015/03/04. // Copyright (c) 2015年 Naoyuki Takura. All rights reserved. // import UIKit class Lesson1_2ViewController: UIViewController { @IBOutlet weak var myView: UIView! @IBOutlet weak var mySegmentedControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // initialize segmented control mySegmentedControl.addTarget(self, action: #selector(Lesson1_2ViewController.segmentedValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged) // image content let image = UIImage(named: "chess.png") // set image to layer contents myView.layer.contents = image?.CGImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func segmentedValueChanged(target: UISegmentedControl) { switch (target.selectedSegmentIndex) { case 0: // myView.contentMode = UIViewContentMode.ScaleToFill case 1: // myView.contentMode = UIViewContentMode.ScaleAspectFit case 2: myView.contentMode = UIViewContentMode.ScaleAspectFill case 3: myView.contentMode = UIViewContentMode.Center case 4: myView.contentMode = UIViewContentMode.Bottom default: print("no such index. index : \(target.selectedSegmentIndex)") } print("geometryFlipped value : \(myView.layer.geometryFlipped)") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ebbfb4ca2d7350bd8cd63785662d33fe
26.448718
160
0.62681
5.518041
false
false
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/Reminder/FMCalendarAndReminderViewController.swift
1
4514
// // FMRootViewController.swift // TestCode // // Created by Zhouheng on 2020/6/3. // Copyright © 2020 tataUFO. All rights reserved. // import UIKit import EventKit class FMCalendarAndReminderViewController: UIViewController { let reminderManager = GGReminderManager() var currentCalendar: EKCalendar? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = .gray setupUI() } private func setupUI() { view.addSubview(addButton) view.addSubview(queryButton) view.addSubview(removeButton) view.addSubview(editButton) // view.addSubview(popButton) // view.addSubview(reminderButton) } /// MARK: --- action @objc private func add(_ sender: UIButton) { addReminder() } @objc private func query(_ sender: UIButton) { reminderManager.queryReminder { (_) in } } @objc private func remove(_ sender: UIButton) { reminderManager.removeReminder("E17FFAAD-3B65-4E42-98BF-71CD4EC667C0") } @objc private func edit(_ sender: UIButton) { reminderManager.updateReminder("E17FFAAD-3B65-4E42-98BF-71CD4EC667C0") } @objc private func popAction(_ sender: UIButton) { } @objc private func reminderAction(_ sender: UIButton) { } private func addReminder() { let sDate = Date(timeInterval: 60 * 10, since: Date()) let eDate = Date(timeInterval: 60 * 20, since: Date()) let title = "reminder title 提醒事件标题" // 申请提醒权限 reminderManager.requestAuthorized(.reminder) { [weak self] (granted, error) in guard let `self` = self else { return } if granted { self.reminderManager.createReminder(title, startDate: sDate, endDate: eDate, repeatIndex: 0, remindIndexs: [0, 1, 2], notes: "reminder 测试事件") } else { print("没有添加事件的权限") if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.openURL(url) } } } } /// MARK: --- lazy loading lazy var addButton: UIButton = { let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 50, width: 200, height: 50)) button.setTitle("添加提醒", for: .normal) button.addTarget(self, action: #selector(add(_:)), for: .touchUpInside) button.backgroundColor = .gray return button }() lazy var queryButton: UIButton = { let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 110, width: 200, height: 50)) button.setTitle("查找提醒", for: .normal) button.addTarget(self, action: #selector(query(_:)), for: .touchUpInside) button.backgroundColor = .gray return button }() lazy var removeButton: UIButton = { let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 170, width: 200, height: 50)) button.setTitle("删除提醒", for: .normal) button.addTarget(self, action: #selector(remove(_:)), for: .touchUpInside) button.backgroundColor = .gray return button }() lazy var editButton: UIButton = { let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 230, width: 200, height: 50)) button.setTitle("修改提醒", for: .normal) button.addTarget(self, action: #selector(edit(_:)), for: .touchUpInside) button.backgroundColor = .gray return button }() lazy var popButton: UIButton = { let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 290, width: 200, height: 50)) button.setTitle("弹框", for: .normal) button.addTarget(self, action: #selector(popAction(_:)), for: .touchUpInside) button.backgroundColor = .gray return button }() lazy var reminderButton: UIButton = { let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 360, width: 200, height: 50)) button.setTitle("提醒", for: .normal) button.addTarget(self, action: #selector(reminderAction(_:)), for: .touchUpInside) button.backgroundColor = .gray return button }() }
apache-2.0
53b8bb94da7f5e782110ef8ce87b6380
32.255639
157
0.591002
4.208373
false
false
false
false
pepperbilly/messUp
messUp/DetailViewController.swift
1
993
// // DetailViewController.swift // messUp // // Created by Sascha Bencze on 16.03.16. // Copyright © 2016 Sascha Bencze. All rights reserved. // import Foundation import UIKit class DetailViewController : UIViewController, ConnectionModelProtocal { func itemsDownloaded(items: NSArray){ dispatch_async(dispatch_get_main_queue()) { // self.tableView.reloadData() } } var dataPassed:String! var dataPassedAddress:String! @IBOutlet weak var detailLabelName: UITextField! @IBOutlet weak var detailLabelAddress: UILabel! let connectionModel = ConnectionModel() let viewController = ViewController() override func viewDidLoad() { super.viewDidLoad() connectionModel.delegate = self self.detailLabelName.text = String(dataPassed) self.detailLabelAddress.text = String(dataPassedAddress) print(self.dataPassed) print(self.dataPassedAddress) } }
mit
c376609a15a13dccc5db0b891d7fefa6
25.131579
72
0.674395
4.571429
false
false
false
false
aipeople/SimplyLayout
SimplyLayoutDemo/ViewController.swift
1
3927
// // ViewController.swift // SimplyLayoutDemo // // Created by aipeople on 15/09/2017. // Copyright © 2017 aipeople. All rights reserved. // import UIKit import SimplyLayout class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let background = UIView() background.backgroundColor = .lightGray view.addSubview(background) background.edgeAnchor == background.superview!.edgeAnchor + UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20) let boxA = UIView() let boxB = UIView() view.addSubview(boxA) view.addSubview(boxB) boxA.backgroundColor = .red boxB.backgroundColor = .orange let verticalConstraintGroup = NSLayoutConstraint.group { boxA.centerXAnchor == boxA.superview!.centerXAnchor boxB.centerXAnchor == boxB.superview!.centerXAnchor boxA.heightAnchor == boxB.heightAnchor boxA.widthAnchor == 40 boxB.widthAnchor == 40 boxA.topAnchor == boxA.superview!.topAnchor + 10 boxB.topAnchor == boxA.bottomAnchor + 10 boxB.bottomAnchor == boxB.superview!.bottomAnchor - 10 } let horizontalConstraintGroup = NSLayoutConstraint.group(activated: false) { boxA.centerYAnchor == boxA.superview!.centerYAnchor boxB.centerYAnchor == boxB.superview!.centerYAnchor boxA.widthAnchor == boxB.widthAnchor boxA.heightAnchor == 40 boxB.heightAnchor == 40 boxA.leftAnchor == boxA.superview!.leftAnchor + 10 boxB.leftAnchor == boxA.rightAnchor + 10 boxB.rightAnchor == boxB.superview!.rightAnchor - 10 } let box = UIView() box.backgroundColor = .lightGray view.addSubview(box) // Setup globally configs // Basically, configs should be set in `didFinishLaunchingWithOptions:` //SimplyLayout.config.defaultActivation = true // Default value is `true` //SimplyLayout.config.defaultPriority = .required // Default value is `.required` // Setup a constraint with constant by using `+` or `-` box.widthAnchor == 100 // The constant can be Int, Double, CGFloat // Setup a constraint with mutiplier by using `*` box.heightAnchor == box.superview!.heightAnchor * 0.25 + 40 // Setup a constraint with priority by using `~` box.heightAnchor == box.superview!.heightAnchor * 0.25 ~ 750 // Setup a constraint with activate or inactivate state by using `--` or `++` box.centerXAnchor == box.superview!.centerXAnchor ~ 750 // The constraint will be activated based on the value of `defaultActivation` in configs. box.centerXAnchor == --box.superview!.centerXAnchor + 100 // This will force the constraint stays in inactive mode after created. // Store the created constraint let centerYConstraint = box.centerYAnchor == box.superview!.centerYAnchor // Modify the stored constraint DispatchQueue.global().async { sleep(3) DispatchQueue.main.async { UIView.animate(withDuration: 0.5, animations: { centerYConstraint.constant = 100 verticalConstraintGroup.deactivateAll() horizontalConstraintGroup.activateAll() self.view.layoutIfNeeded() }) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f04d6aa89c94068ec684080e272c7906
35.018349
153
0.588385
5.283984
false
false
false
false
FaiChou/Cassini
Cassini/Cassini/Global.swift
1
1785
// // Global.swift // Cassini // // Created by 周辉 on 2017/5/22. // Copyright © 2017年 周辉. All rights reserved. // import Foundation import UIKit struct Global { private init() {} static let ThemeColor = UIColor(red:0.13, green:0.13, blue:0.20, alpha:1.00) static let screenWidth: CGFloat = UIScreen.main.bounds.width static let screenHeight: CGFloat = UIScreen.main.bounds.height static let naviHeight: CGFloat = 64 static let tabHeight: CGFloat = 49 } let HOST = "CassiniHost" let PORT = "CassiniPort" let CassiniJourneyDescription = "Saturn, get ready for your close-up! Today the Cassini spacecraft starts a series of swoops between Saturn and its rings. These cosmic acrobatics are part of Cassini's dramatic \"Grand Finale,\" a set of orbits offering Earthlings an unprecedented look at the second largest planet in our solar system.\n\n" + "By plunging into this fascinating frontier, Cassini will help scientists learn more about the origins, mass, and age of Saturn's rings, as well as the mysteries of the gas giant's interior. And of course there will be breathtaking additions to Cassini's already stunning photo gallery. Cassini recently revealed some secrets of Saturn's icy moon Enceladus -- including conditions friendly to life! Who knows what marvels this hardy explorer will uncover in the final chapter of its mission?\n\n" + "Cassini is a joint endeavor of NASA, the European Space Agency (ESA), and the Italian space agency (ASI). The spacecraft began its 2.2 billion–mile journey 20 years ago and has been hanging out with Saturn since 2004. Later this year, Cassini will say goodbye and become part of Saturn when it crashes through the planet’s atmosphere. But first, it has some spectacular sightseeing to do!"
mit
eb2e95e627419ae7e84c4a1627d820f1
58
501
0.764972
3.742072
false
false
false
false
Jezong/JZScrollTitleView
JZScrollTitleView/ViewController.swift
1
2102
// // ViewController.swift // JZScrollTitleView // // Created by jezong on 16/2/25. // Copyright © 2016年 jezong. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { var scrollTitleView: JZScrollTitleView! var scrollImageView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() let effectView = UIVisualEffectView(frame: CGRectMake(0, 0, self.view.bounds.width, 50)) scrollTitleView = JZScrollTitleView(frame: effectView.bounds) scrollImageView = UIScrollView(frame: self.view.bounds) self.view.addSubview(scrollImageView) self.view.addSubview(effectView) effectView.contentView.addSubview(scrollTitleView) //添加模糊效果 effectView.effect = UIBlurEffect(style: .ExtraLight) scrollImageView.bounces = false scrollImageView.pagingEnabled = true scrollImageView.delegate = self let pics = ["Shanghai", "Paris", "Singapore", "Taipei", "Willemstad"] scrollTitleView.titles = pics scrollTitleView.backgroundColor = .clearColor() scrollTitleView.addTarget(self, action: "tapTitle", forControlEvents: .ValueChanged) for (index, pic) in pics.enumerate() { let imageView = UIImageView(frame: CGRectOffset(scrollImageView.bounds, CGFloat(index)*scrollImageView.bounds.width, 0)) imageView.image = UIImage(named: pic) imageView.contentMode = .ScaleAspectFit scrollImageView.addSubview(imageView) } scrollImageView.contentSize = CGSizeMake(CGFloat(pics.count)*scrollImageView.bounds.width, scrollImageView.bounds.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tapTitle() { var point = CGPointZero point.x = CGFloat(scrollTitleView.currentPos) * scrollImageView.bounds.width scrollImageView.setContentOffset(point, animated: true) } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let pos = Int(scrollView.contentOffset.x / scrollView.bounds.width) scrollTitleView.setSelectedPosition(pos, animated: true) } }
mit
dec61ceaa896b3ce12b7c8db8cbd2b79
32.66129
123
0.759463
4.044574
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Coursera/Enumerate.swift
1
2149
// // Enumerate.swift // Algorithm // // Created by 朱双泉 on 2018/5/18. // Copyright © 2018 Castie!. All rights reserved. // import Foundation func money100chicken100() { for x in 0...100 { for y in 0...(100 - x) { let z = 100 - x - y if z % 3 == 0, 5 * x + 3 * y + z / 3 == 100 { print("(\(x), \(y), \(z) is solution") } } } } var puzzle = [[Int]](repeating: [Int](repeating: 0, count: 8), count: 6) var press = [[Int]](repeating: [Int](repeating: 0, count: 8), count: 6) func guess() -> Bool { for r in 1..<5 { for c in 1..<7 { press[r + 1][c] = (puzzle[r][c] + press[r][c] + press[r - 1][c] + press[r][c - 1] + press[r][c + 1]) % 2 } } for c in 1..<7 { if (press[5][c - 1] + press[5][c] + press[5][c + 1] + press[4][c]) % 2 != puzzle[5][c] { return false } } return true } func enumerate() { var c = 1 for _ in 1..<7 { press[1][c] = 0 while (guess() == false) { press[1][1] += 1 c = 1 while press[1][c] > 1 { press[1][c] = 0 c += 1 press[1][c] += 1 } } c += 1 } } class Enumerate { static func main() { let cases = 1 for r in 0..<6 { press[r][0] = 0 press[r][7] = 0 } for c in 1..<7 { press[0][c] = 0 } for i in 0..<cases { for r in 1..<6 { for c in 1..<7 { puzzle[r][c] = 2.arc4random } } enumerate() print("PUZZLE #\(i + 1)") for r in 1..<6 { for c in 1..<7 { print(puzzle[r][c], terminator: "") } print() } print("== press ==") for r in 1..<6 { for c in 1..<7 { print(press[r][c], terminator: "") } print() } print() } } }
mit
65329c5c9a6fb3fb400325556cf79e08
22.538462
116
0.353408
3.46042
false
false
false
false
danielgindi/ios-charts
Source/Charts/Components/Description.swift
2
1311
// // Description.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 Foundation import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif @objc(ChartDescription) open class Description: ComponentBase { public override init() { #if os(tvOS) // 23 is the smallest recommended font size on the TV font = .systemFont(ofSize: 23) #elseif os(OSX) font = .systemFont(ofSize: NSUIFont.systemFontSize) #else font = .systemFont(ofSize: 8.0) #endif super.init() } /// The text to be shown as the description. @objc open var text: String? /// Custom position for the description text in pixels on the screen. open var position: CGPoint? = nil /// The text alignment of the description text. Default RIGHT. @objc open var textAlign: TextAlignment = TextAlignment.right /// Font object used for drawing the description text. @objc open var font: NSUIFont /// Text color used for drawing the description text @objc open var textColor = NSUIColor.labelOrBlack }
apache-2.0
1f8e5862b4d940190ce1b9b0f0bc3f97
23.277778
73
0.656751
4.3125
false
false
false
false
andersonkxiass/UITableViewHeader
UITableViewHeader/TableViewCell.swift
2
3863
// // TableViewCell.swift // UITableViewHeader // // Created by Anderson Caxias on 13/06/15. // Copyright (c) 2015 Anderson Caxias. All rights reserved. // import UIKit class TableViewCell: UITableViewCell, UITableViewDataSource,UITableViewDelegate { var dataArr:[String] = [] var tableView:UITableView? let cellIdentifierTest:String = "CellTest" var headerView = UIView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style , reuseIdentifier: reuseIdentifier) setUpTable() preservesSuperviewLayoutMargins = true } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUpTable(){ tableView = UITableView(frame: CGRectZero, style:UITableViewStyle.Plain) tableView!.delegate = self tableView!.dataSource = self //Disable scrollview from uitableview tableView!.scrollEnabled = false //Hide Empty rows var tblView = UIView(frame: CGRectZero) tableView!.tableFooterView = tblView tableView!.tableFooterView!.hidden = true tableView!.backgroundColor = UIColor.clearColor() tableView!.separatorStyle = .None tableView!.registerNib(UINib(nibName: "LTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifierTest) self.addSubview(tableView!) } override func layoutSubviews() { super.layoutSubviews() tableView!.frame = CGRectMake(10, 10, self.bounds.size.width - 20, self.bounds.size.height) tableView!.layoutIfNeeded() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:LTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifierTest) as? LTableViewCell if(cell == nil) { cell = NSBundle.mainBundle().loadNibNamed("LTableViewCell", owner: self, options: nil)[0] as? LTableViewCell } cell!.selectionStyle = .None cell?.label.text = "\(indexPath.row) Test" return cell! } // Customize the section headings for each section func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "" } // func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // var headerView = UIView() // headerView = CGRectMake(0, 0, tableView.frame.size.width, 50.0) // headerView = UIColor.whiteColor() // return headerView // } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50.0 } // func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { // var sectionHeaderView = UIView() // sectionHeaderView.frame = CGRectMake(0, 0, tableView.frame.size.width, 50.0) // sectionHeaderView.backgroundColor = UIColor.whiteColor() // return sectionHeaderView // } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 50.0 } }
apache-2.0
62d16f481b7a04a58a98867d01025f89
31.470588
121
0.645612
5.313618
false
false
false
false
radex/swift-compiler-crashes
crashes-duplicates/03815-swift-sourcemanager-getmessage.swift
11
2285
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing C { println() { func g class return " typealias e : c<T>: NSObject { let t: T> typealias e : Int -> U) typealias e == { return """ typealias e == ""[1)" class func g class a<T where T : Int -> U))"[Void{ func i: c { class a { let t: a { protocol A { class class a { case c<T>: c { func i: a { class b: a { class class c<T>: a { typealias e == " let i: b: c { println("\("[Void{ struct A { func g: b println(f: e : a { class b println("[Void{ typealias e { case c<d where g var d = ""[Void{ typealias e == { class typealias e : P typealias e { protocol A { class c, class a protocol A { func g<d where T : NSObject { } struct Q<T: e class b protocol A : e println(" class a<T>: b class protocol A : NSObject { func i: a { class class protocol A { let i: a { class a<T> let i: e : Int -> U) typealias e == ""[1)"\("\() { let t: e return " } } typealias e : b: a { class c, } } typealias e == "\() -> () { class c<T where g<T where T : b return " func f: a { typealias e { func g: Int -> U)" println(" class struct Q<d where T : e : e == { let t: NSObject { println() -> U) return "[1)"" class a { class let f = [Void{ { protocol A { case c, let t: C { class } struct A { class a { class c<T : a { class a { let f = " struct A { class a { } class var d = [Void{ class case c<T : e == "[1)"""" struct A { class case c, struct Q<d where T where g protocol A : NSObject { { func f: NSObject { class let i() -> () -> U)"" case c<T where T where g class a { let f = " let t: e : BooleanType, A { let t: e { protocol A { protocol A { struct A { struct Q<d where T where T { typealias e : C { struct S<T>: e : e : b let f = [1)" struct S<T : a { class case c, class let t: T>: c<T> class a { protocol A : a { } class let t: C { let f = [Void{ func g<T where g: b func f: b: T>: e { return " let t: b let i: a { { class a { func a<T>: a { class class b: a { let t: a { func g class c<T : a { func a<T> struct A { func g: NSObject { func i: C { println(f: C { class a<T where T : Int -> (f: e : c { let i: NSObject { struct S<T: NSObject { func i: a { let f = { class a<T> typealias e : e { let f = [1) class } } protocol A { }
mit
2953c6b8db5167873bd8b896f1a87c54
12.52071
87
0.596061
2.536071
false
false
false
false
jingkecn/WatchWorker
src/ios/Services/WCMessageService.swift
1
2338
// // WCMessageService.swift // WTVJavaScriptCore // // Created by Jing KE on 18/07/16. // Copyright © 2016 WizTiVi. All rights reserved. // import Foundation import WatchConnectivity public class WCMessageService: NSObject, WCSessionDelegate { typealias MessageListener = (message: String) -> Void public typealias StartHandler = () -> Void public static let sharedInstance = WCMessageService() var session: WCSession? = { guard WCSession.isSupported() else { return nil } return WCSession.defaultSession() }() var listeners = Array<MessageListener>() } extension WCMessageService { public func startService(onSuccess successHandler: StartHandler? = nil, onError errorHandler: StartHandler? = nil) { print("Starting message service. onSuccess = \(successHandler), onError = \(errorHandler)") self.session?.delegate = self self.session?.activateSession() if let session = self.session where session.reachable { successHandler?() } else { errorHandler?() } } } extension WCMessageService { func addMessageListener(listener: MessageListener) { self.listeners.append(listener) } func dispatchMessage(message: String) { self.listeners.forEach({ $0(message: message) }) } } extension WCMessageService { var isReachable: Bool { return self.session?.reachable ?? false } func sendMessage(message: String) { guard let session = self.session /*where session.reachable*/ else { return } session.sendMessage([PHONE_MESSAGE: message], replyHandler: nil, errorHandler: nil) } } // MARK: ********** Basic interactive messaging ********** extension WCMessageService { public func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) { print("Receiving message without reply handler...") if let messageBody = message[WATCH_MESSAGE] as? String { print("Receiving a message from iPhone: \(messageBody)") dispatch_async(dispatch_get_main_queue(), { self.dispatchMessage(messageBody) }) } else { print("Receiving an invalid message: \(message)") } } }
mit
a2c7b807cf814fe0548480365daa9b96
26.833333
120
0.633718
4.878914
false
false
false
false
Rag0n/QuNotes
Carthage/Checkouts/WSTagsField/Source/WSTag.swift
1
537
// // WSTag.swift // Whitesmith // // Created by Ricardo Pereira on 12/05/16. // Copyright © 2016 Whitesmith. All rights reserved. // import Foundation public struct WSTag: Hashable { public let text: String public init(_ text: String) { self.text = text } public var hashValue: Int { return self.text.hashValue } public func equals(_ other: WSTag) -> Bool { return self.text == other.text } } public func ==(lhs: WSTag, rhs: WSTag) -> Bool { return lhs.equals(rhs) }
gpl-3.0
5dc5280bbb0c7ba5ccc2d477d4db4244
16.290323
53
0.61194
3.480519
false
false
false
false
martinpucik/VIPER-Example
VIPER-Example/Modules/Main/Wireframe/MainWireframe.swift
1
3518
// // ResetPasswordWireframe.swift // oneprove-ios // import UIKit class MainWireframe { weak var viewController: MainViewController? fileprivate weak var menuController: MenuWireframe? init() { viewController = loadControllerFromSB() let interactor = MainInteractor() let presenter = MainPresenter() presenter.wireframe = self presenter.view = viewController presenter.interactor = interactor viewController?.presenter = presenter interactor.presenter = presenter } fileprivate func loadControllerFromSB() -> MainViewController? { // For multiple idioms support in one module, just instantiate correct controller from storyboard let name = UIDevice.current.userInterfaceIdiom == .pad ? "Main-iPad":"Main" let storyboard = UIStoryboard.init(name: name, bundle: nil) let controller = storyboard.instantiateInitialViewController() as? MainViewController return controller } } extension MainWireframe: WireframeProtocol { func push() { guard let window = UIApplication.shared.keyWindow, let root = window.rootViewController as? UINavigationController, let vc = viewController else { return } root.pushViewController(vc, animated: true) } func pop() { guard let viewController = viewController else { return } viewController.navigationController?.popViewController(animated: true) } func dismiss() { viewController?.dismiss(animated: true, completion: nil) } func present() { guard let window = UIApplication.shared.keyWindow, let root = window.rootViewController, let viewController = viewController else { return } root.present(viewController, animated: true, completion: nil) } func makeRoot() { if (UIApplication.shared.delegate as! AppDelegate).window == nil { let window = UIWindow.init(frame: UIScreen.main.bounds) (UIApplication.shared.delegate as! AppDelegate).window = window } let window = (UIApplication.shared.delegate as! AppDelegate).window! guard let viewController = viewController else { return } let navController = UINavigationController.init(rootViewController: viewController) window.rootViewController = navController window.makeKeyAndVisible() } } extension MainWireframe: MainWireframeInterface { func pushResetPassword() { let wireframe = ResetPasswordWireframe() wireframe.push() } func presentMenu() { let wireframe = MenuWireframe.init() wireframe.present() } func presentMenuInteractive() { if menuController == nil { debugPrint("creating menu") menuController = MenuWireframe.init() } menuController?.presentInteractive() } func presentTakeOverview(withArtwork artwork: Artwork) { let wireframe = TakeOverviewWireframe.init(withArtwork: artwork) wireframe.present() } func updateInteraction(withProgress progress: CGFloat) { menuController?.updateInteraction(withProgress: progress) } func cancelInteraction() { menuController?.cancelInteraction() menuController = nil } func finishInteraction() { menuController?.finishInteraction() menuController = nil } }
mit
3dd87fecde67c6fb9f4fb26088b4439b
30.981818
105
0.65776
5.548896
false
false
false
false
tourani/GHIssue
Pods/p2.OAuth2/Sources/Base/OAuth2Error.swift
2
10576
// // OAuth2Error.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** All errors that might occur. The response errors return a description as defined in the spec: http://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ public enum OAuth2Error: Error, CustomStringConvertible, Equatable { /// An error for which we don't have a specific one. case generic(String) /// An error holding on to an NSError. case nsError(Foundation.NSError) /// Invalid URL components, failed to create a URL case invalidURLComponents(URLComponents) // MARK: - Client errors /// There is no client id. case noClientId /// There is no client secret. case noClientSecret /// There is no redirect URL. case noRedirectURL /// There is no username. case noUsername /// There is no password. case noPassword /// The client is already authorizing. case alreadyAuthorizing /// There is no authorization context. case noAuthorizationContext /// The authorization context is invalid. case invalidAuthorizationContext /// The redirect URL is invalid; with explanation. case invalidRedirectURL(String) /// There is no refresh token. case noRefreshToken /// There is no registration URL. case noRegistrationURL // MARK: - Request errors /// The request is not using SSL/TLS. case notUsingTLS /// Unable to open the authorize URL. case unableToOpenAuthorizeURL /// The request is invalid. case invalidRequest /// The request was cancelled. case requestCancelled // MARK: - Response Errors /// There was no token type in the response. case noTokenType /// The token type is not supported. case unsupportedTokenType(String) /// There was no data in the response. case noDataInResponse /// Some prerequisite failed; with explanation. case prerequisiteFailed(String) /// The state parameter was missing in the response. case missingState /// The state parameter was invalid. case invalidState /// The JSON response could not be parsed. case jsonParserError /// Unable to UTF-8 encode. case utf8EncodeError /// Unable to decode to UTF-8. case utf8DecodeError // MARK: - OAuth2 errors /// The client is unauthorized (HTTP status 401). case unauthorizedClient /// The request was forbidden (HTTP status 403). case forbidden /// Username or password was wrong (HTTP status 403 on password grant). case wrongUsernamePassword /// Access was denied. case accessDenied /// Response type is not supported. case unsupportedResponseType /// Scope was invalid. case invalidScope /// A 500 was thrown. case serverError /// The service is temporarily unavailable. case temporarilyUnavailable /// Other response error, as defined in its String. case responseError(String) /** Instantiate the error corresponding to the OAuth2 response code, if it is known. - parameter code: The code, like "access_denied", that should be interpreted - parameter fallback: The error string to use in case the error code is not known - returns: An appropriate OAuth2Error */ public static func fromResponseError(_ code: String, fallback: String? = nil) -> OAuth2Error { switch code { case "invalid_request": return .invalidRequest case "unauthorized_client": return .unauthorizedClient case "access_denied": return .accessDenied case "unsupported_response_type": return .unsupportedResponseType case "invalid_scope": return .invalidScope case "server_error": return .serverError case "temporarily_unavailable": return .temporarilyUnavailable default: return .responseError(fallback ?? "Authorization error: \(code)") } } /// Human understandable error string. public var description: String { switch self { case .generic(let message): return message case .nsError(let error): return error.localizedDescription case .invalidURLComponents(let components): return "Failed to create URL from components: \(components)" case .noClientId: return "Client id not set" case .noClientSecret: return "Client secret not set" case .noRedirectURL: return "Redirect URL not set" case .noUsername: return "No username" case .noPassword: return "No password" case .alreadyAuthorizing: return "The client is already authorizing, wait for it to finish or abort authorization before trying again" case .noAuthorizationContext: return "No authorization context present" case .invalidAuthorizationContext: return "Invalid authorization context" case .invalidRedirectURL(let url): return "Invalid redirect URL: \(url)" case .noRefreshToken: return "I don't have a refresh token, not trying to refresh" case .noRegistrationURL: return "No registration URL defined" case .notUsingTLS: return "You MUST use HTTPS/SSL/TLS" case .unableToOpenAuthorizeURL: return "Cannot open authorize URL" case .invalidRequest: return "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed." case .requestCancelled: return "The request has been cancelled" case .noTokenType: return "No token type received, will not use the token" case .unsupportedTokenType(let message): return message case .noDataInResponse: return "No data in the response" case .prerequisiteFailed(let message): return message case .missingState: return "The state parameter was missing in the response" case .invalidState: return "The state parameter did not check out" case .jsonParserError: return "Error parsing JSON" case .utf8EncodeError: return "Failed to UTF-8 encode the given string" case .utf8DecodeError: return "Failed to decode given data as a UTF-8 string" case .unauthorizedClient: return "The client is not authorized to request an access token using this method." case .forbidden: return "Forbidden" case .wrongUsernamePassword: return "The username or password is incorrect" case .accessDenied: return "The resource owner or authorization server denied the request." case .unsupportedResponseType: return "The authorization server does not support obtaining an access token using this method." case .invalidScope: return "The requested scope is invalid, unknown, or malformed." case .serverError: return "The authorization server encountered an unexpected condition that prevented it from fulfilling the request." case .temporarilyUnavailable: return "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server." case .responseError(let message): return message } } // MARK: - Equatable public static func ==(lhs: OAuth2Error, rhs: OAuth2Error) -> Bool { switch (lhs, rhs) { case (.generic(let lhm), .generic(let rhm)): return lhm == rhm case (.nsError(let lhe), .nsError(let rhe)): return lhe.isEqual(rhe) case (.invalidURLComponents(let lhe), .invalidURLComponents(let rhe)): return (lhe == rhe) case (.noClientId, .noClientId): return true case (.noClientSecret, .noClientSecret): return true case (.noRedirectURL, .noRedirectURL): return true case (.noUsername, .noUsername): return true case (.noPassword, .noPassword): return true case (.alreadyAuthorizing, .alreadyAuthorizing): return true case (.noAuthorizationContext, .noAuthorizationContext): return true case (.invalidAuthorizationContext, .invalidAuthorizationContext): return true case (.invalidRedirectURL(let lhu), .invalidRedirectURL(let rhu)): return lhu == rhu case (.noRefreshToken, .noRefreshToken): return true case (.notUsingTLS, .notUsingTLS): return true case (.unableToOpenAuthorizeURL, .unableToOpenAuthorizeURL): return true case (.invalidRequest, .invalidRequest): return true case (.requestCancelled, .requestCancelled): return true case (.noTokenType, .noTokenType): return true case (.unsupportedTokenType(let lhm), .unsupportedTokenType(let rhm)): return lhm == rhm case (.noDataInResponse, .noDataInResponse): return true case (.prerequisiteFailed(let lhm), .prerequisiteFailed(let rhm)): return lhm == rhm case (.missingState, .missingState): return true case (.invalidState, .invalidState): return true case (.jsonParserError, .jsonParserError): return true case (.utf8EncodeError, .utf8EncodeError): return true case (.utf8DecodeError, .utf8DecodeError): return true case (.unauthorizedClient, .unauthorizedClient): return true case (.forbidden, .forbidden): return true case (.wrongUsernamePassword, .wrongUsernamePassword): return true case (.accessDenied, .accessDenied): return true case (.unsupportedResponseType, .unsupportedResponseType): return true case (.invalidScope, .invalidScope): return true case (.serverError, .serverError): return true case (.temporarilyUnavailable, .temporarilyUnavailable): return true case (.responseError(let lhm), .responseError(let rhm)): return lhm == rhm default: return false } } } public extension Error { /** Convenience getter to easily retrieve an OAuth2Error from any Error. */ public var asOAuth2Error: OAuth2Error { if let oaerror = self as? OAuth2Error { return oaerror } return OAuth2Error.nsError(self as NSError) } }
mit
e37b3793684e7cb218b496924f8a4fa2
31.739938
157
0.698818
4.264113
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Music/Tools/MGMusicOperationTool.swift
1
4446
// // MGMusicOperationTool.swift // MGDS_Swift // // Created by i-Techsys.com on 17/3/2. // Copyright © 2017年 i-Techsys. All rights reserved. // http://music.baidu.com/data/music/links?songIds=276867440 import UIKit class MGMusicOperationTool: NSObject { static let share = MGMusicOperationTool() /** 存放的播放列表 */ lazy var musicMs = [SongDetail]() /** 播放音乐的工具 */ fileprivate var audioTool = MGAudioTool() /** 单个播放器的player */ var currentPlayer: AVAudioPlayer? fileprivate var message : MGMessageModel = MGMessageModel() var currentMusic: OneSong? /** 记录当前音乐播放的下标 */ var currentIndex: Int = 0 { didSet { let count = self.musicMs.count if (currentIndex < 0) { currentIndex = count - 1; }else if (currentIndex > count - 1){ currentIndex = 0; } } } /** 代理 */ weak var delegate: AVAudioPlayerDelegate? { didSet { self.audioTool.delegate = delegate } } override init() { super.init() } func getMusicMessageM() -> MGMessageModel{ if musicMs.count == 0 { // || currentMusic == nil return message } // 获取当前歌曲播放时间和总时长 message.costTime = self.currentPlayer!.currentTime message.totalTime = self.currentPlayer!.duration message.isPlaying = self.currentPlayer!.isPlaying // message.musicM = musicMs[currentIndex] message.musicM = self.currentMusic return message } // 根据模型播放音乐 func playWithMusicName(musicM: SongDetail,index: Int){ let parameters: [String: Any] = ["songIds": self.musicMs[index].song_id] NetWorkTools.requestData(type: .get, urlString: "http://ting.baidu.com/data/music/links", parameters: parameters, succeed: { (result, err) in guard let resultDict = result as? [String : Any] else { return } // 2.根据data该key,获取数组 guard let resultDictArray = resultDict["data"] as? [String : Any] else { return } guard let dataArray = resultDictArray["songList"] as? [[String : Any]] else { return } self.currentMusic = OneSong(dict: dataArray.first!) self.currentIndex = self.musicMs.index(of: musicM)! self.getOneMusic(urlStr: self.currentMusic!.songLink) self.getMusicMessageM().musicM = self.currentMusic }) { (err) in } } func getOneMusic(urlStr: String) { NetWorkTools.share.downloadMusicData(type: .get, urlString: urlStr) { (filePath) in // "/Users/ZBKF001/Library/Developer/CoreSimulator/Devices/A4E38A94-59E6-455E-A92C-8340FF650EA8/data/Containers/Data/Application/62473072-48F5-4F11-837E-5C558F68A4C5/Documents/刚好遇见你.mp3" // 根据资源路径, 创建播放器对象 self.currentPlayer = self.audioTool.playAudioWith(urlStr: filePath) } } /** * 暂停当前正在播放的音乐 */ func pauseCurrentMusic(){ self.audioTool.pauseAudio() } /** * 继续播放当前的音乐 */ func playCurrentMusic() { let model = self.musicMs[self.currentIndex]; self.playWithMusicName(musicM: model,index: currentIndex) } /** * 播放下一首音乐 */ func playNexttMusic() { self.currentIndex += 1 let model = self.musicMs[self.currentIndex]; self.playWithMusicName(musicM: model,index: currentIndex) } /** * 播放上一首音乐 */ func playPreMusic() { self.currentIndex -= 1 let model = self.musicMs[self.currentIndex]; self.playWithMusicName(musicM: model,index: currentIndex) } /** * 根据时间播放 */ func seekToTimeInterval(currentTime: TimeInterval){ self.audioTool.seekToTimeInterval(currentTime: currentTime) } } class MGMessageModel: NSObject { /** 当前正在播放的音乐数据模型 */ var musicM: OneSong! /** 当前播放的时长 */ var costTime: Double = 0.0 /** 当前播放总时长 */ var totalTime: Double = 0.0 /** 当前的播放状态 */ var isPlaying: Bool = false }
mit
9a2fbcbd59a7cb1e8a8dcd605769fb5f
28.119718
198
0.596372
3.897267
false
false
false
false
chrisbudro/GrowlerHour
growlers/NearbyBrowseViewController.swift
1
2585
// // NearbyBrowseViewController.swift // growlers // // Created by Chris Budro on 10/3/15. // Copyright © 2015 chrisbudro. All rights reserved. // import UIKit class NearbyBrowseViewController: UITableViewController { var queryManager = GenericQueryManager(type: .Retailer) var retailerList = [Retailer]() let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: kTapNibName, bundle: nil), forCellReuseIdentifier: kTapCellReuseIdentifier) tableView.estimatedRowHeight = kEstimatedCellHeight tableView.rowHeight = UITableViewAutomaticDimension updateRetailerList() } func updateRetailerList() { retailerList = [] tableView.reloadData() activityIndicator.center = tableView.center tableView.addSubview(activityIndicator) activityIndicator.startAnimating() queryManager.results { (results, error) in if let error = error { let alert = ErrorAlertController.alertControllerWithError(error) self.presentViewController(alert, animated: true, completion: nil) } else if let results = results as? [Retailer] { self.retailerList = results self.tableView.reloadData() } self.activityIndicator.stopAnimating() } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return retailerList.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let retailer = retailerList[section] // return retailer.taps.count return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(kTapCellReuseIdentifier, forIndexPath: indexPath) as! BeerViewCell // let retailer = retailerList[indexPath.section] // let tap = retailer.taps[indexPath.row] // if tap.isDataAvailable() { // cell.configureCellForObject(tap) // } else { // tap.fetchIfNeededInBackgroundWithBlock { (tap, error) in // if let error = error { // } else if let tap = tap as? Tap { // cell.configureCellForObject(tap) // } // } // } return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let retailer = retailerList[section] return retailer.retailerName } }
mit
13fee1810dbf4660aa20e4b128c23ffd
29.4
125
0.703173
4.66426
false
false
false
false
liuxianghong/GreenBaby
工程/greenbaby/greenbaby/View/ForumThreadsDetailHeadTableViewCell.swift
1
4671
// // ForumThreadsDetailHeadTableViewCell.swift // greenbaby // // Created by 刘向宏 on 15/12/17. // Copyright © 2015年 刘向宏. All rights reserved. // import UIKit class ForumThreadsDetailHeadTableViewCell: UITableViewCell, UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { @IBOutlet weak var headImageView : UIImageView! @IBOutlet weak var nameLabel : UILabel! @IBOutlet weak var addressLabel : UILabel! @IBOutlet weak var timeLabel : UILabel! @IBOutlet weak var titleLabel : UILabel! @IBOutlet weak var goodButton : UIButton! @IBOutlet weak var commentButton : UIButton! @IBOutlet weak var collectionView : UICollectionView! @IBOutlet weak var collectionViewConstraint : NSLayoutConstraint! var imageArray : NSArray = NSArray() var dataDic : NSDictionary! { willSet{ guard let value = newValue else{ return } if value.count > 0{ self.nameLabel.text = value["posterName"] as? String self.titleLabel.text = value["title"] as? String //self.addressLabel.text = value["title"] as? String self.commentButton.setTitle("\(value["commentCount"] as! Int)", forState: .Normal) self.goodButton.setTitle("\(value["praiseCount"] as! Int)", forState: .Normal) if value["posterHeadImage"] != nil{ let url = NSURL(string: (value["posterHeadImage"] as! String).toResourceSeeURL()) self.headImageView.sd_setImageWithURL(url, placeholderImage: nil) } self.addressLabel.text = value["posterLocation"] as? String let time = value["postTime"] as! NSTimeInterval let timeDate = NSDate(timeIntervalSince1970: time/1000) let format = NSDateFormatter() format.dateFormat = "yyyy-MM-dd" timeLabel.text = format.stringFromDate(timeDate) imageArray = value["threadImages"] as! NSArray if imageArray.count == 0 { collectionViewConstraint.constant = 0 } else if imageArray.count == 1{ collectionViewConstraint.constant = (UIScreen.mainScreen().bounds.size.width - 10 - 10 - 15)/2+10 } else { collectionViewConstraint.constant = (UIScreen.mainScreen().bounds.size.width - 10 - 10 - 20)/3+10 } collectionView.reloadData() } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code self.collectionView.backgroundColor = UIColor.whiteColor() headImageView.layer.cornerRadius = 21; headImageView.layer.masksToBounds = true; } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageArray.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{ return 1 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! ImageCollectionViewCell let url = NSURL(string: (imageArray[indexPath.row] as! String).toResourceSeeURL()) cell.imageView.sd_setImageWithURL(url, placeholderImage: nil) cell.setNeedsLayout() cell.layoutIfNeeded() return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print(indexPath) } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let height = collectionView.frame.size.height - 15 return CGSize(width: height, height: height) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 5, 5, 5) } }
lgpl-3.0
721c86ad0f85d5ced572c7aec1945af0
39.842105
169
0.642182
5.562724
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Period Stats/Countries/Map/CountriesMapView.swift
2
2569
import FSInteractiveMap import WordPressShared class CountriesMapView: UIView, NibLoadable { private var map = FSInteractiveMapView(frame: CGRect(x: 0, y: 0, width: 335, height: 224)) private var countries: CountriesMap? private lazy var colors: [UIColor] = { return mapColors() }() @IBOutlet private var minViewsCountLabel: UILabel! { didSet { decorate(minViewsCountLabel) } } @IBOutlet private var maxViewsCountLabel: UILabel! { didSet { decorate(maxViewsCountLabel) } } @IBOutlet private var gradientView: GradientView! { didSet { setGradientColors() } } @IBOutlet private var mapContainer: UIView! { didSet { setBasicMapColors() map.loadMap("world-map", withData: [:], colorAxis: colors) mapContainer.addSubview(map) } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .listForeground map.backgroundColor = .listForeground colors = mapColors() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) colors = mapColors() setGradientColors() setBasicMapColors() gradientView.layoutIfNeeded() if let countries = countries { setData(countries) } } func setData(_ countries: CountriesMap) { self.countries = countries map.frame = mapContainer.bounds map.setData(countries.data, colorAxis: colors) minViewsCountLabel.text = String(countries.minViewsCount.abbreviatedString()) maxViewsCountLabel.text = String(countries.maxViewsCount.abbreviatedString()) } } private extension CountriesMapView { func decorate(_ label: UILabel) { label.font = WPStyleGuide.fontForTextStyle(.footnote) label.textColor = .neutral(.shade70) } func mapColors() -> [UIColor] { if #available(iOS 13, *) { if traitCollection.userInterfaceStyle == .dark { return [.primary(.shade90), .primary] } } return [.primary(.shade5), .primary] } func setGradientColors() { gradientView.fromColor = colors.first ?? .white gradientView.toColor = colors.last ?? .black } func setBasicMapColors() { map.strokeColor = .listForeground map.fillColor = WPStyleGuide.Stats.mapBackground } }
gpl-2.0
348651c493bf7dc7d025202fb479c228
28.528736
94
0.626703
4.969052
false
false
false
false
suzuki-0000/SKPhotoBrowser
SKPhotoBrowser/SKPaginationView.swift
1
5774
// // SKPaginationView.swift // SKPhotoBrowser // // Created by keishi_suzuki on 2017/12/20. // Copyright © 2017年 suzuki_keishi. All rights reserved. // import UIKit class SKPaginationView: UIView { var counterLabel: UILabel? var prevButton: UIButton? var nextButton: UIButton? private var margin: CGFloat = 100 private var extraMargin: CGFloat = SKMesurement.isPhoneX ? 40 : 0 fileprivate weak var browser: SKPhotoBrowser? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, browser: SKPhotoBrowser?) { self.init(frame: frame) self.frame = CGRect(x: 0, y: frame.height - margin - extraMargin, width: frame.width, height: 100) self.browser = browser setupApperance() setupCounterLabel() setupPrevButton() setupNextButton() update(browser?.currentPageIndex ?? 0) } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if let view = super.hitTest(point, with: event) { if let counterLabel = counterLabel, counterLabel.frame.contains(point) { return view } else if let prevButton = prevButton, prevButton.frame.contains(point) { return view } else if let nextButton = nextButton, nextButton.frame.contains(point) { return view } return nil } return nil } func updateFrame(frame: CGRect) { self.frame = CGRect(x: 0, y: frame.height - margin, width: frame.width, height: 100) } func update(_ currentPageIndex: Int) { guard let browser = browser else { return } if browser.photos.count > 1 { counterLabel?.text = "\(currentPageIndex + 1) / \(browser.photos.count)" } else { counterLabel?.text = nil } guard let prevButton = prevButton, let nextButton = nextButton else { return } prevButton.isEnabled = (currentPageIndex > 0) nextButton.isEnabled = (currentPageIndex < browser.photos.count - 1) } func setControlsHidden(hidden: Bool) { let alpha: CGFloat = hidden ? 0.0 : 1.0 UIView.animate(withDuration: 0.35, animations: { () -> Void in self.alpha = alpha }, completion: nil) } } private extension SKPaginationView { func setupApperance() { backgroundColor = .clear clipsToBounds = true } func setupCounterLabel() { guard SKPhotoBrowserOptions.displayCounterLabel else { return } let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) label.center = CGPoint(x: frame.width / 2, y: frame.height / 2) label.textAlignment = .center label.backgroundColor = .clear label.shadowColor = SKToolbarOptions.textShadowColor label.shadowOffset = CGSize(width: 0.0, height: 1.0) label.font = SKToolbarOptions.font label.textColor = SKToolbarOptions.textColor label.translatesAutoresizingMaskIntoConstraints = true label.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] addSubview(label) counterLabel = label } func setupPrevButton() { guard SKPhotoBrowserOptions.displayBackAndForwardButton else { return } guard browser?.photos.count ?? 0 > 1 else { return } let button = SKPrevButton(frame: frame) button.center = CGPoint(x: frame.width / 2 - 100, y: frame.height / 2) button.addTarget(browser, action: #selector(SKPhotoBrowser.gotoPreviousPage), for: .touchUpInside) addSubview(button) prevButton = button } func setupNextButton() { guard SKPhotoBrowserOptions.displayBackAndForwardButton else { return } guard browser?.photos.count ?? 0 > 1 else { return } let button = SKNextButton(frame: frame) button.center = CGPoint(x: frame.width / 2 + 100, y: frame.height / 2) button.addTarget(browser, action: #selector(SKPhotoBrowser.gotoNextPage), for: .touchUpInside) addSubview(button) nextButton = button } } class SKPaginationButton: UIButton { let insets: UIEdgeInsets = UIEdgeInsets(top: 13.25, left: 17.25, bottom: 13.25, right: 17.25) func setup(_ imageName: String) { backgroundColor = .clear imageEdgeInsets = insets translatesAutoresizingMaskIntoConstraints = true autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] contentMode = .center setImage(UIImage.bundledImage(named: imageName), for: .normal) } } class SKPrevButton: SKPaginationButton { let imageName = "btn_common_back_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) setup(imageName) } } class SKNextButton: SKPaginationButton { let imageName = "btn_common_forward_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) setup(imageName) } }
mit
d47a80d2bcd3071d4d754500c06fd147
32.947059
106
0.605094
4.680454
false
false
false
false
glessard/async-deferred
Tests/deferredTests/DeferredDelayTests.swift
3
2421
// // DeferredDelayTests.swift // deferredTests // // Created by Guillaume Lessard // Copyright © 2017-2020 Guillaume Lessard. All rights reserved. // import XCTest import Foundation import Dispatch import deferred class DelayTests: XCTestCase { func testDelayValue() { let t1 = 0.05 let d1 = Deferred<Date, Never>(value: Date()).delay(seconds: t1).map { Date().timeIntervalSince($0) } XCTAssertGreaterThan(d1.value!, t1) } func testDelayError() { let d1 = Deferred<Date, Cancellation>(value: Date()).delay(until: .distantFuture) let d2 = d1.delay(seconds: 0.05) d1.cancel() XCTAssertEqual(d2.value, nil) } func testCancelDelay() { let d0 = Deferred<Date, Cancellation>(value: Date()) let d1 = d0.delay(until: .now() + 0.1) let e1 = expectation(description: #function) XCTAssertEqual(d1.state, .waiting) d1.onError { _ in e1.fulfill() } XCTAssertEqual(d1.state, .executing) d1.cancel() XCTAssertEqual(d1.error, .canceled("")) waitForExpectations(timeout: 0.1) } func testSourceSlowerThanDelay() { let d1 = Deferred<Int, Never>(value: nzRandom()).delay(.milliseconds(100)) let d2 = d1.delay(until: .now() + .microseconds(100)) XCTAssertEqual(d1.value, d2.value) XCTAssertNotNil(d2.value) } func testDelayToThePast() { let d1 = Deferred<Int, Never>(value: nzRandom()) let d2 = d1.delay(until: .now() - 1.0) XCTAssertEqual(d1.value, d2.value) XCTAssertEqual(ObjectIdentifier(d1), ObjectIdentifier(d2)) } func testDistantFutureDelay() { let d1 = Deferred<Date, Never>(value: Date()) let d2 = d1.delay(until: .distantFuture) XCTAssertEqual(d1.state, .resolved) XCTAssertEqual(d2.state, .waiting) d2.onValue { _ in fatalError(#function) } XCTAssertEqual(d2.state, .executing) } func testDelayedDemand() { let delay = 0.01 let d1 = Deferred<Date, Never>(task: { $0.resolve(value: Date()) }).delayingDemand(seconds: delay) let t1 = Date() let t2 = d1.get() XCTAssertGreaterThanOrEqual(t2.timeIntervalSince(t1), delay) let t3 = Date() let d2 = Deferred<Date, Never>(task: { $0.resolve(value: Date()) }).delayingDemand(.seconds(-1)) let d3 = d2.map { $0.timeIntervalSince(t3) } let t4 = d3.get() XCTAssertGreaterThanOrEqual(t4, 0) XCTAssertLessThanOrEqual(t4, delay) // this is not a robust assertion. } }
mit
487852ad151828f6e2ff20f2c78ec18c
25.888889
105
0.66405
3.403657
false
true
false
false
pvzig/SlackKit
SKServer/Sources/Titan/TitanRouter/TitanRoutingExtension.swift
2
4041
// Copyright 2017 Enervolution GmbH // // 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. extension Titan { /// Core routing handler for Titan Routing. /// Passing `nil` for the method results in matching all methods for a given path /// Path matching is defined in `matchRoute` method, documented in `docs/Routes.md` public func route(method: HTTPMethod? = nil, path: String, handler: @escaping TitanFunc) { let routeFunction: TitanFunc = { (req, res) in if let m = method, m != req.method { return (req, res) } guard matchRoute(path: req.path.prefixUpToQuery(), route: path) else { return (req, res) } return handler(req, res) } addFunction(routeFunction) } public func route(_ method: HTTPMethod?, _ path: String, _ handler: @escaping TitanFunc) { self.route(method: method, path: path, handler: handler) } /// Synonym for `route` public func addFunction(path: String, handler: @escaping TitanFunc) { route(path: path, handler: handler) } public func addFunction(_ path: String, _ handler: @escaping TitanFunc) { self.addFunction(path: path, handler: handler) } /// Synonym for `route` public func allMethods(path: String, handler: @escaping TitanFunc) { route(path: path, handler: handler) } public func allMethods(_ path: String, _ handler: @escaping TitanFunc) { self.allMethods(path: path, handler: handler) } } /// Match a given path with a route. Segments containing an asterisk are treated as wild. /// Assuming querystring has already been stripped, including the question mark private func matchRoute(path: String, route: String) -> Bool { guard !route.contains(where: { (char) -> Bool in return char == "*" }) else { return true } // If it's a wildcard, bail out – I hope the branch predictor's okay with this! guard route.parameters != 0 else { return path == route // If there are no wildcards, this is easy } // PARAMETERS LOGIC let splitPath = path.splitOnSlashes() // /foo/bar/baz -> [foo, bar, baz] let splitRoute = route.splitOnSlashes() // /foo/{id}/baz -> [foo, {id}, baz] guard splitRoute.count == splitPath.count else { // if the number of route segments != path segments, then it can't be a match return false } let zipped = zip(splitPath, splitRoute) // produce [(foo, foo), (bar, *), (baz, baz)] for (pathSegment, routeSegment) in zipped { // If the route segment does not equal the path segment, and the route segment is not a wildcard, then it does not match if (routeSegment != pathSegment) && (!routeSegment.hasPrefix("{") && !routeSegment.hasPrefix("}") ) { return false } else { continue } } return true } extension String { /// Separate a string into an array of strings, separated by "/" characters func splitOnSlashes() -> [String] { return self.split(separator: "/").map { String($0) } } var parameters: Int { return self.splitOnSlashes().filter { (value) -> Bool in return value.hasPrefix("{") && value.hasSuffix("}") }.count } /// Return `Self` without the query string. func prefixUpToQuery() -> String { return self.firstIndex(of: "?") .map { self.prefix(upTo: $0) } .map(String.init) ?? self } }
mit
1c116d7586a84a78757b54a1bf994339
34.743363
130
0.629859
4.134084
false
false
false
false
DevaLee/LYCSwiftDemo
LYCSwiftDemo/Classes/Component/HYPageView/HYTitleView.swift
1
11441
// // HYTitleView.swift // HYContentPageView // // Created by xiaomage on 2016/10/27. // Copyright © 2016年 seemygo. All rights reserved. // import UIKit // MARK:- 定义协议 protocol HYTitleViewDelegate : class { func titleView(_ titleView : HYTitleView, selectedIndex index : Int) } class HYTitleView: UIView { // MARK: 对外属性 weak var delegate : HYTitleViewDelegate? // MARK: 定义属性 fileprivate var titles : [String]! fileprivate var style : HYTitleStyle! fileprivate var currentIndex : Int = 0 // MARK: 存储属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() // MARK: 控件属性 fileprivate lazy var scrollView : UIScrollView = { let scrollV = UIScrollView() scrollV.frame = self.bounds scrollV.showsHorizontalScrollIndicator = false scrollV.scrollsToTop = false return scrollV }() fileprivate lazy var splitLineView : UIView = { let splitView = UIView() splitView.backgroundColor = UIColor.lightGray let h : CGFloat = 0.5 splitView.frame = CGRect(x: 0, y: self.frame.height - h, width: self.frame.width, height: h) return splitView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverBgColor coverView.alpha = 0.7 return coverView }() // MARK: 计算属性 fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor) fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectedColor) // MARK: 自定义构造函数 init(frame: CGRect, titles : [String], style : HYTitleStyle) { super.init(frame: frame) self.titles = titles self.style = style setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面内容 extension HYTitleView { fileprivate func setupUI() { // 1.添加Scrollview addSubview(scrollView) // 2.添加底部分割线 addSubview(splitLineView) // 3.设置所有的标题Label setupTitleLabels() // 4.设置Label的位置 setupTitleLabelsPosition() // 5.设置底部的滚动条 if style.isShowBottomLine { setupBottomLine() } // 6.设置遮盖的View if style.isShowCover { setupCoverView() } } fileprivate func setupTitleLabels() { for (index, title) in titles.enumerated() { let label = UILabel() label.tag = index label.text = title label.textColor = index == 0 ? style.selectedColor : style.normalColor label.font = style.font label.textAlignment = .center label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_ :))) label.addGestureRecognizer(tapGes) titleLabels.append(label) scrollView.addSubview(label) } } fileprivate func setupTitleLabelsPosition() { var titleX: CGFloat = 0.0 var titleW: CGFloat = 0.0 let titleY: CGFloat = 0.0 let titleH : CGFloat = frame.height let count = titles.count for (index, label) in titleLabels.enumerated() { if style.isScrollEnable { let rect = (label.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : style.font], context: nil) titleW = rect.width if index == 0 { titleX = style.titleMargin * 0.5 } else { let preLabel = titleLabels[index - 1] titleX = preLabel.frame.maxX + style.titleMargin } } else { titleW = frame.width / CGFloat(count) titleX = titleW * CGFloat(index) } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) // 放大的代码 if index == 0 { let scale = style.isNeedScale ? style.scaleRange : 1.0 label.transform = CGAffineTransform(scaleX: scale, y: scale) } } if style.isScrollEnable { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: 0) } } fileprivate func setupBottomLine() { scrollView.addSubview(bottomLine) bottomLine.frame = titleLabels.first!.frame bottomLine.frame.size.height = style.bottomLineH bottomLine.frame.origin.y = bounds.height - style.bottomLineH } fileprivate func setupCoverView() { scrollView.insertSubview(coverView, at: 0) let firstLabel = titleLabels[0] var coverW = firstLabel.frame.width let coverH = style.coverH var coverX = firstLabel.frame.origin.x let coverY = (bounds.height - coverH) * 0.5 if style.isScrollEnable { coverX -= style.coverMargin coverW += style.coverMargin * 2 } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverRadius coverView.layer.masksToBounds = true } } // MARK:- 事件处理 extension HYTitleView { @objc fileprivate func titleLabelClick(_ tap : UITapGestureRecognizer) { // 0.获取当前Label guard let currentLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = style.selectedColor oldLabel.textColor = style.normalColor // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.通知代理 delegate?.titleView(self, selectedIndex: currentIndex) // 6.居中显示 contentViewDidEndScroll() // 7.调整bottomLine if style.isShowBottomLine { UIView.animate(withDuration: 0.15, animations: { self.bottomLine.frame.origin.x = currentLabel.frame.origin.x self.bottomLine.frame.size.width = currentLabel.frame.size.width }) } // 8.调整比例 if style.isNeedScale { oldLabel.transform = CGAffineTransform.identity currentLabel.transform = CGAffineTransform(scaleX: style.scaleRange, y: style.scaleRange) } // 9.遮盖移动 if style.isShowCover { let coverX = style.isScrollEnable ? (currentLabel.frame.origin.x - style.coverMargin) : currentLabel.frame.origin.x let coverW = style.isScrollEnable ? (currentLabel.frame.width + style.coverMargin * 2) : currentLabel.frame.width UIView.animate(withDuration: 0.15, animations: { self.coverView.frame.origin.x = coverX self.coverView.frame.size.width = coverW }) } } } // MARK:- 获取RGB的值 extension HYTitleView { fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) { guard let components = color.cgColor.components else { fatalError("请使用RGB方式给Title赋值颜色") } return (components[0] * 255, components[1] * 255, components[2] * 255) } } // MARK:- 对外暴露的方法 extension HYTitleView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isShowBottomLine { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } // 6.放大的比例 if style.isNeedScale { let scaleDelta = (style.scaleRange - 1.0) * progress sourceLabel.transform = CGAffineTransform(scaleX: style.scaleRange - scaleDelta, y: style.scaleRange - scaleDelta) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta) } // 7.计算cover的滚动 if style.isShowCover { coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress) coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress) } } func contentViewDidEndScroll() { // 0.如果是不需要滚动,则不需要调整中间位置 guard style.isScrollEnable else { return } // 1.获取获取目标的Label let targetLabel = titleLabels[currentIndex] // 2.计算和中间位置的偏移量 var offSetX = targetLabel.center.x - bounds.width * 0.5 if offSetX < 0 { offSetX = 0 } let maxOffset = scrollView.contentSize.width - bounds.width if offSetX > maxOffset { offSetX = maxOffset } // 3.滚动UIScrollView scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
mit
3c35b86ea62bc1ff33c73b8d3b024860
33.344828
214
0.594012
4.788462
false
false
false
false
ainame/Swift-WebP
Sources/WebP/WebPDecoder+Platform.swift
1
2336
import Foundation import CWebP #if os(macOS) || os(iOS) import CoreGraphics extension WebPDecoder { public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage { let feature = try WebPImageInspector.inspect(webPData) let height: Int = options.useScaling ? options.scaledHeight : feature.height let width: Int = options.useScaling ? options.scaledWidth : feature.width let decodedData: CFData = try decode(byRGBA: webPData, options: options) as CFData guard let provider = CGDataProvider(data: decodedData) else { throw WebPError.unexpectedError(withMessage: "Couldn't initialize CGDataProvider") } let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue) let colorSpace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent let bytesPerPixel = 4 if let cgImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8 * bytesPerPixel, bytesPerRow: bytesPerPixel * width, space: colorSpace, bitmapInfo: bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false, intent: renderingIntent) { return cgImage } throw WebPError.unexpectedError(withMessage: "Couldn't initialize CGImage") } } #endif #if os(iOS) import UIKit extension WebPDecoder { public func decode(toUImage webPData: Data, options: WebPDecoderOptions) throws -> UIImage { let cgImage: CGImage = try decode(webPData, options: options) return UIImage(cgImage: cgImage) } } #endif #if os(macOS) import AppKit extension WebPDecoder { public func decode(toNSImage webPData: Data, options: WebPDecoderOptions) throws -> NSImage { let cgImage: CGImage = try decode(webPData, options: options) return NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height)) } } #endif
mit
ba835d9ae324a8a6bbba0a787c0ca654
36.677419
131
0.618579
5.067245
false
false
false
false
alusev/EGFormValidator
EGFormValidatorTests/ValidatorMaxlengthTests.swift
1
1417
// // ValidatorMaxlengthTests.swift // EGFormValidator // // Created by Evgeny Gushchin on 02/01/17. // Copyright © 2017 Evgeny Gushchin. All rights reserved. // import XCTest @testable import EGFormValidator class ValidatorMaxlengthTests: XCTestCase { var textField: UITextField! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. textField = UITextField() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDefaultValue() { XCTAssertEqual(Int.max, textField.maxLength, "Default value is too short") } func testMaxlength() { textField.maxLength = 5 textField.text = "qwe" textField.limitLength(textField: textField) XCTAssertEqual(textField.text?.count, 3) textField.text = "qwert" textField.limitLength(textField: textField) XCTAssertEqual(textField.text?.count, 5) textField.text = "qwerty" textField.limitLength(textField: textField) XCTAssertEqual(textField.text?.count, 5) // test getter textField.maxLength = 15 textField.limitLength(textField: textField) XCTAssertEqual(textField.maxLength, 15) } }
mit
4f75cd189c662a1dce09ca29d3e20bfb
27.32
111
0.666667
4.481013
false
true
false
false
material-motion/material-motion-swift
examples/TossableExample.swift
1
1416
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialMotion class TossableExampleViewController: ExampleViewController { var runtime: MotionRuntime! override func viewDidLoad() { super.viewDidLoad() let square = center(createExampleSquareView(), within: view) view.addSubview(square) runtime = MotionRuntime(containerView: view) let tossable = Tossable() tossable.spring.destination.value = .init(x: view.bounds.midX, y: view.bounds.midY) tossable.spring.damping.value /= 2 runtime.add(tossable, to: square) runtime.whenAllAtRest([tossable]) { print("Is now at rest") } } override func exampleInformation() -> ExampleInfo { return .init(title: type(of: self).catalogBreadcrumbs().last!, instructions: "Use two fingers to rotate the view.") } }
apache-2.0
674e9bbbf730c882d7b69f849aa65961
29.782609
87
0.733051
4.252252
false
false
false
false
kevinvanderlugt/Exercism-Solutions
swift/phone-number/PhoneNumber.swift
1
1360
import Foundation private let invalidNumberResponse = "0000000000" struct PhoneNumber { var startingNumber: String func number() -> String { return sanitizedPhoneNumber(startingNumber) } func areaCode() -> String { return sanitizedPhoneNumber(startingNumber)[0..<3] } func description() -> String { let phoneNumber = sanitizedPhoneNumber(startingNumber) return "(\(areaCode())) \(phoneNumber[3..<6])-\(phoneNumber[6..<10])" } private func sanitizedPhoneNumber(phoneNumber: String) -> String { let allowedCharacterSet = NSCharacterSet.decimalDigitCharacterSet() let components = phoneNumber.componentsSeparatedByCharactersInSet(allowedCharacterSet.invertedSet) let sanitizedNumber = join("", components) switch countElements(sanitizedNumber) { case 10: return sanitizedNumber case 11: return sanitizedNumber[0] == "1" ? dropFirst(sanitizedNumber) : invalidNumberResponse default: return invalidNumberResponse } } } extension String { subscript (i: Int) -> Character { return self[advance(self.startIndex, i)] } subscript (r: Range<Int>) -> String { return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex))) } }
mit
fd0b1972f3f08d0f84d6c20dfc56b799
32.195122
120
0.670588
5.151515
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Rank/Views/RanksCell.swift
1
2166
// // RanksCell.swift // MusicApp // // Created by Hưng Đỗ on 6/22/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import Kingfisher class RanksCell: UITableViewCell { @IBOutlet weak var rankLabel: UILabel! @IBOutlet weak var rankImageView: UIImageView! @IBOutlet weak var firstItemLabel: UILabel! @IBOutlet weak var secondItemLabel: UILabel! @IBOutlet weak var thirdItemLabel: UILabel! @IBOutlet weak var fourthItemLabel: UILabel! @IBOutlet weak var containerView: UIView! @IBOutlet weak var firstIcon: UIView! @IBOutlet weak var secondIcon: UIView! @IBOutlet weak var thirdIcon: UIView! @IBOutlet weak var fourthIcon: UIView! override func awakeFromNib() { super.awakeFromNib() containerView.layer.cornerRadius = 7 firstIcon.layer.cornerRadius = 5 secondIcon.layer.cornerRadius = 5 thirdIcon.layer.cornerRadius = 5 fourthIcon.layer.cornerRadius = 5 } override func prepareForReuse() { rankLabel.text = "" rankImageView.image = nil firstItemLabel.text = "" secondItemLabel.text = "" thirdItemLabel.text = "" fourthItemLabel.text = "" } var rank: String = "" { didSet { rankLabel.text = rank } } var rankImage: String = "" { didSet { if let image = UIImage(named: rankImage) { rankImageView.image = image return } let imageURL = URL(string: rankImage) rankImageView.kf.setImage(with: imageURL) } } var firstItem: String = "" { didSet { firstItemLabel.text = firstItem } } var secondItem: String = "" { didSet { secondItemLabel.text = secondItem } } var thirdItem: String = "" { didSet { thirdItemLabel.text = thirdItem } } var fourthItem: String = "" { didSet { fourthItemLabel.text = fourthItem } } }
mit
7550d5de5261011024d124101e787622
22.747253
54
0.564091
4.728665
false
false
false
false
JuanjoArreola/YouTubePlayer
YouTubePlayer/YouTubeVideoPlayerController.swift
1
2166
// // YouTubeVideoPlayerController.swift // YouTubePlayer // // Created by Juan Jose Arreola Simon on 4/28/16. // Copyright © 2016 juanjo. All rights reserved. // import Foundation import MediaPlayer import AVKit protocol YouTubeVideoPlayerControllerDelegate: class { func youTubeVideoPlayerController(_ controller: YouTubeVideoPlayerController, didFailWithError: Error) } open class YouTubeVideoPlayerController: AVPlayerViewController { weak var youtubeDelegate: YouTubeVideoPlayerController? var request: YouTubeInfoRequest? var previousStatusBarStyle = UIApplication.shared.statusBarStyle open var preferredQualities = [VideoQuality.liveStreaming, VideoQuality.hd_720, VideoQuality.medium_360, VideoQuality.small_240] open var youTubeVideo: YouTubeVideo? public required convenience init(youTubeVideo: YouTubeVideo) throws { self.init() try setYouTubeVideo(youTubeVideo) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if previousStatusBarStyle == .lightContent { UIApplication.shared.setStatusBarStyle(.default, animated: animated) } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if previousStatusBarStyle == .lightContent { UIApplication.shared.setStatusBarStyle(previousStatusBarStyle, animated: animated) } } open func setYouTubeVideo(_ video: YouTubeVideo) throws { self.youTubeVideo = video for quality in preferredQualities { if let url = video.streamURLs[quality] { self.player = AVPlayer(url: url) return } } throw YouTubeError.invalidQuality } open func play() { self.player?.play() } }
mit
114826c427139c46f3d57fe9fc4a856b
29.492958
132
0.677598
5.070258
false
false
false
false
silt-lang/silt
Sources/Lithosphere/Trivia+Convenience.swift
1
2399
/// Trivia+Convenience.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation extension TriviaPiece { /// Attempts to combine this trivia piece with the provided piece, or /// returns nil if both trivia cannot be combined into a single piece. /// For example, `.spaces(2).combined(with: .spaces(1))` is `.spaces(3)`. /// This can be used to incrementally build-up trivia. /// /// - Parameter piece: The piece you're trying to combine the receiver. /// - Returns: The result of combining two trivia pieces, or `nil` if they /// are not of the same base type. public func combined(with piece: TriviaPiece) -> TriviaPiece? { switch (self, piece) { case let (.spaces(s1), .spaces(s2)): return .spaces(s1 + s2) case let (.tabs(s1), .tabs(s2)): return .tabs(s1 + s2) case let (.verticalTabs(s1), .verticalTabs(s2)): return .verticalTabs(s1 + s2) case let (.formfeeds(s1), .formfeeds(s2)): return .formfeeds(s1 + s2) case let (.newlines(s1), .newlines(s2)): return .newlines(s1 + s2) case let (.carriageReturns(s1), .carriageReturns(s2)): return .carriageReturns(s1 + s2) default: return nil } } /// The total number of characters this trivia piece represents. public var length: Int { switch self { case .spaces(let n), .tabs(let n), .newlines(let n), .verticalTabs(let n), .formfeeds(let n), .carriageReturns(let n): return n case .comment(let s): return s.count } } } extension Trivia { /// The length, in characters, of this trivia piece. public var length: Int { return pieces.reduce(0) { $0 + $1.length } } public var containsWhitespace: Bool { for piece in pieces { if case .spaces(_) = piece { return true } if case .tabs(_) = piece { return true } if case .newlines(_) = piece { return true } if case .carriageReturns(_) = piece { return true } } return false } public var containsNewline: Bool { for piece in pieces { if case .spaces(_) = piece { return false } if case .tabs(_) = piece { return false } if case .newlines(_) = piece { return true } if case .carriageReturns(_) = piece { return false } } return false } }
mit
ae2385dc83f48f5a151b6f6c807fb310
31.418919
76
0.628595
3.70216
false
false
false
false
swiftix/swift.old
test/attr/attr_availability_tvos.swift
1
3655
// RUN: %swift -parse -verify -parse-stdlib -target i386-apple-tvos9.0 %s // REQUIRES: enable_target_appletvos @available(tvOS, introduced=1.0, deprecated=2.0, obsoleted=9.0, message="you don't want to do that anyway") func doSomething() { } // expected-note @-1{{'doSomething()' was obsoleted in tvOS 9.0}} doSomething() // expected-error{{'doSomething()' is unavailable: you don't want to do that anyway}} // Preservation of major.minor.micro @available(tvOS, introduced=1.0, deprecated=2.0, obsoleted=8.0) func doSomethingElse() { } // expected-note @-1{{'doSomethingElse()' was obsoleted in tvOS 8.0}} doSomethingElse() // expected-error{{'doSomethingElse()' is unavailable}} // Preservation of minor-only version @available(tvOS, introduced=1.0, deprecated=1.5, obsoleted=9) func doSomethingReallyOld() { } // expected-note @-1{{'doSomethingReallyOld()' was obsoleted in tvOS 9}} doSomethingReallyOld() // expected-error{{'doSomethingReallyOld()' is unavailable}} // Test deprecations in 9.0 and later @available(tvOS, introduced=1.1, deprecated=9.0, message="Use another function") func deprecatedFunctionWithMessage() { } deprecatedFunctionWithMessage() // expected-warning{{'deprecatedFunctionWithMessage()' was deprecated in tvOS 9.0: Use another function}} @available(tvOS, introduced=1.0, deprecated=9.0) func deprecatedFunctionWithoutMessage() { } deprecatedFunctionWithoutMessage() // expected-warning{{'deprecatedFunctionWithoutMessage()' was deprecated in tvOS 9.0}} @available(tvOS, introduced=1.0, deprecated=9.0, message="Use BetterClass instead") class DeprecatedClass { } func functionWithDeprecatedParameter(p: DeprecatedClass) { } // expected-warning{{'DeprecatedClass' was deprecated in tvOS 9.0: Use BetterClass instead}} @available(tvOS, introduced=7.0, deprecated=10.0, message="Use BetterClass instead") class DeprecatedClassIn8_0 { } // Elements deprecated later than the minimum deployment target (which is 9.0, in this case) should not generate warnings func functionWithDeprecatedLaterParameter(p: DeprecatedClassIn8_0) { } // Treat tvOS as distinct from iOS in availability queries @available(tvOS, introduced=9.2) func functionIntroducedOntvOS9_2() { } if #available(iOS 9.3, *) { functionIntroducedOntvOS9_2() // expected-error {{'functionIntroducedOntvOS9_2()' is only available on tvOS 9.2 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(iOS 9.3, tvOS 9.1, *) { functionIntroducedOntvOS9_2() // expected-error {{'functionIntroducedOntvOS9_2()' is only available on tvOS 9.2 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(iOS 9.1, tvOS 9.2, *) { functionIntroducedOntvOS9_2() } if #available(iOS 8.0, tvOS 9.2, *) { } if #available(iOS 9.2, tvOS 8.0, *) { // expected-warning {{unnecessary check for 'tvOS'; minimum deployment target ensures guard will always be true}} } // Swift-originated iOS availability attributes should not be transcribed to tvOS @available(iOS, unavailable) func swiftOriginatedFunctionUnavailableOnIOS() { } @available(iOS, introduced=6.0, deprecated=9.0) func swiftOriginatedFunctionDeprecatedOnIOS() { } @available(iOS, introduced=10.0) func swiftOriginatedFunctionPotentiallyUnavailableOnIOS() { } func useSwiftOriginatedFunctions() { // We do not expect diagnostics here because iOS availability attributes coming from // Swift should not be transcribed to tvOS. swiftOriginatedFunctionUnavailableOnIOS() swiftOriginatedFunctionDeprecatedOnIOS() swiftOriginatedFunctionPotentiallyUnavailableOnIOS() }
apache-2.0
c152c02b08c227491d47afd114f9763a
37.072917
153
0.743092
3.72579
false
false
false
false
intrahouse/aerogear-ios-http
AeroGearHttp/HttpRequestSerializer.swift
1
8683
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /** An HttpRequest serializer that handles form-encoded URL requess including multipart support. */ open class HttpRequestSerializer: RequestSerializer { /// The url that this request serializer is bound to. open var url: URL? /// Any headers that will be appended on the request. open var headers: [String: String]? /// The cache policy. open var cachePolicy: NSURLRequest.CachePolicy /// The timeout interval. open var timeoutInterval: TimeInterval /// Defualt initializer. public init() { self.timeoutInterval = 60 self.cachePolicy = .useProtocolCachePolicy } /** Build an request using the specified params passed in. :param: url the url of the resource. :param: method the method to be used. :param: parameters the request parameters. :param: headers any headers to be used on this request. :returns: the URLRequest object. */ open func request(url: URL, method: HttpMethod, parameters: [String: Any]?, headers: [String: String]? = nil) -> URLRequest { let request = NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval) request.httpMethod = method.rawValue // apply headers to new request if(headers != nil) { for (key,val) in headers! { request.addValue(val, forHTTPHeaderField: key) } } if method == .get || method == .head || method == .delete { let paramSeparator = request.url?.query != nil ? "&" : "?" var newUrl:String if (request.url?.absoluteString != nil && parameters != nil) { let queryString = self.stringFrom(httpParams: parameters!) newUrl = "\(request.url!.absoluteString)\(paramSeparator)\(queryString)" request.url = URL(string: newUrl)! } } else { // set type request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // set body if (parameters != nil) { let body = self.stringFrom(httpParams: parameters!).data(using: String.Encoding.utf8) request.setValue("\(body?.count)", forHTTPHeaderField: "Content-Length") request.httpBody = body } } return request as URLRequest } /** Build an multipart request using the specified params passed in. :param: url the url of the resource. :param: method the method to be used. :param: parameters the request parameters. :param: headers any headers to be used on this request. :returns: the URLRequest object */ open func multipartRequest(url: URL, method: HttpMethod, parameters: [String: Any]?, headers: [String: String]? = nil) -> URLRequest { let request = NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval) request.httpMethod = method.rawValue // apply headers to new request if(headers != nil) { for (key,val) in headers! { request.addValue(val, forHTTPHeaderField: key) } } let boundary = "AG-boundary-\(arc4random())-\(arc4random())" let type = "multipart/form-data; boundary=\(boundary)" let body = self.multiPartBodyFrom(httpParams: parameters!, boundary: boundary) request.setValue(type, forHTTPHeaderField: "Content-Type") request.setValue("\(body.count)", forHTTPHeaderField: "Content-Length") request.httpBody = body return request as URLRequest } private func stringFrom(httpParams parameters: [String: Any]) -> String { let parametersArray = serialization(httpParams: (nil, parameters)).map({(tuple) in return self.stringValue(tuple) }) return parametersArray.joined(separator: "&") } private func serialization(httpParams tuple: (String?, Any)) -> [(String?, Any)] { var collect:[(String?, Any)] = [] if let array = tuple.1 as? [Any] { for nestedValue : Any in array { let label: String = tuple.0! let myTuple:(String?, Any) = (label + "[]", nestedValue) collect.append(contentsOf: self.serialization(httpParams: myTuple)) } } else if let dict = tuple.1 as? [String: Any] { for (nestedKey, nestedObject) in dict { let newKey = tuple.0 != nil ? "\(tuple.0!)[\(nestedKey)]" : nestedKey let myTuple:(String?, Any) = (newKey, nestedObject) collect.append(contentsOf: self.serialization(httpParams: myTuple)) } } else { collect.append((tuple.0, tuple.1)) } return collect } private func stringValue(_ tuple: (String?, Any)) -> String { var val = "" if let str = tuple.1 as? String { val = str } else if (tuple.1 as AnyObject).description != nil { //TODO revisit Swift3 val = (tuple.1 as AnyObject).description } if tuple.0 == nil { return val.urlEncode() } return "\(tuple.0!.urlEncode())=\(val.urlEncode())" } private func multiPartBodyFrom(httpParams parameters: [String: Any], boundary: String) -> Data { let data = NSMutableData() let prefixData = "--\(boundary)\r\n".data(using: String.Encoding.utf8) let seperData = "\r\n".data(using: String.Encoding.utf8) for (key, value) in parameters { var sectionData: Data? var sectionType: String? var sectionFilename = "" var multipartName:String? = nil var isJsonData:Bool = false if value is MultiPartData { let multiData = value as! MultiPartData sectionData = multiData.data if let fileName = multiData.filename { sectionFilename = " filename=\"\(fileName)\"" } sectionType = multiData.mimeType multipartName = multiData.name isJsonData = multiData.isJsonData } else { sectionData = "\(value)".data(using: String.Encoding.utf8) } data.append(prefixData!) var sectionDisposition: Data? if (isJsonData) { sectionDisposition = "Content-Disposition: form-data; name=\"\(multipartName ?? key)\"\r\n".data(using: String.Encoding.utf8) } else { sectionDisposition = "Content-Disposition: form-data; name=\"\(multipartName ?? key)\";\(sectionFilename)\r\n".data(using: String.Encoding.utf8) } data.append(sectionDisposition!) if let type = sectionType { let contentType = "Content-Type: \(type)\r\n".data(using: String.Encoding.utf8) data.append(contentType!) } // append data data.append(seperData!) data.append(sectionData!) data.append(seperData!) } data.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!) return data as Data } private func hasMultiPartData(httpParams parameters: [String: Any]?) -> Bool { if (parameters == nil) { return false } var isMultiPart = false for (_, value) in parameters! { if value is MultiPartData { isMultiPart = true break } } return isMultiPart } }
apache-2.0
62f19703863a732bebefbb7dbc65941c
36.752174
160
0.570195
4.925128
false
false
false
false
LNTUORG/LntuOnline-iOS-Swift
eduadmin/LoginViewController.swift
1
3782
// // LoginViewController.swift // eduadmin // // Created by Li Jie on 10/16/15. // Copyright © 2015 PUPBOSS. All rights reserved. // import UIKit import Alamofire class LoginViewController: BaseViewController { var userId = "" var password = "" @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() if (CommonTools.getUserDefaultValueForKey(Constants.UserInfoKey.USER_NAME_KEY) == "" || CommonTools.getUserDefaultValueForKey(Constants.UserInfoKey.PASSWORD_KEY) == "") { } else { userId = CommonTools.getUserDefaultValueForKey(Constants.UserInfoKey.USER_NAME_KEY) password = CommonTools.getUserDefaultValueForKey(Constants.UserInfoKey.PASSWORD_KEY) self.userNameTextField.text = userId self.passwordTextField.text = password } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Actions @IBAction func askForHelp() { let url = NSURL(string: ("http://wpa.qq.com/msgrd?v=3&uin=" + Constants.DeveloperInfo.QQ + "&site=qq&menu=yes")) UIApplication.sharedApplication().openURL(url!) } @IBAction func exitEditing() { self.view.endEditing(true) } @IBAction func loginAction() { MBProgressHUD.showMessage(Constants.Notification.LOADING) self.userId = self.userNameTextField.text! self.password = self.passwordTextField.text! if (self.userId.length + self.password.length <= 7) { MBProgressHUD.showError("补全信息后再登录") return } CommonTools.storeUserDefaultValueForKey(Constants.UserInfoKey.USER_NAME_KEY, value: self.userNameTextField.text!) CommonTools.storeUserDefaultValueForKey(Constants.UserInfoKey.PASSWORD_KEY, value: self.passwordTextField.text!) let param = [ "userId": self.userId, "password": self.password ] Alamofire.request(.POST, Constants.ROOT_URL + "account/login", parameters: param).responseJSON { (response: Response<AnyObject, NSError>) -> Void in MBProgressHUD.hideHUD() if let dict = response.result.value as? Dictionary<String, AnyObject> { if response.response?.statusCode == 400 { MBProgressHUD.showError(Constants.Notification.PASSWORD_ERROR) } else { if dict["userType"] as! String == "STUDENT" { Constants.LOGIN_TOKEN = dict["loginToken"] as! String CommonTools.storeUserDefaultValueForKey(Constants.UserInfoKey.LOGIN_TOKEN_KEY, value: dict["loginToken"] as! String) CommonTools.storeUserDefaultValueForKey(Constants.UserInfoKey.EXPRES_AT_KEY, value: dict["expiresAt"] as! String) MBProgressHUD.showSuccess("登录成功") self.dismissViewControllerAnimated(true, completion: nil) } else { MBProgressHUD.showError("暂不支持教师用户") } } } else { MBProgressHUD.showError(Constants.Notification.NET_ERROR) } } } }
gpl-2.0
5035d1d726f94a2a8ced1b0299bd349a
32.702703
178
0.55707
5.375
false
false
false
false
practicalswift/swift
test/Interpreter/late_import_cgfloat.swift
12
294
// RUN: %target-repl-run-simple-swift | %FileCheck %s // REQUIRES: swift_repl // This used to crash. let str = "" import Foundation let pt = CGPoint(x: 1.0, y: 2.0) // CHECK: pt : CGPoint = (1.0, 2.0) import simd let f = float2(x: 1.0, y: 2.0) // CHECK: f : float2 = SIMD2<Float>(1.0, 2.0)
apache-2.0
0b0a732c1fe5f78120a3c233d26797a4
20
53
0.608844
2.370968
false
false
false
false
rain2540/Swift_100_Examples
Arrangement_and_Combination/Arrangement_and_Combination.playground/Contents.swift
1
1935
import UIKit /// 阶乘、排列组合错误类型 /// /// - factorialOfNegativeNumbers: 负数的阶乘 /// - arrangementParameterNonCompliance: 排列参数不符合规范 /// - combinationParameterNonCompliance: 组合参数不符合规范 enum ACError: Error { /// 负数的阶乘 case factorialOfNegativeNumbers /// 排列参数不符合规范 case arrangementParameterNonCompliance /// 组合参数不符合规范 case combinationParameterNonCompliance } /// 阶乘 /// - Parameter num: 需要计算阶乘的非负整数 /// - Throws: 计算中的异常情况 /// - Returns: 阶乘计算结果 func factorial(of num: Int) throws -> Int { guard num >= 0 else { throw ACError.factorialOfNegativeNumbers } return num > 0 ? (1 ... num).reduce(1, { $0 * $1 }) : 1 } /// 排列 /// - Parameters: /// - n: 元素总数 /// - m: 取出元素个数 /// - Throws: 计算中的异常情况 /// - Returns: 排列计算结果 func arrangement(n: Int, m: Int) throws -> Int { guard m <= n else { throw ACError.arrangementParameterNonCompliance } return try factorial(of: n) / factorial(of: n - m) } /// 组合 /// - Parameters: /// - n: 元素总数 /// - m: 取出元素个数 /// - Throws: 计算中的异常情况 /// - Returns: 组合计算结果 func combination(n: Int, m: Int) throws -> Int { guard m <= n else { throw ACError.combinationParameterNonCompliance } return try factorial(of: n) / (factorial(of: m) * factorial(of: n - m)) } //: Examples let n = 4, m = 2 //: Factorial do { let res = try factorial(of: n) print("factorial of \(n) is", res) } catch { print(error) } do { let res = try arrangement(n: n, m: m) print("result of A(\(n), \(m)) is \(res)") } catch { print(error) } do { let res = try combination(n: n, m: m) print("result of C(\(n), \(m)) is \(res)") } catch { print(error) }
mit
a88c9470bf264124c37c71558f9183a3
20.320513
75
0.602526
2.917544
false
false
false
false