repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
ilyapuchka/SwiftNetworking
SwiftNetworking/NSData+Multipart.swift
1
7842
// // NSData+Multipart.swift // SwiftNetworking // // Created by Ilya Puchka on 11.09.15. // Copyright © 2015 Ilya Puchka. All rights reserved. // import Foundation public struct MultipartBodyItem: APIRequestDataEncodable, Equatable { let data: NSData let contentType: MIMEType let headers: [HTTPHeader] public init(data: NSData, contentType: MIMEType, headers: [HTTPHeader]) { self.data = data.copy() as! NSData self.contentType = contentType self.headers = headers } public init?(multipartData: NSData) { let (data, contentType, headers) = MultipartBodyItem.parseMultipartData(multipartData) guard let _ = contentType, _ = data else { return nil } self.headers = headers self.contentType = contentType! self.data = data! } static private func parseMultipartData(multipartData: NSData) -> (NSData?, MIMEType?, [HTTPHeader]) { var headers = [HTTPHeader]() var contentType: MIMEType? var data: NSData? let dataLines = MultipartBodyItem.multipartDataLines(multipartData) for dataLine in dataLines { let line = NSString(data: dataLine, encoding: NSUTF8StringEncoding)! as String if let _contentType = MultipartBodyItem.contentTypeFromLine(line) { contentType = _contentType } else if let contentLength = MultipartBodyItem.contentLengthFromLine(line) { data = MultipartBodyItem.contentDataFromData(multipartData, contentLength: contentLength) } else if let header = MultipartBodyItem.headersFromLine(line) { headers.append(header) } } return (data, contentType, headers) } static private func multipartDataLines(data: NSData) -> [NSData] { var dataLines = data.lines() dataLines.removeLast() return dataLines } private static let ContentTypePrefix = "Content-Type: " private static let ContentLengthPrefix = "Content-Length: " private static func contentTypeFromLine(line: String) -> String? { guard line.hasPrefix(MultipartBodyItem.ContentTypePrefix) else { return nil } return line.substringFromIndex(MultipartBodyItem.ContentTypePrefix.endIndex) } private static func contentLengthFromLine(line: String) -> Int? { guard line.hasPrefix(MultipartBodyItem.ContentLengthPrefix) else { return nil } let scaner = NSScanner(string: line.substringFromIndex(MultipartBodyItem.ContentLengthPrefix.endIndex)) var contentLength: Int = 0 scaner.scanInteger(&contentLength) return contentLength } private static func headersFromLine(line: String) -> HTTPHeader? { guard let colonRange = line.rangeOfString(": ") else { return nil } let key = line.substringToIndex(colonRange.startIndex) let value = line.substringFromIndex(colonRange.endIndex) return HTTPHeader.Custom(key, value) } private static func contentDataFromData(data: NSData, contentLength: Int) -> NSData { let carriageReturn = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)! let range = NSMakeRange(data.length - carriageReturn.length - contentLength, contentLength) return data.subdataWithRange(range) } } //MARK: - APIRequestDataEncodable extension MultipartBodyItem { public func encodeForAPIRequestData() throws -> NSData { return NSData() } } //MARK: - Equatable public func ==(lhs: MultipartBodyItem, rhs: MultipartBodyItem) -> Bool { return lhs.data == rhs.data && lhs.contentType == rhs.contentType && lhs.headers == rhs.headers } public func NSSubstractRange(fromRange: NSRange, _ substractRange: NSRange) -> NSRange { return NSMakeRange(NSMaxRange(substractRange), NSMaxRange(fromRange) - NSMaxRange(substractRange)); } public func NSRangeInterval(fromRange: NSRange, toRange: NSRange) -> NSRange { if (NSIntersectionRange(fromRange, toRange).length > 0) { return NSMakeRange(0, 0); } if (NSMaxRange(fromRange) < NSMaxRange(toRange)) { return NSMakeRange(NSMaxRange(fromRange), toRange.location - NSMaxRange(fromRange)); } else { return NSMakeRange(NSMaxRange(toRange), fromRange.location - NSMaxRange(toRange)); } } extension NSMutableData { public func appendString(string: String) { appendData(string.dataUsingEncoding(NSUTF8StringEncoding) ?? NSData()) } public func appendNewLine() { appendString("\r\n") } public func appendStringLine(string: String) { appendString(string) appendNewLine() } public func appendMultipartBodyItem(item: MultipartBodyItem, boundary: String) { appendStringLine("--\(boundary)") appendStringLine("Content-Type: \(item.contentType)") appendStringLine("Content-Length: \(item.data.length)") for header in item.headers { appendStringLine("\(header.key): \(header.requestHeaderValue)") } appendNewLine() appendData(item.data) appendNewLine() } } extension NSData { public convenience init(multipartDataWithItems items: [MultipartBodyItem], boundary: String) { let multipartData = NSMutableData() for item in items { multipartData.appendMultipartBodyItem(item, boundary: boundary) } multipartData.appendStringLine("--\(boundary)--") self.init(data: multipartData) } public func multipartDataItemsSeparatedWithBoundary(boundary: String) -> [MultipartBodyItem] { let boundaryData = "--\(boundary)".dataUsingEncoding(NSUTF8StringEncoding)! let trailingData = "--\r\n".dataUsingEncoding(NSUTF8StringEncoding)! let items = componentsSeparatedByData(boundaryData).flatMap { (data: NSData) -> MultipartBodyItem? in if data != trailingData { return MultipartBodyItem(multipartData: data) } return nil } return items } public func componentsSeparatedByData(boundary: NSData) -> [NSData] { var components = [NSData]() enumerateBytesByBoundary(boundary) { (dataPart, _, _) -> Void in components.append(dataPart) } return components } public func lines() -> [NSData] { return componentsSeparatedByData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) } private func enumerateBytesByBoundary(boundary: NSData, iteration: (NSData, NSRange, inout Bool) -> Void) { var boundaryRange = NSMakeRange(0, 0) var stop = false repeat { if let subRange = subRange(boundary, boundaryRange: boundaryRange) { if subRange.length > 0 { iteration(subdataWithRange(subRange), subRange, &stop) } boundaryRange = NSMakeRange(NSMaxRange(subRange), boundary.length) } else { break; } } while (!stop && NSMaxRange(boundaryRange) < length) } private func subRange(boundary: NSData, boundaryRange: NSRange) -> NSRange? { let searchRange = NSSubstractRange(NSMakeRange(0, length), boundaryRange) let nextBoundaryRange = rangeOfData(boundary, options: NSDataSearchOptions(), range: searchRange) var subRange: NSRange? if nextBoundaryRange.location != NSNotFound { subRange = NSRangeInterval(boundaryRange, toRange: nextBoundaryRange) } else if (NSMaxRange(boundaryRange) < length) { subRange = searchRange } return subRange } }
mit
35fdd2424d7c3a0aed3adf077d848408
35.138249
111
0.647494
5.101496
false
false
false
false
lieonCX/Live
Live/Others/Lib/RITLImagePicker/Photofiles/Photo/RITLPhotoPreviewController.swift
1
1725
// // RITLPhotoPreviewController.swift // RITLImagePicker-Swift // // Created by YueWen on 2017/1/22. // Copyright © 2017年 YueWen. All rights reserved. // import UIKit import Photos /// 响应3D Touch的视图 class RITLPhotoPreviewController: UIViewController { /// 当前显示的资源对象 var showAsset : PHAsset = PHAsset() /// 展示图片的视图 lazy fileprivate var imageView : UIImageView = { let imageView = UIImageView() imageView.backgroundColor = .white imageView.contentMode = .scaleToFill imageView.layer.cornerRadius = 8.0 return imageView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //获得资源的宽度与高度的比例 let scale = CGFloat(showAsset.pixelHeight) * 1.0 / CGFloat(showAsset.pixelWidth) preferredContentSize = CGSize(width: view.bounds.width, height: view.bounds.width * scale) //添加 view.addSubview(imageView) //约束布局 imageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } //获取图片对象 RITLPhotoHandleManager.asset(representionIn: showAsset, size: preferredContentSize) { (image, asset) in self.imageView.image = image } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { print("\(self.self)deinit") } }
mit
bae73f1c6c57ebd9979e78ef8f6d01d9
22.623188
111
0.58589
4.969512
false
false
false
false
AlphaJian/LarsonApp
LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/WorkOrderScrollView.swift
1
5466
// // WorkOrderScrollView.swift // LarsonApp // // Created by Perry Z Chen on 11/10/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import UIKit class WorkOrderScrollView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBOutlet weak var callNumberContainer: UIView! @IBOutlet weak var callNumberContraint: NSLayoutConstraint! @IBOutlet weak var stationNumberContainer: UIView! @IBOutlet weak var stationNumberConstraint: NSLayoutConstraint! @IBOutlet weak var siteAddressContainer: UIView! @IBOutlet weak var siteAddressConstraint: NSLayoutConstraint! @IBOutlet weak var zipCodeContainer: UIView! @IBOutlet weak var zipCodeConstraint: NSLayoutConstraint! @IBOutlet weak var phoneNumberContainer: UIView! @IBOutlet weak var phoneNumberConstraint: NSLayoutConstraint! @IBOutlet weak var TechNumberContainer: UIView! @IBOutlet weak var techNumberConstraint: NSLayoutConstraint! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var stationTitleLable: UILabel! @IBOutlet weak var stationContentLabel: UILabel! @IBOutlet weak var siteAddressLabel: UILabel! @IBOutlet weak var siteContentLabel: UILabel! @IBOutlet weak var zipContentLabel: UILabel! @IBOutlet weak var zipTitleLabel: UILabel! @IBOutlet weak var phoneNumTitleLabel: UILabel! @IBOutlet weak var phoneNumContentLabel: UILabel! @IBOutlet weak var techTitleLabel: UILabel! @IBOutlet weak var techContentLabel: UILabel! func initUI(model: AppointmentModel) { // let callNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // // callNumberView?.initUI(parameter: ("Call Number", model.telephoneNumber), labelWidth: LCDW) // let height = callNumberView?.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height // print("---> \(height), \(LCDW)") // callNumberView?.frame = CGRect(x: 0, y: 0, width: LCDW, height: height!) // self.callNumberContraint.constant = height! // // self.callNumberContainer.addSubview(callNumberView!) self.titleLabel.text = "Call Number" self.stationTitleLable.text = "Station Number" self.siteAddressLabel.text = "Site Address" self.zipTitleLabel.text = "Zip Code" self.phoneNumTitleLabel.text = "Phone Number" self.techTitleLabel.text = "Phone Number" //\(model.telephoneNumber)\(model.telephoneNumber)\(model.telephoneNumber)\(model.telephoneNumber) let callNumStr = "\(model.telephoneNumber)" as NSString let stationStr = model.stationNumber let siteAddressStr = model.customerAddress let zipStr = model.zipCode let phoneNumStr = model.telephoneNumber let techNumStr = model.techNumber let str = NSMutableAttributedString(string: (callNumStr).uppercased) str.addAttribute(NSFontAttributeName, value:UIFont.systemFont(ofSize: 15.0), range:NSRange(location:0,length: (callNumStr).uppercased.characters.count )) self.callNumberContraint.constant = StringUtil.getAttributeString(str: str, width: LCDW - 30 ) self.contentLabel.text = callNumStr as String self.stationContentLabel.text = stationStr self.siteContentLabel.text = siteAddressStr self.zipContentLabel.text = zipStr self.phoneNumContentLabel.text = phoneNumStr self.techContentLabel.text = techNumStr // let stationNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // stationNumberView?.initUI(parameter: ("Station Number", ""), labelWidth: LCDW) // self.stationNumberContainer.addSubview(stationNumberView!) // // let siteAddressView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // siteAddressView?.initUI(parameter: ("Site Address", ""), labelWidth: LCDW) // self.siteAddressContainer.addSubview(siteAddressView!) // // let zipCodeView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // zipCodeView?.initUI(parameter: ("Zip Code", ""), labelWidth: LCDW) // self.zipCodeContainer.addSubview(zipCodeView!) // // let phoneNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // phoneNumberView?.initUI(parameter: ("Phone Number", ""), labelWidth: LCDW) // self.phoneNumberContainer.addSubview(phoneNumberView!) // // let techNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // techNumberView?.initUI(parameter: ("Tech Number", ""), labelWidth: LCDW) // self.TechNumberContainer.addSubview(techNumberView!) self.layoutIfNeeded() self.setNeedsLayout() // self.contentSize = CGSize(width: (callNumberView?.frame.size.width)!, height: height) } }
apache-2.0
74202722b691cd6ec97d7995a83bdff8
43.430894
161
0.691491
4.832007
false
false
false
false
bluquar/emoji_keyboard
EmojiKeyboard/EmojiSelectKB/KBButton.swift
1
4124
// // KBButton.swift // EmojiKeyboard // // Created by Chris Barker on 10/2/14. // Copyright (c) 2014 Chris Barker. All rights reserved. // import UIKit class KBButton: NSObject { var parentView: UIView var layoutManager: ButtonLayoutManager var button: UIButton var image: UIImageView var container: UIView var row: Int var col: Int init(view: UIView, layoutManager: ButtonLayoutManager) { self.parentView = view self.layoutManager = layoutManager self.row = -1 self.col = -1 self.button = UIButton.buttonWithType(.System) as UIButton self.button.setTitle("", forState: .Normal) self.button.titleLabel?.font = UIFont.systemFontOfSize(14) self.button.backgroundColor = UIColor(white: 0.9, alpha: 0.5) self.button.layer.cornerRadius = 5 self.image = UIImageView() self.image.contentMode = UIViewContentMode.ScaleAspectFit self.container = UIView() super.init() } func addToLayout(row: Int, col: Int) { self.row = row self.col = col // add event listeners self.button.addTarget(self, action: "touchupinside:", forControlEvents: .TouchUpInside) self.button.addTarget(self, action: "touchup:", forControlEvents: .TouchUpOutside) self.button.addTarget(self, action: "touchdown:", forControlEvents: .TouchDown) // construct view hierarchy self.parentView.addSubview(self.container) self.container.addSubview(self.button) self.container.addSubview(self.image) // pin button to view self.button.setTranslatesAutoresizingMaskIntoConstraints(false) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .Width, relatedBy: .Equal, toItem: self.container, attribute: .Width, multiplier: 1.0, constant: -5.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .Height, relatedBy: .Equal, toItem: self.container, attribute: .Height, multiplier: 1.0, constant: -6.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .CenterY, relatedBy: .Equal, toItem: self.container, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) // pin image to view self.image.setTranslatesAutoresizingMaskIntoConstraints(false) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .Width, relatedBy: .LessThanOrEqual, toItem: self.container, attribute: .Width, multiplier: 1.0, constant: -7.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .Height, relatedBy: .LessThanOrEqual, toItem: self.container, attribute: .Height, multiplier: 1.0, constant: -8.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .CenterY, relatedBy: .Equal, toItem: self.container, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) // constrain aspect ratio self.parentView.addConstraint(NSLayoutConstraint(item: self.container, attribute: .Height, relatedBy: .LessThanOrEqual, toItem: self.container, attribute: .Width, multiplier: 0.7, constant: 0.0)) } func touchup(sender: AnyObject) { self.button.backgroundColor = UIColor(white: 0.9, alpha: 0.5) self.image.alpha = 1.0 } func touchdown(sender: AnyObject) { self.button.backgroundColor = UIColor(white: 0.5, alpha: 0.5) self.image.alpha = 0.7 } func touchupinside(sender: AnyObject) { self.touchup(sender) self.layoutManager.tapped(self.row, col: self.col) } }
gpl-2.0
99c65cb9a7239c7d7a3d84a6251e0dfe
46.402299
203
0.682105
4.273575
false
false
false
false
AnthonyMDev/AmazonS3RequestManager
Example/Tests/AmazonS3ACLTests.swift
2
12214
// // AmazonS3ACLTests.swift // AmazonS3RequestManager // // Created by Anthony Miller on 6/9/15. // Copyright (c) 2015 Anthony Miller. All rights reserved. // import Quick import Nimble import AmazonS3RequestManager class AmazonS3ACLSpec: QuickSpec { override func spec() { describe("PredefinedACL") { context(".privateReadWrite") { let acl = PredefinedACL.privateReadWrite it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("private")) } } context(".publicReadWrite") { let acl = PredefinedACL.publicReadWrite it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("public-read-write")) } } context(".publicReadOnly") { let acl = PredefinedACL.publicReadOnly it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("public-read")) } } context(".authenticatedReadOnly") { let acl = PredefinedACL.authenticatedReadOnly it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("authenticated-read")) } } context(".bucketOwnerReadOnly") { let acl = PredefinedACL.bucketOwnerReadOnly it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("bucket-owner-read")) } } context(".bucketOwnerFullControl") { let acl = PredefinedACL.bucketOwnerFullControl it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("bucket-owner-full-control")) } } context(".logDeliveryWrite") { let acl = PredefinedACL.logDeliveryWrite it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("log-delivery-write")) } } } describe("ACL Permission Grant") { describe("With Permission") { func aclWithPermission(_ permission: ACLPermission) -> ACLPermissionGrant { let grantee = ACLGrantee.authenticatedUsers return ACLPermissionGrant(permission: permission, grantee: grantee) } describe("read") { let permission = ACLPermission.read let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).toNot(beNil()) } } describe("write") { let permission = ACLPermission.write let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write"] expect(aclHeader).toNot(beNil()) } } describe("readACL") { let permission = ACLPermission.readACL let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read-acp"] expect(aclHeader).toNot(beNil()) } } describe("writeACL") { let permission = ACLPermission.writeACL let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write-acp"] expect(aclHeader).toNot(beNil()) } } describe("fullControl") { let permission = ACLPermission.fullControl let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-full-control"] expect(aclHeader).toNot(beNil()) } } } describe("With Grantee") { func aclWithGrantee(_ grantee: ACLGrantee) -> ACLPermissionGrant { let permission = ACLPermission.read return ACLPermissionGrant(permission: permission, grantee: grantee) } describe("Grantee: Authenticated Users") { let grantee = ACLGrantee.authenticatedUsers let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AuthenticatedUsers\"")) } } describe("Grantee: All Users") { let grantee = ACLGrantee.allUsers let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AllUsers\"")) } } describe("Grantee: Log Delivery Group") { let grantee = ACLGrantee.logDeliveryGroup let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/s3/LogDelivery\"")) } } describe("Grantee: Email") { let grantee = ACLGrantee.emailAddress("[email protected]") let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("emailAddress=\"[email protected]\"")) } } describe("Grantee: User ID") { let grantee = ACLGrantee.userID("123456") let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("id=\"123456\"")) } } } describe("With Multiple Grantees") { func aclWithGrantees(_ grantees: Set<ACLGrantee>) -> ACLPermissionGrant { let permission = ACLPermission.read return ACLPermissionGrant(permission: permission, grantees: grantees) } it("sets ACL request headers") { let acl = aclWithGrantees([ ACLGrantee.emailAddress("[email protected]"), ACLGrantee.userID("123456")]) var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(contain("emailAddress=\"[email protected]\"")) expect(aclHeader).to(contain("id=\"123456\"")) expect(aclHeader).to(contain(", ")) } } } } }
mit
6c23bae9bc7ffa155f05e89297c58f0c
42.935252
120
0.447519
6.12845
false
true
false
false
vimeo/VimeoNetworking
Sources/Shared/Requests/Request+Video.swift
1
4223
// // Request+Video.swift // VimeoNetworkingExample-iOS // // Created by Huebner, Rob on 4/5/16. // Copyright © 2016 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Request` returning a single `VIMVideo` public typealias VideoRequest = Request<VIMVideo> /// `Request` returning an array of `VIMVideo` public typealias VideoListRequest = Request<[VIMVideo]> public extension Request { // MARK: - /** Create a `Request` to get a specific video - parameter videoURI: the video's URI - returns: a new `Request` */ static func videoRequest(forVideoURI videoURI: String) -> Request { return Request(path: videoURI) } /** Create a `Request` to get a specific VOD video - parameter vodVideoURI: the VOD video's URI - returns: a new `Request` */ static func vodVideoRequest(forVODVideoURI vodVideoURI: String) -> Request { let parameters = ["_video_override": "true"] return Request(path: vodVideoURI, parameters: parameters) } /** Create a `Request` to get the selected users for the vieo - parameter videoURI: the URI of the video - returns: a new `Request` */ static func selectedUsersRequest(forVideoURI videoURI: String) -> Request { let parameters = [String.perPageKey: 100] let path = videoURI + .selectedUsersPrivacyPath return Request(path: path, parameters: parameters) } // MARK: - Search /** Create a `Request` to search for videos - parameter query: the string query to use for the search - parameter refinements: optionally, refinement parameters to add to the search - returns: a new `Request` */ static func queryVideos(withQuery query: String, refinements: VimeoClient.RequestParametersDictionary? = nil) -> Request { var parameters = refinements ?? [:] parameters[.queryKey] = query return Request(path: .videosPath, parameters: parameters) } // MARK: - Edit Video /** Create a `Request` to update a video's metadata - parameter videoURI: the URI of the video to update - parameter parameters: the updated parameters - returns: a new `Request` */ static func patchVideoRequest(withVideoURI videoURI: String, parameters: VimeoClient.RequestParametersDictionary) -> Request { return Request(method: .patch, path: videoURI, parameters: parameters) } /** Create a `Request` to delete a video - parameter videoURI: the URI of the video to update - returns: a new `Request` */ static func deleteVideoRequest(forVideoURI videoURI: String) -> Request { return Request(method: .delete, path: videoURI) } } private extension String { // Request & response keys static let perPageKey = "per_page" static let queryKey = "query" // Paths static let selectedUsersPrivacyPath = "/privacy/users" static let videosPath = "/videos" }
mit
0f5d31c527c7c8c46f276975a1d6ed79
31.728682
130
0.664377
4.544672
false
false
false
false
zisko/swift
stdlib/public/core/Filter.swift
1
14053
//===--- Filter.swift -----------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence whose elements consist of the elements of some base /// sequence that also satisfy a given predicate. /// /// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`, /// is a `LazyFilterSequence`. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyFilterSequence<Base: Sequence> { @_versioned // FIXME(sil-serialize-all) internal var _base: Base /// The predicate used to determine which elements produced by /// `base` are also produced by `self`. @_versioned // FIXME(sil-serialize-all) internal let _predicate: (Base.Element) -> Bool /// Creates an instance consisting of the elements `x` of `base` for /// which `isIncluded(x) == true`. @_inlineable // FIXME(sil-serialize-all) public // @testable init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) { self._base = base self._predicate = isIncluded } } extension LazyFilterSequence { /// An iterator over the elements traversed by some base iterator that also /// satisfy a given predicate. /// /// - Note: This is the associated `Iterator` of `LazyFilterSequence` /// and `LazyFilterCollection`. @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { /// The underlying iterator whose elements are being filtered. public var base: Base.Iterator { return _base } @_versioned // FIXME(sil-serialize-all) internal var _base: Base.Iterator @_versioned // FIXME(sil-serialize-all) internal let _predicate: (Base.Element) -> Bool /// Creates an instance that produces the elements `x` of `base` /// for which `isIncluded(x) == true`. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) { self._base = _base self._predicate = isIncluded } } } extension LazyFilterSequence.Iterator: IteratorProtocol, Sequence { public typealias Element = Base.Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @_inlineable // FIXME(sil-serialize-all) public mutating func next() -> Element? { while let n = _base.next() { if _predicate(n) { return n } } return nil } } extension LazyFilterSequence: LazySequenceProtocol { public typealias Element = Base.Element /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _predicate) } @_inlineable public func _customContainsEquatableElement(_ element: Element) -> Bool? { // optimization to check the element first matches the predicate guard _predicate(element) else { return false } return _base._customContainsEquatableElement(element) } } /// A lazy `Collection` wrapper that includes the elements of an /// underlying collection that satisfy a predicate. /// /// - Note: The performance of accessing `startIndex`, `first`, any methods /// that depend on `startIndex`, or of advancing an index depends /// on how sparsely the filtering predicate is satisfied, and may not offer /// the usual performance given by `Collection`. Be aware, therefore, that /// general operations on `LazyFilterCollection` instances may not have the /// documented complexity. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyFilterCollection<Base : Collection> { @_versioned // FIXME(sil-serialize-all) internal var _base: Base @_versioned // FIXME(sil-serialize-all) internal let _predicate: (Base.Element) -> Bool /// Creates an instance containing the elements of `base` that /// satisfy `isIncluded`. @_inlineable // FIXME(sil-serialize-all) public // @testable init(_base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) { self._base = _base self._predicate = isIncluded } } extension LazyFilterCollection : LazySequenceProtocol { public typealias Element = Base.Element public typealias Iterator = LazyFilterSequence<Base>.Iterator public typealias SubSequence = LazyFilterCollection<Base.SubSequence> // Any estimate of the number of elements that pass `_predicate` requires // iterating the collection and evaluating each element, which can be costly, // is unexpected, and usually doesn't pay for itself in saving time through // preventing intermediate reallocations. (SR-4164) @_inlineable // FIXME(sil-serialize-all) public var underestimatedCount: Int { return 0 } @_inlineable // FIXME(sil-serialize-all) public func _copyToContiguousArray() -> ContiguousArray<Base.Element> { // The default implementation of `_copyToContiguousArray` queries the // `count` property, which evaluates `_predicate` for every element -- // see the note above `underestimatedCount`. Here we treat `self` as a // sequence and only rely on underestimated count. return _copySequenceToContiguousArray(self) } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _predicate) } @_inlineable public func _customContainsEquatableElement(_ element: Element) -> Bool? { guard _predicate(element) else { return false } return _base._customContainsEquatableElement(element) } } extension LazyFilterCollection : LazyCollectionProtocol { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Base.Index /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. /// /// - Complexity: O(*n*), where *n* is the ratio between unfiltered and /// filtered collection counts. @_inlineable // FIXME(sil-serialize-all) public var startIndex: Index { var index = _base.startIndex while index != _base.endIndex && !_predicate(_base[index]) { _base.formIndex(after: &index) } return index } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @_inlineable // FIXME(sil-serialize-all) public var endIndex: Index { return _base.endIndex } // TODO: swift-3-indexing-model - add docs @_inlineable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { var i = i formIndex(after: &i) return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex(after i: inout Index) { // TODO: swift-3-indexing-model: _failEarlyRangeCheck i? var index = i _precondition(index != _base.endIndex, "Can't advance past endIndex") repeat { _base.formIndex(after: &index) } while index != _base.endIndex && !_predicate(_base[index]) i = index } @inline(__always) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _advanceIndex(_ i: inout Index, step: Int) { repeat { _base.formIndex(&i, offsetBy: step) } while i != _base.endIndex && !_predicate(_base[i]) } @inline(__always) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _ensureBidirectional(step: Int) { // FIXME: This seems to be the best way of checking whether _base is // forward only without adding an extra protocol requirement. // index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return // nil when the resulting index lands outside the collection boundaries, // and therefore likely does not trap in these cases. if step < 0 { _ = _base.index( _base.endIndex, offsetBy: step, limitedBy: _base.startIndex) } } @_inlineable // FIXME(sil-serialize-all) public func distance(from start: Index, to end: Index) -> Int { // The following line makes sure that distance(from:to:) is invoked on the // _base at least once, to trigger a _precondition in forward only // collections. _ = _base.distance(from: start, to: end) var _start: Index let _end: Index let step: Int if start > end { _start = end _end = start step = -1 } else { _start = start _end = end step = 1 } var count = 0 while _start != _end { count += step formIndex(after: &_start) } return count } @_inlineable // FIXME(sil-serialize-all) public func index(_ i: Index, offsetBy n: Int) -> Index { var i = i let step = n.signum() // The following line makes sure that index(_:offsetBy:) is invoked on the // _base at least once, to trigger a _precondition in forward only // collections. _ensureBidirectional(step: step) for _ in 0 ..< abs(numericCast(n)) { _advanceIndex(&i, step: step) } return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex(_ i: inout Index, offsetBy n: Int) { i = index(i, offsetBy: n) } @_inlineable // FIXME(sil-serialize-all) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { var i = i let step = n.signum() // The following line makes sure that index(_:offsetBy:limitedBy:) is // invoked on the _base at least once, to trigger a _precondition in // forward only collections. _ensureBidirectional(step: step) for _ in 0 ..< abs(numericCast(n)) { if i == limit { return nil } _advanceIndex(&i, step: step) } return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex( _ i: inout Index, offsetBy n: Int, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @_inlineable // FIXME(sil-serialize-all) public subscript(position: Index) -> Element { return _base[position] } @_inlineable // FIXME(sil-serialize-all) public subscript(bounds: Range<Index>) -> SubSequence { return SubSequence(_base: _base[bounds], _predicate) } } extension LazyFilterCollection : BidirectionalCollection where Base : BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { var i = i formIndex(before: &i) return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex(before i: inout Index) { // TODO: swift-3-indexing-model: _failEarlyRangeCheck i? var index = i _precondition(index != _base.startIndex, "Can't retreat before startIndex") repeat { _base.formIndex(before: &index) } while !_predicate(_base[index]) i = index } } extension LazySequenceProtocol { /// Returns the elements of `self` that satisfy `isIncluded`. /// /// - Note: The elements of the result are computed on-demand, as /// the result is used. No buffering storage is allocated and each /// traversal step invokes `predicate` on one or more underlying /// elements. @_inlineable // FIXME(sil-serialize-all) public func filter( _ isIncluded: @escaping (Elements.Element) -> Bool ) -> LazyFilterSequence<Self.Elements> { return LazyFilterSequence(_base: self.elements, isIncluded) } } extension LazyCollectionProtocol { /// Returns the elements of `self` that satisfy `predicate`. /// /// - Note: The elements of the result are computed on-demand, as /// the result is used. No buffering storage is allocated and each /// traversal step invokes `predicate` on one or more underlying /// elements. @_inlineable // FIXME(sil-serialize-all) public func filter( _ isIncluded: @escaping (Elements.Element) -> Bool ) -> LazyFilterCollection<Self.Elements> { return LazyFilterCollection(_base: self.elements, isIncluded) } } extension LazyFilterSequence { public func filter( _ isIncluded: @escaping (Element) -> Bool ) -> LazyFilterSequence<Base> { return LazyFilterSequence(_base: _base) { isIncluded($0) && self._predicate($0) } } } extension LazyFilterCollection { public func filter( _ isIncluded: @escaping (Element) -> Bool ) -> LazyFilterCollection<Base> { return LazyFilterCollection(_base: _base) { isIncluded($0) && self._predicate($0) } } } // @available(*, deprecated, renamed: "LazyFilterSequence.Iterator") public typealias LazyFilterIterator<T: Sequence> = LazyFilterSequence<T>.Iterator // @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use Base.Index") public typealias LazyFilterIndex<Base: Collection> = Base.Index @available(*, deprecated, renamed: "LazyFilterCollection") public typealias LazyFilterBidirectionalCollection<T> = LazyFilterCollection<T> where T : BidirectionalCollection
apache-2.0
595b30309efc43bcc45cba54e175554e
33.026634
113
0.66975
4.216322
false
false
false
false
MartinLasek/vaporberlinBE
Sources/App/Backend/Helper.swift
1
601
final class Helper { static func validateEmail(_ email: String) -> Bool { /// email must at least have 6 characters e.g: [email protected] let minLength = 6 if email.range(of: "@") == nil || email.range(of: ".") == nil || email.count < minLength { return false } return true } static func validatePassword(_ password: String) -> Bool { let minLength = 8 return password.count >= minLength } static func errorJson(status: Int, message: String) throws -> JSON { return try JSON(node: ["status": status, "message": message]) } }
mit
5269b97687e561912ea71a96a7a983dc
23.04
70
0.590682
4.088435
false
false
false
false
exyte/Macaw
Source/animation/layer_animation/FuncBounds.swift
1
2753
func solveEquation(a: Double, b: Double, c: Double) -> (s1: Double?, s2: Double?) { let epsilon: Double = 0.000000001 if abs(a) < epsilon { if abs(b) < epsilon { return (.none, .none) } let s = -c / b if 0.0 < s && s < 1.0 { return (s, .none) } return (.none, .none) } let b2ac = b * b - 4.0 * c * a if b2ac < 0.0 { return (.none, .none) } let sqrtb2ac = b2ac.squareRoot() let s1 = (-b + sqrtb2ac) / (2.0 * a) var r1: Double? = .none if (s1 >= 0.0) && (s1 <= 1.0) { r1 = s1 } let s2 = (-b - sqrtb2ac) / (2.0 * a) var r2: Double? = .none if (s2 >= 0.0) && (s2 <= 1.0) { r2 = s2 } return (r1, r2) } func boundsWithDerivative(p0: Point, p1: Point, p2: Point, p3: Point) -> Rect? { let ax = -3 * p0.x + 9 * p1.x - 9 * p2.x + 3 * p3.x let bx = 6 * p0.x - 12 * p1.x + 6 * p2.x let cx = 3 * p1.x - 3 * p0.x let sx = solveEquation(a: ax, b: bx, c: cx) let ay = -3 * p0.y + 9 * p1.y - 9 * p2.y + 3 * p3.y let by = 6 * p0.y - 12 * p1.y + 6 * p2.y let cy = 3 * p1.y - 3 * p0.y let sy = solveEquation(a: ay, b: by, c: cy) let solutions = [0, 1, sx.s1, sx.s2, sy.s1, sy.s2].compactMap { $0 } var minX: Double? = .none var minY: Double? = .none var maxX: Double? = .none var maxY: Double? = .none for s in solutions { let p = BezierFunc2D(s, p0: p0, p1: p1, p2: p2, p3: p3) if let mx = minX { if mx > p.x { minX = p.x } } else { minX = p.x } if let my = minY { if my > p.y { minY = p.y } } else { minY = p.y } if let mx = maxX { if mx < p.x { maxX = p.x } } else { maxX = p.x } if let my = maxY { if my < p.y { maxY = p.y } } else { maxY = p.y } } if let x = minX, let mx = maxX, let y = minY, let my = maxY { return Rect(x: x, y: y, w: mx - x, h: my - y) } return .none } func boundsForFunc(_ func2d: Func2D) -> Rect { var p = func2d(0.0) var minX = p.x var minY = p.y var maxX = minX var maxY = minY for t in stride(from: 0.0, to: 1.0, by: 0.01) { p = func2d(t) if minX > p.x { minX = p.x } if minY > p.y { minY = p.y } if maxX < p.x { maxX = p.x } if maxY < p.y { maxY = p.y } } return Rect(x: minX, y: minY, w: maxX - minX, h: maxY - minY) }
mit
3b4a3e720b36f3f75ef8cb2dc81bccba
22.134454
83
0.401744
2.780808
false
false
false
false
rdgonzalez85/BTHorizontalPageableView
BTHorizontalPageableView/BTHorizontalPageableView/BTHorizontalPageableView.swift
1
5738
// // BTHorizontalPageableView.swift // // Created by Rodrigo Gonzalez on 1/21/16. // Copyright © 2016 Rodrigo Gonzalez. All rights reserved. // import UIKit /** The BTHorizontalPageableView class defines a rectangular area on the screen and the interfaces for managing the content in that area. It provides support for displaying multiple contents as it were only one. It allow users to scroll within that content by making swiping gestures. To create a BTHorizontalPageableView you can use code like the following: let btScrollView = BTHorizontalPageableView(frame: frame) */ public class BTHorizontalPageableView: UIView, YSSegmentedControlDelegate, UIScrollViewDelegate { //// The Segmented control, used for display the 'titles' bar. var segmentedControl : YSSegmentedControl? { didSet { oldValue?.removeFromSuperview() self.addSubview(segmentedControl!) segmentedControl!.delegate = self segmentedControl?.appearance.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) segmentedControl?.appearance.selectorColor = UIColor.whiteColor() segmentedControl?.appearance.textColor = UIColor.whiteColor() segmentedControl?.appearance.selectedTextColor = UIColor.whiteColor() } } //// Indicates if the 'views' should be placed under the 'titles' bar. var viewsUnderSegmentedControl = true { didSet { if (viewsUnderSegmentedControl != oldValue) { var frame = scrollView.frame if (viewsUnderSegmentedControl) { frame.origin.y -= segmentedHeight } else { frame.origin.y += segmentedHeight } scrollView.frame = frame } } } //// Height of the segmented view. var segmentedHeight : CGFloat = 44.0 //// Y origin point of the segmented view. var segmentedYOrigin : CGFloat = 0.0 //// X origin point of the segmented view. var segmentedXOrigin : CGFloat = 0.0 //// The titles of the segments. var titles : Array<String>? { didSet { self.segmentedControl = YSSegmentedControl( frame: CGRect( x: self.bounds.origin.x + segmentedXOrigin, y: self.bounds.origin.y + segmentedYOrigin, width: self.frame.width, height: segmentedHeight), titles: titles!) } } //// The duration of the animation for scrolling to a new page. var scrollViewPageChangeAnimationDuration : NSTimeInterval = 0.5 //// The container for the views. var scrollView = UIScrollView() /// The containing views. var views : Array<UIView>? { didSet { addViews() } } public override var frame:CGRect { didSet { scrollView.frame = frame } } override init (frame : CGRect) { super.init(frame : frame) addSubview(self.scrollView) setupScrollView() } convenience init () { self.init(frame: CGRect.zero) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addSubview(self.scrollView) } /** Add all the views in 'views' to 'scrollView' */ private func addViews() { var x : CGFloat = 0.0 guard let safeViews = views else { return } for view in safeViews { var frame = view.frame frame.origin.x = x view.frame = frame scrollView.addSubview(view) x += view.frame.width } scrollView.contentSize = CGSize(width: x, height: scrollView.frame.height) } /** Setups 'scrollView'. Assigns scrollView delegate and set the pagingEnabled property to true. */ private func setupScrollView() { scrollView.frame = self.bounds scrollView.pagingEnabled = true scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false } /** Scrolls the 'scrollView' to 'page' page. - Parameter page: The number of page to scroll to. */ private func scrollToPage(page : Int) { guard let safeViews = views where page < safeViews.count else { return } var frame = scrollView.frame frame.origin.x = frame.width * CGFloat(page) UIView.animateWithDuration(scrollViewPageChangeAnimationDuration, animations: { () -> Void in self.scrollView.scrollRectToVisible(frame, animated: false) }) } //MARK: YSSegmentedControlDelegate internal func segmentedControlDidPressedItemAtIndex (segmentedControl: YSSegmentedControl, index: Int) { scrollToPage(index) } //MARK: UIScrollViewDelegate public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let fractionalPage = targetContentOffset.memory.x / scrollView.frame.size.width; let page = ceil(fractionalPage) guard let safeControl = segmentedControl else { return } guard let safeTitles = titles where Int(page) < safeTitles.count && Int(page) >= 0 else { return } safeControl.selectItemAtIndex(Int(page)) } }
mit
2c65870fcb99909670da95d295429dde
30.877778
281
0.602231
5.336744
false
false
false
false
LimCrazy/SwiftProject3.0-Master
SwiftPreject-Master/SwiftPreject-Master/Class/CustomTabBarVC.swift
1
3414
// // CustomTabBarVC.swift // SwiftPreject-Master // // Created by lim on 2016/12/11. // Copyright © 2016年 Lim. All rights reserved. // import UIKit class CustomTabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() -> () { UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.lightGray,NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.blue,NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .highlighted) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.red,NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .selected) tabBar.isTranslucent = false; // let lineView = UIView(frame: CGRect(x: 0, y: 0, width:KScreenWidth, height: 0.5)) // lineView.backgroundColor = UIColor.lightGray // lineView.alpha = 0.8 // tabBar.addSubview(lineView) let homeNavigaiton = YM_Tools.stroyboard(sbName: "Main", identfier: "NavHomeVC") self.configTabbarItem(title: "今日特卖", imgName:"home_tab_home_btn" , nav: homeNavigaiton) let iMessageNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NaviMessageVC") self.configTabbarItem(title: "淘宝特价", imgName:"home_tab_cpc_btn" , nav: iMessageNavigation) let personCenterNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NavPersonCenter") self.configTabbarItem(title: "拼团", imgName:"home_tab_pina_btn" , nav: personCenterNavigation) let breakNewsNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NavBreakNewsVC") self.configTabbarItem(title: "购物车", imgName:"home_tab_point_btn" , nav: breakNewsNavigation) let mineNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NavMineVC") self.configTabbarItem(title: "我的", imgName:"home_tab_personal_btn" , nav: mineNavigation) self.viewControllers = [homeNavigaiton, iMessageNavigation, personCenterNavigation, breakNewsNavigation, mineNavigation] } func configTabbarItem(title:String,imgName:String,nav:UINavigationController) -> () { let img = UIImage(named: imgName)?.withRenderingMode(.alwaysOriginal) let selectImg = UIImage(named: String.init(format: "%@_c",imgName))?.withRenderingMode(.alwaysOriginal) nav.tabBarItem = UITabBarItem.init(title: title, image: img, selectedImage: selectImg) nav.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3) nav.tabBarItem.imageInsets = UIEdgeInsetsMake(7, 0, -7, 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
fbf1e5d972dcb669aa33678d397379a2
44.689189
172
0.683821
4.59375
false
true
false
false
fs/ios-base-swift
Swift-Base/Tools/Views/TextView.swift
1
1651
// // TextView.swift // Tools // // Created by Oleg Gorelov on 30/05/2018. // Copyright © 2018 Flatstack. All rights reserved. // import UIKit @IBDesignable public class TextView: UITextView { // MARK: - Instance Properties @IBInspectable public var bottomOutset: CGFloat { get { return self.touchEdgeOutset.bottom } set { self.touchEdgeOutset.bottom = newValue } } @IBInspectable public var leftOutset: CGFloat { get { return self.touchEdgeOutset.left } set { self.touchEdgeOutset.left = newValue } } @IBInspectable public var rightOutset: CGFloat { get { return self.touchEdgeOutset.right } set { self.touchEdgeOutset.right = newValue } } @IBInspectable public var topOutset: CGFloat { get { return self.touchEdgeOutset.top } set { self.touchEdgeOutset.top = newValue } } public var touchEdgeOutset: UIEdgeInsets = UIEdgeInsets.zero // MARK: - UIControl public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let rect = CGRect(x: self.bounds.origin.x - self.touchEdgeOutset.left, y: self.bounds.origin.y - self.touchEdgeOutset.top, width: self.bounds.width + self.touchEdgeOutset.left + self.touchEdgeOutset.right, height: self.bounds.height + self.touchEdgeOutset.top + self.touchEdgeOutset.bottom) return rect.contains(point) } }
mit
0242338e2a14fae0e11f872e64ffa5ef
23.626866
110
0.585455
4.824561
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Renderers/ChartYAxisRendererHorizontalBarChart.swift
6
11759
// // ChartYAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // 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 !os(OSX) import UIKit #endif open class ChartYAxisRendererHorizontalBarChart: ChartYAxisRenderer { public override init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. open override func computeAxis(yMin: Double, yMax: Double) { guard let yAxis = yAxis else { return } var yMin = yMin, yMax = yMax // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if (viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX) { let p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if (!yAxis.inverted) { yMin = Double(p1.x) yMax = Double(p2.x) } else { yMin = Double(p2.x) yMax = Double(p1.x) } } computeAxisValues(min: yMin, max: yMax) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = yAxis else { return } if (!yAxis.enabled || !yAxis.drawLabelsEnabled) { return } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entries.count) for i in 0 ..< yAxis.entries.count { positions.append(CGPoint(x: CGFloat(yAxis.entries[i]), y: 0.0)) } transformer.pointValuesToPixel(&positions) let lineHeight = yAxis.labelFont.lineHeight let baseYOffset: CGFloat = 2.5 let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var yPos: CGFloat = 0.0 if (dependency == .left) { if (labelPosition == .outsideChart) { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if (labelPosition == .outsideChart) { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels(context: context, fixedPosition: yPos, positions: positions, offset: yAxis.yOffset) } private var _axisLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderAxisLine(context: CGContext) { guard let yAxis = yAxis else { return } if (!yAxis.enabled || !yAxis.drawAxisLineEnabled) { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if (yAxis.axisLineDashLengths != nil) { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if (yAxis.axisDependency == .left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop context.strokeLineSegments(between: _axisLineSegmentsBuffer) } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom context.strokeLineSegments(between: _axisLineSegmentsBuffer) } context.restoreGState() } /// draws the y-labels on the specified x-position open func drawYLabels(context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { guard let yAxis = yAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor for i in 0 ..< yAxis.entryCount { let text = yAxis.getFormattedLabel(i) if (!yAxis.drawTopYLabelEntryEnabled && i >= yAxis.entryCount - 1) { return } ChartUtils.drawText(context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } open override func renderGridLines(context: CGContext) { guard let yAxis = yAxis else { return } if !yAxis.enabled { return } if yAxis.drawGridLinesEnabled { context.saveGState() // pre alloc var position = CGPoint() context.setShouldAntialias(yAxis.gridAntialiasEnabled) context.setStrokeColor(yAxis.gridColor.cgColor) context.setLineWidth(yAxis.gridLineWidth) context.setLineCap(yAxis.gridLineCap) if (yAxis.gridLineDashLengths != nil) { context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } // draw the horizontal grid for i in 0 ..< yAxis.entryCount { position.x = CGFloat(yAxis.entries[i]) position.y = 0.0 transformer.pointValueToPixel(&position) context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } if yAxis.drawZeroLineEnabled { // draw zero line var position = CGPoint(x: 0.0, y: 0.0) transformer.pointValueToPixel(&position) drawZeroLine(context: context, x1: position.x, x2: position.x, y1: viewPortHandler.contentTop, y2: viewPortHandler.contentBottom); } } private var _limitLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderLimitLines(context: CGContext) { guard let yAxis = yAxis else { return } var limitLines = yAxis.limitLines if (limitLines.count <= 0) { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.enabled { continue } position.x = CGFloat(l.limit) position.y = 0.0 position = position.applying(trans) _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if (l.lineDashLengths != nil) { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokeLineSegments(between: _limitLineSegmentsBuffer) let label = l.label // if drawing the limit-value label is enabled if (l.drawLabelEnabled && label.characters.count > 0) { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = l.lineWidth + l.xOffset let yOffset: CGFloat = 2.0 + l.yOffset if (l.labelPosition == .rightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .rightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .leftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } context.restoreGState() } }
mit
80541dbc58da248a2ecf96dc08a21418
32.985549
233
0.535675
5.733301
false
false
false
false
mmllr/CleanTweeter
CleanTweeter/UseCases/NewPost/UI/Presenter/TagAndMentionHighlightingTransformer.swift
1
1306
import Foundation class TagAndMentionHighlightingTransformer : ValueTransformer { let resourceFactory: ResourceFactory init(factory: ResourceFactory) { self.resourceFactory = factory super.init() } override class func transformedValueClass() -> AnyClass { return NSAttributedString.self } override class func allowsReverseTransformation() -> Bool { return false } override func transformedValue(_ value: Any?) -> Any? { guard let transformedValue = value as! String? else { return nil } return transformedValue.findRangesWithPattern("((@|#)([A-Z0-9a-z(é|ë|ê|è|à|â|ä|á|ù|ü|û|ú|ì|ï|î|í)_]+))|(http(s)?://([A-Z0-9a-z._-]*(/)?)*)").reduce(NSMutableAttributedString(string: transformedValue)) { let string = $0 let length = transformedValue.distance(from: $1.lowerBound, to: $1.upperBound) let range = NSMakeRange(transformedValue.distance(from: transformedValue.startIndex, to: $1.lowerBound), length) string.addAttribute(resourceFactory.highlightingAttribute.0, value: self.resourceFactory.highlightingAttribute.1, range: range) return string } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToNSAttributedStringKey(_ input: String) -> NSAttributedString.Key { return NSAttributedString.Key(rawValue: input) }
mit
03b18801fdb2a4951da019544a3bd069
33.864865
204
0.744186
3.644068
false
false
false
false
pixelmaid/piper
Palette-Knife/SocketManager.swift
2
5085
// // SocketManager.swift // PaletteKnife // // Created by JENNIFER MARY JACOBS on 6/27/16. // Copyright © 2016 pixelmaid. All rights reserved. // import Foundation import Starscream //central manager for all requests to web socket class SocketManager: WebSocketDelegate{ var socket = WebSocket(url: NSURL(string: "ws://pure-beach-75578.herokuapp.com/")!, protocols: ["drawing"]) //var socket = WebSocket(url: NSURL(string: "ws://localhost:5000")!, protocols: ["ipad_client"]) var socketEvent = Event<(String,JSON?)>(); var firstConnection = true; var targets = [WebTransmitter](); //objects which can send or recieve data var startTime:NSDate? var dataQueue = [String](); var transmitComplete = true; let dataKey = NSUUID().UUIDString; init(){ socket.delegate = self; } func connect(){ socket.connect() } // MARK: Websocket Delegate Methods. func websocketDidConnect(ws: WebSocket) { print("websocket is connected") //send name of client socket.writeString("{\"name\":\"drawing\"}") if(firstConnection){ socketEvent.raise(("first_connection",nil)); } else{ socketEvent.raise(("connected",nil)); } } func websocketDidDisconnect(ws: WebSocket, error: NSError?) { if let e = error { print("websocket is disconnected: \(e.localizedDescription)") } else { print("websocket disconnected") } socketEvent.raise(("disconnected",nil)); } func websocketDidReceiveMessage(ws: WebSocket, text: String) { if(text == "init_data_recieved" || text == "message recieved"){ if(dataQueue.count>0){ socket.writeString(dataQueue.removeAtIndex(0)); } else{ transmitComplete = true; } } else if(text == "fabricator connected"){ // self.sendFabricationConfigData(); } else{ if let dataFromString = text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { let json = JSON(data: dataFromString) socketEvent.raise(("fabricator_data",json)) } } } func websocketDidReceiveData(ws: WebSocket, data: NSData) { } // MARK: Disconnect Action func disconnect() { if socket.isConnected { socket.disconnect() } else { socket.connect() } } func sendFabricationConfigData(){ var source_string = "[\"VR, .2, .1, .4, 10, .1, .4, .4, 10, 1, .200, 100, .150, 65, 0, 0, .200, .250 \","; source_string += "\"SW, 2, , \"," source_string += "\"FS, C:/Users/ShopBot/Desktop/Debug/\"" source_string+="]" var data = "{\"type\":\"gcode\"," data += "\"data\":"+source_string+"}" socket.writeString(data) } func sendStylusData() { var string = "{\"type\":\"stylus_data\",\"canvas_id\":\""+stylus.id; string += "\",\"stylusData\":{" string+="\"time\":"+String(stylus.getTimeElapsed())+"," string+="\"pressure\":"+String(stylus.force)+"," string+="\"angle\":"+String(stylus.angle)+"," string+="\"penDown\":"+String(stylus.penDown)+"," string+="\"speed\":"+String(stylus.speed)+"," string+="\"position\":{\"x\":"+String(stylus.position.x)+",\"y\":"+String(stylus.position.y)+"}" // string+="\"delta\":{\"x\":"+String(delta.x)+",\"y\":"+String(delta.y)+"}" string+="}}" dataGenerated(string,key:"_") } func initAction(target:WebTransmitter, type:String){ let data = "{\"type\":\""+type+"\",\"id\":\""+target.id+"\",\"name\":\""+target.name+"\"}"; targets.append(target); target.transmitEvent.addHandler(self,handler: SocketManager.dataGenerated, key:dataKey); target.initEvent.addHandler(self,handler: SocketManager.initEvent, key:dataKey); self.dataGenerated(data,key:"_"); if(type == "brush_init"){ let b = target as! Brush b.setupTransition(); } } func initEvent(data:(WebTransmitter,String), key:String){ self.initAction(data.0, type: data.1) } func dataGenerated(data:(String), key:String){ if(transmitComplete){ transmitComplete = false; socket.writeString(data) } else{ dataQueue.append(data) } } func sendBehaviorData(data:(String)){ let string = "{\"type\":\"behavior_data\",\"data\":"+data+"}" if(transmitComplete){ transmitComplete = false; socket.writeString(string) } else{ dataQueue.append(string) } } }
mit
525b48d219d28b2dfe6a23f3b0983bad
29.08284
114
0.531275
4.551477
false
false
false
false
jjochen/photostickers
MessagesExtension/Scenes/Messages App/Application.swift
1
1303
// // MessageApp.swift // PhotoStickers // // Created by Jochen on 29.03.19. // Copyright © 2019 Jochen Pfeiffer. All rights reserved. // import Foundation final class Application { private let stickerService: StickerService private let imageStoreService: ImageStoreService private let stickerRenderService: StickerRenderService init() { #if PREFILL_STICKERS let dataFolderType = DataFolderType.documentsPrefilled(subfolder: "UITests") #else let dataFolderType = DataFolderType.appGroup #endif let dataFolder = DataFolderService(type: dataFolderType) imageStoreService = ImageStoreService(url: dataFolder.imagesURL) stickerService = StickerService(realmType: .onDisk(url: dataFolder.realmURL), imageStoreService: imageStoreService) stickerRenderService = StickerRenderService() } lazy var appServices = { AppServices(stickerService: self.stickerService, imageStoreService: self.imageStoreService, stickerRenderService: self.stickerRenderService) }() } struct AppServices: HasStickerService, HasImageStoreService, HasStickerRenderService { let stickerService: StickerService let imageStoreService: ImageStoreService let stickerRenderService: StickerRenderService }
mit
75e1ddec21036c7aea21f228e5289695
33.263158
148
0.745776
5.007692
false
false
false
false
abertelrud/swift-package-manager
Sources/SPMTestSupport/SwiftPMProduct.swift
2
1298
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TSCBasic @_exported import TSCTestSupport public enum SwiftPMProduct: Product { case SwiftBuild case SwiftPackage case SwiftPackageRegistry case SwiftTest case SwiftRun case XCTestHelper /// Executable name. public var exec: RelativePath { switch self { case .SwiftBuild: return RelativePath("swift-build") case .SwiftPackage: return RelativePath("swift-package") case .SwiftPackageRegistry: return RelativePath("swift-package-registry") case .SwiftTest: return RelativePath("swift-test") case .SwiftRun: return RelativePath("swift-run") case .XCTestHelper: return RelativePath("swiftpm-xctest-helper") } } }
apache-2.0
a0a8c02f331be9fbe2f59c2de702aefe
29.904762
80
0.581664
5.430962
false
true
false
false
SwiftStudies/OysterKit
Sources/STLR/Generated/Extensions/STLR+CustomStringConvertable.swift
1
4474
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation extension STLR : CustomStringConvertible { public var description: Swift.String { let result = TextFile(grammar.scopeName+".STLR") result.print("grammar \(grammar.scopeName)","") for module in grammar.modules ?? [] { result.print("import \(module.moduleName)") } result.print("") for rule in grammar.rules { result.print(rule.description) } return result.content } } extension STLR.Rule : CustomStringConvertible{ public var description : String { return "\(identifier)\(tokenType == nil ? "" : "\(tokenType!)") \(assignmentOperators.rawValue) \(expression)" } } extension STLR.Expression : CustomStringConvertible { public var description : String { switch self { case .element(let element): return element.description case .sequence(let sequence): return sequence.map({$0.description}).joined(separator: " ") case .choice(let choices): return choices.map({$0.description}).joined(separator: " | ") } } } extension STLR.Element : CustomStringConvertible { public var description : String { let quantity = quantifier?.rawValue ?? "" let allAttribs = annotations?.map({"\($0)"}).joined(separator: " ") ?? "" let prefix = allAttribs+(allAttribs.isEmpty ? "" : " ")+[lookahead,negated,transient,void].compactMap({$0}).joined(separator: "") var core : String if let group = group { core = "\(prefix)(\(group.expression))\(quantity)" } else if let identifier = identifier { core = "\(prefix)\(identifier)\(quantity)" } else if let terminal = terminal { core = "\(prefix)\(terminal.description)\(quantity)" } else { core = "!!UNKNOWN ELEMENT TYPE!!" } return core } } extension STLR.Annotation : CustomStringConvertible { public var description : String { return "@\(label)"+(literal == nil ? "" : "(\(literal!))") } } extension STLR.Literal : CustomStringConvertible { public var description : String { switch self { case .boolean(let value): return "\(value)" case .number(let value): return "\(value)" case .string(let value): return value.stringBody.debugDescription } } } extension STLR.Terminal : CustomStringConvertible { public var description : String { switch self { case .endOfFile(_): return ".endOfFile" case .characterSet(let characterSet): return ".\(characterSet.characterSetName)" case .regex(let regex): return "/\(regex)/" case .terminalString(let terminalString): return terminalString.terminalBody.debugDescription case .characterRange(let characterRange): return "\(characterRange[0].terminalBody)...\(characterRange[0].terminalBody)" } } }
bsd-2-clause
87ca12dfea49570d054cb7881a5eb35c
37.239316
137
0.639473
4.960089
false
false
false
false
manticarodrigo/FieldTextView
FieldTextView.swift
1
1576
// // FieldTextView.swift // Edumate // // Created by Rodrigo Mantica on 12/9/16. // Copyright © 2016 Rodrigo Mantica. All rights reserved. // import UIKit class FieldTextView : UITextView, UITextViewDelegate { override var contentSize: CGSize { didSet { var topCorrection = (self.bounds.size.height - self.contentSize.height * self.zoomScale) / 2.0 topCorrection = max(0, topCorrection) self.contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0) } } let placeholderLabel = UILabel() var placeholder: String? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupView() } override func layoutSubviews() { super.layoutSubviews() self.setupView() } private func setupView() { self.placeholderLabel.text = self.placeholder ?? "Tap to start typing..." self.placeholderLabel.textAlignment = self.textAlignment self.placeholderLabel.font = self.font self.placeholderLabel.sizeToFit() var topCorrection = (self.bounds.size.height - self.contentSize.height * self.zoomScale) / 2.0 topCorrection = max(0, topCorrection) self.placeholderLabel.frame = CGRect(x: 0, y: -topCorrection, width: self.frame.width, height: self.frame.height) self.placeholderLabel.textColor = UIColor(white: 0, alpha: 0.25) self.placeholderLabel.isHidden = !self.text.isEmpty self.addSubview(self.placeholderLabel) } }
apache-2.0
3702506ea6664a3fdda6cef533299337
32.510638
121
0.652063
4.399441
false
false
false
false
sf-arte/Spica
Spica/Flickr.swift
1
8409
// // Flickr.swift // Spica // // Created by Suita Fujino on 2016/09/28. // Copyright © 2016年 ARTE Co., Ltd. All rights reserved. // import OAuthSwift import SwiftyJSON /** FlickrのAPIを呼ぶクラス */ class Flickr { // MARK: 定数 /// Flickr APIのURL private let apiURL = "https://api.flickr.com/services/rest" /// データ保存用のキー private enum KeyForUserDefaults : String { case oauthToken = "OAuthToken" case oauthTokenSecret = "OAuthTokenSecret" } // MARK: - 構造体 /// Flickrから返ってきたトークン private struct OAuthToken { let token : String let secret : String } /// OAuth認証に必要なパラメータ struct OAuthParams { let consumerKey : String let consumerSecret: String let requestTokenURL = "https://www.flickr.com/services/oauth/request_token" let authorizeURL = "https://www.flickr.com/services/oauth/authorize" let accessTokenURL = "https://www.flickr.com/services/oauth/access_token" init(key: String, secret: String) { consumerKey = key consumerSecret = secret } init?(path: String) { do { let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8) let lines = text.components(separatedBy: CharacterSet.newlines) consumerKey = lines[0] consumerSecret = lines[1] } catch (let error) { log?.error(error) return nil } } } // MARK: - プロパティ private let params : OAuthParams private var oauthSwift : OAuth1Swift private var oauthToken : OAuthToken? { didSet { guard let oauthToken = oauthToken else { return } let defaults = UserDefaults.standard defaults.set(oauthToken.token, forKey: KeyForUserDefaults.oauthToken.rawValue) defaults.set(oauthToken.secret, forKey: KeyForUserDefaults.oauthTokenSecret.rawValue) } } // MARK: - Lifecycle init(params: OAuthParams, loadsToken : Bool = true) { self.params = params oauthSwift = OAuth1Swift( consumerKey: params.consumerKey, consumerSecret: params.consumerSecret, requestTokenUrl: params.requestTokenURL, authorizeUrl: params.authorizeURL, accessTokenUrl: params.accessTokenURL ) oauthToken = nil let defaults = UserDefaults.standard // OAuth Tokenのデータがすでにあればそれを読み込み if let token = defaults.object(forKey: KeyForUserDefaults.oauthToken.rawValue) as? String, let secret = defaults.object(forKey: KeyForUserDefaults.oauthTokenSecret.rawValue) as? String, loadsToken { oauthSwift.client = OAuthSwiftClient( consumerKey: params.consumerKey, consumerSecret: params.consumerSecret, oauthToken: token, oauthTokenSecret: secret, version: .oauth1 ) oauthToken = OAuthToken(token: token, secret: secret) } } // MARK: - メソッド /// flickrのユーザーアカウントを表示して、アプリの認証をする。認証を既にしていた場合は処理を行わない。 /// 成功した場合、consumer keyとconsumer secretを利用してOAuth tokenを取得する。 func authorize() { if oauthToken != nil { return } oauthSwift.authorize( withCallbackURL: URL(string: "Spica://oauth-callback/flickr")!, success: { [weak self] credential, response, parameters in self?.oauthToken = OAuthToken(token: credential.oauthToken, secret: credential.oauthTokenSecret) }, failure: { [weak self] error in self?.onAuthorizationFailed(error: error) } ) } /// 認証失敗時の処理 /// /// - parameter error: エラー内容 func onAuthorizationFailed(error: OAuthSwiftError) { log?.error(error.localizedDescription) } /// 指定された座標周辺の写真をJSON形式で取得し、パースする。パースしたデータはPhotoクラスの配列に格納される。 /// /// TODO: 失敗時の処理。未認証時認証。 /// /// - parameter leftBottom: 写真を検索する範囲の左下の座標 /// - parameter rightTop: 写真を検索する範囲の右上の座標 /// - parameter count: 1回に取得する件数。500件まで /// - parameter handler: パースしたデータに対して実行する処理 /// - parameter text: 検索する文字列 func getPhotos(leftBottom: Coordinates, rightTop: Coordinates, count: Int, text: String?, handler: @escaping ([Photo]) -> ()) { // 東経180度線を跨ぐ時の処理。180度線で2つに分割する if leftBottom.longitude > rightTop.longitude { let leftLongitudeDifference = 180.0 - leftBottom.longitude let rightLongitudeDifference = rightTop.longitude + 180.0 let leftCount = Int(Double(count) * leftLongitudeDifference / (leftLongitudeDifference + rightLongitudeDifference)) let rightCount = count - leftCount getPhotos( leftBottom: leftBottom, rightTop: Coordinates(latitude: rightTop.latitude, longitude: 180.0), count: leftCount, text: text ) { [weak self] leftPhotos in self?.getPhotos( leftBottom: Coordinates(latitude: leftBottom.latitude, longitude: -180.0), rightTop: rightTop, count: rightCount, text: text ) { rightPhotos in handler(leftPhotos + rightPhotos) } } return } var parameters : OAuthSwift.Parameters = [ "api_key" : params.consumerKey, "format" : "json", "bbox" : "\(leftBottom.longitude),\(leftBottom.latitude),\(rightTop.longitude),\(rightTop.latitude)", "method" : "flickr.photos.search", "sort" : "interestingness-desc", // not working "extras" : "geo,owner_name,url_o,url_sq,url_l", "per_page" : count, "nojsoncallback" : 1 ] if let text = text, text != "" { parameters["text"] = text } // UIテスト時はモックサーバーを使う let url = ProcessInfo().arguments.index(of: "--mockserver") == nil ? apiURL : "http://127.0.0.1:4567/rest/" oauthSwift.client.get(url, parameters: parameters, headers: nil, success: { response in let json = JSON(data: response.data) let status = json["stat"].stringValue if status != "ok" { log?.error(json["message"].stringValue) } handler(json["photos"]["photo"].arrayValue.map{ Flickr.decode(from: $0) }) }, failure: { error in log?.error(error) } ) } } extension Flickr { static func decode(from json: JSON) -> Photo { let id = json["id"].intValue let owner = json["owner"].stringValue let ownerName = json["ownername"].stringValue let title = json["title"].stringValue let iconURL = json["url_sq"].stringValue let largeURL = json["url_l"].stringValue let originalURL = json["url_o"].stringValue let coordinates = Coordinates(latitude: json["latitude"].doubleValue, longitude: json["longitude"].doubleValue) return Photo( id: id, owner: owner, ownerName: ownerName, iconURL: iconURL, largeURL: largeURL, originalURL: originalURL, photoTitle: title, coordinate: coordinates ) } }
mit
1b9180b1852aaa9c880831a01c942019
32.670996
131
0.559913
4.657485
false
false
false
false
Legoless/iOS-Course
2015-1/Lesson13/Gamebox/Gamebox/GameManager.swift
3
1607
// // GameManager.swift // Gamebox // // Created by Dal Rupnik on 21/10/15. // Copyright © 2015 Unified Sense. All rights reserved. // import Foundation class GameManager : NSObject { static let shared = GameManager() var games : [Game]? var allGames : [Game] { if games == nil { loadAllGames() } return games! } func addGame (game : Game) { if games == nil { loadAllGames() } games!.append(game) NSNotificationCenter.defaultCenter().postNotificationName("NewGame", object: game) } func save () { guard let games = games else { return } var serializedGames = [AnyObject]() for game in games { serializedGames.append(game.toDictionary()) } NSUserDefaults.standardUserDefaults().setObject(serializedGames, forKey: "AllGames") NSUserDefaults.standardUserDefaults().synchronize() } func loadAllGames () { self.games = loadGames() } private func loadGames () -> [Game] { let serializedGames = NSUserDefaults.standardUserDefaults().objectForKey("AllGames") var games = [Game]() if let serializedGames = serializedGames as? [[String : AnyObject]] { for game in serializedGames { let newGame = Game(dictionary: game) games.append(newGame) } } return games } }
mit
c0a1b83b90a2c77d13e2e4c5a96f5421
21.957143
92
0.528643
5.30033
false
false
false
false
Dynamit/DTCalendarView-iOS
Example/DTCalendarView/ViewController.swift
1
5543
// // ViewController.swift // DTCalendarView // // Created by timle8n1-dynamit on 06/14/2017. // Copyright (c) 2017 timle8n1-dynamit. All rights reserved. // import UIKit import DTCalendarView class ViewController: UIViewController { fileprivate let now = Date() fileprivate let calendar = Calendar.current @IBOutlet private var calendarView: DTCalendarView! { didSet { calendarView.delegate = self calendarView.displayEndDate = Date(timeIntervalSinceNow: 60 * 60 * 24 * 30 * 12 * 2) calendarView.previewDaysInPreviousAndMonth = true calendarView.paginateMonths = true } } fileprivate let monthYearFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .none formatter.dateFormat = "MMMM YYYY" return formatter }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { let now = Date() calendarView.selectionStartDate = now calendarView.selectionEndDate = now.addingTimeInterval(60 * 60 * 24 * 5) calendarView.scrollTo(month: calendarView.displayEndDate, animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func currentDate(matchesMonthAndYearOf date: Date) -> Bool { let nowMonth = calendar.component(.month, from: now) let nowYear = calendar.component(.year, from: now) let askMonth = calendar.component(.month, from: date) let askYear = calendar.component(.year, from: date) if nowMonth == askMonth && nowYear == askYear { return true } return false } } extension ViewController: DTCalendarViewDelegate { func calendarView(_ calendarView: DTCalendarView, dragFromDate fromDate: Date, toDate: Date) { if let nowDayOfYear = calendar.ordinality(of: .day, in: .year, for: now), let selectDayOfYear = calendar.ordinality(of :.day, in: .year, for: toDate), selectDayOfYear <= nowDayOfYear { return } if let startDate = calendarView.selectionStartDate, fromDate == startDate { if let endDate = calendarView.selectionEndDate { if toDate < endDate { calendarView.selectionStartDate = toDate } } else { calendarView.selectionStartDate = toDate } } else if let endDate = calendarView.selectionEndDate, fromDate == endDate { if let startDate = calendarView.selectionStartDate { if toDate > startDate { calendarView.selectionEndDate = toDate } } else { calendarView.selectionEndDate = toDate } } } func calendarView(_ calendarView: DTCalendarView, viewForMonth month: Date) -> UIView { let label = UILabel() label.text = monthYearFormatter.string(from: month) label.textColor = UIColor.black label.textAlignment = .center label.backgroundColor = UIColor.white return label } func calendarView(_ calendarView: DTCalendarView, disabledDaysInMonth month: Date) -> [Int]? { if currentDate(matchesMonthAndYearOf: month) { var disabledDays = [Int]() let nowDay = calendar.component(.day, from: now) for day in 1 ... nowDay { disabledDays.append(day) } return disabledDays } return nil } func calendarView(_ calendarView: DTCalendarView, didSelectDate date: Date) { if let nowDayOfYear = calendar.ordinality(of: .day, in: .year, for: now), let selectDayOfYear = calendar.ordinality(of :.day, in: .year, for: date), calendar.component(.year, from: now) == calendar.component(.year, from: date), selectDayOfYear <= nowDayOfYear { return } if calendarView.selectionStartDate == nil { calendarView.selectionStartDate = date } else if calendarView.selectionEndDate == nil { if let startDateValue = calendarView.selectionStartDate { if date <= startDateValue { calendarView.selectionStartDate = date } else { calendarView.selectionEndDate = date } } } else { calendarView.selectionStartDate = date calendarView.selectionEndDate = nil } } func calendarViewHeightForWeekRows(_ calendarView: DTCalendarView) -> CGFloat { return 60 } func calendarViewHeightForWeekdayLabelRow(_ calendarView: DTCalendarView) -> CGFloat { return 50 } func calendarViewHeightForMonthView(_ calendarView: DTCalendarView) -> CGFloat { return 60 } }
mit
162681ae45772faa329a92b6d0e21e9c
30.494318
98
0.578928
5.570854
false
false
false
false
codefellows/sea-c24-iOS-F2
Day 5-8 AutoLayout:Camera:plist:Archiver/AutoLayout/Person.swift
1
1086
// // Person.swift // AutoLayout // // Created by Bradley Johnson on 11/10/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import Foundation import UIKit class Person : NSObject, NSCoding { var firstName : String var lastName : String var image : UIImage? init (first : String) { self.firstName = first self.lastName = "Doe" } required init(coder aDecoder: NSCoder) { self.firstName = aDecoder.decodeObjectForKey("firstName") as String self.lastName = aDecoder.decodeObjectForKey("lastName") as String if let decodedImage = aDecoder.decodeObjectForKey("image") as? UIImage { self.image = decodedImage } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.firstName, forKey: "firstName") aCoder.encodeObject(self.lastName, forKey: "lastName") if self.image != nil { aCoder.encodeObject(self.image!, forKey: "image") } else { aCoder.encodeObject(nil, forKey: "image") } } }
mit
ab100a9cfb3913772e45a2c2666920ce
25.487805
80
0.622468
4.432653
false
false
false
false
thehorbach/instagram-clone
Pods/SwiftKeychainWrapper/SwiftKeychainWrapper/KeychainItemAccessibility.swift
1
6158
// // KeychainOptions.swift // SwiftKeychainWrapper // // Created by James Blair on 4/24/16. // Copyright © 2016 Jason Rendel. All rights reserved. // // The MIT License (MIT) // // 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 protocol KeychainAttrRepresentable { var keychainAttrValue: CFString { get } } // MARK: - KeychainItemAccessibility public enum KeychainItemAccessibility { /** The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups. */ @available(iOS 4, *) case afterFirstUnlock /** The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ @available(iOS 4, *) case afterFirstUnlockThisDeviceOnly /** The data in the keychain item can always be accessed regardless of whether the device is locked. This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups. */ @available(iOS 4, *) case always /** The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted. */ @available(iOS 8, *) case whenPasscodeSetThisDeviceOnly /** The data in the keychain item can always be accessed regardless of whether the device is locked. This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ @available(iOS 4, *) case alwaysThisDeviceOnly /** The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups. This is the default value for keychain items added without explicitly setting an accessibility constant. */ @available(iOS 4, *) case whenUnlocked /** The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ @available(iOS 4, *) case whenUnlockedThisDeviceOnly static func accessibilityForAttributeValue(_ keychainAttrValue: CFString) -> KeychainItemAccessibility? { for (key, value) in keychainItemAccessibilityLookup { if value == keychainAttrValue { return key } } return nil } } private let keychainItemAccessibilityLookup: [KeychainItemAccessibility:CFString] = { var lookup: [KeychainItemAccessibility:CFString] = [ .afterFirstUnlock: kSecAttrAccessibleAfterFirstUnlock, .afterFirstUnlockThisDeviceOnly: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, .always: kSecAttrAccessibleAlways, .alwaysThisDeviceOnly : kSecAttrAccessibleAlwaysThisDeviceOnly, .whenUnlocked: kSecAttrAccessibleWhenUnlocked, .whenUnlockedThisDeviceOnly: kSecAttrAccessibleWhenUnlockedThisDeviceOnly ] // INFO: While this framework only supports iOS 8 and up, the files themselves can be pulled directly into an iOS 7 project and work fine as long as this #available check is in place. Unfortunately, this also generates a warning in the framework project for now. if #available(iOSApplicationExtension 8, *) { lookup[.whenPasscodeSetThisDeviceOnly] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly } return lookup }() extension KeychainItemAccessibility : KeychainAttrRepresentable { internal var keychainAttrValue: CFString { return keychainItemAccessibilityLookup[self]! } }
mit
cae47754db65166efae510d9122570ce
47.480315
380
0.730388
5.303187
false
false
false
false
soapyigu/LeetCode_Swift
DFS/CombinationSum.swift
1
953
/** * Question Link: https://leetcode.com/problems/combination-sum/ * Primary idea: Classic Depth-first Search * * Time Complexity: O(n^n), Space Complexity: O(2^n - 1) * */ class CombinationSum { func combinationSum(candidates: [Int], _ target: Int) -> [[Int]] { var res = [[Int]]() var path = [Int]() _dfs(candidates.sorted(by: <), target, &res, &path, 0) return res } private func _dfs(candidates: [Int], _ target: Int, inout _ res: [[Int]], inout _ path: [Int], _ index: Int) { if target == 0 { res.append(Array(path)) return } for i in index..<candidates.count { guard candidates[i] <= target else { break } path.append(candidates[i]) _dfs(candidates, target - candidates[i], &res, &path, i) path.removeLast() } } }
mit
3a11c8060eb6e6af84aa84ef4b84d49b
26.257143
114
0.498426
3.905738
false
false
false
false
coolmacmaniac/swift-ios
rw/BullsEye/BullsEye/ViewController.swift
1
3219
// // ViewController.swift // BullsEye // // Created by Sourabh on 11/03/18. // Copyright © 2018 Home. All rights reserved. // import UIKit class ViewController: UIViewController { var targetValue = 0 var currentValue = 0 var score = 0 var round = 0 @IBOutlet weak var slider: UISlider! @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var roundLabel: UILabel! //Drongo@123 override func viewDidLoad() { super.viewDidLoad() customizeSlider() startNewGame() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderMoved(_ slider: UISlider) { currentValue = lroundf(slider.value) //print("Val: \(slider.value), Int: \(Int(slider.value)), lroundf: \(lroundf(slider.value))") } @IBAction func showAlert(_ sender: UIButton) { let difference = abs(targetValue - currentValue) var points = 100 - difference // bonus points if difference == 0 { points += 100 // 100 extra bonus } else if difference == 1 { points += 50 // 50 extra bonus } // compute overall score score += points let title: String if difference == 0 { title = "Perfect!!" } else if difference < 5 { title = "You almost had it!" } else if difference < 10 { title = "Pretty good!" } else { title = "Oh! that wasn't close..." } let alert = UIAlertController( title: title, message: "You scored \(points) points", preferredStyle: .alert) let action = UIAlertAction( title: "Close", style: .default, handler: popupHandler) alert.addAction(action) self.present(alert, animated: true, completion: nil) } @IBAction func startNewGame() { currentValue = 0 score = 0 round = 0 startNewRound() } // MARK: - func customizeSlider() { let thumbImageNormal = #imageLiteral(resourceName: "SliderThumb-Normal") // UIImage(named: "SliderThumb-Normal") slider.setThumbImage(thumbImageNormal, for: .normal) let thumbImageHighlighted = #imageLiteral(resourceName: "SliderThumb-Highlighted") // UIImage(named: "SliderThumb-Highlighted") slider.setThumbImage(thumbImageHighlighted, for: .highlighted) let insets = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14) let trackLeftImage = #imageLiteral(resourceName: "SliderTrackLeft") // UIImage(named: "SliderTrackLeft") let trackLeftResizable = trackLeftImage.resizableImage(withCapInsets: insets) slider.setMinimumTrackImage(trackLeftResizable, for: .normal) let trackRightImage = #imageLiteral(resourceName: "SliderTrackRight") // UIImage(named: "SliderTrackRight") let trackRightResizable = trackRightImage.resizableImage(withCapInsets: insets) slider.setMaximumTrackImage(trackRightResizable, for: .normal) } func popupHandler(_ action: UIAlertAction) { startNewRound() } func updateLabels() { targetLabel.text = String(targetValue) scoreLabel.text = String(score) roundLabel.text = String(round) } func startNewRound() { round += 1 targetValue = 1 + Int(arc4random_uniform(100)) currentValue = 50 slider.value = Float(currentValue) updateLabels() } }
gpl-3.0
936942cd012aa1c248ad609d14b4980d
23.945736
129
0.699814
3.698851
false
false
false
false
ostatnicky/kancional-ios
Cancional/UI/Song Detail/AppereanceThemeButton.swift
1
1524
// // AppereanceColorButton.swift // Cancional // // Created by Jiri Ostatnicky on 11/06/2017. // Copyright © 2017 Jiri Ostatnicky. All rights reserved. // import UIKit class AppearanceThemeButton: UIButton { @objc var theme: AppearanceTheme? override var isSelected: Bool { didSet { if isSelected { setSelectedBorder() } else { setNormalBorder() } } } override var isHighlighted: Bool { didSet { isSelected = !isHighlighted } } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() setupUI() } func configure(theme: AppearanceTheme) { self.theme = theme updateUI() } } private extension AppearanceThemeButton { func setupUI() { clipsToBounds = true layer.cornerRadius = 44/2 setNormalBorder() } func updateUI() { guard let theme = theme else { return } let color = UIColor(hexString: theme.backgroundColor) backgroundColor = color setBackgroundImage(UIImage.init(color: color), for: .normal) } func setNormalBorder() { layer.borderColor = UIColor.black.withAlphaComponent(0.3).cgColor layer.borderWidth = 0.5 } func setSelectedBorder() { layer.borderColor = UIColor.Cancional.tintColor().cgColor layer.borderWidth = 6 } }
mit
26c8653f9f8b55d2e7d906486bae0b77
20.757143
73
0.568615
4.789308
false
false
false
false
safx/MioDashboard-swift
MioDashboard-swift WatchKit Extension/InterfaceController.swift
1
5741
// // InterfaceController.swift // MioDashboard-swift WatchKit Extension // // Created by Safx Developer on 2015/05/17. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import WatchKit import Foundation import IIJMioKit class TableRow : NSObject { @IBOutlet weak var hddServiceCode: WKInterfaceLabel! @IBOutlet weak var couponTotal: WKInterfaceLabel! @IBOutlet weak var couponUsedToday: WKInterfaceLabel! var model: MIOCouponInfo_s! { didSet { let f = createByteCountFormatter() hddServiceCode.setText(model!.hddServiceCode) couponTotal.setText(f.stringFromByteCount(Int64(model!.totalCouponVolume) * 1000 * 1000)) couponUsedToday.setText(f.stringFromByteCount(Int64(model!.couponUsedToday) * 1000 * 1000)) } } } class InterfaceController: WKInterfaceController { @IBOutlet weak var table: WKInterfaceTable! @IBOutlet weak var additionalInfo: WKInterfaceLabel! private var model: [MIOCouponInfo_s] = [] private var lastUpdated: NSDate? override func awakeWithContext(context: AnyObject?) { MIORestClient.sharedClient.setUp() super.awakeWithContext(context) restoreSavedInfo { m, date in self.model = m self.lastUpdated = date self.setTableData(model) } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() if let d = lastUpdated where NSDate().timeIntervalSinceDate(d) < 300 { return } loadTableData() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? { precondition(segueIdentifier == "detail") return rowIndex < model.count ? self.model[rowIndex] : nil } private func loadTableData() { let client = MIORestClient.sharedClient if !client.authorized { let status = client.loadAccessToken() if status != .Success { additionalInfo.setText(status.rawValue) return } } client.getMergedInfo { [weak self] (response, error) -> Void in if let e = error { self?.additionalInfo.setText("Error: \(e.code) \(e.description)") } else if let r = response { if r.returnCode != "OK" { self?.additionalInfo.setText(r.returnCode) } else { if let s = self { let m = r.couponInfo!.map{ MIOCouponInfo_s(info: $0) } s.setTableData(m) s.additionalInfo.setText("") s.lastUpdated = NSDate() saveInfo(m, lastUpdated: s.lastUpdated!) } } } else { self?.additionalInfo.setText("No response") } } } private func setTableData(cs: [MIOCouponInfo_s]) { if cs.isEmpty { self.additionalInfo.setText("No data") return } table.setNumberOfRows(cs.count, withRowType: "default") for (i, c) in cs.enumerate() { if let row = table.rowControllerAtIndex(i) as? TableRow { row.model = c } } model = cs } // TODO: use other RowType private func setErrorData(reason: String) { table.setNumberOfRows(1, withRowType: "default") if let row = table.rowControllerAtIndex(0) as? TableRow { row.hddServiceCode.setText(reason) row.couponTotal.setText("Error") row.couponUsedToday.setText("") } } // TODO: use other RowType private func setErrorData(reason: NSError) { table.setNumberOfRows(1, withRowType: "default") if let row = table.rowControllerAtIndex(0) as? TableRow { row.hddServiceCode.setText("\(reason.domain)") row.couponTotal.setText("\(reason.code)") row.couponUsedToday.setText("\(reason.description)") } } } class DetailTableRow : NSObject { @IBOutlet weak var number: WKInterfaceLabel! @IBOutlet weak var couponUsedToday: WKInterfaceLabel! var model: MIOCouponHdoInfo_s! { didSet { let f = createByteCountFormatter() number.setText(model!.phoneNumber) couponUsedToday.setText(f.stringFromByteCount(Int64(model!.couponUsedToday) * 1000 * 1000)) } } } class DetailInterfaceController: WKInterfaceController { @IBOutlet weak var table: WKInterfaceTable! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) if let m = context as? MIOCouponInfo_s { setTableData(m) } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } private func setTableData(model: MIOCouponInfo_s) { let cs = model.hdoInfo table.setNumberOfRows(cs.count, withRowType: "default") for (i, c) in cs.enumerate() { if let row = table.rowControllerAtIndex(i) as? DetailTableRow { row.model = c } } } }
mit
826ecca945253815261b4f525139d4ae
30.883333
136
0.60115
4.851226
false
false
false
false
seeRead/roundware-ios-framework-v2
Pod/Classes/RWFrameworkHTTP.swift
1
26066
// // RWFrameworkHTTP.swift // RWFramework // // Created by Joe Zobkiw on 2/6/15. // Copyright (c) 2015 Roundware. All rights reserved. // import Foundation import MobileCoreServices extension RWFramework: URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate /*, NSURLSessionDownloadDelegate */ { func httpPostUsers(device_id: String, client_type: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postUsersURL()) { let postData = ["device_id": device_id, "client_type": client_type] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postUsersURL unable to be created."]) completion(nil, error) } } func httpPostSessions(project_id: String, timezone: String, client_system: String, language: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postSessionsURL()) { let postData = ["project_id": project_id, "timezone": timezone, "client_system": client_system, "language": language] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postSessionsURL unable to be created."]) completion(nil, error) } } func httpGetProjectsId(project_id: String, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getProjectsIdURL(project_id: project_id, session_id: session_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getProjectsIdURL unable to be created."]) completion(nil, error) } } func httpGetProjectsIdTags(project_id: String, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getProjectsIdTagsURL(project_id: project_id, session_id: session_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getProjectsIdTagsURL unable to be created."]) completion(nil, error) } } func httpGetProjectsIdUIGroups(project_id: String, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getProjectsIdUIGroupsURL(project_id: project_id, session_id: session_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getProjectsIdUIGroupsURL unable to be created."]) completion(nil, error) } } func httpPostStreams(session_id: String, latitude: String?, longitude: String?, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsURL()) { var postData = ["session_id": session_id] if let ourLatitude = latitude, let ourLongitude = longitude { postData["latitude"] = ourLatitude postData["longitude"] = ourLongitude } postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsURL unable to be created."]) completion(nil, error) } } func httpPatchStreamsId(stream_id: String, latitude: String, longitude: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.patchStreamsIdURL(stream_id: stream_id)) { let postData = ["latitude": latitude, "longitude": longitude] patchDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "patchStreamsIdURL unable to be created."]) completion(nil, error) } } func httpPatchStreamsId(stream_id: String, tag_ids: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.patchStreamsIdURL(stream_id: stream_id)) { let postData = ["tag_ids": tag_ids] patchDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "patchStreamsIdURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdHeartbeat(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdHeartbeatURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdHeartbeatURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdSkip(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdSkipURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdSkipURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdPlayAsset(stream_id: String, asset_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdPlayAssetURL(stream_id: stream_id)) { let postData = ["asset_id": asset_id] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdPlayAssetURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdReplayAsset(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdReplayAssetURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdReplayAssetURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdPause(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdPauseURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdPauseURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdResume(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdResumeURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdResumeURL unable to be created."]) completion(nil, error) } } func httpGetStreamsIdCurrent(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getStreamsIdCurrentURL(stream_id: stream_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getStreamsIdCurrentURL unable to be created."]) completion(nil, error) } } func httpPostEnvelopes(session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postEnvelopesURL()) { let postData = ["session_id": session_id] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postEnvelopesURL unable to be created."]) completion(nil, error) } } func httpPatchEnvelopesId(media: Media, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.patchEnvelopesIdURL(envelope_id: media.envelopeID.stringValue)) { let serverMediaType = mapMediaTypeToServerMediaType(mediaType: media.mediaType) let postData = ["session_id": session_id, "media_type": serverMediaType.rawValue, "latitude": media.latitude.stringValue, "longitude": media.longitude.stringValue, "tag_ids": media.tagIDs, "description": media.desc] patchFileAndDataToURL(url: url, filePath: media.string, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "httpPatchEnvelopesId unable to be created."]) completion(nil, error) } } func httpGetAssets(dict: [String:String], completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getAssetsURL(dict: dict)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "httpGetAssets unable to be created."]) completion(nil, error) } } func httpGetAssetsId(asset_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getAssetsIdURL(asset_id: asset_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "httpGetAssetsId unable to be created."]) completion(nil, error) } } func httpPostAssetsIdVotes(asset_id: String, session_id: String, vote_type: String, value: NSNumber = 0, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postAssetsIdVotesURL(asset_id: asset_id)) { let postData = ["session_id": session_id, "vote_type": vote_type, "value": value.stringValue] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postAssetsIdVotesURL unable to be created."]) completion(nil, error) } } func httpGetAssetsIdVotes(asset_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getAssetsIdVotesURL(asset_id: asset_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getAssetsIdVotesURL unable to be created."]) completion(nil, error) } } func httpPostEvents(session_id: String, event_type: String, data: String?, latitude: String, longitude: String, client_time: String, tag_ids: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postEventsURL()) { let postData = ["session_id": session_id, "event_type": event_type, "data": data ?? "", "latitude": latitude, "longitude": longitude, "client_time": client_time, "tag_ids": tag_ids] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postEventsURL unable to be created."]) completion(nil, error) } } // MARK: - Generic functions // Upload file and load data via PATCH and return in completion with or without error func patchFileAndDataToURL(url: NSURL, filePath: String, postData: Dictionary<String,String>, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { // println(object: "patchFileAndDataToURL: " + url.absoluteString + " filePath = " + filePath + " postData = " + postData.description) // Multipart/form-data boundary func makeBoundary() -> String { let uuid = NSUUID().uuidString return "Boundary-\(uuid)" } let boundary = makeBoundary() // Mime type var mimeType: String { get { let pathExtension = (filePath as NSString).pathExtension let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil) let str = UTTypeCopyPreferredTagWithClass(UTI!.takeRetainedValue(), kUTTagClassMIMEType) if (str == nil) { return "application/octet-stream" } else { return str!.takeUnretainedValue() as String } } } let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "PATCH" // Token let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") } // Multipart/form-data request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") var error: NSError? let fileData: NSData? do { fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.alwaysMapped) } catch let error1 as NSError { error = error1 fileData = nil } if (fileData == nil || error != nil) { completion(nil, error) return } // The actual Multipart/form-data content let data = NSMutableData() data.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) let fileName = (filePath as NSString).lastPathComponent data.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) data.append("Content-Type: \(mimeType)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) println(object: "mimeType = \(mimeType)") data.append("\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) data.append(fileData! as Data) data.append("\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) for (key, value) in postData { if (value.lengthOfBytes(using: String.Encoding.utf8) > 0) { data.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) } } data.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) let uploadTask = session.uploadTask(with: request as URLRequest, from: data as Data, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) uploadTask.resume() } // Load data via PATCH and return in completion with or without error func patchDataToURL(url: NSURL, postData: Dictionary<String,String>, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "patchDataToURL: " + url.absoluteString! + " postData = " + postData.description) let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "PATCH" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type") let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") } var body = "" for (key, value) in postData { body += "\(key)=\(value)&" } request.httpBody = body.data( using: String.Encoding.utf8, allowLossyConversion: false) let loadDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } // Load data via POST and return in completion with or without error func postDataToURL(url: NSURL, postData: Dictionary<String,String>, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "postDataToURL: " + url.absoluteString! + " postData = " + postData.description) let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "POST" let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") //could set for whole session //session.configuration.HTTPAdditionalHeaders = ["Authorization" : "token \(token)"] } var body = "" for (key, value) in postData { body += "\(key)=\(value)&" } request.httpBody = body.data( using: String.Encoding.utf8, allowLossyConversion: false) let loadDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) //let's see those error messages //let dict = JSON(data: data!) //self.println(dict) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } /// Load data via GET and return in completion with or without error func getDataFromURL(url: NSURL, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "getDataFromURL: " + url.absoluteString!) let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "GET" let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") } let loadDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } /// Load data via GET and return in completion with or without error /// This call does NOT add any token that may exist func loadDataFromURL(url: NSURL, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "loadDataFromURL: " + url.absoluteString!) let session = URLSession.shared let loadDataTask = session.dataTask(with: url as URL, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(nil, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } // MARK: - NSURLSessionDelegate // MARK: - NSURLSessionTaskDelegate // MARK: - NSURLSessionDataDelegate }
mit
2484e4c73a9e07a6362911828301fcf8
55.176724
233
0.64471
4.82525
false
false
false
false
JakeLin/IBAnimatable
Sources/Views/AnimatableView.swift
2
6072
// // Created by Jake Lin on 11/18/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit @IBDesignable open class AnimatableView: UIView, CornerDesignable, FillDesignable, BorderDesignable, RotationDesignable, ShadowDesignable, BlurDesignable, TintDesignable, GradientDesignable, MaskDesignable, Animatable { // MARK: - CornerDesignable @IBInspectable open var cornerRadius: CGFloat = CGFloat.nan { didSet { configureCornerRadius() } } open var cornerSides: CornerSides = .allSides { didSet { configureCornerRadius() } } @IBInspectable var _cornerSides: String? { didSet { cornerSides = CornerSides(rawValue: _cornerSides) } } // MARK: - FillDesignable @IBInspectable open var fillColor: UIColor? { didSet { configureFillColor() } } open var predefinedColor: ColorType? { didSet { configureFillColor() } } @IBInspectable var _predefinedColor: String? { didSet { predefinedColor = ColorType(string: _predefinedColor) } } @IBInspectable open var opacity: CGFloat = CGFloat.nan { didSet { configureOpacity() } } // MARK: - BorderDesignable open var borderType: BorderType = .solid { didSet { configureBorder() } } @IBInspectable var _borderType: String? { didSet { borderType = BorderType(string: _borderType) } } @IBInspectable open var borderColor: UIColor? { didSet { configureBorder() } } @IBInspectable open var borderWidth: CGFloat = CGFloat.nan { didSet { configureBorder() } } open var borderSides: BorderSides = .AllSides { didSet { configureBorder() } } @IBInspectable var _borderSides: String? { didSet { borderSides = BorderSides(rawValue: _borderSides) } } // MARK: - RotationDesignable @IBInspectable open var rotate: CGFloat = CGFloat.nan { didSet { configureRotate() } } // MARK: - ShadowDesignable @IBInspectable open var shadowColor: UIColor? { didSet { configureShadowColor() } } @IBInspectable open var shadowRadius: CGFloat = CGFloat.nan { didSet { configureShadowRadius() } } @IBInspectable open var shadowOpacity: CGFloat = CGFloat.nan { didSet { configureShadowOpacity() } } @IBInspectable open var shadowOffset: CGPoint = CGPoint(x: CGFloat.nan, y: CGFloat.nan) { didSet { configureShadowOffset() } } // MARK: - BlurDesignable open var blurEffectStyle: UIBlurEffect.Style? { didSet { configureBlurEffectStyle() } } @IBInspectable var _blurEffectStyle: String? { didSet { blurEffectStyle = UIBlurEffect.Style(string: _blurEffectStyle) } } open var vibrancyEffectStyle: UIBlurEffect.Style? { didSet { configureBlurEffectStyle() } } @IBInspectable var _vibrancyEffectStyle: String? { didSet { vibrancyEffectStyle = UIBlurEffect.Style(string: _vibrancyEffectStyle) } } @IBInspectable open var blurOpacity: CGFloat = CGFloat.nan { didSet { configureBlurEffectStyle() } } // MARK: - TintDesignable @IBInspectable open var tintOpacity: CGFloat = CGFloat.nan @IBInspectable open var shadeOpacity: CGFloat = CGFloat.nan @IBInspectable open var toneColor: UIColor? @IBInspectable open var toneOpacity: CGFloat = CGFloat.nan // MARK: - GradientDesignable open var gradientMode: GradientMode = .linear @IBInspectable var _gradientMode: String? { didSet { gradientMode = GradientMode(string: _gradientMode) ?? .linear } } @IBInspectable open var startColor: UIColor? @IBInspectable open var endColor: UIColor? open var predefinedGradient: GradientType? @IBInspectable var _predefinedGradient: String? { didSet { predefinedGradient = GradientType(string: _predefinedGradient) } } open var startPoint: GradientStartPoint = .top @IBInspectable var _startPoint: String? { didSet { startPoint = GradientStartPoint(string: _startPoint, default: .top) } } // MARK: - MaskDesignable open var maskType: MaskType = .none { didSet { configureMask(previousMaskType: oldValue) configureBorder() configureMaskShadow() } } /// The mask type used in Interface Builder. **Should not** use this property in code. @IBInspectable var _maskType: String? { didSet { maskType = MaskType(string: _maskType) } } // MARK: - Animatable open var animationType: AnimationType = .none @IBInspectable var _animationType: String? { didSet { animationType = AnimationType(string: _animationType) } } @IBInspectable open var autoRun: Bool = true @IBInspectable open var duration: Double = Double.nan @IBInspectable open var delay: Double = Double.nan @IBInspectable open var damping: CGFloat = CGFloat.nan @IBInspectable open var velocity: CGFloat = CGFloat.nan @IBInspectable open var force: CGFloat = CGFloat.nan @IBInspectable var _timingFunction: String = "" { didSet { timingFunction = TimingFunctionType(string: _timingFunction) } } open var timingFunction: TimingFunctionType = .none // MARK: - Lifecycle open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configureInspectableProperties() } open override func awakeFromNib() { super.awakeFromNib() configureInspectableProperties() } open override func layoutSubviews() { super.layoutSubviews() configureAfterLayoutSubviews() autoRunAnimation() } // MARK: - Private fileprivate func configureInspectableProperties() { configureAnimatableProperties() configureTintedColor() } fileprivate func configureAfterLayoutSubviews() { configureMask(previousMaskType: maskType) configureCornerRadius() configureBorder() configureMaskShadow() configureGradient() } }
mit
558dc77dce67c730cfff5e4e84c8ace0
23.479839
91
0.670236
4.864583
false
true
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/OnboardingV2/OnboardingPageViewController.swift
1
3394
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import SnapKit import UIKit class OnboardingPageViewController: ViewController { struct PageContext: Context { let title: String let asset: Assets let tagLine: String? init(title: String, asset: Assets, tagLine: String? = nil) { self.title = title self.asset = asset self.tagLine = tagLine } } private let titleLabel = UILabel(typography: .headerTitle, color: Style.Colors.FoundationGreen) private let imageView = UIImageView() private let taglineLabel = UILabel(typography: .bodyRegular, color: Style.Colors.FoundationGreen) convenience init(context: PageContext) { self.init() configure(context: context) } override func configureView() { super.configureView() titleLabel.numberOfLines = 2 titleLabel.adjustsFontSizeToFitWidth = true imageView.contentMode = .scaleAspectFit imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical) imageView.setContentHuggingPriority(.defaultLow, for: .vertical) taglineLabel.textAlignment = .center view.addSubview(titleLabel) { $0.leading.trailing.top.equalToSuperview().inset(Style.Padding.p32) } view.addSubview(taglineLabel) { $0.leading.trailing.bottom.equalToSuperview().inset(Style.Padding.p32) } let layoutGuide = UILayoutGuide() view.addLayoutGuide(layoutGuide) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p32) $0.top.equalTo(titleLabel.snp.bottom) $0.bottom.equalTo(taglineLabel.snp.top) } view.insertSubview(imageView, belowSubview: titleLabel) imageView.snp.makeConstraints { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p32) $0.centerY.equalTo(layoutGuide) } } func configure(context: PageContext) { titleLabel.text = context.title imageView.image = context.asset.image taglineLabel.text = context.tagLine } }
bsd-3-clause
9c2b6dc81c6993f4b48b0cc7c868004c
35.880435
99
0.739169
4.511968
false
false
false
false
aucl/YandexDiskKit
YandexDiskKit/YandexDiskKit/String+YDisk.swift
1
2020
// // String+YDisk.swift // // Copyright (c) 2014-2015, Clemens Auer // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation extension String { func urlEncoded() -> String { let charactersToEscape = "!*'();:@&=+$,/?%#[]\" " let allowedCharacters = NSCharacterSet(charactersInString: charactersToEscape).invertedSet return self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) ?? self } mutating func appendOptionalURLParameter<T>(name: String, value: T?) { if let value = value { let seperator = self.rangeOfString("?") == nil ? "?" : "&" self.splice("\(seperator)\(name)=\(value)", atIndex: self.endIndex) } } }
bsd-2-clause
2f2e37e8bb66d51de68adade88964ab6
43.888889
98
0.720792
4.708625
false
false
false
false
asp2insp/CodePathFinalProject
Pretto/AddEventDateCell.swift
1
1506
// // AddEventDateCell.swift // Pretto // // Created by Francisco de la Pena on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit class AddEventDateCell: UITableViewCell { @IBOutlet var startOrEndLabel: UILabel! @IBOutlet var dateLabel: UILabel! var isStartDate: Bool! { didSet { startOrEndLabel.text = isStartDate! ? "Starts" : "Ends" } } var date: NSDate! { didSet { dateFormatter.dateFormat = "MMM, d - hh:mm a" if isStartDate! { var interval = abs(NSDate().timeIntervalSinceDate(date)) if interval < (60 * 1) { println("Time Interval Since Now = \(interval)") dateLabel.text = "Now!" } else { dateLabel.text = dateFormatter.stringFromDate(date) } } else { dateLabel.text = dateFormatter.stringFromDate(date) } } } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.None self.dateLabel.textColor = UIColor.lightGrayColor() self.startOrEndLabel.textColor = UIColor.prettoOrange() self.tintColor = UIColor.whiteColor() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
6ce39dfb3dd198cd6477d3f2e342ee40
27.961538
72
0.578353
4.811502
false
false
false
false
MTR2D2/TIY-Assignments
Forecaster/Forecaster/APIController.swift
1
2899
// // APIController.swift // Forecaster // // Created by Michael Reynolds on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class APIController { var delegate: APIControllerProtocol init(delegate: APIControllerProtocol) { self.delegate = delegate } func searchMapsFor(searchTerm: String) { let urlPath = "https://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:\(searchTerm)&sensor=false" let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() // not NSURLConnection, use NSURLSession! let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if error != nil { print(error!.localizedDescription) } else { if let dictionary = self.parseJSON(data!) { if let results: NSArray = dictionary["results"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } } }) task.resume() } func searchWeatherFor(city: City) { let latitude = city.latitude let longitude = city.longitude let urlPath = "https://api.forecast.io/forecast/1b3f124941abc3fc2e9ab22e93ba68b4/\(latitude),\(longitude)" print(city.latitude) ; print(city.longitude) let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() // not NSURLConnection, use NSURLSession! let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if error != nil { print(error!.localizedDescription) } else { if let dictionary = self.parseJSON(data!) { if let currently: NSDictionary = dictionary["currently"] as? NSDictionary { self.delegate.didReceiveAPIWeatherResults(currently, city: city) } } } }) task.resume() } func parseJSON(data: NSData) -> NSDictionary? { do { let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary return dictionary } catch let error as NSError { print(error) return nil } } } //https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE
cc0-1.0
e85d8557d4fc18bd7b0d07ce1e4f4257
28.571429
146
0.52588
5.231047
false
false
false
false
Donny8028/Swift-Animation
Emoji Slot Machine/Emoji Slot Machine/ViewController.swift
1
3159
// // ViewController.swift // Emoji Slot Machine // // Created by 賢瑭 何 on 2016/5/19. // Copyright © 2016年 Donny. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { let emojis = ["😂","😎","😡","😱","💩","👽","👀","🐷","🐨","🐣","🙉","🐶","🐯"] var leftRow = [Int]() var midRow = [Int]() var rightRow = [Int]() @IBOutlet weak var buttonView: UIButton! @IBOutlet weak var mid: UIPickerView! @IBAction func start() { var fixedRow: Int? for i in 0...2 { let row = arc4random_uniform(99) mid.selectRow(Int(row), inComponent: i, animated: true) fixedRow = Int(row) } if let row = fixedRow where leftRow[row] == midRow[row] && midRow[row] == rightRow[row] { let alert = UIAlertController(title: "Bingo!", message: "Congrats!", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) } } override func viewDidLoad() { super.viewDidLoad() mid.dataSource = self mid.delegate = self buttonView.layer.cornerRadius = 6 for _ in 0...100 { let left = arc4random_uniform(13) let mid = arc4random_uniform(13) let right = arc4random_uniform(13) leftRow.append(Int(left)) midRow.append(Int(mid)) rightRow.append(Int(right)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 3 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 100 } func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { switch component { case 0 : var left = [String]() let view = UILabel() view.font = UIFont.systemFontOfSize(50) for i in leftRow { left.append(emojis[i]) } view.text = left[row] return view case 1 : var mid = [String]() let view = UILabel() view.font = UIFont.systemFontOfSize(50) for i in midRow { mid.append(emojis[i]) } view.text = mid[row] return view case 2 : var right = [String]() let view = UILabel() view.font = UIFont.systemFontOfSize(50) for i in rightRow { right.append(emojis[i]) } view.text = right[row] return view default: let view = UILabel() return view } } func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 100 } }
mit
8f6493d42257112b77dc1041f06f6108
28.628571
134
0.541305
4.515239
false
false
false
false
ntaku/SwiftEssential
SwiftEssential/ExtImage.swift
1
4239
import Foundation import UIKit public extension UIImage { /** 中心を正方形にクロップする (Exifの画像の向きは考慮されない) */ @objc func crop() -> UIImage { let w = self.size.width let h = self.size.height let size = (w < h) ? w : h let sx = self.size.width/2 - size/2 let sy = self.size.height/2 - size/2 let rect = CGRect(x: sx, y: sy, width: size, height: size) return crop(bounds: rect) } /** 指定した位置をクロップする (Exifの画像の向きは考慮されない) */ @objc func crop(bounds: CGRect) -> UIImage { let cgImage = self.cgImage?.cropping(to: bounds) return UIImage(cgImage: cgImage!) } /** 長辺が指定したサイズになるように自動リサイズする */ @objc func autoResize(_ maxsize: CGFloat) -> UIImage { if(maxsize > 0){ let ratio = maxsize / max(self.size.width, self.size.height) let size = CGSize(width: self.size.width * ratio, height: self.size.height * ratio) // オリジナルが指定サイズより小さい場合 //(resizeを実行しておかないとExifの向きが上向きに修正されないので実行される場合と挙動が異なってしまう。) if self.size.width <= size.width && self.size.height <= size.height { return resize(self.size) } return resize(size) } return resize(self.size) } /** 指定サイズでリサイズする (Exifの画像の向きが上に修正される) */ @objc func resize(_ size: CGSize) -> UIImage { return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { (context) in draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) } } @objc func orientationString() -> String { switch self.imageOrientation { case .up: return "Up" case .down: return "Down" case .left: return "Left" case .right: return "Right" case .upMirrored: return "UpMirrored" case .downMirrored: return "DownMirrored" case .leftMirrored: return "LeftMirrored" case .rightMirrored: return "RightMirrored" @unknown default: return "Unknown" } } /** JPGに変換する */ @objc func toJpeg(_ quality: CGFloat) -> Data? { return self.jpegData(compressionQuality: quality) } /** PNGに変換する */ @objc func toPng() -> Data? { return self.pngData() } /** 指定色の画像を生成する */ @objc class func image(from color: UIColor) -> UIImage { return image(from: color, size: CGSize(width: 1, height: 1)) } //TODO UIGraphicsImageRendererにリプレイス /** 指定色/サイズの画像を生成する */ @objc class func image(from color: UIColor, size: CGSize) -> UIImage { let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(CGSize(width: size.width, height: size.height), false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } //TODO UIGraphicsImageRendererにリプレイス /** 指定色の画像に変換する */ @objc func maskWith(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(.normal) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.clip(to: rect, mask: cgImage!) color.setFill() context.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } }
mit
5a3914b4ded0538f462b971f7996573f
28.834646
104
0.58274
3.910217
false
false
false
false
rad182/CellSignal
Watch Extension/InterfaceController.swift
1
2088
// // InterfaceController.swift // Watch Extension // // Created by Royce Albert Dy on 14/11/2015. // Copyright © 2015 rad182. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet weak var radioTechnologyLabel: WKInterfaceLabel! private var isFetchingData = false override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func didAppear() { super.didAppear() print("didAppear") self.reloadData() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() print("willActivate") self.reloadData() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } // MARK: - Methods func reloadData() { if self.isFetchingData { return } if let currentSession = SessionUtility.currentSession where currentSession.reachable { self.isFetchingData = true SessionUtility.updateCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentage { (currentRadioAccessTechnology, currentSignalStrengthPercentage) -> Void in self.isFetchingData = false if let currentRadioAccessTechnology = currentRadioAccessTechnology where currentRadioAccessTechnology.isEmpty == false { self.radioTechnologyLabel.setText(currentRadioAccessTechnology) SessionUtility.refreshComplications() print(currentRadioAccessTechnology) } else { self.radioTechnologyLabel.setText("No Signal") } } } else { self.radioTechnologyLabel.setText("Not Reachable") print("not reachable") } } }
mit
2106ec571699f2c69dc7697cb7b58ccf
31.123077
136
0.632487
5.928977
false
false
false
false
Turistforeningen/SjekkUT
ios/SjekkUt/views/style/DntTextView.swift
1
677
// // DntTextView.swift // SjekkUt // // Created by Henrik Hartz on 14.02.2017. // Copyright © 2017 Den Norske Turistforening. All rights reserved. // import Foundation @IBDesignable class DntTextView: UITextView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupDntTextView() } func setupDntTextView() { self.layer.cornerRadius = 5 self.layer.borderColor = UIColor.lightGray.cgColor self.layer.borderWidth = 1 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.25 self.layer.shadowOffset = CGSize(width: 1, height: 1) } }
mit
ce1d766dfd42fc6376a0da877a761de2
23.142857
68
0.650888
3.976471
false
false
false
false
gregomni/swift
validation-test/compiler_crashers_fixed/00237-swift-declrefexpr-setspecialized.swift
3
3053
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck -requirement-machine-inferred-signatures=on func b(c) -> <d>(() -> d) { } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func i(c: () -> ()) { } class a { var _ = i() { } } protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F func g<T where T.E == F>(f: B<T>) } struct D : C { typealias F = Int func g<T where T.E == F>(f: B<T>) { } } protocol A { func c() -> String } class B { func d() -> String { return "" B) { } } func ^(a: Boolean, Bool) -> Bool { return !(a) } func f<T : Boolean>(b: T) { } f(true as Boolean) var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? { for (mx : e?) in c { } } protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e(ass func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } class a { typealias b = b } func a(b: Int = 0) { } let c = a c() enum S<T> { case C(T, () -> ()) } func f() { ({}) } enum S<T> : P { func f<T>() -> T -> T { return { x in x } } } protocol P { func f<T>()(T) -> T } protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } class A<T : A> { } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } struct A<T> { let a: [(T, () -> ())] = [] } struct c<d, e: b where d.c == e> { } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) func a<T>() -> (T, T -> T) -> T { var b: ((T, T -> T) -> T)! return b } protocol b { class func e() } struct c { var d: b.Type func e() { d.e() } } import Foundation class d<c>: NSObject { var b: c init(b: c) { self.b = b } } func a<T>() { enum b { case c } } protocol a : a { } class A : A { } class B : C { } typealias C = B
apache-2.0
266aa4cb8abd1eb7365a4b5fe426d117
14.818653
92
0.494268
2.578547
false
false
false
false
heitara/swift-3
playgrounds/Lecture4.playground/Contents.swift
1
8796
//: Playground - noun: a place where people can play import UIKit /* Какво е playground? Това вид проект, който се изпозлва от xCode. Интерактивно показва какво е състоянието на паметта на компютъра във всеки един ред на изпълнение на код-а. Позволява лесно онагледяване на примерния код. Много по лесно може да се анализира кода. Можем да скицираме проблеми и техните решения, които да използваме за напред. */ // Лекция 4 // курс: Увод в прогрмаирането със Swift /* N-торки */ let person = (name: "Иван", familyName: "Петров", age: 25) //тип : (name: String, familyName: String, age: Int) //(String, String, Int) let p:(String, String, age: Int)? = person print("Здравей, \(person.name)!") print("Здравей, г-н \(person.familyName)!") print("Здравей, г-н \(person.1)!") if let pp = p, pp.age > 20 { print("Г-н \(pp.1), Вие сте на \(pp.age) години.") } print("Г-н \(p?.1), Вие сте на \(p?.age) години.") var x:Int? = 7 print("\(x)") /* Интересен пример, който демонстира силата на switch */ let point = (1, 1) switch point { case let (x, y) where x == y: print("X is \(x). Y is \(y). They have the same value."); case (1, let y): print("X is 1. Y is \(y). They could be different."); case (let x, 1): print("X is \(x). Y is 1. They could be different."); case let (x, y) where x > y: print("X is \(x). Y is \(y). X is greater than Y."); default: print("Are you sure?") } //Нека да напишем първата функция, която агрегира няколко действия. //без параметри и без резултат func severalActions() { print("Action 1") print("Action 2") print("Action 3") } //сума на две числа func printSum() { let a = 3 let b = 4 print("Sum \(a) + \(b) = \(a + b)") } //с параметри без резултат //сума на две числа func printSum(a:Int, b:Int) { return; print("Sum \(a) + \(b) = \(a + b)") } //извикване на функцията printSum() //printSum(3, 5) printSum(a:3, b:5) //променливите са let func sum(a:Int, b:Int,in sum: inout Int) { // a = a + b sum = a + b } var sumAB:Int = 0 sum(a:3, b:4, in:&sumAB) //тук ще активираме нашата функция. Може да мислим че я извикваме (call) severalActions() //severalActions() func functionName(labelName constantName:String) -> String { let reurnedValue = constantName + " was passed" return reurnedValue } func functionName(_ a: Int, _ variableName:Double = 5) -> String { let reurnedValue = String(variableName) + " was passed" return reurnedValue } //functionName(1); functionName(17); func f(_ a:Int, _ b:String = "dsadsa", s:String = "dsadsa" ) { let _ = String(a) + " was passed" print("F1001") } func f(_ a:Int,_ b:String = "dsadsa" ) { let _ = String(a) + " was passed" print("F1000") } //func f(_ a:Int) { // let _ = String(a) + " was passed" // print("F1") //} f(4) func functionName(_ variableName:String) -> String { let reurnedValue = variableName + " was passed" return reurnedValue } //ако променим името на аргумента swift счита това за нова различна функция. Т.е. имената на аргумента func functionName(labelNameNew variableName:String) -> String { let reurnedValue = variableName + " NEW was passed" return reurnedValue } //ето и извикването на функцията let resultOfFunctionCall = functionName(labelName: "Nothing") let resultOfFunctionCall2 = functionName("Nothing") functionName(labelNameNew: "Nothing") //когато изпуснем името на аргумента, името на променливата се изпозлва за негово име. т.е. двете съвпадат func functionName(variableName:String) -> String { let reurnedValue = variableName + " was passed. v2" return reurnedValue } //за да извикаме 2рата версия трябва да направим следното обръщение functionName(variableName: "Nothing") // func functionName3(variableName:String) -> String { return variableName + " was passed" } //Пример: на български език //как би изглеждал код-а функцията, ако използваме utf и кирилица func смениСтойността(на вход:inout Int,с новаСтойност: Int) { вход = новаСтойност } func смениСтойността(_ вход:inout Int,_ новаСтойност: Int) { вход = новаСтойност } var променлива = 5 смениСтойността(на: &променлива, с: 15) print("Стойността на променливата е \(променлива)") //класическото програмиране, с което сме свикнали от C, C++, Java смениСтойността(&променлива, 25) print("Стойността на променливата е \(променлива)") //функция, която връша резултат func seven() -> Int { return 7 } let s = seven() print("Това е числото \(s).") /* // невалидна функция, поради дублиране на имената func functionName(argumentName variableName:String, argumentName variableName2:Int) -> String { let reurnedValue = variableName + " was passed" return reurnedValue } */ //как да не позлваме името (label) на аргумент func concatenateStrings(_ s1:String, _ s2:String) -> String { return s1 + s2 } let helloWorld = concatenateStrings("Hello ", "world!") //define a function which finds min and max value in a array of integers func minMax(numbers:[Int]) -> (Int, Int) { var min = Int.max var max = Int.min for val in numbers { if min > val { min = val } if max < val { max = val } } return (min, max) } print(minMax(numbers: [12, 2, 6, 3, 4, 5, 2, 10])) func maxItemIndex(numbers:[Int]) -> (item:Int, index:Int) { var index = -1 var max = Int.min for (i, val) in numbers.enumerated() { if max < val { max = val index = i } } return (max, index) } let maxItemTuple = maxItemIndex(numbers: [12, 2, 6, 3, 4, 5, 2, 10]) if maxItemTuple.index >= 0 { print("Max item is \(maxItemTuple.item).") } func generateGreeting(greet:String, thing:String = "world") -> String { return greet + thing + "!" } print(generateGreeting(greet: "Hello ")) print(generateGreeting(greet: "Hello ", thing: " Swift 4")) func maxValue(params numbers:Int...) -> Int { var max = Int.min for v in numbers { if max < v { max = v } } return max } func maxValue(params numbers:Int) -> Int { return numbers } print(maxValue(params: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 50, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)) print(maxValue(params: 1)) func updateVar(_ x: inout Int, newValue: Int = 5) { x = newValue } var ten = 10 print(ten) updateVar(&ten, newValue: 15) print(ten) //the same example as above, but the paramter has a label func updateVar(oldVariable x: inout Int, newValue: Int = 5) { x = newValue } ten = 10 print(ten) updateVar(oldVariable:&ten, newValue: 15) print(ten) func generateGreeting(_ greeting: String?) -> String { guard let greeting = greeting else { //there is no greeting, we return something and finish return "No greeting :(" } //there is a greeting and we generate a greeting message return greeting + " Swift 4!" } print(generateGreeting(nil)) print(generateGreeting("Hey")) let number = 5 let divisor = 3 let remainder = number % divisor //remainder is again integer let quotient = number / divisor // quotient is again integer let hey = "Hi" let greeting = hey + " Swift 4!" //operator + concatenates strings
mit
88e2fdf99d191d48bfd646480a0587be
22.528302
325
0.637129
2.876586
false
false
false
false
richardpiazza/MiseEnPlace
Sources/MiseEnPlace/Double+MiseEnPlace.swift
1
1151
import Foundation public extension Double { /// Rounds to the number of decimal-places specified func rounded(to places: Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } /// An interpreted representation of the value, composed of the /// integral and fraction as needed. var fractionedString: String { guard self.isNaN == false && self.isInfinite == false else { return "0" } let decomposedAmount = modf(self) guard decomposedAmount.1 > 0.0 else { return "\(Int(decomposedAmount.0))" } let integral = Int(decomposedAmount.0) let fraction = Fraction(proximateValue: decomposedAmount.1) switch fraction { case .zero: return "\(integral)" case .one: return "\(Int(integral + 1))" default: if integral == 0 { return "\(fraction.description)" } else { return "\(integral)\(fraction.description)" } } } }
mit
a8a51b0769b9d00604f71395f025dbb1
28.512821
68
0.537793
4.961207
false
false
false
false
weby/Stencil
Sources/Filters.swift
1
601
func toString(value: Any?) -> String? { if let value = value as? String { return value } else if let value = value as? CustomStringConvertible { return value.description } return nil } func capitalise(value: Any?) -> Any? { if let value = toString(value: value) { return value.capitalized } return value } func uppercase(value: Any?) -> Any? { if let value = toString(value: value) { return value.uppercased() } return value } func lowercase(value: Any?) -> Any? { if let value = toString(value: value) { return value.lowercased() } return value }
bsd-2-clause
2382985d6acaa2faa69c1c59381dabd2
17.212121
59
0.647255
3.687117
false
false
false
false
ksco/swift-algorithm-club-cn
Segment Tree/SegmentTree.swift
1
2429
/* Segment tree Performance: building the tree is O(n) query is O(log n) replace item is O(log n) */ public class SegmentTree<T> { private var value: T private var function: (T, T) -> T private var leftBound: Int private var rightBound: Int private var leftChild: SegmentTree<T>? private var rightChild: SegmentTree<T>? public init(array: [T], leftBound: Int, rightBound: Int, function: (T, T) -> T) { self.leftBound = leftBound self.rightBound = rightBound self.function = function if leftBound == rightBound { value = array[leftBound] } else { let middle = (leftBound + rightBound) / 2 leftChild = SegmentTree<T>(array: array, leftBound: leftBound, rightBound: middle, function: function) rightChild = SegmentTree<T>(array: array, leftBound: middle+1, rightBound: rightBound, function: function) value = function(leftChild!.value, rightChild!.value) } } public convenience init(array: [T], function: (T, T) -> T) { self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function) } public func queryWithLeftBound(leftBound: Int, rightBound: Int) -> T { if self.leftBound == leftBound && self.rightBound == rightBound { return self.value } guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } if leftChild.rightBound < leftBound { return rightChild.queryWithLeftBound(leftBound, rightBound: rightBound) } else if rightChild.leftBound > rightBound { return leftChild.queryWithLeftBound(leftBound, rightBound: rightBound) } else { let leftResult = leftChild.queryWithLeftBound(leftBound, rightBound: leftChild.rightBound) let rightResult = rightChild.queryWithLeftBound(rightChild.leftBound, rightBound: rightBound) return function(leftResult, rightResult) } } public func replaceItemAtIndex(index: Int, withItem item: T) { if leftBound == rightBound { value = item } else if let leftChild = leftChild, rightChild = rightChild { if leftChild.rightBound >= index { leftChild.replaceItemAtIndex(index, withItem: item) } else { rightChild.replaceItemAtIndex(index, withItem: item) } value = function(leftChild.value, rightChild.value) } } }
mit
104444d8bdd9168087ea6462a4e4f926
34.202899
112
0.683821
4.465074
false
false
false
false
aleph7/PlotKit
PlotKit/Model/PointSet.swift
1
2141
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of PlotKit. The full PlotKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Foundation public enum PointType { case none case ring(radius: Double) case disk(radius: Double) case square(side: Double) case filledSquare(side: Double) } public struct Point { public var x: Double public var y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } public class PointSet { public var points: [Point] { didSet { updateIntervals() } } public var lineWidth = CGFloat(1.0) public var lineColor: NSColor? = NSColor.red public var fillColor: NSColor? = nil public var pointColor: NSColor? = NSColor.red public var pointType = PointType.none public var xInterval: ClosedRange<Double> = (0 ... 0) public var yInterval: ClosedRange<Double> = (0 ... 0) public init() { self.points = [] } public init<T: Sequence>(points: T) where T.Iterator.Element == Point { self.points = [Point](points) updateIntervals() } public init<T: Sequence>(values: T) where T.Iterator.Element == Double { self.points = values.enumerated().map{ Point(x: Double($0.0), y: $0.1) } updateIntervals() } func updateIntervals() { guard let first = points.first else { xInterval = 0...0 yInterval = 0...0 return } var minX = first.x var maxX = first.x var minY = first.y var maxY = first.y for p in points { if p.x < minX { minX = p.x } if p.x > maxX { maxX = p.x } if p.y < minY { minY = p.y } if p.y > maxY { maxY = p.y } } xInterval = minX...maxX yInterval = minY...maxY } }
mit
9ba71cd9edb700caf118d9619482d814
24.47619
80
0.549533
4.115385
false
false
false
false
OscarSwanros/swift
test/SourceKit/CodeComplete/complete_filter.swift
31
3678
struct Foo { func aaa() {} func aab() {} func abc() {} func b() {} func c() {} } func foo() { let x = Foo() x.#^FOO,,a,aa,ab,abc,abcd^# } // XFAIL: broken_std_regex // RUN: %sourcekitd-test -req=complete.open -pos=11:5 %s -- %s > %t.all // RUN: %FileCheck -check-prefix=CHECK-ALL %s < %t.all // CHECK-ALL: key.name: "aaa // CHECK-ALL: key.name: "aab // CHECK-ALL: key.name: "abc // CHECK-ALL: key.name: "b // CHECK-ALL: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=a %s -- %s > %t.a // RUN: %FileCheck -check-prefix=CHECKA %s < %t.a // CHECKA-NOT: key.name // CHECKA: key.name: "aaa // CHECKA: key.name: "aab // CHECKA: key.name: "abc // CHECKA-NOT: key.name: "b // CHECKA-NOT: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 %s -- %s \ // RUN: == -req=complete.update -pos=11:5 -req-opts=filtertext=a %s -- %s > %t.both // RUN: cat %t.all %t.a > %t.both.check // RUN: diff -u %t.both %t.both.check // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=b %s -- %s > %t.b // RUN: %FileCheck -check-prefix=CHECKB %s < %t.b // CHECKB-NOT: key.name // CHECKB: key.name: "b // CHECKB-NOT: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=c %s -- %s > %t.c // RUN: %FileCheck -check-prefix=CHECKC %s < %t.c // CHECKC-NOT: key.name // CHECKC: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=d %s -- %s > %t.d // RUN: %FileCheck -check-prefix=CHECKD %s < %t.d // CHECKD-NOT: key.name // CHECKD: ], // CHECKD-NEXT: key.kind: source.lang.swift.codecomplete.group // CHECKD-NEXT: key.name: "" // CHECKD-NEXT: key.nextrequeststart: 0 // CHECKD-NEXT: } // RUN: %complete-test -tok=FOO %s | %FileCheck %s // CHECK-LABEL: Results for filterText: [ // CHECK-NEXT: aaa() // CHECK-NEXT: aab() // CHECK-NEXT: abc() // CHECK-NEXT: b() // CHECK-NEXT: c() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: a [ // CHECK-NEXT: aaa() // CHECK-NEXT: aab() // CHECK-NEXT: abc() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: aa [ // CHECK-NEXT: aaa() // CHECK-NEXT: aab() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: abc [ // CHECK-NEXT: abc() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: abcd [ // CHECK-NEXT: ] struct A {} func over() {} func overload() {} func overload(_ x: A) {} func test() { #^OVER,over,overload,overloadp^# } // Don't create empty groups, or groups with one element // RUN: %complete-test -group=overloads -tok=OVER %s | %FileCheck -check-prefix=GROUP %s // GROUP-LABEL: Results for filterText: over [ // GROUP: overload: // GROUP-NEXT: overload() // GROUP-NEXT: overload(x: A) // GROUP: ] // GROUP-LABEL: Results for filterText: overload [ // GROUP-NEXT: overload() // GROUP-NEXT: overload(x: A) // GROUP-NEXT: ] // GROUP-LABEL: Results for filterText: overloadp [ // GROUP-NEXT: ] struct UnnamedArgs { func dontMatchAgainst(_ unnamed: Int, arguments: Int, _ unnamed2:Int) {} func test() { self.#^UNNAMED_ARGS_0,dont,arguments,unnamed^# } } // RUN: %complete-test -tok=UNNAMED_ARGS_0 %s | %FileCheck %s -check-prefix=UNNAMED_ARGS_0 // UNNAMED_ARGS_0: Results for filterText: dont [ // UNNAMED_ARGS_0-NEXT: dontMatchAgainst(unnamed: Int, arguments: Int, unnamed2: Int) // UNNAMED_ARGS_0-NEXT: ] // UNNAMED_ARGS_0-NEXT: Results for filterText: arguments [ // UNNAMED_ARGS_0-NEXT: dontMatchAgainst(unnamed: Int, arguments: Int, unnamed2: Int) // UNNAMED_ARGS_0-NEXT: ] // UNNAMED_ARGS_0-NEXT: Results for filterText: unnamed [ // UNNAMED_ARGS_0-NEXT: ]
apache-2.0
c517cc6bfbc788716bc745b2cbe6cfc6
28.190476
90
0.630234
2.718404
false
true
false
false
LoopKit/LoopKit
LoopKitUI/View Controllers/GlucoseEntryTableViewController.swift
1
2171
// // GlucoseEntryTableViewController.swift // LoopKitUI // // Created by Michael Pangburn on 11/24/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import UIKit import HealthKit import LoopKit public protocol GlucoseEntryTableViewControllerDelegate: AnyObject { func glucoseEntryTableViewControllerDidChangeGlucose(_ controller: GlucoseEntryTableViewController) } public class GlucoseEntryTableViewController: TextFieldTableViewController { let glucoseUnit: HKUnit private lazy var glucoseFormatter: NumberFormatter = { let quantityFormatter = QuantityFormatter() quantityFormatter.setPreferredNumberFormatter(for: glucoseUnit) return quantityFormatter.numberFormatter }() public var glucose: HKQuantity? { get { guard let value = value, let doubleValue = Double(value) else { return nil } return HKQuantity(unit: glucoseUnit, doubleValue: doubleValue) } set { if let newValue = newValue { value = glucoseFormatter.string(from: newValue.doubleValue(for: glucoseUnit)) } else { value = nil } } } public weak var glucoseEntryDelegate: GlucoseEntryTableViewControllerDelegate? public init(glucoseUnit: HKUnit) { self.glucoseUnit = glucoseUnit super.init(style: .grouped) unit = glucoseUnit.shortLocalizedUnitString() keyboardType = .decimalPad placeholder = "Enter glucose value" delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension GlucoseEntryTableViewController: TextFieldTableViewControllerDelegate { public func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController) { glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self) } public func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController) { glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self) } }
mit
208bbeacc66ea0c108325c662dcdfc6f
30.911765
103
0.70553
5.880759
false
false
false
false
LoopKit/LoopKit
LoopKit/DailyValueSchedule.swift
1
9251
// // QuantitySchedule.swift // Naterade // // Created by Nathan Racklyeft on 1/18/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit public struct RepeatingScheduleValue<T> { public var startTime: TimeInterval public var value: T public init(startTime: TimeInterval, value: T) { self.startTime = startTime self.value = value } public func map<U>(_ transform: (T) -> U) -> RepeatingScheduleValue<U> { return RepeatingScheduleValue<U>(startTime: startTime, value: transform(value)) } } extension RepeatingScheduleValue: Equatable where T: Equatable { public static func == (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool { return abs(lhs.startTime - rhs.startTime) < .ulpOfOne && lhs.value == rhs.value } } extension RepeatingScheduleValue: Hashable where T: Hashable {} public struct AbsoluteScheduleValue<T>: TimelineValue { public let startDate: Date public let endDate: Date public let value: T } extension AbsoluteScheduleValue: Equatable where T: Equatable {} extension RepeatingScheduleValue: RawRepresentable where T: RawRepresentable { public typealias RawValue = [String: Any] public init?(rawValue: RawValue) { guard let startTime = rawValue["startTime"] as? Double, let rawValue = rawValue["value"] as? T.RawValue, let value = T(rawValue: rawValue) else { return nil } self.init(startTime: startTime, value: value) } public var rawValue: RawValue { return [ "startTime": startTime, "value": value.rawValue ] } } extension RepeatingScheduleValue: Codable where T: Codable {} public protocol DailySchedule { associatedtype T var items: [RepeatingScheduleValue<T>] { get } var timeZone: TimeZone { get set } func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] func value(at time: Date) -> T } public extension DailySchedule { func value(at time: Date) -> T { return between(start: time, end: time).first!.value } } extension DailySchedule where T: Comparable { public func valueRange() -> ClosedRange<T> { items.range(of: { $0.value })! } } public struct DailyValueSchedule<T>: DailySchedule { let referenceTimeInterval: TimeInterval let repeatInterval: TimeInterval public let items: [RepeatingScheduleValue<T>] public var timeZone: TimeZone public init?(dailyItems: [RepeatingScheduleValue<T>], timeZone: TimeZone? = nil) { self.repeatInterval = TimeInterval(hours: 24) self.items = dailyItems.sorted { $0.startTime < $1.startTime } self.timeZone = timeZone ?? TimeZone.currentFixed guard let firstItem = self.items.first else { return nil } referenceTimeInterval = firstItem.startTime } var maxTimeInterval: TimeInterval { return referenceTimeInterval + repeatInterval } /** Returns the time interval for a given date normalized to the span of the schedule items - parameter date: The date to convert */ func scheduleOffset(for date: Date) -> TimeInterval { // The time interval since a reference date in the specified time zone let interval = date.timeIntervalSinceReferenceDate + TimeInterval(timeZone.secondsFromGMT(for: date)) // The offset of the time interval since the last occurence of the reference time + n * repeatIntervals. // If the repeat interval was 1 day, this is the fractional amount of time since the most recent repeat interval starting at the reference time return ((interval - referenceTimeInterval).truncatingRemainder(dividingBy: repeatInterval)) + referenceTimeInterval } /** Returns a slice of schedule items that occur between two dates - parameter startDate: The start date of the range - parameter endDate: The end date of the range - returns: A slice of `ScheduleItem` values */ public func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] { guard startDate <= endDate else { return [] } let startOffset = scheduleOffset(for: startDate) let endOffset = startOffset + endDate.timeIntervalSince(startDate) guard endOffset <= maxTimeInterval else { let boundaryDate = startDate.addingTimeInterval(maxTimeInterval - startOffset) return between(start: startDate, end: boundaryDate) + between(start: boundaryDate, end: endDate) } var startIndex = 0 var endIndex = items.count for (index, item) in items.enumerated() { if startOffset >= item.startTime { startIndex = index } if endOffset < item.startTime { endIndex = index break } } let referenceDate = startDate.addingTimeInterval(-startOffset) return (startIndex..<endIndex).map { (index) in let item = items[index] let endTime = index + 1 < items.count ? items[index + 1].startTime : maxTimeInterval return AbsoluteScheduleValue( startDate: referenceDate.addingTimeInterval(item.startTime), endDate: referenceDate.addingTimeInterval(endTime), value: item.value ) } } public func map<U>(_ transform: (T) -> U) -> DailyValueSchedule<U> { return DailyValueSchedule<U>( dailyItems: items.map { $0.map(transform) }, timeZone: timeZone )! } public static func zip<L, R>(_ lhs: DailyValueSchedule<L>, _ rhs: DailyValueSchedule<R>) -> DailyValueSchedule where T == (L, R) { precondition(lhs.timeZone == rhs.timeZone) var (leftCursor, rightCursor) = (lhs.items.startIndex, rhs.items.startIndex) var alignedItems: [RepeatingScheduleValue<(L, R)>] = [] repeat { let (leftItem, rightItem) = (lhs.items[leftCursor], rhs.items[rightCursor]) let alignedItem = RepeatingScheduleValue( startTime: max(leftItem.startTime, rightItem.startTime), value: (leftItem.value, rightItem.value) ) alignedItems.append(alignedItem) let nextLeftStartTime = leftCursor == lhs.items.endIndex - 1 ? nil : lhs.items[leftCursor + 1].startTime let nextRightStartTime = rightCursor == rhs.items.endIndex - 1 ? nil : rhs.items[rightCursor + 1].startTime switch (nextLeftStartTime, nextRightStartTime) { case (.some(let leftStart), .some(let rightStart)): if leftStart < rightStart { leftCursor += 1 } else if rightStart < leftStart { rightCursor += 1 } else { leftCursor += 1 rightCursor += 1 } case (.some, .none): leftCursor += 1 case (.none, .some): rightCursor += 1 case (.none, .none): leftCursor += 1 rightCursor += 1 } } while leftCursor < lhs.items.endIndex && rightCursor < rhs.items.endIndex return DailyValueSchedule(dailyItems: alignedItems, timeZone: lhs.timeZone)! } } extension DailyValueSchedule: RawRepresentable, CustomDebugStringConvertible where T: RawRepresentable { public typealias RawValue = [String: Any] public init?(rawValue: RawValue) { guard let rawItems = rawValue["items"] as? [RepeatingScheduleValue<T>.RawValue] else { return nil } var timeZone: TimeZone? if let offset = rawValue["timeZone"] as? Int { timeZone = TimeZone(secondsFromGMT: offset) } let validScheduleItems = rawItems.compactMap(RepeatingScheduleValue<T>.init(rawValue:)) guard validScheduleItems.count == rawItems.count else { return nil } self.init(dailyItems: validScheduleItems, timeZone: timeZone) } public var rawValue: RawValue { let rawItems = items.map { $0.rawValue } return [ "timeZone": timeZone.secondsFromGMT(), "items": rawItems ] } public var debugDescription: String { return String(reflecting: rawValue) } } extension DailyValueSchedule: Codable where T: Codable {} extension DailyValueSchedule: Equatable where T: Equatable {} extension RepeatingScheduleValue { public static func == <L: Equatable, R: Equatable> (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool where T == (L, R) { return lhs.startTime == rhs.startTime && lhs.value == rhs.value } } extension DailyValueSchedule { public static func == <L: Equatable, R: Equatable> (lhs: DailyValueSchedule, rhs: DailyValueSchedule) -> Bool where T == (L, R) { return lhs.timeZone == rhs.timeZone && lhs.items.count == rhs.items.count && Swift.zip(lhs.items, rhs.items).allSatisfy(==) } }
mit
bb92449674215c58608c78017f2313bf
32.636364
151
0.632216
4.970446
false
false
false
false
grafele/Prototyper
Prototyper/Classes/APIHandler.swift
2
8060
// // APIHandler.swift // Prototype // // Created by Stefan Kofler on 17.06.15. // Copyright (c) 2015 Stephan Rabanser. All rights reserved. // import Foundation import UIKit let sharedInstance = APIHandler() private let defaultBoundary = "------VohpleBoundary4QuqLuM1cE5lMwCy" class APIHandler { let session: URLSession var appId: String! { return Bundle.main.object(forInfoDictionaryKey: "PrototyperAppId") as? String ?? UserDefaults.standard.string(forKey: UserDefaultKeys.AppId) } var releaseId: String! { return Bundle.main.object(forInfoDictionaryKey: "PrototyperReleaseId") as? String ?? UserDefaults.standard.string(forKey: UserDefaultKeys.ReleaseId) } var isLoggedIn: Bool = false init() { let sessionConfig = URLSessionConfiguration.default session = URLSession(configuration: sessionConfig) } class var sharedAPIHandler: APIHandler { return sharedInstance } // MARK: API Methods func fetchReleaseInformation(success: @escaping (_ appId: String, _ releaseId: String) -> Void, failure: @escaping (_ error : Error?) -> Void) { let bundleId = Bundle.main.infoDictionary?[kCFBundleIdentifierKey as String] as? String ?? "" let bundleVersion = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String ?? "" let url = URL(string: API.EndPoints.fetchReleaseInfo(bundleId: bundleId, bundleVersion: bundleVersion), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.GET, requestURL: url) executeRequest(request as URLRequest) { (data, response, error) in guard let data = data else { failure(error) return } do { let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Int] if let dict = dict, let appId = dict["app_id"], let releaseId = dict["release_id"] { success("\(appId)", "\(releaseId)") } else { failure(error) } } catch { failure(error) } } } func login(_ email: String, password: String, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { let params = postParamsForLogin(email: email, password: password) let articlesURL = URL(string: API.EndPoints.Login, relativeTo: API.BaseURL as URL?) guard let requestURL = articlesURL else { failure(NSError.APIURLError()) return } guard let bodyData = try? JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) else { failure(NSError.dataEncodeError()) return } let request = jsonRequestForHttpMethod(.POST, requestURL: requestURL, bodyData: bodyData) executeRequest(request as URLRequest) { (data, response, networkError) in let httpURLResponse: HTTPURLResponse! = response as? HTTPURLResponse let error = (data == nil || httpURLResponse.statusCode != 200) ? NSError.dataParseError() : networkError error != nil ? failure(error) : success() self.isLoggedIn = error == nil } } func sendGeneralFeedback(description: String, name: String? = nil, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { guard let appId = appId, let releaseId = releaseId else { print("You need to set the app and release id first") return } let url = URL(string: API.EndPoints.feedback(appId, releaseId: releaseId, text: description.escapedString, username: name?.escapedString), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.POST, requestURL: url) executeRequest(request as URLRequest) { (data, response, error) in error != nil ? failure(error) : success() } } func sendScreenFeedback(screenshot: UIImage, description: String, name: String? = nil, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { guard let appId = appId, let releaseId = releaseId else { print("You need to set the app and release id first") failure(nil) return } let contentType = "\(MimeType.Multipart.rawValue); boundary=\(defaultBoundary)" let bodyData = bodyDataForImage(screenshot) let url = URL(string: API.EndPoints.feedback(appId, releaseId: releaseId, text: description.escapedString, username: name?.escapedString), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.POST, requestURL: url, bodyData: bodyData, contentType: contentType) executeRequest(request as URLRequest) { (data, response, error) in error != nil ? failure(error) : success() } } func sendShareRequest(for email: String, because explanation: String, name: String? = nil, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { guard let appId = appId, let releaseId = releaseId else { print("You need to set the app and release id first") failure(nil) return } let url = URL(string: API.EndPoints.share(appId, releaseId: releaseId, sharedEmail: email.escapedString, explanation: explanation.escapedString, username: name?.escapedString), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.POST, requestURL: url) executeRequest(request as URLRequest) { (data, response, error) in error != nil ? failure(error) : success() } } // TODO: Add method to check for new versions // MARK: Helper fileprivate func jsonRequestForHttpMethod(_ method: HTTPMethod, requestURL: URL, bodyData: Data? = nil, contentType: String = MimeType.JSON.rawValue) -> NSMutableURLRequest { let request = NSMutableURLRequest(url: requestURL) request.httpMethod = method.rawValue request.setValue(contentType, forHTTPHeaderField: HTTPHeaderField.ContentType.rawValue) request.setValue(MimeType.JSON.rawValue, forHTTPHeaderField: HTTPHeaderField.Accept.rawValue) request.httpBody = bodyData return request } fileprivate func bodyDataForImage(_ image: UIImage, boundary: String = defaultBoundary) -> Data { let bodyData = NSMutableData() let imageData = UIImageJPEGRepresentation(image, 0.4) bodyData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) bodyData.append("Content-Disposition: form-data; name=\"[feedback]screenshot\"; filename=\"screenshot.jpg\"\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) bodyData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) bodyData.append(imageData!) bodyData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) return bodyData as Data } fileprivate func executeRequest(_ request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) { let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in OperationQueue.main.addOperation { completionHandler(data, response, error) } return () }) dataTask.resume() } // MARK: Post params fileprivate func postParamsForLogin(email: String, password: String) -> [String: Any] { typealias Session = API.DataTypes.Session return [Session.Session: [Session.Email: email, Session.Password: password]] } }
mit
3a4b3541e5d2ae0dcc3001e9c59982b0
44.027933
210
0.637097
4.878935
false
false
false
false
gottesmm/swift
test/expr/expressions.swift
2
36345
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Tests and samples. //===----------------------------------------------------------------------===// // Comment. With unicode characters: ¡ç®åz¥! func markUsed<T>(_: T) {} // Various function types. var func1 : () -> () // No input, no output. var func2 : (Int) -> Int var func3 : () -> () -> () // Takes nothing, returns a fn. var func3a : () -> (() -> ()) // same as func3 var func6 : (_ fn : (Int,Int) -> Int) -> () // Takes a fn, returns nothing. var func7 : () -> (Int,Int,Int) // Takes nothing, returns tuple. // Top-Level expressions. These are 'main' content. func1() _ = 4+7 var bind_test1 : () -> () = func1 var bind_test2 : Int = 4; func1 // expected-error {{expression resolves to an unused l-value}} (func1, func2) // expected-error {{expression resolves to an unused l-value}} func basictest() { // Simple integer variables. var x : Int var x2 = 4 // Simple Type inference. var x3 = 4+x*(4+x2)/97 // Basic Expressions. // Declaring a variable Void, aka (), is fine too. var v : Void var x4 : Bool = true var x5 : Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}} //var x6 : Float = 4+5 var x7 = 4; 5 // expected-warning {{integer literal is unused}} // Test implicit conversion of integer literal to non-Int64 type. var x8 : Int8 = 4 x8 = x8 + 1 _ = x8 + 1 _ = 0 + x8 1.0 + x8 // expected-error{{binary operator '+' cannot be applied to operands of type 'Double' and 'Int8'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var x9 : Int16 = x8 + 1 // expected-error {{cannot convert value of type 'Int8' to specified type 'Int16'}} // Various tuple types. var tuple1 : () var tuple2 : (Int) var tuple3 : (Int, Int, ()) var tuple2a : (a : Int) // expected-error{{cannot create a single-element tuple with an element label}}{{18-22=}} var tuple3a : (a : Int, b : Int, c : ()) var tuple4 = (1, 2) // Tuple literal. var tuple5 = (1, 2, 3, 4) // Tuple literal. var tuple6 = (1 2) // expected-error {{expected ',' separator}} {{18-18=,}} // Brace expressions. var brace3 = { var brace2 = 42 // variable shadowing. _ = brace2+7 } // Function calls. var call1 : () = func1() var call2 = func2(1) var call3 : () = func3()() // Cannot call an integer. bind_test2() // expected-error {{cannot call value of non-function type 'Int'}}{{13-15=}} } // <https://bugs.swift.org/browse/SR-3522> func testUnusedLiterals_SR3522() { 42 // expected-warning {{integer literal is unused}} 2.71828 // expected-warning {{floating-point literal is unused}} true // expected-warning {{boolean literal is unused}} false // expected-warning {{boolean literal is unused}} "Hello" // expected-warning {{string literal is unused}} "Hello \(42)" // expected-warning {{string literal is unused}} #file // expected-warning {{#file literal is unused}} (#line) // expected-warning {{#line literal is unused}} #column // expected-warning {{#column literal is unused}} #function // expected-warning {{#function literal is unused}} #dsohandle // expected-warning {{#dsohandle literal is unused}} __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}} expected-warning {{#file literal is unused}} __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}} expected-warning {{#line literal is unused}} __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}} expected-warning {{#column literal is unused}} __FUNCTION__ // expected-error {{__FUNCTION__ has been replaced with #function in Swift 3}} expected-warning {{#function literal is unused}} __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}} expected-warning {{#dsohandle literal is unused}} nil // expected-error {{'nil' requires a contextual type}} #fileLiteral(resourceName: "what.txt") // expected-error {{could not infer type of file reference literal}} expected-note * {{}} #imageLiteral(resourceName: "hello.png") // expected-error {{could not infer type of image literal}} expected-note * {{}} #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error {{could not infer type of color literal}} expected-note * {{}} } // Infix operators and attribute lists. infix operator %% : MinPrecedence precedencegroup MinPrecedence { associativity: left lowerThan: AssignmentPrecedence } func %%(a: Int, b: Int) -> () {} var infixtest : () = 4 % 2 + 27 %% 123 // The 'func' keyword gives a nice simplification for function definitions. func funcdecl1(_ a: Int, _ y: Int) {} func funcdecl2() { return funcdecl1(4, 2) } func funcdecl3() -> Int { return 12 } func funcdecl4(_ a: ((Int) -> Int), b: Int) {} func signal(_ sig: Int, f: (Int) -> Void) -> (Int) -> Void {} // Doing fun things with named arguments. Basic stuff first. func funcdecl6(_ a: Int, b: Int) -> Int { return a+b } // Can dive into tuples, 'b' is a reference to a whole tuple, c and d are // fields in one. Cannot dive into functions or through aliases. func funcdecl7(_ a: Int, b: (c: Int, d: Int), third: (c: Int, d: Int)) -> Int { _ = a + b.0 + b.c + third.0 + third.1 b.foo // expected-error {{value of tuple type '(c: Int, d: Int)' has no member 'foo'}} } // Error recovery. func testfunc2 (_: ((), Int) -> Int) -> Int {} func errorRecovery() { testfunc2({ $0 + 1 }) // expected-error {{contextual closure type '((), Int) -> Int' expects 2 arguments, but 1 was used in closure body}} enum union1 { case bar case baz } var a: Int = .hello // expected-error {{type 'Int' has no member 'hello'}} var b: union1 = .bar // ok var c: union1 = .xyz // expected-error {{type 'union1' has no member 'xyz'}} var d: (Int,Int,Int) = (1,2) // expected-error {{cannot convert value of type '(Int, Int)' to specified type '(Int, Int, Int)'}} var e: (Int,Int) = (1, 2, 3) // expected-error {{cannot convert value of type '(Int, Int, Int)' to specified type '(Int, Int)'}} var f: (Int,Int) = (1, 2, f : 3) // expected-error {{cannot convert value of type '(Int, Int, f: Int)' to specified type '(Int, Int)'}} // <rdar://problem/22426860> CrashTracer: [USER] swift at …mous_namespace::ConstraintGenerator::getTypeForPattern + 698 var (g1, g2, g3) = (1, 2) // expected-error {{'(Int, Int)' is not convertible to '(_, _, _)', tuples have a different number of elements}} } func acceptsInt(_ x: Int) {} acceptsInt(unknown_var) // expected-error {{use of unresolved identifier 'unknown_var'}} var test1a: (Int) -> (Int) -> Int = { { $0 } } // expected-error{{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{38-38= _ in}} var test1b = { 42 } var test1c = { { 42 } } var test1d = { { { 42 } } } func test2(_ a: Int, b: Int) -> (c: Int) { // expected-error{{cannot create a single-element tuple with an element label}} {{34-37=}} expected-note {{did you mean 'a'?}} expected-note {{did you mean 'b'?}} _ = a+b a+b+c // expected-error{{use of unresolved identifier 'c'}} return a+b } func test3(_ arg1: Int, arg2: Int) -> Int { return 4 } func test4() -> ((_ arg1: Int, _ arg2: Int) -> Int) { return test3 } func test5() { let a: (Int, Int) = (1,2) var _: ((Int) -> Int, Int) = a // expected-error {{cannot convert value of type '(Int, Int)' to specified type '((Int) -> Int, Int)'}} let c: (a: Int, b: Int) = (1,2) let _: (b: Int, a: Int) = c // Ok, reshuffle tuple. } // Functions can obviously take and return values. func w3(_ a: Int) -> Int { return a } func w4(_: Int) -> Int { return 4 } func b1() {} func foo1(_ a: Int, b: Int) -> Int {} func foo2(_ a: Int) -> (_ b: Int) -> Int {} func foo3(_ a: Int = 2, b: Int = 3) {} prefix operator ^^ prefix func ^^(a: Int) -> Int { return a + 1 } func test_unary1() { var x: Int x = ^^(^^x) x = *x // expected-error {{'*' is not a prefix unary operator}} x = x* // expected-error {{'*' is not a postfix unary operator}} x = +(-x) x = + -x // expected-error {{unary operator cannot be separated from its operand}} {{8-9=}} } func test_unary2() { var x: Int // FIXME: second diagnostic is redundant. x = &; // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}} } func test_unary3() { var x: Int // FIXME: second diagnostic is redundant. x = &, // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}} } func test_as_1() { var _: Int } func test_as_2() { let x: Int = 1 x as [] // expected-error {{expected element type}} } func test_lambda() { // A simple closure. var a = { (value: Int) -> () in markUsed(value+1) } // A recursive lambda. // FIXME: This should definitely be accepted. var fib = { (n: Int) -> Int in if (n < 2) { return n } return fib(n-1)+fib(n-2) // expected-error 2 {{variable used within its own initial value}} } } func test_lambda2() { { () -> protocol<Int> in // expected-warning @-1 {{'protocol<...>' composition syntax is deprecated and not needed here}} {{11-24=Int}} // expected-error @-2 {{non-protocol type 'Int' cannot be used within a protocol composition}} // expected-warning @-3 {{result of call is unused}} return 1 }() } func test_floating_point() { _ = 0.0 _ = 100.1 var _: Float = 0.0 var _: Double = 0.0 } func test_nonassoc(_ x: Int, y: Int) -> Bool { // FIXME: the second error and note here should arguably disappear return x == y == x // expected-error {{adjacent operators are in non-associative precedence group 'ComparisonPrecedence'}} expected-error {{binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '==' exist with these partially matching parameter lists:}} } // More realistic examples. func fib(_ n: Int) -> Int { if (n < 2) { return n } return fib(n-2) + fib(n-1) } //===----------------------------------------------------------------------===// // Integer Literals //===----------------------------------------------------------------------===// // FIXME: Should warn about integer constants being too large <rdar://problem/14070127> var il_a: Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}} var il_b: Int8 = 123123 var il_c: Int8 = 4 // ok struct int_test4 : ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral value: Int) {} // user type. } var il_g: int_test4 = 4 // This just barely fits in Int64. var il_i: Int64 = 18446744073709551615 // This constant is too large to fit in an Int64, but it is fine for Int128. // FIXME: Should warn about the first. <rdar://problem/14070127> var il_j: Int64 = 18446744073709551616 // var il_k: Int128 = 18446744073709551616 var bin_literal: Int64 = 0b100101 var hex_literal: Int64 = 0x100101 var oct_literal: Int64 = 0o100101 // verify that we're not using C rules var oct_literal_test: Int64 = 0123 assert(oct_literal_test == 123) // ensure that we swallow random invalid chars after the first invalid char var invalid_num_literal: Int64 = 0QWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_bin_literal: Int64 = 0bQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_hex_literal: Int64 = 0xQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_oct_literal: Int64 = 0oQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_exp_literal: Double = 1.0e+QWERTY // expected-error{{expected a digit in floating point exponent}} // rdar://11088443 var negative_int32: Int32 = -1 // <rdar://problem/11287167> var tupleelemvar = 1 markUsed((tupleelemvar, tupleelemvar).1) func int_literals() { // Fits exactly in 64-bits - rdar://11297273 _ = 1239123123123123 // Overly large integer. // FIXME: Should warn about it. <rdar://problem/14070127> _ = 123912312312312312312 } // <rdar://problem/12830375> func tuple_of_rvalues(_ a:Int, b:Int) -> Int { return (a, b).1 } extension Int { func testLexingMethodAfterIntLiteral() {} func _0() {} // Hex letters func ffa() {} // Hex letters + non hex. func describe() {} // Hex letters + 'p'. func eap() {} // Hex letters + 'p' + non hex. func fpValue() {} } 123.testLexingMethodAfterIntLiteral() 0b101.testLexingMethodAfterIntLiteral() 0o123.testLexingMethodAfterIntLiteral() 0x1FFF.testLexingMethodAfterIntLiteral() 123._0() 0b101._0() 0o123._0() 0x1FFF._0() 0x1fff.ffa() 0x1FFF.describe() 0x1FFF.eap() 0x1FFF.fpValue() var separator1: Int = 1_ var separator2: Int = 1_000 var separator4: Int = 0b1111_0000_ var separator5: Int = 0b1111_0000 var separator6: Int = 0o127_777_ var separator7: Int = 0o127_777 var separator8: Int = 0x12FF_FFFF var separator9: Int = 0x12FF_FFFF_ //===----------------------------------------------------------------------===// // Float Literals //===----------------------------------------------------------------------===// var fl_a = 0.0 var fl_b: Double = 1.0 var fl_c: Float = 2.0 // FIXME: crummy diagnostic var fl_d: Float = 2.0.0 // expected-error {{expected named member of numeric literal}} var fl_e: Float = 1.0e42 var fl_f: Float = 1.0e+ // expected-error {{expected a digit in floating point exponent}} var fl_g: Float = 1.0E+42 var fl_h: Float = 2e-42 var vl_i: Float = -.45 // expected-error {{'.45' is not a valid floating point literal; it must be written '0.45'}} {{20-20=0}} var fl_j: Float = 0x1p0 var fl_k: Float = 0x1.0p0 var fl_l: Float = 0x1.0 // expected-error {{hexadecimal floating point literal must end with an exponent}} var fl_m: Float = 0x1.FFFFFEP-2 var fl_n: Float = 0x1.fffffep+2 var fl_o: Float = 0x1.fffffep+ // expected-error {{expected a digit in floating point exponent}} var fl_p: Float = 0x1p // expected-error {{expected a digit in floating point exponent}} var fl_q: Float = 0x1p+ // expected-error {{expected a digit in floating point exponent}} var fl_r: Float = 0x1.0fp // expected-error {{expected a digit in floating point exponent}} var fl_s: Float = 0x1.0fp+ // expected-error {{expected a digit in floating point exponent}} var fl_t: Float = 0x1.p // expected-error {{value of type 'Int' has no member 'p'}} var fl_u: Float = 0x1.p2 // expected-error {{value of type 'Int' has no member 'p2'}} var fl_v: Float = 0x1.p+ // expected-error {{'+' is not a postfix unary operator}} var fl_w: Float = 0x1.p+2 // expected-error {{value of type 'Int' has no member 'p'}} var if1: Double = 1.0 + 4 // integer literal ok as double. var if2: Float = 1.0 + 4 // integer literal ok as float. var fl_separator1: Double = 1_.2_ var fl_separator2: Double = 1_000.2_ var fl_separator3: Double = 1_000.200_001 var fl_separator4: Double = 1_000.200_001e1_ var fl_separator5: Double = 1_000.200_001e1_000 var fl_separator6: Double = 1_000.200_001e1_000 var fl_separator7: Double = 0x1_.0FFF_p1_ var fl_separator8: Double = 0x1_0000.0FFF_ABCDp10_001 var fl_bad_separator1: Double = 1e_ // expected-error {{expected a digit in floating point exponent}} var fl_bad_separator2: Double = 0x1p_ // expected-error {{expected a digit in floating point exponent}} expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} expected-error {{consecutive statements on a line must be separated by ';'}} {{37-37=;}} //===----------------------------------------------------------------------===// // String Literals //===----------------------------------------------------------------------===// var st_a = "" var st_b: String = "" var st_c = "asdfasd // expected-error {{unterminated string literal}} var st_d = " \t\n\r\"\'\\ " // Valid simple escapes var st_e = " \u{12}\u{0012}\u{00000078} " // Valid unicode escapes var st_u1 = " \u{1} " var st_u2 = " \u{123} " var st_u3 = " \u{1234567} " // expected-error {{invalid unicode scalar}} var st_u4 = " \q " // expected-error {{invalid escape sequence in literal}} var st_u5 = " \u{FFFFFFFF} " // expected-error {{invalid unicode scalar}} var st_u6 = " \u{D7FF} \u{E000} " // Fencepost UTF-16 surrogate pairs. var st_u7 = " \u{D800} " // expected-error {{invalid unicode scalar}} var st_u8 = " \u{DFFF} " // expected-error {{invalid unicode scalar}} var st_u10 = " \u{0010FFFD} " // Last valid codepoint, 0xFFFE and 0xFFFF are reserved in each plane var st_u11 = " \u{00110000} " // expected-error {{invalid unicode scalar}} func stringliterals(_ d: [String: Int]) { // rdar://11385385 let x = 4 "Hello \(x+1) world" // expected-warning {{string literal is unused}} "Error: \(x+1"; // expected-error {{unterminated string literal}} "Error: \(x+1 // expected-error {{unterminated string literal}} ; // expected-error {{';' statements are not allowed}} // rdar://14050788 [DF] String Interpolations can't contain quotes "test \("nested")" "test \("\("doubly nested")")" "test \(d["hi"])" "test \("quoted-paren )")" "test \("quoted-paren (")" "test \("\\")" "test \("\n")" "test \("\")" // expected-error {{unterminated string literal}} "test \ // expected-error @-1 {{unterminated string literal}} expected-error @-1 {{invalid escape sequence in literal}} "test \("\ // expected-error @-1 {{unterminated string literal}} "test newline \("something" + "something else")" // expected-error @-2 {{unterminated string literal}} expected-error @-1 {{unterminated string literal}} // expected-warning @+2 {{variable 'x2' was never used; consider replacing with '_' or removing it}} // expected-error @+1 {{unterminated string literal}} var x2 : () = ("hello" + " ; } func testSingleQuoteStringLiterals() { _ = 'abc' // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}} _ = 'abc' + "def" // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}} _ = 'ab\nc' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\nc"}} _ = "abc\('def')" // expected-error{{single-quoted string literal found, use '"'}}{{13-18="def"}} _ = "abc' // expected-error{{unterminated string literal}} _ = 'abc" // expected-error{{unterminated string literal}} _ = "a'c" _ = 'ab\'c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab'c"}} _ = 'ab"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-13="ab\\"c"}} _ = 'ab\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\"c"}} _ = 'ab\\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-15="ab\\\\\\"c"}} } // <rdar://problem/17128913> var s = "" s.append(contentsOf: ["x"]) //===----------------------------------------------------------------------===// // InOut arguments //===----------------------------------------------------------------------===// func takesInt(_ x: Int) {} func takesExplicitInt(_ x: inout Int) { } func testInOut(_ arg: inout Int) { var x: Int takesExplicitInt(x) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{20-20=&}} takesExplicitInt(&x) takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} var y = &x // expected-error{{'&' can only appear immediately in a call argument list}} \ // expected-error {{variable has type 'inout Int' which includes nested inout parameters}} var z = &arg // expected-error{{'&' can only appear immediately in a call argument list}} \ // expected-error {{variable has type 'inout Int' which includes nested inout parameters}} takesExplicitInt(5) // expected-error {{cannot pass immutable value as inout argument: literals are not mutable}} } //===----------------------------------------------------------------------===// // Conversions //===----------------------------------------------------------------------===// var pi_f: Float var pi_d: Double struct SpecialPi {} // Type with no implicit construction. var pi_s: SpecialPi func getPi() -> Float {} // expected-note 3 {{found this candidate}} func getPi() -> Double {} // expected-note 3 {{found this candidate}} func getPi() -> SpecialPi {} enum Empty { } extension Empty { init(_ f: Float) { } } func conversionTest(_ a: inout Double, b: inout Int) { var f: Float var d: Double a = Double(b) a = Double(f) a = Double(d) // no-warning b = Int(a) f = Float(b) var pi_f1 = Float(pi_f) var pi_d1 = Double(pi_d) var pi_s1 = SpecialPi(pi_s) // expected-error {{argument passed to call that takes no arguments}} var pi_f2 = Float(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_d2 = Double(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_s2: SpecialPi = getPi() // no-warning var float = Float.self var pi_f3 = float.init(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_f4 = float.init(pi_f) var e = Empty(f) var e2 = Empty(d) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Float'}} var e3 = Empty(Float(d)) } struct Rule { // expected-note {{'init(target:dependencies:)' declared here}} var target: String var dependencies: String } var ruleVar: Rule ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}} class C { var x: C? init(other: C?) { x = other } func method() {} } _ = C(3) // expected-error {{missing argument label 'other:' in call}} _ = C(other: 3) // expected-error {{cannot convert value of type 'Int' to expected argument type 'C?'}} //===----------------------------------------------------------------------===// // Unary Operators //===----------------------------------------------------------------------===// func unaryOps(_ i8: inout Int8, i64: inout Int64) { i8 = ~i8 i64 += 1 i8 -= 1 Int64(5) += 1 // expected-error{{left side of mutating operator isn't mutable: function call returns immutable value}} // <rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error not being able to apply ++ to Float let a = i8 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a += 1 // expected-error {{left side of mutating operator isn't mutable: 'a' is a 'let' constant}} var b : Int { get { }} b += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a get-only property}} } //===----------------------------------------------------------------------===// // Iteration //===----------------------------------------------------------------------===// func..<(x: Double, y: Double) -> Double { return x + y } func iterators() { _ = 0..<42 _ = 0.0..<42.0 } //===----------------------------------------------------------------------===// // Magic literal expressions //===----------------------------------------------------------------------===// func magic_literals() { _ = __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}} _ = __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}} _ = __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}} _ = __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}} _ = #file _ = #line + #column var _: UInt8 = #line + #column } //===----------------------------------------------------------------------===// // lvalue processing //===----------------------------------------------------------------------===// infix operator +-+= @discardableResult func +-+= (x: inout Int, y: Int) -> Int { return 0} func lvalue_processing() { var i = 0 i += 1 // obviously ok var fn = (+-+=) var n = 42 fn(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{6-6=&}} fn(&n, 12) // expected-warning {{result of call is unused, but produces 'Int'}} n +-+= 12 (+-+=)(&n, 12) // ok. (+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} } struct Foo { func method() {} mutating func mutatingMethod() {} } func test() { var x = Foo() let y = Foo() // FIXME: Bad diagnostics // rdar://15708430 (&x).method() // expected-error {{type of expression is ambiguous without more context}} (&x).mutatingMethod() // expected-error {{cannot use mutating member on immutable value of type 'inout Foo'}} } // Unused results. func unusedExpressionResults() { // Unused l-value _ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} // <rdar://problem/20749592> Conditional Optional binding hides compiler error let optionalc:C? = nil optionalc?.method() // ok optionalc?.method // expected-error {{expression resolves to an unused function}} } //===----------------------------------------------------------------------===// // Collection Literals //===----------------------------------------------------------------------===// func arrayLiterals() { let _ = [1,2,3] let _ : [Int] = [] let _ = [] // expected-error {{empty collection literal requires an explicit type}} } func dictionaryLiterals() { let _ = [1 : "foo",2 : "bar",3 : "baz"] let _: Dictionary<Int, String> = [:] let _ = [:] // expected-error {{empty collection literal requires an explicit type}} } func invalidDictionaryLiteral() { // FIXME: lots of unnecessary diagnostics. var a = [1: ; // expected-error {{expected value in dictionary literal}} var b = [1: ;] // expected-error {{expected value in dictionary literal}} var c = [1: "one" ;] // expected-error {{expected key expression in dictionary literal}} expected-error {{expected ',' separator}} {{20-20=,}} var d = [1: "one", ;] // expected-error {{expected key expression in dictionary literal}} var e = [1: "one", 2] // expected-error {{expected ':' in dictionary literal}} var f = [1: "one", 2 ;] // expected-error {{expected ':' in dictionary literal}} var g = [1: "one", 2: ;] // expected-error {{expected value in dictionary literal}} } // FIXME: The issue here is a type compatibility problem, there is no ambiguity. [4].joined(separator: [1]) // expected-error {{type of expression is ambiguous without more context}} [4].joined(separator: [[[1]]]) // expected-error {{type of expression is ambiguous without more context}} //===----------------------------------------------------------------------===// // nil/metatype comparisons //===----------------------------------------------------------------------===// _ = Int.self == nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}} _ = nil == Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}} _ = Int.self != nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}} _ = nil != Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}} // <rdar://problem/19032294> Disallow postfix ? when not chaining func testOptionalChaining(_ a : Int?, b : Int!, c : Int??) { _ = a? // expected-error {{optional chain has no effect, expression already produces 'Int?'}} {{8-9=}} _ = a?.customMirror _ = b? // expected-error {{'?' must be followed by a call, member lookup, or subscript}} _ = b?.customMirror var _: Int? = c? // expected-error {{'?' must be followed by a call, member lookup, or subscript}} } // <rdar://problem/19657458> Nil Coalescing operator (??) should have a higher precedence func testNilCoalescePrecedence(cond: Bool, a: Int?, r: CountableClosedRange<Int>?) { // ?? should have higher precedence than logical operators like || and comparisons. if cond || (a ?? 42 > 0) {} // Ok. if (cond || a) ?? 42 > 0 {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}} if (cond || a) ?? (42 > 0) {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}} if cond || a ?? 42 > 0 {} // Parses as the first one, not the others. // ?? should have lower precedence than range and arithmetic operators. let r1 = r ?? (0...42) // ok let r2 = (r ?? 0)...42 // not ok: expected-error {{cannot convert value of type 'Int' to expected argument type 'CountableClosedRange<Int>'}} let r3 = r ?? 0...42 // parses as the first one, not the second. // <rdar://problem/27457457> [Type checker] Diagnose unsavory optional injections // Accidental optional injection for ??. let i = 42 _ = i ?? 17 // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Int', so the right side is never used}} {{9-15=}} } // <rdar://problem/19772570> Parsing of as and ?? regressed func testOptionalTypeParsing(_ a : AnyObject) -> String { return a as? String ?? "default name string here" } func testParenExprInTheWay() { let x = 42 if x & 4.0 {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}} if (x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}} if !(x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} //expected-note @-1 {{expected an argument list of type '(Int, Int)'}} if x & x {} // expected-error {{'Int' is not convertible to 'Bool'}} } // <rdar://problem/21352576> Mixed method/property overload groups can cause a crash during constraint optimization public struct TestPropMethodOverloadGroup { public typealias Hello = String public let apply:(Hello) -> Int public func apply(_ input:Hello) -> Int { return apply(input) } } // <rdar://problem/18496742> Passing ternary operator expression as inout crashes Swift compiler func inoutTests(_ arr: inout Int) { var x = 1, y = 2 (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}} // expected-warning @-1 {{expression of type 'inout Int' is unused}} let a = (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}} // expected-error @-1 {{variable has type 'inout Int' which includes nested inout parameters}} inoutTests(true ? &x : &y); // expected-error 2 {{'&' can only appear immediately in a call argument list}} &_ // expected-error {{expression type 'inout _' is ambiguous without more context}} inoutTests((&x)) // expected-error {{'&' can only appear immediately in a call argument list}} inoutTests(&x) // <rdar://problem/17489894> inout not rejected as operand to assignment operator &x += y // expected-error {{'&' can only appear immediately in a call argument list}} // <rdar://problem/23249098> func takeAny(_ x: Any) {} takeAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}} func takeManyAny(_ x: Any...) {} takeManyAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}} takeManyAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}} func takeIntAndAny(_ x: Int, _ y: Any) {} takeIntAndAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}} } // <rdar://problem/20802757> Compiler crash in default argument & inout expr var g20802757 = 2 func r20802757(_ z: inout Int = &g20802757) { // expected-error {{'&' can only appear immediately in a call argument list}} print(z) } _ = _.foo // expected-error {{type of expression is ambiguous without more context}} // <rdar://problem/22211854> wrong arg list crashing sourcekit func r22211854() { func f(_ x: Int, _ y: Int, _ z: String = "") {} // expected-note 2 {{'f' declared here}} func g<T>(_ x: T, _ y: T, _ z: String = "") {} // expected-note 2 {{'g' declared here}} f(1) // expected-error{{missing argument for parameter #2 in call}} g(1) // expected-error{{missing argument for parameter #2 in call}} func h() -> Int { return 1 } f(h() == 1) // expected-error{{missing argument for parameter #2 in call}} g(h() == 1) // expected-error{{missing argument for parameter #2 in call}} } // <rdar://problem/22348394> Compiler crash on invoking function with labeled defaulted param with non-labeled argument func r22348394() { func f(x: Int = 0) { } f(Int(3)) // expected-error{{missing argument label 'x:' in call}} } // <rdar://problem/23185177> Compiler crashes in Assertion failed: ((AllowOverwrite || !E->hasLValueAccessKind()) && "l-value access kind has already been set"), function visit protocol P { var y: String? { get } } func r23185177(_ x: P?) -> [String] { return x?.y // expected-error{{cannot convert return expression of type 'String?' to return type '[String]'}} } // <rdar://problem/22913570> Miscompile: wrong argument parsing when calling a function in swift2.0 func r22913570() { func f(_ from: Int = 0, to: Int) {} // expected-note {{'f(_:to:)' declared here}} f(1 + 1) // expected-error{{missing argument for parameter 'to' in call}} } // <rdar://problem/23708702> Emit deprecation warnings for ++/-- in Swift 2.2 func swift22_deprecation_increment_decrement() { var i = 0 var f = 1.0 i++ // expected-error {{'++' is unavailable}} {{4-6= += 1}} --i // expected-error {{'--' is unavailable}} {{3-5=}} {{6-6= -= 1}} _ = i++ // expected-error {{'++' is unavailable}} ++f // expected-error {{'++' is unavailable}} {{3-5=}} {{6-6= += 1}} f-- // expected-error {{'--' is unavailable}} {{4-6= -= 1}} _ = f-- // expected-error {{'--' is unavailable}} {{none}} // <rdar://problem/24530312> Swift ++fix-it produces bad code in nested expressions // This should not get a fixit hint. var j = 2 i = ++j // expected-error {{'++' is unavailable}} {{none}} } // SR-628 mixing lvalues and rvalues in tuple expression var x = 0 var y = 1 let _ = (x, x + 1).0 let _ = (x, 3).1 (x,y) = (2,3) (x,4) = (1,2) // expected-error {{cannot assign to value: literals are not mutable}} (x,y).1 = 7 // expected-error {{cannot assign to immutable expression of type 'Int'}} x = (x,(3,y)).1.1 // SE-0101 sizeof family functions are reconfigured into MemoryLayout protocol Pse0101 { associatedtype Value func getIt() -> Value } class Cse0101<U> { typealias T = U var val: U { fatalError() } } func se0101<P: Pse0101>(x: Cse0101<P>) { // Note: The first case is actually not allowed, but it is very common and can be compiled currently. _ = sizeof(P) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-16=>.size}} {{none}} // expected-warning@-1 {{missing '.self' for reference to metatype of type 'P'}} _ = sizeof(P.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-21=>.size}} {{none}} _ = sizeof(P.Value.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{21-27=>.size}} {{none}} _ = sizeof(Cse0101<P>.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{24-30=>.size}} {{none}} _ = alignof(Cse0101<P>.T.self) // expected-error {{'alignof' is unavailable: use MemoryLayout<T>.alignment instead.}} {{7-15=MemoryLayout<}} {{27-33=>.alignment}} {{none}} _ = strideof(P.Type.self) // expected-error {{'strideof' is unavailable: use MemoryLayout<T>.stride instead.}} {{7-16=MemoryLayout<}} {{22-28=>.stride}} {{none}} _ = sizeof(type(of: x)) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-26=MemoryLayout<Cse0101<P>>.size}} {{none}} }
apache-2.0
727d6083f1b5625ec91e18251af69ce7
38.32684
310
0.611619
3.629082
false
true
false
false
bman4789/bpm
BPM/BPM/MainViewController.swift
1
3203
// // MainViewController.swift // BPM // // Created by Brian Mitchell and Zach Litzinger on 4/8/16. // Copyright © 2016 Brian Mitchell. All rights reserved. // import UIKit import Foundation import ChameleonFramework import FontAwesome_swift class MainViewController: UIViewController { var loadTheme: Bool = { Style.loadTheme() return true }() @IBOutlet weak var settings: UIButton! @IBOutlet weak var bpmDisplay: UILabel! @IBOutlet weak var bpmTap: BMButton! override func viewDidLoad() { super.viewDidLoad() settings.titleLabel?.font = UIFont.fontAwesomeOfSize(30) settings.setTitle(String.fontAwesomeIconWithName(.Cog), forState: .Normal) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateTheme() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateTheme() { self.setStatusBarStyle(UIStatusBarStyleContrast) self.view.backgroundColor = Style.colorArray[2] bpmDisplay.textColor = UIColor(contrastingBlackOrWhiteColorOn:Style.colorArray[2], isFlat:Style.isFlat) bpmTap.setTitleColor(UIColor(contrastingBlackOrWhiteColorOn:Style.colorArray[2], isFlat:Style.isFlat), forState: UIControlState.Normal) bpmTap.strokeColor = Style.colorArray[1].colorWithAlphaComponent(0.25) bpmTap.rippleColor = Style.colorArray[1].colorWithAlphaComponent(0.33) self.view.tintColor = UIColor(contrastingBlackOrWhiteColorOn:Style.colorArray[2], isFlat:Style.isFlat) } // BPM logic and functionality var X: Double = 0.0 var P: Double = 0.0 var Q: Double = 0.0 var A: Double = 0.0 var H: Double = 0.0 var R: Double = 0.0 var lastTime: NSDate? = nil func initBPM() { X = 1 //Initial Duration between the taps P = 0.1 //Initial confidence in the measurements of the values of x Q = 0.00001 //Constant error: you know that you are often slow A = 1 // ------- might be important? H = 0.001 //How accurately we believe the instrument is measuring R = 0.0001 //Speed of response to variant lastTime = nil } @IBAction func bpmTap(sender: BMButton) { if lastTime?.timeIntervalSinceNow < -5.0 { initBPM() } let timeDiff = timeDifference() let calculation = correct(timeDiff) bpmDisplay.text = "\(Int(60.0 / calculation))" } func timeDifference() -> Double { let currentTime = NSDate() if lastTime == nil { lastTime = NSDate(timeIntervalSinceNow: -1) } let timeDiff = currentTime.timeIntervalSinceDate(lastTime!) lastTime = currentTime return timeDiff } func predict() { X = A * X P = A * P + Q } func correct(measurement: Double) -> Double { predict() let K = P * (1 / (P + R)) X = X + K * (measurement - X) P = (1 - K) * P return X } }
mit
4e31549b39f950801a14ca43ed1775c5
30.087379
143
0.6193
4.453408
false
false
false
false
petroladkin/SwiftyBluetooth
SwiftyBluetooth/Source/CBExtensions.swift
1
6437
// // CBExtensions.swift // // Copyright (c) 2016 Jordane Belanger // // 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 CoreBluetooth extension CBPeripheral { public func serviceWithUUID(_ uuid: CBUUID) -> CBService? { guard let services = self.services else { return nil } return services.filter { $0.uuid == uuid }.first } public func servicesWithUUIDs(_ servicesUUIDs: [CBUUID]) -> (foundServices: [CBService], missingServicesUUIDs: [CBUUID]) { assert(servicesUUIDs.count > 0) guard let currentServices = self.services , currentServices.count > 0 else { return (foundServices: [], missingServicesUUIDs: servicesUUIDs) } let currentServicesUUIDs = currentServices.map { $0.uuid } let currentServicesUUIDsSet = Set(currentServicesUUIDs) let requestedServicesUUIDsSet = Set(servicesUUIDs) let foundServicesUUIDsSet = requestedServicesUUIDsSet.intersection(currentServicesUUIDsSet) let missingServicesUUIDsSet = requestedServicesUUIDsSet.subtracting(currentServicesUUIDsSet) let foundServices = currentServices.filter { foundServicesUUIDsSet.contains($0.uuid) } return (foundServices: foundServices, missingServicesUUIDs: Array(missingServicesUUIDsSet)) } public var uuidIdentifier: UUID { #if os(OSX) if #available(OSX 10.13, *) { return self.identifier } else { let description: String = self.description //<CBPeripheral: 0x6080000c3fe0 identifier = 7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, Name = "(null)", state = disconnected> guard let range = description.range(of:"identifier = .+?,", options:.regularExpression) else { return UUID(uuidString: "11111111-1111-1111-1111-111111111111")! } var uuid = description.substring(with: range) //identifier = 7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, uuid = uuid.substring(from: uuid.index(uuid.startIndex, offsetBy: 13)) //7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, uuid = uuid.substring(to: uuid.index(before: uuid.endIndex)) //7E33A1DD-7E65-4162-89A4-F44A2B4F9D67 return UUID(uuidString: uuid)! } #else return self.identifier #endif } } extension CBService { public func characteristicWithUUID(_ uuid: CBUUID) -> CBCharacteristic? { guard let characteristics = self.characteristics else { return nil } return characteristics.filter { $0.uuid == uuid }.first } public func characteristicsWithUUIDs(_ characteristicsUUIDs: [CBUUID]) -> (foundCharacteristics: [CBCharacteristic], missingCharacteristicsUUIDs: [CBUUID]) { assert(characteristicsUUIDs.count > 0) guard let currentCharacteristics = self.characteristics , currentCharacteristics.count > 0 else { return (foundCharacteristics: [], missingCharacteristicsUUIDs: characteristicsUUIDs) } let currentCharacteristicsUUID = currentCharacteristics.map { $0.uuid } let currentCharacteristicsUUIDSet = Set(currentCharacteristicsUUID) let requestedCharacteristicsUUIDSet = Set(characteristicsUUIDs) let foundCharacteristicsUUIDSet = requestedCharacteristicsUUIDSet.intersection(currentCharacteristicsUUIDSet) let missingCharacteristicsUUIDSet = requestedCharacteristicsUUIDSet.subtracting(currentCharacteristicsUUIDSet) let foundCharacteristics = currentCharacteristics.filter { foundCharacteristicsUUIDSet.contains($0.uuid) } return (foundCharacteristics: foundCharacteristics, missingCharacteristicsUUIDs: Array(missingCharacteristicsUUIDSet)) } } extension CBCharacteristic { public func descriptorWithUUID(_ uuid: CBUUID) -> CBDescriptor? { guard let descriptors = self.descriptors else { return nil } return descriptors.filter { $0.uuid == uuid }.first } public func descriptorsWithUUIDs(_ descriptorsUUIDs: [CBUUID]) -> (foundDescriptors: [CBDescriptor], missingDescriptorsUUIDs: [CBUUID]) { assert(descriptorsUUIDs.count > 0) guard let currentDescriptors = self.descriptors , currentDescriptors.count > 0 else { return (foundDescriptors: [], missingDescriptorsUUIDs: descriptorsUUIDs) } let currentDescriptorsUUIDs = currentDescriptors.map { $0.uuid } let currentDescriptorsUUIDsSet = Set(currentDescriptorsUUIDs) let requestedDescriptorsUUIDsSet = Set(descriptorsUUIDs) let foundDescriptorsUUIDsSet = requestedDescriptorsUUIDsSet.intersection(currentDescriptorsUUIDsSet) let missingDescriptorsUUIDsSet = requestedDescriptorsUUIDsSet.subtracting(currentDescriptorsUUIDsSet) let foundDescriptors = currentDescriptors.filter { foundDescriptorsUUIDsSet.contains($0.uuid) } return (foundDescriptors: foundDescriptors, missingDescriptorsUUIDs: Array(missingDescriptorsUUIDsSet)) } }
mit
74425c98fddec6ce61b10acde25ebd6c
44.013986
161
0.675781
5.145484
false
false
false
false
Fenrikur/ef-app_ios
Eurofurence/Modules/Event Feedback/Presenter/EventFeedbackPresenterFactoryImpl.swift
1
2035
import EurofurenceModel struct EventFeedbackPresenterFactoryImpl: EventFeedbackPresenterFactory { private let eventService: EventsService private let dayOfWeekFormatter: DayOfWeekFormatter private let startTimeFormatter: HoursDateFormatter private let endTimeFormatter: HoursDateFormatter private let successHaptic: SuccessHaptic private let failureHaptic: FailureHaptic private let successWaitingRule: EventFeedbackSuccessWaitingRule init(eventService: EventsService, dayOfWeekFormatter: DayOfWeekFormatter, startTimeFormatter: HoursDateFormatter, endTimeFormatter: HoursDateFormatter, successHaptic: SuccessHaptic, failureHaptic: FailureHaptic, successWaitingRule: EventFeedbackSuccessWaitingRule) { self.eventService = eventService self.dayOfWeekFormatter = dayOfWeekFormatter self.startTimeFormatter = startTimeFormatter self.endTimeFormatter = endTimeFormatter self.successHaptic = successHaptic self.failureHaptic = failureHaptic self.successWaitingRule = successWaitingRule } func makeEventFeedbackPresenter(for event: EventIdentifier, scene: EventFeedbackScene, delegate: EventFeedbackModuleDelegate) { guard let event = eventService.fetchEvent(identifier: event) else { return } _ = EventFeedbackPresenter(event: event, scene: scene, delegate: delegate, dayOfWeekFormatter: dayOfWeekFormatter, startTimeFormatter: startTimeFormatter, endTimeFormatter: endTimeFormatter, successHaptic: successHaptic, failureHaptic: failureHaptic, successWaitingRule: successWaitingRule) } }
mit
d23b3476ccbbdc216d521f574a05723f
44.222222
84
0.635381
7.593284
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/PaymentMethodSelector/Extensions/PXPaymentMethodSelector+Tracking.swift
1
4972
import Foundation // MARK: Tracking extension PXPaymentMethodSelector { func startTracking(then: @escaping (() -> Void)) { viewModel?.trackingConfiguration?.updateTracker() MPXTracker.sharedInstance.startNewSession() // Track init event var properties: [String: Any] = [:] if !String.isNullOrEmpty(viewModel?.checkoutPreference.id) { properties["checkout_preference_id"] = viewModel?.checkoutPreference.id } else if let checkoutPreference = viewModel?.checkoutPreference { properties["checkout_preference"] = getCheckoutPrefForTracking(checkoutPreference: checkoutPreference) } properties["esc_enabled"] = viewModel?.getAdvancedConfiguration().isESCEnabled() properties["express_enabled"] = viewModel?.getAdvancedConfiguration().expressEnabled viewModel?.populateCheckoutStore() properties["split_enabled"] = false MPXTracker.sharedInstance.trackEvent(event: MercadoPagoCheckoutTrackingEvents.didInitFlow(properties)) then() } func trackInitFlowFriction(flowError: InitFlowError) { var properties: [String: Any] = [:] properties["path"] = TrackingPaths.Screens.PaymentVault.getPaymentVaultPath() properties["style"] = Tracking.Style.screen properties["id"] = Tracking.Error.Id.genericError properties["message"] = "Hubo un error" properties["attributable_to"] = Tracking.Error.Atrributable.user var extraDic: [String: Any] = [:] var errorDic: [String: Any] = [:] errorDic["url"] = flowError.requestOrigin?.rawValue errorDic["retry_available"] = flowError.shouldRetry errorDic["status"] = flowError.apiException?.status if let causes = flowError.apiException?.cause { var causesDic: [String: Any] = [:] for cause in causes where !String.isNullOrEmpty(cause.code) { causesDic["code"] = cause.code causesDic["description"] = cause.causeDescription } errorDic["causes"] = causesDic } extraDic["api_error"] = errorDic properties["extra_info"] = extraDic MPXTracker.sharedInstance.trackEvent(event: GeneralErrorTrackingEvents.error(properties)) } func trackInitFlowRefreshFriction(cardId: String) { var properties: [String: Any] = [:] properties["path"] = TrackingPaths.Screens.OneTap.getOneTapPath() properties["style"] = Tracking.Style.noScreen properties["id"] = Tracking.Error.Id.genericError properties["message"] = "No se pudo recuperar la tarjeta ingresada" properties["attributable_to"] = Tracking.Error.Atrributable.mercadopago var extraDic: [String: Any] = [:] extraDic["cardId"] = cardId properties["extra_info"] = extraDic MPXTracker.sharedInstance.trackEvent(event: GeneralErrorTrackingEvents.error(properties)) } private func getCheckoutPrefForTracking(checkoutPreference: PXCheckoutPreference) -> [String: Any] { var checkoutPrefDic: [String: Any] = [:] var itemsDic: [[String: Any]] = [] for item in checkoutPreference.items { itemsDic.append(item.getItemForTracking()) } checkoutPrefDic["items"] = itemsDic checkoutPrefDic["binary_mode"] = checkoutPreference.binaryModeEnabled checkoutPrefDic["marketplace"] = checkoutPreference.marketplace checkoutPrefDic["site_id"] = checkoutPreference.siteId checkoutPrefDic["expiration_date_from"] = checkoutPreference.expirationDateFrom?.stringDate() checkoutPrefDic["expiration_date_to"] = checkoutPreference.expirationDateTo?.stringDate() checkoutPrefDic["payment_methods"] = getPaymentPreferenceForTracking(paymentPreference: checkoutPreference.paymentPreference) return checkoutPrefDic } func getPaymentPreferenceForTracking(paymentPreference: PXPaymentPreference) -> [String: Any] { var paymentPrefDic: [String: Any] = [:] paymentPrefDic["installments"] = paymentPreference.maxAcceptedInstallments paymentPrefDic["default_installments"] = paymentPreference.defaultInstallments paymentPrefDic["excluded_payment_methods"] = transformTrackingArray(paymentPreference.excludedPaymentMethodIds) paymentPrefDic["excluded_payment_types"] = transformTrackingArray(paymentPreference.excludedPaymentTypeIds) paymentPrefDic["default_card_id"] = paymentPreference.cardId return paymentPrefDic } private func transformTrackingArray(_ items: [String]) -> [[String: String]] { var newArray = [[String: String]]() for item in items { let newItem = transformTrackingItem(item) newArray.append(newItem) } return newArray } private func transformTrackingItem(_ item: String) -> [String: String] { return ["id": item] } }
mit
356d44ba4bd9de5d122c80878e7395a6
45.037037
133
0.682019
5.057986
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Scene/GridImageryProvider.swift
1
13191
// // GridImageryProvider.swift // CesiumKit // // Created by Ryan Walklin on 29/09/14. // Copyright (c) 2014 Test Toast. All rights reserved. // /** * An {@link ImageryProvider} that draws a wireframe grid on every tile with controllable background and glow. * May be useful for custom rendering effects or debugging terrain. * * @alias GridImageryProvider * @constructor * * @param {Object} [options] Object with the following properties: * @param {TilingScheme} [options.tilingScheme=new GeographicTilingScheme()] The tiling scheme for which to draw tiles. * @param {Number} [options.cells=8] The number of grids cells. * @param {Color} [options.color=Color(1.0, 1.0, 1.0, 0.4)] The color to draw grid lines. * @param {Color} [options.glowColor=Color(0.0, 1.0, 0.0, 0.05)] The color to draw glow for grid lines. * @param {Number} [options.glowWidth=6] The width of lines used for rendering the line glow effect. * @param {Color} [backgroundColor=Color(0.0, 0.5, 0.0, 0.2)] Background fill color. * @param {Number} [options.tileWidth=256] The width of the tile for level-of-detail selection purposes. * @param {Number} [options.tileHeight=256] The height of the tile for level-of-detail selection purposes. * @param {Number} [options.canvasSize=256] The size of the canvas used for rendering. */ class GridImageryProvider/*: ImageryProvider*/ { /* /*global define*/ define([ '../Core/Color', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/Event', '../Core/GeographicTilingScheme' ], function( Color, defaultValue, defined, defineProperties, Event, GeographicTilingScheme) { "use strict"; var defaultColor = new Color(1.0, 1.0, 1.0, 0.4); var defaultGlowColor = new Color(0.0, 1.0, 0.0, 0.05); var defaultBackgroundColor = new Color(0.0, 0.5, 0.0, 0.2); /** * An {@link ImageryProvider} that draws a wireframe grid on every tile with controllable background and glow. * May be useful for custom rendering effects or debugging terrain. * * @alias GridImageryProvider * @constructor * * @param {Object} [options] Object with the following properties: * @param {TilingScheme} [options.tilingScheme=new GeographicTilingScheme()] The tiling scheme for which to draw tiles. * @param {Ellipsoid} [options.ellipsoid] The ellipsoid. If the tilingScheme is specified, * this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither * parameter is specified, the WGS84 ellipsoid is used. * @param {Number} [options.cells=8] The number of grids cells. * @param {Color} [options.color=Color(1.0, 1.0, 1.0, 0.4)] The color to draw grid lines. * @param {Color} [options.glowColor=Color(0.0, 1.0, 0.0, 0.05)] The color to draw glow for grid lines. * @param {Number} [options.glowWidth=6] The width of lines used for rendering the line glow effect. * @param {Color} [backgroundColor=Color(0.0, 0.5, 0.0, 0.2)] Background fill color. * @param {Number} [options.tileWidth=256] The width of the tile for level-of-detail selection purposes. * @param {Number} [options.tileHeight=256] The height of the tile for level-of-detail selection purposes. * @param {Number} [options.canvasSize=256] The size of the canvas used for rendering. */ var GridImageryProvider = function GridImageryProvider(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); this._tilingScheme = defined(options.tilingScheme) ? options.tilingScheme : new GeographicTilingScheme({ ellipsoid : options.ellipsoid }); this._cells = defaultValue(options.cells, 8); this._color = defaultValue(options.color, defaultColor); this._glowColor = defaultValue(options.glowColor, defaultGlowColor); this._glowWidth = defaultValue(options.glowWidth, 6); this._backgroundColor = defaultValue(options.backgroundColor, defaultBackgroundColor); this._errorEvent = new Event(); this._tileWidth = defaultValue(options.tileWidth, 256); this._tileHeight = defaultValue(options.tileHeight, 256); // A little larger than tile size so lines are sharper // Note: can't be too much difference otherwise texture blowout this._canvasSize = defaultValue(options.canvasSize, 256); // We only need a single canvas since all tiles will be the same this._canvas = this._createGridCanvas(); }; defineProperties(GridImageryProvider.prototype, { /** * Gets the proxy used by this provider. * @memberof GridImageryProvider.prototype * @type {Proxy} * @readonly */ proxy : { get : function() { return undefined; } }, /** * Gets the width of each tile, in pixels. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ tileWidth : { get : function() { return this._tileWidth; } }, /** * Gets the height of each tile, in pixels. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ tileHeight : { get : function() { return this._tileHeight; } }, /** * Gets the maximum level-of-detail that can be requested. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ maximumLevel : { get : function() { return undefined; } }, /** * Gets the minimum level-of-detail that can be requested. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ minimumLevel : { get : function() { return undefined; } }, /** * Gets the tiling scheme used by this provider. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {TilingScheme} * @readonly */ tilingScheme : { get : function() { return this._tilingScheme; } }, /** * Gets the rectangle, in radians, of the imagery provided by this instance. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Rectangle} * @readonly */ rectangle : { get : function() { return this._tilingScheme.rectangle; } }, /** * Gets the tile discard policy. If not undefined, the discard policy is responsible * for filtering out "missing" tiles via its shouldDiscardImage function. If this function * returns undefined, no tiles are filtered. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {TileDiscardPolicy} * @readonly */ tileDiscardPolicy : { get : function() { return undefined; } }, /** * Gets an event that is raised when the imagery provider encounters an asynchronous error. By subscribing * to the event, you will be notified of the error and can potentially recover from it. Event listeners * are passed an instance of {@link TileProviderError}. * @memberof GridImageryProvider.prototype * @type {Event} * @readonly */ errorEvent : { get : function() { return this._errorEvent; } }, /** * Gets a value indicating whether or not the provider is ready for use. * @memberof GridImageryProvider.prototype * @type {Boolean} * @readonly */ ready : { get : function() { return true; } }, /** * Gets the credit to display when this imagery provider is active. Typically this is used to credit * the source of the imagery. This function should not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Credit} * @readonly */ credit : { get : function() { return undefined; } }, /** * Gets a value indicating whether or not the images provided by this imagery provider * include an alpha channel. If this property is false, an alpha channel, if present, will * be ignored. If this property is true, any images without an alpha channel will be treated * as if their alpha is 1.0 everywhere. When this property is false, memory usage * and texture upload time are reduced. * @memberof GridImageryProvider.prototype * @type {Boolean} * @readonly */ hasAlphaChannel : { get : function() { return true; } } }); /** * Draws a grid of lines into a canvas. */ GridImageryProvider.prototype._drawGrid = function(context) { var minPixel = 0; var maxPixel = this._canvasSize; for (var x = 0; x <= this._cells; ++x) { var nx = x / this._cells; var val = 1 + nx * (maxPixel - 1); context.moveTo(val, minPixel); context.lineTo(val, maxPixel); context.moveTo(minPixel, val); context.lineTo(maxPixel, val); } context.stroke(); }; /** * Render a grid into a canvas with background and glow */ GridImageryProvider.prototype._createGridCanvas = function() { var canvas = document.createElement('canvas'); canvas.width = this._canvasSize; canvas.height = this._canvasSize; var minPixel = 0; var maxPixel = this._canvasSize; var context = canvas.getContext('2d'); // Fill the background var cssBackgroundColor = this._backgroundColor.toCssColorString(); context.fillStyle = cssBackgroundColor; context.fillRect(minPixel, minPixel, maxPixel, maxPixel); // Glow for grid lines var cssGlowColor = this._glowColor.toCssColorString(); context.strokeStyle = cssGlowColor; // Wide context.lineWidth = this._glowWidth; context.strokeRect(minPixel, minPixel, maxPixel, maxPixel); this._drawGrid(context); // Narrow context.lineWidth = this._glowWidth * 0.5; context.strokeRect(minPixel, minPixel, maxPixel, maxPixel); this._drawGrid(context); // Grid lines var cssColor = this._color.toCssColorString(); // Border context.strokeStyle = cssColor; context.lineWidth = 2; context.strokeRect(minPixel, minPixel, maxPixel, maxPixel); // Inner context.lineWidth = 1; this._drawGrid(context); return canvas; }; /** * Gets the credits to be displayed when a given tile is displayed. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level; * @returns {Credit[]} The credits to be displayed when the tile is displayed. * * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready. */ GridImageryProvider.prototype.getTileCredits = function(x, y, level) { return undefined; }; /** * Requests the image for a given tile. This function should * not be called before {@link GridImageryProvider#ready} returns true. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @returns {Promise.<Image|Canvas>|undefined} A promise for the image that will resolve when the image is available, or * undefined if there are too many active requests to the server, and the request * should be retried later. The resolved image may be either an * Image or a Canvas DOM object. */ GridImageryProvider.prototype.requestImage = function(x, y, level) { return this._canvas; }; /** * Picking features is not currently supported by this imagery provider, so this function simply returns * undefined. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @param {Number} longitude The longitude at which to pick features. * @param {Number} latitude The latitude at which to pick features. * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous * picking completes. The resolved value is an array of {@link ImageryLayerFeatureInfo} * instances. The array may be empty if no features are found at the given location. * It may also be undefined if picking is not supported. */ GridImageryProvider.prototype.pickFeatures = function() { return undefined; }; return GridImageryProvider; }); */ }
apache-2.0
f4a44f328923622d939cbc9102a80492
34.847826
142
0.659692
4.3235
false
false
false
false
linusnyberg/RepoList
Pods/OAuthSwift/Sources/String+OAuthSwift.swift
1
2643
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { var urlEncodedString: String { let customAllowedSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") let escapedString = self.addingPercentEncoding(withAllowedCharacters: customAllowedSet) return escapedString! } var parametersFromQueryString: [String: String] { return dictionaryBySplitting("&", keyValueSeparator: "=") } var urlQueryEncoded: String? { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } fileprivate func dictionaryBySplitting(_ elementSeparator: String, keyValueSeparator: String) -> [String: String] { var string = self if(hasPrefix(elementSeparator)) { string = String(characters.dropFirst(1)) } var parameters = Dictionary<String, String>() let scanner = Scanner(string: string) var key: NSString? var value: NSString? while !scanner.isAtEnd { key = nil scanner.scanUpTo(keyValueSeparator, into: &key) scanner.scanString(keyValueSeparator, into: nil) value = nil scanner.scanUpTo(elementSeparator, into: &value) scanner.scanString(elementSeparator, into: nil) if let key = key as String?, let value = value as String? { parameters.updateValue(value, forKey: key) } } return parameters } public var headerDictionary: OAuthSwift.Headers { return dictionaryBySplitting(",", keyValueSeparator: "=") } var safeStringByRemovingPercentEncoding: String { return self.removingPercentEncoding ?? self } var droppedLast: String { return self.substring(to: self.index(before: self.endIndex)) } mutating func dropLast() { self.remove(at: self.index(before: self.endIndex)) } func substring(to offset: String.IndexDistance) -> String{ return self.substring(to: self.index(self.startIndex, offsetBy: offset)) } func substring(from offset: String.IndexDistance) -> String{ return self.substring(from: self.index(self.startIndex, offsetBy: offset)) } } extension String.Encoding { var charset: String { let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.rawValue)) return charset! as String } }
mit
d7578d37bba1f97eaa7f2f458e822c80
27.728261
128
0.663261
5.053537
false
false
false
false
suifengqjn/CatLive
CatLive/CatLive/Classes/Home/CLPageView/CLPageView.swift
1
2466
// // CLPageView.swift // CatLive // // Created by qianjn on 2017/6/11. // Copyright © 2017年 SF. All rights reserved. // import UIKit class CLPageView: UIView { // MARK: 定义属性 fileprivate var titles : [String]! fileprivate var style : CLTitleStyle! fileprivate var childVcs : [UIViewController]! fileprivate weak var parentVc : UIViewController! fileprivate var titleView : CLTitleView! fileprivate var contentView : CLContentView! // MARK: 自定义构造函数 init(frame: CGRect, titles : [String], style : CLTitleStyle, childVcs : [UIViewController], parentVc : UIViewController) { super.init(frame: frame) assert(titles.count == childVcs.count, "标题&控制器个数不同,请检测!!!") self.style = style self.titles = titles self.childVcs = childVcs self.parentVc = parentVc parentVc.automaticallyAdjustsScrollViewInsets = false setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置界面内容 extension CLPageView { fileprivate func setupUI() { let titleH : CGFloat = 44 let titleFrame = CGRect(x: 0, y: 0, width: frame.width, height: titleH) titleView = CLTitleView(frame: titleFrame, titles: titles, style : style) titleView.delegate = self addSubview(titleView) let contentFrame = CGRect(x: 0, y: titleH, width: frame.width, height: frame.height - titleH) contentView = CLContentView(frame: contentFrame, childVcs: childVcs, parentViewController: parentVc) contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] contentView.delegate = self addSubview(contentView) } } // MARK:- 设置CLContentView的代理 extension CLPageView : CLContentViewDelegate { func contentView(_ contentView: CLContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { titleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } func contentViewEndScroll(_ contentView: CLContentView) { titleView.contentViewDidEndScroll() } } // MARK:- 设置CLTitleView的代理 extension CLPageView : CLTitleViewDelegate { func titleView(_ titleView: CLTitleView, selectedIndex index: Int) { contentView.setCurrentIndex(index) } }
apache-2.0
5f1f8bba779d6f8d9fcb451fa60c981b
29.576923
126
0.672956
4.750996
false
false
false
false
mlilback/rc2SwiftClient
MacClient/session/output/OutputTabController.swift
1
11634
// // OutputTabController.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Cocoa import Rc2Common import MJLLogger import Networking import ClientCore import ReactiveSwift import SwiftyUserDefaults enum OutputTab: Int { case console = 0, preview, webKit, image, help } // to allow parent controller to potentially modify contextual menu of a child controller protocol ContextualMenuDelegate: class { func contextMenuItems(for: OutputController) -> [NSMenuItem] } protocol OutputController: Searchable { var contextualMenuDelegate: ContextualMenuDelegate? { get set } } class OutputTabController: NSTabViewController, OutputHandler, ToolbarItemHandler { // MARK: properties @IBOutlet var additionContextMenuItems: NSMenu? var currentOutputController: OutputController! weak var consoleController: ConsoleOutputController? weak var previewController: LivePreviewDisplayController? weak var imageController: ImageOutputController? weak var webController: WebKitOutputController? weak var helpController: HelpOutputController? weak var searchButton: NSSegmentedControl? var previewOutputController: LivePreviewOutputController? { return previewController } var imageCache: ImageCache? { return sessionController?.session.imageCache } weak var sessionController: SessionController? { didSet { sessionControllerUpdated() } } weak var displayedFile: AppFile? var searchBarVisible: Bool { get { return currentOutputController.searchBarVisible } set { currentOutputController.performFind(action: newValue ? .showFindInterface : .hideFindInterface) } } let selectedOutputTab = MutableProperty<OutputTab>(.console) /// temp storage for state to restore because asked to restore before session is set private var restoredState: SessionState.OutputControllerState? // MARK: methods override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayHelp(_:)), name: .displayHelpTopic, object: nil) selectedOutputTab.signal.observe(on: UIScheduler()).observeValues { [weak self] tab in self?.switchTo(tab: tab) } } override func viewWillAppear() { super.viewWillAppear() guard consoleController == nil else { return } consoleController = firstChildViewController(self) consoleController?.viewFileOrImage = { [weak self] (fw) in self?.displayAttachment(fw) } consoleController?.contextualMenuDelegate = self previewController = firstChildViewController(self) previewController?.contextualMenuDelegate = self imageController = firstChildViewController(self) imageController?.imageCache = imageCache imageController?.contextualMenuDelegate = self webController = firstChildViewController(self) webController?.onClear = { [weak self] in self?.selectedOutputTab.value = .console } webController?.contextualMenuDelegate = self helpController = firstChildViewController(self) helpController?.contextualMenuDelegate = self currentOutputController = consoleController } private func sessionControllerUpdated() { imageController?.imageCache = imageCache DispatchQueue.main.async { self.loadSavedState() } } override func viewDidAppear() { super.viewDidAppear() if let myView = tabView as? OutputTopView { myView.windowSetCall = { self.hookupToToolbarItems(self, window: myView.window!) } } } @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let action = menuItem.action else { return false } switch action { case #selector(switchToSubView(_:)): guard let desiredTab = OutputTab(rawValue: menuItem.tag) else { return false } return desiredTab != selectedOutputTab.value default: return false } } func initialFirstResponder() -> NSResponder { return (self.consoleController?.consoleTextField)! } func handlesToolbarItem(_ item: NSToolbarItem) -> Bool { if item.itemIdentifier.rawValue == "clear" { item.target = self item.action = #selector(OutputTabController.clearConsole(_:)) if let myItem = item as? ClearConsoleToolbarItem { myItem.textView = consoleController?.resultsView myItem.tabController = self } return true } else if item.itemIdentifier.rawValue == "search" { searchButton = item.view as? NSSegmentedControl TargetActionBlock { [weak self] _ in self?.toggleSearchBar() }.installInControl(searchButton!) if let myItem = item as? ValidatingToolbarItem { myItem.validationHandler = { [weak self] item in item.isEnabled = self?.currentOutputController.supportsSearchBar ?? false } } return true } return false } func switchToPreview() { guard selectedOutputTab.value != .preview else { return } selectedOutputTab.value = .preview } func showHelp(_ topics: [HelpTopic]) { guard topics.count > 0 else { if let rstr = sessionController?.format(errorString: NSLocalizedString("No Help Found", comment: "")) { consoleController?.append(responseString: rstr) } return } if topics.count == 1 { showHelpTopic(topics[0]) return } //TODO: handle prompt for selecting a topic out of topics showHelpTopic(topics[0]) } @objc func handleDisplayHelp(_ note: Notification) { if let topic: HelpTopic = note.object as? HelpTopic { showHelpTopic(topic) } else if let topicName = note.object as? String { showHelp(HelpController.shared.topicsWithName(topicName)) } else { //told to show without a topic. switch back to console. selectedOutputTab.value = .console } } func toggleSearchBar() { let action: NSTextFinder.Action = currentOutputController.searchBarVisible ? .hideFindInterface : .showFindInterface currentOutputController.performFind(action: action) } @IBAction func clearConsole(_ sender: Any?) { consoleController?.clearConsole(sender) imageCache?.clearCache() } /// action that switches to the OutputTab specified in a NSMenuItem's tag property @IBAction func switchToSubView(_ sender: Any?) { guard let mItem = sender as? NSMenuItem, let tab = OutputTab(rawValue: mItem.tag) else { return } selectedOutputTab.value = tab } func displayAttachment(_ fileWrapper: FileWrapper) { Log.info("told to display file \(fileWrapper.filename!)", .app) guard let attachment = try? MacConsoleAttachment.from(data: fileWrapper.regularFileContents!) else { Log.warn("asked to display invalid attachment", .app) return } switch attachment.type { case .file: if let file = sessionController?.session.workspace.file(withId: attachment.fileId) { webController?.load(file: file) selectedOutputTab.value = .webKit } else { Log.warn("error getting file attachment to display: \(attachment.fileId)", .app) let err = AppError(.fileNoLongerExists) presentError(err, modalFor: view.window!, delegate: nil, didPresent: nil, contextInfo: nil) } case .image: if let image = attachment.image { imageController?.display(image: image) selectedOutputTab.value = .image // This might not be necessary tabView.window?.toolbar?.validateVisibleItems() } } } func show(file: AppFile?) { //strip optional guard let file = file else { webController?.clearContents() selectedOutputTab.value = .console displayedFile = nil return } let url = self.sessionController!.session.fileCache.cachedUrl(file: file) guard url.fileSize() > 0 else { //caching/download bug. not sure what causes it. recache the file and then call again sessionController?.session.fileCache.recache(file: file).observe(on: UIScheduler()).startWithCompleted { self.show(file: file) } return } displayedFile = file // use webkit to handle images the user selected since the imageView only works with images in the cache self.selectedOutputTab.value = .webKit self.webController?.load(file: file) } func append(responseString: ResponseString) { consoleController?.append(responseString: responseString) //switch back to console view if appropriate type switch responseString.type { case .input, .output, .error: if selectedOutputTab.value != .console { selectedOutputTab.value = .console } default: break } } /// This is called when the current file in the editor has changed. /// It should decide if the output view should be changed to match the editor document. /// /// - Parameter editorMode: the mode of the editor func considerTabChange(editorMode: EditorMode) { switch editorMode { case .preview: selectedOutputTab.value = .preview case .source: selectedOutputTab.value = .console } } func handleSearch(action: NSTextFinder.Action) { currentOutputController.performFind(action: action) } func save(state: inout SessionState.OutputControllerState) { state.selectedTabId = selectedOutputTab.value.rawValue state.selectedImageId = imageController?.selectedImageId ?? 0 consoleController?.save(state: &state) webController?.save(state: &state.webViewState) helpController?.save(state: &state.helpViewState) } func restore(state: SessionState.OutputControllerState) { restoredState = state } /// actually loads the state from instance variable func loadSavedState() { guard let savedState = restoredState else { return } consoleController?.restore(state: savedState) if let selTab = OutputTab(rawValue: savedState.selectedTabId) { self.selectedOutputTab.value = selTab } let imgId = savedState.selectedImageId self.imageController?.display(imageId: imgId) webController?.restore(state: savedState.webViewState) helpController?.restore(state: savedState.helpViewState) restoredState = nil } } // MARK: - contextual menu delegate extension OutputTabController: ContextualMenuDelegate { func contextMenuItems(for: OutputController) -> [NSMenuItem] { // have to return copies of items guard let tmpMenu = additionContextMenuItems?.copy() as? NSMenu else { return [] } return tmpMenu.items } } // MARK: - private methods private extension OutputTabController { /// should only ever be called via the closure for selectedOutputTab.signal.observeValues set in viewDidLoad. func switchTo(tab: OutputTab) { selectedTabViewItemIndex = tab.rawValue switch selectedOutputTab.value { case .console: currentOutputController = consoleController case .preview: currentOutputController = previewController case .image: currentOutputController = imageController case .webKit: currentOutputController = webController case .help: currentOutputController = helpController } if view.window?.firstResponder == nil { view.window?.makeFirstResponder(currentOutputController as? NSResponder) } } ///actually shows the help page for the specified topic func showHelpTopic(_ topic: HelpTopic) { selectedOutputTab.value = .help helpController!.loadHelpTopic(topic) } } // MARK: - helper classes class OutputTopView: NSTabView { var windowSetCall: (() -> Void)? override func viewDidMoveToWindow() { if self.window != nil { windowSetCall?() } windowSetCall = nil } } class ClearConsoleToolbarItem: NSToolbarItem { var textView: NSTextView? weak var tabController: NSTabViewController? override func validate() { guard let textLength = textView?.textStorage?.length else { isEnabled = false; return } isEnabled = textLength > 0 && tabController?.selectedTabViewItemIndex == 0 } } class OutputConsoleToolbarItem: NSToolbarItem { weak var tabController: NSTabViewController? override func validate() { guard let tabController = tabController else { return } isEnabled = tabController.selectedTabViewItemIndex > 0 } }
isc
831f7d68b3489ecba59a6a139a50b017
32.048295
128
0.75303
4.184532
false
false
false
false
Swiftline/Swiftline
Source/Env.swift
3
2313
// // Env.swift // Swiftline // // Created by Omar Abdelhafith on 24/11/2015. // Copyright © 2015 Omar Abdelhafith. All rights reserved. // import Darwin public class Env { /// Return the list of all the enviromenment keys passed to the script public static var keys: [String] { let keyValues = run("env").stdout.components(separatedBy: "\n") let keys = keyValues.map { $0.components(separatedBy: "=").first! }.filter { !$0.isEmpty } return keys } /// Return the list of all the enviromenment values passed to the script public static var values: [String] { return self.keys.map { self.get($0)! } } /** Return the enviromenment for the provided key - parameter key: The enviromenment variable key - returns: The enviromenment variable value */ public static func get(_ key: String) -> String? { guard let value = getenv(key) else { return nil } return String(cString: value) } /** Set a new value for the enviromenment variable - parameter key: The enviromenment variable key - parameter value: The enviromenment variable value */ public static func set(_ key: String, _ value: String?) { if let newValue = value { setenv(key, newValue, 1) } else { unsetenv(key) } } /** Clear all the enviromenment variables */ public static func clear() { self.keys .map { String($0) } .filter { $0 != nil } .forEach{ self.set($0!, nil) } } /** Check if the enviromenment variable key exists - parameter key: The enviromenment variable key - returns: true if exists false otherwise */ public static func hasKey(_ key: String) -> Bool { return self.keys.contains(key) } /** Check if the enviromenment variable value exists - parameter key: The enviromenment variable value - returns: true if exists false otherwise */ public static func hasValue(_ value: String) -> Bool { return self.values.contains(value) } /** Iterate through the list of enviromenment variables - parameter callback: callback to call on each key/value pair */ public static func eachPair(_ callback: (_ key: String, _ value: String) -> ()) { zip(self.keys, self.values).forEach(callback) } }
mit
26bcb1bdd31484bb1bac9c012e599b20
23.336842
94
0.641436
4.188406
false
false
false
false
banxi1988/Staff
Pods/BXiOSUtils/Pod/Classes/CGRectExtentions.swift
1
1611
// // CGRectExtentions.swift // Pods // // Created by Haizhen Lee on 15/12/18. // // import Foundation import UIKit public extension CGSize{ public func sizeByScaleToWidth(width:CGFloat) -> CGSize{ let factor = width / self.width let h = self.height * factor return CGSize(width: width, height: h) } public init(size:CGFloat){ self.init(width:size,height:size) } } public extension CGRect{ public func rectBySliceLeft(left:CGFloat) -> CGRect{ return CGRect(x: origin.x + left, y: origin.y, width: width - left, height: height) } public func rectBySliceRight(right:CGFloat) -> CGRect{ return CGRect(x: origin.x, y: origin.y, width: width - right, height: height) } public func rectBySliceTop(top:CGFloat) -> CGRect{ return insetBy(dx: 0, dy: top) } } extension CGRect{ public var center:CGPoint{ get{ return CGPoint(x: midX, y: midY) } set(newCenter){ origin.x = newCenter.x - (width / 2) origin.y = newCenter.y - (height / 2 ) } } public init(center:CGPoint,radius:CGFloat){ origin = CGPoint(x: center.x - radius, y: center.y - radius) size = CGSize(width: radius, height: radius) } public init(center:CGPoint,width:CGFloat, height:CGFloat){ origin = CGPoint(x: center.x - width * 0.5, y: center.y - height * 0.5) size = CGSize(width: width, height: height) } public init(center:CGPoint,size:CGSize){ origin = CGPoint(x: center.x - size.width * 0.5, y: center.y - size.height * 0.5) self.size = size } public var area:CGFloat{ return width * height } }
mit
5a6499a58474e0ec756c039ea2dbc1bf
23.059701
87
0.6437
3.30123
false
false
false
false
RocketChat/Rocket.Chat.iOS
Pods/MobilePlayer/MobilePlayer/MobilePlayerViewController.swift
1
25438
// // MobilePlayerViewController.swift // MobilePlayer // // Created by Baris Sencan on 12/02/15. // Copyright (c) 2015 MovieLaLa. All rights reserved. // import UIKit import MediaPlayer /// A view controller for playing media content. open class MobilePlayerViewController: MPMoviePlayerViewController { // MARK: Playback State /// Playback state. public enum State { /// Either playback has not started or playback was stopped due to a `stop()` call or an error. When an error /// occurs, a corresponding `MobilePlayerDidEncounterErrorNotification` notification is posted. case idle /// The video will start playing, but sufficient data to start playback has to be loaded first. case buffering /// The video is currently playing. case playing /// The video is currently paused. case paused } /// The previous value of `state`. Default is `.Idle`. public private(set) var previousState: State = .idle /// Current `State` of the player. Default is `.Idle`. public private(set) var state: State = .idle { didSet { previousState = oldValue } } // MARK: Player Configuration // TODO: Move inside MobilePlayerConfig private static let playbackInterfaceUpdateInterval = 0.25 /// The global player configuration object that is loaded by a player if none is passed for its /// initialization. public static let globalConfig = MobilePlayerConfig() /// The configuration object that was used to initialize the player, may point to the global player configuration /// object. public let config: MobilePlayerConfig // MARK: Mapped Properties /// A localized string that represents the video this controller manages. Setting a value will update the title label /// in the user interface if one exists. open override var title: String? { didSet { guard let titleLabel = getViewForElementWithIdentifier("title") as? Label else { return} titleLabel.text = title titleLabel.superview?.setNeedsLayout() } } // MARK: Private Properties private let controlsView: MobilePlayerControlsView private var previousStatusBarHiddenValue: Bool? private var previousStatusBarStyle: UIStatusBarStyle! private var isFirstPlay = true fileprivate var seeking = false fileprivate var wasPlayingBeforeSeek = false private var playbackInterfaceUpdateTimer: Timer? private var hideControlsTimer: Timer? // MARK: Initialization /// Initializes a player with content given by `contentURL`. If provided, the overlay view controllers used to /// initialize the player should be different instances from each other. /// /// - parameters: /// - contentURL: URL of the content that will be used for playback. /// - config: Player configuration. Defaults to `globalConfig`. /// - prerollViewController: Pre-roll view controller. Defaults to `nil`. /// - pauseOverlayViewController: Pause overlay view controller. Defaults to `nil`. /// - postrollViewController: Post-roll view controller. Defaults to `nil`. public init(contentURL: URL, config: MobilePlayerConfig = MobilePlayerViewController.globalConfig, prerollViewController: MobilePlayerOverlayViewController? = nil, pauseOverlayViewController: MobilePlayerOverlayViewController? = nil, postrollViewController: MobilePlayerOverlayViewController? = nil) { self.config = config controlsView = MobilePlayerControlsView(config: config) self.prerollViewController = prerollViewController self.pauseOverlayViewController = pauseOverlayViewController self.postrollViewController = postrollViewController super.init(contentURL: contentURL) initializeMobilePlayerViewController() } /// Returns a player initialized from data in a given unarchiver. `globalConfig` is used for configuration in this /// case. In most cases the other intializer should be used. /// /// - parameters: /// - coder: An unarchiver object. public required init?(coder aDecoder: NSCoder) { config = MobilePlayerViewController.globalConfig controlsView = MobilePlayerControlsView(config: config) self.prerollViewController = nil self.pauseOverlayViewController = nil self.postrollViewController = nil super.init(coder: aDecoder) initializeMobilePlayerViewController() } private func initializeMobilePlayerViewController() { view.clipsToBounds = true edgesForExtendedLayout = [] moviePlayer.scalingMode = .aspectFit moviePlayer.controlStyle = .none initializeNotificationObservers() initializeControlsView() parseContentURLIfNeeded() if let watermarkConfig = config.watermarkConfig { showOverlayViewController(WatermarkViewController(config: watermarkConfig)) } } private func initializeNotificationObservers() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( forName: NSNotification.Name.MPMoviePlayerPlaybackStateDidChange, object: moviePlayer, queue: OperationQueue.main) { [weak self] notification in guard let slf = self else { return } slf.handleMoviePlayerPlaybackStateDidChangeNotification() NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerStateDidChangeNotification), object: slf) } notificationCenter.removeObserver( self, name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer) notificationCenter.addObserver( forName: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer, queue: OperationQueue.main) { [weak self] notification in guard let slf = self else { return } if let userInfo = notification.userInfo as? [String: AnyObject], let error = userInfo["error"] as? NSError { NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerDidEncounterErrorNotification), object: self, userInfo: [MobilePlayerErrorUserInfoKey: error]) } if let postrollVC = slf.postrollViewController { slf.prerollViewController?.dismiss() slf.pauseOverlayViewController?.dismiss() slf.showOverlayViewController(postrollVC) } } } private func initializeControlsView() { (getViewForElementWithIdentifier("playback") as? Slider)?.delegate = self (getViewForElementWithIdentifier("close") as? Button)?.addCallback( callback: { [weak self] in guard let slf = self else { return } if let navigationController = slf.navigationController { navigationController.popViewController(animated: true) } else if let presentingController = slf.presentingViewController { presentingController.dismissMoviePlayerViewControllerAnimated() } }, forControlEvents: .touchUpInside) if let actionButton = getViewForElementWithIdentifier("action") as? Button { actionButton.isHidden = true // Initially hidden until 1 or more `activityItems` are set. actionButton.addCallback( callback: { [weak self] in guard let slf = self else { return } slf.showContentActions(sourceView: actionButton) }, forControlEvents: .touchUpInside) } (getViewForElementWithIdentifier("play") as? ToggleButton)?.addCallback( callback: { [weak self] in guard let slf = self else { return } slf.resetHideControlsTimer() slf.state == .playing ? slf.pause() : slf.play() }, forControlEvents: .touchUpInside) initializeControlsViewTapRecognizers() } private func initializeControlsViewTapRecognizers() { let singleTapRecognizer = UITapGestureRecognizer { [weak self] in self?.handleContentTap() } singleTapRecognizer.numberOfTapsRequired = 1 controlsView.addGestureRecognizer(singleTapRecognizer) let doubleTapRecognizer = UITapGestureRecognizer { [weak self] in self?.handleContentDoubleTap() } doubleTapRecognizer.numberOfTapsRequired = 2 controlsView.addGestureRecognizer(doubleTapRecognizer) singleTapRecognizer.require(toFail: doubleTapRecognizer) } // MARK: View Controller Lifecycle /// Called after the controller'€™s view is loaded into memory. /// /// This method is called after the view controller has loaded its view hierarchy into memory. This method is /// called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the /// `loadView` method. You usually override this method to perform additional initialization on views that were /// loaded from nib files. /// /// If you override this method make sure you call super's implementation. open override func viewDidLoad() { super.viewDidLoad() view.addSubview(controlsView) playbackInterfaceUpdateTimer = Timer.scheduledTimerWithTimeInterval( ti: MobilePlayerViewController.playbackInterfaceUpdateInterval, callback: { [weak self] in self?.updatePlaybackInterface() }, repeats: true) if let prerollViewController = prerollViewController { shouldAutoplay = false showOverlayViewController(prerollViewController) } } /// Called to notify the view controller that its view is about to layout its subviews. /// /// When a view'€™s bounds change, the view adjusts the position of its subviews. Your view controller can override /// this method to make changes before the view lays out its subviews. /// /// The default implementation of this method sets the frame of the controls view. open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() controlsView.frame = view.bounds } /// Notifies the view controller that its view is about to be added to a view hierarchy. /// /// If `true`, the view is being added to the window using an animation. /// /// The default implementation of this method hides the status bar. /// /// - parameters: /// - animated: If `true`, the view is being added to the window using an animation. open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Force hide status bar. previousStatusBarHiddenValue = UIApplication.shared.isStatusBarHidden UIApplication.shared.isStatusBarHidden = true setNeedsStatusBarAppearanceUpdate() } /// Notifies the view controller that its view is about to be removed from a view hierarchy. /// /// If `true`, the disappearance of the view is being animated. /// /// The default implementation of this method stops playback and restores status bar appearance to how it was before /// the view appeared. /// /// - parameters: /// - animated: If `true`, the disappearance of the view is being animated. open override func viewWillDisappear(_ animated: Bool) { // Restore status bar appearance. if let previousStatusBarHidden = previousStatusBarHiddenValue { UIApplication.shared.isStatusBarHidden = previousStatusBarHidden setNeedsStatusBarAppearanceUpdate() } super.viewWillDisappear(animated) stop() } // MARK: Deinitialization deinit { playbackInterfaceUpdateTimer?.invalidate() hideControlsTimer?.invalidate() NotificationCenter.default.removeObserver(self) } // MARK: Playback /// Indicates whether content should begin playback automatically. /// /// The default value of this property is true. This property determines whether the playback of network-based /// content begins automatically when there is enough buffered data to ensure uninterrupted playback. public var shouldAutoplay: Bool { get { return moviePlayer.shouldAutoplay } set { moviePlayer.shouldAutoplay = newValue } } /// Initiates playback of current content. /// /// Starting playback causes dismiss to be called on prerollViewController, pauseOverlayViewController /// and postrollViewController. public func play() { moviePlayer.play() } /// Pauses playback of current content. /// /// Pausing playback causes pauseOverlayViewController to be shown. public func pause() { moviePlayer.pause() } /// Ends playback of current content. public func stop() { moviePlayer.stop() } // MARK: Video Rendering /// Makes playback content fit into player's view. public func fitVideo() { moviePlayer.scalingMode = .aspectFit } /// Makes playback content fill player's view. public func fillVideo() { moviePlayer.scalingMode = .aspectFill } /// Makes playback content switch between fill/fit modes when content area is double tapped. Overriding this method /// is recommended if you want to change this behavior. public func handleContentDoubleTap() { // TODO: videoScalingMode property and enum. moviePlayer.scalingMode != .aspectFill ? fillVideo() : fitVideo() } // MARK: Social /// An array of activity items that will be used for presenting a `UIActivityViewController` when the action /// button is pressed (if it exists). If content is playing, it is paused automatically at presentation and will /// continue after the controller is dismissed. Override `showContentActions()` if you want to change the button's /// behavior. public var activityItems: [Any]? { didSet { let isEmpty = activityItems?.isEmpty ?? true getViewForElementWithIdentifier("action")?.isHidden = isEmpty } } /// An array of activity types that will be excluded when presenting a `UIActivityViewController` public var excludedActivityTypes: [UIActivity.ActivityType]? = [ .assignToContact, .saveToCameraRoll, .postToVimeo, .airDrop ] /// Method that is called when a control interface button with identifier "action" is tapped. Presents a /// `UIActivityViewController` with `activityItems` set as its activity items. If content is playing, it is paused /// automatically at presentation and will continue after the controller is dismissed. Overriding this method is /// recommended if you want to change this behavior. /// /// parameters: /// - sourceView: On iPads the activity view controller is presented as a popover and a source view needs to /// provided or a crash will occur. open func showContentActions(sourceView: UIView? = nil) { guard let activityItems = activityItems, !activityItems.isEmpty else { return } let wasPlaying = (state == .playing) moviePlayer.pause() let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) activityVC.excludedActivityTypes = excludedActivityTypes activityVC.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in if wasPlaying { self.moviePlayer.play() } } if let sourceView = sourceView { activityVC.popoverPresentationController?.sourceView = controlsView activityVC.popoverPresentationController?.sourceRect = sourceView.convert( sourceView.bounds, to: controlsView) } present(activityVC, animated: true, completion: nil) } // MARK: Controls /// Indicates if player controls are hidden. Setting its value will animate controls in or out. public var controlsHidden: Bool { get { return controlsView.controlsHidden } set { newValue ? hideControlsTimer?.invalidate() : resetHideControlsTimer() controlsView.controlsHidden = newValue } } /// Returns the view associated with given player control element identifier. /// /// - parameters: /// - identifier: Element identifier. /// - returns: View or nil if element is not found. public func getViewForElementWithIdentifier(_ identifier: String) -> UIView? { if let view = controlsView.topBar.getViewForElementWithIdentifier(identifier: identifier) { return view } return controlsView.bottomBar.getViewForElementWithIdentifier(identifier: identifier) } /// Hides/shows controls when content area is tapped once. Overriding this method is recommended if you want to change /// this behavior. public func handleContentTap() { controlsHidden = !controlsHidden } // MARK: Overlays private var timedOverlays = [TimedOverlayInfo]() /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content at start. If a /// controller is set then content will not start playing automatically even if `shouldAutoplay` is `true`. The /// controller will dismiss if user presses the play button or `play()` is called. public let prerollViewController: MobilePlayerOverlayViewController? /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content whenever playback is /// paused. Does not include pauses in playback due to buffering. public let pauseOverlayViewController: MobilePlayerOverlayViewController? /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content when playback /// finishes. public let postrollViewController: MobilePlayerOverlayViewController? /// Presents given overlay view controller on top of the player content immediately, or at a given content time for /// a given duration. Both starting time and duration parameters should be provided to show a timed overlay. /// /// - parameters: /// - overlayViewController: The `MobilePlayerOverlayViewController` to be presented. /// - startingAtTime: Content time the overlay will be presented at. /// - forDuration: Added on top of `startingAtTime` to calculate the content time when overlay will be dismissed. public func showOverlayViewController(_ overlayViewController: MobilePlayerOverlayViewController, startingAtTime presentationTime: TimeInterval? = nil, forDuration showDuration: TimeInterval? = nil) { if let presentationTime = presentationTime, let showDuration = showDuration { timedOverlays.append(TimedOverlayInfo( startTime: presentationTime, duration: showDuration, overlay: overlayViewController)) } else if overlayViewController.parent == nil { overlayViewController.delegate = self addChild(overlayViewController) overlayViewController.view.clipsToBounds = true overlayViewController.view.frame = controlsView.overlayContainerView.bounds controlsView.overlayContainerView.addSubview(overlayViewController.view) overlayViewController.didMove(toParent: self) } } /// Dismisses all currently presented overlay view controllers and clears any timed overlays. public func clearOverlays() { for timedOverlayInfo in timedOverlays { timedOverlayInfo.overlay.dismiss() } timedOverlays.removeAll() for childViewController in children { if childViewController is WatermarkViewController { continue } (childViewController as? MobilePlayerOverlayViewController)?.dismiss() } } // MARK: Private Methods private func parseContentURLIfNeeded() { guard let youtubeID = YoutubeParser.youtubeIDFromURL(url: moviePlayer.contentURL) else { return } YoutubeParser.h264videosWithYoutubeID(youtubeID) { videoInfo, error in if let error = error { NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerDidEncounterErrorNotification), object: self, userInfo: [MobilePlayerErrorUserInfoKey: error]) } guard let videoInfo = videoInfo else { return } self.title = self.title ?? videoInfo.title if let previewImageURLString = videoInfo.previewImageURL, let previewImageURL = URL(string: previewImageURLString) { URLSession.shared.dataTask(with: previewImageURL) { data, response, error in guard let data = data else { return } DispatchQueue.main.async { self.controlsView.previewImageView.image = UIImage(data: data) } } } if let videoURL = videoInfo.videoURL { self.moviePlayer.contentURL = URL(string: videoURL) } } } private func doFirstPlaySetupIfNeeded() { if isFirstPlay { isFirstPlay = false controlsView.previewImageView.isHidden = true controlsView.activityIndicatorView.stopAnimating() } } private func updatePlaybackInterface() { if let playbackSlider = getViewForElementWithIdentifier("playback") as? Slider { playbackSlider.maximumValue = Float(moviePlayer.duration.isNormal ? moviePlayer.duration : 0) if !seeking { let sliderValue = Float(moviePlayer.currentPlaybackTime.isNormal ? moviePlayer.currentPlaybackTime : 0) playbackSlider.setValue(value: sliderValue, animatedForDuration: MobilePlayerViewController.playbackInterfaceUpdateInterval) } let availableValue = Float(moviePlayer.playableDuration.isNormal ? moviePlayer.playableDuration : 0) playbackSlider.setAvailableValue( availableValue: availableValue, animatedForDuration: MobilePlayerViewController.playbackInterfaceUpdateInterval) } if let currentTimeLabel = getViewForElementWithIdentifier("currentTime") as? Label { currentTimeLabel.text = textForPlaybackTime(time: moviePlayer.currentPlaybackTime) currentTimeLabel.superview?.setNeedsLayout() } if let remainingTimeLabel = getViewForElementWithIdentifier("remainingTime") as? Label { remainingTimeLabel.text = "-\(textForPlaybackTime(time: moviePlayer.duration - moviePlayer.currentPlaybackTime))" remainingTimeLabel.superview?.setNeedsLayout() } if let durationLabel = getViewForElementWithIdentifier("duration") as? Label { durationLabel.text = textForPlaybackTime(time: moviePlayer.duration) durationLabel.superview?.setNeedsLayout() } updateShownTimedOverlays() } private func textForPlaybackTime(time: TimeInterval) -> String { if !time.isNormal { return "00:00" } let hours = Int(floor(time / 3600)) let minutes = Int(floor((time / 60).truncatingRemainder(dividingBy: 60))) let seconds = Int(floor(time.truncatingRemainder(dividingBy: 60))) let minutesAndSeconds = NSString(format: "%02d:%02d", minutes, seconds) as String if hours > 0 { return NSString(format: "%02d:%@", hours, minutesAndSeconds) as String } else { return minutesAndSeconds } } private func resetHideControlsTimer() { hideControlsTimer?.invalidate() hideControlsTimer = Timer.scheduledTimerWithTimeInterval( ti: 3, callback: { self.controlsView.controlsHidden = (self.state == .playing) }, repeats: false) } private func handleMoviePlayerPlaybackStateDidChangeNotification() { state = StateHelper.calculateStateUsing(previousState: previousState, andPlaybackState: moviePlayer.playbackState) let playButton = getViewForElementWithIdentifier("play") as? ToggleButton if state == .playing { doFirstPlaySetupIfNeeded() playButton?.toggled = true if !controlsView.controlsHidden { resetHideControlsTimer() } prerollViewController?.dismiss() pauseOverlayViewController?.dismiss() postrollViewController?.dismiss() } else { playButton?.toggled = false hideControlsTimer?.invalidate() controlsView.controlsHidden = false if let pauseOverlayViewController = pauseOverlayViewController, (state == .paused && !seeking) { showOverlayViewController(pauseOverlayViewController) } } } private func updateShownTimedOverlays() { let currentTime = self.moviePlayer.currentPlaybackTime if !currentTime.isNormal { return } DispatchQueue.global().async { for timedOverlayInfo in self.timedOverlays { if timedOverlayInfo.startTime <= currentTime && currentTime <= timedOverlayInfo.startTime + timedOverlayInfo.duration { if timedOverlayInfo.overlay.parent == nil { DispatchQueue.main.async { self.showOverlayViewController(timedOverlayInfo.overlay) } } } else if timedOverlayInfo.overlay.parent != nil { DispatchQueue.main.async { timedOverlayInfo.overlay.dismiss() } } } } } } // MARK: - MobilePlayerOverlayViewControllerDelegate extension MobilePlayerViewController: MobilePlayerOverlayViewControllerDelegate { func dismiss(mobilePlayerOverlayViewController overlayViewController: MobilePlayerOverlayViewController) { overlayViewController.willMove(toParent: nil) overlayViewController.view.removeFromSuperview() overlayViewController.removeFromParent() if overlayViewController == prerollViewController { play() } } } // MARK: - TimeSliderDelegate extension MobilePlayerViewController: SliderDelegate { func sliderThumbPanDidBegin(slider: Slider) { seeking = true wasPlayingBeforeSeek = (state == .playing) pause() } func sliderThumbDidPan(slider: Slider) {} func sliderThumbPanDidEnd(slider: Slider) { seeking = false moviePlayer.currentPlaybackTime = TimeInterval(slider.value) if wasPlayingBeforeSeek { play() } } }
mit
322acc0f9bf79140745494f5148a3a28
38.371517
186
0.721672
5.495678
false
false
false
false
ben-ng/swift
test/type/self.swift
10
866
// RUN: %target-typecheck-verify-swift struct S0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{21-25=S0}} } class C0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{21-25=C0}} } enum E0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{21-25=E0}} } // rdar://problem/21745221 struct X { typealias T = Int } extension X { struct Inner { } } extension X.Inner { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'Inner'?}}{{21-25=Inner}} }
apache-2.0
e45fe9b01cc6cf66b9c8800eb02a8be0
31.074074
167
0.648961
3.115108
false
false
false
false
adrfer/swift
stdlib/public/core/StringCharacterView.swift
1
10908
//===--- StringCharacterView.swift - String's Collection of Characters ----===// // // 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 // //===----------------------------------------------------------------------===// // // String is-not-a SequenceType or CollectionType, but it exposes a // collection of characters. // //===----------------------------------------------------------------------===// extension String { /// A `String`'s collection of `Character`s ([extended grapheme /// clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster)) /// elements. public struct CharacterView { internal var _core: _StringCore /// Create a view of the `Character`s in `text`. public init(_ text: String) { self._core = text._core } public // @testable init(_ _core: _StringCore) { self._core = _core } } /// A collection of `Characters` representing the `String`'s /// [extended grapheme /// clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster). public var characters: CharacterView { return CharacterView(self) } /// Efficiently mutate `self` by applying `body` to its `characters`. /// /// - Warning: Do not rely on anything about `self` (the `String` /// that is the target of this method) during the execution of /// `body`: it may not appear to have its correct value. Instead, /// use only the `String.CharacterView` argument to `body`. public mutating func withMutableCharacters<R>(body: (inout CharacterView) -> R) -> R { // Naively mutating self.characters forces multiple references to // exist at the point of mutation. Instead, temporarily move the // core of this string into a CharacterView. var tmp = CharacterView("") swap(&_core, &tmp._core) let r = body(&tmp) swap(&_core, &tmp._core) return r } /// Construct the `String` corresponding to the given sequence of /// Unicode scalars. public init(_ characters: CharacterView) { self.init(characters._core) } } /// `String.CharacterView` is a collection of `Character`. extension String.CharacterView : CollectionType { internal typealias UnicodeScalarView = String.UnicodeScalarView internal var unicodeScalars: UnicodeScalarView { return UnicodeScalarView(_core) } /// A character position. public struct Index : BidirectionalIndexType, Comparable, _Reflectable { public // SPI(Foundation) init(_base: String.UnicodeScalarView.Index) { self._base = _base self._lengthUTF16 = Index._measureExtendedGraphemeClusterForward(_base) } internal init(_base: UnicodeScalarView.Index, _lengthUTF16: Int) { self._base = _base self._lengthUTF16 = _lengthUTF16 } /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. public func successor() -> Index { _precondition(_base != _base._viewEndIndex, "cannot increment endIndex") return Index(_base: _endBase) } /// Returns the previous consecutive value before `self`. /// /// - Requires: The previous value is representable. public func predecessor() -> Index { _precondition(_base != _base._viewStartIndex, "cannot decrement startIndex") let predecessorLengthUTF16 = Index._measureExtendedGraphemeClusterBackward(_base) return Index( _base: UnicodeScalarView.Index( _utf16Index - predecessorLengthUTF16, _base._core)) } internal let _base: UnicodeScalarView.Index /// The length of this extended grapheme cluster in UTF-16 code units. internal let _lengthUTF16: Int /// The integer offset of this index in UTF-16 code units. public // SPI(Foundation) var _utf16Index: Int { return _base._position } /// The one past end index for this extended grapheme cluster in Unicode /// scalars. internal var _endBase: UnicodeScalarView.Index { return UnicodeScalarView.Index( _utf16Index + _lengthUTF16, _base._core) } /// Returns the length of the first extended grapheme cluster in UTF-16 /// code units. @warn_unused_result internal static func _measureExtendedGraphemeClusterForward( start: UnicodeScalarView.Index ) -> Int { var start = start let end = start._viewEndIndex if start == end { return 0 } let startIndexUTF16 = start._position let unicodeScalars = UnicodeScalarView(start._core) let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[start].value) start._successorInPlace() while start != end { // FIXME(performance): consider removing this "fast path". A branch // that is hard to predict could be worse for performance than a few // loads from cache to fetch the property 'gcb1'. if segmenter.isBoundaryAfter(gcb0) { break } let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[start].value) if segmenter.isBoundary(gcb0, gcb1) { break } gcb0 = gcb1 start._successorInPlace() } return start._position - startIndexUTF16 } /// Returns the length of the previous extended grapheme cluster in UTF-16 /// code units. @warn_unused_result internal static func _measureExtendedGraphemeClusterBackward( end: UnicodeScalarView.Index ) -> Int { let start = end._viewStartIndex if start == end { return 0 } let endIndexUTF16 = end._position let unicodeScalars = UnicodeScalarView(start._core) let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() var graphemeClusterStart = end graphemeClusterStart._predecessorInPlace() var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[graphemeClusterStart].value) var graphemeClusterStartUTF16 = graphemeClusterStart._position while graphemeClusterStart != start { graphemeClusterStart._predecessorInPlace() let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[graphemeClusterStart].value) if segmenter.isBoundary(gcb1, gcb0) { break } gcb0 = gcb1 graphemeClusterStartUTF16 = graphemeClusterStart._position } return endIndexUTF16 - graphemeClusterStartUTF16 } /// Returns a mirror that reflects `self`. public func _getMirror() -> _MirrorType { return _IndexMirror(self) } } /// The position of the first `Character` if `self` is /// non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return Index(_base: unicodeScalars.startIndex) } /// The "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return Index(_base: unicodeScalars.endIndex) } /// Access the `Character` at `position`. /// /// - Requires: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(i: Index) -> Character { return Character(String(unicodeScalars[i._base..<i._endBase])) } internal struct _IndexMirror : _MirrorType { var _value: Index init(_ x: Index) { _value = x } var value: Any { return _value } var valueType: Any.Type { return (_value as Any).dynamicType } var objectIdentifier: ObjectIdentifier? { return nil } var disposition: _MirrorDisposition { return .Aggregate } var count: Int { return 0 } subscript(i: Int) -> (String, _MirrorType) { _preconditionFailure("_MirrorType access out of bounds") } var summary: String { return "\(_value._utf16Index)" } var quickLookObject: PlaygroundQuickLook? { return .Int(Int64(_value._utf16Index)) } } } extension String.CharacterView : RangeReplaceableCollectionType { /// Create an empty instance. public init() { self.init("") } /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`subRange.count`) if `subRange.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceRange< C: CollectionType where C.Generator.Element == Character >( subRange: Range<Index>, with newElements: C ) { let rawSubRange = subRange.startIndex._base._position ..< subRange.endIndex._base._position let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 } _core.replaceRange(rawSubRange, with: lazyUTF16) } /// Reserve enough space to store `n` ASCII characters. /// /// - Complexity: O(`n`). public mutating func reserveCapacity(n: Int) { _core.reserveCapacity(n) } /// Append `c` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(c: Character) { switch c._representation { case .Small(let _63bits): let bytes = Character._smallValue(_63bits) _core.appendContentsOf(Character._SmallUTF16(bytes)) case .Large(_): _core.append(String(c)._core) } } /// Append the elements of `newElements` to `self`. public mutating func appendContentsOf< S : SequenceType where S.Generator.Element == Character >(newElements: S) { reserveCapacity(_core.count + newElements.underestimateCount()) for c in newElements { self.append(c) } } /// Create an instance containing `characters`. public init< S : SequenceType where S.Generator.Element == Character >(_ characters: S) { self = String.CharacterView() self.appendContentsOf(characters) } } // Algorithms extension String.CharacterView { /// Access the characters in the given `subRange`. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(subRange: Range<Index>) -> String.CharacterView { let unicodeScalarRange = subRange.startIndex._base..<subRange.endIndex._base return String.CharacterView( String(_core).unicodeScalars[unicodeScalarRange]._core) } }
apache-2.0
b2413d36ffe464e44e6d12720de3438c
30.98827
88
0.656124
4.645656
false
false
false
false
fschneider1509/RuleBasedXMLParserDelegate
RuleBasedXMLParserDelegateKit/XMLRuleBasedParserDelegate.swift
1
3710
// // XMLRuleBasedParserDelegate.swift // RuleBasedXMLParserDelegate // // Created by Fabian Schneider // fabian(at)fabianschneider.org // MIT License // import Foundation class XMLRuleBasedParserDelegate<T: XMLParserNodeProtocol> : NSObject, XMLParserDelegate, XMLRuleBasedParserDelegateProtocol { private let _xmlDocument: XMLParserDocument private let _rootNode: T init(rootNode: inout T) { _rootNode = rootNode _xmlDocument = XMLParserDocument() } func addRule(rule: XMLParserRuleProtocol) { _xmlDocument.addRule(rule: rule) } func parserDidStartDocument(_ parser: XMLParser) { // Stub } func parserDidEndDocument(_ parser: XMLParser) { // Stub } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let parent: String? = _xmlDocument.getParentElement() if let parent = parent { let rule: XMLParserEndEventRuleProtocol? = _xmlDocument.getRuleForElement(elementName: elementName, parentName: parent, ruleType: XMLParserEndEventRuleProtocol.self) as! XMLParserEndEventRuleProtocol? if let rule = rule { rule.doOnElementEnd(rootNode: _rootNode) } _xmlDocument.popElement() } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing end tag of an element!", element: elementName)) } catch {} } } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { _xmlDocument.pushElement(elementName: elementName) let parent: String? = _xmlDocument.getParentElement() if let parent = parent { let rule: XMLParserStartEventRuleProtocol? = _xmlDocument.getRuleForElement(elementName: elementName, parentName: parent, ruleType: XMLParserStartEventRuleProtocol.self) as! XMLParserStartEventRuleProtocol? if let rule = rule { rule.doOnElementStart(rootNode: _rootNode) } } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing start tag of an element!", element: elementName)) } catch {} } } func parser(_ parser: XMLParser, foundCharacters string: String) { let parent: String? = _xmlDocument.getParentElement() let currentElement: String? = _xmlDocument.getCurrentElement() if let parent = parent { if let currentElement = currentElement { let rule: XMLParserReadRuleProtocol? = _xmlDocument.getRuleForElement(elementName: currentElement, parentName: parent, ruleType: XMLParserReadRuleProtocol.self) as! XMLParserReadRuleProtocol? if let rule = rule { rule.doOnElementRead(elementValue: string, rootNode: _rootNode) } } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing start tag of an element - parent!", element: parent)) } catch {} } } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing value of an element!", element: "")) } catch {} } } func throwParsingError(error: XMLParserDelegateError) throws { throw error } }
mit
e44aa9048f3f84dd98c423ece7186b04
40.685393
218
0.645013
5.338129
false
false
false
false
mcomisso/hellokiwi
kiwi/BWWalkthroughViewController.swift
1
10144
// // BWWalkthroughViewController.swift // // Created by Yari D'areglia on 15/09/14 (wait... why do I wrote code the Day of my Birthday?! C'Mon Yari... ) // Copyright (c) 2014 Yari D'areglia. All rights reserved. // import UIKit // MARK: - Protocols - /** Walkthrough Delegate: This delegate performs basic operations such as dismissing the Walkthrough or call whatever action on page change. Probably the Walkthrough is presented by this delegate. **/ @objc protocol BWWalkthroughViewControllerDelegate{ @objc optional func walkthroughCloseButtonPressed() // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed. @objc optional func walkthroughNextButtonPressed() // @objc optional func walkthroughPrevButtonPressed() // @objc optional func walkthroughPageDidChange(pageNumber:Int) // Called when current page changes } /** Walkthrough Page: The walkthrough page represents any page added to the Walkthrough. At the moment it's only used to perform custom animations on didScroll. **/ @objc protocol BWWalkthroughPage{ // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. @objc func walkthroughDidScroll(position:CGFloat, offset:CGFloat) // Called when the main Scrollview...scroll } @objc(BWWalkthroughViewController) class BWWalkthroughViewController: UIViewController, UIScrollViewDelegate{ // MARK: - Public properties - var delegate:BWWalkthroughViewControllerDelegate? // TODO: If you need a page control, next or prev buttons add them via IB and connect them with these Outlets @IBOutlet var pageControl:UIPageControl? @IBOutlet var nextButton:UIButton? @IBOutlet var prevButton:UIButton? @IBOutlet var closeButton:UIButton? var currentPage:Int{ // The index of the current page (readonly) get{ let page = Int((scrollview.contentOffset.x / view.bounds.size.width)) return page } } // MARK: - Private properties - private let scrollview:UIScrollView! private var controllers:[UIViewController]! private var lastViewConstraint:NSArray? // MARK: - Overrides - required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Setup the scrollview scrollview = UIScrollView() scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.pagingEnabled = true // Controllers as empty array controllers = Array() } override init() { super.init() scrollview = UIScrollView() controllers = Array() } override func viewDidLoad() { super.viewDidLoad() // Initialize UIScrollView scrollview.delegate = self scrollview.setTranslatesAutoresizingMaskIntoConstraints(false) view.insertSubview(scrollview, atIndex: 0) //scrollview is inserted as first view of the hierarchy // Set scrollview related constraints view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollview]-0-|", options:nil, metrics: nil, views: ["scrollview":scrollview])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollview]-0-|", options:nil, metrics: nil, views: ["scrollview":scrollview])) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); pageControl?.numberOfPages = controllers.count pageControl?.currentPage = 0 } // MARK: - Internal methods - @IBAction func nextPage(){ if (currentPage + 1) < controllers.count { delegate?.walkthroughNextButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(currentPage + 1) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } @IBAction func prevPage(){ if currentPage > 0 { delegate?.walkthroughNextButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(currentPage - 1) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } // TODO: If you want to implement a "skip" option // connect a button to this IBAction and implement the delegate with the skipWalkthrough @IBAction func close(sender: AnyObject){ delegate?.walkthroughCloseButtonPressed?() } /** addViewController Add a new page to the walkthrough. To have information about the current position of the page in the walkthrough add a UIVIewController which implements BWWalkthroughPage */ func addViewController(vc:UIViewController)->Void{ controllers.append(vc) // Setup the viewController view vc.view.setTranslatesAutoresizingMaskIntoConstraints(false) scrollview.addSubview(vc.view) // Constraints let metricDict = ["w":vc.view.bounds.size.width,"h":vc.view.bounds.size.height] // - Generic cnst vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(h)]", options:nil, metrics: metricDict, views: ["view":vc.view])) vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(w)]", options:nil, metrics: metricDict, views: ["view":vc.view])) scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]|", options:nil, metrics: nil, views: ["view":vc.view,])) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]", options:nil, metrics: nil, views: ["view":vc.view,])) // cnst for position: other elements }else{ let previousVC = controllers[controllers.count-2] let previousView = previousVC.view; scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousView]-0-[view]", options:nil, metrics: nil, views: ["previousView":previousView,"view":vc.view])) if let cst = lastViewConstraint{ scrollview.removeConstraints(cst) } lastViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[view]-|", options:nil, metrics: nil, views: ["view":vc.view]) scrollview.addConstraints(lastViewConstraint!) } } /** Update the UI to reflect the current walkthrough situation **/ private func updateUI(){ // Get the current page pageControl?.currentPage = currentPage // Notify delegate about the new page delegate?.walkthroughPageDidChange?(currentPage) // Hide/Show navigation buttons if currentPage == controllers.count - 1{ nextButton?.hidden = true }else{ nextButton?.hidden = false } if currentPage == 0{ prevButton?.hidden = true }else{ prevButton?.hidden = false } } // MARK: - Scrollview Delegate - func scrollViewDidScroll(sv: UIScrollView) { for var i=0; i < controllers.count; i++ { if let vc = controllers[i] as? BWWalkthroughPage{ let mx = ((scrollview.contentOffset.x + view.bounds.size.width) - (view.bounds.size.width * CGFloat(i))) / view.bounds.size.width // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. // print the mx value to get more info. // println("\(i):\(mx)") // We animate only the previous, current and next page if(mx < 2 && mx > -2.0){ vc.walkthroughDidScroll(scrollview.contentOffset.x, offset: mx) } } } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { updateUI() } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { updateUI() } /* WIP */ override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { println("CHANGE") } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { println("SIZE") } }
apache-2.0
53bf878094dba4dd0091f98fe36cac79
37.139098
194
0.633182
5.297128
false
false
false
false
actilot/ACMaterialDesignIcons
ACMaterialDesignIcons.swift
1
45525
// // ACMaterialDesignIcons.swift // ACMaterialDesignIcons // // Created by Axel Ros Campaña on 9/5/17. // Copyright © 2017 Axel Ros Campaña. All rights reserved. // import Foundation import UIKit public class ACMaterialDesignIcons { public var iconAttributedString: NSMutableAttributedString? public var fontSize: CGFloat = 0.0 public static func loadFont() { let bundle = Bundle(for: ACMaterialDesignIcons.self) let identifier = bundle.bundleIdentifier let name = "Material-Design-Iconic-Font" var fontURL: URL if identifier?.hasPrefix("org.cocoapods") == true { // If this framework is added using CocoaPods, resources is placed under a subdirectory fontURL = bundle.url(forResource: name, withExtension: "ttf", subdirectory: "ACMaterialDesignIcons.bundle")! } else { fontURL = bundle.url(forResource: name, withExtension: "ttf")! } let fontDataProvider = CGDataProvider(url: fontURL as CFURL) let newFont = CGFont(fontDataProvider!) CTFontManagerRegisterGraphicsFont(newFont, nil) } public static func icon(withCode code: String!, fontSize: CGFloat) -> ACMaterialDesignIcons { loadFont() let icon = ACMaterialDesignIcons() icon.fontSize = fontSize icon.iconAttributedString = NSMutableAttributedString(string: code, attributes: [NSFontAttributeName: iconFont(withSize: fontSize)!]) return icon } public static func iconFont(withSize size: CGFloat) -> UIFont? { let font = UIFont(name: "Material-Design-Iconic-Font", size: size) return font } public func image(_ imageSize: CGSize? = nil) -> UIImage { var imageSize = imageSize if imageSize == nil { imageSize = CGSize(width: fontSize, height: fontSize) } UIGraphicsBeginImageContextWithOptions(imageSize!, false, UIScreen.main.scale) let iconSize = iconAttributedString?.size() let xOffset = (imageSize!.width - iconSize!.width) / 2.0 let yOffset = (imageSize!.height - iconSize!.height) / 2.0 let rect = CGRect(x: xOffset, y: yOffset, width: iconSize!.width, height: iconSize!.height) iconAttributedString?.draw(in: rect) let iconImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return iconImage! } public func rangeForAttributedText() -> NSRange { return NSRange(location: 0, length: iconAttributedString!.length) } public func addAttributes(_ attributes: Dictionary<String, Any>) { iconAttributedString?.addAttributes(attributes, range: rangeForAttributedText()) } public func addAttribute(withName name: String, value: Any) { iconAttributedString?.addAttribute(name, value: value, range: rangeForAttributedText()) } public func removeAttribute(withName name: String) { iconAttributedString?.removeAttribute(name, range: rangeForAttributedText()) } public func allIcons() -> Array<String> { return [ACMaterialDesignIconCode.md_3d_rotation, ACMaterialDesignIconCode.md_airplane_off, ACMaterialDesignIconCode.md_airplane, ACMaterialDesignIconCode.md_album, ACMaterialDesignIconCode.md_archive, ACMaterialDesignIconCode.md_assignment_account, ACMaterialDesignIconCode.md_assignment_alert, ACMaterialDesignIconCode.md_assignment_check, ACMaterialDesignIconCode.md_assignment_o, ACMaterialDesignIconCode.md_assignment_return, ACMaterialDesignIconCode.md_assignment_returned, ACMaterialDesignIconCode.md_assignment, ACMaterialDesignIconCode.md_attachment_alt, ACMaterialDesignIconCode.md_attachment, ACMaterialDesignIconCode.md_audio, ACMaterialDesignIconCode.md_badge_check, ACMaterialDesignIconCode.md_balance_wallet, ACMaterialDesignIconCode.md_balance, ACMaterialDesignIconCode.md_battery_alert, ACMaterialDesignIconCode.md_battery_flash, ACMaterialDesignIconCode.md_battery_unknown, ACMaterialDesignIconCode.md_battery, ACMaterialDesignIconCode.md_bike, ACMaterialDesignIconCode.md_block_alt, ACMaterialDesignIconCode.md_block, ACMaterialDesignIconCode.md_boat, ACMaterialDesignIconCode.md_book_image, ACMaterialDesignIconCode.md_book, ACMaterialDesignIconCode.md_bookmark_outline, ACMaterialDesignIconCode.md_bookmark, ACMaterialDesignIconCode.md_brush, ACMaterialDesignIconCode.md_bug, ACMaterialDesignIconCode.md_bus, ACMaterialDesignIconCode.md_cake, ACMaterialDesignIconCode.md_car_taxi, ACMaterialDesignIconCode.md_car_wash, ACMaterialDesignIconCode.md_car, ACMaterialDesignIconCode.md_card_giftcard, ACMaterialDesignIconCode.md_card_membership, ACMaterialDesignIconCode.md_card_travel, ACMaterialDesignIconCode.md_card, ACMaterialDesignIconCode.md_case_check, ACMaterialDesignIconCode.md_case_download, ACMaterialDesignIconCode.md_case_play, ACMaterialDesignIconCode.md_case, ACMaterialDesignIconCode.md_cast_connected, ACMaterialDesignIconCode.md_cast, ACMaterialDesignIconCode.md_chart_donut, ACMaterialDesignIconCode.md_chart, ACMaterialDesignIconCode.md_city_alt, ACMaterialDesignIconCode.md_city, ACMaterialDesignIconCode.md_close_circle_o, ACMaterialDesignIconCode.md_close_circle, ACMaterialDesignIconCode.md_close, ACMaterialDesignIconCode.md_cocktail, ACMaterialDesignIconCode.md_code_setting, ACMaterialDesignIconCode.md_code_smartphone, ACMaterialDesignIconCode.md_code, ACMaterialDesignIconCode.md_coffee, ACMaterialDesignIconCode.md_collection_bookmark, ACMaterialDesignIconCode.md_collection_case_play, ACMaterialDesignIconCode.md_collection_folder_image, ACMaterialDesignIconCode.md_collection_image_o, ACMaterialDesignIconCode.md_collection_image, ACMaterialDesignIconCode.md_collection_item_1, ACMaterialDesignIconCode.md_collection_item_2, ACMaterialDesignIconCode.md_collection_item_3, ACMaterialDesignIconCode.md_collection_item_4, ACMaterialDesignIconCode.md_collection_item_5, ACMaterialDesignIconCode.md_collection_item_6, ACMaterialDesignIconCode.md_collection_item_7, ACMaterialDesignIconCode.md_collection_item_8, ACMaterialDesignIconCode.md_collection_item_9_plus, ACMaterialDesignIconCode.md_collection_item_9, ACMaterialDesignIconCode.md_collection_item, ACMaterialDesignIconCode.md_collection_music, ACMaterialDesignIconCode.md_collection_pdf, ACMaterialDesignIconCode.md_collection_plus, ACMaterialDesignIconCode.md_collection_speaker, ACMaterialDesignIconCode.md_collection_text, ACMaterialDesignIconCode.md_collection_video, ACMaterialDesignIconCode.md_compass, ACMaterialDesignIconCode.md_cutlery, ACMaterialDesignIconCode.md_delete, ACMaterialDesignIconCode.md_dialpad, ACMaterialDesignIconCode.md_dns, ACMaterialDesignIconCode.md_drink, ACMaterialDesignIconCode.md_edit, ACMaterialDesignIconCode.md_email_open, ACMaterialDesignIconCode.md_email, ACMaterialDesignIconCode.md_eye_off, ACMaterialDesignIconCode.md_eye, ACMaterialDesignIconCode.md_eyedropper, ACMaterialDesignIconCode.md_favorite_outline, ACMaterialDesignIconCode.md_favorite, ACMaterialDesignIconCode.md_filter_list, ACMaterialDesignIconCode.md_fire, ACMaterialDesignIconCode.md_flag, ACMaterialDesignIconCode.md_flare, ACMaterialDesignIconCode.md_flash_auto, ACMaterialDesignIconCode.md_flash_off, ACMaterialDesignIconCode.md_flash, ACMaterialDesignIconCode.md_flip, ACMaterialDesignIconCode.md_flower_alt, ACMaterialDesignIconCode.md_flower, ACMaterialDesignIconCode.md_font, ACMaterialDesignIconCode.md_fullscreen_alt, ACMaterialDesignIconCode.md_fullscreen_exit, ACMaterialDesignIconCode.md_fullscreen, ACMaterialDesignIconCode.md_functions, ACMaterialDesignIconCode.md_gas_station, ACMaterialDesignIconCode.md_gesture, ACMaterialDesignIconCode.md_globe_alt, ACMaterialDesignIconCode.md_globe_lock, ACMaterialDesignIconCode.md_globe, ACMaterialDesignIconCode.md_graduation_cap, ACMaterialDesignIconCode.md_home, ACMaterialDesignIconCode.md_hospital_alt, ACMaterialDesignIconCode.md_hospital, ACMaterialDesignIconCode.md_hotel, ACMaterialDesignIconCode.md_hourglass_alt, ACMaterialDesignIconCode.md_hourglass_outline, ACMaterialDesignIconCode.md_hourglass, ACMaterialDesignIconCode.md_http, ACMaterialDesignIconCode.md_image_alt, ACMaterialDesignIconCode.md_image_o, ACMaterialDesignIconCode.md_image, ACMaterialDesignIconCode.md_inbox, ACMaterialDesignIconCode.md_invert_colors_off, ACMaterialDesignIconCode.md_invert_colors, ACMaterialDesignIconCode.md_key, ACMaterialDesignIconCode.md_label_alt_outline, ACMaterialDesignIconCode.md_label_alt, ACMaterialDesignIconCode.md_label_heart, ACMaterialDesignIconCode.md_label, ACMaterialDesignIconCode.md_labels, ACMaterialDesignIconCode.md_lamp, ACMaterialDesignIconCode.md_landscape, ACMaterialDesignIconCode.md_layers_off, ACMaterialDesignIconCode.md_layers, ACMaterialDesignIconCode.md_library, ACMaterialDesignIconCode.md_link, ACMaterialDesignIconCode.md_lock_open, ACMaterialDesignIconCode.md_lock_outline, ACMaterialDesignIconCode.md_lock, ACMaterialDesignIconCode.md_mail_reply_all, ACMaterialDesignIconCode.md_mail_reply, ACMaterialDesignIconCode.md_mail_send, ACMaterialDesignIconCode.md_mall, ACMaterialDesignIconCode.md_map, ACMaterialDesignIconCode.md_menu, ACMaterialDesignIconCode.md_money_box, ACMaterialDesignIconCode.md_money_off, ACMaterialDesignIconCode.md_money, ACMaterialDesignIconCode.md_more_vert, ACMaterialDesignIconCode.md_more, ACMaterialDesignIconCode.md_movie_alt, ACMaterialDesignIconCode.md_movie, ACMaterialDesignIconCode.md_nature_people, ACMaterialDesignIconCode.md_nature, ACMaterialDesignIconCode.md_navigation, ACMaterialDesignIconCode.md_open_in_browser, ACMaterialDesignIconCode.md_open_in_new, ACMaterialDesignIconCode.md_palette, ACMaterialDesignIconCode.md_parking, ACMaterialDesignIconCode.md_pin_account, ACMaterialDesignIconCode.md_pin_assistant, ACMaterialDesignIconCode.md_pin_drop, ACMaterialDesignIconCode.md_pin_help, ACMaterialDesignIconCode.md_pin_off, ACMaterialDesignIconCode.md_pin, ACMaterialDesignIconCode.md_pizza, ACMaterialDesignIconCode.md_plaster, ACMaterialDesignIconCode.md_power_setting, ACMaterialDesignIconCode.md_power, ACMaterialDesignIconCode.md_print, ACMaterialDesignIconCode.md_puzzle_piece, ACMaterialDesignIconCode.md_quote, ACMaterialDesignIconCode.md_railway, ACMaterialDesignIconCode.md_receipt, ACMaterialDesignIconCode.md_refresh_alt, ACMaterialDesignIconCode.md_refresh_sync_alert, ACMaterialDesignIconCode.md_refresh_sync_off, ACMaterialDesignIconCode.md_refresh_sync, ACMaterialDesignIconCode.md_refresh, ACMaterialDesignIconCode.md_roller, ACMaterialDesignIconCode.md_ruler, ACMaterialDesignIconCode.md_scissors, ACMaterialDesignIconCode.md_screen_rotation_lock, ACMaterialDesignIconCode.md_screen_rotation, ACMaterialDesignIconCode.md_search_for, ACMaterialDesignIconCode.md_search_in_file, ACMaterialDesignIconCode.md_search_in_page, ACMaterialDesignIconCode.md_search_replace, ACMaterialDesignIconCode.md_search, ACMaterialDesignIconCode.md_seat, ACMaterialDesignIconCode.md_settings_square, ACMaterialDesignIconCode.md_settings, ACMaterialDesignIconCode.md_shield_check, ACMaterialDesignIconCode.md_shield_security, ACMaterialDesignIconCode.md_shopping_basket, ACMaterialDesignIconCode.md_shopping_cart_plus, ACMaterialDesignIconCode.md_shopping_cart, ACMaterialDesignIconCode.md_sign_in, ACMaterialDesignIconCode.md_sort_amount_asc, ACMaterialDesignIconCode.md_sort_amount_desc, ACMaterialDesignIconCode.md_sort_asc, ACMaterialDesignIconCode.md_sort_desc, ACMaterialDesignIconCode.md_spellcheck, ACMaterialDesignIconCode.md_storage, ACMaterialDesignIconCode.md_store_24, ACMaterialDesignIconCode.md_store, ACMaterialDesignIconCode.md_subway, ACMaterialDesignIconCode.md_sun, ACMaterialDesignIconCode.md_tab_unselected, ACMaterialDesignIconCode.md_tab, ACMaterialDesignIconCode.md_tag_close, ACMaterialDesignIconCode.md_tag_more, ACMaterialDesignIconCode.md_tag, ACMaterialDesignIconCode.md_thumb_down, ACMaterialDesignIconCode.md_thumb_up_down, ACMaterialDesignIconCode.md_thumb_up, ACMaterialDesignIconCode.md_ticket_star, ACMaterialDesignIconCode.md_toll, ACMaterialDesignIconCode.md_toys, ACMaterialDesignIconCode.md_traffic, ACMaterialDesignIconCode.md_translate, ACMaterialDesignIconCode.md_triangle_down, ACMaterialDesignIconCode.md_triangle_up, ACMaterialDesignIconCode.md_truck, ACMaterialDesignIconCode.md_turning_sign, ACMaterialDesignIconCode.md_wallpaper, ACMaterialDesignIconCode.md_washing_machine, ACMaterialDesignIconCode.md_window_maximize, ACMaterialDesignIconCode.md_window_minimize, ACMaterialDesignIconCode.md_window_restore, ACMaterialDesignIconCode.md_wrench, ACMaterialDesignIconCode.md_zoom_in, ACMaterialDesignIconCode.md_zoom_out, ACMaterialDesignIconCode.md_alert_circle_o, ACMaterialDesignIconCode.md_alert_circle, ACMaterialDesignIconCode.md_alert_octagon, ACMaterialDesignIconCode.md_alert_polygon, ACMaterialDesignIconCode.md_alert_triangle, ACMaterialDesignIconCode.md_help_outline, ACMaterialDesignIconCode.md_help, ACMaterialDesignIconCode.md_info_outline, ACMaterialDesignIconCode.md_info, ACMaterialDesignIconCode.md_notifications_active, ACMaterialDesignIconCode.md_notifications_add, ACMaterialDesignIconCode.md_notifications_none, ACMaterialDesignIconCode.md_notifications_off, ACMaterialDesignIconCode.md_notifications_paused, ACMaterialDesignIconCode.md_notifications, ACMaterialDesignIconCode.md_account_add, ACMaterialDesignIconCode.md_account_box_mail, ACMaterialDesignIconCode.md_account_box_o, ACMaterialDesignIconCode.md_account_box_phone, ACMaterialDesignIconCode.md_account_box, ACMaterialDesignIconCode.md_account_calendar, ACMaterialDesignIconCode.md_account_circle, ACMaterialDesignIconCode.md_account_o, ACMaterialDesignIconCode.md_account, ACMaterialDesignIconCode.md_accounts_add, ACMaterialDesignIconCode.md_accounts_alt, ACMaterialDesignIconCode.md_accounts_list_alt, ACMaterialDesignIconCode.md_accounts_list, ACMaterialDesignIconCode.md_accounts_outline, ACMaterialDesignIconCode.md_accounts, ACMaterialDesignIconCode.md_face, ACMaterialDesignIconCode.md_female, ACMaterialDesignIconCode.md_male_alt, ACMaterialDesignIconCode.md_male_female, ACMaterialDesignIconCode.md_male, ACMaterialDesignIconCode.md_mood_bad, ACMaterialDesignIconCode.md_mood, ACMaterialDesignIconCode.md_run, ACMaterialDesignIconCode.md_walk, ACMaterialDesignIconCode.md_cloud_box, ACMaterialDesignIconCode.md_cloud_circle, ACMaterialDesignIconCode.md_cloud_done, ACMaterialDesignIconCode.md_cloud_download, ACMaterialDesignIconCode.md_cloud_off, ACMaterialDesignIconCode.md_cloud_outline_alt, ACMaterialDesignIconCode.md_cloud_outline, ACMaterialDesignIconCode.md_cloud_upload, ACMaterialDesignIconCode.md_cloud, ACMaterialDesignIconCode.md_download, ACMaterialDesignIconCode.md_file_plus, ACMaterialDesignIconCode.md_file_text, ACMaterialDesignIconCode.md_file, ACMaterialDesignIconCode.md_folder_outline, ACMaterialDesignIconCode.md_folder_person, ACMaterialDesignIconCode.md_folder_star_alt, ACMaterialDesignIconCode.md_folder_star, ACMaterialDesignIconCode.md_folder, ACMaterialDesignIconCode.md_gif, ACMaterialDesignIconCode.md_upload, ACMaterialDesignIconCode.md_border_all, ACMaterialDesignIconCode.md_border_bottom, ACMaterialDesignIconCode.md_border_clear, ACMaterialDesignIconCode.md_border_color, ACMaterialDesignIconCode.md_border_horizontal, ACMaterialDesignIconCode.md_border_inner, ACMaterialDesignIconCode.md_border_left, ACMaterialDesignIconCode.md_border_outer, ACMaterialDesignIconCode.md_border_right, ACMaterialDesignIconCode.md_border_style, ACMaterialDesignIconCode.md_border_top, ACMaterialDesignIconCode.md_border_vertical, ACMaterialDesignIconCode.md_copy, ACMaterialDesignIconCode.md_crop, ACMaterialDesignIconCode.md_format_align_center, ACMaterialDesignIconCode.md_format_align_justify, ACMaterialDesignIconCode.md_format_align_left, ACMaterialDesignIconCode.md_format_align_right, ACMaterialDesignIconCode.md_format_bold, ACMaterialDesignIconCode.md_format_clear_all, ACMaterialDesignIconCode.md_format_clear, ACMaterialDesignIconCode.md_format_color_fill, ACMaterialDesignIconCode.md_format_color_reset, ACMaterialDesignIconCode.md_format_color_text, ACMaterialDesignIconCode.md_format_indent_decrease, ACMaterialDesignIconCode.md_format_indent_increase, ACMaterialDesignIconCode.md_format_italic, ACMaterialDesignIconCode.md_format_line_spacing, ACMaterialDesignIconCode.md_format_list_bulleted, ACMaterialDesignIconCode.md_format_list_numbered, ACMaterialDesignIconCode.md_format_ltr, ACMaterialDesignIconCode.md_format_rtl, ACMaterialDesignIconCode.md_format_size, ACMaterialDesignIconCode.md_format_strikethrough_s, ACMaterialDesignIconCode.md_format_strikethrough, ACMaterialDesignIconCode.md_format_subject, ACMaterialDesignIconCode.md_format_underlined, ACMaterialDesignIconCode.md_format_valign_bottom, ACMaterialDesignIconCode.md_format_valign_center, ACMaterialDesignIconCode.md_format_valign_top, ACMaterialDesignIconCode.md_redo, ACMaterialDesignIconCode.md_select_all, ACMaterialDesignIconCode.md_space_bar, ACMaterialDesignIconCode.md_text_format, ACMaterialDesignIconCode.md_transform, ACMaterialDesignIconCode.md_undo, ACMaterialDesignIconCode.md_wrap_text, ACMaterialDesignIconCode.md_comment_alert, ACMaterialDesignIconCode.md_comment_alt_text, ACMaterialDesignIconCode.md_comment_alt, ACMaterialDesignIconCode.md_comment_edit, ACMaterialDesignIconCode.md_comment_image, ACMaterialDesignIconCode.md_comment_list, ACMaterialDesignIconCode.md_comment_more, ACMaterialDesignIconCode.md_comment_outline, ACMaterialDesignIconCode.md_comment_text_alt, ACMaterialDesignIconCode.md_comment_text, ACMaterialDesignIconCode.md_comment_video, ACMaterialDesignIconCode.md_comment, ACMaterialDesignIconCode.md_comments, ACMaterialDesignIconCode.md_check_all, ACMaterialDesignIconCode.md_check_circle_u, ACMaterialDesignIconCode.md_check_circle, ACMaterialDesignIconCode.md_check_square, ACMaterialDesignIconCode.md_check, ACMaterialDesignIconCode.md_circle_o, ACMaterialDesignIconCode.md_circle, ACMaterialDesignIconCode.md_dot_circle_alt, ACMaterialDesignIconCode.md_dot_circle, ACMaterialDesignIconCode.md_minus_circle_outline, ACMaterialDesignIconCode.md_minus_circle, ACMaterialDesignIconCode.md_minus_square, ACMaterialDesignIconCode.md_minus, ACMaterialDesignIconCode.md_plus_circle_o_duplicate, ACMaterialDesignIconCode.md_plus_circle_o, ACMaterialDesignIconCode.md_plus_circle, ACMaterialDesignIconCode.md_plus_square, ACMaterialDesignIconCode.md_plus, ACMaterialDesignIconCode.md_square_o, ACMaterialDesignIconCode.md_star_circle, ACMaterialDesignIconCode.md_star_half, ACMaterialDesignIconCode.md_star_outline, ACMaterialDesignIconCode.md_star, ACMaterialDesignIconCode.md_bluetooth_connected, ACMaterialDesignIconCode.md_bluetooth_off, ACMaterialDesignIconCode.md_bluetooth_search, ACMaterialDesignIconCode.md_bluetooth_setting, ACMaterialDesignIconCode.md_bluetooth, ACMaterialDesignIconCode.md_camera_add, ACMaterialDesignIconCode.md_camera_alt, ACMaterialDesignIconCode.md_camera_bw, ACMaterialDesignIconCode.md_camera_front, ACMaterialDesignIconCode.md_camera_mic, ACMaterialDesignIconCode.md_camera_party_mode, ACMaterialDesignIconCode.md_camera_rear, ACMaterialDesignIconCode.md_camera_roll, ACMaterialDesignIconCode.md_camera_switch, ACMaterialDesignIconCode.md_camera, ACMaterialDesignIconCode.md_card_alert, ACMaterialDesignIconCode.md_card_off, ACMaterialDesignIconCode.md_card_sd, ACMaterialDesignIconCode.md_card_sim, ACMaterialDesignIconCode.md_desktop_mac, ACMaterialDesignIconCode.md_desktop_windows, ACMaterialDesignIconCode.md_device_hub, ACMaterialDesignIconCode.md_devices_off, ACMaterialDesignIconCode.md_devices, ACMaterialDesignIconCode.md_dock, ACMaterialDesignIconCode.md_floppy, ACMaterialDesignIconCode.md_gamepad, ACMaterialDesignIconCode.md_gps_dot, ACMaterialDesignIconCode.md_gps_off, ACMaterialDesignIconCode.md_gps, ACMaterialDesignIconCode.md_headset_mic, ACMaterialDesignIconCode.md_headset, ACMaterialDesignIconCode.md_input_antenna, ACMaterialDesignIconCode.md_input_composite, ACMaterialDesignIconCode.md_input_hdmi, ACMaterialDesignIconCode.md_input_power, ACMaterialDesignIconCode.md_input_svideo, ACMaterialDesignIconCode.md_keyboard_hide, ACMaterialDesignIconCode.md_keyboard, ACMaterialDesignIconCode.md_laptop_chromebook, ACMaterialDesignIconCode.md_laptop_mac, ACMaterialDesignIconCode.md_laptop, ACMaterialDesignIconCode.md_mic_off, ACMaterialDesignIconCode.md_mic_outline, ACMaterialDesignIconCode.md_mic_setting, ACMaterialDesignIconCode.md_mic, ACMaterialDesignIconCode.md_mouse, ACMaterialDesignIconCode.md_network_alert, ACMaterialDesignIconCode.md_network_locked, ACMaterialDesignIconCode.md_network_off, ACMaterialDesignIconCode.md_network_outline, ACMaterialDesignIconCode.md_network_setting, ACMaterialDesignIconCode.md_network, ACMaterialDesignIconCode.md_phone_bluetooth, ACMaterialDesignIconCode.md_phone_end, ACMaterialDesignIconCode.md_phone_forwarded, ACMaterialDesignIconCode.md_phone_in_talk, ACMaterialDesignIconCode.md_phone_locked, ACMaterialDesignIconCode.md_phone_missed, ACMaterialDesignIconCode.md_phone_msg, ACMaterialDesignIconCode.md_phone_paused, ACMaterialDesignIconCode.md_phone_ring, ACMaterialDesignIconCode.md_phone_setting, ACMaterialDesignIconCode.md_phone_sip, ACMaterialDesignIconCode.md_phone, ACMaterialDesignIconCode.md_portable_wifi_changes, ACMaterialDesignIconCode.md_portable_wifi_off, ACMaterialDesignIconCode.md_portable_wifi, ACMaterialDesignIconCode.md_radio, ACMaterialDesignIconCode.md_reader, ACMaterialDesignIconCode.md_remote_control_alt, ACMaterialDesignIconCode.md_remote_control, ACMaterialDesignIconCode.md_router, ACMaterialDesignIconCode.md_scanner, ACMaterialDesignIconCode.md_smartphone_android, ACMaterialDesignIconCode.md_smartphone_download, ACMaterialDesignIconCode.md_smartphone_erase, ACMaterialDesignIconCode.md_smartphone_info, ACMaterialDesignIconCode.md_smartphone_iphone, ACMaterialDesignIconCode.md_smartphone_landscape_lock, ACMaterialDesignIconCode.md_smartphone_landscape, ACMaterialDesignIconCode.md_smartphone_lock, ACMaterialDesignIconCode.md_smartphone_portrait_lock, ACMaterialDesignIconCode.md_smartphone_ring, ACMaterialDesignIconCode.md_smartphone_setting, ACMaterialDesignIconCode.md_smartphone_setup, ACMaterialDesignIconCode.md_smartphone, ACMaterialDesignIconCode.md_speaker, ACMaterialDesignIconCode.md_tablet_android, ACMaterialDesignIconCode.md_tablet_mac, ACMaterialDesignIconCode.md_tablet, ACMaterialDesignIconCode.md_tv_alt_play, ACMaterialDesignIconCode.md_tv_list, ACMaterialDesignIconCode.md_tv_play, ACMaterialDesignIconCode.md_tv, ACMaterialDesignIconCode.md_usb, ACMaterialDesignIconCode.md_videocam_off, ACMaterialDesignIconCode.md_videocam_switch, ACMaterialDesignIconCode.md_videocam, ACMaterialDesignIconCode.md_watch, ACMaterialDesignIconCode.md_wifi_alt_2, ACMaterialDesignIconCode.md_wifi_alt, ACMaterialDesignIconCode.md_wifi_info, ACMaterialDesignIconCode.md_wifi_lock, ACMaterialDesignIconCode.md_wifi_off, ACMaterialDesignIconCode.md_wifi_outline, ACMaterialDesignIconCode.md_wifi, ACMaterialDesignIconCode.md_arrow_left_bottom, ACMaterialDesignIconCode.md_arrow_left, ACMaterialDesignIconCode.md_arrow_merge, ACMaterialDesignIconCode.md_arrow_missed, ACMaterialDesignIconCode.md_arrow_right_top, ACMaterialDesignIconCode.md_arrow_right, ACMaterialDesignIconCode.md_arrow_split, ACMaterialDesignIconCode.md_arrows, ACMaterialDesignIconCode.md_caret_down_circle, ACMaterialDesignIconCode.md_caret_down, ACMaterialDesignIconCode.md_caret_left_circle, ACMaterialDesignIconCode.md_caret_left, ACMaterialDesignIconCode.md_caret_right_circle, ACMaterialDesignIconCode.md_caret_right, ACMaterialDesignIconCode.md_caret_up_circle, ACMaterialDesignIconCode.md_caret_up, ACMaterialDesignIconCode.md_chevron_down, ACMaterialDesignIconCode.md_chevron_left, ACMaterialDesignIconCode.md_chevron_right, ACMaterialDesignIconCode.md_chevron_up, ACMaterialDesignIconCode.md_forward, ACMaterialDesignIconCode.md_long_arrow_down, ACMaterialDesignIconCode.md_long_arrow_left, ACMaterialDesignIconCode.md_long_arrow_return, ACMaterialDesignIconCode.md_long_arrow_right, ACMaterialDesignIconCode.md_long_arrow_tab, ACMaterialDesignIconCode.md_long_arrow_up, ACMaterialDesignIconCode.md_rotate_ccw, ACMaterialDesignIconCode.md_rotate_cw, ACMaterialDesignIconCode.md_rotate_left, ACMaterialDesignIconCode.md_rotate_right, ACMaterialDesignIconCode.md_square_down, ACMaterialDesignIconCode.md_square_right, ACMaterialDesignIconCode.md_swap_alt, ACMaterialDesignIconCode.md_swap_vertical_circle, ACMaterialDesignIconCode.md_swap_vertical, ACMaterialDesignIconCode.md_swap, ACMaterialDesignIconCode.md_trending_down, ACMaterialDesignIconCode.md_trending_flat, ACMaterialDesignIconCode.md_trending_up, ACMaterialDesignIconCode.md_unfold_less, ACMaterialDesignIconCode.md_unfold_more, ACMaterialDesignIconCode.md_apps, ACMaterialDesignIconCode.md_grid_off, ACMaterialDesignIconCode.md_grid, ACMaterialDesignIconCode.md_view_agenda, ACMaterialDesignIconCode.md_view_array, ACMaterialDesignIconCode.md_view_carousel, ACMaterialDesignIconCode.md_view_column, ACMaterialDesignIconCode.md_view_comfy, ACMaterialDesignIconCode.md_view_compact, ACMaterialDesignIconCode.md_view_dashboard, ACMaterialDesignIconCode.md_view_day, ACMaterialDesignIconCode.md_view_headline, ACMaterialDesignIconCode.md_view_list_alt, ACMaterialDesignIconCode.md_view_list, ACMaterialDesignIconCode.md_view_module, ACMaterialDesignIconCode.md_view_quilt, ACMaterialDesignIconCode.md_view_stream, ACMaterialDesignIconCode.md_view_subtitles, ACMaterialDesignIconCode.md_view_toc, ACMaterialDesignIconCode.md_view_web, ACMaterialDesignIconCode.md_view_week, ACMaterialDesignIconCode.md_widgets, ACMaterialDesignIconCode.md_alarm_check, ACMaterialDesignIconCode.md_alarm_off, ACMaterialDesignIconCode.md_alarm_plus, ACMaterialDesignIconCode.md_alarm_snooze, ACMaterialDesignIconCode.md_alarm, ACMaterialDesignIconCode.md_calendar_alt, ACMaterialDesignIconCode.md_calendar_check, ACMaterialDesignIconCode.md_calendar_close, ACMaterialDesignIconCode.md_calendar_note, ACMaterialDesignIconCode.md_calendar, ACMaterialDesignIconCode.md_time_countdown, ACMaterialDesignIconCode.md_time_interval, ACMaterialDesignIconCode.md_time_restore_setting, ACMaterialDesignIconCode.md_time_restore, ACMaterialDesignIconCode.md_time, ACMaterialDesignIconCode.md_timer_off, ACMaterialDesignIconCode.md_timer, ACMaterialDesignIconCode.md_android_alt, ACMaterialDesignIconCode.md_android, ACMaterialDesignIconCode.md_apple, ACMaterialDesignIconCode.md_behance, ACMaterialDesignIconCode.md_codepen, ACMaterialDesignIconCode.md_dribbble, ACMaterialDesignIconCode.md_dropbox, ACMaterialDesignIconCode.md_evernote, ACMaterialDesignIconCode.md_facebook_box, ACMaterialDesignIconCode.md_facebook, ACMaterialDesignIconCode.md_github_box, ACMaterialDesignIconCode.md_github, ACMaterialDesignIconCode.md_google_drive, ACMaterialDesignIconCode.md_google_earth, ACMaterialDesignIconCode.md_google_glass, ACMaterialDesignIconCode.md_google_maps, ACMaterialDesignIconCode.md_google_pages, ACMaterialDesignIconCode.md_google_play, ACMaterialDesignIconCode.md_google_plus_box, ACMaterialDesignIconCode.md_google_plus, ACMaterialDesignIconCode.md_google, ACMaterialDesignIconCode.md_instagram, ACMaterialDesignIconCode.md_language_css3, ACMaterialDesignIconCode.md_language_html5, ACMaterialDesignIconCode.md_language_javascript, ACMaterialDesignIconCode.md_language_python_alt, ACMaterialDesignIconCode.md_language_python, ACMaterialDesignIconCode.md_lastfm, ACMaterialDesignIconCode.md_linkedin_box, ACMaterialDesignIconCode.md_paypal, ACMaterialDesignIconCode.md_pinterest_box, ACMaterialDesignIconCode.md_pocket, ACMaterialDesignIconCode.md_polymer, ACMaterialDesignIconCode.md_share, ACMaterialDesignIconCode.md_stack_overflow, ACMaterialDesignIconCode.md_steam_square, ACMaterialDesignIconCode.md_steam, ACMaterialDesignIconCode.md_twitter_box, ACMaterialDesignIconCode.md_twitter, ACMaterialDesignIconCode.md_vk, ACMaterialDesignIconCode.md_wikipedia, ACMaterialDesignIconCode.md_windows, ACMaterialDesignIconCode.md_aspect_ratio_alt, ACMaterialDesignIconCode.md_aspect_ratio, ACMaterialDesignIconCode.md_blur_circular, ACMaterialDesignIconCode.md_blur_linear, ACMaterialDesignIconCode.md_blur_off, ACMaterialDesignIconCode.md_blur, ACMaterialDesignIconCode.md_brightness_2, ACMaterialDesignIconCode.md_brightness_3, ACMaterialDesignIconCode.md_brightness_4, ACMaterialDesignIconCode.md_brightness_5, ACMaterialDesignIconCode.md_brightness_6, ACMaterialDesignIconCode.md_brightness_7, ACMaterialDesignIconCode.md_brightness_auto, ACMaterialDesignIconCode.md_brightness_setting, ACMaterialDesignIconCode.md_broken_image, ACMaterialDesignIconCode.md_center_focus_strong, ACMaterialDesignIconCode.md_center_focus_weak, ACMaterialDesignIconCode.md_compare, ACMaterialDesignIconCode.md_crop_16_9, ACMaterialDesignIconCode.md_crop_3_2, ACMaterialDesignIconCode.md_crop_5_4, ACMaterialDesignIconCode.md_crop_7_5, ACMaterialDesignIconCode.md_crop_din, ACMaterialDesignIconCode.md_crop_free, ACMaterialDesignIconCode.md_crop_landscape, ACMaterialDesignIconCode.md_crop_portrait, ACMaterialDesignIconCode.md_crop_square, ACMaterialDesignIconCode.md_exposure_alt, ACMaterialDesignIconCode.md_exposure, ACMaterialDesignIconCode.md_filter_b_and_w, ACMaterialDesignIconCode.md_filter_center_focus, ACMaterialDesignIconCode.md_filter_frames, ACMaterialDesignIconCode.md_filter_tilt_shift, ACMaterialDesignIconCode.md_gradient, ACMaterialDesignIconCode.md_grain, ACMaterialDesignIconCode.md_graphic_eq, ACMaterialDesignIconCode.md_hdr_off, ACMaterialDesignIconCode.md_hdr_strong, ACMaterialDesignIconCode.md_hdr_weak, ACMaterialDesignIconCode.md_hdr, ACMaterialDesignIconCode.md_iridescent, ACMaterialDesignIconCode.md_leak_off, ACMaterialDesignIconCode.md_leak, ACMaterialDesignIconCode.md_looks, ACMaterialDesignIconCode.md_loupe, ACMaterialDesignIconCode.md_panorama_horizontal, ACMaterialDesignIconCode.md_panorama_vertical, ACMaterialDesignIconCode.md_panorama_wide_angle, ACMaterialDesignIconCode.md_photo_size_select_large, ACMaterialDesignIconCode.md_photo_size_select_small, ACMaterialDesignIconCode.md_picture_in_picture, ACMaterialDesignIconCode.md_slideshow, ACMaterialDesignIconCode.md_texture, ACMaterialDesignIconCode.md_tonality, ACMaterialDesignIconCode.md_vignette, ACMaterialDesignIconCode.md_wb_auto, ACMaterialDesignIconCode.md_eject_alt, ACMaterialDesignIconCode.md_eject, ACMaterialDesignIconCode.md_equalizer, ACMaterialDesignIconCode.md_fast_forward, ACMaterialDesignIconCode.md_fast_rewind, ACMaterialDesignIconCode.md_forward_10, ACMaterialDesignIconCode.md_forward_30, ACMaterialDesignIconCode.md_forward_5, ACMaterialDesignIconCode.md_hearing, ACMaterialDesignIconCode.md_pause_circle_outline, ACMaterialDesignIconCode.md_pause_circle, ACMaterialDesignIconCode.md_pause, ACMaterialDesignIconCode.md_play_circle_outline, ACMaterialDesignIconCode.md_play_circle, ACMaterialDesignIconCode.md_play, ACMaterialDesignIconCode.md_playlist_audio, ACMaterialDesignIconCode.md_playlist_plus, ACMaterialDesignIconCode.md_repeat_one, ACMaterialDesignIconCode.md_repeat, ACMaterialDesignIconCode.md_replay_10, ACMaterialDesignIconCode.md_replay_30, ACMaterialDesignIconCode.md_replay_5, ACMaterialDesignIconCode.md_replay, ACMaterialDesignIconCode.md_shuffle, ACMaterialDesignIconCode.md_skip_next, ACMaterialDesignIconCode.md_skip_previous, ACMaterialDesignIconCode.md_stop, ACMaterialDesignIconCode.md_surround_sound, ACMaterialDesignIconCode.md_tune, ACMaterialDesignIconCode.md_volume_down, ACMaterialDesignIconCode.md_volume_mute, ACMaterialDesignIconCode.md_volume_off, ACMaterialDesignIconCode.md_volume_up, ACMaterialDesignIconCode.md_n_1_square, ACMaterialDesignIconCode.md_n_2_square, ACMaterialDesignIconCode.md_n_3_square, ACMaterialDesignIconCode.md_n_4_square, ACMaterialDesignIconCode.md_n_5_square, ACMaterialDesignIconCode.md_n_6_square, ACMaterialDesignIconCode.md_neg_1, ACMaterialDesignIconCode.md_neg_2, ACMaterialDesignIconCode.md_plus_1, ACMaterialDesignIconCode.md_plus_2, ACMaterialDesignIconCode.md_sec_10, ACMaterialDesignIconCode.md_sec_3, ACMaterialDesignIconCode.md_zero, ACMaterialDesignIconCode.md_airline_seat_flat_angled, ACMaterialDesignIconCode.md_airline_seat_flat, ACMaterialDesignIconCode.md_airline_seat_individual_suite, ACMaterialDesignIconCode.md_airline_seat_legroom_extra, ACMaterialDesignIconCode.md_airline_seat_legroom_normal, ACMaterialDesignIconCode.md_airline_seat_legroom_reduced, ACMaterialDesignIconCode.md_airline_seat_recline_extra, ACMaterialDesignIconCode.md_airline_seat_recline_normal, ACMaterialDesignIconCode.md_airplay, ACMaterialDesignIconCode.md_closed_caption, ACMaterialDesignIconCode.md_confirmation_number, ACMaterialDesignIconCode.md_developer_board, ACMaterialDesignIconCode.md_disc_full, ACMaterialDesignIconCode.md_explicit, ACMaterialDesignIconCode.md_flight_land, ACMaterialDesignIconCode.md_flight_takeoff, ACMaterialDesignIconCode.md_flip_to_back, ACMaterialDesignIconCode.md_flip_to_front, ACMaterialDesignIconCode.md_group_work, ACMaterialDesignIconCode.md_hd, ACMaterialDesignIconCode.md_hq, ACMaterialDesignIconCode.md_markunread_mailbox, ACMaterialDesignIconCode.md_memory, ACMaterialDesignIconCode.md_nfc, ACMaterialDesignIconCode.md_play_for_work, ACMaterialDesignIconCode.md_power_input, ACMaterialDesignIconCode.md_present_to_all, ACMaterialDesignIconCode.md_satellite, ACMaterialDesignIconCode.md_tap_and_play, ACMaterialDesignIconCode.md_vibration, ACMaterialDesignIconCode.md_voicemail] } }
mit
b85e76bc4323e7b7737e6697ee38ce4b
53.387097
141
0.633628
6.328653
false
false
false
false
naoto0822/try-reactive-swift
TryRxSwift/TryRxSwift/Item.swift
1
775
// // Item.swift // TryRxSwift // // Created by naoto yamaguchi on 2016/04/11. // Copyright © 2016年 naoto yamaguchi. All rights reserved. // import UIKit public struct Item { // MARK: - Property public let id: String public let title: String public let url: String public let user: User // MARK: - Public init(dictionary: [String: AnyObject]) { self.id = dictionary["id"] as? String ?? "" self.title = dictionary["title"] as? String ?? "" self.url = dictionary["url"] as? String ?? "" if let userDictionary = dictionary["user"] as? [String: AnyObject] { self.user = User(dictionary: userDictionary) } else { self.user = User() } } }
mit
ef0cc2f96eb0b132d7ed77c3cb548d31
22.393939
76
0.563472
4.084656
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/UIImageView+Fade.swift
1
787
// // UIImageView+Fade.swift // Wuakup // // Created by Guillermo Gutiérrez on 08/01/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation import SDWebImage extension UIImageView { func setImageAnimated(url: URL!, completed: SDExternalCompletionBlock? = nil) { sd_setImage(with: url) { (image, error, cacheType, url) in if (cacheType == .none) { let animation = CATransition() animation.duration = 0.3 animation.type = CATransitionType.fade self.layer.add(animation, forKey: "image-load") } if let completeBlock = completed { completeBlock(image, error, cacheType, url) } } } }
mit
03097c69c0b46769a4c0038a8f0e2b85
28.111111
83
0.575064
4.491429
false
false
false
false
Octadero/TensorFlow
Sources/CAPI/Session.swift
1
20856
/* Copyright 2017 The Octadero Authors. All Rights Reserved. Created by Volodymyr Pavliukevych on 2017. Licensed under the GPL License, Version 3.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.gnu.org/licenses/gpl-3.0.txt 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 CTensorFlow import MemoryLayoutKit import Foundation import Proto /// Representation of devices in session public struct TF_Device { let name: String? let type: String? let memorySize: Int64 } /// API for driving Graph execution. /// Return a new execution session with the associated graph, or NULL on error. // /// *graph must be a valid graph (not deleted or nullptr). This function will /// prevent the graph from being deleted until TF_DeleteSession() is called. /// Does not take ownership of opts. public func newSession(graph: TF_Graph!, sessionOptions: TF_SessionOptions!) throws -> TF_Session! { let status = TF_NewStatus() defer { delete(status: status) } let session: TF_Session = TF_NewSession(graph, sessionOptions, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } return session } /// This function creates a new TF_Session (which is created on success) using /// `session_options`, and then initializes state (restoring tensors and other /// assets) using `run_options`. // /// Any NULL and non-NULL value combinations for (`run_options, `meta_graph_def`) /// are valid. // /// - `export_dir` must be set to the path of the exported SavedModel. /// - `tags` must include the set of tags used to identify one MetaGraphDef in /// the SavedModel. /// - `graph` must be a graph newly allocated with TF_NewGraph(). // /// If successful, populates `graph` with the contents of the Graph and /// `meta_graph_def` with the MetaGraphDef of the loaded model. public func loadSessionFromSavedModel(sessionOptions: TF_SessionOptions, runOptions: Tensorflow_RunOptions?, exportPath: String, tags: [String], graph: TF_Graph, metaDataGraphDefInjection: (_ bufferPointer: UnsafeMutablePointer<TF_Buffer>?) throws ->Void) throws -> TF_Session { let status = TF_NewStatus() guard let exportDir = exportPath.cString(using: .utf8) else { throw CAPIError.canNotComputPointer(functionName: "for export dir")} var runOptionsBufferPointer: UnsafeMutablePointer<TF_Buffer>? = nil if let runOptions = runOptions { let data = try runOptions.serializedData() let buffer = newBuffer(from: data) runOptionsBufferPointer = buffer } let tagsCArray = try tags.cArray() defer { delete(status: status) } let metaGraphDef = TF_NewBuffer() let nullableSession = TF_LoadSessionFromSavedModel(sessionOptions, runOptionsBufferPointer, exportDir, tagsCArray.pointerList, Int32(tagsCArray.count), graph, metaGraphDef, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } try metaDataGraphDefInjection(metaGraphDef) if runOptionsBufferPointer != nil { TF_DeleteBuffer(runOptionsBufferPointer) } TF_DeleteBuffer(metaGraphDef) guard let session = nullableSession else { throw CAPIError.cancelled(message: "Returned session is nil.")} return session } /// Close a session. // /// Contacts any other processes associated with the session, if applicable. /// May not be called after TF_DeleteSession(). public func close(session: TF_Session!) throws { let status = TF_NewStatus() defer { delete(status: status) } TF_CloseSession(session, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } } /// Destroy a session object. // /// Even if error information is recorded in *status, this call discards all /// local resources associated with the session. The session may not be used /// during or after this call (and the session drops its reference to the /// corresponding graph). public func delete(session: TF_Session!, status: TF_Status!) { TF_DeleteSession(session, status) } /// Run the graph associated with the session starting with the supplied inputs /// (inputs[0,ninputs-1] with corresponding values in input_values[0,ninputs-1]). // /// Any NULL and non-NULL value combinations for (`run_options`, /// `run_metadata`) are valid. // /// - `run_options` may be NULL, in which case it will be ignored; or /// non-NULL, in which case it must point to a `TF_Buffer` containing the /// serialized representation of a `RunOptions` protocol buffer. /// - `run_metadata` may be NULL, in which case it will be ignored; or /// non-NULL, in which case it must point to an empty, freshly allocated /// `TF_Buffer` that may be updated to contain the serialized representation /// of a `RunMetadata` protocol buffer. // /// The caller retains ownership of `input_values` (which can be deleted using /// TF_DeleteTensor). The caller also retains ownership of `run_options` and/or /// `run_metadata` (when not NULL) and should manually call TF_DeleteBuffer on /// them. // /// On success, the tensors corresponding to outputs[0,noutputs-1] are placed in /// output_values[]. Ownership of the elements of output_values[] is transferred /// to the caller, which must eventually call TF_DeleteTensor on them. // /// On failure, output_values[] contains NULLs. public func run(session: TF_Session, runOptions: Tensorflow_RunOptions?, inputs: [TF_Output], inputsValues: [TF_Tensor?], outputs: [TF_Output], targetOperations: [TF_Operation?], metadata: UnsafeMutablePointer<TF_Buffer>?) throws -> [TF_Tensor] { var runOptionsBufferPointer: UnsafeMutablePointer<TF_Buffer>? = nil if let runOptions = runOptions { let data = try runOptions.serializedData() let buffer = newBuffer(from: data) runOptionsBufferPointer = buffer } guard inputsValues.count == inputs.count else { throw CAPIError.cancelled(message: "Incorrect number of inputs and thirs values") } let numberOfInputs = Int32(inputs.count) let numberOfOutputs = Int32(outputs.count) let numberOfTargets = Int32(targetOperations.count) let status = TF_NewStatus() /// Inputs let inputsPointer = inputs.withUnsafeBufferPointer {$0.baseAddress} let inputsValuesPointer = inputsValues.withUnsafeBufferPointer {$0.baseAddress} /// Outputs let outputsPointer = outputs.withUnsafeBufferPointer {$0.baseAddress} /// Targets let targetOperationsPointer = targetOperations.withUnsafeBufferPointer { $0.baseAddress } var outputsValuesPointer: UnsafeMutablePointer<TF_Tensor?>? if numberOfOutputs > 0 { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>.allocate(capacity: Int(numberOfOutputs)) } else { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>(bitPattern: 0) } defer { delete(status: status) outputsValuesPointer?.deallocate() if runOptionsBufferPointer != nil { TF_DeleteBuffer(runOptionsBufferPointer) } } TF_SessionRun(session, runOptionsBufferPointer, inputsPointer, inputsValuesPointer, numberOfInputs, outputsPointer, outputsValuesPointer, numberOfOutputs, targetOperationsPointer, numberOfTargets, metadata, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } if numberOfOutputs > 0, let pointer = outputsValuesPointer { let result = UnsafeMutableBufferPointer<TF_Tensor?>(start: pointer, count: Int(numberOfOutputs)).compactMap{ $0 } return result } else { return [TF_Tensor]() } } /// RunOptions /// Input tensors /// Output tensors /// Target operations /// RunMetadata /// Output status /// Set up the graph with the intended feeds (inputs) and fetches (outputs) for a /// sequence of partial run calls. // /// On success, returns a handle that is used for subsequent PRun calls. The /// handle should be deleted with TF_DeletePRunHandle when it is no longer /// needed. // /// On failure, out_status contains a tensorflow::Status with an error /// message. /// NOTE: This is EXPERIMENTAL and subject to change. public func sessionPartialRunSetup(session: TF_Session, inputs: [TF_Output], outputs: [TF_Output], targetOperations: [TF_Operation?]) throws -> UnsafePointer<Int8> { let numberOfInputs = Int32(inputs.count) let numberOfOutputs = Int32(outputs.count) let numberOfTargets = Int32(targetOperations.count) let inputsPointer = inputs.withUnsafeBufferPointer {$0.baseAddress} let outputsPointer = outputs.withUnsafeBufferPointer {$0.baseAddress} let targetOperationsPointer = targetOperations.withUnsafeBufferPointer { $0.baseAddress } var handle = UnsafePointer<CChar>(bitPattern: 0) let status = TF_NewStatus() defer { delete(status: status) } TF_SessionPRunSetup(session, inputsPointer, numberOfInputs, outputsPointer, numberOfOutputs, targetOperationsPointer, numberOfTargets, &handle, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } guard let result = handle else { throw CAPIError.cancelled(message: "Can't produce handle pointer at TF_SessionPRunSetup call.") } return result } /// Input names /// Output names /// Target operations /// Output handle /// Output status /// Continue to run the graph with additional feeds and fetches. The /// execution state is uniquely identified by the handle. /// NOTE: This is EXPERIMENTAL and subject to change. public func sessionPartialRun(session: TF_Session, handle: UnsafePointer<Int8>, inputs: [TF_Output], inputsValues: [TF_Tensor?], outputs: [TF_Output], targetOperations: [TF_Operation?]) throws -> [TF_Tensor] { guard inputsValues.count == inputs.count else { throw CAPIError.cancelled(message: "Incorrect number of inputs and thirs values") } let numberOfInputs = Int32(inputs.count) let numberOfOutputs = Int32(outputs.count) let numberOfTargets = Int32(targetOperations.count) let status = TF_NewStatus() defer { delete(status: status) } /// Inputs let inputsPointer = inputs.withUnsafeBufferPointer {$0.baseAddress} let inputsValuesPointer = inputsValues.withUnsafeBufferPointer {$0.baseAddress} /// Outputs let outputsPointer = outputs.withUnsafeBufferPointer {$0.baseAddress} /// Targets let targetOperationsPointer = targetOperations.withUnsafeBufferPointer { $0.baseAddress } var outputsValuesPointer: UnsafeMutablePointer<TF_Tensor?>? if numberOfOutputs > 0 { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>.allocate(capacity: Int(numberOfOutputs)) } else { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>(bitPattern: 0) } TF_SessionPRun(session, handle, inputsPointer, inputsValuesPointer, numberOfInputs, outputsPointer, outputsValuesPointer, numberOfOutputs, targetOperationsPointer, numberOfTargets, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } if numberOfOutputs > 0, let pointer = outputsValuesPointer { let result = UnsafeMutableBufferPointer<TF_Tensor?>(start: pointer, count: Int(numberOfOutputs)).compactMap{ $0 } outputsValuesPointer?.deinitialize(count: Int(numberOfOutputs)) return result } else { return [TF_Tensor]() } } /// Input tensors /// Output tensors /// Target operations /// Output status /// Deletes a handle allocated by TF_SessionPRunSetup. /// Once called, no more calls to TF_SessionPRun should be made. public func deletePartialRun(handle: UnsafePointer<Int8>!) { return TF_DeletePRunHandle(handle) } /// The deprecated session API. Please switch to the above instead of /// TF_ExtendGraph(). This deprecated API can be removed at any time without /// notice. public func newDeprecatedSession(options: TF_SessionOptions!, status: TF_Status!) -> TF_DeprecatedSession! { return TF_NewDeprecatedSession(options, status) } public func closeDeprecated(session: TF_DeprecatedSession!, status: TF_Status!) { fatalError("\(#function): Not implemented.") } public func deleteDeprecated(session: TF_DeprecatedSession!, status: TF_Status!) { fatalError("\(#function): Not implemented.") } public func reset(options: TF_SessionOptions!, containers: UnsafeMutablePointer<UnsafePointer<Int8>?>!, containersNumber: Int32, status: TF_Status!) { fatalError("\(#function): Not implemented.") } /// Treat the bytes proto[0,proto_len-1] as a serialized GraphDef and /// add the nodes in that GraphDef to the graph for the session. // /// Prefer use of TF_Session and TF_GraphImportGraphDef over this. public func extendGraph(oPointer:OpaquePointer!, _ proto: UnsafeRawPointer!, _ proto_len: Int, status: TF_Status!) { fatalError("\(#function): Not implemented.") /* TF_Reset(const TF_SessionOptions* opt, const char** containers, int ncontainers, TF_Status* status); */ } /// See TF_SessionRun() above. public func run(session: TF_Session!, runOptions: Tensorflow_RunOptions?, inputNames: [String], inputs: [TF_Tensor?], outputNames: [String], targetOperationsNames: [String], metaDataGraphDefInjection: (_ bufferPointer: UnsafeMutablePointer<TF_Buffer>?) throws ->Void) throws -> [TF_Tensor] { var runOptionsBufferPointer: UnsafeMutablePointer<TF_Buffer>? = nil if let runOptions = runOptions { let data = try runOptions.serializedData() let buffer = newBuffer(from: data) runOptionsBufferPointer = buffer } let inputNamesCArray = try inputNames.cArray() let outputNamesCArray = try outputNames.cArray() let targetOperationsNamesCArray = try targetOperationsNames.cArray() let metaGraphDef = TF_NewBuffer() let status = TF_NewStatus() var inputs = inputs let inputsPointer = inputs.withUnsafeMutableBufferPointer { (pointer) -> UnsafeMutablePointer<TF_Tensor?>? in pointer.baseAddress } let numberOfOutputs = Int32(outputNames.count) var outputsValuesPointer: UnsafeMutablePointer<TF_Tensor?>? if numberOfOutputs > 0 { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>.allocate(capacity: Int(numberOfOutputs)) } else { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>(bitPattern: 0) } TF_Run(session, runOptionsBufferPointer, inputNamesCArray.pointerList, inputsPointer, Int32(inputs.count), outputNamesCArray.pointerList, outputsValuesPointer, numberOfOutputs, targetOperationsNamesCArray.pointerList, Int32(targetOperationsNames.count), metaGraphDef, status) try metaDataGraphDefInjection(metaGraphDef) if let status = status, let error = StatusError(tfStatus: status) { throw error } if runOptionsBufferPointer != nil { TF_DeleteBuffer(runOptionsBufferPointer) } TF_DeleteBuffer(metaGraphDef) delete(status: status) if numberOfOutputs > 0, let pointer = outputsValuesPointer { let result = UnsafeMutableBufferPointer<TF_Tensor?>(start: pointer, count: Int(numberOfOutputs)).compactMap{ $0 } pointer.deallocate() return result } else { return [TF_Tensor]() } } /// See TF_SessionPRunSetup() above. public func partialRunSetup(session:TF_Session, inputNames: [String], inputs: [TF_Output], outputs: [TF_Output], targetOperations: [TF_Operation]? = nil) throws -> UnsafePointer<Int8> { fatalError("Not ready") } /// See TF_SessionPRun above. public func partialRun(sessiong: TF_DeprecatedSession!, handle: UnsafePointer<Int8>!, inputNames: UnsafeMutablePointer<UnsafePointer<Int8>?>!, inputs: UnsafeMutablePointer<OpaquePointer?>!, inputsNumber: Int32, outputNames: UnsafeMutablePointer<UnsafePointer<Int8>?>!, outputs: UnsafeMutablePointer<OpaquePointer?>!, outputsNumber: Int32, targetOperationsNames: UnsafeMutablePointer<UnsafePointer<Int8>?>!, targetsNumber: Int32, status: TF_Status!) { TF_PRun(sessiong, handle, inputNames, inputs, inputsNumber, outputNames, outputs, outputsNumber, targetOperationsNames, targetsNumber, status) } /// TF_SessionOptions holds options that can be passed during session creation. /// Return a new options object. public func newSessionOptions() -> TF_SessionOptions! { return TF_NewSessionOptions() } /// Set the target in TF_SessionOptions.options. /// target can be empty, a single entry, or a comma separated list of entries. /// Each entry is in one of the following formats : /// "local" /// ip:port /// host:port public func set(target: UnsafePointer<Int8>!, for options: TF_SessionOptions!) { TF_SetTarget(options, target) } /// Set the config in TF_SessionOptions.options. /// config should be a serialized tensorflow.ConfigProto proto. /// If config was not parsed successfully as a ConfigProto, record the /// error information in *status. public func setConfig(options: TF_SessionOptions!, proto: UnsafeRawPointer!, protoLength: Int) throws { let status = TF_NewStatus() defer { delete(status: status) } TF_SetConfig(options, proto, protoLength, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } } /// Destroy an options object. public func delete(sessionOptions: TF_SessionOptions!) { TF_DeleteSessionOptions(sessionOptions) } /// Lists all devices in a TF_Session. /// /// Caller takes ownership of the returned TF_DeviceList* which must eventually /// be freed with a call to TF_DeleteDeviceList. public func devices(`in` session: TF_Session) throws -> [TF_Device] { let status = TF_NewStatus() defer { delete(status: status) } let list = TF_SessionListDevices(session, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } var devices = [TF_Device]() let count = TF_DeviceListCount(list) for index in 0..<count { guard let deviceName = String(utf8String: TF_DeviceListName(list, index, status)) else { if let status = status, let error = StatusError(tfStatus: status) { debugPrint("Error at getting device list: \(error).") } continue } guard let deviceType = String(utf8String: TF_DeviceListType(list, index, status)) else { if let status = status, let error = StatusError(tfStatus: status) { debugPrint("Error at getting device list: \(error).") } continue } let memorySize = TF_DeviceListMemoryBytes(list, index, status) if let status = status, let error = StatusError(tfStatus: status) { debugPrint("Error at getting device list: \(error).") continue } devices.append(TF_Device(name: deviceName, type: deviceType, memorySize: memorySize)) } TF_DeleteDeviceList(list) return devices }
gpl-3.0
52db69e84acd43ccb05455b28443b711
34.529813
154
0.663262
4.651204
false
false
false
false
xwu/swift
test/Generics/rdar83687967.swift
1
2090
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s public protocol P1 {} public protocol P2 { associatedtype A: P1 } public protocol P3 { associatedtype B: P2 associatedtype A where B.A == A } public struct G<A: P1>: P2 {} public func callee<T: P1>(_: T.Type) {} // CHECK: rdar83687967.(file).caller11@ // CHECK: Generic signature: <Child where Child : P3, Child.B == G<Child.A>> public func caller11<Child: P3>(_: Child) where Child.B == G<Child.A> { callee(Child.A.self) } // CHECK: rdar83687967.(file).caller12@ // CHECK: Generic signature: <Child where Child : P3, Child.B == G<Child.A>> public func caller12<Child: P3>(_: Child) // expected-note@-1 {{conformance constraint 'Child.A' : 'P1' implied here}} where Child.B == G<Child.A>, Child.A : P1 { // expected-warning@-1 {{redundant conformance constraint 'Child.A' : 'P1'}} // Make sure IRGen can evaluate the conformance access path // (Child : P3)(Self.B : P2)(Self.A : P1). callee(Child.A.self) } // CHECK: rdar83687967.(file).X1@ // CHECK: Requirement signature: <Self where Self.Child : P3, Self.Child.B == G<Self.Child.A>> public protocol X1 { associatedtype Child: P3 where Child.B == G<Child.A> } // CHECK: rdar83687967.(file).X2@ // CHECK: Requirement signature: <Self where Self.Child : P3, Self.Child.B == G<Self.Child.A>> public protocol X2 { associatedtype Child: P3 // expected-note@-1 {{conformance constraint 'Self.Child.A' : 'P1' implied here}} where Child.B == G<Child.A>, Child.A : P1 // expected-warning@-1 {{redundant conformance constraint 'Self.Child.A' : 'P1'}} } public func caller21<T : X1>(_: T) { // Make sure IRGen can evaluate the conformance access path // (T : X1)(Child : P3)(Self.B : P2)(Self.A : P1). callee(T.Child.A.self) } public func caller22<T : X2>(_: T) { // Make sure IRGen can evaluate the conformance access path // (T : X2)(Child : P3)(Self.B : P2)(Self.A : P1). callee(T.Child.A.self) }
apache-2.0
d3d4c67869810836a9f645d363943ca6
30.666667
94
0.658373
2.985714
false
false
false
false
Tomikes/eidolon
KioskTests/App/RAC/RACFunctionsTests.swift
7
4576
import Quick import Nimble @testable import Kiosk import ReactiveCocoa class RACFunctionsTests: QuickSpec { override func spec() { describe("email address check") { it("requires @") { let valid = stringIsEmailAddress("ashartsymail.com") as! Bool expect(valid) == false } it("requires name") { let valid = stringIsEmailAddress("@artsymail.com") as! Bool expect(valid) == false } it("requires domain") { let valid = stringIsEmailAddress("[email protected]") as! Bool expect(valid) == false } it("requires tld") { let valid = stringIsEmailAddress("ash@artsymail") as! Bool expect(valid) == false } it("validates good emails") { let valid = stringIsEmailAddress("[email protected]") as! Bool expect(valid) == true } } describe("presenting cents as dollars") { it("works with valid input") { let input = 1_000_00 let formattedDolars = centsToPresentableDollarsString(input) as! String expect(formattedDolars) == "$1,000" } it("returns the empty string on invalid input") { let input = "something not a number" let formattedDolars = centsToPresentableDollarsString(input) as! String expect(formattedDolars) == "" } } describe("zero length string check") { it("returns true for zero-length strings") { let valid = isZeroLengthString("") as! Bool expect(valid) == true } it("returns false for non zero-length strings") { let valid = isZeroLengthString("something else") as! Bool expect(valid) == false } it("returns false for non zero-length strings of spaces") { let valid = isZeroLengthString(" ") as! Bool expect(valid) == false } } describe("string length range check") { it("returns true when the string length is within the specified range") { let valid = isStringLengthIn(1..<5)(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is not within the specified range") { let valid = isStringLengthIn(3..<5)(string: "hi") as! Bool expect(valid) == false } } describe("string length check") { it("returns true when the string length is the specified length") { let valid = isStringOfLength(2)(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is not the specified length") { let valid = isStringOfLength(3)(string: "hi") as! Bool expect(valid) == false } } describe("string length minimum check") { it("returns true when the string length is the specified length") { let valid = isStringLengthAtLeast(2)(string: "hi") as! Bool expect(valid) == true } it("returns true when the string length is more than the specified length") { let valid = isStringLengthAtLeast(1)(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is less than the specified length") { let valid = isStringLengthAtLeast(3)(string: "hi") as! Bool expect(valid) == false } } describe("string length one of check") { it("returns true when the string length is one of the specified lengths") { let valid = isStringLengthOneOf([0,2])(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is not one of the specified lengths") { let valid = isStringLengthOneOf([0,1])(string: "hi") as! Bool expect(valid) == false } it("returns false when the string length is between the specified lengths") { let valid = isStringLengthOneOf([1,3])(string: "hi") as! Bool expect(valid) == false } } } }
mit
dbc67c933fde9e0d4412c42341578988
35.608
92
0.521853
5.017544
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.SupportedDiagnosticsModes.swift
1
2101
import Foundation public extension AnyCharacteristic { static func supportedDiagnosticsModes( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read], description: String? = "Supported Diagnostics Modes", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.supportedDiagnosticsModes( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func supportedDiagnosticsModes( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read], description: String? = "Supported Diagnostics Modes", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<UInt32> { GenericCharacteristic<UInt32>( type: .supportedDiagnosticsModes, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
7d629690389b0eeb3401b08813debcc6
33.442623
66
0.591147
5.528947
false
false
false
false
mcgraw/dojo-custom-camera
dojo-custom-camera/XMCCameraViewController.swift
3
3787
// // XMCCameraViewController.swift // dojo-custom-camera // // Created by David McGraw on 11/13/14. // Copyright (c) 2014 David McGraw. All rights reserved. // import UIKit import AVFoundation enum Status: Int { case Preview, Still, Error } class XMCCameraViewController: UIViewController, XMCCameraDelegate { @IBOutlet weak var cameraStill: UIImageView! @IBOutlet weak var cameraPreview: UIView! @IBOutlet weak var cameraStatus: UILabel! @IBOutlet weak var cameraCapture: UIButton! @IBOutlet weak var cameraCaptureShadow: UILabel! var preview: AVCaptureVideoPreviewLayer? var camera: XMCCamera? var status: Status = .Preview override func viewDidLoad() { super.viewDidLoad() self.initializeCamera() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.establishVideoPreviewArea() } func initializeCamera() { self.cameraStatus.text = "Starting Camera" self.camera = XMCCamera(sender: self) } func establishVideoPreviewArea() { self.preview = AVCaptureVideoPreviewLayer(session: self.camera?.session) self.preview?.videoGravity = AVLayerVideoGravityResizeAspectFill self.preview?.frame = self.cameraPreview.bounds self.preview?.cornerRadius = 8.0 self.cameraPreview.layer.addSublayer(self.preview!) } // MARK: Button Actions @IBAction func captureFrame(sender: AnyObject) { if self.status == .Preview { self.cameraStatus.text = "Capturing Photo" UIView.animateWithDuration(0.225, animations: { () -> Void in self.cameraPreview.alpha = 0.0; self.cameraStatus.alpha = 1.0 }) self.camera?.captureStillImage({ (image) -> Void in if image != nil { self.cameraStill.image = image; UIView.animateWithDuration(0.225, animations: { () -> Void in self.cameraStill.alpha = 1.0; self.cameraStatus.alpha = 0.0; }) self.status = .Still } else { self.cameraStatus.text = "Uh oh! Something went wrong. Try it again." self.status = .Error } self.cameraCapture.setTitle("Reset", forState: UIControlState.Normal) }) } else if self.status == .Still || self.status == .Error { UIView.animateWithDuration(0.225, animations: { () -> Void in self.cameraStill.alpha = 0.0; self.cameraStatus.alpha = 0.0; self.cameraPreview.alpha = 1.0; self.cameraCapture.setTitle("Capture", forState: UIControlState.Normal) }, completion: { (done) -> Void in self.cameraStill.image = nil; self.status = .Preview }) } } // MARK: Camera Delegate func cameraSessionConfigurationDidComplete() { self.camera?.startCamera() } func cameraSessionDidBegin() { self.cameraStatus.text = "" UIView.animateWithDuration(0.225, animations: { () -> Void in self.cameraStatus.alpha = 0.0 self.cameraPreview.alpha = 1.0 self.cameraCapture.alpha = 1.0 self.cameraCaptureShadow.alpha = 0.4; }) } func cameraSessionDidStop() { self.cameraStatus.text = "Camera Stopped" UIView.animateWithDuration(0.225, animations: { () -> Void in self.cameraStatus.alpha = 1.0 self.cameraPreview.alpha = 0.0 }) } }
mit
66422b139983047a85aa8220567b627b
31.930435
89
0.57671
4.848912
false
false
false
false
GabrielGhe/SwiftProjects
App13CardTilt/CardTilt/TipInCellAnimator.swift
1
1464
// // TipInCellAnimator.swift // CardTilt // // Created by Gabriel Gheorghian on 2014-09-08. // Copyright (c) 2014 RayWenderlich.com. All rights reserved. // import UIKit import QuartzCore let TipInCellAnimatorStartTransform:CATransform3D = { // Variables let rotationDegrees: CGFloat = -15.0 let rotationRadians: CGFloat = rotationDegrees * (CGFloat(M_PI)/180.0) let offset = CGPointMake(-20, -20) var startTransform = CATransform3DIdentity // Rotate Identity 15 degrees counter clockwise startTransform = CATransform3DRotate(CATransform3DIdentity, rotationRadians, 0.0, 0.0, 1.0) // Translate the card a bit startTransform = CATransform3DTranslate(startTransform, offset.x, offset.y, 0.0) return startTransform }() class TipInCellAnimator { class func animate(cell: UITableViewCell) { let view = cell.contentView view.layer.opacity = 0.1 UIView.animateWithDuration(1.4, animations: { view.layer.opacity = 1 }) } class func animateByRotating(cell: UITableViewCell) { let view = cell.contentView // Initial state view.layer.transform = TipInCellAnimatorStartTransform view.layer.opacity = 0.8 // Animate back to normal UIView.animateWithDuration(0.4) { view.layer.transform = CATransform3DIdentity view.layer.opacity = 1 } } }
mit
41badfe2c2236195b0bfacadc574b549
27.173077
84
0.655055
4.280702
false
false
false
false
ihomway/RayWenderlichCourses
Intermediate Swift 3/Intermediate Swift 3.playground/Pages/Classes Challenge.xcplaygroundpage/Contents.swift
1
892
//: [Previous](@previous) import UIKit /*: #### Intermediate Swift Video Tutorial Series - raywenderlich.com #### Video 5: Classes **Note:** If you're seeing this text as comments rather than nicely-rendered text, select Editor\Show Rendered Markup in the Xcode menu. Make the following objects and determine whether they are structs or classes. For the properties, use properties unless noted below. TShirt: size, color Address: street, city, state, zipCode User: firstName, lastName, address (Address object) ShoppingCart: shirts (array of TShirt), User (user object) */ struct Tshirt { } struct Address { var street: String = "" var city: String = "" var state: String = "" var zipCode: Int = 0 } class User { var firstName = "" var lastName = "" var address: Address = Address() } class ShoppingCart { var shirts: [Tshirt] = [] var user = User() } //: [Next](@next)
mit
87a76953b520c2428033a29b7cecba13
20.238095
136
0.702915
3.582329
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/Media/MediaThumbnailExporter.swift
2
11255
import Foundation import MobileCoreServices /// Media export handling of thumbnail images from videos or images. /// class MediaThumbnailExporter: MediaExporter { /// Directory type for the ThumbnailExporter, defaults to the .cache directory. /// var mediaDirectoryType: MediaDirectory = .cache // MARK: Export Options var options = Options() /// Available options for an thumbnail export. /// struct Options { /// The preferred size of the image, in points, typically for the actual display /// of the image within a layout's dimensions. If nil, the image will not be resized. /// /// - Note: The final size may or may not match the preferred dimensions, depending /// on the original image. /// var preferredSize: CGSize? /// The scale for the actual pixel size of the image when resizing, /// generally matching a screen scale of 1.0, 2.0, 3.0, etc. /// /// - Note: Defaults to the main UIScreen scale. The final image may or may not match /// the intended scale/pixels, depending on the original image. /// var scale: CGFloat = UIScreen.main.scale /// The compression quality of the thumbnail, if the image type supports compression. /// var compressionQuality = 0.90 /// The target image type of the exported thumbnail images. /// /// - Note: Passed on to the MediaImageExporter.Options.exportImageType. /// var thumbnailImageType = kUTTypeJPEG as String /// Computed preferred size, at scale. /// var preferredSizeAtScale: CGSize? { guard let size = preferredSize else { return nil } return CGSize(width: size.width * scale, height: size.height * scale) } /// Computed preferred maximum size, at scale. /// var preferredMaximumSizeAtScale: CGFloat? { guard let size = preferredSize else { return nil } return max(size.width, size.height) * scale } lazy var identifier: String = { return UUID().uuidString }() } // MARK: - Types /// A generated thumbnail identifier representing a reference to the image files that /// result from a thumbnail export. This ensures unique files are created and URLs /// can be recreated as needed, relative to both the identifier and the configured /// options for an exporter. /// /// - Note: Media objects should store or cache these identifiers in order to reuse /// previously exported Media files that match the given identifier and configured options. /// typealias ThumbnailIdentifier = String /// Completion block with the generated thumbnail identifier and resulting image export. /// typealias OnThumbnailExport = (ThumbnailIdentifier, MediaExport) -> Void /// Errors specific to exporting thumbnails. /// public enum ThumbnailExportError: MediaExportError { case failedToGenerateThumbnailFileURL case unsupportedThumbnailFromOriginalType var description: String { switch self { default: return NSLocalizedString("Thumbnail unavailable.", comment: "Message shown if a thumbnail preview of a media item unavailable.") } } } // MARK: - Public /// The available file URL of a thumbnail, if it exists, relative to the identifier /// and exporter's configured options. /// /// - Note: Consider using this URL for cacheing exported images located at the URL. /// func availableThumbnail(with identifier: ThumbnailIdentifier) -> URL? { guard let thumbnail = try? thumbnailURL(withIdentifier: identifier) else { return nil } guard let type = thumbnail.typeIdentifier, UTTypeConformsTo(type as CFString, options.thumbnailImageType as CFString) else { return nil } return thumbnail } /// Check for whether or not a file URL supports a thumbnail export. /// func supportsThumbnailExport(forFile url: URL) -> Bool { do { let expected = try MediaURLExporter.expectedExport(with: url) switch expected { case .image, .video, .gif: return true case .other: return false } } catch { return false } } let url: URL? init(url: URL? = nil) { self.url = url } public func export(onCompletion: @escaping OnMediaExport, onError: @escaping OnExportError) -> Progress { guard let fileURL = url else { onError(exporterErrorWith(error: ThumbnailExportError.failedToGenerateThumbnailFileURL)) return Progress.discreteCompletedProgress() } return exportThumbnail(forFile: fileURL, onCompletion: { (identifier, export) in onCompletion(export) }, onError: onError) } /// Export a thumbnail image for a file at the URL, with an expected type of an image or video. /// /// - Note: GIFs are currently unsupported and throw the .gifThumbnailsUnsupported error. /// @discardableResult func exportThumbnail(forFile url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress { do { let expected = try MediaURLExporter.expectedExport(with: url) switch expected { case .image, .gif: return exportImageThumbnail(at: url, onCompletion: onCompletion, onError: onError) case .video: return exportVideoThumbnail(at: url, onCompletion: onCompletion, onError: onError) case .other: return Progress.discreteCompletedProgress() } } catch { onError(exporterErrorWith(error: error)) return Progress.discreteCompletedProgress() } } /// Export an existing image as a thumbnail image, based on the exporter options. /// @discardableResult func exportThumbnail(forImage image: UIImage, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress { let exporter = MediaImageExporter(image: image, filename: UUID().uuidString) exporter.mediaDirectoryType = .temporary exporter.options = imageExporterOptions return exporter.export(onCompletion: { (export) in self.exportImageToThumbnailCache(export, onCompletion: onCompletion, onError: onError) }, onError: onError) } /// Export a known video at the URL, being either a file URL or a remote URL. /// @discardableResult func exportThumbnail(forVideoURL url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress { if url.isFileURL { return exportThumbnail(forFile: url, onCompletion: onCompletion, onError: onError) } else { return exportVideoThumbnail(at: url, onCompletion: onCompletion, onError: onError) } } // MARK: - Private /// Export a thumbnail for a known image at the URL, using self.options for ImageExporter options. /// @discardableResult fileprivate func exportImageThumbnail(at url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress { let exporter = MediaImageExporter(url: url) exporter.mediaDirectoryType = .temporary exporter.options = imageExporterOptions return exporter.export(onCompletion: { (export) in self.exportImageToThumbnailCache(export, onCompletion: onCompletion, onError: onError) }, onError: onError) } /// Export a thumbnail for a known video at the URL, using self.options for ImageExporter options. /// @discardableResult fileprivate func exportVideoThumbnail(at url: URL, onCompletion: @escaping OnThumbnailExport, onError: @escaping OnExportError) -> Progress { let exporter = MediaVideoExporter(url: url) exporter.mediaDirectoryType = .temporary return exporter.exportPreviewImageForVideo(atURL: url, imageOptions: imageExporterOptions, onCompletion: { (export) in self.exportImageToThumbnailCache(export, onCompletion: onCompletion, onError: onError) }, onError: onError) } /// The default options to use for exporting images based on the thumbnail exporter's options. /// fileprivate var imageExporterOptions: MediaImageExporter.Options { var imageOptions = MediaImageExporter.Options() if let maximumSize = options.preferredMaximumSizeAtScale { imageOptions.maximumImageSize = maximumSize } imageOptions.imageCompressionQuality = options.compressionQuality imageOptions.exportImageType = options.thumbnailImageType return imageOptions } /// A thumbnail URL written with the corresponding identifier and configured export options. /// fileprivate func thumbnailURL(withIdentifier identifier: ThumbnailIdentifier) throws -> URL { var filename = "thumbnail-\(identifier)" if let preferredSize = options.preferredSizeAtScale { filename.append("-\(Int(preferredSize.width))x\(Int(preferredSize.height))") } // Get a new URL for the file as a thumbnail within the cache. return try mediaFileManager.makeLocalMediaURL(withFilename: filename, fileExtension: URL.fileExtensionForUTType(options.thumbnailImageType), incremented: false) } /// Renames and moves an exported thumbnail to the expected directory with the expected thumbnail filenaming convention. /// fileprivate func exportImageToThumbnailCache(_ export: MediaExport, onCompletion: OnThumbnailExport, onError: OnExportError) { do { // Generate a unique ID let identifier = options.identifier let thumbnail = try thumbnailURL(withIdentifier: identifier) let fileManager = FileManager.default // Move the exported file at the url to the new URL. try? fileManager.removeItem(at: thumbnail) try fileManager.moveItem(at: export.url, to: thumbnail) // Configure with the new URL let thumbnailExport = MediaExport(url: thumbnail, fileSize: export.fileSize, width: export.width, height: export.height, duration: nil) // And return. onCompletion(identifier, thumbnailExport) } catch { onError(exporterErrorWith(error: error)) } } }
gpl-2.0
ce5fc0f312d31d9fb7308b0c82ac0df5
41.632576
164
0.627099
5.580069
false
false
false
false
Roommate-App/roomy
roomy/Pods/Starscream/Sources/WebSocket.swift
2
54234
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2017 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CoreFoundation import SSCommonCrypto public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" //Standard WebSocket close codes public enum CloseCode : UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } public enum ErrorType: Error { case outputStreamWriteError //output stream error during write case compressionError case invalidSSLError //Invalid SSL certificate case writeTimeoutError //The socket timed out waiting to be ready to write case protocolError //There was an error parsing the WebSocket frames case upgradeError //There was an error during the HTTP upgrade case closeError //There was an error during the close (socket probably has been dereferenced) } public struct WSError: Error { public let type: ErrorType public let message: String public let code: Int } //WebSocketClient is setup to be dependency injection for testing public protocol WebSocketClient: class { var delegate: WebSocketDelegate? {get set } var disableSSLCertValidation: Bool { get set } var overrideTrustHostname: Bool { get set } var desiredTrustHostname: String? { get set } #if os(Linux) #else var security: SSLTrustValidator? { get set } var enabledSSLCipherSuites: [SSLCipherSuite]? { get set } #endif var isConnected: Bool { get } func connect() func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16) func write(string: String, completion: (() -> ())?) func write(data: Data, completion: (() -> ())?) func write(ping: Data, completion: (() -> ())?) func write(pong: Data, completion: (() -> ())?) } //implements some of the base behaviors extension WebSocketClient { public func write(string: String) { write(string: string, completion: nil) } public func write(data: Data) { write(data: data, completion: nil) } public func write(ping: Data) { write(ping: ping, completion: nil) } public func write(pong: Data) { write(pong: pong, completion: nil) } public func disconnect() { disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue) } } //SSL settings for the stream public struct SSLSettings { let useSSL: Bool let disableCertValidation: Bool var overrideTrustHostname: Bool var desiredTrustHostname: String? #if os(Linux) #else let cipherSuites: [SSLCipherSuite]? #endif } public protocol WSStreamDelegate: class { func newBytesInStream() func streamDidError(error: Error?) } //This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used public protocol WSStream { weak var delegate: WSStreamDelegate? {get set} func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) func write(data: Data) -> Int func read() -> Data? func cleanup() #if os(Linux) || os(watchOS) #else func sslTrust() -> (trust: SecTrust?, domain: String?) #endif } open class FoundationStream : NSObject, WSStream, StreamDelegate { private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) private var inputStream: InputStream? private var outputStream: OutputStream? public weak var delegate: WSStreamDelegate? let BUFFER_MAX = 4096 public var enableSOCKSProxy = false public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) { var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h = url.host! as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work #else if enableSOCKSProxy { let proxyDict = CFNetworkCopySystemProxySettings() let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue()) let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy) CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig) CFReadStreamSetProperty(inputStream, propertyKey, socksConfig) } #endif guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if ssl.useSSL { inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work #else var settings = [NSObject: NSObject]() if ssl.disableCertValidation { settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false) } if ssl.overrideTrustHostname { if let hostname = ssl.desiredTrustHostname { settings[kCFStreamSSLPeerName] = hostname as NSString } else { settings[kCFStreamSSLPeerName] = kCFNull } } inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) #endif #if os(Linux) #else if let cipherSuites = ssl.cipherSuites { #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work #else if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn))) } if resOut != errSecSuccess { completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut))) } } #endif } #endif } CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue) inStream.open() outStream.open() var out = timeout// wait X seconds before giving up FoundationStream.sharedWorkQueue.async { [weak self] in while !outStream.hasSpaceAvailable { usleep(100) // wait until the socket is ready out -= 100 if out < 0 { completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0)) return } else if let error = outStream.streamError { completion(error) return // disconnectStream will be called. } else if self == nil { completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0)) return } } completion(nil) //success! } } public func write(data: Data) -> Int { guard let outStream = outputStream else {return -1} let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) return outStream.write(buffer, maxLength: data.count) } public func read() -> Data? { guard let stream = inputStream else {return nil} let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = stream.read(buffer, maxLength: BUFFER_MAX) if length < 1 { return nil } return Data(bytes: buffer, count: length) } public func cleanup() { if let stream = inputStream { stream.delegate = nil CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { stream.delegate = nil CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil } #if os(Linux) || os(watchOS) #else public func sslTrust() -> (trust: SecTrust?, domain: String?) { let trust = outputStream!.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? var domain = outputStream!.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String if domain == nil, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { var peerNameLen: Int = 0 SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) var peerName = Data(count: peerNameLen) let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) } if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { domain = peerDomain } } return (trust, domain) } #endif /** Delegate for the stream methods. Processes incoming bytes */ open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if eventCode == .hasBytesAvailable { if aStream == inputStream { delegate?.newBytesInStream() } } else if eventCode == .errorOccurred { delegate?.streamDidError(error: aStream.streamError) } else if eventCode == .endEncountered { delegate?.streamDidError(error: nil) } } } //WebSocket implementation //standard delegate you should use public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocketClient) func websocketDidDisconnect(socket: WebSocketClient, error: Error?) func websocketDidReceiveMessage(socket: WebSocketClient, text: String) func websocketDidReceiveData(socket: WebSocketClient, data: Data) } //got pongs public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocketClient, data: Data?) } // A Delegate with more advanced info on messages and connection etc. public protocol WebSocketAdvancedDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: Error?) func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse) func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse) func websocketHttpUpgrade(socket: WebSocket, request: String) func websocketHttpUpgrade(socket: WebSocket, response: String) } open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate { public enum OpCode : UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. } public static let ErrorDomain = "WebSocket" // Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = DispatchQueue.main // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSExtensionName = "Sec-WebSocket-Extensions" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let RSV1Mask: UInt8 = 0x40 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] public class WSResponse { var isFin = false public var code: OpCode = .continueFrame var bytesLeft = 0 public var frameCount = 0 public var buffer: NSMutableData? public let firstFrame = { return Date() }() } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. public weak var delegate: WebSocketDelegate? /// The optional advanced delegate can be used instead of of the delegate public weak var advancedDelegate: WebSocketAdvancedDelegate? /// Receives a callback for each pong message recived. public weak var pongDelegate: WebSocketPongDelegate? public var onConnect: (() -> Void)? public var onDisconnect: ((Error?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((Data) -> Void)? public var onPong: ((Data?) -> Void)? public var disableSSLCertValidation = false public var overrideTrustHostname = false public var desiredTrustHostname: String? = nil public var enableCompression = true #if os(Linux) #else public var security: SSLTrustValidator? public var enabledSSLCipherSuites: [SSLCipherSuite]? #endif public var isConnected: Bool { connectedMutex.lock() let isConnected = connected connectedMutex.unlock() return isConnected } public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect public var currentURL: URL { return request.url! } public var respondToPingWithPong: Bool = true // MARK: - Private private struct CompressionState { var supportsCompression = false var messageNeedsDecompression = false var serverMaxWindowBits = 15 var clientMaxWindowBits = 15 var clientNoContextTakeover = false var serverNoContextTakeover = false var decompressor:Decompressor? = nil var compressor:Compressor? = nil } private var stream: WSStream private var connected = false private var isConnecting = false private let connectedMutex = NSLock() private var compressionState = CompressionState() private var writeQueue = OperationQueue() private var readStack = [WSResponse]() private var inputQueue = [Data]() private var fragBuffer: Data? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private var headerSecKey = "" private let readyToWriteMutex = NSLock() private var canDispatch: Bool { readyToWriteMutex.lock() let canWork = readyToWrite readyToWriteMutex.unlock() return canWork } /// Used for setting protocols. public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) { self.request = request self.stream = stream if request.value(forHTTPHeaderField: headerOriginName) == nil { guard let url = request.url else {return} var origin = url.absoluteString if let hostUrl = URL (string: "/", relativeTo: url) { origin = hostUrl.absoluteString origin.remove(at: origin.index(before: origin.endIndex)) } self.request.setValue(origin, forHTTPHeaderField: headerOriginName) } if let protocols = protocols { self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName) } writeQueue.maxConcurrentOperationCount = 1 } public convenience init(url: URL, protocols: [String]? = nil) { var request = URLRequest(url: url) request.timeoutInterval = 5 self.init(request: request, protocols: protocols) } // Used for specifically setting the QOS for the write queue. public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) { self.init(url: url, protocols: protocols) writeQueue.qualityOfService = writeQueueQOS } /** Connect to the WebSocket server on a background thread. */ open func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. */ open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { guard isConnected else { return } switch forceTimeout { case .some(let seconds) where seconds > 0: let milliseconds = Int(seconds * 1_000) callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in self?.disconnectStream(nil) } fallthrough case .none: writeError(closeCode) default: disconnectStream(nil) break } } /** Write a string to the websocket. This sends it as a text frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter string: The string to write. - parameter completion: The (optional) completion handler. */ open func write(string: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) } /** Write binary data to the websocket. This sends it as a binary frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter data: The data to write. - parameter completion: The (optional) completion handler. */ open func write(data: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) } /** Write a ping to the websocket. This sends it as a control frame. Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s */ open func write(ping: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(ping, code: .ping, writeCompletion: completion) } /** Write a pong to the websocket. This sends it as a control frame. Respond to a Yodel. */ open func write(pong: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(pong, code: .pong, writeCompletion: completion) } /** Private method that starts the connection. */ private func createHTTPRequest() { guard let url = request.url else {return} var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName) request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName) headerSecKey = generateWebSocketKey() request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName) request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName) if enableCompression { let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" request.setValue(val, forHTTPHeaderField: headerWSExtensionName) } let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)" request.setValue(hostValue, forHTTPHeaderField: headerWSHostName) var path = url.absoluteString let offset = (url.scheme?.count ?? 2) + 3 path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex]) if let range = path.range(of: "/") { path = String(path[range.lowerBound..<path.endIndex]) } else { path = "/" if let query = url.query { path += "?" + query } } var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n" if let headers = request.allHTTPHeaderFields { for (key, val) in headers { httpBody += "\(key): \(val)\r\n" } } httpBody += "\r\n" initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!)) advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody) } /** Generate a WebSocket key as needed in RFC. */ private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni!))" } let data = key.data(using: String.Encoding.utf8) let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return baseKey! } /** Start the stream connection and write the data to the output stream. */ private func initStreamsWithData(_ data: Data, _ port: Int) { guard let url = request.url else { disconnectStream(nil, runDelegate: true) return } // Disconnect and clean up any existing streams before setting up a new pair disconnectStream(nil, runDelegate: false) let useSSL = supportedSSLSchemes.contains(url.scheme!) #if os(Linux) let settings = SSLSettings(useSSL: useSSL, disableCertValidation: disableSSLCertValidation, overrideTrustHostname: overrideTrustHostname, desiredTrustHostname: desiredTrustHostname) #else let settings = SSLSettings(useSSL: useSSL, disableCertValidation: disableSSLCertValidation, overrideTrustHostname: overrideTrustHostname, desiredTrustHostname: desiredTrustHostname, cipherSuites: self.enabledSSLCipherSuites) #endif certValidated = !useSSL let timeout = request.timeoutInterval * 1_000_000 stream.delegate = self stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in guard let s = self else {return} if error != nil { s.disconnectStream(error) return } let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in guard let sOperation = operation, let s = self else { return } guard !sOperation.isCancelled else { return } // Do the pinning now if needed #if os(Linux) || os(watchOS) s.certValidated = false #else if let sec = s.security, !s.certValidated { let trustObj = s.stream.sslTrust() if let possibleTrust = trustObj.trust { s.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain) } else { s.certValidated = false } if !s.certValidated { s.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0)) return } } #endif let _ = s.stream.write(data: data) } s.writeQueue.addOperation(operation) }) self.readyToWriteMutex.lock() self.readyToWrite = true self.readyToWriteMutex.unlock() } /** Delegate for the stream methods. Processes incoming bytes */ public func newBytesInStream() { processInputStream() } public func streamDidError(error: Error?) { disconnectStream(error) } /** Disconnect the stream object and notifies the delegate. */ private func disconnectStream(_ error: Error?, runDelegate: Bool = true) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } cleanupStream() connectedMutex.lock() connected = false connectedMutex.unlock() if runDelegate { doDisconnect(error) } } /** cleanup the streams. */ private func cleanupStream() { stream.cleanup() fragBuffer = nil } /** Handles the incoming bytes and sending them to the proper processing method. */ private func processInputStream() { let data = stream.read() guard let d = data else { return } var process = false if inputQueue.count == 0 { process = true } inputQueue.append(d) if process { dequeueInput() } } /** Dequeue the incoming input so it is processed in order. */ private func dequeueInput() { while !inputQueue.isEmpty { autoreleasepool { let data = inputQueue[0] var work = data if let buffer = fragBuffer { var combine = NSData(data: buffer) as Data combine.append(data) work = combine fragBuffer = nil } let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) let length = work.count if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter{ $0 != data } } } } /** Handle checking the inital connection status */ private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: break case -1: fragBuffer = Data(bytes: buffer, count: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code)) } } /** Finds the HTTP Packet in the TCP stream, by looking for the CRLF. */ private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 4 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } isConnecting = false connectedMutex.lock() connected = true connectedMutex.unlock() didDisconnect = false if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(socket: s) s.advancedDelegate?.websocketDidConnect(socket: s) NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) } } //totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } /** Validates the HTTP is a 101 as per the RFC spec. */ private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 } let splitArr = str.components(separatedBy: "\r\n") var code = -1 var i = 0 var headers = [String: String]() for str in splitArr { if i == 0 { let responseSplit = str.components(separatedBy: .whitespaces) guard responseSplit.count > 1 else { return -1 } if let c = Int(responseSplit[1]) { code = c } } else { let responseSplit = str.components(separatedBy: ":") guard responseSplit.count > 1 else { break } let key = responseSplit[0].trimmingCharacters(in: .whitespaces) let val = responseSplit[1].trimmingCharacters(in: .whitespaces) headers[key.lowercased()] = val } i += 1 } advancedDelegate?.websocketHttpUpgrade(socket: self, response: str) if code != httpSwitchProtocolCode { return code } if let extensionHeader = headers[headerWSExtensionName.lowercased()] { processExtensionHeader(extensionHeader) } if let acceptKey = headers[headerWSAcceptName.lowercased()] { if acceptKey.count > 0 { if headerSecKey.count > 0 { let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() if sha != acceptKey as String { return -1 } } return 0 } } return -1 } /** Parses the extension header, setting up the compression parameters. */ func processExtensionHeader(_ extensionHeader: String) { let parts = extensionHeader.components(separatedBy: ";") for p in parts { let part = p.trimmingCharacters(in: .whitespaces) if part == "permessage-deflate" { compressionState.supportsCompression = true } else if part.hasPrefix("server_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressionState.serverMaxWindowBits = val } } else if part.hasPrefix("client_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressionState.clientMaxWindowBits = val } } else if part == "client_no_context_takeover" { compressionState.clientNoContextTakeover = true } else if part == "server_no_context_takeover" { compressionState.serverNoContextTakeover = true } } if compressionState.supportsCompression { compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits) compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits) } } /** Read a 16 bit big endian value from a buffer */ private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } /** Read a 64 bit big endian value from a buffer */ private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } /** Write a 16-bit big endian value to a buffer. */ private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } /** Write a 64-bit big endian value to a buffer. */ private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } /** Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. */ private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last guard let baseAddress = buffer.baseAddress else {return emptyBuffer} let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = Data(buffer: buffer) return emptyBuffer } if let response = response, response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.append(Data(bytes: baseAddress, count: len)) _ = processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if compressionState.supportsCompression && receivedOpcode != .continueFrame { compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0 } if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode))) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && receivedOpcode != .textFrame && receivedOpcode != .pong) { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode))) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode))) writeError(errCode) return emptyBuffer } var closeCode = CloseCode.normal.rawValue if receivedOpcode == .connectionClose { if payloadLen == 1 { closeCode = CloseCode.protocolError.rawValue } else if payloadLen > 1 { closeCode = WebSocket.readUint16(baseAddress, offset: offset) if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { closeCode = CloseCode.protocolError.rawValue } } if payloadLen < 2 { doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode))) writeError(closeCode) return emptyBuffer } } else if isControlFrame && payloadLen > 125 { writeError(CloseCode.protocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += MemoryLayout<UInt64>.size } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += MemoryLayout<UInt16>.size } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = Data(bytes: baseAddress, count: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } if receivedOpcode == .connectionClose && len > 0 { let size = MemoryLayout<UInt16>.size offset += size len -= UInt64(size) } let data: Data if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor { do { data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0) if isFin > 0 && compressionState.serverNoContextTakeover { try decompressor.reset() } } catch { let closeReason = "Decompression failed: \(error)" let closeCode = CloseCode.encoding.rawValue doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) writeError(closeCode) return emptyBuffer } } else { data = Data(bytes: baseAddress+offset, count: Int(len)) } if receivedOpcode == .connectionClose { var closeReason = "connection closed by server" if let customCloseReason = String(data: data, encoding: .utf8) { closeReason = customCloseReason } else { closeCode = CloseCode.protocolError.rawValue } doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) writeError(closeCode) return emptyBuffer } if receivedOpcode == .pong { if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } let pongData: Data? = data.count > 0 ? data : nil s.onPong?(pongData) s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .continueFrame && response == nil { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode))) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .continueFrame { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode))) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .continueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode))) writeError(errCode) return emptyBuffer } response!.buffer!.append(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } _ = processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } /** Process all messages in the buffer if possible. */ private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if buffer.count > 0 { fragBuffer = Data(buffer: buffer) } } /** Process the finished response of a buffer. */ private func processResponse(_ response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .ping { if respondToPingWithPong { let data = response.buffer! // local copy so it is perverse for writing dequeueWrite(data as Data, code: .pong) } } else if response.code == .textFrame { guard let str = String(data: response.buffer! as Data, encoding: .utf8) else { writeError(CloseCode.encoding.rawValue) return false } if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onText?(str) s.delegate?.websocketDidReceiveMessage(socket: s, text: str) s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str, response: response) } } } else if response.code == .binaryFrame { if canDispatch { let data = response.buffer! // local copy so it is perverse for writing callbackQueue.async { [weak self] in guard let s = self else { return } s.onData?(data as Data) s.delegate?.websocketDidReceiveData(socket: s, data: data as Data) s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response) } } } readStack.removeLast() return true } return false } /** Write an error to the socket */ private func writeError(_ code: UInt16) { let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose) } /** Used to write things to the stream */ private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in //stream isn't ready, let's wait guard let s = self else { return } guard let sOperation = operation else { return } var offset = 2 var firstByte:UInt8 = s.FinMask | code.rawValue var data = data if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor { do { data = try compressor.compress(data) if s.compressionState.clientNoContextTakeover { try compressor.reset() } firstByte |= s.RSV1Mask } catch { // TODO: report error? We can just send the uncompressed frame. } } let dataLength = data.count let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) buffer[0] = firstByte if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += MemoryLayout<UInt16>.size } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += MemoryLayout<UInt64>.size } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey) offset += MemoryLayout<UInt32>.size for i in 0..<dataLength { buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size] offset += 1 } var total = 0 while !sOperation.isCancelled { if !s.readyToWrite { s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) break } let stream = s.stream let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total)) if len <= 0 { s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) break } else { total += len } if total >= offset { if let queue = self?.callbackQueue, let callback = writeCompletion { queue.async { callback() } } break } } } writeQueue.addOperation(operation) } /** Used to preform the disconnect delegate */ private func doDisconnect(_ error: Error?) { guard !didDisconnect else { return } didDisconnect = true isConnecting = false connectedMutex.lock() connected = false connectedMutex.unlock() guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(socket: s, error: error) s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error) let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { readyToWriteMutex.lock() readyToWrite = false readyToWriteMutex.unlock() cleanupStream() writeQueue.cancelAllOperations() } } private extension String { func sha1Base64() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } return Data(bytes: digest).base64EncodedString() } } private extension Data { init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress!, count: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0) #if swift(>=4) #else fileprivate extension String { var count: Int { return self.characters.count } } #endif
mit
cf248536a4dac655b7535cee46202589
39.352679
226
0.586422
5.343778
false
false
false
false
Cleverlance/Pyramid
Example/Tests/Scope Management/Application/InstanceProviderImplTests.swift
1
1303
// // Copyright © 2016 Cleverlance. All rights reserved. // import XCTest import Nimble import Pyramid class InstanceProviderImplTests: XCTestCase { func test_ItConformsToInstanceProvider() { let _: InstanceProvider<Int>? = (nil as InstanceProviderImpl<Int>?) } func test_ItDependsOnScopeController() { let _ = InstanceProviderImpl<Int>(scopeController: ScopeControllerDummy()) } func test_GetInstance_ItShouldReturnInstanceFromScopeFromGivenController() { let provider = InstanceProviderImpl<Int>( scopeController: ScopeControllerWithScopeReturning42() ) let result = provider.getInstance() expect(result) == 42 } } private class ScopeControllerDummy: ScopeController { let isScopeLoaded = false func discardScope() {} func getScope() -> Scope { return ScopeDummy(parent: nil) } } private class ScopeControllerWithScopeReturning42: ScopeController { let isScopeLoaded = false func discardScope() {} func getScope() -> Scope { return ScopeReturning42(parent: nil) } } private class ScopeReturning42: Scope { required init(parent: Scope?) {} func getInstance<T>(of type: T.Type) -> T? { if let result = 42 as? T { return result } return nil } }
mit
fe319de64185cb45658524e5485977c0
25.571429
82
0.682028
4.398649
false
true
false
false
GermanCentralLibraryForTheBlind/LargePrintMusicNotes
LargePrintMusicNotesViewer/PdfViewerController.swift
1
2561
// Created by Lars Voigt. // //The MIT License (MIT) //Copyright (c) 2016 German Central Library for the Blind (DZB) //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 PdfViewerController: UIViewController { @IBOutlet weak var webView: UIWebView! var composition = [String:AnyObject]() override func viewDidLoad() { super.viewDidLoad() // if let pdf = NSBundle.mainBundle().URLForResource("example", withExtension: "pdf", subdirectory: nil, localization: nil) { // let req = NSURLRequest(URL: pdf) // self.webView.loadRequest(req) // } self.navigationItem.title = composition["title"] as? String let url = "http://dacapolp.dzb.de:13857/DaCapoLP/show/?id=" + String((composition["id"] as? Int)!) self.webView.loadRequest(URLRequest(url: URL(string: url)!)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setCurrentComposition(_ compo: [String:AnyObject]) { composition = compo } /* // 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
171a53cb3a8bc2edf444d3418b5b0825
39.650794
141
0.696993
4.656364
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Personal/PublishTourPhotoCollectionTableViewCell.swift
1
4600
// // PublishTourPhotoCollectionTableViewCell.swift // Whereami // // Created by A on 16/4/28. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit //import TZImagePickerController class PublishTourPhotoCollectionTableViewCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { var collectionView:UICollectionView? = nil var photoArray:[AnyObject]? = nil override func awakeFromNib() { super.awakeFromNib() // Initialization code } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } func setupUI(){ self.backgroundColor = UIColor.clearColor() let flowLayout = UICollectionViewFlowLayout() self.collectionView = UICollectionView(frame: self.contentView.bounds,collectionViewLayout: flowLayout) self.collectionView?.backgroundColor = UIColor.clearColor() self.collectionView?.dataSource = self self.collectionView?.delegate = self self.collectionView?.scrollEnabled = false self.contentView.addSubview(self.collectionView!) self.collectionView?.registerClass(PersonalPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PersonalPhotoCollectionViewCell") self.collectionView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0, 0, 0, 0)) } func updateCollections(){ self.collectionView?.reloadData() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let photos = self.photoArray else { return 0 } if(photos.count == 9 ) { return 9 } else { return photos.count+1 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PersonalPhotoCollectionViewCell", forIndexPath: indexPath) as! PersonalPhotoCollectionViewCell if indexPath.row == self.photoArray?.count { cell.photoView?.image = UIImage(named: "plus") } else{ // if self.photoArray![indexPath.row].isKindOfClass(UIImage) { // let image = self.photoArray![indexPath.row] as! UIImage // cell.photoView?.image = image // } // else{ // TZImageManager().getPhotoWithAsset(self.photoArray![indexPath.row], completion: { (image, dic, bool) in // cell.photoView?.image = image // }) // } cell.photoView?.image = self.photoArray![indexPath.row] as? UIImage } // cell.photoView?.image = self.photoArray![indexPath.row] as? UIImage return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(8, 16, 8, 16) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 8 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{ return 8 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let screenW = UIScreen.mainScreen().bounds.width let photoWidth = (screenW-16*2-8*3)/4 let size = CGSize(width: photoWidth,height: photoWidth) return size } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.photoArray?.count { NSNotificationCenter.defaultCenter().postNotificationName("didTouchAddButton", object: collectionView) } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
b0dd7e4939f865abedd2a0742acecd06
37.957627
177
0.676746
5.73192
false
false
false
false
GermanCentralLibraryForTheBlind/LargePrintMusicNotes
LargePrintMusicNotesViewer/RESTConnector.swift
1
5168
// Created by Lars Voigt. // //The MIT License (MIT) //Copyright (c) 2016 German Central Library for the Blind (DZB) //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 Alamofire import SwiftyJSON class RESTConnector { //let endpoint = "http://musiclargeprint-tttttest.rhcloud.com/" let endpoint = "http://dacapolp.dzb.de:13857/DaCapoLP/" let login = "login/" let list = "list/" let show = "show/" func getUserData(_ userName : String, password : String, completionHandler: @escaping ([[String:AnyObject]], String?) -> Void) { var parameters: [String:Any] = [:] Alamofire.request(self.endpoint + self.login, method: .get, parameters: parameters).responseJSON { response in switch response.result { case .success: if let JSON = response.result.value { // print("Did receive JSON data: \(JSON)") let jsonData = JSON as! [String:Any] let csrf_token = jsonData["csrf_token"] as! String; parameters = ["username" : userName, "password" : password , "csrfmiddlewaretoken" : csrf_token] } else { completionHandler([[String:AnyObject]](), "JSON(csrf_token) data is nil."); } Alamofire.request(self.endpoint + self.login, method: .post, parameters: parameters).responseJSON { response in switch response.result { case .success: Alamofire.request(self.endpoint + self.list, method: .get).responseJSON { response in switch response.result { case .success(let value): if let resData = JSON(value)["files"].arrayObject { completionHandler(resData as! [[String:AnyObject]], nil) } break case .failure: completionHandler([[String:AnyObject]](), self.getErrorMessage(response)) break } } break case .failure: completionHandler([[String:AnyObject]](), self.getErrorMessage(response)) break } } case .failure: completionHandler([[String:AnyObject]](), self.getErrorMessage(response)) break } } } func getErrorMessage(_ response: Alamofire.DataResponse<Any>) -> String { let message : String if let httpStatusCode = response.response?.statusCode { switch(httpStatusCode) { case 400: message = "Nutzername oder Passwort nicht vorhanden." case 401: message = "Der eingegebene Nutzername und/oder das Passwort ist nicht gültig." case 404: message = "Der gewünschte Service steht zur Zeit nicht zur Verfügung." case 500: message = "Der Service arbeitet fehlerhaft, bitte kontaktieren Sie einen DZB-Mitarbieter." case 503: message = "Der Service ist nicht verfügbar, bitte kontaktieren Sie einen DZB-Mitarbieter." default: message = "Status Code: " + String(httpStatusCode); } } else { message = response.result.error!.localizedDescription; } // print("error: " + message); return message; } }
mit
24dbea54285cfc0f922e7c50bb724c55
40.312
132
0.524593
5.481953
false
false
false
false
apple/swift-experimental-string-processing
Sources/_StringProcessing/Engine/Consume.swift
1
1521
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// var checkComments = true extension Engine { func makeProcessor( input: String, bounds: Range<String.Index>, matchMode: MatchMode ) -> Processor { Processor( program: program, input: input, subjectBounds: bounds, searchBounds: bounds, matchMode: matchMode, isTracingEnabled: enableTracing, shouldMeasureMetrics: enableMetrics) } func makeFirstMatchProcessor( input: String, subjectBounds: Range<String.Index>, searchBounds: Range<String.Index> ) -> Processor { Processor( program: program, input: input, subjectBounds: subjectBounds, searchBounds: searchBounds, matchMode: .partialFromFront, isTracingEnabled: enableTracing, shouldMeasureMetrics: enableMetrics) } } extension Processor { // TODO: Should we throw here? mutating func consume() -> Input.Index? { while true { switch self.state { case .accept: return self.currentPosition case .fail: return nil case .inProgress: self.cycle() } } } }
apache-2.0
8ae4c08cb800d216d13cbb961abc383d
25.224138
80
0.596318
4.798107
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/View Models/GameViewModel.swift
1
2366
// // GameViewModel.swift // ScoreReporter // // Created by Bradley Smith on 9/25/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import UIKit public enum GameViewState { case full case normal case minimal } public struct GameViewModel { public let game: Game? public let startDate: String? public let homeTeamName: NSAttributedString public let homeTeamScore: NSAttributedString? public let awayTeamName: NSAttributedString public let awayTeamScore: NSAttributedString? public let fieldName: String public let status: String? public let state: GameViewState fileprivate let winnerAttributes = [ NSFontAttributeName: UIFont.systemFont(ofSize: 16.0, weight: UIFontWeightBlack) ] fileprivate let loserAttributes = [ NSFontAttributeName: UIFont.systemFont(ofSize: 16.0, weight: UIFontWeightThin) ] public init(game: Game?, state: GameViewState = .normal ) { self.game = game let dateFormatter = DateService.gameStartDateFullFormatter startDate = game?.startDateFull.flatMap { dateFormatter.string(from: $0) } var homeAttributes = loserAttributes var awayAttributes = loserAttributes let homeScore = game?.homeTeamScore ?? "" let awayScore = game?.awayTeamScore ?? "" if let status = game?.status, status == "Final" { let score1 = Int(homeScore) ?? 0 let score2 = Int(awayScore) ?? 0 if score1 > score2 { homeAttributes = winnerAttributes awayAttributes = loserAttributes } else { homeAttributes = loserAttributes awayAttributes = winnerAttributes } } let homeName = game?.homeTeamName ?? "TBD" homeTeamName = NSAttributedString(string: homeName, attributes: homeAttributes) homeTeamScore = NSAttributedString(string: homeScore, attributes: homeAttributes) let awayName = game?.awayTeamName ?? "TBD" awayTeamName = NSAttributedString(string: awayName, attributes: awayAttributes) awayTeamScore = NSAttributedString(string: awayScore, attributes: awayAttributes) fieldName = game?.fieldName ?? "TBD" status = game?.status self.state = state } }
mit
982e737d9c6eafdce0e68b3fa15cf3ea
30.118421
89
0.657082
5.06424
false
false
false
false
kenshin03/Cherry
Cherry/Shared/Utils/KTActivityManager.swift
5
8784
// // KTActivityManager.swift // Cherry // // Created by Kenny Tang on 2/22/15. // // import UIKit protocol KTActivityManagerDelegate { func activityManager(manager:KTActivityManager?, activityDidUpdate model:KTPomodoroActivityModel?) func activityManager(manager:KTActivityManager?, activityDidPauseForBreak elapsedBreakTime:Int) } class KTActivityManager { // MARK: - Properties var activity:KTPomodoroActivityModel? var activityTimer:NSTimer? var breakTimer:NSTimer? var currentPomo:Int? var breakElapsed:Int? var delegate:KTActivityManagerDelegate? // MARK: - Public class var sharedInstance: KTActivityManager { struct Static { static let instance: KTActivityManager = KTActivityManager() } return Static.instance } func startActivity(activity:KTPomodoroActivityModel, error:NSErrorPointer) { if (self.hasOtherActiveActivityInSharedState(activity.activityID)) { error.memory = NSError(domain:"com.corgitoergosum.net", code: Constants.KTPomodoroStartActivityError.OtherActivityActive.rawValue, userInfo: nil) return } // initialize internal variables self.intializeInternalState(activity) // start timer self.startActivityTimer() } func continueActivity(activity:KTPomodoroActivityModel) { self.activity = activity self.currentPomo = activity.current_pomo.integerValue self.updateSharedActiveActivityStateFromModel(activity) self.startActivityTimer() } func stopActivity() { self.activity?.status = Constants.KTPomodoroActivityStatus.Stopped.rawValue if let activity = self.activity { self.updateSharedActiveActivityStateFromModel(activity) } // save to disk KTCoreDataStack.sharedInstance.saveContext() self.resetManagerInternalState() } // MARK: - Private // MARK: startActivity: helper methods func resetManagerInternalState() { self.activity = nil self.currentPomo = 0 self.breakElapsed = 0 self.invalidateTimers() } func startActivityTimer () { self.invalidateTimers() self.activityTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("activityTimerFired"), userInfo: nil, repeats: true) self.scheduleTimerInRunLoop(self.activityTimer!) } func intializeInternalState(activity:KTPomodoroActivityModel) { self.currentPomo = 1; self.breakElapsed = 0; activity.current_pomo = 0; activity.current_pomo_elapsed_time = 0 activity.status = Constants.KTPomodoroActivityStatus.InProgress.rawValue; self.activity = activity; self.updateSharedActiveActivityStateFromModel(activity) } func hasOtherActiveActivityInSharedState(ID:String) -> Bool { if let activity = self.activeActivityInSharedStorage() as KTActiveActivityState? { return activity.activityID != ID } return false } func activeActivityInSharedStorage() -> KTActiveActivityState? { if let activityData = KTSharedUserDefaults.sharedUserDefaults.objectForKey("ActiveActivity") as? NSData { if let activity = NSKeyedUnarchiver.unarchiveObjectWithData(activityData) as? KTActiveActivityState{ return activity } } return nil } func updateSharedActiveActivityStateFromModel(activeActivity:KTPomodoroActivityModel) { var updatedActiveActivity:KTActiveActivityState if let sharedActivity = self.activeActivityInSharedStorage(){ if (sharedActivity.activityID == activeActivity.activityID) { // update existing object updatedActiveActivity = sharedActivity updatedActiveActivity.currentPomo = activeActivity.current_pomo.integerValue updatedActiveActivity.status = activeActivity.status.integerValue updatedActiveActivity.elapsedSecs = activeActivity.current_pomo_elapsed_time.integerValue } else { updatedActiveActivity = self.createActiveActivityFromModel(activeActivity) } } else { //creaate new object the first time updatedActiveActivity = self.createActiveActivityFromModel(activeActivity) } if (updatedActiveActivity.status == Constants.KTPomodoroActivityStatus.Stopped.rawValue) { KTSharedUserDefaults.sharedUserDefaults.removeObjectForKey("ActiveActivity") } else { let encodedActivity:NSData = NSKeyedArchiver.archivedDataWithRootObject(updatedActiveActivity); KTSharedUserDefaults.sharedUserDefaults.setObject(encodedActivity, forKey: "ActiveActivity") } KTSharedUserDefaults.sharedUserDefaults.synchronize() } func createActiveActivityFromModel(activeActivity:KTPomodoroActivityModel) -> KTActiveActivityState { return KTActiveActivityState(id: activeActivity.activityID, name: activeActivity.name, status: activeActivity.status.integerValue, currentPomo: activeActivity.current_pomo.integerValue, elapsed: activeActivity.current_pomo_elapsed_time.integerValue) } func invalidateTimers() { self.activityTimer?.invalidate() self.breakTimer?.invalidate() } func scheduleTimerInRunLoop(timer:NSTimer) { NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode) } // MARK - timers helper methods @objc func activityTimerFired() { // increment current pomo elapsed time self.activity?.current_pomo = self.currentPomo!; var currentPomoElapsed = 0 if let elapsed = self.activity?.current_pomo_elapsed_time.integerValue { currentPomoElapsed = elapsed + 1 self.activity?.current_pomo_elapsed_time = currentPomoElapsed } self.delegate?.activityManager(self, activityDidUpdate: self.activity) if let activity = self.activity { self.updateSharedActiveActivityStateFromModel(activity) } if (currentPomoElapsed == KTSharedUserDefaults.pomoDuration*60) { // reached end of pomo self.handlePomoEnded() } } // Swift Gotchas @objc func breakTimerFired() { self.breakElapsed!++ if (self.breakElapsed < KTSharedUserDefaults.breakDuration*60) { self.delegate?.activityManager(self, activityDidPauseForBreak: self.breakElapsed!) } else { self.invalidateTimers() self.breakElapsed = 0 self.startNextPomo() } } // MARK: breakTimerFired: helper methods func startNextPomo() { println("starting next pomo") self.activity?.current_pomo = self.currentPomo!; self.activity?.current_pomo_elapsed_time = 0; // restart the timer self.activityTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("activityTimerFired"), userInfo: nil, repeats: true) self.scheduleTimerInRunLoop(self.activityTimer!) } // MARK: activityTimerFired: helper methods func handlePomoEnded() { if (self.activityHasMorePomo(self.activity)) { self.currentPomo!++ self.activity?.current_pomo = self.currentPomo! self.pauseActivityStartBreak() } else { self.completeActivityOnLastPomo() } } // MARK: handlePomoEnded helper methods func completeActivityOnLastPomo() { self.activity?.status = Constants.KTPomodoroActivityStatus.Completed.rawValue self.activity?.actual_pomo = self.currentPomo! // save to disk KTCoreDataStack.sharedInstance.saveContext() self.delegate?.activityManager(self, activityDidUpdate: self.activity) self.resetManagerInternalState() } func pauseActivityStartBreak() { self.activityTimer?.invalidate() self.startBreakTimer() } func startBreakTimer() { println("starting break") self.breakTimer?.invalidate() self.breakTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("breakTimerFired"), userInfo: nil, repeats: true) self.scheduleTimerInRunLoop(self.breakTimer!) } func activityHasMorePomo(activity:KTPomodoroActivityModel?) -> Bool{ if let activity = activity { let expectedPomo = activity.expected_pomo.integerValue if let currentPomo = self.currentPomo { return expectedPomo > currentPomo } } return false } }
mit
89bdb51480dff1825e64fb2bfdc0ddd7
32.022556
139
0.672587
5.369193
false
false
false
false
apple/swift-package-manager
Sources/PackageModel/Snippets/Model/Snippet.swift
2
1197
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TSCBasic public struct Snippet { public var path: AbsolutePath public var explanation: String public var presentationCode: String public var groupName: String? = nil public var name: String { path.basenameWithoutExt } init(parsing source: String, path: AbsolutePath) { let extractor = PlainTextSnippetExtractor(source: source) self.path = path self.explanation = extractor.explanation self.presentationCode = extractor.presentationCode } public init(parsing file: AbsolutePath) throws { let source = try String(contentsOf: file.asURL) self.init(parsing: source, path: file) } }
apache-2.0
eab70f3493f0c086472b5e980a024f25
32.25
80
0.609023
5.115385
false
false
false
false
balthild/Mathemalpha
Mathemalpha/SchemesView.swift
1
1120
// // TypesView.swift // Mathemalpha // // Created by Balthild Ires on 18/09/2017. // Copyright © 2017 Balthild Ires. All rights reserved. // import Cocoa class SchemesView: NSView { var selected = 0 override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) var y: CGFloat = 0 for (i, type) in Schemes.schemeNames.enumerated() { let rect = NSMakeRect(0, y, 140, 24) let marginTop = (24 - type.size(withAttributes: Styles.schemesTextAttributes).height) / 2 let textRect = NSMakeRect(10, y + marginTop, 120, 24 - marginTop) if i == selected { let path = NSBezierPath(roundedRect: rect, xRadius: 4, yRadius: 4) Styles.schemesTileColor.set() path.fill() type.draw(in: textRect, withAttributes: Styles.schemesSelectedTextAttributes) } else { type.draw(in: textRect, withAttributes: Styles.schemesTextAttributes) } y += 24 } } override var isFlipped: Bool { return true } }
gpl-3.0
96a93f9903a48c53edb4b8a8843f86ee
23.866667
101
0.575514
4.238636
false
false
false
false
apple/swift-async-algorithms
Sources/AsyncAlgorithms/AsyncChannel.swift
1
8882
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @preconcurrency @_implementationOnly import OrderedCollections /// A channel for sending elements from one task to another with back pressure. /// /// The `AsyncChannel` class is intended to be used as a communication type between tasks, /// particularly when one task produces values and another task consumes those values. The back /// pressure applied by `send(_:)` via the suspension/resume ensures that /// the production of values does not exceed the consumption of values from iteration. This method /// suspends after enqueuing the event and is resumed when the next call to `next()` /// on the `Iterator` is made, or when `finish()` is called from another Task. /// As `finish()` induces a terminal state, there is no need for a back pressure management. /// This function does not suspend and will finish all the pending iterations. public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable { /// The iterator for a `AsyncChannel` instance. public struct Iterator: AsyncIteratorProtocol, Sendable { let channel: AsyncChannel<Element> var active: Bool = true init(_ channel: AsyncChannel<Element>) { self.channel = channel } /// Await the next sent element or finish. public mutating func next() async -> Element? { guard active else { return nil } let generation = channel.establish() let nextTokenStatus = ManagedCriticalState<ChannelTokenStatus>(.new) let value = await withTaskCancellationHandler { await channel.next(nextTokenStatus, generation) } onCancel: { [channel] in channel.cancelNext(nextTokenStatus, generation) } if let value { return value } else { active = false return nil } } } typealias Pending = ChannelToken<UnsafeContinuation<UnsafeContinuation<Element?, Never>?, Never>> typealias Awaiting = ChannelToken<UnsafeContinuation<Element?, Never>> struct ChannelToken<Continuation: Sendable>: Hashable, Sendable { var generation: Int var continuation: Continuation? init(generation: Int, continuation: Continuation) { self.generation = generation self.continuation = continuation } init(placeholder generation: Int) { self.generation = generation self.continuation = nil } func hash(into hasher: inout Hasher) { hasher.combine(generation) } static func == (_ lhs: ChannelToken, _ rhs: ChannelToken) -> Bool { return lhs.generation == rhs.generation } } enum ChannelTokenStatus: Equatable { case new case cancelled } enum Emission : Sendable { case idle case pending(OrderedSet<Pending>) case awaiting(OrderedSet<Awaiting>) case finished } struct State : Sendable { var emission: Emission = .idle var generation = 0 } let state = ManagedCriticalState(State()) /// Create a new `AsyncChannel` given an element type. public init(element elementType: Element.Type = Element.self) { } func establish() -> Int { state.withCriticalRegion { state in defer { state.generation &+= 1 } return state.generation } } func cancelNext(_ nextTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int) { state.withCriticalRegion { state in let continuation: UnsafeContinuation<Element?, Never>? switch state.emission { case .awaiting(var nexts): continuation = nexts.remove(Awaiting(placeholder: generation))?.continuation if nexts.isEmpty { state.emission = .idle } else { state.emission = .awaiting(nexts) } default: continuation = nil } nextTokenStatus.withCriticalRegion { status in if status == .new { status = .cancelled } } continuation?.resume(returning: nil) } } func next(_ nextTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int) async -> Element? { return await withUnsafeContinuation { (continuation: UnsafeContinuation<Element?, Never>) in var cancelled = false var terminal = false state.withCriticalRegion { state in if nextTokenStatus.withCriticalRegion({ $0 }) == .cancelled { cancelled = true } switch state.emission { case .idle: state.emission = .awaiting([Awaiting(generation: generation, continuation: continuation)]) case .pending(var sends): let send = sends.removeFirst() if sends.count == 0 { state.emission = .idle } else { state.emission = .pending(sends) } send.continuation?.resume(returning: continuation) case .awaiting(var nexts): nexts.updateOrAppend(Awaiting(generation: generation, continuation: continuation)) state.emission = .awaiting(nexts) case .finished: terminal = true } } if cancelled || terminal { continuation.resume(returning: nil) } } } func cancelSend(_ sendTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int) { state.withCriticalRegion { state in let continuation: UnsafeContinuation<UnsafeContinuation<Element?, Never>?, Never>? switch state.emission { case .pending(var sends): let send = sends.remove(Pending(placeholder: generation)) if sends.isEmpty { state.emission = .idle } else { state.emission = .pending(sends) } continuation = send?.continuation default: continuation = nil } sendTokenStatus.withCriticalRegion { status in if status == .new { status = .cancelled } } continuation?.resume(returning: nil) } } func send(_ sendTokenStatus: ManagedCriticalState<ChannelTokenStatus>, _ generation: Int, _ element: Element) async { let continuation: UnsafeContinuation<Element?, Never>? = await withUnsafeContinuation { continuation in state.withCriticalRegion { state in if sendTokenStatus.withCriticalRegion({ $0 }) == .cancelled { continuation.resume(returning: nil) return } switch state.emission { case .idle: state.emission = .pending([Pending(generation: generation, continuation: continuation)]) case .pending(var sends): sends.updateOrAppend(Pending(generation: generation, continuation: continuation)) state.emission = .pending(sends) case .awaiting(var nexts): let next = nexts.removeFirst().continuation if nexts.count == 0 { state.emission = .idle } else { state.emission = .awaiting(nexts) } continuation.resume(returning: next) case .finished: continuation.resume(returning: nil) } } } continuation?.resume(returning: element) } /// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made /// or when a call to `finish()` is made from another Task. /// If the channel is already finished then this returns immediately /// If the task is cancelled, this function will resume. Other sending operations from other tasks will remain active. public func send(_ element: Element) async { let generation = establish() let sendTokenStatus = ManagedCriticalState<ChannelTokenStatus>(.new) await withTaskCancellationHandler { await send(sendTokenStatus, generation, element) } onCancel: { [weak self] in self?.cancelSend(sendTokenStatus, generation) } } /// Send a finish to all awaiting iterations. /// All subsequent calls to `next(_:)` will resume immediately. public func finish() { state.withCriticalRegion { state in defer { state.emission = .finished } switch state.emission { case .pending(let sends): for send in sends { send.continuation?.resume(returning: nil) } case .awaiting(let nexts): for next in nexts { next.continuation?.resume(returning: nil) } default: break } } } /// Create an `Iterator` for iteration of an `AsyncChannel` public func makeAsyncIterator() -> Iterator { return Iterator(self) } }
apache-2.0
22cd6fc50d44239a67eaa5184c038bb5
31.298182
120
0.640059
5.07833
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/Scenes/Controller/SetPayPwdVC.swift
1
7655
// // SetPayPwdVC.swift // YStar // // Created by MONSTER on 2017/7/18. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class SetPayPwdVC: BaseTableViewController,UITextFieldDelegate { var setPass = false var showKeyBoard : Bool = false var passString : String = "" // 下一步按钮 @IBOutlet weak var doSetPwdButton: UIButton! fileprivate var pwdCircleArr = [UILabel]() fileprivate var textField:UITextField! // MARK: - 初始化 override func viewDidLoad() { super.viewDidLoad() initUI() setupUI() } func initUI() { doSetPwdButton.setTitle(setPass == false ? "下一步" :"确定", for: .normal) self.title = setPass == true ? "请确认交易密码" : "设置交易密码" self.doSetPwdButton.backgroundColor = UIColor.gray } func setupUI() { textField = UITextField(frame: CGRect(x: 0,y: 60, width: view.frame.size.width, height: 35)) textField.delegate = self textField.isHidden = true textField.keyboardType = UIKeyboardType.numberPad view.addSubview(textField!) textField.backgroundColor = UIColor.red textField.becomeFirstResponder() for i in 0 ..< 6 { let line:UIView = UIView(frame: CGRect(x: 30 + CGFloat(i) * 10 + (( kScreenWidth - 110) / 6.0) * CGFloat(i), y: 120, width: ((kScreenWidth - 110) / 6.0) , height: ((kScreenWidth - 110) / 6.0))) line.backgroundColor = UIColor.clear line.alpha = 1 line.layer.borderWidth = 1 line.layer.cornerRadius = 3 line.layer.borderColor = UIColor.gray.cgColor view.addSubview(line) let circleLabel:UILabel = UILabel(frame: CGRect(x: 0 , y: 0 , width: ((kScreenWidth - 110) / 6.0), height: ((kScreenWidth - 110) / 6.0))) circleLabel.textAlignment = .center circleLabel.text = "﹡" circleLabel.font = UIFont.systemFont(ofSize: 17) circleLabel.layer.masksToBounds = true circleLabel.isHidden = true pwdCircleArr.append(circleLabel) line.addSubview(circleLabel) } let btn = UIButton.init(type: .custom) btn.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 150) btn.addTarget(self, action: #selector(showKeyBordButtonAction(_:)), for: .touchUpInside) view.addSubview(btn) } // MARK: - 显示键盘 @IBAction func showKeyBordButtonAction(_ sender: UIButton) { if showKeyBoard == true { textField.resignFirstResponder() } else { textField.becomeFirstResponder() } showKeyBoard = !showKeyBoard } // MARK: - 下一步按钮 @IBAction func doSetPwdButtonAction(_ sender: UIButton) { let phoneNum = UserDefaults.standard.value(forKey: AppConst.UserDefaultKey.phone.rawValue) as! String // 请求接口设置交易密码 if setPass == true { if passString.length() == 6 { if ShareModelHelper.instance().setPayPwd["passString"] != passString { SVProgressHUD.showErrorMessage(ErrorMessage: "两次密码输入不一致", ForDuration: 2.0, completion: {}) return } } let model = ResetPayPwdRequestModel() model.phone = phoneNum model.pwd = passString.md5() model.timestamp = 1 model.type = 0 AppAPIHelper.commen().ResetPayPwd(requestModel: model, complete: { (response) -> ()? in if let objects = response as? ResultModel { if objects.result == 0 { SVProgressHUD.showSuccessMessage(SuccessMessage: "设置成功", ForDuration: 2.0, completion: { let vcCount = self.navigationController?.viewControllers.count _ = self.navigationController?.popToViewController((self.navigationController?.viewControllers[vcCount! - 3])!, animated: true) }) } } else { SVProgressHUD.showErrorMessage(ErrorMessage: "设置失败", ForDuration: 2.0, completion: nil) } return nil }, error: { (error) -> ()? in self.didRequestError(error) return nil }) } else { if passString.length() == 6 { let setPayPwdVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "SetPayPwdVC") as! SetPayPwdVC setPayPwdVC.setPass = true ShareModelHelper.instance().setPayPwd["passString"] = passString self.navigationController?.pushViewController(setPayPwdVC, animated: true) } else { SVProgressHUD.showErrorMessage(ErrorMessage: "密码需要6位", ForDuration: 2.0, completion: {}) } } } // MARK: - 输入变成点 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if(textField.text?.characters.count > 5 && string.characters.count > 0) { return false } var password : String if string.characters.count <= 0 && textField.text?.length() != 0 { let index = textField.text?.characters.index((textField.text?.endIndex)!, offsetBy: -1) password = textField.text!.substring(to: index!) } else { password = textField.text! + string } passString = "" self.doSetPwdButton.backgroundColor = UIColor.gray self.setCircleShow(password.characters.count) if(password.characters.count == 6) { passString = password self.doSetPwdButton.backgroundColor = UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue) } return true; } func setCircleShow(_ count:NSInteger) { for circle in pwdCircleArr { let supView = circle.superview supView?.layer.borderColor = UIColor.gray.cgColor supView?.layer.borderWidth = 1 circle.isHidden = true; } for i in 0 ..< count { pwdCircleArr[i].isHidden = false let view = pwdCircleArr[i] let supView = view.superview supView?.layer.borderColor = UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue).cgColor supView?.layer.borderWidth = 2 } } }
mit
46c59129b1bfe9019e4efddceda3c568
34.239437
155
0.534772
4.961005
false
false
false
false
kz56cd/ios_sandbox_animate
IosSandboxAnimate/CustomParts/BottomShadowButton.swift
1
776
// // BottomShadowButton.swift // e-park // // Created by KaiKeima on 2015/12/22. // Copyright © 2015年 OHAKO,inc. All rights reserved. // import UIKit @IBDesignable class BottomShadowButton: UIButton { override func drawRect(rect: CGRect) { self.layer.backgroundColor = self.backgroundColor?.CGColor self.backgroundColor = UIColor.clearColor() self.layer.cornerRadius = 4.0 self.layer.shadowColor = self.backgroundColor!.transitionColor(nextColor: UIColor.blackColor(), portion: 0.5).CGColor self.layer.shadowOpacity = 1.0 self.layer.shadowRadius = 0.0 self.layer.shadowOffset = CGSizeMake(0, 2.0) // self.clipsToBounds = true // super.drawRect(rect) } }
mit
b73c569f210d8366ffbb5b4b08033ddc
25.655172
125
0.649418
4.005181
false
false
false
false
tad-iizuka/swift-sdk
Source/RetrieveAndRankV1/Models/SearchResponse.swift
3
3712
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** The response received when searching a specific query within the Solr cluster and collection. */ public struct SearchResponse: JSONDecodable { /// A header containing information about the request and response. public let header: SearchResponseHeader /// An object containing the results of the Search request. public let body: SearchResponseBody /// Used internally to initialize a `SearchResponse` model from JSON. public init(json: JSON) throws { header = try json.decode(at: "responseHeader", type: SearchResponseHeader.self) body = try json.decode(at: "response", type: SearchResponseBody.self) } } /** An object returned with a Search request, returning more information about the request. */ public struct SearchResponseHeader: JSONDecodable { /// The status. public let status: Int /// The query time. public let qTime: Int /// An object containing the parameters that were sent in the request. public let params: RequestParameters /// Used internally to initialize a `SearchResponseHeader` model from JSON. public init(json: JSON) throws { status = try json.getInt(at: "status") qTime = try json.getInt(at: "QTime") params = try json.decode(at: "params", type: RequestParameters.self) } } /** An object containing the query parameters that were sent in the original request. */ public struct RequestParameters: JSONDecodable { /// The original query string. public let query: String /// The return fields the user specified. public let returnFields: String /// The writer type. public let writerType: String /// Used internally to initialize a `RequestParameters` model from JSON. public init(json: JSON) throws { query = try json.getString(at: "q") returnFields = try json.getString(at: "fl") writerType = try json.getString(at: "wt") } } /** A named alias for the document results returned by a search function. */ public typealias Document = NSDictionary /** Contains the results of the Search request. */ public struct SearchResponseBody: JSONDecodable { /// The number of results found. public let numFound: Int /// The index the given results start from. public let start: Int /// A list of possible answers whose structure depends on the list of fields the user /// requested to be returned. public let documents: [Document] /// Used internally to initialize a `SearchResponseBody` model from JSON. public init(json: JSON) throws { numFound = try json.getInt(at: "numFound") start = try json.getInt(at: "start") var docs = [Document]() let docsJSON = try json.getArray(at: "docs") for docJSON in docsJSON { let doc = try JSONSerialization.jsonObject(with: docJSON.serialize(), options: JSONSerialization.ReadingOptions.allowFragments) as! Document docs.append(doc) } documents = docs } }
apache-2.0
8ce291fc11baec3e99d644d92d7f90a2
34.352381
152
0.684267
4.651629
false
false
false
false
imitationgame/pokemonpassport
pokepass/View/Create/VCreateFinder.swift
1
5961
import UIKit class VCreateFinder:UIView, UITextFieldDelegate { weak var controller:CCreate! weak var field:UITextField! convenience init(controller:CCreate) { self.init() self.controller = controller clipsToBounds = true backgroundColor = UIColor.white translatesAutoresizingMaskIntoConstraints = false let image:UIImageView = UIImageView() image.image = UIImage(named:"search") image.isUserInteractionEnabled = false image.translatesAutoresizingMaskIntoConstraints = false image.clipsToBounds = true image.contentMode = UIViewContentMode.center let border:UIView = UIView() border.backgroundColor = UIColor.main border.isUserInteractionEnabled = false border.translatesAutoresizingMaskIntoConstraints = false border.clipsToBounds = true let button:UIButton = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.addTarget( self, action:#selector(self.actionButton(sender:)), for:UIControlEvents.touchUpInside) let buttonSearch:UIButton = UIButton() buttonSearch.translatesAutoresizingMaskIntoConstraints = false buttonSearch.titleLabel?.font = UIFont.bold(size:13) buttonSearch.setTitleColor(UIColor.main, for:UIControlState()) buttonSearch.setTitleColor(UIColor.main.withAlphaComponent(0.2), for:UIControlState.highlighted) buttonSearch.setTitle(NSLocalizedString("VCreateFinder_searchButton", comment:""), for:UIControlState()) buttonSearch.addTarget( self, action:#selector(self.actionSearch(sender:)), for:UIControlEvents.touchUpInside) let field:UITextField = UITextField() field.keyboardType = UIKeyboardType.alphabet field.translatesAutoresizingMaskIntoConstraints = false field.clipsToBounds = true field.backgroundColor = UIColor.clear field.borderStyle = UITextBorderStyle.none field.font = UIFont.medium(size:17) field.textColor = UIColor.black field.tintColor = UIColor.black field.returnKeyType = UIReturnKeyType.search field.keyboardAppearance = UIKeyboardAppearance.light field.autocorrectionType = UITextAutocorrectionType.no field.spellCheckingType = UITextSpellCheckingType.no field.autocapitalizationType = UITextAutocapitalizationType.words field.clearButtonMode = UITextFieldViewMode.never field.placeholder = NSLocalizedString("VCreateFinder_fieldPlaceholder", comment:"") field.delegate = self field.clearsOnBeginEditing = true self.field = field addSubview(border) addSubview(image) addSubview(button) addSubview(field) addSubview(buttonSearch) let views:[String:UIView] = [ "border":border, "image":image, "button":button, "buttonSearch":buttonSearch, "field":field] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[border]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[button]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:[buttonSearch(70)]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-30-[field(200)]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-5-[image(20)]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[border(1)]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[image]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[button]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[field]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[buttonSearch]-0-|", options:[], metrics:metrics, views:views)) } //MARK: actions func actionButton(sender button:UIButton) { field.becomeFirstResponder() } func actionSearch(sender button:UIButton) { field.resignFirstResponder() performSearch() } //MARK: private private func performSearch() { let text:String = field.text! DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.controller.viewCreate.map.searchLocation(query:text) } } //MARK: field delegate func textFieldDidBeginEditing(_ textField:UITextField) { controller.viewCreate.map.deselectAll() } func textFieldShouldReturn(_ textField:UITextField) -> Bool { textField.resignFirstResponder() performSearch() return true } }
mit
3d88e50f75b4f4e6516648412b1919db
33.258621
112
0.612984
5.961
false
false
false
false
FuckBoilerplate/RxCache
iOS/Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift
140
3116
import Foundation #if _runtime(_ObjC) public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) -> Bool public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool public class NMBObjCMatcher : NSObject, NMBMatcher { let _match: MatcherBlock let _doesNotMatch: MatcherBlock let canMatchNil: Bool public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) { self.canMatchNil = canMatchNil self._match = matcher self._doesNotMatch = notMatcher } public convenience init(matcher: @escaping MatcherBlock) { self.init(canMatchNil: true, matcher: matcher) } public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) { self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in return !matcher(actualExpression, failureMessage) })) } public convenience init(matcher: @escaping FullMatcherBlock) { self.init(canMatchNil: true, matcher: matcher) } public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) { self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in return matcher(actualExpression, failureMessage, false) }), notMatcher: ({ actualExpression, failureMessage in return matcher(actualExpression, failureMessage, true) })) } private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { do { if !canMatchNil { if try actualExpression.evaluate() == nil { failureMessage.postfixActual = " (use beNil() to match nils)" return false } } } catch let error { failureMessage.actualValue = "an unexpected error thrown: \(error)" return false } return true } public func matches(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let expr = Expression(expression: actualBlock, location: location) let result = _match( expr, failureMessage) if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) { return result } else { return false } } public func doesNotMatch(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let expr = Expression(expression: actualBlock, location: location) let result = _doesNotMatch( expr, failureMessage) if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) { return result } else { return false } } } #endif
mit
0c601a117d5d85b29494791a6d9e0b60
37.469136
144
0.650513
5.554367
false
false
false
false
Groupr-Purdue/Groupr-Backend
Sources/Library/Models/Course.swift
1
2373
import Vapor import Fluent import HTTP public final class Course: Model { public var id: Node? public var exists: Bool = false /// The course's name (i.e. 'CS 408'). public var name: String /// The course's title (i.e. 'Software Testing'). public var title: String /// The course's current enrollment (i.e. 40 students). public var enrollment: Int /// The designated initializer. public init(name: String, title: String, enrollment: Int) { self.id = nil self.name = name self.title = title self.enrollment = enrollment } /// Internal: Fluent::Model::init(Node, Context). public init(node: Node, in context: Context) throws { self.id = try? node.extract("id") self.name = try node.extract("name") self.title = try node.extract("title") self.enrollment = try node.extract("enrollment") } /// Internal: Fluent::Model::makeNode(Context). public func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "name": name, "title": title, "enrollment": enrollment ]) } /// Establish a many-to-many relationship with User. public func users() throws -> Siblings<User> { return try siblings() } /// Establish parent-children relation with Group public func groups() throws -> Children<Group> { return try children() } } extension Course: Preparation { /// Create the Course schema when required in the database. public static func prepare(_ database: Database) throws { try database.create("courses", closure: { (courses) in courses.id() courses.string("name", length: nil, optional: false, unique: true, default: nil) courses.string("title", length: nil, optional: true, unique: false, default: nil) courses.int("enrollment", optional: true) }) } /// Delete/revert the Course schema when required in the database. public static func revert(_ database: Database) throws { try database.delete("courses") } } public extension Request { public func course() throws -> Course { guard let json = self.json else { throw Abort.badRequest } return try Course(node: json) } }
mit
246fd976c4fb41fe8df728d5fde7aa6d
28.6625
93
0.605984
4.370166
false
false
false
false
urbn/URBNValidator
URBNValidator.playground/Pages/Object Validation.xcplaygroundpage/Contents.swift
1
1040
//: [Block Rules](@previous) /*: # Object Validation This is what it's all about. Here we're giving a map of keys to rules, and validating against them */ import Foundation import URBNValidator class Tester: Validateable { typealias V = AnyObject var requiredString: String? var children = [String]() func validationMap() -> [String : ValidatingValue<V>] { return [ "requiredString": ValidatingValue(value: self.requiredString, rules: URBNRequiredRule()), "children": ValidatingValue(value: self.children, rules: URBNMinLengthRule(minLength: 3)) ] } @objc func valueForKey(key: String) -> AnyObject? { let d: [String: AnyObject?] = [ "requiredString": self.requiredString, "children": self.children ] return d[key]! } } let obj = Tester() let validator = URBNValidator() do { try validator.validate(obj) } catch let err as NSError { print(err.underlyingErrors!.map({ $0.localizedDescription })) }
mit
61a6e4583a2ffe5ed58b5bb869877fe3
23.186047
101
0.639423
4.297521
false
false
false
false
mrchenhao/American-TV-Series-Calendar
American-tv-series-calendar/SettingTableViewController.swift
1
6565
// // SettingTableViewController.swift // American-tv-series-calendar // // Created by ChenHao on 10/27/15. // Copyright © 2015 HarriesChen. All rights reserved. // import UIKit import EventKitUI class SettingTableViewController: UITableViewController { var showStart: Bool = false var showEnd: Bool = false override func viewDidLoad() { super.viewDidLoad() self.title = "设置" self.tableView.tableFooterView = UIView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 2 && indexPath.section == 0 { let dateCell: SettingDatePickerCell = tableView.dequeueReusableCellWithIdentifier("datePickerCell", forIndexPath: indexPath) as! SettingDatePickerCell dateCell.delegate = self dateCell.dateType = .start dateCell.datePickerView.date = NSDate.getDateByString(SettingManager.startTime) dateCell.selectionStyle = .None return dateCell } if indexPath.row == 4 && indexPath.section == 0 { let dateCell: SettingDatePickerCell = tableView.dequeueReusableCellWithIdentifier("datePickerCell", forIndexPath: indexPath) as! SettingDatePickerCell dateCell.delegate = self dateCell.dateType = .end dateCell.datePickerView.date = NSDate.getDateByString(SettingManager.endTime) dateCell.selectionStyle = .None return dateCell } let cell = tableView.dequeueReusableCellWithIdentifier("settingBaseCell", forIndexPath: indexPath) cell.textLabel?.text = "" cell.detailTextLabel?.text = "" if indexPath.section == 0 { if indexPath.row == 0 { cell.textLabel?.text = "默认日历" let userdefault: NSUserDefaults = NSUserDefaults.standardUserDefaults() if (userdefault.valueForKey(Constant.defaultCalendar) != nil) { let calendar:EKCalendar = EKManager.sharedInstance.getCalendarByIdentifer(userdefault.valueForKey(Constant.defaultCalendar) as! String) cell.detailTextLabel?.text = calendar.title } else { cell.detailTextLabel?.text = EKManager.sharedInstance.getDefaultCalendar().title } } if indexPath.row == 1 { cell.textLabel?.text = "默认开始时间" cell.detailTextLabel?.text = SettingManager.startTime } if indexPath.row == 3 { cell.textLabel?.text = "默认结束时间" cell.detailTextLabel?.text = SettingManager.endTime } if indexPath.row == 5 { cell.textLabel?.text = "关于" } } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { if indexPath.row == 0 { let choose: EKCalendarChooser = EKCalendarChooser(selectionStyle: .Single, displayStyle: .WritableCalendarsOnly, entityType: .Event, eventStore: EKManager.sharedInstance.store) choose.showsDoneButton = true choose.delegate = self self.navigationController?.pushViewController(choose, animated: true) } if indexPath.row == 1 { showStart = !showStart showEnd = false self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0), NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: .Automatic) } if indexPath.row == 3 { showEnd = !showEnd showStart = false self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0), NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: .Automatic) } } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 2 { if showStart { return 216 } return 0 } if indexPath.row == 4 { if showEnd { return 216 } return 0 } return 44 } } extension SettingTableViewController: SettingDatePickerCellDelegate { func datePicker(datePicker: datePickerType, didChangeDate date: NSDate) { switch datePicker { case .start: let cell: UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))! cell.detailTextLabel?.text = date.getHourAndMin() SettingManager.startTime = date.getHourAndMin() case .end: let cell: UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))! cell.detailTextLabel?.text = date.getHourAndMin() SettingManager.endTime = date.getHourAndMin() } } } extension SettingTableViewController: EKCalendarChooserDelegate { func calendarChooserDidFinish(calendarChooser: EKCalendarChooser) { if calendarChooser.selectedCalendars.count > 0 { let userdefault: NSUserDefaults = NSUserDefaults.standardUserDefaults() userdefault.setValue(calendarChooser.selectedCalendars.first!.calendarIdentifier, forKey: Constant.defaultCalendar) userdefault.synchronize() let cell: UITableViewCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))! cell.detailTextLabel!.text = calendarChooser.selectedCalendars.first!.title calendarChooser.navigationController?.popViewControllerAnimated(true) } } } extension NSDate { func getHourAndMin() -> String { let calendar = NSCalendar.currentCalendar() let components:NSDateComponents = calendar.components([.Hour, .Minute], fromDate: self) return String(format: "%.2d:%.2d", arguments: [components.hour,components.minute]) } }
mit
77f4b28a2565f4763aad8e987c17f725
39.271605
192
0.631974
5.496209
false
false
false
false
airspeedswift/swift
test/SourceKit/CodeComplete/complete_checkdeps_avoid_check.swift
4
2606
import ClangFW import SwiftFW func foo() { /*HERE*/ } // Checks that, due to default check delay, a modification will be ignored and fast completion will still activate. // REQUIRES: shell // RUN: %empty-directory(%t/Frameworks) // RUN: %empty-directory(%t/MyProject) // RUN: COMPILER_ARGS=( \ // RUN: -target %target-triple \ // RUN: -module-name MyProject \ // RUN: -F %t/Frameworks \ // RUN: -I %t/MyProject \ // RUN: -import-objc-header %t/MyProject/Bridging.h \ // RUN: %t/MyProject/Library.swift \ // RUN: %s \ // RUN: ) // RUN: INPUT_DIR=%S/Inputs/checkdeps // RUN: DEPCHECK_INTERVAL=1 // RUN: SLEEP_TIME=2 // RUN: cp -R $INPUT_DIR/MyProject %t/ // RUN: cp -R $INPUT_DIR/ClangFW.framework %t/Frameworks/ // RUN: %empty-directory(%t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule) // RUN: %target-swift-frontend -emit-module -module-name SwiftFW -o %t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule/%target-swiftmodule-name $INPUT_DIR/SwiftFW_src/Funcs.swift // RUN: %sourcekitd-test \ // RUN: -req=global-config == \ // RUN: -shell -- echo "### Initial" == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \ // RUN: -shell -- echo '### Modify framework (c)' == \ // RUN: -shell -- sleep $SLEEP_TIME == \ // RUN: -shell -- cp -R $INPUT_DIR/ClangFW.framework_mod/* %t/Frameworks/ClangFW.framework/ == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \ // RUN: -req=global-config -completion-check-dependency-interval ${DEPCHECK_INTERVAL} == \ // RUN: -shell -- echo '### Checking dependencies' == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} \ // RUN: | %FileCheck %s // CHECK-LABEL: ### Initial // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK-NOT: key.reusingastcontext: 1 // CHECK-LABEL: ### Modify framework (c) // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK: key.reusingastcontext: 1 // CHECK-LABEL: ### Checking dependencies // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc_mod()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK-NOT: key.reusingastcontext: 1
apache-2.0
f497d179938569fba3d7df85e70dfdc0
33.746667
187
0.656178
3.139759
false
false
false
false
JuanjoArreola/AllCache
Sources/ImageCache/ImageResizer.swift
1
3133
// // ImageResizer.swift // ImageCache // // Created by JuanJo on 31/08/20. // import Foundation import AllCache #if os(OSX) import AppKit #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit #endif public enum ImageProcessError: Error { case resizeError } private let resizeFunctions: [DefaultImageResizer.ContentMode: (CGSize, CGSize) -> CGRect] = [ .scaleAspectFit: aspectFit, .scaleAspectFill: aspectFill, .center: center, .top: top, .bottom: bottom, .left: left, .right: right, .topLeft: topLeft, .topRight: topRight, .bottomLeft: bottomLeft, .bottomRight: bottomRight, ] public final class DefaultImageResizer: Processor<Image> { public enum ContentMode: Int { case scaleToFill, scaleAspectFit, scaleAspectFill case redraw case center, top, bottom, left, right case topLeft, topRight, bottomLeft, bottomRight } public var size: CGSize public var scale: CGFloat public var mode: ContentMode public init(size: CGSize, scale: CGFloat, mode: ContentMode) { self.size = size self.scale = scale self.mode = mode super.init(identifier: "\(size.width)x\(size.height),\(scale),\(mode.rawValue)") } public override func process(_ instance: Image) throws -> Image { var image = instance if shouldScale(image: image) { guard let scaledImage = self.scale(image: instance) else { throw ImageProcessError.resizeError } image = scaledImage } if let nextProcessor = next { return try nextProcessor.process(image) } return image } func shouldScale(image: Image) -> Bool { #if os(OSX) return image.size != size #elseif os(iOS) || os(tvOS) || os(watchOS) let scale = self.scale != 0.0 ? self.scale : UIScreen.main.scale return image.size != size || image.scale != scale #endif } #if os(iOS) || os(tvOS) || os(watchOS) public func scale(image: Image) -> Image? { UIGraphicsBeginImageContextWithOptions(size, false, scale) image.draw(in: drawRect(for: image)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } #else public func scale(image: Image) -> Image? { let scaledImage = Image(size: size) scaledImage.lockFocus() guard let context = NSGraphicsContext.current else { return nil } context.imageInterpolation = .high image.draw(in: drawRect(for: image), from: NSRect(origin: .zero, size: image.size), operation: .copy, fraction: 1) scaledImage.unlockFocus() return scaledImage } #endif public func drawRect(for image: Image) -> CGRect { if let method = resizeFunctions[mode] { return method(size, image.size) } return CGRect(origin: CGPoint.zero, size: size) } }
mit
aa41a83283bf0307d5db8aba1eb7222d
25.777778
122
0.602617
4.443972
false
false
false
false
trujillo138/MyExpenses
MyExpenses/MyExpenses/Services/ModelController.swift
1
1168
// // ModelController.swift // MyExpenses // // Created by Tomas Trujillo on 5/22/17. // Copyright © 2017 TOMApps. All rights reserved. // import Foundation class ModelController { //MARK: Properties var user: User private let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! private var expensesURL: URL { return documentsDirectoryURL.appendingPathComponent("Expenses").appendingPathExtension("plist") } //MARK: Model methods func save(_ user: User) { self.user = user saveData() } //MARK: Loading and Saving required init() { user = User() loadData() } private func loadData() { guard let expenseModelPlist = NSDictionary.init(contentsOf: expensesURL) as? [String: AnyObject] else { return } user = User(plist: expenseModelPlist) } private func saveData() { let expenseDictionary = user.plistRepresentation as NSDictionary expenseDictionary.write(to: expensesURL, atomically: true) } }
apache-2.0
3ee24d2ab044c093f8a00543e44f924c
22.34
117
0.61868
4.882845
false
false
false
false
aofan/ZKSwift
ZKSwift/ZKBaseTableViewController.swift
1
5707
// // ZKBaseTableViewController.swift // ZKSwift // // Created by lizhikai on 16/7/4. // Copyright © 2016年 ZK. All rights reserved. // import UIKit public class ZKBaseTableViewController: UITableViewController { /// 数据源 public var dataArray : Array<AnyObject>?; /// 是否分组 public var isGroup:Bool = false; /// 默认每页10条数据 public var pageSize = 10; /// 开始页 默认第一页开始的 public var startPageNum = 1; /// 当前页页码 public var pageNum = 1; /// 是否第一次进行网络请求 public var isFirstRequest = true; /// 是否有数据 public var isHaveData : Bool!{ get{ if self.dataArray?.count > 0 { return true; } return false; } } /** 请求数据 要求子类实现 */ public func loadListRequest(){} /** 请求更多数据 要求子类实现 */ public func loadMoreListRequest(){} /** 全部加载完成 */ public func loadAllFinish(){} /** 请求成功 */ public func loadRequestSuccess(){} /** 请求失败 */ public func loadRequestFail(){} override public func viewDidLoad() { super.viewDidLoad() self.pageNum = self.startPageNum; } // MARK: - tableView数据展示的处理 override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { //分组 if isGroup { //有数据 if (self.dataArray != nil) { return (self.dataArray?.count)!; } //无数据 return 0; } //不分组 return 1; } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //分组 if isGroup { //有数据 if (self.dataArray != nil) { return self.dataArray![section].count } //没数据 return 0; }else{//不分组 //没数据 if ((self.dataArray?.count) == nil) { return 0; } //有数据 return (self.dataArray?.count)!; } } override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let baseModel : ZKBaseModel? = self.indexPathForSource(indexPath); return self.indexPathWithSourceForCell(indexPath, baseModel: baseModel); } /** 根据数据模型和索引创建对应的cell - parameter indexPath: 索引 - parameter baseModel: 数据模型 - returns: cell */ private func indexPathWithSourceForCell( indexPath : NSIndexPath, baseModel : ZKBaseModel?) -> ZKBaseTableViewCell{ var cell : ZKBaseTableViewCell?; let reuseIdentifier = String(baseModel!.cellClass!); //是否加载xib 处理展示的cell if baseModel?.isloadNib == true { let nib = UINib.init( nibName: reuseIdentifier, bundle:NSBundle.mainBundle()); tableView.registerNib( nib, forCellReuseIdentifier: reuseIdentifier ); cell = tableView.dequeueReusableCellWithIdentifier( reuseIdentifier, forIndexPath: indexPath ) as? ZKBaseTableViewCell; }else{ let type = baseModel!.cellClass as! ZKBaseTableViewCell.Type; //对于Cell复用的处理 cell = tableView.dequeueReusableCellWithIdentifier( reuseIdentifier ) as? ZKBaseTableViewCell; if cell == nil { cell = type.init( style:UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier ); } } cell!.source = baseModel; cell!.indexPath = indexPath; cell?.cellEventHandler = cellEventHandler; return cell!; } // MARK: - cell的点击事件处理 override public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.didSelectCell(self.indexPathForSource(indexPath)); } /** cell 的整体点击事件 子类要想响应点击事件必须掉用此方法 - parameter source: 数据模型 */ public func didSelectCell( source : ZKBaseModel ) { self.cellEventHandler(source); } /** cell 的事件处理 子类用到时候需要重写 - parameter source: 数据模型 - parameter cell: 发生事件的cell - parameter target: 区分同一个cell上的不同事件的标志 - parameter indexPath: 索引 */ public func cellEventHandler( source : ZKBaseModel, cell : ZKBaseTableViewCell? = nil, target : AnyObject? = nil, indexPath : NSIndexPath? = nil ){ } // MARK: - 根据cell获取数据模型 /** 获取cell对应的模型 - parameter indexPath: 索引 - returns: 数据模型 */ private func indexPathForSource( indexPath : NSIndexPath) -> ZKBaseModel{ var baseModel : ZKBaseModel?; //是否分组来处理数据源 if self.isGroup { baseModel = self.dataArray![indexPath.section][indexPath.row] as? ZKBaseModel; }else{ baseModel = self.dataArray![indexPath.row] as? ZKBaseModel; } return baseModel!; } }
mit
a2dd10c54c4419799443e3fa573f8058
24.174757
151
0.551485
5.129575
false
false
false
false
yichizhang/YZLibrary
YZLibraryDemo/Pods/Nimble/Sources/Nimble/Matchers/BeEmpty.swift
55
4255
import Foundation /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty<S: SequenceType>() -> NonNilMatcherFunc<S> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualSeq = try actualExpression.evaluate() if actualSeq == nil { return true } var generator = actualSeq!.generate() return generator.next() == nil } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<String> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualString = try actualExpression.evaluate() return actualString == nil || NSString(string: actualString!).length == 0 } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For NSString instances, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NSString> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualString = try actualExpression.evaluate() return actualString == nil || actualString!.length == 0 } } // Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray, // etc, since they conform to SequenceType as well as NMBCollection. /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NSDictionary> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualDictionary = try actualExpression.evaluate() return actualDictionary == nil || actualDictionary!.count == 0 } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NSArray> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualArray = try actualExpression.evaluate() return actualArray == nil || actualArray!.count == 0 } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NMBCollection> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actual = try actualExpression.evaluate() return actual == nil || actual!.count == 0 } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func beEmptyMatcher() -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() failureMessage.postfixMessage = "be empty" if let value = actualValue as? NMBCollection { let expr = Expression(expression: ({ value as NMBCollection }), location: location) return try! beEmpty().matches(expr, failureMessage: failureMessage) } else if let value = actualValue as? NSString { let expr = Expression(expression: ({ value as String }), location: location) return try! beEmpty().matches(expr, failureMessage: failureMessage) } else if let actualValue = actualValue { failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSDictionaries, NSHashTables, and NSStrings)" failureMessage.actualValue = "\(classAsString(actualValue.dynamicType)) type" } return false } } } #endif
mit
2c63e99b3f536896440058fa0337ad2c
45.25
137
0.698942
5.089713
false
false
false
false
AliSoftware/Dip
Sources/AutoWiring.swift
2
3528
// // Dip // // Copyright (c) 2015 Olivier Halligon <[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. // protocol AutoWiringDefinition: DefinitionType { var numberOfArguments: Int { get } var autoWiringFactory: ((DependencyContainer, DependencyContainer.Tag?) throws -> Any)? { get } } extension DependencyContainer { /// Tries to resolve instance using auto-wiring func autowire<T>(key aKey: DefinitionKey) throws -> T { let key = aKey guard key.typeOfArguments == Void.self else { throw DipError.definitionNotFound(key: key) } let autoWiringKey = try autoWiringDefinition(byKey: key).key do { let key = autoWiringKey.tagged(with: key.tag ?? context.tag) return try _resolve(key: key) { definition in try definition.autoWiringFactory!(self, key.tag) as! T } } catch { throw DipError.autoWiringFailed(type: key.type, underlyingError: error) } } private func autoWiringDefinition(byKey key: DefinitionKey) throws -> KeyDefinitionPair { do { return try autoWiringDefinition(byKey: key, strictByTag: true) } catch { if key.tag != nil { return try autoWiringDefinition(byKey: key, strictByTag: false) } else { throw error } } } private func autoWiringDefinition(byKey key: DefinitionKey, strictByTag: Bool) throws -> KeyDefinitionPair { var definitions = self.definitions.map({ (key: $0.0, definition: $0.1) }) definitions = filter(definitions: definitions, byKey: key, strictByTag: strictByTag) definitions = definitions.sorted(by: { $0.definition.numberOfArguments > $1.definition.numberOfArguments }) guard definitions.count > 0 && definitions[0].definition.numberOfArguments > 0 else { throw DipError.definitionNotFound(key: key) } let maximumNumberOfArguments = definitions.first?.definition.numberOfArguments definitions = definitions.filter({ $0.definition.numberOfArguments == maximumNumberOfArguments }) //when there are several definitions with the same number of arguments but different arguments types if definitions.count > 1 && definitions[0].key.typeOfArguments != definitions[1].key.typeOfArguments { let error = DipError.ambiguousDefinitions(type: key.type, definitions: definitions.map({ $0.definition })) throw DipError.autoWiringFailed(type: key.type, underlyingError: error) } else { return definitions[0] } } }
mit
f0c820e94ecd1e72c24ff7583937cd65
40.023256
112
0.71712
4.443325
false
false
false
false