repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ohad7/SwiftHTTP
HTTPTask.swift
1
22240
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPTask.swift // // Created by Dalton Cherry on 6/3/14. // Copyright (c) 2014 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation /// HTTP Verbs. /// /// - GET: For GET requests. /// - POST: For POST requests. /// - PUT: For PUT requests. /// - HEAD: For HEAD requests. /// - DELETE: For DELETE requests. /// - PATCH: For PATCH requests. public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case DELETE = "DELETE" case PATCH = "PATCH" } /// Object representation of a HTTP Response. public class HTTPResponse { /// The header values in HTTP response. public var headers: Dictionary<String,String>? /// The mime type of the HTTP response. public var mimeType: String? /// The suggested filename for a downloaded file. public var suggestedFilename: String? /// The body or response data of the HTTP Response. public var responseObject: AnyObject? /// The status code of the HTTP Response. public var statusCode: Int? /// The URL of the HTTP Response. public var URL: NSURL? ///Returns the response as a string public var text: String? { if let d = self.responseObject as? NSData { return NSString(data: d, encoding: NSUTF8StringEncoding) as? String } else if let val: AnyObject = self.responseObject { return "\(val)" } return nil } //get the description of the response public var description: String { var buffer = "" if let u = self.URL { buffer += "URL:\n\(u)\n\n" } if let code = self.statusCode { buffer += "Status Code:\n\(code)\n\n" } if let heads = self.headers { buffer += "Headers:\n" for (key, value) in heads { buffer += "\(key): \(value)\n" } buffer += "\n" } if let s = self.text { buffer += "Payload:\n\(s)\n" } return buffer } } /// Holds the blocks of the background task. class BackgroundBlocks { // these 2 only get used for background download/upload since they have to be delegate methods var success:((HTTPResponse) -> Void)? var failure:((NSError, HTTPResponse?) -> Void)? var progress:((Double) -> Void)? /** Initializes a new Background Block :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. :param: progress The block that is run on the progress of a HTTP Upload or Download. */ init(_ success: ((HTTPResponse) -> Void)?, _ failure: ((NSError, HTTPResponse?) -> Void)?,_ progress: ((Double) -> Void)?) { self.failure = failure self.success = success self.progress = progress } } /// Subclass of NSOperation for handling and scheduling HTTPTask on a NSOperationQueue. public class HTTPOperation : NSOperation { private var task: NSURLSessionDataTask! private var stopped = false private var running = false /// Controls if the task is finished or not. public var done = false //MARK: Subclassed NSOperation Methods /// Returns if the task is asynchronous or not. This should always be false. override public var asynchronous: Bool { return false } /// Returns if the task has been cancelled or not. override public var cancelled: Bool { return stopped } /// Returns if the task is current running. override public var executing: Bool { return running } /// Returns if the task is finished. override public var finished: Bool { return done } /// Returns if the task is ready to be run or not. override public var ready: Bool { return !running } /// Starts the task. override public func start() { super.start() stopped = false running = true done = false task.resume() } /// Cancels the running task. override public func cancel() { super.cancel() running = false stopped = true done = true task.cancel() } /// Sets the task to finished. public func finish() { self.willChangeValueForKey("isExecuting") self.willChangeValueForKey("isFinished") running = false done = true self.didChangeValueForKey("isExecuting") self.didChangeValueForKey("isFinished") } } /// Configures NSURLSession Request for HTTPOperation. Also provides convenience methods for easily running HTTP Request. public class HTTPTask : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { var backgroundTaskMap = Dictionary<String,BackgroundBlocks>() //var sess: NSURLSession? public var baseURL: String? public var requestSerializer = HTTPRequestSerializer() public var responseSerializer: HTTPResponseSerializer? //This gets called on auth challenges. If nil, default handling is use. //Returning nil from this method will cause the request to be rejected and cancelled public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? //MARK: Public Methods /// A newly minted HTTPTask for your enjoyment. public override init() { super.init() } /** Creates a HTTPOperation that can be scheduled on a NSOperationQueue. Called by convenience HTTP verb methods below. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. :returns: A freshly constructed HTTPOperation to add to your NSOperationQueue. */ public func create(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> HTTPOperation? { let serialReq = createRequest(url, method: method, parameters: parameters) if serialReq.error != nil { if failure != nil { failure(serialReq.error!, nil) } return nil } let opt = HTTPOperation() let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.dataTaskWithRequest(serialReq.request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in opt.finish() var extraResponse = HTTPResponse() if let hresponse = response as? NSHTTPURLResponse { extraResponse.headers = hresponse.allHeaderFields as? Dictionary<String,String> extraResponse.mimeType = hresponse.MIMEType extraResponse.suggestedFilename = hresponse.suggestedFilename extraResponse.statusCode = hresponse.statusCode extraResponse.URL = hresponse.URL } if error != nil { if failure != nil { failure(error, extraResponse) } return } if data != nil { var responseObject: AnyObject = data if self.responseSerializer != nil { let resObj = self.responseSerializer!.responseObjectFromResponse(response, data: data) if resObj.error != nil { if failure != nil { failure(resObj.error!, extraResponse) } return } if resObj.object != nil { responseObject = resObj.object! } } extraResponse.responseObject = responseObject if extraResponse.statusCode > 299 { if failure != nil { failure(self.createError(extraResponse.statusCode!), extraResponse) } } else if success != nil { success(extraResponse) } } else if failure != nil { failure(error, extraResponse) } }) opt.task = task return opt } /** Creates a HTTPOperation as a HTTP GET request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func GET(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.GET, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP POST request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func POST(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.POST, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP PATCH request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func PATCH(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.PATCH, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP PUT request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func PUT(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.PUT, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP DELETE request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func DELETE(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.DELETE, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP HEAD request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func HEAD(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.HEAD, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates and starts a HTTPOperation to download a file in the background. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: progress The progress returned in the progress block is between 0 and 1. :param: success The block that is run on a sucessful HTTP Request. The HTTPResponse responseObject object will be a fileURL. You MUST copy the fileURL return in HTTPResponse.responseObject to a new location before using it (e.g. your documents directory). :param: failure The block that is run on a failed HTTP Request. */ public func download(url: String, method: HTTPMethod = .GET, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> NSURLSessionDownloadTask? { let serialReq = createRequest(url,method: method, parameters: parameters) if serialReq.error != nil { failure(serialReq.error!, nil) return nil } let ident = createBackgroundIdent() let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident) let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.downloadTaskWithRequest(serialReq.request) self.backgroundTaskMap[ident] = BackgroundBlocks(success,failure,progress) //this does not have to be queueable as Apple's background dameon *should* handle that. task.resume() return task } //TODO: not implemented yet. /// not implemented yet. public func uploadFile(url: String, parameters: Dictionary<String,AnyObject>?, progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError) -> Void)!) -> Void { let serialReq = createRequest(url,method: .GET, parameters: parameters) if serialReq.error != nil { failure(serialReq.error!) return } let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(createBackgroundIdent()) let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) //session.uploadTaskWithRequest(serialReq.request, fromData: nil) } //MARK: Private Helper Methods /** Creates and starts a HTTPOperation to download a file in the background. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A NSURLRequest from configured requestSerializer. */ private func createRequest(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!) -> (request: NSURLRequest, error: NSError?) { var urlVal = url //probably should change the 'http' to something more generic if !url.hasPrefix("http") && self.baseURL != nil { var split = url.hasPrefix("/") ? "" : "/" urlVal = "\(self.baseURL!)\(split)\(url)" } if let u = NSURL(string: urlVal) { return self.requestSerializer.createRequest(u, method: method, parameters: parameters) } return (NSURLRequest(),createError(-1001)) } /** Creates a random string to use for the identifier of the background download/upload requests. :returns: Identifier String. */ private func createBackgroundIdent() -> String { let letters = "abcdefghijklmnopqurstuvwxyz" var str = "" for var i = 0; i < 14; i++ { let start = Int(arc4random() % 14) str.append(letters[advance(letters.startIndex,start)]) } return "com.vluxe.swifthttp.request.\(str)" } /** Creates a random string to use for the identifier of the background download/upload requests. :param: code Code for error. :returns: An NSError. */ private func createError(code: Int) -> NSError { var text = "An error occured" if code == 404 { text = "Page not found" } else if code == 401 { text = "Access denied" } else if code == -1001 { text = "Invalid URL" } return NSError(domain: "HTTPTask", code: code, userInfo: [NSLocalizedDescriptionKey: text]) } /** Creates a random string to use for the identifier of the background download/upload requests. :param: identifier The identifier string. :returns: An NSError. */ private func cleanupBackground(identifier: String) { self.backgroundTaskMap.removeValueForKey(identifier) } //MARK: NSURLSession Delegate Methods /// Method for authentication challenge. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if let a = auth { let cred = a(challenge) if let c = cred { completionHandler(.UseCredential, c) return } completionHandler(.RejectProtectionSpace, nil) return } completionHandler(.PerformDefaultHandling, nil) } /// Called when the background task failed. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let err = error { let blocks = self.backgroundTaskMap[session.configuration.identifier] if blocks?.failure != nil { //Swift bug. Can't use && with block (radar: 17469794) blocks?.failure!(err, nil) cleanupBackground(session.configuration.identifier) } } } /// The background download finished and reports the url the data was saved to. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) { let blocks = self.backgroundTaskMap[session.configuration.identifier] if blocks?.success != nil { var resp = HTTPResponse() if let hresponse = downloadTask.response as? NSHTTPURLResponse { resp.headers = hresponse.allHeaderFields as? Dictionary<String,String> resp.mimeType = hresponse.MIMEType resp.suggestedFilename = hresponse.suggestedFilename resp.statusCode = hresponse.statusCode resp.URL = hresponse.URL } resp.responseObject = location if resp.statusCode > 299 { if blocks?.failure != nil { blocks?.failure!(self.createError(resp.statusCode!), resp) } return } blocks?.success!(resp) cleanupBackground(session.configuration.identifier) } } /// Will report progress of background download func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let increment = 100.0/Double(totalBytesExpectedToWrite) var current = (increment*Double(totalBytesWritten))*0.01 if current > 1 { current = 1; } let blocks = self.backgroundTaskMap[session.configuration.identifier] if blocks?.progress != nil { blocks?.progress!(current) } } /// The background download finished, don't have to really do anything. public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { } //TODO: not implemented yet. /// not implemented yet. The background upload finished and reports the response data (if any). func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) { //add upload finished logic } //TODO: not implemented yet. /// not implemented yet. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { //add progress block logic } //TODO: not implemented yet. /// not implemented yet. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { } }
apache-2.0
4abeea939c93007a1ee439b11bee2f9c
40.492537
263
0.61232
5.116172
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Renderers/RadiusPieChartRenderer.swift
1
7513
// // RadiusPieChartRenderer.swift // Pods // // Created by Wojciech Rutkowski on 02/10/2016. // // import UIKit class RadiusPieChartRenderer: PieChartRenderer { override func drawDataSet(context: CGContext, dataSet: IPieChartDataSet) { guard let chart = chart, let data = chart.data, let animator = animator else { return } var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle let phaseX = animator.phaseX let phaseY = animator.phaseY let entryCount = dataSet.entryCount var drawAngles = chart.drawAngles let center = chart.centerCircleBox var radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 var visibleAngleCount = 0 for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount += 1 } } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace context.saveGState() for j in 0 ..< entryCount { let sliceAngle = drawAngles[j] var innerRadius = userInnerRadius guard let e = dataSet.entryForIndex(j) else { continue } if let radiusRatio = e.data as? Double { radius = chart.radius * CGFloat(radiusRatio) } // draw only if the value and radius is greater than zero if (abs(e.value) > 0.000001 && radius > 0) { if (!chart.needsHighlight(xIndex: e.xIndex, dataSetIndex: data.indexOfDataSet(dataSet))) { let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0 context.setFillColor(dataSet.colorAt(j).cgColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD) let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD) let path = CGMutablePath() path.move(to: CGPoint(x: arcStartPointX, y: arcStartPointY)) path.addRelativeArc(center: CGPoint(x: center.x, y: center.y), radius: radius, startAngle: startAngleOuter * ChartUtils.Math.FDEG2RAD, delta: sweepAngleOuter * ChartUtils.Math.FDEG2RAD) if drawInnerArc && (innerRadius > 0.0 || accountForSliceSpacing) { if accountForSliceSpacing { var minSpacedRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = min(max(innerRadius, minSpacedRadius), radius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner path.addLine(to: CGPoint(x: center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), y: center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))) path.addRelativeArc(center: CGPoint(x: center.x, y: center.y), radius: innerRadius, startAngle: endAngleInner * ChartUtils.Math.FDEG2RAD, delta: -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { if accountForSliceSpacing { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let sliceSpaceOffset = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) path.addLine(to: CGPoint(x: arcEndPointX, y: arcEndPointY)) } else { path.addLine(to: CGPoint(x: center.x, y: center.y)) } } path.closeSubpath() context.beginPath() context.addPath(path) context.fillPath(using: .evenOdd) } } angle += sliceAngle * phaseX } context.restoreGState() } }
mit
5c757a080a6d228a759d16dc165bc905
44.259036
124
0.445761
6.083401
false
false
false
false
Great-Li-Xin/Xcode
hangge_756/hangge_756/ysocket/yudpsocket.swift
3
6418
/* Copyright (c) <2014>, skysent 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by skysent. 4. Neither the name of the skysent nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY skysent ''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 skysent 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 @_silgen_name("yudpsocket_server") func c_yudpsocket_server(_ host:UnsafePointer<Int8>,port:Int32) -> Int32 @_silgen_name("yudpsocket_recive") func c_yudpsocket_recive(_ fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32 @_silgen_name("yudpsocket_close") func c_yudpsocket_close(_ fd:Int32) -> Int32 @_silgen_name("yudpsocket_client") func c_yudpsocket_client() -> Int32 @_silgen_name("yudpsocket_get_server_ip") func c_yudpsocket_get_server_ip(_ host:UnsafePointer<Int8>,ip:UnsafePointer<Int8>) -> Int32 @_silgen_name("yudpsocket_sentto") func c_yudpsocket_sentto(_ fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,ip:UnsafePointer<Int8>,port:Int32) -> Int32 @_silgen_name("enable_broadcast") func c_enable_broadcast(_ fd:Int32) open class UDPClient: YSocket { public override init(addr a:String,port p:Int){ super.init() let remoteipbuff:[Int8] = [Int8](repeating: 0x0,count: 16) let ret=c_yudpsocket_get_server_ip(a, ip: remoteipbuff) if ret==0{ if let ip=String(cString: remoteipbuff, encoding: String.Encoding.utf8){ self.addr=ip self.port=p let fd:Int32=c_yudpsocket_client() if fd>0{ self.fd=fd } } } } /* * send data * return success or fail with message */ open func send(data d:[UInt8])->(Bool,String){ if let fd:Int32=self.fd{ let sendsize:Int32=c_yudpsocket_sentto(fd, buff: d, len: Int32(d.count), ip: self.addr,port: Int32(self.port)) if Int(sendsize)==d.count{ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * send string * return success or fail with message */ open func send(str s:String)->(Bool,String){ if let fd:Int32=self.fd{ let sendsize:Int32=c_yudpsocket_sentto(fd, buff: s, len: Int32(strlen(s)), ip: self.addr,port: Int32(self.port)) if sendsize==Int32(strlen(s)){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * enableBroadcast */ open func enableBroadcast(){ if let fd:Int32=self.fd{ c_enable_broadcast(fd) } } /* * * send nsdata */ open func send(data d:Data)->(Bool,String){ if let fd:Int32=self.fd{ var buff:[UInt8] = [UInt8](repeating: 0x0,count: d.count) (d as NSData).getBytes(&buff, length: d.count) let sendsize:Int32=c_yudpsocket_sentto(fd, buff: buff, len: Int32(d.count), ip: self.addr,port: Int32(self.port)) if sendsize==Int32(d.count){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } open func close()->(Bool,String){ if let fd:Int32=self.fd{ c_yudpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } //TODO add multycast and boardcast } open class UDPServer:YSocket{ public override init(addr a:String,port p:Int){ super.init(addr: a, port: p) let fd:Int32 = c_yudpsocket_server(self.addr, port: Int32(self.port)) if fd>0{ self.fd=fd } } //TODO add multycast and boardcast open func recv(_ expectlen:Int)->([UInt8]?,String,Int){ if let fd:Int32 = self.fd{ var buff:[UInt8] = [UInt8](repeating: 0x0,count: expectlen) var remoteipbuff:[Int8] = [Int8](repeating: 0x0,count: 16) var remoteport:Int32=0 let readLen:Int32=c_yudpsocket_recive(fd, buff: buff, len: Int32(expectlen), ip: &remoteipbuff, port: &remoteport) let port:Int=Int(remoteport) var addr:String="" if let ip=String(cString: remoteipbuff, encoding: String.Encoding.utf8){ addr=ip } if readLen<=0{ return (nil,addr,port) } let rs=buff[0...Int(readLen-1)] let data:[UInt8] = Array(rs) return (data,addr,port) } return (nil,"no ip",0) } open func close()->(Bool,String){ if let fd:Int32=self.fd{ c_yudpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } }
mit
94859d021e8a3079bac6b2627b4f9529
37.662651
165
0.619352
3.884988
false
false
false
false
tattn/SPAJAM2017-Final
SPAJAM2017Final/UI/TopVC.swift
1
4249
// // TopVC.swift // HackathonStarter // // Created by 田中 達也 on 2016/06/30. // Copyright © 2016年 tattn. All rights reserved. // import UIKit import Instantiate import InstantiateStandard import RxSwift import RxCocoa import Alamofire final class TopVC: UIViewController, StoryboardInstantiatable { static var me: GraphMe? static var friends: [GraphMe]? = [] @IBOutlet private weak var label: UILabel! @IBOutlet private weak var label2: UILabel! static var storyboard: UIStoryboard { return UIStoryboard(name: "Main", bundle: nil) } func inject(_ dependency: String) { label.text = dependency } override func viewDidLoad() { super.viewDidLoad() label.text = "🐱" label2.text = "🐶" var tapGesture = UITapGestureRecognizer() label.addGestureRecognizer(tapGesture) tapGesture.rx.event.subscribe(onNext: { _ in TopVC.fetchFacebookData(view: self) { self.navigationController?.setNavigationBarHidden(true, animated: false) self.navigationController?.pushViewController(BraveInfectionVC.instantiate(with: .init(title: "")), animated: true) } }) .disposed(by: disposeBag) tapGesture = UITapGestureRecognizer() label2.addGestureRecognizer(tapGesture) tapGesture.rx.event.subscribe(onNext: { _ in self.navigationController?.pushViewController(SimpleCollectionVC.instantiate(with: .init(title: "🐶")), animated: true) }) .disposed(by: disposeBag) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @IBAction func tapLoginButton(_ sender: Any) { // Login.login(from: self) { //// APIClient.registerPhotos(userId: "101761067145209") // APIClient.getTags(userId: "101761067145209") // } // // return //Login.login(from: self) { // GraphAPI.me { _ in // GraphAPI.friends { _ in // GraphAPI.profile(userId: "747789068725242") { _ in // GraphAPI.feed(userId: "747789068725242") { _ in // GraphAPI.photos(userId: "101761067145209") { _ in // } // } // } // } TopVC.fetchFacebookData(view: self, completion: nil) } class func fetchFacebookData(view: UIViewController, completion: (() -> Void)?) { Login.login(from: view) { GraphAPI.me { meResult in switch meResult { case .success(let me): TopVC.me = me case .failure(_): break } GraphAPI.friends { friendsResult in switch friendsResult { case .success(let friends): TopVC.friends = friends case .failure(_): break } completion?() // ちょっと失礼しますね★ if let id = TopVC.me?.id, let friends = TopVC.friends { // 102318787089064 for friend in friends { APIClient.getTags(userId: friend.id) { _ in } } // GraphAPI.photos(userId: id) { _ in // APIClient.getTags { tags in // print(tags) // } // } // APIClient.registerPhotos(userId: id) // 102318787089064 } /* GraphAPI.profile(userId: "747789068725242") { _ in GraphAPI.feed(userId: "747789068725242") { _ in GraphAPI.photos(userId: "747789068725242") { _ in } } }*/ } } } } }
mit
d5e211897ab23af4ac5320b717d2e8ad
33.186992
131
0.484423
4.895227
false
false
false
false
mightydeveloper/swift
stdlib/public/core/Sequence.swift
8
21622
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Encapsulates iteration state and interface for iteration over a /// *sequence*. /// /// - Note: While it is safe to copy a *generator*, advancing one /// copy may invalidate the others. /// /// Any code that uses multiple generators (or `for`...`in` loops) /// over a single *sequence* should have static knowledge that the /// specific *sequence* is multi-pass, either because its concrete /// type is known or because it is constrained to `CollectionType`. /// Also, the generators must be obtained by distinct calls to the /// *sequence's* `generate()` method, rather than by copying. public protocol GeneratorType { /// The type of element generated by `self`. typealias Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. Specific implementations of this protocol /// are encouraged to respond to violations of this requirement by /// calling `preconditionFailure("...")`. @warn_unused_result mutating func next() -> Element? } /// A type that can be iterated with a `for`...`in` loop. /// /// `SequenceType` makes no requirement on conforming types regarding /// whether they will be destructively "consumed" by iteration. To /// ensure non-destructive iteration, constrain your *sequence* to /// `CollectionType`. /// /// As a consequence, it is not possible to run multiple `for` loops /// on a sequence to "resume" iteration: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // Not guaranteed to continue from the next element. /// } /// /// `SequenceType` makes no requirement about the behavior in that /// case. It is not correct to assume that a sequence will either be /// "consumable" and will resume iteration, or that a sequence is a /// collection and will restart iteration from the first element. /// A conforming sequence that is not a collection is allowed to /// produce an arbitrary sequence of elements from the second generator. public protocol SequenceType { /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. typealias Generator : GeneratorType // FIXME: should be constrained to SequenceType // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A type that represents a subsequence of some of the elements. typealias SubSequence /// Return a *generator* over the elements of this *sequence*. /// /// - Complexity: O(1). @warn_unused_result func generate() -> Generator /// Return a value less than or equal to the number of elements in /// `self`, **nondestructively**. /// /// - Complexity: O(N). @warn_unused_result func underestimateCount() -> Int /// Return an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] /// Return an `Array` containing the elements of `self`, /// in order, that satisfy the predicate `includeElement`. @warn_unused_result func filter( @noescape includeElement: (Generator.Element) throws -> Bool ) rethrows -> [Generator.Element] /// Call `body` on each element in `self` in the same order as a /// *for-in loop.* /// /// sequence.forEach { /// // body code /// } /// /// is similar to: /// /// for element in sequence { /// // body code /// } /// /// - Note: You cannot use the `break` or `continue` statement to exit the /// current call of the `body` closure or skip subsequent calls. /// - Note: Using the `return` statement in the `body` closure will only /// exit from the current call to `body`, not any outer scope, and won't /// skip subsequent calls. /// /// - Complexity: O(`self.count`) func forEach(@noescape body: (Generator.Element) throws -> Void) rethrows /// Returns a subsequence containing all but the first `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result func dropFirst(n: Int) -> SubSequence /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `self` is a finite sequence. /// - Requires: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result func dropLast(n: Int) -> SubSequence /// Returns a subsequence, up to `maxLength` in length, containing the /// initial elements. /// /// If `maxLength` exceeds `self.count`, the result contains all /// the elements of `self`. /// /// - Requires: `maxLength >= 0` @warn_unused_result func prefix(maxLength: Int) -> SubSequence /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `s`. /// /// - Requires: `self` is a finite sequence. /// - Requires: `maxLength >= 0` @warn_unused_result func suffix(maxLength: Int) -> SubSequence /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: (Generator.Element) throws -> Bool ) rethrows -> [SubSequence] @warn_unused_result func _customContainsEquatableElement( element: Generator.Element ) -> Bool? /// If `self` is multi-pass (i.e., a `CollectionType`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. func _preprocessingPass<R>(preprocess: (Self)->R) -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Generator.Element> /// Copy a Sequence into an array, returning one past the last /// element initialized. func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>) -> UnsafeMutablePointer<Generator.Element> } /// A default generate() function for `GeneratorType` instances that /// are declared to conform to `SequenceType` extension SequenceType where Self.Generator == Self, Self : GeneratorType { public func generate() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` generator before possibly returning the first available element. /// /// The underlying generator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already dropped from the underlying sequence. internal class _DropFirstSequence<Base : GeneratorType> : SequenceType, GeneratorType { internal var generator: Base internal let limit: Int internal var dropped: Int internal init(_ generator: Base, limit: Int, dropped: Int = 0) { self.generator = generator self.limit = limit self.dropped = dropped } internal func generate() -> _DropFirstSequence<Base> { return self } internal func next() -> Base.Element? { while dropped < limit { if generator.next() == nil { dropped = limit return nil } ++dropped } return generator.next() } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` generator. /// /// The underlying generator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already taken from the underlying sequence. internal class _PrefixSequence<Base : GeneratorType> : SequenceType, GeneratorType { internal let maxLength: Int internal var generator: Base internal var taken: Int internal init(_ generator: Base, maxLength: Int, taken: Int = 0) { self.generator = generator self.maxLength = maxLength self.taken = taken } internal func generate() -> _PrefixSequence<Base> { return self } internal func next() -> Base.Element? { if taken >= maxLength { return nil } ++taken if let next = generator.next() { return next } taken = maxLength return nil } } //===----------------------------------------------------------------------===// // Default implementations for SequenceType //===----------------------------------------------------------------------===// extension SequenceType { /// Return an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result public func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimateCount() var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var generator = generate() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(generator.next()!)) } // Add remaining elements, if any. while let element = generator.next() { result.append(try transform(element)) } return Array(result) } /// Return an `Array` containing the elements of `self`, /// in order, that satisfy the predicate `includeElement`. @warn_unused_result public func filter( @noescape includeElement: (Generator.Element) throws -> Bool ) rethrows -> [Generator.Element] { var result = ContiguousArray<Generator.Element>() var generator = generate() while let element = generator.next() { if try includeElement(element) { result.append(element) } } return Array(result) } /// Returns a subsequence containing all but the first `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropFirst(n: Int) -> AnySequence<Generator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). // FIXME: <rdar://problem/21885675> Use method dispatch to fold // _PrefixSequence and _DropFirstSequence counts if let any = self as? AnySequence<Generator.Element>, let box = any._box as? _SequenceBox<_DropFirstSequence<Generator>> { let base = box._base let folded = _DropFirstSequence(base.generator, limit: base.limit + n, dropped: base.dropped) return AnySequence(folded) } return AnySequence(_DropFirstSequence(generate(), limit: n)) } /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `self` is a finite collection. /// - Requires: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast(n: Int) -> AnySequence<Generator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Generator.Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Generator.Element] = [] var ringBuffer: [Generator.Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = i.successor() % n } } return AnySequence(result) } @warn_unused_result public func prefix(maxLength: Int) -> AnySequence<Generator.Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Generator.Element>()) } // FIXME: <rdar://problem/21885675> Use method dispatch to fold // _PrefixSequence and _DropFirstSequence counts if let any = self as? AnySequence<Generator.Element>, let box = any._box as? _SequenceBox<_PrefixSequence<Generator>> { let base = box._base let folded = _PrefixSequence( base.generator, maxLength: min(base.maxLength, maxLength), taken: base.taken) return AnySequence(folded) } return AnySequence(_PrefixSequence(generate(), maxLength: maxLength)) } @warn_unused_result public func suffix(maxLength: Int) -> AnySequence<Generator.Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Generator.Element] = [] ringBuffer.reserveCapacity(min(maxLength, underestimateCount())) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i = i.successor() % maxLength } } if i != ringBuffer.startIndex { return AnySequence( [ringBuffer[i..<ringBuffer.endIndex], ringBuffer[0..<i]].flatten()) } return AnySequence(ringBuffer) } /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( maxSplit: Int = Int.max, allowEmptySlices: Bool = false, @noescape isSeparator: (Generator.Element) throws -> Bool ) rethrows -> [AnySequence<Generator.Element>] { _precondition(maxSplit >= 0, "Must take zero or more splits") var result: [AnySequence<Generator.Element>] = [] var subSequence: [Generator.Element] = [] func appendSubsequence() -> Bool { if subSequence.isEmpty && !allowEmptySlices { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplit == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var hitEnd = false var generator = self.generate() while true { guard let element = generator.next() else { hitEnd = true break } if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplit { break } } else { subSequence.append(element) } } if !hitEnd { while let element = generator.next() { subSequence.append(element) } } appendSubsequence() return result } /// Return a value less than or equal to the number of elements in /// `self`, **nondestructively**. /// /// - Complexity: O(N). @warn_unused_result public func underestimateCount() -> Int { return 0 } public func _preprocessingPass<R>(preprocess: (Self)->R) -> R? { return nil } @warn_unused_result public func _customContainsEquatableElement( element: Generator.Element ) -> Bool? { return nil } } extension SequenceType { /// Call `body` on each element in `self` in the same order as a /// *for-in loop.* /// /// sequence.forEach { /// // body code /// } /// /// is similar to: /// /// for element in sequence { /// // body code /// } /// /// - Note: You cannot use the `break` or `continue` statement to exit the /// current call of the `body` closure or skip subsequent calls. /// - Note: Using the `return` statement in the `body` closure will only /// exit from the current call to `body`, not any outer scope, and won't /// skip subsequent calls. /// /// - Complexity: O(`self.count`) public func forEach( @noescape body: (Generator.Element) throws -> Void ) rethrows { for element in self { try body(element) } } } extension SequenceType where Generator.Element : Equatable { /// Returns the maximal `SubSequence`s of `self`, in order, around elements /// equatable to `separator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( separator: Generator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [AnySequence<Generator.Element>] { return split(maxSplit, allowEmptySlices: allowEmptySlices, isSeparator: { $0 == separator }) } } extension SequenceType { /// Returns a subsequence containing all but the first element. /// /// - Complexity: O(1) @warn_unused_result public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element. /// /// - Requires: `self` is a finite sequence. /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast() -> SubSequence { return dropLast(1) } } /// Return an underestimate of the number of elements in the given /// sequence, without consuming the sequence. For Sequences that are /// actually Collections, this will return `x.count`. @available(*, unavailable, message="call the 'underestimateCount()' method on the sequence") public func underestimateCount<T : SequenceType>(x: T) -> Int { fatalError("unavailable function can't be called") } extension SequenceType { public func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>) -> UnsafeMutablePointer<Generator.Element> { var p = UnsafeMutablePointer<Generator.Element>(ptr) for x in GeneratorSequence(self.generate()) { p++.initialize(x) } return p } } // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass a GeneratorType through GeneratorSequence to give it "SequenceType-ness" /// A sequence built around a generator of type `G`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just a generator `g`: /// /// for x in GeneratorSequence(g) { ... } public struct GeneratorSequence< Base : GeneratorType > : GeneratorType, SequenceType { @available(*, unavailable, renamed="Base") public typealias G = Base /// Construct an instance whose generator is a copy of `base`. public init(_ base: Base) { _base = base } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. public mutating func next() -> Base.Element? { return _base.next() } internal var _base: Base }
apache-2.0
54338b9baa41a3b7dee53a5347aefa60
32.061162
92
0.647581
4.268904
false
false
false
false
Mai-Tai-D/maitaid001
maitaid002/TideChart.swift
1
24245
// // TideChart.swift // maitaid002 // // Created by David Neely on 6/2/17. // Copyright © 2017 Vision Runner LLC. All rights reserved. // import Foundation import SwiftyJSON import SwiftCharts import UIKit class TideChart { //TODO: Add in swift style documentation with three slashes static func showHistoricalAndProjectedGraph(withViewController inputViewController: ViewController, andRect inputRect: CGRect, andDepthTimes inputDepthTimes: [JSON], andDepths inputDepths: [JSON], andProjectedDepths inputProjectedDepths: [JSON], andProjectedDepthTimes inputProjectedDepthTimes: [JSON], andSalinityTimes inputSalinityTimes: [JSON], andSalinity inputSalinity: [JSON], andTemperatureTimes inputTemperatureTimes: [JSON], andTemperature inputTemperature: [JSON]) -> Chart { var returnChart: Chart let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) var chartPointsDepth: [ChartPoint] = [] var chartPointsProjectedDepth: [ChartPoint] = [] var chartPointsSalinity: [ChartPoint] = [] var chartPointsTemperature: [ChartPoint] = [] //TODO: Refactor to method // Create chartpoints from the depth times for index in 0..<inputDepths.count { // Convert Json to Double //TODO: Could crash with unexpectedly found nil while unwrapping optional let iteratedChartPointXInt = inputDepthTimes[index].rawValue as! Double let iteratedChartPointYInt = inputDepths[index].rawValue as! Double // Set x data to append as charpoint let iteratedChartPointX = ChartAxisValue.init( scalar: iteratedChartPointXInt, labelSettings: labelSettings) // Set y data to append as charpoint let iteratedChartPointY = ChartAxisValue.init( scalar: iteratedChartPointYInt, labelSettings: labelSettings) // Add the new chartpoint to the array of points to chart chartPointsDepth.append(ChartPoint.init(x: iteratedChartPointX, y: iteratedChartPointY)) } // Create chartpoints from the depth times for index in 0..<inputProjectedDepths.count { // Convert Json to Double let iteratedChartPointXInt = inputProjectedDepthTimes[index].rawValue as! Double let iteratedChartPointYInt = inputProjectedDepths[index].rawValue as! Double // Set x data to append as charpoint let iteratedChartPointX = ChartAxisValue.init( scalar: iteratedChartPointXInt, labelSettings: labelSettings) // Set y data to append as charpoint let iteratedChartPointY = ChartAxisValue.init( scalar: iteratedChartPointYInt, labelSettings: labelSettings) // Add the new chartpoint to the array of points to chart chartPointsProjectedDepth.append(ChartPoint.init(x: iteratedChartPointX, y: iteratedChartPointY)) } print(chartPointsProjectedDepth) // Create chartpoints from the salinity times for index in 0..<inputSalinity.count { // Convert Json to Double let iteratedChartPointXInt = inputSalinityTimes[index].rawValue as! Double let iteratedChartPointYInt = inputSalinity[index].rawValue as! Double // Set x data to append as charpoint let iteratedChartPointX = ChartAxisValue.init( scalar: iteratedChartPointXInt, labelSettings: labelSettings) // Set y data to append as charpoint let iteratedChartPointY = ChartAxisValue.init( scalar: iteratedChartPointYInt, labelSettings: labelSettings) // Add the new chartpoint to the array of points to chart chartPointsSalinity.append(ChartPoint.init(x: iteratedChartPointX, y: iteratedChartPointY)) } // Create chartpoints from the temperature times for index in 0..<inputTemperature.count { // Convert Json to Double let iteratedChartPointXInt = inputTemperatureTimes[index].rawValue as! Double let iteratedChartPointYInt = inputTemperature[index].rawValue as! Double // Set x data to append as charpoint let iteratedChartPointX = ChartAxisValue.init( scalar: iteratedChartPointXInt, labelSettings: labelSettings) // Set y data to append as charpoint let iteratedChartPointY = ChartAxisValue.init( scalar: iteratedChartPointYInt, labelSettings: labelSettings) // Add the new chartpoint to the array of points to chart chartPointsTemperature.append(ChartPoint.init(x: iteratedChartPointX, y: iteratedChartPointY)) } //TODO: Refactor to a helper class //TODO: Do this as a protocol func thin(by inputNumber: Int, in inputArray: [ChartPoint]) -> [ChartPoint] { //Thins out the data points so the chart is easier to pan var returnPoints: [ChartPoint] = [] //TODO: Fix bug as this causes program to crash when device rotated. for index in 0..<inputArray.count - 1 { if index % inputNumber == 0 { returnPoints.append(chartPointsDepth[index]) } } return returnPoints } // chartPointsDepth = thin(by: 100, in: chartPointsDepth) // chartPointsProjectedDepth = thin(by: 100, in: chartPointsProjectedDepth) let xGeneratorDate = ChartAxisValuesGeneratorDate(unit: .minute, preferredDividers: 2, minSpace: 1, maxTextSize: 12) var displayDateFormatter = DateFormatter() displayDateFormatter.dateFormat = FormatDisplay.YearMonthDate.rawValue var displayFormatter = DateFormatter() displayFormatter.dateFormat = FormatDisplay.Full.rawValue let xLabelGeneratorDate = ChartAxisLabelsGeneratorDate(labelSettings: labelSettings, formatter: displayFormatter) var firstDate = Date.init() var lastDate = Date.init() var firstReceptionTime: Double var lastReceptionTime: Double // Chart first and last dates on x axis based on historical reception times guard let unwrappedFirstReceptionTime = inputDepthTimes[0].rawValue as? Double else { fatalError() } firstReceptionTime = unwrappedFirstReceptionTime firstDate = Date(timeIntervalSince1970: firstReceptionTime) // Get projected tide data let arrayOfProjectedTideData = NoaaTidePredictions.getArrayOfProjectedTideData() // Updates last date to plot as the last date in the projected tide data at the end of the year lastReceptionTime = arrayOfProjectedTideData[(arrayOfProjectedTideData.count - 1)].timeInterval lastDate = Date(timeIntervalSince1970: Dates.getDateHalfAWeekFromNow()) // Append chartpoints from the projected reception times for index in 0..<arrayOfProjectedTideData.count { let iteratedProjectedX = arrayOfProjectedTideData[index].timeInterval if let iteratedProjectedY = Double(arrayOfProjectedTideData[index].pred_in_ft) { // Set x data to append as charpoint let iteratedChartPointX = ChartAxisValue.init( scalar: Double(iteratedProjectedX), labelSettings: labelSettings) // Set y data to append as charpoint let iteratedChartPointY = ChartAxisValue.init( scalar: Double(iteratedProjectedY), labelSettings: labelSettings) // filter out some of the points let offset = firstReceptionTime - 100000 if iteratedChartPointX.scalar > offset { chartPointsSalinity.append(ChartPoint.init(x: iteratedChartPointX, y: iteratedChartPointY)) } } } //TODO: Decide if this feature is going to be tabled. //TODO: Update this to set the moon phase label with this var that is returned // let moonPhase = NetworkCalls.getMoonphaseForNow() let xModel = ChartAxisModel(firstModelValue: firstDate.timeIntervalSince1970, lastModelValue: lastDate.timeIntervalSince1970, axisTitleLabels: [ChartAxisLabel(text: InterfaceLabel.x.rawValue, settings: labelSettings)], axisValuesGenerator: xGeneratorDate, labelsGenerator: xLabelGeneratorDate) //TODO: Update to show the chartPointsDepth and the chartPointsDepthProjections //TODO: Verify that the chartPointsDepthProjections has items in it. let xValues = ChartAxisValuesStaticGenerator.generateXAxisValuesWithChartPoints(chartPointsDepth, minSegmentCount: 1, maxSegmentCount: 10, multiple: 1000, // hour interval axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: true) let yValues = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPointsDepth, minSegmentCount: 1, maxSegmentCount: 10, multiple: 0.1, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: true) let valuesGenerator = ChartAxisGeneratorMultiplier(1) let labelsGenerator = ChartAxisLabelsGeneratorNumber(labelSettings: ChartLabelSettings()) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: InterfaceLabel.y.rawValue, settings: labelSettings.defaultVertical())) let chartFrame = inputRect let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) let lineModelDepth = ChartLineModel(chartPoints: chartPointsDepth, lineColor: UIColor.purple, lineWidth: 3, animDuration: 1, animDelay: 1) let lineModelDepthProjections = ChartLineModel(chartPoints: chartPointsProjectedDepth, lineColor: UIColor.purple, lineWidth: 3, animDuration: 2, animDelay: 2, dashPattern: [5.0, 5.0]) let lineModelSalinity = ChartLineModel(chartPoints: chartPointsSalinity, lineColor: UIColor.blue, lineWidth: 1, animDuration: 5, animDelay: 1) let lineModelTemperature = ChartLineModel(chartPoints: chartPointsTemperature, lineColor: UIColor.green, lineWidth: 1, animDuration: 5, animDelay: 1) var gradientChartPoints = chartPointsDepth //Adds chart points from array of projected depths to gradient points for chartPoint in chartPointsProjectedDepth { gradientChartPoints.append(chartPoint) } // Sets first and last x positions // Then connects those two points // Then draws the gradient // And draws a nice clean line from first and last x positions // Because they are both zero. if let first = gradientChartPoints.first { gradientChartPoints.insert(ChartPoint(x: first.x, y: ChartAxisValueInt(0)), at: 0) } if let last = gradientChartPoints.last { gradientChartPoints.append(ChartPoint(x: last.x, y: ChartAxisValueInt(0))) } let lineModel1AreaLayer = ChartPointsAreaLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: gradientChartPoints, areaColors: [UIColor.purple.withAlphaComponent(0.66), UIColor.clear], animDuration: 1, animDelay: 1, addContainerPoints: false) // Adds in touch behaviors let thumbSettings = ChartPointsLineTrackerLayerThumbSettings(thumbSize: Env.iPad ? 20 : 10, thumbBorderWidth: Env.iPad ? 4 : 2) let trackerLayerSettings = ChartPointsLineTrackerLayerSettings(thumbSettings: thumbSettings) // reset all labels and remove them from the view var hudViews: [UIView] = [] let chartPointsTrackerLayer = ChartPointsLineTrackerLayer<ChartPoint, Any>( xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lines: [chartPointsDepth, chartPointsProjectedDepth], lineColor: UIColor.lightGray, animDuration: 0.5, animDelay: 2, settings: trackerLayerSettings) {chartPointsWithScreenLoc in hudViews.forEach{$0.removeFromSuperview() } for (index, chartPointWithScreenLoc) in chartPointsWithScreenLoc.enumerated() { let label = UILabel() let moonPhaseLabel = UILabel() let dateLabel = UILabel() var day = "" var depth: Double = 0.0 var projectedDepth: Double = 0.0 var temperature: Double = 0.0 var salinity: Double = 0.0 // find item closest to but not over the inputTimeInterval func getDatum(fromChartPoints inputChartPoints: [ChartPoint], withTimeInterval inputTimeInterval: Double) -> Double { var returnDouble = -1.0 //TODO:Fix. This HAck was used to differentiate between an empty chart point and a value for point in inputChartPoints { let iteratedTimeInterval = point.x.scalar if iteratedTimeInterval < inputTimeInterval { returnDouble = point.y.scalar } } return returnDouble } let selectedTimeInterval = chartPointWithScreenLoc.chartPoint.x.scalar depth = getDatum(fromChartPoints: chartPointsDepth, withTimeInterval: selectedTimeInterval) print("depth: \(depth)") projectedDepth = getDatum(fromChartPoints: chartPointsProjectedDepth, withTimeInterval: selectedTimeInterval) print("projectedDepth: \(projectedDepth)") temperature = getDatum(fromChartPoints: chartPointsTemperature, withTimeInterval: selectedTimeInterval) print("temperature: \(temperature)") salinity = getDatum(fromChartPoints: chartPointsSalinity, withTimeInterval: selectedTimeInterval) print("salinity: \(salinity)") let dateTime = chartPointWithScreenLoc.chartPoint.x.scalar let iteratedDate = Date(timeIntervalSince1970: dateTime) let dateTimeString = (displayFormatter.string(from: iteratedDate)) let dateString = (displayDateFormatter.string(from: iteratedDate)) if let dayOfTheWeek = Dates.getDayOfWeek(today: dateString) { switch dayOfTheWeek { case 0: day = DaysOfTheWeek.Saturday.rawValue case 1: day = DaysOfTheWeek.Sunday.rawValue case 2: day = DaysOfTheWeek.Monday.rawValue case 3: day = DaysOfTheWeek.Tuesday.rawValue case 4: day = DaysOfTheWeek.Wednesday.rawValue case 5: day = DaysOfTheWeek.Thursday.rawValue case 6: day = DaysOfTheWeek.Friday.rawValue default: day = DaysOfTheWeek.Saturday.rawValue } // Set up Date and Year label dateLabel.font = UIFont(name: FontNames.Futura.rawValue, size: 27) dateLabel.text = "\(day) \(dateString)" dateLabel.sizeToFit() } else { print() fatalError() } // Create an circle let circle = UIView() let radius: CGFloat = 30.0 circle.frame = CGRect.init(x: 0, y: 0, width: radius*2, height: radius*2) circle.layer.cornerRadius = radius circle.clipsToBounds = true circle.layer.borderColor = UIColor.yellow.cgColor circle.backgroundColor = UIColor.yellow circle.layer.borderWidth = 1.0 circle.alpha = 0.6 circle.center = CGPoint(x: chartPointWithScreenLoc.screenLoc.x, y: chartPointWithScreenLoc.screenLoc.y + chartFrame.minY) hudViews.append(circle) inputViewController.view.addSubview(circle) // Sets buttons to display currently selected dtw and date time //TODO: HAck to show projected tide data in gauages if depth > -1.0 { inputViewController.setCurrentDepth(withDepth: depth) } if projectedDepth > -1.0 { inputViewController.setCurrentDepth(withDepth: projectedDepth) } inputViewController.setCurrentTemperature(withTemperature: temperature) inputViewController.setCurrentSalinity(withSalinity: salinity) inputViewController.setCurrentTime(withTime: day.uppercased() + " " + dateTimeString) } } //MARK: - Adds notifications let notificationViewWidth: CGFloat = Env.iPad ? 20 : 60 let notificationViewHeight: CGFloat = Env.iPad ? 20 : 30 let notificationGenerator = { (chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) // Get last element in the array to show now label let lastIndex = chartPointModel.index if chartPoint.y.scalar >= 2.0 { let chartPointView = HandlingView(frame: CGRect(x: screenLoc.x - notificationViewWidth/2, y: screenLoc.y + notificationViewHeight * 4.0, width: notificationViewWidth, height: notificationViewHeight)) // Creates first high tide label let nowLabel = UILabel(frame: chartPointView.bounds) nowLabel.layer.cornerRadius = Env.iPad ? 15 : 10 nowLabel.clipsToBounds = true nowLabel.backgroundColor = UIColor.green nowLabel.textColor = UIColor.black nowLabel.textAlignment = NSTextAlignment.center nowLabel.font = UIFont.boldSystemFont(ofSize: Env.iPad ? 20 : 16) nowLabel.text = String(chartPoint.y.scalar) + InterfaceLabel.feetMeasurement.rawValue chartPointView.addSubview(nowLabel) nowLabel.transform = CGAffineTransform(scaleX: 0, y: 0) chartPointView.movedToSuperViewHandler = { UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { nowLabel.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } return chartPointView } return nil } let chartPointsNotificationsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPointsDepth, viewGenerator: notificationGenerator, displayDelay: 1, mode: .custom) // To preserve the offset of the notification views from the chart point they represent, during transforms, we need to pass mode: .custom along with this custom transformer. chartPointsNotificationsLayer.customTransformer = {(model, view, layer) -> Void in let screenLoc = layer.modelLocToScreenLoc(x: model.chartPoint.x.scalar, y: model.chartPoint.y.scalar) view.frame.origin = CGPoint(x: screenLoc.x + 5, y: screenLoc.y - notificationViewHeight - 5) } let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModelDepth, lineModelDepthProjections], pathGenerator: CatmullPathGenerator()) // || CubicLinePathGenerator let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: guidelinesLayerSettings) // Shows Mean High Tide with arbitrary data. //TODO: Update to mean high tide at specific makaha after 3 years of data can be gathered. let guidelinesHighlightLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.red, linesWidth: 1, dotWidth: 4, dotSpacing: 4) let meanHighTideGuidelinesHighlightLayer = ChartGuideLinesForValuesDottedLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, settings: guidelinesHighlightLayerSettings, axisValuesX: [ChartAxisValueDouble(0)], axisValuesY: [ChartAxisValueDouble(0)]) // Shows MLLW with arbitrary data. //TODO: Update to MLLW at specific makaha after 3 years of data can be gathered. let mllwGuidelinesHighlightLayer = ChartGuideLinesForValuesDottedLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, settings: guidelinesHighlightLayerSettings, axisValuesX: [ChartAxisValueDouble(0)], axisValuesY: [ChartAxisValueDouble(2)]) returnChart = Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, meanHighTideGuidelinesHighlightLayer, mllwGuidelinesHighlightLayer, chartPointsLineLayer, lineModel1AreaLayer, chartPointsNotificationsLayer, chartPointsTrackerLayer ] ) return returnChart } } //MARK: - Converts the Double to a Decimal with variable number of places. extension Double { // Rounds the double to decimal places value func roundTo(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } }
mit
edc9e8826bdb8769e8549c3df234abcf
45.179048
260
0.609429
5.679082
false
false
false
false
TongjiUAppleClub/WeCitizens
WeCitizensTests/UserModelTests.swift
1
2024
// // UserModelTests.swift // WeCitizens // // Created by Teng on 3/13/16. // Copyright © 2016 Tongji Apple Club. All rights reserved. // import XCTest class UserModelTests: XCTestCase { let testUserModel = UserModel() var expectation:XCTestExpectation? = nil let users = ["[email protected]", "[email protected]", "[email protected]"] override func setUp() { super.setUp() self.expectation = self.expectationWithDescription("Handler called") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } //未通过 func testAddResume() { testUserModel.addUserResume("7hPxfbuamI") { (success, error) -> Void in XCTAssertNil(error) XCTAssertTrue(success) self.expectation!.fulfill() } self.waitForExpectationsWithTimeout(10.0, handler: nil) } //未通过 func testMinusResume() { testUserModel.minusUserResume("vETKWM6fe5") { (success, error) -> Void in XCTAssertNil(error) XCTAssertTrue(success) self.expectation!.fulfill() } self.waitForExpectationsWithTimeout(10.0, handler: nil) } //未通过 func testSetAvatar() { } func testGetUserData() { testUserModel.getUsersInfo(users, needStore: true) { (objects, error) -> Void in XCTAssertNil(error) if error == nil { XCTAssertNotNil(objects) if let users = objects { for user in users { print("Got User Info:\(user.userName)") } } } else { print("Get User Info Error: \(error!) \(error!.userInfo)") } self.expectation!.fulfill() } self.waitForExpectationsWithTimeout(10.0, handler: nil) } }
mit
ebe0b7c26d8ff098b9a33ef84255cf96
27.239437
111
0.565586
4.505618
false
true
false
false
abertelrud/swift-package-manager
Sources/PackageFingerprint/Model.swift
2
1890
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 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 struct Foundation.URL import struct TSCUtility.Version public struct Fingerprint: Equatable { public let origin: Origin public let value: String public init(origin: Origin, value: String) { self.origin = origin self.value = value } } public extension Fingerprint { enum Kind: String, Hashable { case sourceControl case registry } enum Origin: Equatable, CustomStringConvertible { case sourceControl(URL) case registry(URL) public var kind: Fingerprint.Kind { switch self { case .sourceControl: return .sourceControl case .registry: return .registry } } public var url: URL? { switch self { case .sourceControl(let url): return url case .registry(let url): return url } } public var description: String { switch self { case .sourceControl(let url): return "sourceControl(\(url))" case .registry(let url): return "registry(\(url))" } } } } public typealias PackageFingerprints = [Version: [Fingerprint.Kind: Fingerprint]] public enum FingerprintCheckingMode: String { case strict case warn }
apache-2.0
2cb21aa57f72ee9f07c293351cadde11
25.619718
81
0.542328
5.206612
false
false
false
false
nalexn/ViewInspector
Tests/ViewInspectorTests/SwiftUI/ForEachTests.swift
1
5928
import XCTest import SwiftUI import UniformTypeIdentifiers.UTType @testable import ViewInspector @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) final class ForEachTests: XCTestCase { func testSingleEnclosedView() throws { let data = [TestStruct(id: "0")] let view = ForEach(data) { Text($0.id) } let value = try view.inspect().forEach().text(0).string() XCTAssertEqual(value, "0") } func testSingleEnclosedViewIndexOutOfBounds() throws { let data = [TestStruct(id: "0")] let view = ForEach(data) { Text($0.id) } XCTAssertThrows( try view.inspect().forEach().text(1), "Enclosed view index '1' is out of bounds: '0 ..< 1'") } func testMultipleIdentifiableEnclosedViews() throws { let data = ["0", "1", "2"].map { TestStruct(id: $0) } let view = ForEach(data) { Text($0.id) } let value1 = try view.inspect().forEach().text(0).string() let value2 = try view.inspect().forEach().text(1).string() let value3 = try view.inspect().forEach().text(2).string() XCTAssertEqual(value1, "0") XCTAssertEqual(value2, "1") XCTAssertEqual(value3, "2") } func testSearch() throws { let data = ["0", "1", "2"].map { TestStruct(id: $0) } let view = AnyView(ForEach(data) { Text($0.id) }) XCTAssertEqual(try view.inspect().find(ViewType.ForEach.self).pathToRoot, "anyView().forEach()") XCTAssertEqual(try view.inspect().find(text: "2").pathToRoot, "anyView().forEach().text(2)") } func testMultipleNonIdentifiableEnclosedViews() throws { let data = ["0", "1", "2"].map { NonIdentifiable(id: $0) } let view = ForEach(data, id: \.id) { Text($0.id) } let value1 = try view.inspect().forEach().text(0).string() let value2 = try view.inspect().forEach().text(1).string() let value3 = try view.inspect().forEach().text(2).string() XCTAssertEqual(value1, "0") XCTAssertEqual(value2, "1") XCTAssertEqual(value3, "2") } func testMultipleEnclosedViewsIndexOutOfBounds() throws { let data = ["0", "1"].map { TestStruct(id: $0) } let view = ForEach(data) { Text($0.id) } XCTAssertThrows( try view.inspect().forEach().text(2), "Enclosed view index '2' is out of bounds: '0 ..< 2'") } func testResetsModifiers() throws { let view = ForEach(Array(0 ... 10), id: \.self) { Text("\($0)") } .padding() let sut = try view.inspect().forEach().text(5) XCTAssertEqual(sut.content.medium.viewModifiers.count, 0) } func testExtractionFromSingleViewContainer() throws { let data = ["0", "1"].map { TestStruct(id: $0) } let view = AnyView(ForEach(data) { Text($0.id) }) XCTAssertNoThrow(try view.inspect().anyView().forEach()) } func testExtractionFromMultipleViewContainer() throws { let data = ["0", "1"].map { TestStruct(id: $0) } let forEach = ForEach(data) { Text($0.id) } let view = Group { forEach; forEach } XCTAssertNoThrow(try view.inspect().group().forEach(0).text(1)) XCTAssertNoThrow(try view.inspect().group().forEach(1).text(0)) } func testRangeBased() throws { let range = 0..<5 let view = ForEach(0..<5) { Text(verbatim: "\($0)") } let sut = try view.inspect().forEach() XCTAssertEqual(sut.count, 5) XCTAssertEqual(try sut.text(4).string(), "\(range.upperBound - 1)") XCTAssertThrows( try sut.text(range.upperBound), "Enclosed view index '5' is out of bounds: '0 ..< 5'") } func testForEachIteration() throws { let view = ForEach([0, 1, 3], id: \.self) { id in Text("\(id)") } let sut = try view.inspect().forEach() var counter = 0 try sut.forEach { view in XCTAssertNoThrow(try view.text()) counter += 1 } XCTAssertEqual(counter, 3) } func testOnDelete() throws { let exp = XCTestExpectation(description: #function) let set = IndexSet(0...1) let sut = ForEach([0, 1, 3], id: \.self) { id in Text("\(id)") } .onDelete { value in XCTAssertEqual(value, set) exp.fulfill() } try sut.inspect().forEach().callOnDelete(set) wait(for: [exp], timeout: 0.1) } func testOnMove() throws { let exp = XCTestExpectation(description: #function) let set = IndexSet(0...1) let index = 2 let sut = ForEach([0, 1, 3], id: \.self) { id in Text("\(id)") } .onMove { value1, value2 in XCTAssertEqual(value1, set) XCTAssertEqual(value2, index) exp.fulfill() } try sut.inspect().forEach().callOnMove(set, index) wait(for: [exp], timeout: 0.1) } #if os(macOS) func testOnInsert() throws { guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let exp = XCTestExpectation(description: #function) let sut = ForEach([0, 1, 3], id: \.self) { id in Text("\(id)") } .onInsert(of: [UTType.pdf]) { (index, providers) in exp.fulfill() } XCTAssertThrows(try sut.inspect().forEach().callOnInsert(of: [UTType.jpeg], 0, []), "ForEach<Array<Int>, Int, Text> does not have 'onInsert(of: [\"public.jpeg\"], perform:)' modifier") try sut.inspect().forEach().callOnInsert(of: [UTType.pdf], 0, []) wait(for: [exp], timeout: 0.1) } #endif } private struct TestStruct: Identifiable { var id: String } private struct NonIdentifiable { var id: String }
mit
a502715690811150a3224a2b0aca17a7
36.518987
108
0.559548
3.952
false
true
false
false
S-Shimotori/Chalcedony
Chalcedony/Chalcedony/CCDSetting.swift
1
5211
// // CCDSetting.swift // Chalcedony // // Created by S-Shimotori on 7/2/15. // Copyright (c) 2015 S-Shimotori. All rights reserved. // import UIKit struct CCDSetting { private enum BoolForKey: String { case Initialized = "initialized" case UseTwitter = "useTwitter" case UseLaboridaChallenge = "useLaboridaChallenge" case UseLaboLocate = "useLaboLocate" } private enum NSDateForKey: String { case LastEntranceDate = "lastEntranceDate" } private enum IntForKey: String { case KaeritaiCount = "kaeritaiCount" } private enum StringForKey: String { case TwitterId = "twitterId" case MessageToTweetLaboin = "messageToTweetLaboin" case MessageToTweetLaborida = "messageToTweetLaborida" case MessageToTweetKaeritai = "messageToTweetKaeritai" } static func initializeApplication() { initialized = true lastEntranceDate = nil kaeritaiCount = 0 twitterId = nil messageToTweetLaboin = "らぼなう" messageToTweetLaborida = "らぼりだ" messageToTweetKaeritai = "研゛究゛室゛や゛だ゛ーーーーー!!!お゛う゛ち゛か゛え゛る゛ーーーーーーーーーー!!!!!!" } static var initialized: Bool { get { return getBool(.Initialized) } set(newValue) { setBool(newValue, boolForKey: .Initialized) } } static var lastEntranceDate: NSDate? { get { return getNSDate(.LastEntranceDate) } set(newValue) { setNSDate(newValue, nsDateForKey: .LastEntranceDate) } } static func isInLabo() -> Bool { if let lastEntranceDate = lastEntranceDate { return true } else { return false } } static var kaeritaiCount: Int { get { return getInt(.KaeritaiCount) } set(newValue) { setInt(newValue, intForKey: .KaeritaiCount) } } static var twitterId: String? { get { return getString(.TwitterId) } set(newValue) { setString(newValue, stringForKey: .TwitterId) } } static var useTwitter: Bool { get { return getBool(.UseTwitter) } set(newValue) { setBool(newValue, boolForKey: .UseTwitter) } } static var useLaboridaChallenge: Bool { get { return getBool(.UseLaboridaChallenge) } set(newValue) { setBool(newValue, boolForKey: .UseLaboridaChallenge) } } static var useLaboLocate: Bool { get { return getBool(.UseLaboLocate) } set(newValue) { setBool(newValue, boolForKey: .UseLaboLocate) } } static var messageToTweetLaboin: String? { get { return getString(.MessageToTweetLaboin) } set(newValue) { setString(newValue, stringForKey: .MessageToTweetLaboin) } } static var messageToTweetLaborida: String? { get { return getString(.MessageToTweetLaborida) } set(newValue) { setString(newValue, stringForKey: .MessageToTweetLaborida) } } static var messageToTweetKaeritai: String? { get { return getString(.MessageToTweetKaeritai) } set(newValue) { setString(newValue, stringForKey: .MessageToTweetKaeritai) } } private static func setBool(value: Bool, boolForKey: BoolForKey) { NSUserDefaults.standardUserDefaults().setBool(value, forKey: boolForKey.rawValue) NSUserDefaults.standardUserDefaults().synchronize() } private static func getBool(boolForKey: BoolForKey) -> Bool { return NSUserDefaults.standardUserDefaults().boolForKey(boolForKey.rawValue) } private static func setInt(value: Int, intForKey: IntForKey) { NSUserDefaults.standardUserDefaults().setInteger(value, forKey: intForKey.rawValue) NSUserDefaults.standardUserDefaults().synchronize() } private static func getInt(intForKey: IntForKey) -> Int { return NSUserDefaults.standardUserDefaults().integerForKey(intForKey.rawValue) } private static func setNSDate(value: NSDate?, nsDateForKey: NSDateForKey) { NSUserDefaults.standardUserDefaults().setObject(value, forKey: nsDateForKey.rawValue) NSUserDefaults.standardUserDefaults().synchronize() } private static func getNSDate(nsDateForKey: NSDateForKey) -> NSDate? { return NSUserDefaults.standardUserDefaults().objectForKey(nsDateForKey.rawValue) as? NSDate } private static func setString(value: String?, stringForKey: StringForKey) { NSUserDefaults.standardUserDefaults().setObject(value, forKey: stringForKey.rawValue) NSUserDefaults.standardUserDefaults().synchronize() } private static func getString(stringForKey: StringForKey) -> String? { return NSUserDefaults.standardUserDefaults().objectForKey(stringForKey.rawValue) as? String } }
mit
699bf35b04b807ea49dfdd8b5cfdc766
29.740964
99
0.627866
4.464567
false
false
false
false
nathawes/swift
test/SILGen/objc_dynamic_init.swift
22
1999
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/objc_dynamic_init.h %s | %FileCheck %s // REQUIRES: objc_interop import Foundation protocol Hoozit { init() } protocol Wotsit { init() } class Gadget: NSObject, Hoozit { required override init() { super.init() } } // CHECK-LABEL: sil hidden [ossa] @$s17objc_dynamic_init6GadgetCACycfC : $@convention(method) (@thick Gadget.Type) -> @owned Gadget // CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype %0 : $@thick Gadget.Type to $@objc_metatype Gadget.Type // CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] %1 : $@objc_metatype Gadget.Type, $Gadget // CHECK: [[INIT:%.*]] = function_ref @$s17objc_dynamic_init6GadgetCACycfcTD : $@convention(method) (@owned Gadget) -> @owned Gadget // CHECK: [[NEW_SELF:%.*]] = apply [[INIT]]([[SELF]]) : $@convention(method) (@owned Gadget) -> @owned Gadget // CHECK: return [[NEW_SELF]] // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s17objc_dynamic_init6GadgetCAA6HoozitA2aDPxycfCTW : // CHECK: function_ref @$s17objc_dynamic_init6GadgetCACycfC class Gizmo: Gadget, Wotsit { required init() { super.init() } } class Thingamabob: ObjCBaseWithInitProto { required init(proto: Int) { super.init(proto: proto) } } final class Bobamathing: Thingamabob { required init(proto: Int) { super.init(proto: proto) } } // CHECK-LABEL: sil hidden [ossa] @$s17objc_dynamic_init8callInityyF : $@convention(thin) () -> () // CHECK: [[METATYPE:%.*]] = metatype $@thick Gadget.Type // CHECK: [[CTOR:%.*]] = function_ref @$s17objc_dynamic_init6GadgetCACycfC // CHECK: [[INSTANCE:%.*]] = apply [[CTOR]]([[METATYPE]]) // CHECK: destroy_value [[INSTANCE]] func callInit() { let metatype = Gadget.self _ = metatype.init() } // CHECK-LABEL: sil_vtable Gadget { // CHECK-NOT: #Gadget.init!allocator // CHECK-LABEL: sil_vtable Gizmo { // CHECK-NOT: #Gadget.init!allocator
apache-2.0
85440c04079eb00102beb66b6e59427f
30.730159
133
0.654327
3.183121
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Array/836_Rectangle Overlap.swift
1
2207
// 836_Rectangle Overlap // https://leetcode.com/problems/rectangle-overlap // // Created by Honghao Zhang on 9/20/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner. // //Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. // //Given two (axis-aligned) rectangles, return whether they overlap. // //Example 1: // //Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] //Output: true //Example 2: // //Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] //Output: false //Notes: // //Both rectangles rec1 and rec2 are lists of 4 integers. //All coordinates in rectangles will be between -10^9 and 10^9. // import Foundation class Num836 { /// Reduce the problme to 1D, to check if both of two segments are overlapped func isRectangleOverlap(_ rect1: [Int], _ rect2: [Int]) -> Bool { return isOverlapped(rect1[0], rect1[2], rect2[0], rect2[2]) && isOverlapped(rect1[1], rect1[3], rect2[1], rect2[3]) } /// Checks if two segments are overlapped /// a-b, c-d private func isOverlapped(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool { guard b > a, d > c else { return false } if a < c { return b > c } else if a > c { return a < d } else { return true } } /// Optimized version /// a----b /// c----d /// /// a----b /// c----d private func isOverlapped2(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool { guard b > a, d > c else { return false } if a <= c, c < b { // c < b, c == b is not allowed return true } if c <= a, a < d { return true } return false } /// Check with Counterexample, this is easier to understand. /// a----b /// c----d /// /// a----b /// c----d private func isOverlapped3(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool { guard b > a, d > c else { return false } return !(b <= c || a >= d) } }
mit
478d349b7f17e41f1f87bf0de82db01f
24.356322
177
0.56709
3.081006
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/OpenIdBridge.swift
1
3458
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Managing the OpenID operations Auto-generated implementation of IOpenId specification. */ public class OpenIdBridge : BaseSecurityBridge, IOpenId, APIBridge { /** API Delegate. */ private var delegate : IOpenId? = nil /** Constructor with delegate. @param delegate The delegate implementing platform specific functions. */ public init(delegate : IOpenId?) { self.delegate = delegate } /** Get the delegate implementation. @return IOpenId delegate that manages platform specific functions.. */ public final func getDelegate() -> IOpenId? { return self.delegate } /** Set the delegate implementation. @param delegate The delegate implementing platform specific functions. */ public final func setDelegate(delegate : IOpenId) { self.delegate = delegate; } /** Invokes the given method specified in the API request object. @param request APIRequest object containing method name and parameters. @return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions. */ public override func invoke(request : APIRequest) -> APIResponse? { let response : APIResponse = APIResponse() var responseCode : Int32 = 200 var responseMessage : String = "OK" let responseJSON : String? = "null" switch request.getMethodName()! { default: // 404 - response null. responseCode = 404 responseMessage = "OpenIdBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15." } response.setResponse(responseJSON!) response.setStatusCode(responseCode) response.setStatusMessage(responseMessage) return response } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
25376b26748ec8b623543f76f1cc1f3b
34.628866
185
0.622106
5.052632
false
false
false
false
russbishop/swift
stdlib/public/core/Zip.swift
1
3545
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A sequence of pairs built out of two underlying sequences, where /// the elements of the `i`th pair are the `i`th elements of each /// underlying sequence. public func zip<Sequence1 : Sequence, Sequence2 : Sequence>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2) } /// An iterator for `Zip2Sequence`. public struct Zip2Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Iterator1.Element, Iterator2.Element) /// Construct around a pair of underlying iterators. internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } /// 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. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences, where /// the elements of the `i`th pair are the `i`th elements of each /// underlying sequence. public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> : Sequence { public typealias Stream1 = Sequence1.Iterator public typealias Stream2 = Sequence2.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip2Iterator<Stream1, Stream2> @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Construct an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 }
apache-2.0
13316ca26ce6f48ca5a8747cc8ad43e1
34.45
80
0.672779
4.333741
false
false
false
false
russbishop/swift
test/SILGen/objc_nonnull_lie_hack.swift
1
4156
// RUN: rm -rf %t/APINotes // RUN: mkdir -p %t/APINotes // RUN: %clang_apinotes -yaml-to-binary %S/Inputs/gizmo.apinotes -o %t/APINotes/gizmo.apinotesc // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -I %t/APINotes -enable-source-import -primary-file %s | FileCheck -check-prefix=SILGEN %s // RUN: %target-swift-frontend -emit-sil -O -sdk %S/Inputs -I %S/Inputs -I %t/APINotes -enable-source-import -primary-file %s | FileCheck -check-prefix=OPT %s // REQUIRES: objc_interop import Foundation import gizmo // SILGEN-LABEL: sil hidden @_TF21objc_nonnull_lie_hack10makeObjectFT_GSqCSo8NSObject_ // SILGEN: [[INIT:%.*]] = function_ref @_TFCSo8NSObjectC // SILGEN: [[NONOPTIONAL:%.*]] = apply [[INIT]] // SILGEN: [[OPTIONAL:%.*]] = unchecked_ref_cast [[NONOPTIONAL]] // OPT-LABEL: sil hidden @_TF21objc_nonnull_lie_hack10makeObjectFT_GSqCSo8NSObject_ // OPT: [[OPT:%.*]] = unchecked_ref_cast // OPT: switch_enum [[OPT]] : $Optional<NSObject>, case #Optional.none!enumelt: [[NIL:bb[0-9]+]] func makeObject() -> NSObject? { let foo: NSObject? = NSObject() if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TF21objc_nonnull_lie_hack15callClassMethod // OPT: [[METATYPE:%[0-9]+]] = metatype $@thick Gizmo.Type // OPT: [[METHOD:%[0-9]+]] = class_method [volatile] [[METATYPE]] : $@thick Gizmo.Type, #Gizmo.nonNilGizmo!1.foreign : (Gizmo.Type) -> () -> Gizmo , $@convention(objc_method) (@objc_metatype Gizmo.Type) -> @autoreleased Gizmo // OPT: [[OBJC_METATYPE:%[0-9]+]] = metatype $@objc_metatype Gizmo.Type // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJC_METATYPE]]) : $@convention(objc_method) (@objc_metatype Gizmo.Type) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo> // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo> func callClassMethod() -> Gizmo? { let foo: Gizmo? = Gizmo.nonNilGizmo() if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack18callInstanceMetho // OPT: [[METHOD:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.nonNilGizmo!1.foreign : (Gizmo) -> () -> Gizmo , $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo> func callInstanceMethod(gizmo: Gizmo) -> Gizmo? { let foo: Gizmo? = gizmo.nonNilGizmo() if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack12loadPropertyFT5gizmoCSo5Gizmo_GSqS0__ // OPT: [[GETTER:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.nonNilGizmoProperty!getter.1.foreign : (Gizmo) -> () -> Gizmo , $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo> // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo>, func loadProperty(gizmo: Gizmo) -> Gizmo? { let foo: Gizmo? = gizmo.nonNilGizmoProperty if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack19loadUnownedPropertyFT5gizmoCSo5Gizmo_GSqS0__ // OPT: [[GETTER:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.unownedNonNilGizmoProperty!getter.1.foreign : (Gizmo) -> () -> Gizmo , $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo> // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo> func loadUnownedProperty(gizmo: Gizmo) -> Gizmo? { let foo: Gizmo? = gizmo.unownedNonNilGizmoProperty if foo == nil { print("nil") } return foo }
apache-2.0
cc938b2bd34db50254003ccecbfe9e13
50.308642
225
0.651347
3.28278
false
false
false
false
KaiCode2/ResearchKit
samples/ORKSample/ORKSample/ConsentDocument.swift
10
8412
/* Copyright (c) 2015, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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 ResearchKit class ConsentDocument: ORKConsentDocument { // MARK: Properties let ipsum = [ "Vivamus laoreet erat sit amet tincidunt scelerisque. Maecenas odio sapien, molestie eu vulputate sodales, tincidunt at neque. Nunc venenatis velit et ligula dictum, eget accumsan felis consectetur. Donec scelerisque fermentum vestibulum. Nam molestie finibus mauris, id congue lectus ultrices eu. Nunc et odio vitae dui interdum dictum. Proin sagittis leo quam. Proin vulputate massa ac orci pulvinar, eget rhoncus urna congue. Sed ut vehicula tellus, eget scelerisque enim. Cras lobortis diam at faucibus scelerisque. Curabitur pharetra arcu erat, nec tincidunt mi eleifend ut. Nunc suscipit risus vitae consectetur sodales. Aenean vitae lectus odio. Phasellus diam orci, accumsan non elementum at, finibus condimentum mauris. Nullam est enim, rhoncus a rutrum sed, laoreet a magna.", "Duis euismod sollicitudin elementum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed at pharetra sapien. Pellentesque cursus laoreet interdum. Nunc mi sapien, congue vel eleifend in, luctus sit amet massa. Nam tempus metus nec mauris bibendum, vel suscipit quam aliquet. Vestibulum sagittis mi et tempus iaculis. Integer varius eros non sagittis elementum. Proin dictum magna sit amet nulla volutpat posuere eget ac mi. Cras aliquam tristique velit nec porttitor. Integer nulla ligula, vestibulum a ullamcorper non, volutpat non nibh. Integer auctor ipsum id leo pharetra, vitae dapibus augue sagittis. Proin ut diam non orci vulputate rutrum a et nulla. Maecenas in varius augue, eu pretium metus. In auctor ornare augue ac sodales.", "Aenean in ligula quis arcu rhoncus tristique. Donec ut nisl suscipit augue ornare venenatis. Suspendisse commodo nibh dignissim, congue justo quis, ultrices sapien. Aliquam at lacinia ante. Sed venenatis quam eget dui lobortis, non ullamcorper tellus molestie. Quisque tempus fringilla velit, et viverra odio accumsan quis. Suspendisse potenti. Nullam ac dolor nunc. Pellentesque nec scelerisque risus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus consectetur efficitur rutrum. Suspendisse in arcu id ex luctus aliquam quis at quam.", "Maecenas quis varius massa. Nam in dapibus turpis, ut varius eros. Proin a ex enim. Sed faucibus magna vel tincidunt facilisis. Donec id ligula vel mi suscipit sollicitudin. Nulla non magna blandit, semper augue vel, sagittis dui. Curabitur quis rutrum ex. Sed ipsum odio, mattis et dignissim sit amet, volutpat et turpis. Sed quis placerat orci. Duis vitae bibendum diam.", "Sed nec tortor sapien. Quisque tempor scelerisque vulputate. Nulla eget consequat urna. Aliquam tempus sagittis orci vel tempus. Mauris porta ante sed maximus iaculis. Etiam elit purus, pretium nec ipsum non, aliquam commodo erat. Aliquam sagittis, nibh at porta pellentesque, libero purus finibus nulla, sed consectetur tellus sem non nisl. Duis eu sollicitudin orci. Quisque tincidunt feugiat sapien ac accumsan. Nullam vitae fringilla quam.", "Integer tristique, nulla nec auctor consectetur, justo dolor sagittis erat, vel laoreet erat turpis vitae dui. Praesent purus tellus, eleifend faucibus sapien id, egestas mollis turpis. Fusce enim lorem, ornare quis ligula a, mattis feugiat diam. Praesent ullamcorper fringilla urna sollicitudin convallis. Curabitur eget dapibus ipsum, ac suscipit mauris. In hac habitasse platea dictumst. Vestibulum non hendrerit ex.", "Nulla convallis ligula ornare efficitur ullamcorper. Vivamus erat enim, malesuada sit amet dolor ac, tristique blandit felis. Praesent a ante ac nisi tempor elementum. Mauris ligula tellus, porttitor eu vehicula eget, condimentum sed nisi. Donec pharetra lacus tincidunt sapien dignissim iaculis. Duis id ultrices tortor, at congue dolor. Donec consequat fringilla leo, eu congue nulla suscipit non.", "Sed convallis, ligula vel egestas commodo, mauris nisl tincidunt arcu, id tristique est nunc sit amet felis. Curabitur tortor dolor, ullamcorper vitae pulvinar egestas, venenatis a sem. Cras sit amet maximus magna. Vivamus auctor nisi quis felis mattis, vel sagittis purus pulvinar. Nunc tristique nibh mauris, at eleifend arcu sodales nec. Curabitur rhoncus rutrum metus, ac pretium ante tempor sed. Sed vehicula placerat felis, nec interdum nisl fringilla eu. Nunc iaculis sit amet massa fringilla rhoncus. Maecenas consequat, risus eget commodo suscipit, lorem ex condimentum orci, et sollicitudin nisi eros sed lectus. Sed at erat nisl. Nunc venenatis mi tellus, vitae congue erat dictum a." ] // MARK: Initialization override init() { super.init() title = NSLocalizedString("Research Health Study Consent Form", comment: "") let sectionTypes: [ORKConsentSectionType] = [ .Overview, .DataGathering, .Privacy, .DataUse, .TimeCommitment, .StudySurvey, .StudyTasks, .Withdrawing ] sections = zip(sectionTypes, ipsum).map { sectionType, ipsum in let section = ORKConsentSection(type: sectionType) let localizedIpsum = NSLocalizedString(ipsum, comment: "") let localizedSummary = localizedIpsum.componentsSeparatedByString(".")[0] + "." section.summary = localizedSummary section.content = localizedIpsum return section } let signature = ORKConsentSignature(forPersonWithTitle: nil, dateFormatString: nil, identifier: "ConsentDocumentParticipantSignature") addSignature(signature) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ORKConsentSectionType: CustomStringConvertible { public var description: String { switch self { case .Overview: return "Overview" case .DataGathering: return "DataGathering" case .Privacy: return "Privacy" case .DataUse: return "DataUse" case .TimeCommitment: return "TimeCommitment" case .StudySurvey: return "StudySurvey" case .StudyTasks: return "StudyTasks" case .Withdrawing: return "Withdrawing" case .Custom: return "Custom" case .OnlyInDocument: return "OnlyInDocument" } } }
bsd-3-clause
9c2007074717ffad3082211e15f620df
68.528926
794
0.724441
5.267376
false
false
false
false
DayLogger/ADVOperation
Source/DelayOperation.swift
1
2139
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows how to make an operation that efficiently waits. */ import Foundation /** `DelayOperation` is an `Operation` that will simply wait for a given time interval, or until a specific `NSDate`. It is important to note that this operation does **not** use the `sleep()` function, since that is inefficient and blocks the thread on which it is called. Instead, this operation uses `dispatch_after` to know when the appropriate amount of time has passed. If the interval is negative, or the `NSDate` is in the past, then this operation immediately finishes. */ public class DelayOperation: Operation { // MARK: Types private enum Delay { case Interval(NSTimeInterval) case Date(NSDate) } // MARK: Properties private let delay: Delay // MARK: Initialization public init(interval: NSTimeInterval) { delay = .Interval(interval) super.init() } public init(until date: NSDate) { delay = .Date(date) super.init() } override public func execute() { let interval: NSTimeInterval // Figure out how long we should wait for. switch delay { case .Interval(let theInterval): interval = theInterval case .Date(let date): interval = date.timeIntervalSinceNow } guard interval > 0 else { finish() return } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { // If we were cancelled, then finish() has already been called. if !self.cancelled { self.finish() } } } override public func cancel() { super.cancel() // Cancelling the operation means we don't want to wait anymore. self.finish() } }
unlicense
424476c4b69c53f39f50d5b45222afff
26.397436
91
0.604586
4.738359
false
false
false
false
OctMon/OMExtension
OMExtension/OMExtension/Source/UIKit/OMFont.swift
1
21953
// // OMFont.swift // OMExtension // // The MIT License (MIT) // // Copyright (c) 2016 OctMon // // 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 #if !os(macOS) import UIKit public extension UIFont { struct OM { public enum Family: String { case academyEngravedLET = "Academy Engraved LET" case alNile = "Al Nile" case americanTypewriter = "American Typewriter" case appleColorEmoji = "Apple Color Emoji" case appleSDGothicNeo = "Apple SD Gothic Neo" case arial = "Arial" case arialHebrew = "Arial Hebrew" case arialRoundedMTBold = "Arial Rounded MT Bold" case avenir = "Avenir" case avenirNext = "Avenir Next" case avenirNextCondensed = "Avenir Next Condensed" case banglaSangamMN = "Bangla Sangam MN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case baskerville = "Baskerville" case bodoni72 = "Bodoni 72" case bodoni72Oldstyle = "Bodoni 72 Oldstyle" case bodoni72Smallcaps = "Bodoni 72 Smallcaps" case bodoniOrnaments = "Bodoni Ornaments" case bradleyHand = "Bradley Hand" case chalkboardSE = "Chalkboard SE" case chalkduster = "Chalkduster" case cochin = "Cochin" case copperplate = "Copperplate" case courier = "Courier" case courierNew = "Courier New" case damascus = "Damascus" case devanagariSangamMN = "Devanagari Sangam MN" case didot = "Didot" case dINAlternate = "DIN Alternate" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case dINCondensed = "DIN Condensed" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case euphemiaUCAS = "Euphemia UCAS" case farah = "Farah" case futura = "Futura" case geezaPro = "Geeza Pro" case georgia = "Georgia" case gillSans = "Gill Sans" case gujaratiSangamMN = "Gujarati Sangam MN" case gurmukhiMN = "Gurmukhi MN" case heitiSC = "Heiti SC" case heitiTC = "Heiti TC" case helvetica = "Helvetica" case helveticaNeue = "Helvetica Neue" case hiraginoKakuGothicProN = "Hiragino Kaku Gothic ProN" case hiraginoMinchoProN = "Hiragino Mincho ProN" case hoeflerText = "Hoefler Text" case iowanOldStyle = "Iowan Old Style" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case kailasa = "Kailasa" case kannadaSangamMN = "Kannada Sangam MN" case khmerSangamMN = "Khmer Sangam MN" /*@available(*, introduced=8.0)*/ case kohinoorBangla = "Kohinoor Bangla" /*@available(*, introduced=8.0)*/ case kohinoorDevanagari = "Kohinoor Devanagari" /*@available(*, introduced=8.0)*/ case laoSangamMN = "Lao Sangam MN" /*@available(*, introduced=8.0)*/ case malayalamSangamMN = "Malayalam Sangam MN" case marion = "Marion" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case markerFelt = "Marker Felt" case menlo = "Menlo" case mishafi = "Mishafi" case noteworthy = "Noteworthy" case optima = "Optima" case oriyaSangamMN = "Oriya Sangam MN" case palatino = "Palatino" case papyrus = "Papyrus" case partyLET = "Party LET" case savoyeLET = "Savoye LET" case sinhalaSangamMN = "Sinhala Sangam MN" case snellRoundhand = "Snell Roundhand" case superclarendon = "Superclarendon" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case symbol = "Symbol" case tamilSangamMN = "Tamil Sangam MN" case teluguSangamMN = "Telugu Sangam MN" case thonburi = "Thonburi" case timesNewRoman = "Times New Roman" case trebuchetMS = "Trebuchet MS" case verdana = "Verdana" case zapfDingbats = "Zapf Dingbats" case zapfino = "Zapfino" } public enum Font : String { case academyEngravedLetPlain = "AcademyEngravedLetPlain" case alNile = "AlNile" case alNileBold = "AlNile-Bold" case americanTypewriter = "AmericanTypewriter" case americanTypewriterBold = "AmericanTypewriter-Bold" case americanTypewriterCondensed = "AmericanTypewriter-Condensed" case americanTypewriterCondensedBold = "AmericanTypewriter-CondensedBold" case americanTypewriterCondensedLight = "AmericanTypewriter-CondensedLight" case americanTypewriterLight = "AmericanTypewriter-Light" case appleColorEmoji = "AppleColorEmoji" case appleSDGothicNeoBold = "AppleSDGothicNeo-Bold" case appleSDGothicNeoLight = "AppleSDGothicNeo-Light" case appleSDGothicNeoMedium = "AppleSDGothicNeo-Medium" case appleSDGothicNeoRegular = "AppleSDGothicNeo-Regular" case appleSDGothicNeoSemiBold = "AppleSDGothicNeo-SemiBold" case appleSDGothicNeoThin = "AppleSDGothicNeo-Thin" case appleSDGothicNeoUltraLight = "AppleSDGothicNeo-UltraLight" /*@available(*, introduced=9.0)*/ case arialBoldItalicMT = "Arial-BoldItalicMT" case arialBoldMT = "Arial-BoldMT" case arialHebrew = "ArialHebrew" case arialHebrewBold = "ArialHebrew-Bold" case arialHebrewLight = "ArialHebrew-Light" case arialItalicMT = "Arial-ItalicMT" case arialMT = "ArialMT" case arialRoundedMTBold = "ArialRoundedMTBold" case aSTHeitiLight = "ASTHeiti-Light" case aSTHeitiMedium = "ASTHeiti-Medium" case avenirBlack = "Avenir-Black" case avenirBlackOblique = "Avenir-BlackOblique" case avenirBook = "Avenir-Book" case avenirBookOblique = "Avenir-BookOblique" case avenirHeavyOblique = "Avenir-HeavyOblique" case avenirHeavy = "Avenir-Heavy" case avenirLight = "Avenir-Light" case avenirLightOblique = "Avenir-LightOblique" case avenirMedium = "Avenir-Medium" case avenirMediumOblique = "Avenir-MediumOblique" case avenirNextBold = "AvenirNext-Bold" case avenirNextBoldItalic = "AvenirNext-BoldItalic" case avenirNextCondensedBold = "AvenirNextCondensed-Bold" case avenirNextCondensedBoldItalic = "AvenirNextCondensed-BoldItalic" case avenirNextCondensedDemiBold = "AvenirNextCondensed-DemiBold" case avenirNextCondensedDemiBoldItalic = "AvenirNextCondensed-DemiBoldItalic" case avenirNextCondensedHeavy = "AvenirNextCondensed-Heavy" case avenirNextCondensedHeavyItalic = "AvenirNextCondensed-HeavyItalic" case avenirNextCondensedItalic = "AvenirNextCondensed-Italic" case avenirNextCondensedMedium = "AvenirNextCondensed-Medium" case avenirNextCondensedMediumItalic = "AvenirNextCondensed-MediumItalic" case avenirNextCondensedRegular = "AvenirNextCondensed-Regular" case avenirNextCondensedUltraLight = "AvenirNextCondensed-UltraLight" case avenirNextCondensedUltraLightItalic = "AvenirNextCondensed-UltraLightItalic" case avenirNextDemiBold = "AvenirNext-DemiBold" case avenirNextDemiBoldItalic = "AvenirNext-DemiBoldItalic" case avenirNextHeavy = "AvenirNext-Heavy" case avenirNextItalic = "AvenirNext-Italic" case avenirNextMedium = "AvenirNext-Medium" case avenirNextMediumItalic = "AvenirNext-MediumItalic" case avenirNextRegular = "AvenirNext-Regular" case avenirNextUltraLight = "AvenirNext-UltraLight" case avenirNextUltraLightItalic = "AvenirNext-UltraLightItalic" case avenirOblique = "Avenir-Oblique" case avenirRoman = "Avenir-Roman" case banglaSangamMN = "BanglaSangamMN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case banglaSangamMNBold = "BanglaSangamMN-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case baskerville = "Baskerville" case baskervilleBold = "Baskerville-Bold" case baskervilleBoldItalic = "Baskerville-BoldItalic" case baskervilleItalic = "Baskerville-Italic" case baskervilleSemiBold = "Baskerville-SemiBold" case baskervilleSemiBoldItalic = "Baskerville-SemiBoldItalic" case bodoniOrnamentsITCTT = "BodoniOrnamentsITCTT" case bodoniSvtyTwoITCTTBold = "BodoniSvtyTwoITCTT-Bold" case bodoniSvtyTwoITCTTBook = "BodoniSvtyTwoITCTT-Book" case bodoniSvtyTwoITCTTBookIta = "BodoniSvtyTwoITCTT-BookIta" case bodoniSvtyTwoOSITCTTBold = "BodoniSvtyTwoOSITCTT-Bold" case bodoniSvtyTwoOSITCTTBook = "BodoniSvtyTwoOSITCTT-Book" case bodoniSvtyTwoOSITCTTBookIt = "BodoniSvtyTwoOSITCTT-BookIt" case bodoniSvtyTwoSCITCTTBook = "BodoniSvtyTwoSCITCTT-Book" case bradleyHandITCTTBold = "BradleyHandITCTT-Bold" case chalkboardSEBold = "ChalkboardSE-Bold" case chalkboardSELight = "ChalkboardSE-Light" case chalkboardSERegular = "ChalkboardSE-Regular" case chalkduster = "Chalkduster" case cochin = "Cochin" case cochinBold = "Cochin-Bold" case cochinBoldItalic = "Cochin-BoldItalic" case cochinItalic = "Cochin-Italic" case copperplate = "Copperplate" case copperplateBold = "Copperplate-Bold" case copperplateLight = "Copperplate-Light" case courier = "Courier" case courierBold = "Courier-Bold" case courierBoldOblique = "Courier-BoldOblique" case courierNewPSBoldItalicMT = "CourierNewPS-BoldItalicMT" case courierNewPSBoldMT = "CourierNewPS-BoldMT" case courierNewPSItalicMT = "CourierNewPS-ItalicMT" case courierNewPSMT = "CourierNewPSMT" case courierOblique = "Courier-Oblique" case damascus = "Damascus" case damascusBold = "DamascusBold" case damascusMedium = "DamascusMedium" case damascusSemiBold = "DamascusSemiBold" case devanagariSangamMN = "DevanagariSangamMN" case devanagariSangamMNBold = "DevanagariSangamMN-Bold" case didot = "Didot" case didotBold = "Didot-Bold" case didotItalic = "Didot-Italic" case dINAlternateBold = "DINAlternate-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case dINCondensedBold = "DINCondensed-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case diwanMishafi = "DiwanMishafi" case euphemiaUCAS = "EuphemiaUCAS" case euphemiaUCASBold = "EuphemiaUCAS-Bold" case euphemiaUCASItalic = "EuphemiaUCAS-Italic" case farah = "Farah" case futuraCondensedExtraBold = "Futura-ExtraBold" case futuraCondensedMedium = "Futura-CondensedMedium" case futuraMedium = "Futura-Medium" case futuraMediumItalicm = "Futura-MediumItalic" case geezaPro = "GeezaPro" case geezaProBold = "GeezaPro-Bold" case geezaProLight = "GeezaPro-Light" case georgia = "Georgia" case georgiaBold = "Georgia-Bold" case georgiaBoldItalic = "Georgia-BoldItalic" case georgiaItalic = "Georgia-Italic" case gillSans = "GillSans" case gillSansBold = "GillSans-Bold" case gillSansBoldItalic = "GillSans-BoldItalic" case gillSansItalic = "GillSans-Italic" case gillSansLight = "GillSans-Light" case gillSansLightItalic = "GillSans-LightItalic" case gujaratiSangamMN = "GujaratiSangamMN" case gujaratiSangamMNBold = "GujaratiSangamMN-Bold" case gurmukhiMN = "GurmukhiMN" case gurmukhiMNBold = "GurmukhiMN-Bold" case helvetica = "Helvetica" case helveticaBold = "Helvetica-Bold" case helveticaBoldOblique = "Helvetica-BoldOblique" case helveticaLight = "Helvetica-Light" case helveticaLightOblique = "Helvetica-LightOblique" case helveticaNeue = "HelveticaNeue" case helveticaNeueBold = "HelveticaNeue-Bold" case helveticaNeueBoldItalic = "HelveticaNeue-BoldItalic" case helveticaNeueCondensedBlack = "HelveticaNeue-CondensedBlack" case helveticaNeueCondensedBold = "HelveticaNeue-CondensedBold" case helveticaNeueItalic = "HelveticaNeue-Italic" case helveticaNeueLight = "HelveticaNeue-Light" case helveticaNeueMedium = "HelveticaNeue-Medium" case helveticaNeueMediumItalic = "HelveticaNeue-MediumItalic" case helveticaNeueThin = "HelveticaNeue-Thin" case helveticaNeueThinItalic = "HelveticaNeue-ThinItalic" case helveticaNeueUltraLight = "HelveticaNeue-UltraLight" case helveticaNeueUltraLightItalic = "HelveticaNeue-UltraLightItalic" case helveticaOblique = "Helvetica-Oblique" case hiraKakuProNW3 = "HiraKakuProN-W3" case hiraKakuProNW6 = "HiraKakuProN-W6" case hiraMinProNW3 = "HiraMinProN-W3" case hiraMinProNW6 = "HiraMinProN-W6" case hoeflerTextBlack = "HoeflerText-Black" case hoeflerTextBlackItalic = "HoeflerText-BlackItalic" case hoeflerTextItalic = "HoeflerText-Italic" case hoeflerTextRegular = "HoeflerText-Regular" case iowanOldStyleBold = "IowanOldStyle-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case iowanOldStyleBoldItalic = "IowanOldStyle-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case iowanOldStyleItalic = "IowanOldStyle-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case iowanOldStyleRoman = "IowanOldStyle-Roman" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case kailasa = "Kailasa" case kailasaBold = "Kailasa-Bold" case kannadaSangamMN = "KannadaSangamMN" case kannadaSangamMNBold = "KannadaSangamMN-Bold" case khmerSangamMN = "KhmerSangamMN" /*@available(*, introduced=8.0)*/ case kohinoorBanglaLight = "KohinoorBangla-Light" /*@available(*, introduced=9.0)*/ case kohinoorBanglaMedium = "KohinoorBangla-Medium" /*@available(*, introduced=9.0)*/ case kohinoorBanglaRegular = "KohinoorBangla-Regular" /*@available(*, introduced=9.0)*/ case kohinoorDevanagariLight = "KohinoorDevanagari-Light" /*@available(*, introduced=8.0)*/ case kohinoorDevanagariMedium = "KohinoorDevanagari-Medium" /*@available(*, introduced=8.0)*/ case kohinoorDevanagariBook = "KohinoorDevanagari-Book" /*@available(*, introduced=8.0)*/ case laoSangamMN = "LaoSangamMN" /*@available(*, introduced=8.0)*/ case malayalamSangamMN = "MalayalamSangamMN" case malayalamSangamMNBold = "MalayalamSangamMN-Bold" case marionBold = "Marion-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case marionItalic = "Marion-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case marionRegular = "Marion-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case markerFeltThin = "MarkerFelt-Thin" case markerFeltWide = "MarkerFelt-Wide" case menloBold = "Menlo-Bold" case menloBoldItalic = "Menlo-BoldItalic" case menloItalic = "Menlo-Italic" case menloRegular = "Menlo-Regular" case noteworthyBold = "Noteworthy-Bold" case noteworthyLight = "Noteworthy-Light" case optimaBold = "Optima-Bold" case optimaBoldItalic = "Optima-BoldItalic" case optimaExtraBlack = "Optima-ExtraBold" case optimaItalic = "Optima-Italic" case optimaRegular = "Optima-Regular" case oriyaSangamMN = "OriyaSangamMN" case oriyaSangamMNBold = "OriyaSangamMN-Bold" case palatinoBold = "Palatino-Bold" case palatinoBoldItalic = "Palatino-BoldItalic" case palatinoItalic = "Palatino-Italic" case palatinoRoman = "Palatino-Roman" case papyrus = "Papyrus" case papyrusCondensed = "Papyrus-Condensed" case partyLetPlain = "PartyLetPlain" case savoyeLetPlain = "SavoyeLetPlain" case sinhalaSangamMN = "SinhalaSangamMN" case sinhalaSangamMNBold = "SinhalaSangamMN-Bold" case snellRoundhand = "SnellRoundhand" case snellRoundhandBlack = "SnellRoundhand-Black" case snellRoundhandBold = "SnellRoundhand-Bold" case sTHeitiSCLight = "STHeitiSC-Light" case sTHeitiSCMedium = "STHeitiSC-Medium" case sTHeitiTCLight = "STHeitiTC-Light" case sTHeitiTCMedium = "STHeitiTC-Medium" case superclarendonBlack = "Superclarendon-Black" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonBlackItalic = "Superclarendon-BalckItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonBold = "Superclarendon-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonBoldItalic = "Superclarendon-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonItalic = "Superclarendon-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonLight = "Superclarendon-Light" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonLightItalic = "Superclarendon-LightItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case superclarendonRegular = "Superclarendon-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/ case symbol = "Symbol" case tamilSangamMN = "TamilSangamMN" case tamilSangamMNBold = "TamilSangamMN-Bold" case teluguSangamMN = "TeluguSangamMN" case teluguSangamMNBold = "TeluguSangamMN-Bold" case thonburi = "Thonburi" case thonburiBold = "Thonburi-Bold" case thonburiLight = "Thonburi-Light" case timesNewRomanPSBoldItalicMT = "TimesNewRomanPS-BoldItalic" case timesNewRomanPSBoldMT = "TimesNewRomanPS-Bold" case timesNewRomanPSItalicMT = "TimesNewRomanPS-ItalicMT" case timesNewRomanPSMT = "TimesNewRomanPSMT" case trebuchetBoldItalic = "Trebuchet-BoldItalic" case trebuchetMS = "TrebuchetMS" case trebuchetMSBold = "TrebuchetMS-Bold" case trebuchetMSItalic = "TrebuchetMS-Italic" case verdana = "Verdana" case verdanaBold = "Verdana-Bold" case verdanaBoldItalic = "Verdana-BoldItalic" case verdanaItalic = "Verdana-Italic" } } convenience init?(omFontName: OM.Font, size: CGFloat) { self.init(name: omFontName.rawValue, size: size) } } #endif
mit
b0ee49b18ce7f7fccb43b6e4450c0485
58.817439
173
0.651073
4.73329
false
false
false
false
naoyashiga/Spring
Spring/LoadingView.swift
5
2876
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class LoadingView: UIView { @IBOutlet public weak var indicatorView: SpringView! override public func awakeFromNib() { let animation = CABasicAnimation() animation.keyPath = "transform.rotation.z" animation.fromValue = degreesToRadians(0) animation.toValue = degreesToRadians(360) animation.duration = 0.9 animation.repeatCount = HUGE indicatorView.layer.addAnimation(animation, forKey: "") } class func designCodeLoadingView() -> UIView { return NSBundle(forClass: self).loadNibNamed("LoadingView", owner: self, options: nil)[0] as UIView } } public extension UIView { struct LoadingViewConstants { static let Tag = 1000 } public func showLoading() { if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) { // If loading view is already found in current view hierachy, do nothing return } let loadingXibView = LoadingView.designCodeLoadingView() loadingXibView.frame = self.bounds loadingXibView.tag = LoadingViewConstants.Tag self.addSubview(loadingXibView) loadingXibView.alpha = 0 spring(0.7, { loadingXibView.alpha = 1 }) } public func hideLoading() { if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) { loadingXibView.alpha = 1 springWithCompletion(0.7, { loadingXibView.alpha = 0 loadingXibView.transform = CGAffineTransformMakeScale(3, 3) }, { (completed) -> Void in loadingXibView.removeFromSuperview() }) } } }
mit
41bfaeb7adbe0aab0569d77865aa9e51
34.073171
107
0.68185
4.941581
false
false
false
false
firebase/firebase-ios-sdk
FirebaseCombineSwift/Tests/Unit/Auth/SignInWithCustomTokenTests.swift
2
4776
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Combine import XCTest import FirebaseAuth class SignInWithCustomTokenTests: XCTestCase { override class func setUp() { FirebaseApp.configureForTests() } override class func tearDown() { FirebaseApp.app()?.delete { success in if success { print("Shut down app successfully.") } else { print("💥 There was a problem when shutting down the app..") } } } override func setUp() { do { try Auth.auth().signOut() } catch {} } static let apiKey = Credentials.apiKey static let accessTokenTimeToLive: TimeInterval = 60 * 60 static let refreshToken = "REFRESH_TOKEN" static let accessToken = "ACCESS_TOKEN" static let email = "[email protected]" static let password = "secret" static let localID = "LOCAL_ID" static let displayName = "Johnny Appleseed" static let passwordHash = "UkVEQUNURUQ=" static let oAuthSessionID = "sessionID" static let oAuthRequestURI = "requestURI" static let googleID = "GOOGLE_ID" static let googleDisplayName = "Google Doe" static let googleEmail = "[email protected]" static let customToken = "CUSTOM_TOKEN" class MockVerifyCustomTokenResponse: FIRVerifyCustomTokenResponse { override var idToken: String { return SignInWithCustomTokenTests.accessToken } override var refreshToken: String { return SignInWithCustomTokenTests.refreshToken } override var approximateExpirationDate: Date { Date(timeIntervalSinceNow: SignInWithCustomTokenTests.accessTokenTimeToLive) } } class MockGetAccountInfoResponseUser: FIRGetAccountInfoResponseUser { override var localID: String? { return SignInWithCustomTokenTests.localID } override var displayName: String { return SignInWithCustomTokenTests.displayName } override var email: String? { return SignInWithCustomTokenTests.email } override var passwordHash: String? { return SignInWithCustomTokenTests.passwordHash } } class MockGetAccountInfoResponse: FIRGetAccountInfoResponse { override var users: [FIRGetAccountInfoResponseUser] { return [MockGetAccountInfoResponseUser(dictionary: [:])] } } class MockAuthBackend: AuthBackendImplementationMock { override func verifyCustomToken(_ request: FIRVerifyCustomTokenRequest, callback: @escaping FIRVerifyCustomTokenResponseCallback) { XCTAssertEqual(request.apiKey, SignInWithCustomTokenTests.apiKey) XCTAssertEqual(request.token, SignInWithCustomTokenTests.customToken) XCTAssertTrue(request.returnSecureToken) callback(MockVerifyCustomTokenResponse(), nil) } override func getAccountInfo(_ request: FIRGetAccountInfoRequest, callback: @escaping FIRGetAccountInfoResponseCallback) { XCTAssertEqual(request.apiKey, SignInWithCustomTokenTests.apiKey) XCTAssertEqual(request.accessToken, SignInWithCustomTokenTests.accessToken) let response = MockGetAccountInfoResponse() callback(response, nil) } } func testSignInWithCustomToken() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) var cancellables = Set<AnyCancellable>() let userSignInExpectation = expectation(description: "User signed in") // when Auth.auth() .signIn(withCustomToken: SignInWithCustomTokenTests.customToken) .sink { completion in switch completion { case .finished: print("Finished") case let .failure(error): XCTFail("💥 Something went wrong: \(error)") } } receiveValue: { authDataResult in let user = authDataResult.user XCTAssertNotNil(user) XCTAssertEqual(user.uid, SignInWithCustomTokenTests.localID) XCTAssertEqual(user.displayName, SignInWithCustomTokenTests.displayName) XCTAssertEqual(user.email, SignInWithCustomTokenTests.email) XCTAssertFalse(user.isAnonymous) XCTAssertEqual(user.providerData.count, 0) userSignInExpectation.fulfill() } .store(in: &cancellables) // then wait(for: [userSignInExpectation], timeout: expectationTimeout) } }
apache-2.0
07e4ed05061c4ca4d5a6dcf624b733fd
34.864662
95
0.725367
4.837728
false
true
false
false
Herb-Sun/OKKLineSwift
OKKLineSwift/Models/Indicators/OKEMAVOLUMEModel.swift
1
3041
// // OKKLineSwift // // Copyright © 2016年 Herb - https://github.com/Herb-Sun/OKKLineSwift // // 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 struct OKEMAVOLUMEModel { let indicatorType: OKIndicatorType let klineModels: [OKKLineModel] init(indicatorType: OKIndicatorType, klineModels: [OKKLineModel]) { self.indicatorType = indicatorType self.klineModels = klineModels } public func fetchDrawEMAVOLUMEData(drawRange: NSRange?) -> [OKKLineModel] { var datas = [OKKLineModel]() guard klineModels.count > 0 else { return datas } for (index, model) in klineModels.enumerated() { switch indicatorType { case .EMA_VOLUME(let days): var values = [Double?]() for (idx, day) in days.enumerated() { let previousEMA_VOLUME: Double? = index > 0 ? datas[index - 1].EMA_VOLUMEs?[idx] : nil values.append(handleEMA_VOLUME(day: day, model: model, index: index, previousEMA_VOLUME: previousEMA_VOLUME)) } model.EMA_VOLUMEs = values default: break } datas.append(model) } if let range = drawRange { return Array(datas[range.location..<range.location+range.length]) } else { return datas } } private func handleEMA_VOLUME(day: Int, model: OKKLineModel, index: Int, previousEMA_VOLUME: Double?) -> Double? { if day <= 0 || index < (day - 1) { return nil } else { if previousEMA_VOLUME != nil { return Double(day - 1) / Double(day + 1) * previousEMA_VOLUME! + 2 / Double(day + 1) * model.volume } else { return 2 / Double(day + 1) * model.volume } } } }
mit
3c2395df815e037d697e7b80e0aae55c
36.506173
129
0.60632
4.243017
false
false
false
false
CodaFi/swiftz
Tests/SwiftzTests/ListSpec.swift
2
6216
// // ListSpec.swift // Swiftz // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015-2016 TypeLift. All rights reserved. // import XCTest import Swiftz import SwiftCheck #if SWIFT_PACKAGE import Operadics import Swiftx #endif /// Generates an array of arbitrary values. extension List : Arbitrary where Element : Arbitrary { public static var arbitrary : Gen<List<Element>> { return [Element].arbitrary.map(List.init) } public static func shrink(_ xs : List<Element>) -> [List<Element>] { return List.init <^> [Element].shrink(xs.map(identity)) } } class ListSpec : XCTestCase { func testProperties() { property("Lists of Equatable elements obey reflexivity") <- forAll { (l : List<Int>) in return l == l } property("Lists of Equatable elements obey symmetry") <- forAll { (x : List<Int>) in return forAll { (y : List<Int>) in return (x == y) == (y == x) } } property("Lists of Equatable elements obey transitivity") <- forAll { (x : List<Int>) in return forAll { (y : List<Int>) in let inner = forAll { (z : List<Int>) in return ((x == y) && (y == z)) ==> (x == z) } return inner } } property("Lists of Equatable elements obey negation") <- forAll { (x : List<Int>) in return forAll { (y : List<Int>) in return (x != y) == !(x == y) } } property("Lists of Comparable elements obey reflexivity") <- forAll { (l : List<Int>) in return l == l } property("List obeys the Functor identity law") <- forAll { (x : List<Int>) in return (x.fmap(identity)) == identity(x) } property("List obeys the Functor composition law") <- forAll { (_ f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in return forAll { (x : List<Int>) in return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow)) } } property("List obeys the Applicative identity law") <- forAll { (x : List<Int>) in return (List.pure(identity) <*> x) == x } property("List obeys the Applicative homomorphism law") <- forAll { (_ f : ArrowOf<Int, Int>, x : Int) in return (List.pure(f.getArrow) <*> List.pure(x)) == List.pure(f.getArrow(x)) } property("List obeys the Applicative interchange law") <- forAll { (fu : List<ArrowOf<Int, Int>>) in return forAll { (y : Int) in let u = fu.fmap { $0.getArrow } return (u <*> List.pure(y)) == (List.pure({ f in f(y) }) <*> u) } } // Swift unroller can't handle our scale; Use only small lists. property("List obeys the first Applicative composition law") <- forAll { (fl : List<ArrowOf<Int8, Int8>>, gl : List<ArrowOf<Int8, Int8>>, x : List<Int8>) in return (fl.count <= 3 && gl.count <= 3) ==> { let f = fl.fmap({ $0.getArrow }) let g = gl.fmap({ $0.getArrow }) return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x)) } } property("List obeys the second Applicative composition law") <- forAll { (fl : List<ArrowOf<Int8, Int8>>, gl : List<ArrowOf<Int8, Int8>>, x : List<Int8>) in return (fl.count <= 3 && gl.count <= 3) ==> { let f = fl.fmap({ $0.getArrow }) let g = gl.fmap({ $0.getArrow }) return (List.pure(curry(•)) <*> f <*> g <*> x) == (f <*> (g <*> x)) } } property("List obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, Int>) in let f : (Int) -> List<Int> = List<Int>.pure • fa.getArrow return (List<Int>.pure(a) >>- f) == f(a) } property("List obeys the Monad right identity law") <- forAll { (m : List<Int>) in return (m >>- List<Int>.pure) == m } property("List obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, Int>, ga : ArrowOf<Int, Int>) in let f : (Int) -> List<Int> = List<Int>.pure • fa.getArrow let g : (Int) -> List<Int> = List<Int>.pure • ga.getArrow return forAll { (m : List<Int>) in return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g }) } } property("List obeys the Monoidal left identity law") <- forAll { (x : List<Int8>) in return (x <> List()) == x } property("List obeys the Monoidal right identity law") <- forAll { (x : List<Int8>) in return (List() <> x) == x } property("List can cycle into an infinite list") <- forAll { (x : List<Int8>) in return !x.isEmpty ==> { let cycle = x.cycle() return forAll { (n : Positive<Int>) in // broken up as 'too complex' for compiler let range = (0...UInt(n.getPositive)) let transform = { i in cycle[i] == x[(i % x.count)] } let filter = { $0 == false } return range.map(transform).filter(filter).isEmpty } } } property("isEmpty behaves") <- forAll { (xs : List<Int>) in return xs.isEmpty == (xs.count == 0) } property("map behaves") <- forAll { (xs : List<Int>) in return xs.map({ $0 + 1 }) == xs.fmap({ $0 + 1 }) } property("map behaves") <- forAll { (xs : List<Int>) in let fs = { List<Int>.replicate(2, value: $0) } return (xs >>- fs) == xs.map(fs).reduce(+, initial: List()) } property("filter behaves") <- forAll { (pred : ArrowOf<Int, Bool>) in return forAll { (xs : List<Int>) in return xs.filter(pred.getArrow).reduce({ acc, i in acc && pred.getArrow(i) }, initial: true) } } property("take behaves") <- forAll { (limit : UInt) in return forAll { (xs : List<Int>) in return xs.take(limit).count <= limit } } property("drop behaves") <- forAll { (limit : UInt) in return forAll { (xs : List<Int>) in let l = xs.drop(limit) if xs.count >= limit { return l.count == (xs.count - limit) } return l == [] } } property("scanl behaves") <- forAll { (withArray : List<Int>) in let scanned = withArray.scanl(curry(+), initial: 0) switch withArray.match { case .Nil: return scanned == [0] case let .Cons(x, xs): let rig = (List.pure(0) + xs.scanl(curry(+), initial: 0 + x)) return scanned == rig } } property("sequence occurs in order") <- forAll { (xs : [String]) in let seq = sequence(xs.map(List.pure)) return forAllNoShrink(Gen.pure(seq)) { ss in return ss.head! == xs } } } #if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) static var allTests = testCase([ ("testProperties", testProperties), ]) #endif }
bsd-3-clause
89b331bf50715268718b589f825611d1
30.02
159
0.588008
3.063704
false
false
false
false
Dimentar/SwiftGen
swiftgen-cli/templates.swift
1
1658
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Commander import PathKit import GenumKit let allSubcommands = ["colors", "images", "storyboards", "strings", "fonts"] let templatesCommand = command( Option<String>("only", "", flag: "l", description: "If specified, only list templates valid for that specific subcommand") { guard allSubcommands.contains($0) else { throw ArgumentError.InvalidType(value: $0, type: "subcommand", argument: "--only") } return $0 }) { onlySubcommand in let customTemplates = (try? appSupportTemplatesPath.children()) ?? [] let bundledTemplates = (try? bundledTemplatesPath.children()) ?? [] let printTemplates = { (prefix: String, list: [Path]) in for file in list where file.lastComponent.hasPrefix("\(prefix)-") && file.`extension` == "stencil" { let basename = file.lastComponentWithoutExtension let idx = basename.startIndex.advancedBy(prefix.characters.count+1) let name = basename[idx..<basename.endIndex] print(" - \(name)") } } let subcommandsToList = onlySubcommand.isEmpty ? allSubcommands : [onlySubcommand] for prefix in subcommandsToList { print("\(prefix):") print(" custom:") printTemplates(prefix, customTemplates) print(" bundled:") printTemplates(prefix, bundledTemplates) } print("---") print("You can add custom templates in ~/Library/Application Support/SwiftGen/templates.") print("Simply name them 'subcmd-customname.stencil' where subcmd is one of the swiftgen subcommand,") print("namely " + allSubcommands.map({"\($0)-xxx.stencil"}).joinWithSeparator(", ") + ".") }
mit
25988576a17021ca5bae05f618e8d304
35.043478
104
0.689988
4.155388
false
false
false
false
zzw19880707/shadow
Sources/main.swift
1
800
// // main.swift // PerfectTemplate // // Created by Kyle Jessup on 2015-11-05. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectLib import PerfectHTTP import PerfectHTTPServer //启动 do { DBBaseManager().createTable() try SDServer().startup() } catch PerfectError.networkError(let err, let msg) { print("网络出现错误:\(err) \(msg)") }
apache-2.0
a8a819c8bd0ebaac642d6fe05aabaa38
25.066667
80
0.557545
4.494253
false
false
false
false
BananosTeam/CreativeLab
OAuthSwift-0.5.2/OAuthSwiftTests/TestServer.swift
1
3434
// // TestServer.swift // OAuthSwift // // Created by phimage on 17/11/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import Foundation import Swifter class TestServer { let server: HttpServer var port: in_port_t = 8765 var baseurl: String { return "http://localhost:\(self.port)/" } var v1: String { return "\(baseurl)1/" } var authorizeURL: String { return "\(v1)authorize" } var accessTokenURL: String { return "\(v1)accessToken" } var requestTokenURL: String { return "\(v1)requestToken" } var v2: String { return "\(baseurl)2/" } var authorizeURLV2: String { return "\(v2)authorize" } var accessTokenURLV2: String { return "\(v2)accessToken" } var expireURLV2: String { return "\(v2)expire" } enum AccessReturnType { case JSON, Data } var accessReturnType: AccessReturnType = .Data let oauth_token = "accesskey" let oauth_token_secret = "accesssecret" let valid_key = "key" let valid_secret = "key" init() { server = HttpServer() server["1/requestToken"] = { request in guard request.method == "POST" else { return .BadRequest(.Text("Method must be POST")) } // TODO check request.headers["authorization"] for consumer key, etc... let oauth_token = "requestkey" let oauth_token_secret = "requestsecret" return .OK(.Text("oauth_token=\(oauth_token)&oauth_token_secret=\(oauth_token_secret)" as String) ) } server["1/accessToken"] = { request in guard request.method == "POST" else { return HttpResponse.BadRequest(.Text("Method must be POST")) } // TODO check request.headers["authorization"] for consumer key, etc... return .OK(.Text("oauth_token=\(self.oauth_token)&oauth_token_secret=\(self.oauth_token_secret)" as String) ) } /* server["1/authorize"] = { .OK(.HTML("You asked for " + $0.url)) } server["/callback"] = { .OK(.HTML("You asked for " + $0.url)) } */ server["2/accessToken"] = { request in guard request.method == "POST" else { return .BadRequest(.Text("Method must be POST")) } /*guard let autho = request.headers["authorization"] where autho == "Beared" else { return HttpResponse.BadRequest }*/ // TODO check body for consumer key, etc... switch self.accessReturnType { case .JSON: return .OK(.Json(["access_token":self.oauth_token])) case .Data: return .OK(.Text("access_token=\(self.oauth_token)" as String)) } } server["2/authorize"] = { request in return .OK(HttpResponseBody.Html("You asked for \(request.path)")) } server["2/expire"] = { request in return HttpResponse.RAW(401, "Unauthorized",["WWW-Authenticate": "Bearer realm=\"example\",error=\"invalid_token\",error_description=\"The access token expired\""], nil) } } func start() throws { try server.start(self.port) } func stop() { self.server.stop() } }
mit
80afa181b3fc8242873a809990fcb98a
30.796296
181
0.54413
4.334596
false
false
false
false
HTWDD/htwcampus
HTWDD/Core/UI/Views/ReactiveButton.swift
2
1340
// // IntroButton.swift // HTWDD // // Created by Fabian Ehlert on 12.10.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import UIKit class ReactiveButton: UIButton { var isHighlightable: Bool = true override var isHighlighted: Bool { didSet { self.isHighlighted ? self.highlight(animated: true) : self.unhighlight(animated: true) } } override var isEnabled: Bool { didSet { self.alpha = self.isEnabled ? 1 : 0.3 } } } // MARK: - Highlightable extension ReactiveButton: Highlightable { enum Const { static let highlightedScale: CGFloat = 0.95 static let normalAlpha: CGFloat = 1.0 static let highlightedAlpha: CGFloat = 0.6 } func highlight(animated: Bool) { let animations: () -> Void = { self.transform = CGAffineTransform.identity.scaledBy(x: Const.highlightedScale, y: Const.highlightedScale) self.alpha = Const.highlightedAlpha } if !animated { animations() } else { let duration = 0.08 UIView.animate(withDuration: duration, animations: animations) } } func unhighlight(animated: Bool) { let animations: () -> Void = { self.transform = CGAffineTransform.identity self.alpha = Const.normalAlpha } if !animated { animations() } else { let duration = 0.18 UIView.animate(withDuration: duration, animations: animations) } } }
mit
db3a61dfb90448ad2bf50c0445abf079
19.6
109
0.68932
3.424552
false
false
false
false
lyle-luan/firefox-ios
Extensions/SendTo/ActionViewController.swift
2
6597
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage import Snappy protocol LoginViewControllerDelegate { func loginViewControllerDidCancel(loginViewController: LoginViewController) -> Void } /*! The LoginViewController is a viewcontroller that we show if the user is not logged in yet. It not clear yet what needs to be done so consider this a temporary placeholder for now. */ class LoginViewController: UIViewController { var delegate: LoginViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() let label = UILabel() label.text = NSLocalizedString("TODO Not logged in.", comment: "") view.addSubview(label) label.snp_makeConstraints { (make) -> () in make.center.equalTo(label.superview!) return } navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancel") } func cancel() { delegate?.loginViewControllerDidCancel(self) } } protocol ClientPickerViewControllerDelegate { func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) -> Void func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [Client]) -> Void } /*! The ClientPickerViewController displays a list of clients associated with the provided Account. The user can select a number of devices and hit the Send button. This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. That is up to it's delegate, who can listen for cancellation and success events. */ class ClientPickerViewController: UITableViewController { var profile: Profile? var clientPickerDelegate: ClientPickerViewControllerDelegate? var clients: [Client] = [] override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Send To Device", comment: "") refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancel") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) reloadClients() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return clients.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.font = UIFont(name: "FiraSans-Regular", size: 17) cell.textLabel?.text = NSLocalizedString("Send to ", comment: "") + clients[indexPath.row].name // TODO This needs a localized format string return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) clientPickerDelegate?.clientPickerViewController(self, didPickClients: [clients[indexPath.row]]) } private func reloadClients() { profile?.clients.getAll( { response in self.clients = response dispatch_async(dispatch_get_main_queue()) { self.refreshControl?.endRefreshing() self.tableView.reloadData() } }, error: { err in // TODO: Figure out a good way to handle this. print("Error: could not load clients: ") println(err) }) } func refresh() { reloadClients() } func cancel() { self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil) } } /*! The ActionViewController is the initial viewcontroller that is presented (full screen) when the share extension is activated. Depending on whether the user is logged in or not, this viewcontroller will present either a Login or ClientPicker. */ @objc(ActionViewController) class ActionViewController: UINavigationController, ClientPickerViewControllerDelegate, LoginViewControllerDelegate { var profile: Profile? var sharedItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in if error == nil && item != nil { self.sharedItem = item let accountManager = AccountProfileManager(loginCallback: { _ in () }, logoutCallback: { _ in () }) self.profile = accountManager.getAccount() if self.profile == nil { let loginViewController = LoginViewController() loginViewController.delegate = self self.pushViewController(loginViewController, animated: false) } else { let clientPickerViewController = ClientPickerViewController() clientPickerViewController.clientPickerDelegate = self clientPickerViewController.profile = self.profile self.pushViewController(clientPickerViewController, animated: false) } } else { self.extensionContext!.completeRequestReturningItems([], completionHandler: nil); } }) } func finish() { self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil) } func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [Client]) { profile?.clients.sendItem(self.sharedItem!, toClients: clients) finish() } func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) { finish() } func loginViewControllerDidCancel(loginViewController: LoginViewController) { finish() } }
mpl-2.0
cf636673b071e6c4901961877f913d62
37.805882
148
0.680158
5.832891
false
false
false
false
infobip/mobile-messaging-sdk-ios
Example/Tests/MobileMessagingTests/PrimaryDeviceTests.swift
1
2535
// // File.swift // MobileMessagingExample // // Created by Andrey Kadochnikov on 26/06/2018. // import XCTest @testable import MobileMessaging class PrimaryDeviceTests: MMTestCase { func testDataPersisting() { MMTestCase.startWithCorrectApplicationCode() XCTAssertFalse(MobileMessaging.getInstallation()!.isPrimaryDevice) MobileMessaging.sharedInstance!.isPrimaryDevice = true waitForExpectations(timeout: 20, handler: { _ in XCTAssertTrue(MobileMessaging.getInstallation()!.isPrimaryDevice) let installation = MobileMessaging.getInstallation()! XCTAssertNotNil(MMInstallation.delta!["isPrimaryDevice"]) XCTAssertTrue(installation.isPrimaryDevice) }) } func testPutSync() { MMTestCase.startWithCorrectApplicationCode() weak var expectation = self.expectation(description: "sync completed") mobileMessagingInstance.pushRegistrationId = "123" let remoteApiProvider = RemoteAPIProviderStub() remoteApiProvider.patchInstanceClosure = { _, _, _, _ -> UpdateInstanceDataResult in return UpdateInstanceDataResult.Success(EmptyResponse()) } mobileMessagingInstance.remoteApiProvider = remoteApiProvider let installation = MobileMessaging.getInstallation()! XCTAssertFalse(installation.isPrimaryDevice) installation.isPrimaryDevice = true MobileMessaging.saveInstallation(installation) { (error) in expectation?.fulfill() } waitForExpectations(timeout: 20, handler: { _ in let installation = MobileMessaging.getInstallation()! XCTAssertNil(MMInstallation.delta?["isPrimaryDevice"]) XCTAssertTrue(installation.isPrimaryDevice) }) } func testGetSync() { MMTestCase.startWithCorrectApplicationCode() weak var expectation = self.expectation(description: "sync completed") mobileMessagingInstance.pushRegistrationId = "123" let remoteApiProvider = RemoteAPIProviderStub() remoteApiProvider.patchInstanceClosure = { _, _, _, _ -> UpdateInstanceDataResult in return UpdateInstanceDataResult.Success(EmptyResponse()) } mobileMessagingInstance.remoteApiProvider = remoteApiProvider MobileMessaging.fetchInstallation { (installation, error) in XCTAssertFalse(installation!.isPrimaryDevice) expectation?.fulfill() } waitForExpectations(timeout: 20, handler: { _ in let installation = MobileMessaging.getInstallation()! XCTAssertNil(MMInstallation.delta?["isPrimaryDevice"]) XCTAssertFalse(installation.isPrimaryDevice) }) } }
apache-2.0
19c30dc1b5823f375a8bed5e8af35f3c
32.8
86
0.752663
5.248447
false
true
false
false
RoverPlatform/rover-ios-beta
Sources/Models/BarcodeBlock.swift
2
1208
// // BarcodeBlock.swift // Rover // // Created by Sean Rucker on 2018-04-24. // Copyright © 2018 Rover Labs Inc. All rights reserved. // public struct BarcodeBlock: Block { public var background: Background public var barcode: Barcode public var border: Border public var id: String public var name: String public var insets: Insets public var opacity: Double public var position: Position public var tapBehavior: BlockTapBehavior public var keys: [String: String] public var tags: [String] public var conversion: Conversion? public init(background: Background, barcode: Barcode, border: Border, id: String, name: String, insets: Insets, opacity: Double, position: Position, tapBehavior: BlockTapBehavior, keys: [String: String], tags: [String], conversion: Conversion?) { self.background = background self.barcode = barcode self.border = border self.id = id self.name = name self.insets = insets self.opacity = opacity self.position = position self.tapBehavior = tapBehavior self.keys = keys self.tags = tags self.conversion = conversion } }
mit
b84c330e939ff813ef6f0b5664fceefc
30.763158
250
0.664457
4.405109
false
false
false
false
hirohisa/RxSwift
RxTests/RxSwiftTests/Tests/Observable+StandardSequenceOperatorsTest.swift
3
86815
// // Observable+StandardSequenceOperatorsTest.swift // Rx // // Created by Krunoslav Zaher on 2/17/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift class ObservableStandardSequenceOperators : RxTest { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } } func isPrime(i: Int) -> Bool { if i <= 1 { return false } var max = Int(sqrt(Float(i))) for (var j = 2; j <= max; ++j) { if i % j == 0 { return false } } return true } // where extension ObservableStandardSequenceOperators { func test_whereComplete() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600), next(610, 12), error(620, testError), completed(630) ]) let res = scheduler.start { () -> Observable<Int> in return xs >- filter { (num: Int) -> Bool in invoked++; return isPrime(num); } } XCTAssertEqual(res.messages, [ next(230, 3), next(340, 5), next(390, 7), next(580, 11), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(9, invoked) } func test_whereTrue() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) let res = scheduler.start { () -> Observable<Int> in return xs >- filter { (num: Int) -> Bool in invoked++ return true } } XCTAssertEqual(res.messages, [ next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(9, invoked) } func test_whereFalse() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) let res = scheduler.start { () -> Observable<Int> in return xs >- filter { (num: Int) -> Bool in invoked++ return false } } XCTAssertEqual(res.messages, [ completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(9, invoked) } func test_whereDisposed() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) let res = scheduler.start(400) { () -> Observable<Int> in return xs >- filter { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(230, 3), next(340, 5), next(390, 7) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) XCTAssertEqual(5, invoked) } } // takeWhile extension ObservableStandardSequenceOperators { func testTakeWhile_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(330), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(330) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 330) ]) XCTAssertEqual(4, invoked) } func testTakeWhile_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) XCTAssertEqual(6, invoked) } func testTakeWhile_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), error(270, testError), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), error(270, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) XCTAssertEqual(2, invoked) } func testTakeWhile_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) XCTAssertEqual(6, invoked) } func testTakeWhile_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start(300) { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 300) ]) XCTAssertEqual(3, invoked) } func testTakeWhile_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start(400) { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) XCTAssertEqual(6, invoked) } func testTakeWhile_Zero() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start(300) { () -> Observable<Int> in return xs >- takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ completed(205) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 205) ]) XCTAssertEqual(1, invoked) } func testTakeWhile_Index1() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int, index) -> Bool in return index < 5 } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(350) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 350) ]) } func testTakeWhile_Index2() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), completed(400) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int, index) -> Bool in return index >= 0 } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), completed(400) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } func testTakeWhile_Index_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), error(400, testError) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs >- takeWhile { (num: Int, index) -> Bool in return index >= 0 } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), error(400, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } } // map // these test are not port from Rx extension ObservableStandardSequenceOperators { func testMap_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), ]) let res = scheduler.start { xs >- map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(300) ]) let res = scheduler.start { xs >- map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Range() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), completed(300) ]) let res = scheduler.start { xs >- map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), next(230, 2 * 2), next(240, 4 * 2), completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), error(300, testError) ]) let res = scheduler.start { xs >- map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), next(230, 2 * 2), next(240, 4 * 2), error(300, testError) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), error(300, testError) ]) let res = scheduler.start(290) { xs >- map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), next(230, 2 * 2), next(240, 4 * 2), ] let correctSubscriptions = [ Subscription(200, 290) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), error(300, testError) ]) let res = scheduler.start { xs >- mapOrDie { $0 < 2 ? success($0 * 2) : failure(testError) } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), error(230, testError) ] let correctSubscriptions = [ Subscription(200, 230) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), ]) let res = scheduler.start { xs >- mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(300) ]) let res = scheduler.start { xs >- mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Range() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), completed(300) ]) let res = scheduler.start { xs >- mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), next(230, (7 + 2) * 2), next(240, (8 + 3) * 2), completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), error(300, testError) ]) let res = scheduler.start { xs >- mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), next(230, (7 + 2) * 2), next(240, (8 + 3) * 2), error(300, testError) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), error(300, testError) ]) let res = scheduler.start(290) { xs >- mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), next(230, (7 + 2) * 2), next(240, (8 + 3) * 2), ] let correctSubscriptions = [ Subscription(200, 290) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), error(300, testError) ]) let res = scheduler.start { xs >- mapWithIndexOrDie { $0 < 7 ? success(($0 + $1) * 2) : failure(testError) } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), error(230, testError) ] let correctSubscriptions = [ Subscription(200, 230) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_DisposeOnCompleted() { just("A") >- map { a in return a } >- subscribeNext { _ in } } func testMap1_DisposeOnCompleted() { just("A") >- mapWithIndex { (a, i) in return a } >- subscribeNext { _ in } } } // flatMap extension ObservableStandardSequenceOperators { func testFlatMap_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs >- flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), completed(960) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMap_Complete_InnerNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), ]) let res = scheduler.start { xs >- flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMap_Complete_OuterNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs >- flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 1000) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMap_Complete_ErrorOuter() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), error(900, testError) ]) let res = scheduler.start { xs >- flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), error(900, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 900) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 900) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 900) ]) } func testFlatMap_Error_Inner() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), error(460, testError) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs >- flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), error(760, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 760) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 760) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 760) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMap_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start(700) { xs >- flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 700) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 700) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 700) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMap_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) var invoked = 0 let res = scheduler.start { return xs >- flatMapOrDie { (x: ColdObservable<Int>) -> RxResult<Observable<Int>> in invoked++ if invoked == 3 { return failure(testError) } return success(x) } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), error(550, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 550) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 550) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 550) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMap_UseFunction() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 4), next(220, 3), next(250, 5), next(270, 1), completed(290) ]) var invoked = 0 let res = scheduler.start { xs >- flatMap { (x) in return interval(10, scheduler) >- map { _ in x } >- take(x) } } XCTAssertEqual(res.messages, [ next(220, 4), next(230, 3), next(230, 4), next(240, 3), next(240, 4), next(250, 3), next(250, 4), next(260, 5), next(270, 5), next(280, 1), next(280, 5), next(290, 5), next(300, 5), completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) } func testFlatMapIndex_Index() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 4), next(220, 3), next(250, 5), next(270, 1), completed(290) ]) let res = scheduler.start { xs >- flatMapWithIndex { (x, i) in return just(ElementIndexPair(x, i)) } } XCTAssertEqual(res.messages, [ next(210, ElementIndexPair(4, 0)), next(220, ElementIndexPair(3, 1)), next(250, ElementIndexPair(5, 2)), next(270, ElementIndexPair(1, 3)), completed(290) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) } func testFlatMapWithIndex_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs >- flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), completed(960) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMapWithIndex_Complete_InnerNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), ]) let res = scheduler.start { xs >- flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMapWithIndex_Complete_OuterNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs >- flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 1000) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMapWithIndex_Complete_ErrorOuter() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), error(900, testError) ]) let res = scheduler.start { xs >- flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), error(900, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 900) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 900) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 900) ]) } func testFlatMapWithIndex_Error_Inner() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), error(460, testError) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs >- flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), error(760, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 760) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 760) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 760) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMapWithIndex_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start(700) { xs >- flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 700) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 700) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 700) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMapWithIndex_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) var invoked = 0 let res = scheduler.start { return xs >- flatMapWithIndexOrDie { (x: ColdObservable<Int>, _: Int) -> RxResult<Observable<Int>> in invoked++ if invoked == 3 { return failure(testError) } return success(x) } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), error(550, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 550) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 550) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 550) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMapWithIndex_UseFunction() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 4), next(220, 3), next(250, 5), next(270, 1), completed(290) ]) var invoked = 0 let res = scheduler.start { xs >- flatMapWithIndex { (x, _) in return interval(10, scheduler) >- map { _ in x } >- take(x) } } XCTAssertEqual(res.messages, [ next(220, 4), next(230, 3), next(230, 4), next(240, 3), next(240, 4), next(250, 3), next(250, 4), next(260, 5), next(270, 5), next(280, 1), next(280, 5), next(290, 5), next(300, 5), completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) } } // take extension ObservableStandardSequenceOperators { func testTake_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- take(20) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testTake_Complete_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- take(17) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(630) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 630) ]) } func testTake_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- take(10) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), completed(415) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 415) ]) } func testTake_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs >- take(20) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testTake_Error_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs >- take(17) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(630) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 630) ]) } func testTake_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs >- take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), completed(270) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) } func testTake_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start(250) { xs >- take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testTake_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start(400) { xs >- take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), completed(270) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) } func testTake_0_DefaultScheduler() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13) ]) let res = scheduler.start { xs >- take(0) } XCTAssertEqual(res.messages, [ completed(200) ]) XCTAssertEqual(xs.subscriptions, [ ]) } func testTake_Take1() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), completed(400) ]) let res = scheduler.start { xs >- take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), completed(270) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) } func testTake_DecrementCountsFirst() { let k = BehaviorSubject(value: false) k >- take(1) >- subscribeNext { n in sendNext(k, !n) } } } // skip extension ObservableStandardSequenceOperators { func testSkip_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- skip(20) } XCTAssertEqual(res.messages, [ completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Complete_Some() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- skip(17) } XCTAssertEqual(res.messages, [ completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- skip(10) } XCTAssertEqual(res.messages, [ next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Complete_Zero() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs >- skip(0) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs >- skip(20) } XCTAssertEqual(res.messages, [ error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Error_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs >- skip(17) } XCTAssertEqual(res.messages, [ error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs >- skip(3) } XCTAssertEqual(res.messages, [ next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), ]) let res = scheduler.start(250) { xs >- skip(3) } XCTAssertEqual(res.messages, [ ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testSkip_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), ]) let res = scheduler.start(400) { xs >- skip(3) } XCTAssertEqual(res.messages, [ next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } }
mit
355243e58c87858a71e0190445dc26af
26.657216
118
0.423233
4.790322
false
true
false
false
jisudong/study
MyPlayground.playground/Pages/协议.xcplaygroundpage/Contents.swift
1
7826
//: [Previous](@previous) import Foundation //// 协议(协议是一种类型) /* * 在值类型(即结构体和枚举)的实例方法中,将 mutating 关键字作为方法的前缀 * 实现协议中的 mutating 方法时,若是类类型,则不用写 mutating 关键字。而对于结构体和枚举,则必须写 mutating 关键字 * 你可以在遵循协议的类中实现构造器,必须为构造器实现标上 required 修饰符(如果类已经被标记为 final,那么不需要在协议构造器的实现中使用 required 修饰符) * 如果一个子类重写了父类的指定构造器,并且该构造器满足了某个协议的要求,那么该构造器的实现需要同时标注 required 和 override 修饰符 * 遵循协议的类型可以通过可失败构造器(init?)或非可失败构造器(init)来满足协议中定义的可失败构造器要求。协议中定义的非可失败构造器要求可以通过非可失败构造器(init)或隐式解包可失败构造器(init!)来满足 * 一个属性的类型是一个协议类型(SomeProtocol),遵循了这个协议的类型的实例都可以赋值给这个属性 */ //// mutating protocol Togglable { mutating func toggle() // mutating 修饰的方法 } enum OnOffSwitch: Togglable { case On, Off mutating func toggle() { switch self { case .On: self = .Off case .Off: self = .On } } } //// required, override protocol SomeProtocol { init(someParameter: Int) init() } class SomeClass: SomeProtocol { required init(someParameter: Int) { } required init() { } } class SomeSuperClass { init() { } } class SomeSubClass: SomeSuperClass, SomeProtocol { required override init() { // required, override } required init(someParameter: Int) { // required } } //// 协议继承 protocol TextRepresentable { var textualDescription: String { get } } protocol PrettyTextRepresentable: TextRepresentable { var prettyTextualDescription: String { get } } class AClass: PrettyTextRepresentable { var textualDescription: String { return "TextRepresentable-description" } var prettyTextualDescription: String { return textualDescription + "prettyTextualDescription-description" } } //// 类类型专属协议 protocol SomeClassProtocol: class, TextRepresentable { // 这个协议只能被类类型遵循 } //// 协议的合成 protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } // 协议合成并不会生成新的、永久的协议类型,而是将多个协议中的要求合成到一个只在局部作用域有效的临时协议中 typealias named_aged = Named & Aged // & 用来合成协议 func wishHappyBirthday(to celebrator: named_aged) { print("Happy birthday, \(celebrator.name), you're \(celebrator.age)") } let birthdayPerson = Person(name: "jenny", age: 21) wishHappyBirthday(to: birthdayPerson) // 检查协议一致性 /* is 用来检查实例是否符合某个协议,若符合则返回 true,否则返回 false。 as? 返回一个可选值,当实例符合某个协议时,返回类型为协议类型的可选值,否则返回 nil。 as! 将实例强制向下转换到某个协议类型,如果强转失败,会引发运行时错误 */ protocol HasArea { var area: Double { get } } class Circle: HasArea { let pi = 3.1415926 var radius: Double var area: Double { // 实现成计算属性 return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double // 实现成存储属性 init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } let objects: [AnyObject] = [ Circle(radius: 5), Country(area: 243_610), Animal(legs: 4) ] for object in objects { if let objectWithArea = object as? HasArea { print("Area is \(objectWithArea.area)") } else { print("Something that doesn't have an area") } } //// 可选的协议要求 @objc protocol CounterDataSource { @objc optional func increment(forCount count: Int) -> Int @objc optional var fixedIncrement: Int { get } } class Counter { var count: Int = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.increment?(forCount: count) { count += amount } else if let amount = dataSource?.fixedIncrement { count += amount } } } class ThreeSource: NSObject, CounterDataSource { let fixedIncrement: Int = 3 } var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() print(counter.count) } @objc class TowardsZeroSource: NSObject, CounterDataSource { func increment(forCount count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() print(counter.count) } // 协议扩展 protocol Coder { var haveFun: Bool { get } var ownMoney: Bool { get } } protocol Swifter { var codingLevel: Int { get } } struct CoderFromA: Coder { var name: String var haveFun: Bool var ownMoney: Bool } struct CoderFromB: Coder, Swifter { var name: String var codingLevel = 3 } struct CoderFromC: Coder, Swifter { var name: String var codingLevel = 5 } extension Coder where Self: Swifter { // 协议扩展中不能定义存储属性 // var haveFun: Bool = true // 会报错 var haveFun: Bool { return true } var ownMoney: Bool { return true } } //// 协议的静态特性 protocol SharedString { // func methodForOverride() // func methodWithoutOverride() } extension SharedString { func methodForOverride() { print("~\\(^o^)/~") } func methodWithoutOverride() { print("--------") methodForOverride() print("--------") } } extension String: SharedString { func methodForOverride() { print(self) } } "hello".methodForOverride() "hello".methodWithoutOverride() // 修改上下文 let hello: SharedString = "hello" hello.methodForOverride() hello.methodWithoutOverride() //// 协议继承中的静态特性 protocol SearchIntArrayMax { } extension SearchIntArrayMax where Self: Collection, Self.Iterator.Element == Int { func showMax() -> String { if let max = self.max() { return "\(max)" } return "无最大值" } } extension Array: SearchIntArrayMax { // 这里实现了协议,覆盖了协议的默认实现 func showMax() -> Iterator.Element? { if self.count > 0 { return self.last } return nil } } protocol CanCompareMax: SearchIntArrayMax { } extension CanCompareMax where Self: Collection, Self.Iterator.Element == Int { func compareMax(other: Self) -> String { // 虽然上面扩展实现了协议,但是由于静态特性,showMax()还是调用默认实现 switch (self.showMax(), other.showMax()) { case ("无最大值", _) : fallthrough case (_, "无最大值") : return "无最大值" case let (a, b) where a == b : return a default: return "不相等" } } } extension Array: CanCompareMax { } [1, 2, 3].compareMax(other: [1, 1, 1]) [1, 2, 3].compareMax(other: [1, 3, 1]) [1, 2, 3].compareMax(other: [])
mit
52be46617ce2e59e79a20705a1ae78ac
20.753333
112
0.632394
3.523758
false
false
false
false
harenbrs/swix
swixUseCases/swix-iOS/swix/ndarray/operators.swift
2
7804
// // oneD-functions.swift // swix // // Created by Scott Sievert on 7/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func make_operator(lhs:ndarray, operation:String, rhs:ndarray) -> ndarray{ assert(lhs.n == rhs.n, "Sizes must match!") var array = zeros(lhs.n) // lhs[i], rhs[i] var arg_b = zeros(lhs.n) var arg_c = zeros(lhs.n) // see [1] on how to integrate Swift and accelerate // [1]:https://github.com/haginile/SwiftAccelerate var result = lhs.copy() var N = lhs.n if operation=="+" {cblas_daxpy(N.cint, 1.0.cdouble, !rhs, 1.cint, !result, 1.cint);} else if operation=="-" {cblas_daxpy(N.cint, -1.0.cdouble, !rhs, 1.cint, !result, 1.cint);} else if operation=="*" {vDSP_vmulD(!lhs, 1, !rhs, 1, !result, 1, lhs.n.length)} else if operation=="/" {vDSP_vdivD(!rhs, 1, !lhs, 1, !result, 1, lhs.n.length)} else if operation=="%"{ array = remainder(lhs, rhs) } else if operation=="<" || operation==">" || operation==">=" || operation=="<=" { result = zeros(lhs.n) CVWrapper.compare(!lhs, with: !rhs, using: operation.nsstring, into: !result, ofLength: lhs.n.cint) // since opencv uses images which use 8-bit values result /= 255 } else if operation == "=="{ return abs(lhs-rhs) < 1e-9 } else if operation == "!=="{ return abs(lhs-rhs) > 1e-9 } else {assert(false, "operation not recongized!")} return result } func make_operator(lhs:ndarray, operation:String, rhs:Double) -> ndarray{ var array = zeros(lhs.n) var right = [rhs] if operation == "%"{ // unoptimized. for loop in c var r = zeros_like(lhs) + rhs array = remainder(lhs, r) } else if operation == "*"{ var C:CDouble = 0 var mul = CDouble(rhs) vDSP_vsmsaD(!lhs, 1.stride, &mul, &C, !array, 1.stride, lhs.n.length) } else if operation == "+" {vDSP_vsaddD(!lhs, 1, &right, !array, 1, lhs.n.length)} else if operation=="/" {vDSP_vsdivD(!lhs, 1, &right, !array, 1, lhs.n.length)} else if operation=="-" {array = make_operator(lhs, "-", ones(lhs.n)*rhs)} else if operation=="<" || operation==">" || operation=="<=" || operation==">="{ CVWrapper.compare(!lhs, withDouble:rhs.cdouble, using:operation.nsstring, into:!array, ofLength:lhs.n.cint) array /= 255 } else {assert(false, "operation not recongnized! Error with the speedup?")} return array } func make_operator(lhs:Double, operation:String, rhs:ndarray) -> ndarray{ var array = zeros(rhs.n) // lhs[i], rhs[i] var l = ones(rhs.n) * lhs if operation == "*" {array = make_operator(rhs, "*", lhs)} else if operation=="%"{ var l = zeros_like(rhs) + lhs array = remainder(l, rhs) } else if operation == "+"{ array = make_operator(rhs, "+", lhs)} else if operation=="-" {array = -1 * make_operator(rhs, "-", lhs)} else if operation=="/"{ array = make_operator(l, "/", rhs)} else if operation=="<"{ array = make_operator(rhs, ">", lhs)} else if operation==">"{ array = make_operator(rhs, "<", lhs)} else if operation=="<="{ array = make_operator(rhs, ">=", lhs)} else if operation==">="{ array = make_operator(rhs, "<=", lhs)} else {assert(false, "Operator not reconginzed")} return array } // EQUALITY infix operator ~== {associativity none precedence 140} func ~== (lhs: ndarray, rhs: ndarray) -> Bool{ assert(lhs.n == rhs.n, "`~==` only works on arrays of equal size") return max(abs(lhs - rhs)) > 1e-6 ? false : true; } func == (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "==", rhs)} func !== (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "!==", rhs)} // NICE ARITHMETIC func += (inout x: ndarray, right: Double){ x = x + right} func *= (inout x: ndarray, right: Double){ x = x * right} func -= (inout x: ndarray, right: Double){ x = x - right} func /= (inout x: ndarray, right: Double){ x = x / right} // MOD infix operator % {associativity none precedence 140} func % (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "%", rhs)} func % (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "%", rhs)} func % (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "%", rhs)} // POW infix operator ^ {associativity none precedence 140} func ^ (lhs: ndarray, rhs: Double) -> ndarray{ return pow(lhs, rhs)} func ^ (lhs: ndarray, rhs: ndarray) -> ndarray{ return pow(lhs, rhs)} func ^ (lhs: Double, rhs: ndarray) -> ndarray{ return pow(lhs, rhs)} // PLUS infix operator + {associativity none precedence 140} func + (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "+", rhs)} func + (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "+", rhs)} func + (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "+", rhs)} // MINUS infix operator - {associativity none precedence 140} func - (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "-", rhs)} func - (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "-", rhs)} func - (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "-", rhs)} // TIMES infix operator * {associativity none precedence 140} func * (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "*", rhs)} func * (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "*", rhs)} func * (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "*", rhs)} // DIVIDE infix operator / {associativity none precedence 140} func / (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "/", rhs) } func / (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "/", rhs)} func / (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "/", rhs)} // LESS THAN infix operator < {associativity none precedence 140} func < (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "<", rhs)} func < (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<", rhs)} func < (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<", rhs)} // GREATER THAN infix operator > {associativity none precedence 140} func > (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, ">", rhs)} func > (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">", rhs)} func > (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">", rhs)} // GREATER THAN OR EQUAL infix operator >= {associativity none precedence 140} func >= (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, ">=", rhs)} func >= (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">=", rhs)} func >= (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">=", rhs)} // LESS THAN OR EQUAL infix operator <= {associativity none precedence 140} func <= (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "<=", rhs)} func <= (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<=", rhs)} func <= (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<=", rhs)} // LOGICAL AND infix operator && {associativity none precedence 140} func && (lhs: ndarray, rhs: ndarray) -> ndarray{ return lhs * rhs} // LOGICAL OR func || (lhs: ndarray, rhs: ndarray) -> ndarray { var i = lhs + rhs var j = argwhere(i>1.double) i[j] = ones(j.n) return i}
mit
5eec10119d89383c161dd0bddfd13657
31.247934
115
0.601999
3.393043
false
false
false
false
AlexeyGolovenkov/DocGenerator
GRMustache.swift/Tests/Public/ObjcKeyAccessTests.swift
1
2183
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Mustache class ObjcKeyAccessTests: XCTestCase { class ClassWithProperties: NSObject { let property: String = "property" func method() -> String { return "method" } } func testPropertiesAreSafeAndAvailable() { let object = ClassWithProperties() // test setup XCTAssertEqual(object.property, "property") XCTAssertEqual((object.valueForKey("property") as! String), "property") // test context let context = Context(Box(object)) XCTAssertEqual((context.mustacheBoxForKey("property").value as! String), "property") } func testMethodsAreUnsafeAndNotAvailable() { let object = ClassWithProperties() // test setup XCTAssertEqual(object.method(), "method") XCTAssertEqual((object.valueForKey("method") as! String), "method") // test context let context = Context(Box(object)) XCTAssertTrue(context.mustacheBoxForKey("method").value == nil) } }
mit
ed31f202c63d7866ae24696bf74e52bf
37.280702
92
0.698442
4.848889
false
true
false
false
dreamsxin/swift
test/expr/closure/basic.swift
3
1129
// RUN: %target-parse-verify-swift func takeIntToInt(_ f: (Int) -> Int) { } func takeIntIntToInt(_ f: (Int, Int) -> Int) { } // Simple closures func simple() { takeIntToInt({(x: Int) -> Int in return x + 1 }) takeIntIntToInt({(x: Int, y: Int) -> Int in return x + y }) } // Closures with variadic argument lists func variadic() { var f = {(start: Int, rest: Int...) -> Int in var result = start for x in rest { result += x } return result } _ = f(1) _ = f(1, 2) _ = f(1, 3) let D = { (Ss ...) in 1 } // expected-error{{'...' cannot be applied to a subpattern which is not explicitly typed}}, expected-error{{unable to infer closure type in the current context}} } // Closures with attributes in the parameter list. func attrs() { _ = {(z: inout Int) -> Int in z } } // Closures with argument and parameter names. func argAndParamNames() -> Int { let _: (x: Int, y: Int) -> Int = { (a x, b y) in x + y } // expected-error 2 {{closure cannot have keyword arguments}} let f1: (x: Int, y: Int) -> Int = { (x, y) in x + y } _ = f1(x: 1, y: 2) return f1(x: 1, y: 2) }
apache-2.0
9282e001b964f3f10b3bae05528565d3
25.255814
189
0.575731
3.067935
false
false
false
false
Melon-IT/base-model-swift
MelonBaseModel/MelonBaseModel/MPropertyListData.swift
1
2954
// // MBFBaseDataParser.swift // MelonBaseModel // // Created by Tomasz Popis on 10/06/16. // Copyright © 2016 Melon. All rights reserved. // import Foundation /* public protocol MBFDataParserProtocol { var parserDataListener: MBFParserDataListener? {set get} var resource: Any? {set get} func load() func save() func clear() func delete() func parse(completionHandler: ((Bool) -> Void)?) } public protocol MBFParserDataListener { func dataDidParse(success: Bool, type: UInt?) } */ public class MPropertyList<Type> { public var resourcesName: String? fileprivate var resources: Type? public init() {} public init(resources: String) { self.resourcesName = resources } fileprivate func readResourcesFromBundle() { if let path = Bundle.main.path(forResource: resourcesName, ofType: "plist"), let content = try? Data(contentsOf: URL(fileURLWithPath: path)) { self.resources = (try? PropertyListSerialization.propertyList(from: content, options: [], format: nil)) as? Type } } fileprivate func cleanResources() { self.resources = nil } } public class MBundleDictionaryPropertyList<Type>: MPropertyList<Dictionary<String,Type>> { public func read() { self.readResourcesFromBundle(); } public func clean() { super.cleanResources() } public var numberOfItems: Int { var result = 0; if let counter = self.resources?.count { result = counter } return result } public subscript(key: String) -> Type? { return self.resources?[key] } } public class MBundleArrayPropertyList<Type>: MPropertyList<Array<Type>> { public func read() { self.readResourcesFromBundle(); } public func clean() { super.cleanResources() } public var numberOfItems: Int { var result = 0; if let counter = self.resources?.count { result = counter } return result } public subscript(index: Int) -> Type? { var result: Type? if let counter = self.resources?.count, index >= 0 && index < counter { result = self.resources?[index] } return result } } /* open class MBFBaseDataParser { public init() { } open func loadData() { } open func saveData() { } open func parseData(data: AnyObject?) { } open func loadFromDefaults(key: String) -> AnyObject? { let defaults = UserDefaults.standard return defaults.object(forKey: key) as AnyObject? } open func saveToDefaults(key: String, object: AnyObject?) { let defaults = UserDefaults.standard defaults.set(object, forKey: key) defaults.synchronize() } open func uniqueUserKey(userId: String, separator: String, suffix: String) -> String { return "\(userId)\(separator)\(suffix)" } } */
mit
cda29c1efe1073838fe1b1ae04a7545b
17.929487
91
0.624788
4.212553
false
false
false
false
alexcurylo/iso3166-flags-maps-worldheritage
masterlister/Masterlister/SitelistVC.swift
1
11790
// @copyright Trollwerks Inc. import Cocoa final class SitelistVC: NSViewController { private let members: [Member] = { let path = Bundle.main.path(forResource: "unesco_members", ofType: "json") // swiftlint:disable:next force_try force_unwrapping let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) // swiftlint:disable:next force_try let array = try! JSONDecoder().decode([Member].self, from: data) assert(array.count == 206, "Should be 195 states and 10 associates and 1 observer (VA) in 2017") return array }() let countries = Country.countries let sites = WHS.sitelist let tentatives = TWHS.sitelist let mtpVisitChecker = MTPVisitChecker() private lazy var visits: [Visit] = { let path = Bundle.main.path(forResource: "visits", ofType: "json") var array: [Visit] = [] do { // swiftlint:disable:next force_unwrapping let data = try Data(contentsOf: URL(fileURLWithPath: path!)) array = try JSONDecoder().decode([Visit].self, from: data) } catch { print("Error decoding visits", error) } return array }() private lazy var whsVisits: [Visit] = { let array = visits.filter { $0.whs != nil } let ids = array.compactMap { $0.whs } let duplicates = Array(Set(ids.filter { (i: Int) in ids.filter { $0 == i }.count > 1 })) assert(duplicates.isEmpty, "Should not have duplicate WHS visits \(duplicates)") let wrong = Set(ids).subtracting(Set(sites.map { $0.siteId })) assert(wrong.isEmpty, "Should not have wrong WHS visits \(wrong)") return array }() private lazy var twhsVisits: [Visit] = { let array = visits.filter { $0.twhs != nil } let ids = visits.compactMap { $0.twhs } let duplicates = Array(Set(ids.filter { (i: Int) in ids.filter { $0 == i }.count > 1 })) assert(duplicates.isEmpty, "Should not have duplicate TWHS visits \(duplicates)") let wrong = Set(ids).subtracting(Set(tentatives.map { $0.siteId })) assert(wrong.isEmpty, "Should not have wrong TWHS visits \(wrong)") return array }() private lazy var countryFiles: [CountryFile] = { let path = Bundle.main.path(forResource: "country-files", ofType: "json") var array: [CountryFile] = [] do { // swiftlint:disable:next force_unwrapping let data = try Data(contentsOf: URL(fileURLWithPath: path!)) array = try JSONDecoder().decode([CountryFile].self, from: data) } catch { print("Error decoding country files", error) } return array }() @IBOutlet private var output: NSTextView! private var whsVisited = Set<Int>() private var twhsVisited = Set<Int>() override func viewDidLoad() { super.viewDidLoad() MTPSiteChecker().check(sites: sites) //generate(for: .html) generate(for: .wordpress) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func generate(for type: Document) { writeHeader(for: type) writeCountries() writeFooter(for: type) } func writeHeader(for type: Document) { if type == .html { let htmlHeader = NSAttributedString(string: """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sitelist</title> </head> <body>\n """) output.textStorage?.append(htmlHeader) } let textHeader = NSAttributedString(string: """ <p><strong>The UNESCO World Heritage Site Master Sitelist</strong><br> <small>Inscribed properties are in plain text<br> <i>Tentative properties are in italic text</i></small></p>\n """) output.textStorage?.append(textHeader) } // private func pageExists(at url: URL) -> Bool { // var request = URLRequest(url: url) // request.httpMethod = "HEAD" // request.timeoutInterval = 10 // var response: URLResponse? // try! NSURLConnection.sendSynchronousRequest(request, // returning: &response) // let httpResponse = response as! HTTPURLResponse // if httpResponse.statusCode != 200 { return false } // if httpResponse.url != url { return false } // return true // } private func writeCountries() { for country in countries { guard members.contains(where: { country.iso == $0.iso }) else { continue } var whsSites = sites.filter { $0.countries.contains(country.iso.lowercased()) } // Special Jerusalem handling, put it in Israel if country.iso == Country.Code.israel.rawValue { let countryless = sites.filter { $0.countries.isEmpty } assert(countryless.count == 1, "Not exactly Jerusalem without a country?") // swiftlint:disable:next force_unwrapping whsSites.append(countryless.first!) } let twhsSites = tentatives.filter { $0.countries.contains(country.iso) } let unescoURL = "http://whc.unesco.org/en/statesparties/\(country.iso)/" let unescoLink = """ <a href="\(unescoURL)">\(country.title)</a> """ var fileLink = "" if let file = countryFiles.first(where: { country.iso == $0.iso })?.file { fileLink = " — <a href=\"\(file)\">Country File</a>" } // swiftlint:disable:next line_length let countryStart = NSAttributedString(string: "<p><strong>\(unescoLink)</strong> <small>(\(whsSites.count) WHS, \(twhsSites.count) TWHS)\(fileLink)</small><br>\n") output.textStorage?.append(countryStart) writeSites(in: country, whs: whsSites, twhs: twhsSites) let countryEnd = NSAttributedString(string: """ </p> """) output.textStorage?.append(countryEnd) } } private func writeSites(in country: Country, whs whsSites: [WHS], twhs twhsSites: [TWHS]) { guard !whsSites.isEmpty || !twhsSites.isEmpty else { let countryStart = NSAttributedString(string: """ <i><small>no inscribed or tentative sites yet!</small></i><br>\n """) output.textStorage?.append(countryStart) return } for whs in whsSites { output.textStorage?.append(whsLine(whs: whs)) } if !twhsSites.isEmpty { output.textStorage?.append(NSAttributedString(string: "<i>")) for twhs in twhsSites { output.textStorage?.append(twhsLine(twhs: twhs)) } output.textStorage?.append(NSAttributedString(string: "</i>")) } } private func whsLine(whs: WHS) -> NSAttributedString { let link = """ <a href="http://whc.unesco.org/en/list/\(whs.siteId)">\(whs.name)</a> """ var mark = Visited.no.rawValue var blogLinks = "" if let visited = whsVisits.first(where: { $0.whs == whs.siteId }) { whsVisited.insert(whs.siteId) mtpVisitChecker.check(whs: whs.siteId) mark = Visited.yes.rawValue var visitLink = "" var stayLink = "" var eatLink = "" if let visitURL = visited.visit { visitLink = " — <a href=\"\(visitURL)\">Visit</a>" } if let stayURL = visited.stay { stayLink = " — <a href=\"\(stayURL)\">Stay</a>" } if let eatURL = visited.eat { eatLink = " — <a href=\"\(eatURL)\">Eat</a>" } if !visitLink.isEmpty || !stayLink.isEmpty || !eatLink.isEmpty { blogLinks = "<small>\(visitLink)\(stayLink)\(eatLink)</small>" } } let whsLine = NSAttributedString(string: "\(mark) \(link)\(blogLinks)<br>\n") return whsLine } private func twhsLine(twhs: TWHS) -> NSAttributedString { let link = """ <a href="http://whc.unesco.org/en/tentativelists/\(twhs.siteId)">\(twhs.name)</a> """ var mark = Visited.no.rawValue var blogLinks = "" if let visited = twhsVisits.first(where: { $0.twhs == twhs.siteId }) { twhsVisited.insert(twhs.siteId) mark = Visited.yes.rawValue var visitLink = "" var stayLink = "" var eatLink = "" if let visitURL = visited.visit { visitLink = " — <a href=\"\(visitURL)\">Visit</a>" } if let stayURL = visited.stay { stayLink = " — <a href=\"\(stayURL)\">Stay</a>" } if let eatURL = visited.eat { eatLink = " — <a href=\"\(eatURL)\">Eat</a>" } if !visitLink.isEmpty || !stayLink.isEmpty || !eatLink.isEmpty { blogLinks = "<small>\(visitLink)\(stayLink)\(eatLink)</small>" } } let twhsLine = NSAttributedString(string: "\(mark) \(link)\(blogLinks)<br>\n") return twhsLine } private func writeFooter(for type: Document) { mtpVisitChecker.checkMissing() assert(whsVisited.count == 525, "Should be 525 WHS visited not \(whsVisited.count) (2019.10.30)") assert(twhsVisited.count == 374, "Should be 374 TWHS visited not \(twhsVisited.count) (2019.10.30)") // swiftlint:disable:next line_length let updatesURL = "http://whc.unesco.org/en/tentativelists/?action=listtentative&pattern=&state=&theme=&criteria_restrication=&date_start=02%2F08%2F2019&date_end=&order=year" let whsPercent = String(format: "%.1f", Float(whsVisited.count) / Float(sites.count) * 100) let twhsPercent = String(format: "%.1f", Float(twhsVisited.count) / Float(tentatives.count) * 100) let total = sites.count + tentatives.count let totalVisits = whsVisited.count + twhsVisited.count let totalPercent = String(format: "%.1f", Float(totalVisits) / Float(total) * 100) let textFooter = NSAttributedString(string: """ <p><small>WHS: \(whsVisited.count)/\(sites.count) \ (\(whsPercent)%) — TWHS: \(twhsVisited.count)/\(tentatives.count) \ (\(twhsPercent)%) — TOTAL: \(totalVisits)/\(total) (\(totalPercent)%)<br> <i>Last compiled 2019.08.02 — <a href=\"\(updatesURL)\">Check for updates</a></i>\ </small></p> """) output.textStorage?.append(textFooter) if type == .html { let htmlFooter = NSAttributedString(string: """ </body> </html> """) output.textStorage?.append(htmlFooter) } } } private struct CountryFile: Codable { let iso: String let file: URL? let name: String? // for easily locating unfiled countries } private struct Member: Codable { let iso: String let name: String let joined: String let region: String } private struct Visit: Codable { let wonder: Int? let whs: Int? let twhs: Int? let visit: URL? let stay: URL? let eat: URL? }
mit
7cbd8665ab09cbb93eb28bca6cd30679
36.012579
181
0.551317
4.101045
false
false
false
false
gmertk/SwiftSequence
SwiftSequence/Categorise.swift
1
6555
// MARK: - Eager // MARK: Categorise public extension SequenceType { /// Categorises elements of self into a dictionary, with the keys given by keyFunc func categorise<U : Hashable>(@noescape keyFunc: Generator.Element -> U) -> [U:[Generator.Element]] { var dict: [U:[Generator.Element]] = [:] for el in self { let key = keyFunc(el) dict[key]?.append(el) ?? {dict[key] = [el]}() } return dict } } public extension SequenceType where Generator.Element : Hashable { // MARK: Frequencies /// Returns a dictionary where the keys are the elements of self, and the values /// are their respective frequencies func freqs() -> [Generator.Element:Int] { var freqs: [Generator.Element:Int] = [:] for el in self {freqs[el]?._successorInPlace() ?? {freqs[el] = 1}()} return freqs } // MARK: Uniques /// Returns an array of self with duplicates removed func uniques() -> [Generator.Element] { var prevs: Set<Generator.Element> = [] return self.filter { el in defer { prevs.insert(el) } return !prevs.contains(el) } } // MARK: Replace /// Returns self with all of the keys in reps replaced by their values func replace(reps: [Generator.Element:Generator.Element]) -> [Generator.Element] { return self.map{reps[$0] ?? $0} } } // MARK: - Lazy // MARK: Uniques public struct UniquesGen<G : GeneratorType where G.Element : Hashable> : GeneratorType { private var prevs: Set<G.Element> private var g: G public mutating func next() -> G.Element? { while let next = g.next() { if !prevs.contains(next) { prevs.insert(next) return next } } return nil } } public struct UniquesSeq< S : SequenceType where S.Generator.Element : Hashable > : LazySequenceType { private let seq: S public func generate() -> UniquesGen<S.Generator> { return UniquesGen(prevs: [], g: seq.generate()) } } public extension LazySequenceType where Generator.Element : Hashable { /// returns a lazy sequence of self with duplicates removed func uniques() -> UniquesSeq<Self> { return UniquesSeq(seq: self) } } // MARK: Replace public extension LazySequenceType where Generator.Element : Hashable { /// Returns a lzy sequence of self with all of the keys in reps replaced by their values func replace(reps: [Generator.Element:Generator.Element]) -> LazySequence<MapSequence<Self, Self.Generator.Element>> { return lazy(self).map { reps[$0] ?? $0 } } } // MARK: Grouping public struct GroupGen<G : GeneratorType where G.Element : Equatable> : GeneratorType { private var g : G private var last: [G.Element]? mutating public func next() -> [G.Element]? { while let next = g.next() { if next == last?[0] { last!.append(next) } else { defer { last = [next] } return last } } defer { last = nil } return last } private init(var g : G) { self.last = g.next().map{[$0]} self.g = g } } public struct GroupByGen<G : GeneratorType> : GeneratorType { private var g : G private var last: [G.Element]? private let isEquivalent: (G.Element, G.Element) -> Bool mutating public func next() -> [G.Element]? { while let next = g.next() { if let lastU = last where isEquivalent(lastU[0], next) { last!.append(next) } else { defer { last = [next] } return last } } defer { last = nil } return last } private init(var g : G, isEquivalent: (G.Element, G.Element) -> Bool) { self.last = g.next().map{[$0]} self.g = g self.isEquivalent = isEquivalent } } public struct GroupSeq< S : SequenceType where S.Generator.Element : Equatable > : LazySequenceType { private let seq: S public func generate() -> GroupGen<S.Generator> { return GroupGen(g: seq.generate()) } } public struct GroupBySeq<S : SequenceType> : LazySequenceType { private let seq: S private let isEquivalent: (S.Generator.Element, S.Generator.Element) -> Bool public func generate() -> GroupByGen<S.Generator> { return GroupByGen(g: seq.generate(), isEquivalent: isEquivalent) } } public extension LazySequenceType where Generator.Element : Equatable { /// Returns a lazy sequence of self, chunked into arrays of adjacent equal values /// ``` swift /// lazy([1, 2, 2, 3, 1, 1, 3, 4, 2]).group() /// /// [1], [2, 2], [3], [1, 1], [3], [4], [2] /// ``` func group() -> GroupSeq<Self> { return GroupSeq(seq: self) } } public extension LazySequenceType { /// Returns a lazy sequence of self, chunked into arrays of adjacent equal values /// - Parameter isEquivalent: a function that returns true if its two parameters are equal /// ``` /// lazy([1, 3, 5, 20, 22, 18, 6, 7]).groupBy { abs($0 - $1) < 5 } /// /// [1, 3, 5], [20, 22, 18], [6, 7] /// ``` func group(isEquivalent: (Generator.Element, Generator.Element) -> Bool) -> GroupBySeq<Self> { return GroupBySeq(seq: self, isEquivalent: isEquivalent) } } public struct GroupByKeyGen<G : GeneratorType, K: Equatable> : GeneratorType { private var g: G private var head: K? private var list: [G.Element]? private let keyFunc: G.Element -> K mutating public func next() -> [G.Element]? { while let next = g.next() { if keyFunc(next) == head { list?.append(next) } else { defer { head = keyFunc(next) list = [next] } return list } } defer { list = nil } return list } } public struct GroupByKeySeq<S : SequenceType, K : Equatable> : LazySequenceType { private let seq: S private let keyFunc: S.Generator.Element -> K public func generate() -> GroupByKeyGen<S.Generator, K> { var g = seq.generate() let list = [g.next()!] let head = keyFunc(list[0]) return GroupByKeyGen(g: g, head: head, list: list, keyFunc: keyFunc) } } public extension LazySequenceType { /// Returns a lazy sequence of self, chunked into arrays of adjacent equal keys /// - Parameter keyFunc: a function that returns the keys by which to group the elements of self /// ``` /// lazy([1, 3, 5, 2, 4, 6, 6, 7, 1, 1]).groupBy { $0 % 2 } /// /// [[1, 3, 5], [2, 4, 6, 6], [7, 1, 1]] /// ``` func groupBy<T : Equatable> (keyFunc: (Generator.Element) -> T) -> GroupByKeySeq<Self, T> { return GroupByKeySeq(seq: self, keyFunc: keyFunc) } }
mit
bdff53294262980205c7c8772af45b5a
24.406977
120
0.615408
3.61755
false
false
false
false
lorismaz/LaDalle
LaDalle/LaDalle/Yelp.swift
1
2835
// // Yelp.swift // LaDalle // // Created by Loris Mazloum on 9/18/16. // Copyright © 2016 Loris Mazloum. All rights reserved. // import Foundation import UIKit class Yelp { private let server = "https://api.yelp.com/v3/" //static let sharedInstance = Yelp() var token: String? = nil init() { } } //Get Yelp Token extension Yelp { func getToken() { print("Calling Yelp to get a token") // create the url //let link = server + "oauth2/token" let link = "https://api.yelp.com/oauth2/token" guard let url = URL(string: link) else { return } //set headers let headers = [ "content-type": "application/x-www-form-urlencoded" ] let clientId = valueForAPIKey(named: "YELP_API_CLIENT_ID") let clientSecret = valueForAPIKey(named: "YELP_API_SECRET_ID") // set body let bodyData = "client_id=\(clientId)&client_secret=\(clientSecret)&grant_type=client_credentials" //set request var request = URLRequest.init(url: url) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = bodyData.data(using: .utf8) //create sharedSession let sharedSession = URLSession.shared // setup completion handler let completionHandler: (Data?, URLResponse?, Error?) -> Void = { data, response, error in guard let data = data, error == nil else { // check for networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } do { let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) guard let result = jsonObject as? NSDictionary else { return } guard let accessToken = result["access_token"] as? String else { return } self.token = accessToken //store token in plist } catch { print("Could not get an Access Token") return } } // set dataTask let dataTask = sharedSession.dataTask(with: request, completionHandler: completionHandler) //resume dataTask dataTask.resume() } }
mit
6c4d360fa9a42bc599b2e313f6a7881a
28.216495
127
0.528934
5.106306
false
false
false
false
yanagiba/swift-ast
Sources/Frontend/Terminal/TerminalDiagnosticConsumer.swift
2
2012
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import Bocho import Diagnostic import Source struct TerminalDiagnosticConsumer : DiagnosticConsumer { func consume(diagnostics: [Diagnostic]) { var cachedContent: [String: String] = [:] for d in diagnostics { let levelStr: String switch d.level { case .fatal, .error: levelStr = d.level.rawValue.colored(with: .red) case .warning: levelStr = d.level.rawValue.colored(with: .yellow) } print("\(d.location) \(levelStr): \(d.kind.diagnosticMessage)") let filePath = d.location.identifier var fileContent = cachedContent[filePath] if fileContent == nil { fileContent = (try? SourceReader.read(at: filePath))?.content } if let fileContent = fileContent { cachedContent[filePath] = fileContent let lines = fileContent.components(separatedBy: .newlines) var lineNum = d.location.line - 1 if lineNum < 0 { lineNum = 0 } if lineNum < lines.count { print(lines[lineNum]) var paddingNum = d.location.column - 1 if paddingNum < 0 { paddingNum = 0 } let padding = String(repeating: " ", count: paddingNum) let pointer = padding + "^~~~".colored(with: .green) print(pointer) } } print() } } }
apache-2.0
4ccf6a7c8f50a802a61b89ce9374389d
30.936508
85
0.646123
4.541761
false
false
false
false
anasmeister/nRF-Coventry-University
nRF Toolbox/HRS/NORHRMViewController.swift
1
22690
// // NORHRMViewController.swift // nRF Toolbox // // Created by Mostafa Berg on 04/05/16. // Copyright © 2016 Nordic Semiconductor. All rights reserved. //// Edited by Anastasios Panagoulias on 11/01/07 import UIKit import CoreBluetooth import CorePlot 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 } } fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } class NORHRMViewController: NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate, CPTPlotDataSource, CPTPlotSpaceDelegate { //MARK: - Properties var bluetoothManager : CBCentralManager? var hrValues : NSMutableArray? var xValues : NSMutableArray? var plotXMaxRange : Int? var plotXMinRange : Int? var plotYMaxRange : Int? var plotYMinRange : Int? var plotXInterval : Int? var plotYInterval : Int? var isBluetoothOn : Bool? var isDeviceConnected : Bool? var isBackButtonPressed : Bool? var batteryServiceUUID : CBUUID var batteryLevelCharacteristicUUID : CBUUID var hrServiceUUID : CBUUID var hrMeasurementCharacteristicUUID : CBUUID var hrLocationCharacteristicUUID : CBUUID var linePlot : CPTScatterPlot? var graph : CPTGraph? var peripheral : CBPeripheral? //MARK: - UIVIewController Outlets @IBOutlet weak var verticalLabel: UILabel! @IBOutlet weak var battery: UIButton! @IBOutlet weak var deviceName: UILabel! @IBOutlet weak var connectionButton: UIButton! @IBOutlet weak var hrLocation: UILabel! @IBOutlet weak var hrValue: UILabel! @IBOutlet weak var graphView: CPTGraphHostingView! //MARK: - UIVIewController Actions @IBAction func connectionButtonTapped(_ sender: AnyObject) { if peripheral != nil { bluetoothManager?.cancelPeripheralConnection(peripheral!) } } @IBAction func aboutButtonTapped(_ sender: AnyObject) { self.showAbout(message: NORAppUtilities.getHelpTextForService(service: .hrm)) } //MARK: - UIViewController delegate required init?(coder aDecoder: NSCoder) { hrServiceUUID = CBUUID(string: NORServiceIdentifiers.hrsServiceUUIDString) hrMeasurementCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.hrsHeartRateCharacteristicUUIDString) hrLocationCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.hrsSensorLocationCharacteristicUUIDString) batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString) batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Rotate the vertical label verticalLabel.transform = CGAffineTransform(translationX: -120.0, y: 0.0).rotated(by: CGFloat(-M_PI_2)) isBluetoothOn = false isDeviceConnected = false isBackButtonPressed = false peripheral = nil hrValues = NSMutableArray() xValues = NSMutableArray() initLinePlot() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if peripheral != nil && isBackButtonPressed == true { bluetoothManager?.cancelPeripheralConnection(peripheral!) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) isBackButtonPressed = true } //MARK: - CTPPlot Implementation func initLinePlot() { //Initialize and display Graph (x and y axis lines) graph = CPTXYGraph(frame: graphView.bounds) self.graphView.hostedGraph = self.graph; /////////////////////////////////////////////////apply styling to Graph graph?.apply(CPTTheme(named: CPTThemeName.plainBlackTheme)) //set graph backgound area transparent graph?.fill = CPTFill(color: CPTColor.clear()) graph?.plotAreaFrame?.fill = CPTFill(color: CPTColor.clear()) graph?.plotAreaFrame?.fill = CPTFill(color: CPTColor.clear()) //This removes top and right lines of graph graph?.plotAreaFrame?.borderLineStyle = CPTLineStyle(style: nil) //This shows x and y axis labels from 0 to 1 graph?.plotAreaFrame?.masksToBorder = false // set padding for graph from Left and Bottom graph?.paddingBottom = 30; graph?.paddingLeft = 50; graph?.paddingRight = 0; graph?.paddingTop = 0; //Define x and y axis range // x-axis from 0 to 100 // y-axis from 0 to 300 let plotSpace = graph?.defaultPlotSpace plotSpace?.allowsUserInteraction = true plotSpace?.delegate = self; self.resetPlotRange() let axisSet = graph?.axisSet as! CPTXYAxisSet; let axisLabelFormatter = NumberFormatter() axisLabelFormatter.generatesDecimalNumbers = false axisLabelFormatter.numberStyle = NumberFormatter.Style.decimal //Define x-axis properties //x-axis intermediate interval 2 let xAxis = axisSet.xAxis xAxis?.majorIntervalLength = plotXInterval as NSNumber? xAxis?.minorTicksPerInterval = 4; xAxis?.minorTickLength = 5; xAxis?.majorTickLength = 7; xAxis?.title = "Time (s)" xAxis?.titleOffset = 25; xAxis?.labelFormatter = axisLabelFormatter //Define y-axis properties let yAxis = axisSet.yAxis yAxis?.majorIntervalLength = plotYInterval as NSNumber? yAxis?.minorTicksPerInterval = 4 yAxis?.minorTickLength = 5 yAxis?.majorTickLength = 7 yAxis?.title = "BPM" yAxis?.titleOffset = 30 yAxis?.labelFormatter = axisLabelFormatter //Define line plot and set line properties linePlot = CPTScatterPlot() linePlot?.dataSource = self graph?.add(linePlot!, to: plotSpace) //set line plot style let lineStyle = linePlot?.dataLineStyle!.mutableCopy() as! CPTMutableLineStyle lineStyle.lineWidth = 2 lineStyle.lineColor = CPTColor.white() linePlot!.dataLineStyle = lineStyle; let symbolLineStyle = CPTMutableLineStyle(style: lineStyle) symbolLineStyle.lineColor = CPTColor.white() let symbol = CPTPlotSymbol.ellipse() symbol.fill = CPTFill(color: CPTColor.white()) symbol.lineStyle = symbolLineStyle symbol.size = CGSize(width: 3.0, height: 3.0) linePlot?.plotSymbol = symbol; //set graph grid lines let gridLineStyle = CPTMutableLineStyle() gridLineStyle.lineColor = CPTColor.gray() gridLineStyle.lineWidth = 0.5 xAxis?.majorGridLineStyle = gridLineStyle yAxis?.majorGridLineStyle = gridLineStyle } func resetPlotRange() { plotXMaxRange = 121 plotXMinRange = -1 plotYMaxRange = 310 plotYMinRange = -1 plotXInterval = 20 plotYInterval = 50 let plotSpace = graph?.defaultPlotSpace as! CPTXYPlotSpace plotSpace.xRange = CPTPlotRange(location: NSNumber(value: plotXMinRange!), length: NSNumber(value: plotXMaxRange!)) plotSpace.yRange = CPTPlotRange(location: NSNumber(value: plotYMinRange!), length: NSNumber(value: plotYMaxRange!)) } func clearUI() { deviceName.text = "DEFAULT HRM"; battery.setTitle("N/A", for: UIControlState()) battery.tag = 0; hrLocation.text = "n/a"; hrValue.text = "-"; // Clear and reset the graph hrValues?.removeAllObjects() xValues?.removeAllObjects() resetPlotRange() graph?.reloadData() } func addHRvalueToGraph(data value: Int) { // In this method the new value is added to hrValues array hrValues?.add(NSDecimalNumber(value: value as Int)) // Also, we save the time when the data was received // 'Last' and 'previous' values are timestamps of those values. We calculate them to know whether we should automatically scroll the graph var lastValue : NSDecimalNumber var firstValue : NSDecimalNumber if xValues?.count > 0 { lastValue = xValues?.lastObject as! NSDecimalNumber firstValue = xValues?.firstObject as! NSDecimalNumber }else{ lastValue = 0 firstValue = 0 } let previous : Double = lastValue.subtracting(firstValue).doubleValue xValues?.add(NORHRMViewController.longUnixEpoch()) lastValue = xValues?.lastObject as! NSDecimalNumber firstValue = xValues?.firstObject as! NSDecimalNumber let last : Double = lastValue.subtracting(firstValue).doubleValue // Here we calculate the max value visible on the graph let plotSpace = graph!.defaultPlotSpace as! CPTXYPlotSpace let max = plotSpace.xRange.locationDouble + plotSpace.xRange.lengthDouble if last > max && previous <= max { let location = Int(last) - plotXMaxRange! + 1 plotSpace.xRange = CPTPlotRange(location: NSNumber(value: (location)), length: NSNumber(value: plotXMaxRange!)) } // Rescale Y axis to display higher values if value >= plotYMaxRange { while (value >= plotYMaxRange) { plotYMaxRange = plotYMaxRange! + 50 } plotSpace.yRange = CPTPlotRange(location: NSNumber(value: plotYMinRange!), length: NSNumber(value: plotYMaxRange!)) } graph?.reloadData() } //MARK: - NORScannerDelegate func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral){ // We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller bluetoothManager = aManager; bluetoothManager!.delegate = self; // The sensor has been selected, connect to it peripheral = aPeripheral; aPeripheral.delegate = self; let options = NSDictionary(object: NSNumber(value: true as Bool), forKey: CBConnectPeripheralOptionNotifyOnNotificationKey as NSCopying) bluetoothManager!.connect(aPeripheral, options: options as? [String : AnyObject]) } //MARK: - CPTPlotDataSource func numberOfRecords(for plot :CPTPlot) -> UInt { return UInt(hrValues!.count) } func number(for plot: CPTPlot, field fieldEnum: UInt, record idx: UInt) -> Any? { let fieldVal = NSInteger(fieldEnum) let scatterPlotField = CPTScatterPlotField(rawValue: fieldVal) switch (scatterPlotField!) { case .X: // The xValues stores timestamps. To show them starting from 0 we have to subtract the first one. return (xValues?.object(at: Int(idx)) as! NSDecimalNumber).subtracting(xValues?.firstObject as! NSDecimalNumber) case .Y: return hrValues?.object(at: Int(idx)) as AnyObject? } } //MARK: - CPRPlotSpaceDelegate func plotSpace(_ space: CPTPlotSpace, shouldScaleBy interactionScale: CGFloat, aboutPoint interactionPoint: CGPoint) -> Bool { return false } func plotSpace(_ space: CPTPlotSpace, willDisplaceBy proposedDisplacementVector: CGPoint) -> CGPoint { return CGPoint(x: proposedDisplacementVector.x, y: 0) } func plotSpace(_ space: CPTPlotSpace, willChangePlotRangeTo newRange: CPTPlotRange, for coordinate: CPTCoordinate) -> CPTPlotRange? { // The Y range does not change here if coordinate == CPTCoordinate.Y { return newRange; } // Adjust axis on scrolling let axisSet = space.graph?.axisSet as! CPTXYAxisSet if newRange.location.intValue >= plotXMinRange! { // Adjust axis to keep them in view at the left and bottom; // adjust scale-labels to match the scroll. axisSet.yAxis!.orthogonalPosition = NSNumber(value: newRange.locationDouble - Double(plotXMinRange!)) return newRange } axisSet.yAxis!.orthogonalPosition = 0 return CPTPlotRange(location: NSNumber(value: plotXMinRange!), length: NSNumber(value: plotXMaxRange!)) } //MARK: - CBCentralManagerDelegate func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOff { print("Bluetooth powered off") } else { print("Bluetooth powered on") } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async { self.deviceName.text = peripheral.name self.connectionButton.setTitle("DISCONNECT", for: UIControlState()) self.hrValues?.removeAllObjects() self.xValues?.removeAllObjects() self.resetPlotRange() } if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))){ UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .sound], categories: nil)) } NotificationCenter.default.addObserver(self, selector: #selector(NORHRMViewController.appDidEnterBackgroundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(NORHRMViewController.appDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) // Peripheral has connected. Discover required services peripheral.discoverServices([hrServiceUUID, batteryServiceUUID]) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to peripheral failed. Try again") self.connectionButton.setTitle("CONNCECT", for: UIControlState()) self.peripheral = nil self.clearUI() }); } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { self.connectionButton.setTitle("CONNECT", for: UIControlState()) self.peripheral = nil; self.clearUI() if NORAppUtilities.isApplicationInactive() { let name = peripheral.name ?? "Peripheral" NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.") } NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) }); } //MARK: - CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard error == nil else { print("An error occured while discovering services: \(error!.localizedDescription)") bluetoothManager!.cancelPeripheralConnection(peripheral) return } for aService : CBService in peripheral.services! { if aService.uuid.isEqual(hrServiceUUID){ print("HRM Service found") peripheral.discoverCharacteristics(nil, for: aService) } else if aService.uuid.isEqual(batteryServiceUUID) { print("Battery service found") peripheral.discoverCharacteristics(nil, for: aService) } } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard error == nil else { print("Error occurred while discovering characteristic: \(error!.localizedDescription)") bluetoothManager!.cancelPeripheralConnection(peripheral) return } if service.uuid.isEqual(hrServiceUUID) { for aCharactersistic : CBCharacteristic in service.characteristics! { if aCharactersistic.uuid.isEqual(hrMeasurementCharacteristicUUID) { print("Heart rate measurement characteristic found") peripheral.setNotifyValue(true, for: aCharactersistic) }else if aCharactersistic.uuid.isEqual(hrLocationCharacteristicUUID) { print("Heart rate sensor location characteristic found") peripheral.readValue(for: aCharactersistic) } } } else if service.uuid.isEqual(batteryServiceUUID) { for aCharacteristic : CBCharacteristic in service.characteristics! { if aCharacteristic.uuid.isEqual(batteryLevelCharacteristicUUID) { print("Battery level characteristic found") peripheral.readValue(for: aCharacteristic) } } } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { guard error == nil else { print("Error occurred while updating characteristic value: \(error!.localizedDescription)") return } DispatchQueue.main.async { if characteristic.uuid.isEqual(self.hrMeasurementCharacteristicUUID) { let value = self.decodeHRValue(withData: characteristic.value!) self.addHRvalueToGraph(data: Int(value)) self.hrValue.text = "\(value)" } else if characteristic.uuid.isEqual(self.hrLocationCharacteristicUUID) { self.hrLocation.text = self.decodeHRLocation(withData: characteristic.value!) } else if characteristic.uuid.isEqual(self.batteryLevelCharacteristicUUID) { let data = characteristic.value as NSData? let array : UnsafePointer<UInt8> = (data?.bytes)!.assumingMemoryBound(to: UInt8.self) let batteryLevel : UInt8 = array[0] let text = "\(batteryLevel)%" self.battery.setTitle(text, for: UIControlState.disabled) if self.battery.tag == 0 { if characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue > 0 { self.battery.tag = 1 // Mark that we have enabled notifications peripheral.setNotifyValue(true, for: characteristic) } } } } } //MARK: - UIApplicationDelegate callbacks func appDidEnterBackgroundCallback() { let name = peripheral?.name ?? "peripheral" NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name). It will collect data also in background.") } func appDidBecomeActiveCallback() { UIApplication.shared.cancelAllLocalNotifications() } //MARK: - Segue management override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { // The 'scan' seque will be performed only if connectedPeripheral == nil (if we are not connected already). return identifier != "scan" || peripheral == nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "scan" { // Set this contoller as scanner delegate let nc = segue.destination as! UINavigationController let controller = nc.childViewControllerForStatusBarHidden as! NORScannerViewController controller.filterUUID = hrServiceUUID controller.delegate = self } } //MARK: - Helpers static func longUnixEpoch() -> NSDecimalNumber { return NSDecimalNumber(value: Date().timeIntervalSince1970 as Double) } func decodeHRValue(withData data: Data) -> Int { let count = data.count / MemoryLayout<UInt8>.size var array = [UInt8](repeating: 0, count: count) (data as NSData).getBytes(&array, length:count * MemoryLayout<UInt8>.size) var bpmValue : Int = 0; if ((array[0] & 0x01) == 0) { bpmValue = Int(array[1]) } else { //Convert Endianess from Little to Big bpmValue = Int(UInt16(array[2] * 0xFF) + UInt16(array[1])) } return bpmValue } func decodeHRLocation(withData data:Data) -> String { let location = (data as NSData).bytes.bindMemory(to: UInt16.self, capacity: data.count) switch (location[0]) { case 0: return "Other" case 1: return "Chest" case 2: return "Wrist" case 3: return "Finger" case 4: return "Hand"; case 5: return "Ear Lobe" case 6: return "Foot" default: return "Invalid"; } } }
bsd-3-clause
41823a92519776f1c99ab4f89a937999
40.78453
197
0.624179
5.108984
false
false
false
false
invoy/CoreDataQueryInterface
Examples/TopHits/TopHits/SetupViewController.swift
1
2148
/* The MIT License (MIT) Copyright (c) 2015 Gregory Higley (Prosumma) 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 SetupViewController: UIViewController { @IBOutlet weak var applicationSubtitleLabel: UILabel! @IBOutlet weak var progressIndicatorView: UIActivityIndicatorView! @IBOutlet weak var yearLabel: UILabel! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: CoreDataController.ProgressNotification), object: nil, queue: nil) { notification in self.applicationSubtitleLabel.isHidden = true self.progressIndicatorView.startAnimating() self.yearLabel.text = "Processing \((notification as NSNotification).userInfo!["year"]!)…" self.yearLabel.isHidden = false } CoreDataController.sharedInstance.setup { NotificationCenter.default.removeObserver(observer) self.view.window!.rootViewController = self.storyboard!.instantiateViewController(withIdentifier: "search") } } }
mit
441af04f80e4a0a623b399e9c8a25fb7
43.708333
185
0.756291
5.109524
false
false
false
false
thatseeyou/iOSSDKExamples
Pages/UITextChcker.xcplaygroundpage/Contents.swift
1
1257
/*: # UITextChecker 다음과 같은 기능을 제공 * 오타찾기 * 자동완성 * 단어등록 */ import Foundation import UIKit UITextChecker.availableLanguages() /*: ### 오타찾기 : rangeOfMisspelledWordInString */ func ex1() { let textChecker = UITextChecker() let document = "I loev you" let language = "en_US" print("\(document.characters.count)") let rangeOfMisspelled = textChecker.rangeOfMisspelledWordInString(document, range: NSMakeRange(0, document.characters.count), startingAt: 0, wrap: false, language: language) if rangeOfMisspelled.location == NSNotFound { print("Not Found") } else { print(rangeOfMisspelled) textChecker.guessesForWordRange(rangeOfMisspelled, inString: document, language: language) } } /*: ### 자동완성 : completionsForPartialWordRange */ func ex2() { let textChecker = UITextChecker() let document = "lov" let language = "en_US" let completions = textChecker.completionsForPartialWordRange(NSMakeRange(0, document.characters.count), inString: document, language: language) if let completions = completions as? [String] { print(completions) } else { print("No completions") } } ex1() ex2()
mit
5b2899be2c8823952947b15724a499e7
20
177
0.684211
3.459538
false
false
false
false
GiantForJ/GYGestureUnlock
GYGestureUnlock/Classes/View/GYCircleInfoView.swift
1
1748
// // GYCircleInfoView.swift // GYGestureUnlock // // Created by zhuguangyang on 16/8/24. // Copyright © 2016年 Giant. All rights reserved. // import UIKit public class GYCircleInfoView: UIView { public init() { super.init(frame: CGRect.zero) lockViewPrepare() } public override init(frame: CGRect) { super.init(frame: frame) lockViewPrepare() } public func lockViewPrepare() { self.backgroundColor = CircleBackgroundColor for _ in 0..<9 { let circl = GYCircle() circl.type = CircleTye.circleTypeInfo addSubview(circl) } } public override func layoutSubviews() { super.layoutSubviews() let itemViewWH = CircleInfoRadius * 2 let marginValue = (self.frame.size.width - 3 * itemViewWH) / 3.0 (self.subviews as NSArray).enumerateObjects({ (object, idx, stop) in let row: NSInteger = idx % 3; let col = idx / 3; let x:CGFloat = marginValue * CGFloat(row) + CGFloat(row) * itemViewWH + marginValue/2 let y: CGFloat = marginValue * CGFloat(col) + CGFloat(col) * itemViewWH + marginValue/2 let frame = CGRect(x: x, y: y, width: itemViewWH, height: itemViewWH) //设置tag->用于记录密码的单元 (object as! UIView).tag = idx + 1 (object as! UIView).frame = frame }) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
72880fd44e812e1e80539a502e3102c9
24.716418
99
0.529309
4.463731
false
false
false
false
mzp/OctoEye
Sources/View/SMRippleView.swift
1
4249
// // SMRippleView // SMRippleView // // Created by Sanjay Maharjan on 5/25/16. // Copyright © 2016 Sanjay Maharjan. All rights reserved. // // fork from https://github.com/sanjaymhj/SMRippleExample/ import UIKit final internal class SMRippleView: UIView { private let originalFrame: CGRect private let interval: Float private let rippleEndScale: Float = 2 private let color: UIColor private let duration: TimeInterval private var timer: Timer? init(frame: CGRect, color: UIColor, interval: Float, duration: Double) { self.originalFrame = frame self.color = color self.interval = interval self.duration = TimeInterval(duration) let squareRect = CGRect(x: frame.minX, y: frame.minY, width: max(frame.width, frame.height), height: max(frame.width, frame.height)) super.init(frame: squareRect) self.startRipple() } func startRipple() { self.timer = Timer.scheduledTimer( timeInterval: Double(self.interval), target: self, selector: #selector(continuousRipples), userInfo: nil, repeats: true) DispatchQueue.main.async { self.continuousRipples() } } func stopAnimation() { self.timer?.invalidate() } private func getLayer() -> RippleCALayer { //Minimum bounds let pathFrame = CGRect(x: -self.bounds.midX, y: -self.bounds.midY, width: self.bounds.size.width, height: self.bounds.size.height) let path = UIBezierPath(roundedRect: pathFrame, cornerRadius: self.frame.size.height) let shapePosition = CGPoint(x: originalFrame.midX, y: originalFrame.midY) let circleShape = RippleCALayer() circleShape.path = path.cgPath // position set to Center of bounds. If set to origin, it will only expand to +x and +y circleShape.position = shapePosition circleShape.fillColor = self.color.cgColor // Opacity is 0 so it is invisible in initial state circleShape.opacity = 0 return circleShape } private func getAnimation() -> CAAnimationGroup { // Scale Animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) scaleAnimation.toValue = NSValue(caTransform3D: CATransform3DMakeScale(CGFloat(self.rippleEndScale), 1, 1)) // Alpha Animation let alphaAnimation = CABasicAnimation(keyPath: "opacity") alphaAnimation.fromValue = 1 alphaAnimation.toValue = 0 let animation = CAAnimationGroup() animation.animations = [scaleAnimation, alphaAnimation] animation.duration = self.duration animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) return animation } @objc private func continuousRipples() { let layer = getLayer() let animation = getAnimation() // To remove layer from super layer after animation completes animation.delegate = layer layer.animationDelegate = self layer.add(animation, forKey: nil) self.superview?.layer.addSublayer(layer) } required init?(coder aDecoder: NSCoder) { fatalError("not implemented") } } // Protocol and extension for removing layer from super layer after animation completes extension SMRippleView: AnimationDelegate { func animationDidStop(_ anim: CAAnimation, layer: CALayer, finished: Bool) { layer.removeFromSuperlayer() } } extension RippleCALayer: CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.animationDelegate?.animationDidStop(anim, layer: self, finished: flag) } } final private class RippleCALayer: CAShapeLayer { weak var animationDelegate: AnimationDelegate? } private protocol AnimationDelegate: class { func animationDidStop(_ anim: CAAnimation, layer: CALayer, finished: Bool) }
mit
2daf1ffc251cc1649aa22163a58c3d3b
32.448819
115
0.64854
4.905312
false
false
false
false
akuraru/PureViewIcon
PureViewIcon/Views/PVICaretRight.swift
1
1957
// // PVICaretRight.swift // // Created by akuraru on 2017/02/11. // import UIKit import SnapKit extension PVIView { func makeCaretRightConstraints() { base.snp.updateConstraints { (make) in make.width.equalToSuperview() make.height.equalToSuperview() make.center.equalToSuperview() } base.transform = resetTransform() before.setup(width: 2) main.setup(width: 2) after.setup(width: 2) // before before.top.alpha = 1 before.left.alpha = 0 before.right.alpha = 0 before.bottom.alpha = 0 before.view.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().dividedBy(13 / 17.0) make.width.equalToSuperview().multipliedBy(14 / 34.0) make.height.equalToSuperview().multipliedBy(2 / 34.0) } before.view.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_4)) // main main.top.alpha = 0 main.left.alpha = 0 main.right.alpha = 0 main.bottom.alpha = 0 main.view.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.equalToSuperview() make.height.equalToSuperview() } main.view.transform = resetTransform() // after after.top.alpha = 1 after.left.alpha = 0 after.right.alpha = 0 after.bottom.alpha = 0 after.view.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().dividedBy(21 / 17.0) make.width.equalToSuperview().multipliedBy(14 / 34.0) make.height.equalToSuperview().multipliedBy(2 / 34.0) } after.view.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_4)) } }
mit
b3572ce5594b812ec47d975e78720108
29.578125
82
0.57537
4.387892
false
false
false
false
tomtclai/swift-algorithm-club
Shortest Path (Unweighted)/ShortestPath.playground/Sources/Node.swift
11
758
public class Node: CustomStringConvertible, Equatable { public var neighbors: [Edge] public private(set) var label: String public var distance: Int? public var visited: Bool public init(label: String) { self.label = label neighbors = [] visited = false } public var description: String { if let distance = distance { return "Node(label: \(label), distance: \(distance))" } return "Node(label: \(label), distance: infinity)" } public var hasDistance: Bool { return distance != nil } public func remove(edge: Edge) { neighbors.remove(at: neighbors.index { $0 === edge }!) } } public func == (lhs: Node, rhs: Node) -> Bool { return lhs.label == rhs.label && lhs.neighbors == rhs.neighbors }
mit
a9d2251c8d7587e82a52f7d78b9d5d00
22.6875
65
0.645119
3.907216
false
false
false
false
Bouke/HAP
Sources/VaporHTTP/Utilities/RequestHandler.swift
1
6187
// swiftlint:disable all import Foundation public class RequestHandler: ChannelDuplexHandler { public typealias InboundIn = HTTPServerRequestPart public typealias InboundOut = HTTPRequest public typealias OutboundIn = HTTPResponse public typealias OutboundOut = HTTPServerResponsePart var state: RequestState = .ready public init() { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch unwrapInboundIn(data) { case .head(let head): switch state { case .ready: break default: assertionFailure("Unexpected state: \(state)") } state = .awaitingBody(head) case .body(var chunk): switch state { case .ready: assertionFailure("Unexpected state: \(state)") case .awaitingBody(let head): state = .collectingBody(head, nil) channelRead(context: context, data: data) case .collectingBody(let head, let existingBody): let body: ByteBuffer if var existing = existingBody { existing.writeBuffer(&chunk) body = existing } else { body = chunk } state = .collectingBody(head, body) case .waitingResponse: assertionFailure("Unexpected state: \(state)") } case .end(let tailHeaders): assert(tailHeaders == nil, "Tail headers are not supported") switch state { case .ready: assertionFailure("Unexpected state: \(state)") case .awaitingBody(let head): state = .waitingResponse(head) respond(to: head, body: .empty, context: context) case .collectingBody(let head, let body): state = .waitingResponse(head) let body: HTTPBody = body.flatMap(HTTPBody.init(buffer:)) ?? .empty respond(to: head, body: body, context: context) case .waitingResponse: assertionFailure("Unexpected state: \(state)") } } } private func respond(to head: HTTPRequestHead, body: HTTPBody, context: ChannelHandlerContext) { let req = HTTPRequest(head: head, body: body, channel: context.channel) context.fireChannelRead(wrapInboundOut(req)) } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { guard case let .waitingResponse(request) = state else { preconditionFailure("Unexpected state: \(state)") } let response = unwrapOutboundIn(data) serialize(response, for: request, context: context, promise: promise) state = .ready } private func serialize(_ res: HTTPResponse, for reqhead: HTTPRequestHead, context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { // add a RFC1123 timestamp to the Date header to make this // a valid request var reshead = res.head reshead.headers.add(name: "date", value: RFC1123DateCache.shared.currentTimestamp()) // add 'Connection' header if needed let connectionHeaders = reshead.headers[canonicalForm: "connection"].map { $0.lowercased() } if !connectionHeaders.contains("keep-alive") && !connectionHeaders.contains("close") { // the user hasn't pre-set either 'keep-alive' or 'close', so we might need to add headers reshead.headers.add(name: "Connection", value: reqhead.isKeepAlive ? "keep-alive" : "close") } // begin serializing context.write(wrapOutboundOut(.head(reshead)), promise: nil) if reqhead.method == .HEAD || res.status == .noContent { // skip sending the body for HEAD requests // also don't send bodies for 204 (no content) requests context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: promise) } else { switch res.body.storage { case .none: context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: promise) case .buffer(let buffer): writeAndflush(buffer: buffer, context: context, shouldClose: !reqhead.isKeepAlive, promise: promise) case .string(let string): var buffer = context.channel.allocator.buffer(capacity: string.count) buffer.writeString(string) writeAndflush(buffer: buffer, context: context, shouldClose: !reqhead.isKeepAlive, promise: promise) case .staticString(let string): var buffer = context.channel.allocator.buffer(capacity: string.utf8CodeUnitCount) buffer.writeStaticString(string) writeAndflush(buffer: buffer, context: context, shouldClose: !reqhead.isKeepAlive, promise: promise) case .data(let data): var buffer = context.channel.allocator.buffer(capacity: data.count) buffer.writeBytes(data) writeAndflush(buffer: buffer, context: context, shouldClose: !reqhead.isKeepAlive, promise: promise) case .dispatchData(let data): var buffer = context.channel.allocator.buffer(capacity: data.count) buffer.writeBytes(data) writeAndflush(buffer: buffer, context: context, shouldClose: !reqhead.isKeepAlive, promise: promise) } } } /// Writes a `ByteBuffer` to the context. private func writeAndflush(buffer: ByteBuffer, context: ChannelHandlerContext, shouldClose: Bool, promise: EventLoopPromise<Void>?) { if buffer.readableBytes > 0 { _ = context.write(wrapOutboundOut(.body(.byteBuffer(buffer)))) } _ = context.writeAndFlush(wrapOutboundOut(.end(nil))).map { if shouldClose { // close connection now context.close(promise: promise) } else { promise?.succeed(()) } } } } enum RequestState { case ready case awaitingBody(HTTPRequestHead) case collectingBody(HTTPRequestHead, ByteBuffer?) case waitingResponse(HTTPRequestHead) }
mit
a72431239c57bcba57d84953aa0c42c3
45.518797
145
0.620979
4.898654
false
false
false
false
mateuscampos/brejas
Brejas/Brejas/Beers/Controller/BeerDetailController.swift
1
1573
// // BeerDetailController.swift // Brejas // // Created by Mateus Campos on 02/07/17. // Copyright © 2017 Mateus Campos. All rights reserved. // import Foundation import UIKit class BeerDetailController: UIViewController, ViewCodingProtocol { var containerView: UIView = UIView() var beer: BeerModel? var beerDetailView: BeerDetailView = BeerDetailView() convenience init(beer: BeerModel) { self.init(nibName:nil, bundle:nil) self.beer = beer } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "Detalhes" self.setupViewConfiguration() if let beer = self.beer { self.fillBeerInfo(beer: beer) } } // MARK: - Actions func fillBeerInfo(beer: BeerModel) { self.beerDetailView.setupInfo(forBeer: beer) } // MARK: - ViewCodingProtocol func buildViewHierarchy() { self.view.addSubview(self.beerDetailView) } func setupConstraints() { self.beerDetailView.snp.makeConstraints { (make) in make.top.equalToSuperview() make.bottom.equalToSuperview() make.left.equalToSuperview() make.width.equalTo(UIScreen.main.bounds.width) } } }
mit
db8bd365455a6d0bbf938d6b9398a7c8
23.952381
82
0.624682
4.428169
false
false
false
false
aleufms/JeraUtils
JeraUtils/Form/FieldValidator.swift
1
5907
// // FieldValidator.swift // Pods // // Created by Alessandro Nakamuta on 5/12/16. // // import RxSwift import Material import RxCocoa public extension TextField { public var rx_errorText: AnyObserver<String?> { return UIBindingObserver(UIElement: self, binding: { (control, value) in if let value = value{ control.detail = value }else{ control.detail = nil } }).asObserver() } } public extension ObservableType where E == String { public func trim() -> Observable<String> { return map({ (text) -> String in return text.trim() }) } public func validate(fieldValidations: [FieldValidationError]) -> Observable<[FieldValidationError]?> { return flatMap({ (text) -> Observable<[FieldValidationError]?> in var otherTextSignal: Variable<String>? for fieldValidation in fieldValidations{ switch fieldValidation{ case .Equal(let text): otherTextSignal = text default: break } } if let otherTextSignal = otherTextSignal{ return otherTextSignal.asObservable().map({ (text2) -> [FieldValidationError]? in var fieldValidationErrors = [FieldValidationError]() for fieldValidation in fieldValidations{ if !fieldValidation.isValid(text){ fieldValidationErrors.append(fieldValidation) } } if fieldValidationErrors.count == 0{ return nil } //If field is empty, only show required error if fieldValidationErrors.contains(.Required){ return [.Required] } return fieldValidationErrors }) } return Observable.create({ (observer) -> Disposable in var fieldValidationErrors = [FieldValidationError]() for fieldValidation in fieldValidations{ if !fieldValidation.isValid(text){ fieldValidationErrors.append(fieldValidation) } } if fieldValidationErrors.count == 0{ observer.onNext(nil) observer.onCompleted() } //If field is empty, only show required error if fieldValidationErrors.contains(.Required){ observer.onNext([.Required]) observer.onCompleted() } observer.onNext(fieldValidationErrors) observer.onCompleted() return NopDisposable.instance }) }) } } public extension ObservableType where E == [FieldValidationError]? { public func validatorDescription() -> Observable<String?> { return map({ (fieldValidatorErrors) -> String? in if let fieldValidatorErrors = fieldValidatorErrors{ let fieldValidatorErrorStrings = fieldValidatorErrors.map({ (fieldValidatorError) -> String in return fieldValidatorError.description() }) return fieldValidatorErrorStrings.joinWithSeparator(", ") } return nil }) } } public enum FieldValidationError: Equatable{ case Required case MinLength(count: Int) case MaxLength(count: Int) case ExactLength(count: Int) case Email case Cpf case Equal(variable: Variable<String>) case Custom(isValidBlock: (String) -> Bool, invalidText: String) public func isValid(text: String) -> Bool{ switch self { case .Required: return text.characters.count > 0 case .MinLength(let count): return text.characters.count >= count case .MaxLength(let count): return text.characters.count <= count case .ExactLength(let count): return text.characters.count == count case .Email: return text.isValidEmail() case .Cpf: return CPF.validate(text) case .Equal(let variable): return text == variable.value case .Custom(let parameters): return parameters.isValidBlock(text) } } public func description() -> String{ switch self { case .Required: return "Campo requerido" case .MinLength(let count): return "Campo deve ter mais que \(count) caracteres" case .MaxLength(let count): return "Campo deve ter menos que \(count) caracteres" case .ExactLength(let count): return "Campo deve ter exatamente \(count) caracteres" case .Email: return "Não é um email válido" case .Cpf: return "CPF Inválido" case .Equal: return "Campos estão diferentes" case .Custom(let parameters): return parameters.invalidText } } } public func ==(a: FieldValidationError, b: FieldValidationError) -> Bool { switch (a, b) { case (.MinLength, .MinLength): return true case (.MaxLength, .MaxLength): return true case (.ExactLength, .ExactLength): return true case (.Required, .Required): return true case (.Email, .Email): return true case (.Cpf, .Cpf): return true case (.Equal, .Equal): return true default: return false } }
mit
f9812f7b0d9243278fe972f39c502006
31.977654
110
0.53304
5.360581
false
false
false
false
RBevilacqua/oauthSwift1.1
OAuthSwift/String+OAuthSwift.swift
1
3463
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { internal func indexOf(sub: String) -> Int? { var pos: Int? if let range = self.rangeOfString(sub) { if !range.isEmpty { pos = distance(self.startIndex, range.startIndex) } } return pos } internal subscript (r: Range<Int>) -> String { get { let startIndex = advance(self.startIndex, r.startIndex) let endIndex = advance(startIndex, r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String { let charactersToBeEscaped = ":/?&=;+!@#$()',*" as CFStringRef let charactersToLeaveUnescaped = "[]." as CFStringRef var raw: NSString = self let result = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, raw, charactersToLeaveUnescaped, charactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) return result as String } func parametersFromQueryString() -> Dictionary<String, String> { var parameters = Dictionary<String, String>() let scanner = NSScanner(string: self) var key: NSString? var value: NSString? while !scanner.atEnd { key = nil scanner.scanUpToString("=", intoString: &key) scanner.scanString("=", intoString: nil) value = nil scanner.scanUpToString("&", intoString: &value) scanner.scanString("&", intoString: nil) if (key != nil && value != nil) { parameters.updateValue(value! as String, forKey: key! as String) } } return parameters } //分割字符 func split(s:String)->[String]{ if s.isEmpty{ var x=[String]() for y in self{ x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } //去掉左右空格 func trim()->String{ return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } //是否包含字符串 func has(s:String)->Bool{ if (self.rangeOfString(s) != nil) { return true }else{ return false } } //是否包含前缀 func hasBegin(s:String)->Bool{ if self.hasPrefix(s) { return true }else{ return false } } //是否包含后缀 func hasEnd(s:String)->Bool{ if self.hasSuffix(s) { return true }else{ return false } } //统计长度 func length()->Int{ return countElements(self.utf16) } //统计长度(别名) func size()->Int{ return countElements(self.utf16) } //重复字符串 func repeat(times: Int) -> String{ var result = "" for i in 0..<times { result += self } return result } //反转 func reverse()-> String{ var s=self.split("").reverse() var x="" for y in s{ x+=y } return x } }
mit
8b403a5a362e6be6f6a9f90cdf7dbaad
24.156716
190
0.536043
4.768034
false
false
false
false
connienguyen/volunteers-iOS
VOLA/VOLA/ViewControllers/SignUpViewController.swift
1
4402
// // SignUpViewController.swift // VOLA // // Created by Connie Nguyen on 6/3/17. // Copyright © 2017 Systers-Opensource. All rights reserved. // import UIKit import FRHyperLabel let agreeLabelKey = "signup-agree.title.label" let tosPromptKey = "tos.title.label" let privacyPromptKey = "privacy.title.label" let signUpErrorKey = "signup-error.title.label" /// View controller allows user to sign up for an account class SignUpViewController: UIViewController { @IBOutlet weak var titleTextField: VLTextField! @IBOutlet weak var firstNameTextField: VLTextField! @IBOutlet weak var lastNameTextField: VLTextField! @IBOutlet weak var affiliationTextField: VLTextField! @IBOutlet weak var emailTextField: VLTextField! @IBOutlet weak var passwordTextField: VLTextField! @IBOutlet weak var confirmTextField: VLTextField! @IBOutlet weak var signUpAgreeLabel: VLHyperLabel! override func viewDidLoad() { super.viewDidLoad() titleTextField.validator = .required firstNameTextField.validator = .name lastNameTextField.validator = .name affiliationTextField.validator = .required emailTextField.validator = .email passwordTextField.validator = .password setUpValidatableFields() confirmTextField.addTarget(self, action: #selector(confirmFieldDidChange(_:)), for: .editingDidEnd) // Set up hyper label let signUpHandlers = [ HyperHandler(linkText: tosPromptKey.localized, linkHandler: { URL.applicationOpen(url: ABIURL.termsOfService) }), HyperHandler(linkText: privacyPromptKey.localized, linkHandler: { URL.applicationOpen(url: ABIURL.privacyPolicy) }) ] signUpAgreeLabel.setUpLabel(agreeLabelKey.localized, textSize: .small, handlers: signUpHandlers) } /// Validate confirmTextField on editing did end func confirmFieldDidChange(_ textField: VLTextField) { confirmTextField.isValid = confirmTextField.text == passwordTextField.text } } // MARK: - IBActions extension SignUpViewController { /** Display validation errors it there are any, otherwise make request to server to create an account */ @IBAction func onSignUpPressed(_ sender: Any) { let errorDescriptions = validationErrorDescriptions guard let title = titleTextField.text, let firstName = firstNameTextField.text, let lastName = lastNameTextField.text, let affiliation = affiliationTextField.text, let email = emailTextField.text, let password = passwordTextField.text, let confirm = confirmTextField.text, password == confirm, errorDescriptions.isEmpty else { let errorMessge = errorDescriptions.joinLocalized() showErrorAlert(errorTitle: VLError.validation.localizedDescription, errorMessage: errorMessge) return } displayActivityIndicator() LoginManager.shared.login(.emailSignup(title: title, firstName: firstName, lastName: lastName, affiliation: affiliation, email: email, password: password)) .then { [weak self] (success) -> Void in guard let `self` = self, success else { return } self.dismiss(animated: true, completion: nil) }.catch { [weak self] error in Logger.error(error) guard let `self` = self else { return } self.showErrorAlert(errorTitle: signUpErrorKey.localized, errorMessage: error.localizedDescription) }.always { [weak self] in self?.removeActivityIndicator() } } } // MARK: - Validatable; protocol to validate applicable text fields on view controller extension SignUpViewController: Validatable { var fieldsToValidate: [VLTextField] { return [titleTextField, firstNameTextField, lastNameTextField, affiliationTextField, emailTextField, passwordTextField] } }
gpl-2.0
c4c7e588dc2b4a11f41ad08d2d81acbb
37.946903
127
0.629175
5.386781
false
false
false
false
ccdeccdecc/ccemoticon
表情键盘/表情键盘/ViewController.swift
1
1097
// // ViewController.swift // 表情键盘 // // Created by apple on 15/11/8. // Copyright © 2015年 eason. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // 设置自定义的键盘 textView.inputView = emoticonVC.view print(CCEmoticonPackage.packages()) // emoji() } ///将16进制的0x1f603转成emoji 表情 private func emoji() { let code = "0x1f603" //扫描器 let scanner = NSScanner(string: code) //存储扫描器 var value: UInt32 = 0 scanner.scanHexInt(&value) print("扫描结果:\(value)") let c = Character(UnicodeScalar(value)) let str = String(c) print("str:\(str)") textView.text = str } //MARK: - 懒加载 private lazy var emoticonVC: CCEmoticonViewController = { let controller = CCEmoticonViewController() return controller }() }
apache-2.0
96f2233c55f84dd8ac53496cb1fc6dc1
20.333333
61
0.576172
4.196721
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/Blog+Lookup.swift
1
4761
import Foundation /// An extension dedicated to looking up and returning blog objects public extension Blog { /// Lookup a Blog by ID /// /// - Parameters: /// - id: The ID associated with the blog. /// /// On a WPMU site, this is the `blog_id` field on the [the wp_blogs table](https://codex.wordpress.org/Database_Description#Table:_wp_blogs). /// - context: An NSManagedObjectContext containing the `Blog` object with the given `blogID`. /// - Returns: The `Blog` object associated with the given `blogID`, if it exists. static func lookup(withID id: Int, in context: NSManagedObjectContext) throws -> Blog? { return try lookup(withID: Int64(id), in: context) } /// Lookup a Blog by ID /// /// - Parameters: /// - id: The ID associated with the blog. /// /// On a WPMU site, this is the `blog_id` field on the [the wp_blogs table](https://codex.wordpress.org/Database_Description#Table:_wp_blogs). /// - context: An NSManagedObjectContext containing the `Blog` object with the given `blogID`. /// - Returns: The `Blog` object associated with the given `blogID`, if it exists. static func lookup(withID id: Int64, in context: NSManagedObjectContext) throws -> Blog? { let fetchRequest = NSFetchRequest<Self>(entityName: Blog.entityName()) fetchRequest.predicate = NSPredicate(format: "blogID == %ld", id) return try context.fetch(fetchRequest).first } /// Lookup a Blog by ID /// /// - Parameters: /// - id: The NSNumber-wrapped ID associated with the blog. /// /// On a WPMU site, this is the `blog_id` field on the [the wp_blogs table](https://codex.wordpress.org/Database_Description#Table:_wp_blogs). /// - context: An NSManagedObjectContext containing the `Blog` object with the given `blogID`. /// - Returns: The `Blog` object associated with the given `blogID`, if it exists. @objc static func lookup(withID id: NSNumber, in context: NSManagedObjectContext) -> Blog? { // Because a `nil` NSNumber can be passed from Objective-C, we can't trust the object // to have a valid value. For that reason, we'll unwrap it to an `int64` and look that up instead. // That way, if the `id` is `nil`, it'll return nil instead of crashing while trying to // assemble the predicate as in `NSPredicate("blogID == %@")` try? lookup(withID: id.int64Value, in: context) } /// Lookup a Blog by its hostname /// /// - Parameters: /// - hostname: The hostname of the blog. /// - context: An `NSManagedObjectContext` containing the `Blog` object with the given `hostname`. /// - Returns: The `Blog` object associated with the given `hostname`, if it exists. @objc(lookupWithHostname:inContext:) static func lookup(hostname: String, in context: NSManagedObjectContext) -> Blog? { try? BlogQuery().hostname(containing: hostname).blog(in: context) } /// Lookup a Blog by WP.ORG Credentials /// /// - Parameters: /// - username: The username associated with the blog. /// - xmlrpc: The xmlrpc URL address /// - context: An NSManagedObjectContext containing the `Blog` object with the given `blogID`. /// - Returns: The `Blog` object associated with the given `username` and `xmlrpc`, if it exists. static func lookup(username: String, xmlrpc: String, in context: NSManagedObjectContext) -> Blog? { let service = BlogService(managedObjectContext: context) return service.findBlog(withXmlrpc: xmlrpc, andUsername: username) } @objc(countInContext:) static func count(in context: NSManagedObjectContext) -> Int { BlogQuery().count(in: context) } @objc(wpComBlogCountInContext:) static func wpComBlogCount(in context: NSManagedObjectContext) -> Int { BlogQuery().hostedByWPCom(true).count(in: context) } @objc(selfHostedInContext:) static func selfHosted(in context: NSManagedObjectContext) -> [Blog] { (try? BlogQuery().hostedByWPCom(false).blogs(in: context)) ?? [] } /// Find a cached comment with given ID. /// /// - Parameter id: The comment id /// - Returns: The `Comment` object associated with the given id, or `nil` if none is found. @objc func comment(withID id: NSNumber) -> Comment? { comment(withID: id.int32Value) } /// Find a cached comment with given ID. /// /// - Parameter id: The comment id /// - Returns: The `Comment` object associated with the given id, or `nil` if none is found. func comment(withID id: Int32) -> Comment? { (comments as? Set<Comment>)?.first { $0.commentID == id } } }
gpl-2.0
e389a8e3e4a56c1160e62c04a7e9fd00
44.342857
150
0.650914
4.118512
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/Comments/Views/Cells/CommentsErrorCell.swift
1
2500
import Library import Prelude import UIKit final class CommentsErrorCell: UITableViewCell, ValueCell { private let iconImageView = UIImageView() private let messageLabel = UILabel() private let rootStackView: UIStackView = { UIStackView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() // MARK: - Lifecycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.bindStyles() self.configureViews() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Styles override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() _ = self.rootStackView |> \.axis .~ .vertical |> \.distribution .~ .fillProportionally |> \.alignment .~ .center |> \.spacing .~ Styles.grid(2) _ = self.messageLabel |> messageLabelStyle _ = self.iconImageView |> UIImageView.lens.image .~ Library.image(named: "icon--alert") |> \.tintColor .~ .ksr_black } // MARK: - Configuration func configureWith(value _: Void) { self.messageLabel.text = Strings.Something_went_wrong_pull_to_refresh() } private func configureViews() { _ = (self.rootStackView, self) |> ksr_addSubviewToParent() _ = ([self.iconImageView, self.messageLabel], self.rootStackView) |> ksr_addArrangedSubviewsToStackView() NSLayoutConstraint.activate([ self.iconImageView.heightAnchor.constraint(equalToConstant: Styles.grid(4)), self.iconImageView.widthAnchor.constraint(equalToConstant: Styles.grid(4)), self.rootStackView.centerYAnchor.constraint(equalTo: self.centerYAnchor), self.rootStackView.heightAnchor.constraint(equalToConstant: Styles.grid(9)), self.rootStackView.leadingAnchor.constraint( equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: Styles.grid(1) ), self.rootStackView.trailingAnchor.constraint( equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: -Styles.grid(1) ) ]) } } // MARK: - Styles private let messageLabelStyle: LabelStyle = { label in label |> \.lineBreakMode .~ .byWordWrapping |> \.numberOfLines .~ 0 |> \.adjustsFontForContentSizeCategory .~ true |> \.font .~ UIFont.ksr_subhead() |> \.textAlignment .~ .center |> \.textColor .~ UIColor.ksr_support_700 }
apache-2.0
7851d55e0b8cbd0459118bc803963b13
27.735632
82
0.678
4.752852
false
false
false
false
naptics/PlainPing
Pod/Classes/PlainPing.swift
1
1969
// // PlainPing.swift // Pods // // Created by Jonas Schoch on 11.02.16. // // import Foundation open class PlainPing: SimplePingAdapterDelegate { fileprivate var pingStartTime: TimeInterval = 0 fileprivate var pingAdapter:SimplePingAdapter! /// completion of a ping public typealias PlainPingCompletion = (_ elapsedTimeMs: Double?, _ error:Error?) -> () fileprivate var completionBlock: PlainPingCompletion! // MARK: - main work /** perform a single ping to a given `hostName` - parameter hostName: a hostname (www.apple.com) or an IP-Address - parameter timeout: (optional, default 3) time in seconds to wait for an answer - parameter completionBlock: getting called after the ping request has finished or failed */ open class func ping(_ hostName:String, withTimeout timeout:TimeInterval = 3, completionBlock: @escaping PlainPingCompletion) { let plainPing = PlainPing() plainPing.pingAdapter = SimplePingAdapter() plainPing.pingAdapter.delegate = plainPing plainPing.completionBlock = completionBlock plainPing.pingAdapter.startPing(hostName, timeout: timeout) } fileprivate func finalizePing(_ latency:TimeInterval? = nil, error:Error? = nil) { if let latency = latency { let elapsedTimeMs = latency*1000 self.completionBlock?(elapsedTimeMs, error) } else { self.completionBlock?(nil, error) } pingAdapter.delegate = nil pingAdapter = nil } // MARK: - Simple Ping Adapter Delegate func didSendPing() { pingStartTime = Date.timeIntervalSinceReferenceDate } func didReceivePong() { let latency = Date.timeIntervalSinceReferenceDate - pingStartTime finalizePing(latency) } func didFailPingWithError(_ error: Error) { finalizePing(error:error) } }
mit
d35d1fd46e22a05eb1408c80bfa39beb
30.253968
131
0.655155
4.837838
false
false
false
false
RylynnLai/V2EX--practise
V2EX/Model/RLTopic.swift
1
4002
// // RLTopic.swift // V2EX // // Created by LLZ on 16/3/31. // Copyright © 2016年 ucs. All rights reserved. // import UIKit class RLTopic: NSObject { var ID:String? var title:String? var url:String? var content:String? var content_rendered:String? var replies:String? lazy var member:RLMember = {return RLMember.init()}() lazy var node:RLNode = {return RLNode()}() var created:String? var createdTime:String? var last_modified:String? var last_touched:String? override static func mj_replacedKeyFromPropertyName() -> [NSObject : AnyObject]! { return ["ID":"id"] } //解析HTML,获取标题等简单数据 internal class func parserHTMLStrs(resArr:NSArray) -> NSMutableArray { let topics = NSMutableArray.init(capacity: resArr.count) for str in resArr { let topic = RLTopic.init() var rangeStart = (str as! NSString).rangeOfString("<img src=\"") var tempStr = (str as! NSString).substringFromIndex(rangeStart.location + rangeStart.length) var rangEnd = (tempStr as NSString).rangeOfString("\" class=\"avatar\"") topic.member.avatar_normal = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("class=\"item_title\"><a href=\"/t/") tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("#") topic.ID = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("reply") tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("\">") topic.replies = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("\">") tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("</a>") topic.title = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("class=\"node\" href=\"/go/") tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("\">") topic.node.name = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("\">") tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("</a>") topic.node.title = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("href=\"/member/") tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("\">") topic.member.username = (tempStr as NSString).substringToIndex(rangEnd.location) rangeStart = (tempStr as NSString).rangeOfString("</strong> &nbsp;•&nbsp;") if rangeStart.location == NSNotFound {continue} tempStr = (tempStr as NSString).substringFromIndex(rangeStart.location + rangeStart.length) rangEnd = (tempStr as NSString).rangeOfString("&nbsp;•&nbsp;") if rangEnd.location == NSNotFound {rangEnd = (tempStr as NSString).rangeOfString("</span>")} topic.createdTime = (tempStr as NSString).substringToIndex(rangEnd.location) topics.addObject(topic) } return topics } }
mit
8a7540145a268f75c03a7f9ecf88b53a
46.86747
104
0.633275
4.635939
false
false
false
false
brentdax/SQLKit
Sources/CorePostgreSQL/Execute.swift
1
8816
// // Execute.swift // LittlinkRouterPerfect // // Created by Brent Royal-Gordon on 11/28/16. // // import Foundation import libpq extension PGConn { /// Execute one or more SQL statements, returning the result of the last /// statement. /// /// - Parameter sql: The SQL to run. /// - Returns: The result of the last statement in the SQL to run. /// - Throws: `SQLError.executionFailed` if any of the statements failed. /// /// - Note: If you need to substitute any values into the statement, use /// `execute(_:with:resultingIn:)` instead. That method will pass the /// parameters out-of-band, avoiding the risk of a SQL injection attack. /// /// - RecommendedOver: `PQexec` public func execute(_ sql: String) throws -> PGResult { let resultPointer = PQexec(pointer, sql)! return try PGResult(pointer: resultPointer) } /// Executes a SQL statement, binding the indicated parameter raw values to any /// placeholders with the indicated types. /// /// - Parameter sql: The SQL to run, with placeholders of the form `$1`, `$2`, /// etc. marking the parameters. /// - Parameter parameterValues: The parameters expressed as `PGRawValue`s. /// `nil` values will be treated as `NULL`. /// - Parameter parameterTypes: The types of the parameters. `nil` or /// unspecified parameters will have a type automatically chosen. /// - Parameter resultFormat: The format the columns in the result should be /// returned in. This should be `textual` unless all of the types /// of the columns conform to `SQLBinaryValue`. /// - Returns: The result of the statement. /// - Throws: `SQLError.executionFailed` if the statement failed. /// /// - Note: This call requires you to manually create `PGRawValue`s for the /// parameters. It will usually be more convenient to use /// `execute(_:with:resultingIn:)`, which automatically converts its /// `PGValue` parameters into `PGRawValue`s. /// /// - RecommendedOver: `PQexecParams` public func execute(_ sql: String, withRaw parameterValues: [PGRawValue?], ofTypes parameterTypes: [PGType?] = [], resultingIn resultFormat: PGRawValue.Format = .textual) throws -> PGResult { var typeOids = oids(of: parameterTypes) // We need to pad this to the same length as the other arrays. let shortfall = parameterValues.count - parameterTypes.count if shortfall > 0 { typeOids += repeatElement(PGType.automaticOid, count: shortfall) } let resultPointer = withDeconstructed(parameterValues) { valueBuffers, lengths, formats in PQexecParams(pointer, sql, Int32(valueBuffers.count), typeOids, valueBuffers, lengths, formats, resultFormat.rawValue)! } return try PGResult(pointer: resultPointer) } /// Executes a SQL statement, binding the indicated parameter values to any /// placeholders. /// /// - Parameter sql: The SQL to run, with placeholders of the form `$1`, `$2`, /// etc. marking the parameters. /// - Parameter parameterValues: The parameters, which must be `PGValue`s. /// `nil` values will be treated as `NULL`. /// - Parameter resultFormat: The format the columns in the result should be /// returned in. This should be `textual` unless all of the types /// of the columns conform to `SQLBinaryValue`. /// - Returns: The result of the statement. /// - Throws: `SQLError.executionFailed` if the statement failed. /// /// - RecommendedOver: `PQexecParams`, `execute(_:withRaw:ofTypes:resultingIn:)` public func execute(_ sql: String, with parameterValues: [PGValue?], resultingIn resultFormat: PGRawValue.Format = .textual) throws -> PGResult { let (rawParameters, types) = rawValues(of: parameterValues) return try execute(sql, withRaw: rawParameters, ofTypes: types, resultingIn: resultFormat) } /// Prepares a SQL statement for later execution. /// /// - Parameter sql: The SQL to run, with placeholders of the form `$1`, `$2`, /// etc. marking the parameters. /// - Parameter types: The types of the parameters. `nil` or unspecified /// parameters will have a type automatically chosen. /// - Parameter name: The name of the prepared statement. If `nil`, a name /// will be generated automatically. /// - Returns: A `PGPreparedStatement` instance which can be used to execute /// the query. /// - Throws: `SQLError.executionFailed` if preparing the statement failed. /// /// - RecommendedOver: `PQprepare` public func prepare(_ sql: String, withRawTypes types: [PGType?] = [], name: String? = nil) throws -> PGPreparedStatement { let name = name ?? ProcessInfo.processInfo.globallyUniqueString let typeOids = oids(of: types) let resultPointer = PQprepare(pointer, name, sql, Int32(typeOids.count), typeOids)! _ = try PGResult(pointer: resultPointer) return PGPreparedStatement(connection: self, name: name, deallocatingOnDeinit: true) } } extension PGPreparedStatement { /// Executes a prepared SQL statement, binding the indicated parameter raw /// values to any placeholders. /// /// - Parameter parameterValues: The parameters expressed as `PGRawValue`s. /// `nil` values will be treated as `NULL`. /// - Parameter resultFormat: The format the columns in the result should be /// returned in. This should be `textual` unless all of the types /// of the columns conform to `SQLBinaryValue`. /// - Returns: The result of the statement. /// - Throws: `SQLError.executionFailed` if the statement failed. /// /// - Note: This call requires you to manually create `PGRawValue`s for the /// parameters. It will usually be more convenient to use /// `execute(with:resultingIn:)`, which automatically converts its /// `PGValue` parameters into `PGRawValue`s. /// /// - Precondition: The prepared statement has not been deallocated. /// /// - RecommendedOver: `PQexecPrepared` public func execute(withRaw parameterValues: [PGRawValue?], resultingIn resultFormat: PGRawValue.Format = .textual) throws -> PGResult { guard let name = self.name else { preconditionFailure("Called execute(with:) on deallocated prepared statement") } let resultPointer = withDeconstructed(parameterValues) { valueBuffers, lengths, formats in PQexecPrepared(self.connection.pointer, name, Int32(valueBuffers.count), valueBuffers, lengths, formats, resultFormat.rawValue)! } return try PGResult(pointer: resultPointer) } /// Executes a prepared SQL statement, binding the indicated parameter /// values to any placeholders. /// /// - Parameter parameterValues: The parameters, which must be `PGValue`s. /// `nil` values will be treated as `NULL`. /// - Parameter resultFormat: The format the columns in the result should be /// returned in. This should be `textual` unless all of the types /// of the columns conform to `SQLBinaryValue`. /// - Returns: The result of the statement. /// - Throws: `SQLError.executionFailed` if the statement failed. /// /// - Precondition: The prepared statement has not been deallocated. /// /// - RecommendedOver: `PQexecPrepared` public func execute(with parameterValues: [PGValue?], resultingIn resultFormat: PGRawValue.Format = .textual) throws -> PGResult { let (rawParameters, _) = rawValues(of: parameterValues) return try execute(withRaw: rawParameters, resultingIn: resultFormat) } } fileprivate func withDeconstructed<R>(_ parameterValues: [PGRawValue?], do body: (_ buffers: [UnsafePointer<Int8>?], _ lengths: [Int32], _ formats: [Int32]) throws -> R) rethrows -> R { var datas: [Data?] = [] var lengths: [Int32] = [] var formats: [Int32] = [] for value in parameterValues { let data = value?.data let length = Int32(data?.count ?? 0) let format = value?.format ?? .textual datas.append(data) lengths.append(length) formats.append(format.rawValue) } return try withUnsafePointers(to: datas) { try body($0, lengths, formats) } }
mit
d7eb1c2661f279f7d74a67aad43d1ab0
47.977778
195
0.633394
4.484232
false
false
false
false
BrunoMazzo/CocoaHeadsApp
CocoaHeadsAppTests/SettingCoordinatorTests.swift
3
2584
@testable import CocoaHeadsApp import Quick import Nimble import CPDAcknowledgements class SettingsCoordinatorTests: QuickSpec { var settingsCoordinator: SettingsCoordinator! var coordinatorDelegate: CoordinatorDelegateMock! override func spec() { describe("MeetupCoordinator") { beforeEach { self.coordinatorDelegate = CoordinatorDelegateMock() self.settingsCoordinator = SettingsCoordinator(delegate: self.coordinatorDelegate) } context("object creation") { it("should have animate set") { expect(self.settingsCoordinator.animate) == true } } context("on start") { var result: UIViewController! beforeEach { result = self.settingsCoordinator.start() } it("should return a navigationController") { expect(result).to(beAnInstanceOf(UINavigationController.self)) } it("should return a MeetupListViewController as rootViewController") { let rootViewController = result as! UINavigationController expect(rootViewController.viewControllers[0]).to(beAnInstanceOf(SettingsViewController)) } context("settingsViewController") { var settings: SettingsViewController! var rootViewController: UINavigationController! beforeEach{ self.settingsCoordinator.animate = false rootViewController = result as! UINavigationController settings = rootViewController.viewControllers[0] as! SettingsViewController } it("should have the coordinator as delegate") { expect(settings.delegate).to(be(self.settingsCoordinator)) } it("should navigate to CPDAcknowledgementsViewController on userDidSelect(.Acknowledgements)") { settings.delegate.userDidSelect(.Acknowledgements) expect(rootViewController.viewControllers[1]).to(beAnInstanceOf(CPDAcknowledgementsViewController.self)) } } } } } }
mit
178a28373a181ee8d7575c9c95e6dcd1
39.390625
128
0.534443
7.446686
false
false
false
false
oscarqpe/machine-learning-algorithms
Swift CNN/CapaCNN.swift
1
1480
// // CapaCNN.swift // Pruebas Swift CNN // // Created by Andre Valdivia on 15/05/16. // Copyright © 2016 Andre Valdivia. All rights reserved. // import Foundation class CapaCNN { var CapaAnterior:CapaCNN? var CapaSiguiente:CapaCNN? var id:Int = 0 internal let rows:Int internal let cols:Int init(rows:Int, cols:Int){ self.rows = rows self.cols = cols } // subscript(row: Int) -> Matrix { // get { // switch type{ // case .Conv: // return convoluciones![row] // case .Pool: // return pools![row] // default: // print("Hubo un error en subscript CNN") // return convoluciones![row] // } // } // set(va) { // switch type{ // case .Conv: // convoluciones![row] = va as! Conv // case .Pool: // pools![row] = va as! Pool // default: // print("Hubo un error en subscript CNN") // convoluciones![row] = va as! Conv // } // } // } // func train(){ // switch type{ // case .Conv: // for m in convoluciones!{ // m.convul() // } // case .Pool: // for m in pools!{ // m.pool() // } // default: // print("Error en train") // // } // } }
gpl-3.0
ec3db10c8561bbbb388211af3c10a7ac
23.666667
60
0.431373
3.431555
false
false
false
false
dfortuna/theCraic3
theCraic3/Main/Settings/SettingsTVC.swift
1
7232
// // SettingsTabVC.swift // Project01 // // Created by Denis Fortuna on 5/05/2017. // Copyright © 2017 Denis. All rights reserved. // import UIKit import CoreLocation class SettingsTVC: UITableViewController, CLLocationManagerDelegate { var model = UserModel() var removeEventsIDs = [String]() let facebookService = FacebookService.shared override func viewDidLoad() { super.viewDidLoad() self.title = "Settings" self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 150 manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyKilometer manager.requestWhenInUseAuthorization() manager.startUpdatingLocation() } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() } func formatAlert(event: Event?, title: String?, message: String, style: UIAlertActionStyle){ let alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: style, handler: { (action) in // if event != nil { // self.event = event! // } })) present(alert, animated: true, completion: nil) } // MARK: - TableView Delegate var cellsID = ["SearchTagsCell", "CategoriesCell", "priceRangeCell", "MaxDistanceCell", "SearchGenderCell", "MapFriendsCell"] override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellsID.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellID = cellsID[indexPath.row] switch cellID { case "SearchTagsCell": let cell = tableView.dequeueReusableCell(withIdentifier: "TagsCell", for: indexPath) as! InputTagsTableViewCell cell.delegate = self cell.updateUI(tags: model.searchingTags, withTitle: true) return cell case "CategoriesCell": let cell = tableView.dequeueReusableCell(withIdentifier: "CategoriesCell", for: indexPath) as! ChooseCategoryTVCell cell.delegate = self var currentCategory = model.currenteCategory if currentCategory == "" { currentCategory = "-- Select --" } cell.categories = model.categories cell.setCategory(category: currentCategory) return cell case "priceRangeCell": let cell = tableView.dequeueReusableCell(withIdentifier: "priceRangeCell", for: indexPath) as! ChoosepriceTVCell cell.delegate = self var currentPrice = model.currenteprice if currentPrice == "" { currentPrice = "-- Select --" } cell.priceRange = model.priceRange cell.setprice(price: currentPrice) return cell case "MaxDistanceCell": let cell = tableView.dequeueReusableCell(withIdentifier: "MaxDistanceCell", for: indexPath) as! MaximumDistanceTVCell cell.delegate = self var currentDistance = model.maxDistance cell.setDistance(distance: currentDistance) return cell case "SearchGenderCell": let cell = tableView.dequeueReusableCell(withIdentifier: "SearchGenderCell", for: indexPath) as! GenderTVCell if model.genderToSearch == "" { cell.genderSelectedLabel.text = "Men & Women >" } else { cell.genderSelectedLabel.text = "\(model.genderToSearch) >" } return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: "MapFriendsCell", for: indexPath) as! MapFriendsEventsTVCell cell.delegate = self cell.setupCell(switchStatus: (model.searchForFriends)) return cell } } // MARK: - CoreLocation Delegate let manager = CLLocationManager() var userLoaction: CLLocation? = nil { didSet{ manager.stopUpdatingLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { userLoaction = locations[0] } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { case "ShowSelectGender": if let destinationVC = segue.destination as? GenderSelectionTVC { destinationVC.currentGender = (model.genderToSearch) destinationVC.delegate = self } default: break } } } extension SettingsTVC: ChooseGenderDelegate { func handleGender(sender: GenderSelectionTVC) { model.genderToSearch = sender.currentGender tableView.reloadData() } } extension SettingsTVC: ChooseCategoryDelegate { func handleCategory(sender: ChooseCategoryTVCell) { model.currenteCategory = sender.currentCategory } } extension SettingsTVC: ChoosepriceDelegate { func handleprice(sender: ChoosepriceTVCell) { model.currenteprice = sender.priceRangeTextField.text! } } extension SettingsTVC: MaxDistanceDelegate { func handleDistance(sender: MaximumDistanceTVCell) { model.maxDistance = sender.currentDistance! } } // MARK: - Tags Delegate extension SettingsTVC: TagsProtocol { func tagAdded(sender: InputTagsTableViewCell) { } func emitAlertSpecialCharacters(sender: InputTagsTableViewCell) { formatAlert(event: nil, title: "Tags can't have special characters:", message: ". $ [ ] # /", style: .default) } } extension SettingsTVC: MapFriendsDelegate { func handleLogoff(sender: MapFriendsEventsTVCell) { facebookService.logoff() let login = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController self.present(login, animated: true, completion: nil) } func handleContact(sender: MapFriendsEventsTVCell) { let appURL = URL(string: "fb://profile/1536425579779197")! let webURL = URL(string: "https://web.facebook.com/The-Craic-App-1536425579779197")! let application = UIApplication.shared if application.canOpenURL(appURL as URL) { application.open(appURL as URL) } else { application.open(webURL as URL) } } func handleMapFriends(sender: MapFriendsEventsTVCell) { if let searchForFriends = sender.mapFriendsCurrentState { model.searchForFriends = searchForFriends } } }
apache-2.0
a3f935e1be5fd8d8a18df245a4edf855
34.62069
129
0.636841
5.056643
false
false
false
false
zhuhaow/NEKit
src/Crypto/HMAC.swift
1
1225
import Foundation import CommonCrypto public struct HMAC { public static func final(value: String, algorithm: HashAlgorithm, key: Data) -> Data { let data = value.data(using: String.Encoding.utf8)! return final(value: data, algorithm: algorithm, key: key) } public static func final(value: Data, algorithm: HashAlgorithm, key: Data) -> Data { var result = Data(count: algorithm.digestLength) _ = value.withUnsafeBytes { v in result.withUnsafeMutableBytes { res in key.withUnsafeBytes { k in CCHmac(algorithm.HMACAlgorithm, k.baseAddress!, key.count, v.baseAddress!, value.count, res.baseAddress!) } } } return result } public static func final(value: UnsafeRawPointer, length: Int, algorithm: HashAlgorithm, key: Data) -> Data { var result = Data(count: algorithm.digestLength) _ = result.withUnsafeMutableBytes { res in key.withUnsafeBytes { k in CCHmac(algorithm.HMACAlgorithm, k.baseAddress!, key.count, value, length, res.baseAddress!) } } return result } }
bsd-3-clause
1d8951ce023d84d9683f6be9dea750d0
34
129
0.6
4.822835
false
false
false
false
ilk33r/IORunner
IORunnerBin/Application.swift
1
43527
// // Application.swift // IORunner // // Created by ilker özcan on 04/07/16. // // #if os(Linux) import Glibc #else import Darwin #endif import IOIni import Foundation import IORunnerExtension import IOGUI internal final class Application { private var logger: Logger! private var appConfig: Config private var appArguments: Arguments private var worker: AppWorker! private var appExtensions: DynamicLoader! private var signalHandler: SignalHandler! private var mainGUI: GUIWidgets! private var inGuiLoop = false private var isModuleWidgetActive = false init(appConfig: Config, appArguments: Arguments) { self.appConfig = appConfig self.appArguments = appArguments let currentLogLevel: Int if let logLevel = appConfig["Logging"]?["LogLevel"] { currentLogLevel = Int(logLevel)! }else{ currentLogLevel = 2 } let currentLogFilePath: String if let logFile = appConfig["Logging"]?["LogFile"] { currentLogFilePath = logFile }else{ currentLogFilePath = "./" + Constants.APP_PACKAGE_NAME + ".log" } let maxLogFileSize: Int if let maxSize = appConfig["Logging"]?["MaxLogSize"] { maxLogFileSize = Int(maxSize)! }else{ maxLogFileSize = 100000000 } do { logger = try Logger(logLevel: currentLogLevel, logFilePath: currentLogFilePath, maxLogFileSize: maxLogFileSize, debugMode: appArguments.debug) } catch Logger.LoggerError.FileIsNotWritable { print("Error: Log file is not writable at \(currentLogFilePath).\n") #if swift(>=3) AppExit.Exit(parent: true, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(true, status: AppExit.EXIT_STATUS.FAILURE) #endif return } catch Logger.LoggerError.FileSizeTooSmall { print("Error: Max log file size \(maxLogFileSize) is too small.\n") #if swift(>=3) AppExit.Exit(parent: true, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(true, status: AppExit.EXIT_STATUS.FAILURE) #endif return } catch { print("Error: An error occured for opening log file.\n") #if swift(>=3) AppExit.Exit(parent: true, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(true, status: AppExit.EXIT_STATUS.FAILURE) #endif return } #if swift(>=3) logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "The main process started.") #elseif swift(>=2.2) && os(OSX) logger.writeLog(Logger.LogLevels.WARNINGS, message: "The main process started.") #endif let currentExtensionDir: String if let extensionsDir = appConfig["Extensions"]?["ExtensionsDir"] { currentExtensionDir = extensionsDir }else{ print("Could not find ExtensionsDir value in config file.") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif return } let currentPidFile: String if let pidFilePath = appConfig["Daemonize"]?["Pid"] { currentPidFile = pidFilePath }else{ currentPidFile = "./" + Constants.APP_PACKAGE_NAME + ".pid" } appExtensions = DynamicLoader(logger: logger, extensionsDir: currentExtensionDir, configFilePath: appArguments.config!, appConfig: appConfig) worker = AppWorker(handlers: appExtensions.getLoadedHandlers(), pidFile: currentPidFile, logger: logger, appArguments: appArguments) if(appArguments.debug || appArguments.textMode) { if(appArguments.signalName == nil) { print("Error: invalid signal!") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif } switch appArguments.signalName! { case "start": print("Starting application.") #if swift(>=3) startHandlers(isChildProcess: false) #elseif swift(>=2.2) && os(OSX) startHandlers(false) #endif print("OK!") break case "stop": print("Stopping application.") #if swift(>=3) stopHandlers(forceStop: false) #elseif swift(>=2.2) && os(OSX) stopHandlers(false) #endif print("OK!") break case "restart": print("Restarting ....") #if swift(>=3) stopHandlers(forceStop: false) #elseif swift(>=2.2) && os(OSX) stopHandlers(false) #endif print("Stopped!") print("Starting ...") #if swift(>=3) startHandlers(isChildProcess: false) #elseif swift(>=2.2) && os(OSX) startHandlers(false) #endif print("OK!") break case "force-stop": print("Force stopping application.") #if swift(>=3) stopHandlers(forceStop: true) #elseif swift(>=2.2) && os(OSX) stopHandlers(true) #endif print("OK!") break case "environ": #if swift(>=3) #if os(Linux) let environments = ProcessInfo.processInfo().environment #else let environments = ProcessInfo.processInfo.environment #endif if let envSignal = environments["IO_RUNNER_SN"] { if(envSignal == "child-start") { startHandlers(isChildProcess: true) }else if(envSignal == "ext-start") { if let extName = environments["IO_RUNNER_EX"] { worker.runExtension(extensionName: extName) } } }else{ logger.writeLog(level: Logger.LogLevels.MINIMAL, message: "Application enviroments could not readed!") } #else let environments = NSProcessInfo().environment if let envSignal = environments["IO_RUNNER_SN"] { if(envSignal == "child-start") { startHandlers(true) }else if(envSignal == "ext-start") { if let extName = environments["IO_RUNNER_EX"] { #if swift(>=3) worker.runExtension(extensionName: extName) #elseif swift(>=2.2) && os(OSX) worker.runExtension(extName) #endif } } }else{ logger.writeLog(Logger.LogLevels.MINIMAL, message: "Application enviroments could not readed!") } #endif break default: print("Error: invalid signal \(appArguments.signalName)!") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif } #if swift(>=3) AppExit.Exit(parent: true, status: AppExit.EXIT_STATUS.SUCCESS) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(true, status: AppExit.EXIT_STATUS.SUCCESS) #endif }else{ #if swift(>=3) if(appArguments.keepalive){ let pidStatus = worker.checkPid() var startApplication = false if(pidStatus == -1) { startApplication = true }else{ if(kill(pidStatus, 0) != 0) { worker.deletePid() startApplication = true } } if(startApplication) { let procPid = getpid() do { try worker.setChildProcessPid(pid: procPid) self.startHandlers(isChildProcess: true) } catch AppWorker.AppWorkerError.PidFileExists { self.logger.writeLog(level: Logger.LogLevels.MINIMAL, message: "Pid file exists.") } catch AppWorker.AppWorkerError.PidFileIsNotWritable { self.logger.writeLog(level: Logger.LogLevels.MINIMAL, message: "Pid file is not writable.") } catch _ { self.logger.writeLog(level: Logger.LogLevels.MINIMAL, message: "An error occured for creating pid file.") } } }else{ self.startGUI() } #elseif swift(>=2.2) && os(OSX) if(appArguments.keepalive){ let pidStatus = worker.checkPid() var startApplication = false if(pidStatus == -1) { startApplication = true }else{ if(kill(pidStatus, 0) != 0) { worker.deletePid() startApplication = true } } if(startApplication) { let procPid = getpid() do { try worker.setChildProcessPid(procPid) self.startHandlers(true) } catch AppWorker.AppWorkerError.PidFileExists { self.logger.writeLog(Logger.LogLevels.MINIMAL, message: "Pid file exists.") } catch AppWorker.AppWorkerError.PidFileIsNotWritable { self.logger.writeLog(Logger.LogLevels.MINIMAL, message: "Pid file is not writable.") } catch _ { self.logger.writeLog(Logger.LogLevels.MINIMAL, message: "An error occured for creating pid file.") } } }else{ self.startGUI() } #endif } #if swift(>=3) logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "The main process stopped.") #elseif swift(>=2.2) && os(OSX) logger.writeLog(Logger.LogLevels.WARNINGS, message: "The main process stopped.") #endif logger.closeLogFile() } private func startGUI() { self.mainGUI = GUIWidgets() { (action) in #if swift(>=3) self.setGuiAction(action: action) #elseif swift(>=2.2) && os(OSX) self.setGuiAction(action) #endif } inGuiLoop = true onGUI() } private func startHandlers(isChildProcess: Bool) { let daemonize: Int if let daemonizeStatus = appConfig["Daemonize"]?["Daemonize"] { daemonize = Int(daemonizeStatus)! }else{ daemonize = 1 } var damonizeMode = false if(daemonize == 1 && !appArguments.debug) { damonizeMode = true } do { #if swift(>=3) try worker.run(daemonize: damonizeMode, isChildProcess: isChildProcess) #elseif swift(>=2.2) && os(OSX) try worker.run(damonizeMode, isChildProcess: isChildProcess) #endif } catch AppWorker.AppWorkerError.DaemonizeFailed { if(appArguments.textMode || appArguments.debug) { print("Daemonize failed!") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif } #if swift(>=3) logger.writeLog(level: Logger.LogLevels.ERROR, message: "Daemonize failed!") #elseif swift(>=2.2) && os(OSX) logger.writeLog(Logger.LogLevels.ERROR, message: "Daemonize failed!") #endif } catch AppWorker.AppWorkerError.PidFileExists { if(appArguments.textMode || appArguments.debug) { print("Pid file exists!") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif } #if swift(>=3) logger.writeLog(level: Logger.LogLevels.ERROR, message: "Pid file exists!") #elseif swift(>=2.2) && os(OSX) logger.writeLog(Logger.LogLevels.ERROR, message: "Pid file exists!") #endif } catch AppWorker.AppWorkerError.PidFileIsNotWritable { if(appArguments.textMode || appArguments.debug) { print("Pid file is not writable!") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif } #if swift(>=3) logger.writeLog(level: Logger.LogLevels.ERROR, message: "Pid file is not writable!") #elseif swift(>=2.2) && os(OSX) logger.writeLog(Logger.LogLevels.ERROR, message: "Pid file is not writable!") #endif } catch _ { if(appArguments.textMode || appArguments.debug) { print("An error occured for running application") #if swift(>=3) AppExit.Exit(parent: false, status: AppExit.EXIT_STATUS.FAILURE) #elseif swift(>=2.2) && os(OSX) AppExit.Exit(false, status: AppExit.EXIT_STATUS.FAILURE) #endif } #if swift(>=3) logger.writeLog(level: Logger.LogLevels.ERROR, message: "An error occured for running application") #elseif swift(>=2.2) && os(OSX) logger.writeLog(Logger.LogLevels.ERROR, message: "An error occured for running application") #endif } } private func stopHandlers(forceStop: Bool) { if(forceStop) { #if swift(>=3) worker.stop(graceful: false) #elseif swift(>=2.2) && os(OSX) worker.stop(false) #endif }else{ worker.stop() } } private func registerGuiSignals() { signalHandler = SignalHandler() #if swift(>=3) signalHandler.register(signal: .Interrupt, handleGUIQuit) signalHandler.register(signal: .Quit, handleGUIQuit) signalHandler.register(signal: .Terminate, handleGUIQuit) SignalHandler.registerSignals() logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Signals registered") #elseif swift(>=2.2) && os(OSX) signalHandler.register(.Interrupt, handleGUIQuit) signalHandler.register(.Quit, handleGUIQuit) signalHandler.register(.Terminate, handleGUIQuit) SignalHandler.registerSignals() logger.writeLog(Logger.LogLevels.WARNINGS, message: "Signals registered") #endif } private func getWorkerStatus() -> UInt { // 0 running, 1 not running, 2 dead if(worker != nil) { let pidStatus = worker.checkPid() if(pidStatus == -1) { return 1 }else{ if(kill(pidStatus, 0) == 0) { return 0 }else{ return 2 } } }else{ return 1 } } func handleGUIQuit() { inGuiLoop = false } private func setGuiAction(action: MainGuiActions) { switch action { case .EXIT: handleGUIQuit() break case .BACK: if(isModuleWidgetActive) { isModuleWidgetActive = false self.mainGUI.deinitModuleWidget() guiMainMenu() } default: break } } private func generateAppInfoData() -> [GUIAppInfo] { let appStatus = getWorkerStatus() var appInfoData = [GUIAppInfo]() switch appStatus { case 0: appInfoData.append(GUIAppInfo(infoKey: "Status:\t\t", infoVal: "Running", infoType: GUIAppInfo.InfoType.SUCCESS)) break case 1: appInfoData.append(GUIAppInfo(infoKey: "Status:\t\t", infoVal: "Not Running", infoType: GUIAppInfo.InfoType.DANGER)) break case 2: appInfoData.append(GUIAppInfo(infoKey: "Status:\t\t", infoVal: "Process Dead", infoType: GUIAppInfo.InfoType.DANGER)) break default: appInfoData.append(GUIAppInfo(infoKey: "Status:\t\t", infoVal: "Not Determined", infoType: GUIAppInfo.InfoType.NORMAL)) break } let loadedModulesInfo = appExtensions.getLoadedModuleInfo() appInfoData.append(GUIAppInfo(infoKey: "Modules:\t\t", infoVal: "\(loadedModulesInfo.0)", infoType: GUIAppInfo.InfoType.NORMAL)) appInfoData.append(GUIAppInfo(infoKey: "Installed Modules:\t", infoVal: "\(loadedModulesInfo.1)", infoType: GUIAppInfo.InfoType.SUCCESS)) return appInfoData } private func guiMainMenu() { var choices = [GUIMenuChoices]() choices.append(GUIMenuChoices(choiceName: "Start Application", choiceCode: 0)) choices.append(GUIMenuChoices(choiceName: "Stop Application", choiceCode: 1)) choices.append(GUIMenuChoices(choiceName: "Restart Application", choiceCode: 2)) choices.append(GUIMenuChoices(choiceName: "Force Stop Application", choiceCode: 3)) choices.append(GUIMenuChoices(choiceName: "Module Settings", choiceCode: 4)) choices.append(GUIMenuChoices(choiceName: "List Config Directives", choiceCode: 5)) choices.append(GUIMenuChoices(choiceName: "Build Info", choiceCode: 6)) choices.append(GUIMenuChoices(choiceName: "Version Info", choiceCode: 7)) choices.append(GUIMenuChoices(choiceName: "Exit", choiceCode: 8)) var startRow = 0 var widgetSize = 2 if(self.mainGUI.hasTitleWidget()) { startRow = 2 widgetSize += (self.mainGUI.titleAndFooter?.widgetRows)! #if swift(>=3) self.mainGUI.titleAndFooter?.updateKeyboardInfo(keyControls: (GUIConstants.MenuButtons, GUIConstants.ArrowsUpDown)) #elseif swift(>=2.2) && os(OSX) self.mainGUI.titleAndFooter?.updateKeyboardInfo((GUIConstants.MenuButtons, GUIConstants.ArrowsUpDown)) #endif } if(self.mainGUI.hasAppInfoWidget()) { widgetSize += (self.mainGUI.appInfo?.widgetRows)! } let menuWidget = MenuWidget(startRow: startRow, widgetSize: Int(widgetSize), choices: choices, delegate: { (selectedChoiceIdx) in switch(selectedChoiceIdx) { case 0: self.startApplicationOnGUI() break case 1: self.stopApplicationOnGUI() break case 2: self.restartApplicationOnGUI() break case 3: self.forceStopApplicationOnGUI() break case 4: self.guiModulesMenu() case 5: self.generateGuiConfigDirectives() break case 6: var buildString = Constants.APP_NAME + "\n\tOS\t\t: " #if os(OSX) buildString += "Mac OS X" #elseif os(Linux) buildString += "Linux" #else buildString += "Other" #endif buildString += "\n\tArch\t\t: " #if arch(x86_64) buildString += "x86_64" #elseif arch(arm) || arch(arm64) buildString += "arm (64)" #elseif arch(i386) buildString += "i386" #else buildString += "Other" #endif buildString += "\n\tSwift Version\t: " #if swift(>=3.0) buildString += ">= 3.0" #elseif swift(>=2.2) buildString += "= 2.2" #elseif swift(>=2.0) buildString += "= 2.0" #else buildString += "Unkown" #endif let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "\tBuild:\n\t\(buildString)", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif break case 7: let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "\tVersion:\n\t\(Constants.APP_NAME) \(Constants.APP_VERSION)\n\t\(Constants.APP_CREDITS)", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif break case 8: self.handleGUIQuit() break default: break } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initMenuWidget(widget: menuWidget) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initMenuWidget(menuWidget) #endif } private func onGUI() { registerGuiSignals() let copyrightText = "\(Constants.APP_CREDITS)\t\t\t\tVersion: \(Constants.APP_VERSION)" let titleWidget = TitleAndFooterWidget(title: Constants.APP_NAME, copyright: copyrightText, keyControls: (GUIConstants.MenuButtons, GUIConstants.ArrowsUpDown), mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initTitleWidget(widget: titleWidget) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initTitleWidget(titleWidget) #endif var startRow = 0 let appInfoData = generateAppInfoData() if(self.mainGUI.hasTitleWidget()) { startRow += (self.mainGUI.titleAndFooter?.widgetRows)! } startRow += appInfoData.count let appInfoWidget = AppInfoWidget(appInfo: appInfoData, startRow: Int32(startRow), mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initAppInfoWidget(widget: appInfoWidget) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initAppInfoWidget(appInfoWidget) #endif guiMainMenu() #if swift(>=3) var loopStartDate: UInt = UInt(Date().timeIntervalSince1970) #if os(Linux) let runLoop = RunLoop.current() repeat { let _ = signalHandler.process() self.mainGUI.onGUI() let curDate: UInt = UInt(Date().timeIntervalSince1970) let dateDif = curDate - loopStartDate if(dateDif > 30) { loopStartDate = curDate if(self.mainGUI.hasAppInfoWidget()) { self.mainGUI.appInfo?.updateAppInfo(appInfo: generateAppInfoData()) } } usleep(Constants.GuiRefreshRate) let _ = runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate().addingTimeInterval(-1 * Constants.CpuSleepMsec)) } while (inGuiLoop) #else let runLoop = RunLoop.current repeat { let _ = signalHandler.process() self.mainGUI.onGUI() let curDate: UInt = UInt(Date().timeIntervalSince1970) let dateDif = curDate - loopStartDate if(dateDif > 30) { logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Updating info data") loopStartDate = curDate if(self.mainGUI.hasAppInfoWidget()) { self.mainGUI.appInfo?.updateAppInfo(appInfo: generateAppInfoData()) } } usleep(Constants.GuiRefreshRate) } while (inGuiLoop && runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: Date().addingTimeInterval(-1 * Constants.CpuSleepMsec))) #endif self.mainGUI.exitGui(status: 0) #else var loopStartDate: UInt = UInt(NSDate().timeIntervalSince1970) let runLoop = NSRunLoop.currentRunLoop() repeat { let _ = signalHandler.process() self.mainGUI.onGUI() let curDate: UInt = UInt(NSDate().timeIntervalSince1970) let dateDif = curDate - loopStartDate if(dateDif > 30) { logger.writeLog(Logger.LogLevels.WARNINGS, message: "Updating info data") loopStartDate = curDate if(self.mainGUI.hasAppInfoWidget()) { self.mainGUI.appInfo?.updateAppInfo(generateAppInfoData()) } } usleep(Constants.GuiRefreshRate) } while (inGuiLoop && runLoop.runMode(NSDefaultRunLoopMode, beforeDate: NSDate().dateByAddingTimeInterval(-1 * Constants.CpuSleepMsec))) self.mainGUI.exitGui(0) #endif } private func startApplicationOnGUI() { let appStatus = self.getWorkerStatus() if(appStatus == 0) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Warning!\n Application is already running.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else if(appStatus == 1) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Are you sure want to START application ?", popupButtons: ["No", "Yes"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in if(selectedChoiceIdx == 1) { self.mainGUI.deinitPopupWidget() #if swift(>=3) self.startHandlers(isChildProcess: false) #elseif swift(>=2.2) && os(OSX) self.startHandlers(false) #endif let waitPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.SYNC_WAIT, popupContent: "Please wait ...", popupButtons: [], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: waitPopup) self.mainGUI.waitPopup(waitForSecond: 5) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(waitPopup) self.mainGUI.waitPopup(5) #endif self.mainGUI.deinitPopupWidget() let endPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Application started!", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() if(self.mainGUI.hasAppInfoWidget()) { #if swift(>=3) self.mainGUI.appInfo?.updateAppInfo(appInfo: self.generateAppInfoData()) #elseif swift(>=2.2) && os(OSX) self.mainGUI.appInfo?.updateAppInfo(self.generateAppInfoData()) #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: endPopup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(endPopup) #endif }else{ self.mainGUI.deinitPopupWidget() } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else{ let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Warning!\n Application is not running but pid file exists.\nUse force stop option.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif } } private func stopApplicationOnGUI() { let appStatus = self.getWorkerStatus() if(appStatus == 0) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Are you sure want to STOP application ?", popupButtons: ["No", "Yes"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in if(selectedChoiceIdx == 1) { self.mainGUI.deinitPopupWidget() #if swift(>=3) self.stopHandlers(forceStop: false) #elseif swift(>=2.2) && os(OSX) self.stopHandlers(false) #endif let waitPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.SYNC_WAIT, popupContent: "Please wait ...", popupButtons: [], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: waitPopup) self.mainGUI.waitPopup(waitForSecond: 5) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(waitPopup) self.mainGUI.waitPopup(5) #endif self.mainGUI.deinitPopupWidget() let resultPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Application stopped!", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() if(self.mainGUI.hasAppInfoWidget()) { #if swift(>=3) self.mainGUI.appInfo?.updateAppInfo(appInfo: self.generateAppInfoData()) #elseif swift(>=2.2) && os(OSX) self.mainGUI.appInfo?.updateAppInfo(self.generateAppInfoData()) #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: resultPopup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(resultPopup) #endif }else{ self.mainGUI.deinitPopupWidget() } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else if(appStatus == 1) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Warning!\n Application is not running.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else{ let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Warning!\n Application is not running but pid file exists.\nUse force stop option.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif } } private func restartApplicationOnGUI() { let appStatus = self.getWorkerStatus() if(appStatus == 0) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Are you sure want to RE-START application ?", popupButtons: ["No", "Yes"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in if(selectedChoiceIdx == 1) { self.mainGUI.deinitPopupWidget() #if swift(>=3) self.stopHandlers(forceStop: false) #elseif swift(>=2.2) && os(OSX) self.stopHandlers(false) #endif let waitPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.SYNC_WAIT, popupContent: "Please wait ...", popupButtons: [], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: waitPopup) self.mainGUI.waitPopup(waitForSecond: 5) self.startHandlers(isChildProcess: false) self.mainGUI.waitPopup(waitForSecond: 5) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(waitPopup) self.mainGUI.waitPopup(5) self.startHandlers(false) self.mainGUI.waitPopup(5) #endif self.mainGUI.deinitPopupWidget() #if swift(>=3) self.mainGUI.waitPopup(waitForSecond: 1) #elseif swift(>=2.2) && os(OSX) self.mainGUI.waitPopup(1) #endif let resultPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.SYNC_WAIT, popupContent: "Application restarted!", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() if(self.mainGUI.hasAppInfoWidget()) { #if swift(>=3) self.mainGUI.appInfo?.updateAppInfo(appInfo: self.generateAppInfoData()) #elseif swift(>=2.2) && os(OSX) self.mainGUI.appInfo?.updateAppInfo(self.generateAppInfoData()) #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: resultPopup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(resultPopup) #endif }else{ self.mainGUI.deinitPopupWidget() } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else if(appStatus == 1) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Warning!\n Application is not running.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else{ let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Warning!\n Application is not running but pid file exists.\nUse force stop option.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif } } private func forceStopApplicationOnGUI() { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Are you sure want to FORCE-STOP application ?", popupButtons: ["No", "Yes"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in if(selectedChoiceIdx == 1) { self.mainGUI.deinitPopupWidget() #if swift(>=3) self.stopHandlers(forceStop: true) #elseif swift(>=2.2) && os(OSX) self.stopHandlers(true) #endif let waitPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.SYNC_WAIT, popupContent: "Please wait ...", popupButtons: [], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: waitPopup) self.mainGUI.waitPopup(waitForSecond: 5) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(waitPopup) self.mainGUI.waitPopup(5) #endif self.mainGUI.deinitPopupWidget() let resultPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Application stopped!", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() if(self.mainGUI.hasAppInfoWidget()) { #if swift(>=3) self.mainGUI.appInfo?.updateAppInfo(appInfo: self.generateAppInfoData()) #elseif swift(>=2.2) && os(OSX) self.mainGUI.appInfo?.updateAppInfo(self.generateAppInfoData()) #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: resultPopup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(resultPopup) #endif }else{ self.mainGUI.deinitPopupWidget() } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif } private func generateGuiConfigDirectives() { var choices = [GUIMenuChoices]() var menuIdx = 1 for sectionIdx in 0..<self.appConfig.sections.count { let sectionData = self.appConfig.sections[sectionIdx] choices.append(GUIMenuChoices(choiceName: "[\(sectionData.name)]", choiceCode: menuIdx)) menuIdx += 1 for sectionConfig in sectionData.settings { choices.append(GUIMenuChoices(choiceName: " \(sectionConfig.0)", choiceCode: menuIdx)) menuIdx += 1 choices.append(GUIMenuChoices(choiceName: " \(sectionConfig.1)", choiceCode: menuIdx)) menuIdx += 1 } choices.append(GUIMenuChoices(choiceName: " ", choiceCode: menuIdx)) menuIdx += 1 } choices.append(GUIMenuChoices(choiceName: "BACK TO THE MAIN MENU", choiceCode: 0)) self.mainGUI.deinitMenuWidget() var startRow = 0 var widgetSize = 2 if(self.mainGUI.hasTitleWidget()) { startRow = 2 widgetSize += (self.mainGUI.titleAndFooter?.widgetRows)! #if swift(>=3) self.mainGUI.titleAndFooter?.updateKeyboardInfo(keyControls: (GUIConstants.MenuButtons, GUIConstants.ArrowsUpDown)) #elseif swift(>=2.2) && os(OSX) self.mainGUI.titleAndFooter?.updateKeyboardInfo((GUIConstants.MenuButtons, GUIConstants.ArrowsUpDown)) #endif } if(self.mainGUI.hasAppInfoWidget()) { widgetSize += (self.mainGUI.appInfo?.widgetRows)! } let menuWidget = MenuWidget(startRow: startRow, widgetSize: widgetSize, choices: choices, delegate: { (selectedChoiceIdx) in self.mainGUI.deinitMenuWidget() self.guiMainMenu() }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initMenuWidget(widget: menuWidget) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initMenuWidget(menuWidget) #endif } private func guiModulesMenu() { var choices = [GUIModulesChoices]() let moduleList = self.appExtensions.getModulesList() var choiceIdx = 0 for module in moduleList { choices.append(GUIModulesChoices(choiceName: module.0, choiceCode: choiceIdx, isActive: module.1)) choiceIdx += 1 } self.mainGUI.deinitMenuWidget() isModuleWidgetActive = true var startRow = 0 var widgetSize = 2 if(self.mainGUI.hasTitleWidget()) { startRow = 2 widgetSize += (self.mainGUI.titleAndFooter?.widgetRows)! #if swift(>=3) self.mainGUI.titleAndFooter?.updateKeyboardInfo(keyControls: (GUIConstants.ModuleButtons, GUIConstants.ArrowsAll)) #elseif swift(>=2.2) && os(OSX) self.mainGUI.titleAndFooter?.updateKeyboardInfo((GUIConstants.ModuleButtons, GUIConstants.ArrowsAll)) #endif } if(self.mainGUI.hasAppInfoWidget()) { widgetSize += (self.mainGUI.appInfo?.widgetRows)! } let modulesWidget = ModulesWidget(startRow: startRow, widgetSize: widgetSize, leftSideTitle: "Installed Modules", rightSideTitle: "Available modules", choices: choices, delegate: { (selectedChoiceIdx, isActive) in if(selectedChoiceIdx == -1) { return } if(isActive) { let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Are you sure want to REMOVE this module ?", popupButtons: ["No", "Yes"], hasShadow: false, popupDelegate: { (popupSelectedChoiceIdx) in self.mainGUI.deinitPopupWidget() if(popupSelectedChoiceIdx == 1) { #if swift(>=3) if(self.appExtensions.deactivateModule(moduleIdx: selectedChoiceIdx)) { let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: " Module removed!\n Changes will be save when application restarted.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(widget: subPopup) if(self.mainGUI.hasModuleWidget()) { var choices = [GUIModulesChoices]() let moduleList = self.appExtensions.getModulesList() var choiceIdx = 0 for module in moduleList { choices.append(GUIModulesChoices(choiceName: module.0, choiceCode: choiceIdx, isActive: module.1)) choiceIdx += 1 } self.mainGUI.modules?.updateModuleList(modules: choices) } }else{ let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "An error occured for deactivating module.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(widget: subPopup) } #elseif swift(>=2.2) && os(OSX) if(self.appExtensions.deactivateModule(selectedChoiceIdx)) { let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: " Module removed!\n Changes will be save when application restarted.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(subPopup) if(self.mainGUI.hasModuleWidget()) { var choices = [GUIModulesChoices]() let moduleList = self.appExtensions.getModulesList() var choiceIdx = 0 for module in moduleList { choices.append(GUIModulesChoices(choiceName: module.0, choiceCode: choiceIdx, isActive: module.1)) choiceIdx += 1 } self.mainGUI.modules?.updateModuleList(choices) } }else{ let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "An error occured for deactivating module.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(subPopup) } #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif }else{ let popup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "Are you sure want to INSTALL this module ?", popupButtons: ["No", "Yes"], hasShadow: false, popupDelegate: { (popupSelectedChoiceIdx) in self.mainGUI.deinitPopupWidget() if(popupSelectedChoiceIdx == 1) { #if swift(>=3) if(self.appExtensions.activateModule(moduleIdx: selectedChoiceIdx)) { let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: " Module installed!\n Changes will be save when application restarted.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(widget: subPopup) if(self.mainGUI.hasModuleWidget()) { var choices = [GUIModulesChoices]() let moduleList = self.appExtensions.getModulesList() var choiceIdx = 0 for module in moduleList { choices.append(GUIModulesChoices(choiceName: module.0, choiceCode: choiceIdx, isActive: module.1)) choiceIdx += 1 } self.mainGUI.modules?.updateModuleList(modules: choices) } }else{ let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "An error occured for activating module.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(widget: subPopup) } #elseif swift(>=2.2) && os(OSX) if(self.appExtensions.activateModule(selectedChoiceIdx)) { let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: " Module installed!\n Changes will be save when application restarted.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(subPopup) if(self.mainGUI.hasModuleWidget()) { var choices = [GUIModulesChoices]() let moduleList = self.appExtensions.getModulesList() var choiceIdx = 0 for module in moduleList { choices.append(GUIModulesChoices(choiceName: module.0, choiceCode: choiceIdx, isActive: module.1)) choiceIdx += 1 } self.mainGUI.modules?.updateModuleList(choices) } }else{ let subPopup = PopupWidget(popuptype: PopupWidget.GUIPopupTypes.CONFIRM, popupContent: "An error occured for activating module.", popupButtons: ["OK"], hasShadow: false, popupDelegate: { (selectedChoiceIdx) in self.mainGUI.deinitPopupWidget() }, mainWindow: self.mainGUI.mainWindow) self.mainGUI.initPopupWidget(subPopup) } #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initPopupWidget(widget: popup) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initPopupWidget(popup) #endif } }, mainWindow: self.mainGUI.mainWindow) #if swift(>=3) self.mainGUI.initModuleWidget(widget: modulesWidget) #elseif swift(>=2.2) && os(OSX) self.mainGUI.initModuleWidget(modulesWidget) #endif } }
mit
3836359b0e550130f8b15f4b66a3dc5c
28.172922
260
0.663098
3.442423
false
false
false
false
onekiloparsec/siesta
Source/Support/Siesta-ObjC.swift
1
14887
// // Siesta-ObjC.swift // Siesta // // Created by Paul on 2015/7/14. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation /* Glue for using Siesta from Objective-C. Siesta follows a Swift-first design approach. It uses the full expressiveness of the language to make everything feel “Swift native,” both in interface and implementation. This means many Siesta APIs can’t simply be marked @objc, and require a separate compatibility layer. Rather than sprinkle that mess throughout the code, it’s all quarrantined here. Features exposed to Objective-C: * Resource path navigation (child, relative, etc.) * Resource state * Observers * Request / load * Request completion callbacks * UI components Some things are not exposed in the compatibility layer, and must be done in Swift: * Subclassing Service * Custom ResponseTransformers * Custom NetworkingProviders * Logging config */ // MARK: - Because Swift structs aren’t visible to Obj-C // (Why not just make Entity and Error classes and avoid all these // shenanigans? Because Swift’s lovely mutable/immutable struct handling lets Resource // expose the full struct to Swift clients sans copying, yet still force mutations to // happen via overrideLocalData() so that observers always know about changes.) @objc(BOSEntity) public class _objc_Entity: NSObject { public var content: AnyObject? public var contentType: String public var charset: String? public var etag: String? private var headers: [String:String] public private(set) var timestamp: NSTimeInterval = 0 public init(content: AnyObject, contentType: String, headers: [String:String]) { self.content = content self.contentType = contentType self.headers = headers } public convenience init(content: AnyObject, contentType: String) { self.init(content: content, contentType: contentType, headers: [:]) } internal init(_ entity: Entity) { if !(entity.content is AnyObject) { NSLog("WARNING: entity content of type \(entity.content.dynamicType)" + " is not an object, and therefore not usable from Objective-C") } self.content = entity.content as? AnyObject self.contentType = entity.contentType self.charset = entity.charset self.etag = entity.etag self.headers = entity.headers } public func header(key: String) -> String? { return headers[key.lowercaseString] } public override var description: String { return debugStr(Entity(entity: self)) } } internal extension Entity { init(entity: _objc_Entity) { self.init(content: entity.content, contentType: entity.contentType, charset: entity.charset, headers: entity.headers) } } @objc(BOSError) public class _objc_Error: NSObject { public var httpStatusCode: Int public var cause: NSError? public var userMessage: String public var entity: _objc_Entity? public let timestamp: NSTimeInterval internal init(_ error: Error) { self.httpStatusCode = error.httpStatusCode ?? -1 self.cause = error.cause as? NSError self.userMessage = error.userMessage self.timestamp = error.timestamp if let errorData = error.entity { self.entity = _objc_Entity(errorData) } } } public extension Resource { @objc(latestData) public var _objc_latestData: _objc_Entity? { if let latestData = latestData { return _objc_Entity(latestData) } else { return nil } } @objc(latestError) public var _objc_latestError: _objc_Error? { if let latestError = latestError { return _objc_Error(latestError) } else { return nil } } @objc(jsonDict) public var _objc_jsonDict: [String:AnyObject] { return jsonDict } @objc(jsonArray) public var _objc_jsonArray: [AnyObject] { return jsonArray } @objc(text) public var _objc_text: String { return text } @objc(overrideLocalData:) public func _objc_overrideLocalData(entity: _objc_Entity) { overrideLocalData(Entity(entity: entity)) } } // MARK: - Because Swift closures aren’t exposed as Obj-C blocks @objc(BOSRequest) public class _objc_Request: NSObject { private let request: Request private init(_ request: Request) { self.request = request } public func onCompletion(objcCallback: @convention(block) (_objc_Entity?, _objc_Error?) -> Void) -> _objc_Request { request.onCompletion { switch $0 { case .Success(let entity): objcCallback(_objc_Entity(entity), nil) case .Failure(let error): objcCallback(nil, _objc_Error(error)) } } return self } public func onSuccess(objcCallback: @convention(block) _objc_Entity -> Void) -> _objc_Request { request.onSuccess { entity in objcCallback(_objc_Entity(entity)) } return self } public func onNewData(objcCallback: @convention(block) _objc_Entity -> Void) -> _objc_Request { request.onNewData { entity in objcCallback(_objc_Entity(entity)) } return self } public func onNotModified(objcCallback: @convention(block) Void -> Void) -> _objc_Request { request.onNotModified(objcCallback) return self } public func onFailure(objcCallback: @convention(block) _objc_Error -> Void) -> _objc_Request { request.onFailure { error in objcCallback(_objc_Error(error)) } return self } public func onProgress(objcCallback: @convention(block) Float -> Void) -> _objc_Request { request.onProgress { p in objcCallback(Float(p)) } return self } public func cancel() { request.cancel() } public override var description: String { return debugStr(request) } } public extension Resource { @objc(load) public func _objc_load() -> _objc_Request { return _objc_Request(load()) } @objc(loadIfNeeded) public func _objc_loadIfNeeded() -> _objc_Request? { if let req = loadIfNeeded() { return _objc_Request(req) } else { return nil } } } // MARK: - Because Swift enums aren’t exposed to Obj-C @objc(BOSResourceObserver) public protocol _objc_ResourceObserver { func resourceChanged(resource: Resource, event: String) optional func resourceRequestProgress(resource: Resource, progress: Double) optional func stoppedObservingResource(resource: Resource) } private class _objc_ResourceObserverGlue: ResourceObserver, CustomDebugStringConvertible { weak var objcObserver: _objc_ResourceObserver? init(objcObserver: _objc_ResourceObserver) { self.objcObserver = objcObserver } func resourceChanged(resource: Resource, event: ResourceEvent) { objcObserver?.resourceChanged(resource, event: event.description) } func resourceRequestProgress(resource: Resource, progress: Double) { objcObserver?.resourceRequestProgress?(resource, progress: progress) } func stoppedObservingResource(resource: Resource) { objcObserver?.stoppedObservingResource?(resource) } var debugDescription: String { if objcObserver != nil { return debugStr(objcObserver) } else { return "_objc_ResourceObserverGlue<deallocated delegate>" } } func isEquivalentToObserver(other: ResourceObserver) -> Bool { if let otherGlue = (other as? _objc_ResourceObserverGlue) { return self.objcObserver === otherGlue.objcObserver } else { return false } } } public extension Resource { @objc(addObserver:) public func _objc_addObserver(observerAndOwner: protocol<_objc_ResourceObserver, AnyObject>) -> Self { return addObserver(_objc_ResourceObserverGlue(objcObserver: observerAndOwner), owner: observerAndOwner) } @objc(addObserver:owner:) public func _objc_addObserver(objcObserver: _objc_ResourceObserver, owner: AnyObject) -> Self { return addObserver(_objc_ResourceObserverGlue(objcObserver: objcObserver), owner: owner) } @objc(addObserverWithOwner:callback:) public func _objc_addObserver(owner owner: AnyObject, block: @convention(block) (Resource,String) -> Void) -> Self { return addObserver(owner: owner) { block($0, $1.description) } } } #if !os(OSX) extension ResourceStatusOverlay: _objc_ResourceObserver { public func resourceChanged(resource: Resource, event eventString: String) { if let event = ResourceEvent.fromDescription(eventString) { resourceChanged(resource, event: event) } } } extension ResourceStatusOverlay { @objc(displayPriority) public var _objc_displayPriority: [String] { get { return displayPriority.map { $0.rawValue } } set { displayPriority = newValue.flatMap { let condition = ResourceStatusOverlay.StateRule(rawValue: $0) if condition == nil { Swift.print("WARNING: ignoring unknown ResourceStatusOverlay.StateRule \"\($0)\"") } return condition } } } } #endif public extension Resource { private func _objc_wrapRequest( methodString: String, @noescape closure: RequestMethod -> Request) -> _objc_Request { guard let method = RequestMethod(rawValue: methodString) else { return _objc_Request( Resource.failedRequest( Error( userMessage: NSLocalizedString("Cannot create request", comment: "userMessage"), cause: _objc_Error.Cause.InvalidRequestMethod(method: methodString)))) } return _objc_Request(closure(method)) } private func _objc_wrapJSONRequest( methodString: String, _ maybeJson: NSObject?, @noescape closure: (RequestMethod, NSJSONConvertible) -> Request) -> _objc_Request { guard let json = maybeJson as? NSJSONConvertible else { return _objc_Request( Resource.failedRequest( Error( userMessage: NSLocalizedString("Cannot send request", comment: "userMessage"), cause: Error.Cause.InvalidJSONObject()))) } return _objc_wrapRequest(methodString) { closure($0, json) } } @objc(requestWithMethod:requestMutation:) public func _objc_request( method: String, requestMutation: (@convention(block) NSMutableURLRequest -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0) { requestMutation?($0) } } } @objc(requestWithMethod:) public func _objc_request(method: String) -> _objc_Request { return _objc_wrapRequest(method) { request($0) } } @objc(requestWithMethod:data:contentType:requestMutation:) public func _objc_request( method: String, data: NSData, contentType: String, requestMutation: (@convention(block) NSMutableURLRequest -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0, data: data, contentType: contentType) { requestMutation?($0) } } } @objc(requestWithMethod:text:) public func _objc_request( method: String, text: String) -> _objc_Request { return _objc_wrapRequest(method) { request($0, text: text) } } @objc(requestWithMethod:text:contentType:encoding:requestMutation:) public func _objc_request( method: String, text: String, contentType: String, encoding: NSStringEncoding = NSUTF8StringEncoding, requestMutation: (@convention(block) NSMutableURLRequest -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0, text: text, contentType: contentType, encoding: encoding) { requestMutation?($0) } } } @objc(requestWithMethod:json:) public func _objc_request( method: String, json: NSObject?) -> _objc_Request { return _objc_wrapJSONRequest(method, json) { request($0, json: $1) } } @objc(requestWithMethod:json:contentType:requestMutation:) public func _objc_request( method: String, json: NSObject?, contentType: String, requestMutation: (@convention(block) NSMutableURLRequest -> ())?) -> _objc_Request { return _objc_wrapJSONRequest(method, json) { request($0, json: $1, contentType: contentType) { requestMutation?($0) } } } @objc(requestWithMethod:urlEncoded:requestMutation:) public func _objc_request( method: String, urlEncoded params: [String:String], requestMutation: (@convention(block) NSMutableURLRequest -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0, urlEncoded: params) { requestMutation?($0) } } } @objc(loadUsingRequest:) public func _objc_load(usingRequest req: _objc_Request) -> _objc_Request { load(usingRequest: req.request) return req } } public extension _objc_Error { public struct Cause { /// Request method specified as a string does not match any of the values in the RequestMethod enum. public struct InvalidRequestMethod: ErrorType { public let method: String } } }
mit
4b1893b21137d2ff1045ea053e715c90
30.043841
125
0.593073
4.831059
false
false
false
false
xedin/swift
stdlib/public/Windows/WinSDK.swift
1
5039
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// @_exported import WinSDK // Clang module // WinBase.h public let HANDLE_FLAG_INHERIT: DWORD = 0x00000001 // WinBase.h public let STARTF_USESTDHANDLES: DWORD = 0x00000100 // WinBase.h public let INFINITE: DWORD = DWORD(bitPattern: -1) // WinBase.h public let WAIT_OBJECT_0: DWORD = 0 // WinBase.h public let STD_INPUT_HANDLE: DWORD = DWORD(bitPattern: -10) public let STD_OUTPUT_HANDLE: DWORD = DWORD(bitPattern: -11) public let STD_ERROR_HANDLE: DWORD = DWORD(bitPattern: -12) // handleapi.h public let INVALID_HANDLE_VALUE: HANDLE = HANDLE(bitPattern: -1)! // shellapi.h public let FOF_NO_UI: FILEOP_FLAGS = FILEOP_FLAGS(FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR) // winioctl.h public let FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4 public let FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8 public let FSCTL_DELETE_REPARSE_POINT: DWORD = 0x900ac // WinSock2.h public let INVALID_SOCKET: SOCKET = SOCKET(bitPattern: -1) public let FIONBIO: Int32 = Int32(bitPattern: 0x8004667e) // WinUser.h public let CW_USEDEFAULT: Int32 = Int32(truncatingIfNeeded: 2147483648) public let WS_OVERLAPPEDWINDOW: UINT = UINT(WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX) public let WS_POPUPWINDOW: UINT = UINT(Int32(WS_POPUP) | WS_BORDER | WS_SYSMENU) // fileapi.h public let INVALID_FILE_ATTRIBUTES: DWORD = DWORD(bitPattern: -1) // CommCtrl.h public let WC_BUTTONW: [WCHAR] = Array<WCHAR>("Button".utf16) public let WC_COMBOBOXW: [WCHAR] = Array<WCHAR>("ComboBox".utf16) public let WC_EDITW: [WCHAR] = Array<WCHAR>("Edit".utf16) public let WC_HEADERW: [WCHAR] = Array<WCHAR>("SysHeader32".utf16) public let WC_LISTBOXW: [WCHAR] = Array<WCHAR>("ListBox".utf16) public let WC_LISTVIEWW: [WCHAR] = Array<WCHAR>("SysListView32".utf16) public let WC_SCROLLBARW: [WCHAR] = Array<WCHAR>("ScrollBar".utf16) public let WC_STATICW: [WCHAR] = Array<WCHAR>("Static".utf16) public let WC_TABCONTROLW: [WCHAR] = Array<WCHAR>("SysTabControl32".utf16) public let WC_TREEVIEWW: [WCHAR] = Array<WCHAR>("SysTreeView32".utf16) public let ANIMATE_CLASSW: [WCHAR] = Array<WCHAR>("SysAnimate32".utf16) public let HOTKEY_CLASSW: [WCHAR] = Array<WCHAR>("msctls_hotkey32".utf16) public let PROGRESS_CLASSW: [WCHAR] = Array<WCHAR>("msctls_progress32".utf16) public let STATUSCLASSNAMEW: [WCHAR] = Array<WCHAR>("msctls_statusbar32".utf16) public let TOOLBARW_CLASSW: [WCHAR] = Array<WCHAR>("ToolbarWindow32".utf16) public let TRACKBAR_CLASSW: [WCHAR] = Array<WCHAR>("msctls_trackbar32".utf16) public let UPDOWN_CLASSW: [WCHAR] = Array<WCHAR>("msctls_updown32".utf16) // consoleapi.h public let PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: DWORD_PTR = 0x00020016 // Swift Convenience public extension FILETIME { var time_t: time_t { let NTTime: Int64 = Int64(self.dwLowDateTime) | (Int64(self.dwHighDateTime) << 32) return (NTTime - 116444736000000000) / 10000000 } init(from time: time_t) { let UNIXTime: Int64 = ((time * 10000000) + 116444736000000000) self = FILETIME(dwLowDateTime: DWORD(UNIXTime & 0xffffffff), dwHighDateTime: DWORD((UNIXTime >> 32) & 0xffffffff)) } } // WindowsBool /// The `BOOL` type declared in WinDefs.h and used throughout WinSDK /// /// The C type is a typedef for `int`. @_fixed_layout public struct WindowsBool : ExpressibleByBooleanLiteral { @usableFromInline var _value: Int32 /// The value of `self`, expressed as a `Bool`. @_transparent public var boolValue: Bool { return !(_value == 0) } @_transparent public init(booleanLiteral value: Bool) { self.init(value) } /// Create an instance initialized to `value`. @_transparent public init(_ value: Bool) { self._value = value ? 1 : 0 } } extension WindowsBool : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension WindowsBool : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension WindowsBool : Equatable { @_transparent public static func ==(lhs: WindowsBool, rhs: WindowsBool) -> Bool { return lhs.boolValue == rhs.boolValue } } @_transparent public // COMPILER_INTRINSIC func _convertBoolToWindowsBool(_ b: Bool) -> WindowsBool { return WindowsBool(b) } @_transparent public // COMPILER_INTRINSIC func _convertWindowsBoolToBool(_ b: WindowsBool) -> Bool { return b.boolValue }
apache-2.0
e76aabed05d690e2795d31e8ea295c73
31.509677
99
0.69875
3.35486
false
false
false
false
apple/swift-tools-support-core
Sources/TSCBasic/OSLog.swift
1
8851
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 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 Swift project authors */ #if canImport(os) import os.log #endif /// A custom log object that can be passed to logging functions in order to send /// messages to the logging system. /// /// This is a thin wrapper for Darwin's log APIs to make them usable without /// platform and availability checks. public final class OSLog { private let storage: Any? #if canImport(os) @available(macOS 10.12, *) @usableFromInline var log: os.OSLog { return storage as! os.OSLog } #endif private init(_ storage: Any? = nil) { self.storage = storage } /// Creates a custom log object. public convenience init(subsystem: String, category: String) { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { self.init(os.OSLog(subsystem: subsystem, category: category)) } else { self.init() } #else self.init() #endif } /// The shared default log. public static let disabled: OSLog = { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return OSLog(os.OSLog.disabled) } else { return OSLog() } #else return OSLog() #endif }() /// The shared default log. public static let `default`: OSLog = { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return OSLog(os.OSLog.default) } else { return OSLog() } #else return OSLog() #endif }() } /// Logging levels supported by the system. public struct OSLogType { private let storage: Any? #if canImport(os) @available(macOS 10.12, *) @usableFromInline var `type`: os.OSLogType { return storage as! os.OSLogType } #endif private init(_ storage: Any? = nil) { self.storage = storage } /// The default log level. public static var `default`: OSLogType { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return self.init(os.OSLogType.default) } else { return self.init() } #else return self.init() #endif } /// The info log level. public static var info: OSLogType { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return self.init(os.OSLogType.info) } else { return self.init() } #else return self.init() #endif } /// The debug log level. public static var debug: OSLogType { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return self.init(os.OSLogType.info) } else { return self.init() } #else return self.init() #endif } } /// Sends a message to the logging system. /// /// This is a thin wrapper for Darwin's log APIs to make them usable without /// platform and availability checks. @inlinable public func os_log( _ type: OSLogType = .default, log: OSLog = .default, _ message: StaticString, _ args: CVarArg... ) { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { switch args.count { case 0: os.os_log(type.type, log: log.log, message) case 1: os.os_log(type.type, log: log.log, message, args[0]) case 2: os.os_log(type.type, log: log.log, message, args[0], args[1]) case 3: os.os_log(type.type, log: log.log, message, args[0], args[1], args[2]) case 4: os.os_log(type.type, log: log.log, message, args[0], args[1], args[2], args[3]) case 5: os.os_log(type.type, log: log.log, message, args[0], args[1], args[2], args[3], args[4]) default: assertionFailure("Unsupported number of arguments") } } #endif } // MARK :- OSSignpost APIs /// The type of a signpost tracepoint. /// /// This is a thin wrapper for Darwin's signpost APIs to make them usable without /// platform and availability checks. public struct OSSignpostType { #if canImport(os) @usableFromInline let type: os.OSSignpostType private init(_ type: os.OSSignpostType) { self.type = type } #else private init() {} #endif /// Begins a signposted interval. public static let begin: OSSignpostType = { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return OSSignpostType(.begin) } else { fatalError("unreachable") } #else return OSSignpostType() #endif }() /// Ends a signposted interval. public static let end: OSSignpostType = { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return OSSignpostType(.end) } else { fatalError("unreachable") } #else return OSSignpostType() #endif }() /// Marks a point of interest in time with no duration. public static let event: OSSignpostType = { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return OSSignpostType(.event) } else { fatalError("unreachable") } #else return OSSignpostType() #endif }() } /// An ID to disambiguate intervals in a signpost. /// /// This is a thin wrapper for Darwin's signpost APIs to make them usable without /// platform and availability checks. public struct OSSignpostID { private let storage: Any? #if canImport(os) @available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) @usableFromInline var id: os.OSSignpostID { return storage as! os.OSSignpostID } #endif private init(_ storage: Any?) { self.storage = storage } // Generates an ID guaranteed to be unique within the matching scope of the // provided log handle. public init(log: OSLog) { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { self.init(os.OSSignpostID(log: log.log)) } else { self.init(nil) } #else self.init(nil) #endif } /// A convenience value for signpost intervals that will never occur /// concurrently. public static let exclusive: OSSignpostID = { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { return OSSignpostID(os.OSSignpostID.exclusive) } else { return OSSignpostID(nil) } #else return OSSignpostID(nil) #endif }() } /// Emits a signpost. @inlinable public func os_signpost( _ type: OSSignpostType, log: OSLog = .default, name: StaticString, signpostID: OSSignpostID = .exclusive ) { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id) } #endif } /// Emits a signpost. @inlinable public func os_signpost( _ type: OSSignpostType, log: OSLog = .default, name: StaticString, signpostID: OSSignpostID = .exclusive, _ format: StaticString, _ args: CVarArg... ) { #if canImport(os) if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) { switch args.count { case 0: os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id, format) case 1: os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id, format, args[0]) case 2: os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id, format, args[0], args[1]) case 3: os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id, format, args[0], args[1], args[2]) case 4: os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id, format, args[0], args[1], args[2], args[3]) case 5: os.os_signpost(type.type, log: log.log, name: name, signpostID: signpostID.id, format, args[0], args[1], args[2], args[3], args[4]) default: assertionFailure("Unsupported number of arguments") } } #endif }
apache-2.0
0723668b7cb326f6ce202cc0327a7c93
27.36859
143
0.582194
3.771197
false
false
false
false
mfitzpatrick79/BidHub-iOS
AuctionApp/BiddingVC/BiddingViewController.swift
1
8110
// // BiddingViewController.swift // AuctionApp // import UIKit import IHKeyboardAvoiding protocol BiddingViewControllerDelegate { func biddingViewControllerDidBid(_ viewController: BiddingViewController, onItem: Item, maxBid: Int) func biddingViewControllerDidCancel(_ viewController: BiddingViewController) } private enum BiddingViewControllerState{ case custom case standard } class BiddingViewController: UIViewController { @IBOutlet var darkView: UIView! @IBOutlet var popUpContainer: UIView! @IBOutlet var predifinedButtonsContainerView: UIView! @IBOutlet var customBidButton: UIButton! @IBOutlet var customBidTextField: UITextField! @IBOutlet var plusOneButton: UIButton! @IBOutlet var plusTenButton: UIButton! @IBOutlet var plusFiveButton: UIButton! var delegate: BiddingViewControllerDelegate? var item: Item? var startPrice = 0 fileprivate var state :BiddingViewControllerState = .standard var incrementOne = 0 var incrementFive = 0 var incrementTen = 0 override func viewDidLoad() { super.viewDidLoad() self.customBidTextField.alpha = 0.0 if let itemUW = item{ incrementOne = itemUW.priceIncrement incrementFive = 2*itemUW.priceIncrement incrementTen = 5*itemUW.priceIncrement switch(itemUW.winnerType){ case .multiple: if itemUW.currentWinners.isEmpty{ let openingBid = itemUW.price - itemUW.priceIncrement setupForSingle(openingBid) }else{ setupForSingle(itemUW.price) } case .single: if itemUW.currentWinners.isEmpty{ let openingBid = itemUW.price - itemUW.priceIncrement setupForSingle(openingBid) }else{ setupForSingle(itemUW.price) } } popUpContainer.backgroundColor = UIColor.white popUpContainer.layer.cornerRadius = 5.0 customBidButton.titleLabel?.font = UIFont(name: "Avenir-Light", size: 18.0)! customBidButton.setTitleColor(UIColor(red: 33/225, green: 161/225, blue: 219/225, alpha: 1), for: UIControlState()) customBidTextField.font = UIFont(name: "Avenir-Light", size: 24.0) customBidTextField.textColor = UIColor(red: 33/225, green: 161/225, blue: 219/225, alpha: 1) customBidTextField.textAlignment = .center //IHKeyboardAvoiding.setBuffer(20) //IHKeyboardAvoiding.setPadding(20) //IHKeyboardAvoiding.setAvoidingView(view, withTarget: popUpContainer) animateIn() } } @IBAction func didTapBackground(_ sender: AnyObject) { if delegate != nil { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.popUpContainer.transform = CGAffineTransform.identity.scaledBy(x: 0.01, y: 0.01); self.darkView.alpha = 0 }, completion: { (finished: Bool) -> Void in self.delegate!.biddingViewControllerDidCancel(self) }) } } func setupForSingle(_ startAmount: Int) { startPrice = startAmount let bidAttrs = [NSFontAttributeName : UIFont(name: "Avenir-Light", size: 14.0)! , NSForegroundColorAttributeName: UIColor.gray] as NSDictionary let otherAttrs = [NSFontAttributeName : UIFont(name: "Avenir-Light", size: 22.0)!, NSForegroundColorAttributeName: UIColor(red: 33/225, green: 161/225, blue: 219/225, alpha: 1)] plusOneButton.titleLabel?.textAlignment = .center plusFiveButton.titleLabel?.textAlignment = .center plusTenButton.titleLabel?.textAlignment = .center let one = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as! [String: NSObject]) one.append(NSMutableAttributedString(string: "$\(startAmount + incrementOne)", attributes: otherAttrs)) plusOneButton.setAttributedTitle(one, for: UIControlState()) let five = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as! [String: NSObject]) five.append(NSMutableAttributedString(string: "$\(startAmount + incrementFive)", attributes: otherAttrs)) plusFiveButton.setAttributedTitle(five, for: UIControlState()) let ten = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as! [String: NSObject]) ten.append(NSMutableAttributedString(string: "$\(startAmount + incrementTen)", attributes: otherAttrs)) plusTenButton.setAttributedTitle(ten, for: UIControlState()) } func setupForMultiple() { self.customBidTextField.alpha = 1.0 self.predifinedButtonsContainerView.alpha = 0.0 self.customBidButton.setTitle("Max Bid", for: UIControlState()) state = .custom } func didSelectAmount(_ bidType: BidType) { var maxBid = 0 switch bidType { case .custom(let total): maxBid = total case .extra(let aditional): maxBid = startPrice + aditional } let bidAlert = UIAlertController(title: "Confirm $\(maxBid) Bid", message: "You didn't think we'd let you bid $\(maxBid) without confirming it, did you?", preferredStyle: UIAlertControllerStyle.alert) bidAlert.addAction(UIAlertAction(title: "Bid", style: .default, handler: { (action: UIAlertAction!) in if self.delegate != nil { if let itemUW = self.item { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.popUpContainer.transform = CGAffineTransform.identity.scaledBy(x: 0.01, y: 0.01); self.darkView.alpha = 0 }, completion: { (finished: Bool) -> Void in self.delegate!.biddingViewControllerDidBid(self, onItem: itemUW, maxBid: maxBid) }) } } })) bidAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in //self.didTapBackground(bidAlert) })) present(bidAlert, animated: true, completion: nil) } @IBAction func customAmountPressed(_ sender: AnyObject) { switch state { case .custom: if let maxBid = Int(customBidTextField.text!){ didSelectAmount(.custom(maxBid)) }else{ didTapBackground("" as AnyObject) } case .standard: UIView.animate(withDuration: 0.5, animations: { () -> Void in self.setupForMultiple() self.customBidTextField.becomeFirstResponder() }) } } @IBAction func bidOnePressed(_ sender: AnyObject) { didSelectAmount(.extra(incrementOne)) } @IBAction func bidFivePressed(_ sender: AnyObject) { didSelectAmount(.extra(incrementFive)) } @IBAction func bidTenPressed(_ sender: AnyObject) { didSelectAmount(.extra(incrementTen)) } func animateIn(){ popUpContainer.transform = CGAffineTransform.identity.scaledBy(x: 0.01, y: 0.01); UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { self.popUpContainer.transform = CGAffineTransform.identity self.darkView.alpha = 1.0 }, completion: { (fininshed: Bool) -> () in } ) } }
apache-2.0
d28e64baff4cb974b7a2e6d59f0cd348
37.075117
208
0.594575
4.954184
false
false
false
false
JockerLUO/ShiftLibra
ShiftLibra/ShiftLibra/Class/Tools/Language.swift
1
2613
// // Language.swift // ShiftLibra // // Created by LUO on 2017/8/16. // Copyright © 2017年 JockerLuo. All rights reserved. // import UIKit var country = "China" { didSet { customExchange = country == "China" ? "设定自定义汇率" : "Set Custom Rate" customCurrency = country == "China" ? "自定义" : "CUSTOM RATES" updatedTime = country == "China" ? "已更新" : "Updated" btnShiftText = country == "China" ? "切换" : "Swap" btnOtherText = country == "China" ? "选择其他" : "Choose Currency" btnCancelText = country == "China" ? "取消" : "Cancel" btnFinishText = country == "China" ? "完成" : "Finish" indexHotText = country == "China" ? "☆热门" : "☆POPULAR" indexcustomExchangeText = country == "China" ? "自定义汇率" : "Set Custom Rate" alertVCTitle = country == "China" ? "提示" : "Info" alertVCMessage = country == "China" ? "由于服务器原因未收录此货币\n汇率信息已过期\n您是否仍要查询此货币汇率" : "The currency has not been credited due to server reasons, Do you still want to check this currency exchange rate?" confirmTitle = country == "China" ? "确定" : "Done" alertVCLangangeMessage = country == "China" ? "当前所在地为国外是否切换为英语" : "Now in China whether to switch to Chinese" alertVCZWDMessage = country == "China" ? "由于津巴布韦元汇率不稳未收录" : "As the Zimbabwe dollar exchange rate instability is not included" searchResultsText = country == "China" ? " " : "search results" } } private(set) var customExchange = "设定自定义汇率" private(set) var customCurrency = "★" private(set) var updatedTime = "已更新" private(set) var btnShiftText = "切换" private(set) var btnOtherText = "选择其他" private(set) var btnCancelText = "取消" private(set) var btnFinishText = "完成" private(set) var indexHotText = "☆热门" private(set) var searchResultsText = "搜索结果" private(set) var indexcustomExchangeText = "自定义汇率" private(set) var alertVCTitle = "提示" private(set) var alertVCMessage = "由于服务器原因未收录此货币,汇率信息已过期,您是否仍要查询此货币汇率" private(set) var confirmTitle = "确定" private(set) var alertVCLangangeMessage = "当前所在地为国外是否切换为英语" private(set) var alertVCZWDMessage = "由于津巴布韦元汇率不稳未收录"
mit
7547a51879940cf4afd9292ba0bd0115
28.210526
202
0.631982
3.117978
false
false
false
false
iosprogrammingwithswift/iosprogrammingwithswift
04_Swift2015_Final.playground/Pages/08_Enumerations.xcplaygroundpage/Contents.swift
1
3676
//: [Previous](@previous) | [Next](@next) import Foundation //: Use `enum` to create an enumeration. Like classes and all other named types, enumerations can have methods associated with them. //: enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.rawValue) } } } let ace = Rank.Ace let aceRawValue = ace.rawValue //: > **Experiment**: //: > Write a function that compares two `Rank` values by comparing their raw values. //: //: In the example above, the raw-value type of the enumeration is `Int`, so you only have to specify the first raw value. The rest of the raw values are assigned in order. You can also use strings or floating-point numbers as the raw type of an enumeration. Use the `rawValue` property to access the raw value of an enumeration case. //: //: Use the `init?(rawValue:)` initializer to make an instance of an enumeration from a raw value. //: if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() } //: The case values of an enumeration are actual values, not just another way of writing their raw values. In fact, in cases where there isn’t a meaningful raw value, you don’t have to provide one. //: enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription() //: > **Experiment**: //: > Add a `color()` method to `Suit` that returns “black” for spades and clubs, and returns “red” for hearts and diamonds. //: //: Notice the two ways that the `Hearts` case of the enumeration is referred to above: When assigning a value to the `hearts` constant, the enumeration case `Suit.Hearts` is referred to by its full name because the constant doesn’t have an explicit type specified. Inside the switch, the enumeration case is referred to by the abbreviated form `.Hearts` because the value of `self` is already known to be a suit. You can use the abbreviated form anytime the value’s type is already known. enum NSDateFormatPattern:String { case clockTime = "HH:mm:ss" case date = "dd-MM-YY" case dateTimeWithMilliseconds = "yyyy-MM-dd HH:mm:ss,SSS ZZZ" case dateTime = "yyyy-MM-dd HH:mm:ss" }; extension NSDate { func formattedStringForDate(format: NSDateFormatPattern) -> String { let formatter = NSDateFormatter() let locale = NSLocale.currentLocale(); //de_DE formatter.locale = locale formatter.dateFormat = format.rawValue return formatter.stringFromDate(self) } } NSDate().formattedStringForDate(.dateTime) ; /*: largely Based of [Apple's Swift Language Guide: Enumerations](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-ID145 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 ) */ //: [Previous](@previous) | [Next](@next)
mit
49a5e241b76ac25d95a434dc7873daef
39.666667
489
0.679235
4.163823
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Extensions/Sources/SwiftExtensions/FloatingPoint.swift
1
1892
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Algorithms extension FloatingPoint { @inlinable public static var unit: Self { .init(1) } } extension Sequence where Element: FloatingPoint { public func sum() -> Element { reduce(0, +) } public func product() -> Element { reduce(1, *) } } public enum SlidingAveragesPrefixAndSuffix: Int { case reverseToFit case reverse case repeating case none } extension RandomAccessCollection where Element: FloatingPoint { public func slidingAverages( radius: Int, prefixAndSuffix: SlidingAveragesPrefixAndSuffix = .reverseToFit ) -> [Element] { guard radius != 0, !isEmpty else { return array } let start: [Element] let end: [Element] switch prefixAndSuffix { case .reverseToFit: start = lazy.prefix(radius).reversed().map { 2 * self.first! - $0 } end = lazy.suffix(radius).reversed().map { 2 * self.last! - $0 } case .reverse: start = prefix(radius).reversed() end = suffix(radius).reversed() case .repeating: start = Array(repeating: first!, count: radius) end = Array(repeating: last!, count: radius) case .none: return slidingAverages(radius: radius) } var array = [Element](); do { array.reserveCapacity(count + radius * 2) array.append(contentsOf: start) array.append(contentsOf: self) array.append(contentsOf: end) } return array.slidingAverages(radius: radius) } private func slidingAverages( radius: Int ) -> [Element] { guard radius != 0 else { return array } let window = (2 * abs(radius)) + 1 return windows(ofCount: window).map { $0.sum() / Element(window) } } }
lgpl-3.0
064ab0b4ec8edac88d42db7c4d7f2260
30
79
0.595981
4.357143
false
false
false
false
vsqweHCL/DouYuZB
DouYuZB/DouYuZB/Classs/Tools/Extension/UIBarButtonItem-Extension.swift
1
1351
// // UIBarButtonItem-Extension.swift // DouYuZB // // Created by HCL黄 on 16/11/3. // Copyright © 2016年 HCL黄. All rights reserved. // import UIKit extension UIBarButtonItem { class func createItem(_ imageName: String, highImageName: String, size: CGSize) ->UIBarButtonItem { let btn = UIButton() btn.setImage(UIImage(named: imageName), for: UIControlState()) btn.setImage(UIImage(named: highImageName), for: .highlighted) btn.frame = CGRect(origin: CGPoint.zero, size: size) let item = UIBarButtonItem(customView: btn) return item } // 便利构造函数:1> convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(self) // swift语法,可以传默认参数,在下面要做判断 convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.zero) { let btn = UIButton() btn.setImage(UIImage(named: imageName), for: UIControlState()) if highImageName != "" { btn.setImage(UIImage(named: highImageName), for: .highlighted) } if size == CGSize.zero { btn.sizeToFit() } else { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView: btn) } }
mit
a8b6665a5e9d72dfe99fe310d67e3c29
29.439024
103
0.606571
4.173913
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/OnThisDayViewControllerHeader.swift
1
2651
import UIKit class OnThisDayViewControllerHeader: UICollectionReusableView { @IBOutlet weak var eventsLabel: UILabel! @IBOutlet weak var onLabel: UILabel! @IBOutlet weak var fromLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() apply(theme: Theme.standard) wmf_configureSubviewsForDynamicType() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) onLabel.font = UIFont.wmf_font(.heavyTitle1, compatibleWithTraitCollection: traitCollection) } func configureFor(eventCount: Int, firstEvent: WMFFeedOnThisDayEvent?, lastEvent: WMFFeedOnThisDayEvent?, midnightUTCDate: Date) { let language = firstEvent?.language let locale = NSLocale.wmf_locale(for: language) semanticContentAttribute = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: language) eventsLabel.semanticContentAttribute = semanticContentAttribute onLabel.semanticContentAttribute = semanticContentAttribute fromLabel.semanticContentAttribute = semanticContentAttribute eventsLabel.text = String(format: WMFLocalizedString("on-this-day-detail-header-title", language: language, value:"{{PLURAL:%1$d|%1$d historical event|%1$d historical events}}", comment:"Title for 'On this day' detail view - %1$d is replaced with the number of historical events which occurred on the given day"), locale: locale, eventCount).uppercased(with: locale) onLabel.text = DateFormatter.wmf_monthNameDayNumberGMTFormatter(for: language).string(from: midnightUTCDate) if let firstEventEraString = firstEvent?.yearString, let lastEventEraString = lastEvent?.yearString { fromLabel.text = String(format: WMFLocalizedString("on-this-day-detail-header-date-range", language: language, value:"from %1$@ - %2$@", comment:"Text for 'On this day' detail view events 'year range' label - %1$@ is replaced with string version of the oldest event year - i.e. '300 BC', %2$@ is replaced with string version of the most recent event year - i.e. '2006', "), locale: locale, lastEventEraString, firstEventEraString) } else { fromLabel.text = nil } } } extension OnThisDayViewControllerHeader: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground eventsLabel.textColor = theme.colors.secondaryText onLabel.textColor = theme.colors.primaryText fromLabel.textColor = theme.colors.secondaryText } }
mit
788102d5acde72f2a820b91870dd7087
54.229167
442
0.724255
5.049524
false
false
false
false
NSSimpleApps/WatchConnector
WatchConnector/WatchConnector/CoreDataManager+Phone.swift
1
2542
// // CoreDataManager+Phone.swift // WatchConnector // // Created by NSSimpleApps on 02.05.16. // Copyright © 2016 NSSimpleApps. All rights reserved. // import Foundation import CoreData let BackgroundContext = "BackgroundContext" extension CoreDataManager { // for watch request func initWatchInteraction() { WatchConnector.shared.listenToReplyDataBlock({ (data: Data, description: String?) -> Data in let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundContext.persistentStoreCoordinator = self.persistentStoreCoordinator let fetchRequest = NSFetchRequest<Note>(entityName: String(describing: Note.self)) fetchRequest.propertiesToFetch = ["image", "url"] do { let notes = try backgroundContext.fetch(fetchRequest) let results = notes.map({ (note: Note) -> [String: Any] in var d = note.toDictionary() d[URIRepresentation] = note.objectID.uriRepresentation().absoluteString return d }) return NSKeyedArchiver.archivedData(withRootObject: [Notes: results]) } catch let error as NSError { print(error) return NSKeyedArchiver.archivedData(withRootObject: [Notes: []]) } }, withIdentifier: DataRequest) } func initDeleteNote() { WatchConnector.shared.listenToMessageBlock({ (message: WCMessageType) -> Void in let id = message[URIRepresentation] as! String let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundContext.name = BackgroundContext backgroundContext.persistentStoreCoordinator = self.persistentStoreCoordinator if let managedObjectID = self.persistentStoreCoordinator.managedObjectID(forURIRepresentation: URL(string: id)!), let object = backgroundContext.object(with: managedObjectID) as? Note { backgroundContext.delete(object) do { try backgroundContext.save() } catch let error as NSError { print(error) } } }, withIdentifier: DeleteNote) } }
mit
01e0e09eb0c96ea11bbb8f3d5826c143
40.655738
197
0.587957
6.3525
false
false
false
false
ZulwiyozaPutra/Alien-Adventure-Tutorial
Alien Adventure/ShuffleStrings.swift
1
1625
// // ShuffleStrings.swift // Alien Adventure // // Created by Jarrod Parkes on 9/30/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func shuffleStrings(s1: String, s2: String, shuffle: String) -> Bool { var s1Array: [Character] = [] var s2Array: [Character] = [] var shuffleArray: [Character] = [] var containedS1Array: [Character] = [] var containedS2Array: [Character] = [] for c in s1.characters { s1Array.append(c) } for c in s2.characters { s2Array.append(c) } for c in shuffle.characters { shuffleArray.append(c) for i in s1Array { if c == i { containedS1Array.append(i) } } for i in s2Array { if c == i { containedS2Array.append(i) } } } //Boolean decision making if s1 == "" && s2 == "" && shuffle == "" { return true } else if !(shuffle.characters.count == (s1.characters.count + s2.characters.count)){ return false } else { if s1Array == containedS1Array && s2Array == containedS2Array { return true } else { return false } } } }
mit
cb01153a78e994f57afa6a37f8e3b08f
22.882353
93
0.406404
4.833333
false
false
false
false
ChinaPicture/ZXYRefresh
RefreshDemo/Refresh/CustomerFresh/SimpleRefreshFooterView.swift
1
3555
// // SimpleRefreshFooterView.swift // RefreshDemo // // Created by developer on 10/04/2017. // Copyright © 2017 developer. All rights reserved. // import UIKit class SimpleRefreshFooterView: RefreshBaseFooterView { var progressLayer: CAShapeLayer = CAShapeLayer.init() var contenLabel: UILabel? override func prepareRefreshViewLayout() { let path = CGMutablePath.init() self.progressLayer.frame = CGRect.init(x: (self.frame.size.width - 14) / 2 - 60, y: (self.frame.size.height - 14) / 2, width: 14, height: 14) path.addArc(center: CGPoint.init(x: 7, y: 7), radius: 7, startAngle: CGFloat(Double.pi / 2), endAngle: CGFloat(Double.pi * 2 + Double.pi / 2), clockwise: false) self.progressLayer.strokeStart = 0.1 self.progressLayer.strokeEnd = 0 self.progressLayer.fillColor = UIColor.clear.cgColor self.progressLayer.strokeColor = UIColor.blue.cgColor self.progressLayer.path = path self.layer.addSublayer(progressLayer) self.contenLabel = UILabel.init(frame: CGRect.init(x: (self.frame.size.width - 100) / 2 + 5 , y: (self.frame.size.height - 20) / 2 , width: 100, height: 20)) self.contenLabel?.text = "下拉刷新数据" self.contenLabel?.textColor = UIColor.lightGray self.contenLabel?.textAlignment = .center self.contenLabel?.font = UIFont.systemFont(ofSize: 12) self.addSubview(self.contenLabel!) } override func layoutSubviews() { super.layoutSubviews() self.progressLayer.frame = CGRect.init(x: (self.frame.size.width - 14) / 2 - 50, y: (self.frame.size.height - 14) / 2 - 1, width: 14, height: 14) self.contenLabel?.frame = CGRect.init(x: (self.frame.size.width - 100) / 2 + 5 , y: (self.frame.size.height - 20) / 2 , width: 100, height: 20) } override func refreshViewStateChanged(scroll: UIScrollView, currentState: RefreshStatus) { super.refreshViewStateChanged(scroll: scroll, currentState: currentState) if currentState == .finish { self.progressLayer.strokeEnd = 0 self.contenLabel?.text = "数据加载完成" } else if currentState == .initial { self.contenLabel?.text = "上拉加载数据" } else if currentState == .load { self.startRotate() self.contenLabel?.text = "正在加载数据" self.progressLayer.strokeEnd = 0.95 self.startRotate() } else if currentState == .willActive { self.contenLabel?.text = "松开加载新数据" } else if currentState == .noMore { self.contenLabel?.text = "没有数据了" self.progressLayer.strokeStart = 0 self.progressLayer.strokeEnd = 0 } if currentState == .finish || currentState == .noMore || currentState == .initial { self.removeRotate() } } override func refreshRatioChange(scroll: UIScrollView , ratio: CGFloat) { super.refreshRatioChange(scroll: scroll, ratio: ratio) self.progressLayer.strokeEnd = 0.1 + 0.85 * ratio } func startRotate() { let ani = CABasicAnimation.init(keyPath: "transform.rotation.z") ani.fromValue = 0 ani.toValue = Double.pi * 2 ani.duration = 0.8 ani.isRemovedOnCompletion = false ani.repeatCount = MAXFLOAT self.progressLayer.add(ani, forKey: nil) } func removeRotate() { self.progressLayer.removeAllAnimations() } }
apache-2.0
da8b33405766fe0c45d0d48e82c6eee5
41.463415
168
0.631246
4.011521
false
false
false
false
cwaffles/Soulcast
Soulcast/RecordButton.swift
1
8999
// // RecordButton.swift // Instant // // Created by Samuel Beek on 21/06/15. // Copyright (c) 2015 Samuel Beek. All rights reserved. // import Foundation import UIKit //import QuartzCore enum RecordButtonState : Int { case standby // 0 case recordingStarted // 1 case recordingLongEnough // 2 case finished // 3 case mutedDuringPlayBack //4 case failed //5 } class RecordButton : UIButton { var buttonColor = offBlue{ didSet { circleLayer.backgroundColor = buttonColor.cgColor circleBorder.borderColor = buttonColor.cgColor } } var progressColor = offRed { didSet { gradientMaskLayer.colors = [progressColor.cgColor, progressColor.cgColor] } } /// Closes the circle and hides when the RecordButton is finished var closeWhenFinished: Bool = false fileprivate var buttonState : RecordButtonState = .standby { didSet { switch buttonState { case .standby: self.alpha = 1.0 currentProgress = 0 setProgress(0) setRecording(false) print("RecordButton is Standby") case .recordingStarted: self.alpha = 1.0 setRecording(true) print("RecordButton is RecordingStarted") case .mutedDuringPlayBack: self.alpha = 0.2 print("RecordButton is MutedDuringPlayBack") case .recordingLongEnough: finishingRecording() print("RecordButton is RecordingLongEnough") case .finished: resetSuccess() print("RecordButton is Finished") default: //print("oldValue: \(oldValue.hashValue), state: \(state.hashValue)") assert(false, "OOPS!!!") } } } fileprivate var circleLayer: CALayer! fileprivate var circleBorder: CALayer! fileprivate var progressLayer: CAShapeLayer! fileprivate var gradientMaskLayer: CAGradientLayer! fileprivate var currentProgress: CGFloat! = 0 override init(frame: CGRect) { super.init(frame: frame) self.drawButton() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func drawButton() { self.backgroundColor = UIColor.clear let layer = self.layer circleLayer = CALayer() circleLayer.backgroundColor = buttonColor.cgColor let size: CGFloat = self.frame.size.width / 1.5 circleLayer.bounds = CGRect(x: 0, y: 0, width: size, height: size) circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleLayer.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) circleLayer.cornerRadius = size / 2 layer.insertSublayer(circleLayer, at: 0) circleBorder = CALayer() circleBorder.backgroundColor = UIColor.clear.cgColor circleBorder.borderWidth = 1 circleBorder.borderColor = buttonColor.cgColor circleBorder.bounds = CGRect(x: 0, y: 0, width: self.bounds.size.width - 1.5, height: self.bounds.size.height - 1.5) circleBorder.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleBorder.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) circleBorder.cornerRadius = self.frame.size.width / 2 layer.insertSublayer(circleBorder, at: 0) let startAngle: CGFloat = CGFloat(M_PI) + CGFloat(M_PI_2) let endAngle: CGFloat = CGFloat(M_PI) * 3 + CGFloat(M_PI_2) let centerPoint: CGPoint = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) gradientMaskLayer = self.gradientMask() progressLayer = CAShapeLayer() progressLayer.path = UIBezierPath(arcCenter: centerPoint, radius: self.frame.size.width / 2 - 2, startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath progressLayer.backgroundColor = UIColor.clear.cgColor progressLayer.fillColor = nil progressLayer.strokeColor = UIColor.black.cgColor progressLayer.lineWidth = 4.0 progressLayer.strokeStart = 0.0 progressLayer.strokeEnd = 0.0 gradientMaskLayer.mask = progressLayer layer.insertSublayer(gradientMaskLayer, at: 0) } fileprivate func setRecording(_ recording: Bool) { let duration: TimeInterval = 0.15 circleLayer.contentsGravity = "center" let scale = CABasicAnimation(keyPath: "transform.scale") scale.fromValue = recording ? 1.0 : 0.88 scale.toValue = recording ? 0.88 : 1 scale.duration = duration scale.fillMode = kCAFillModeForwards scale.isRemovedOnCompletion = false let color = CABasicAnimation(keyPath: "backgroundColor") color.duration = duration color.fillMode = kCAFillModeForwards color.isRemovedOnCompletion = false color.toValue = recording ? progressColor.cgColor : buttonColor.cgColor let circleAnimations = CAAnimationGroup() circleAnimations.isRemovedOnCompletion = false circleAnimations.fillMode = kCAFillModeForwards circleAnimations.duration = duration circleAnimations.animations = [scale, color] let borderColor: CABasicAnimation = CABasicAnimation(keyPath: "borderColor") borderColor.duration = duration borderColor.fillMode = kCAFillModeForwards borderColor.isRemovedOnCompletion = false borderColor.toValue = recording ? UIColor(red: 0.83, green: 0.86, blue: 0.89, alpha: 1).cgColor : buttonColor let borderScale = CABasicAnimation(keyPath: "transform.scale") borderScale.fromValue = recording ? 1.0 : 0.88 borderScale.toValue = recording ? 0.88 : 1.0 borderScale.duration = duration borderScale.fillMode = kCAFillModeForwards borderScale.isRemovedOnCompletion = false let borderAnimations = CAAnimationGroup() borderAnimations.isRemovedOnCompletion = false borderAnimations.fillMode = kCAFillModeForwards borderAnimations.duration = duration borderAnimations.animations = [borderColor, borderScale] let fade = CABasicAnimation(keyPath: "opacity") fade.fromValue = recording ? 0.0 : 1.0 fade.toValue = recording ? 1.0 : 0.0 fade.duration = duration fade.fillMode = kCAFillModeForwards fade.isRemovedOnCompletion = false circleLayer.add(circleAnimations, forKey: "circleAnimations") progressLayer.add(fade, forKey: "fade") circleBorder.add(borderAnimations, forKey: "borderAnimations") } fileprivate func gradientMask() -> CAGradientLayer { let gradientLayer = CAGradientLayer() gradientLayer.frame = self.bounds gradientLayer.locations = [0.0, 1.0] let topColor = progressColor let bottomColor = progressColor gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor] return gradientLayer } override func layoutSubviews() { circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleLayer.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) circleBorder.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleBorder.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) super.layoutSubviews() } func startProgress() { self.buttonState = .recordingStarted } func shakeInDenial(){ let animation = CABasicAnimation() animation.duration = 0.1 animation.repeatCount = 4 animation.fromValue = -10 animation.toValue = 0 self.layer.add(animation, forKey:"transform.translation.x") } func tintLongEnough() { //TODO: print("tintLongEnough()") } /** Set the relative length of the circle border to the specified progress - parameter newProgress: the relative lenght, a percentage as float. */ func resetSuccess() { self.buttonState = .standby } func resetFail() { //TODO: do something different self.buttonState = .standby } func setProgress(_ newProgress: CGFloat) { /* [CATransaction setDisableActions:YES]; myLayer.strokeEnd = 0.5; [CATransaction setDisableActions:NO]; */ CATransaction.setDisableActions(true) progressLayer.strokeEnd = newProgress CATransaction.setDisableActions(false) } func mute() { self.buttonState = .mutedDuringPlayBack } func finishingRecording(){ self.buttonState = .finished } }
mit
c8e9e8cdc467824420ba9afc478693b2
34.290196
172
0.62607
5.067005
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/TextView.swift
3
9371
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(TextViewDelegate) public protocol TextViewDelegate : UITextViewDelegate {} @objc(TextView) open class TextView: UITextView { /// A property that accesses the backing layer's background @IBInspectable open override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.cgColor } } /** The title UILabel that is displayed when there is text. The titleLabel text value is updated with the placeholderLabel text value before being displayed. */ @IBInspectable open var titleLabel: UILabel? { didSet { prepareTitleLabel() } } /// The color of the titleLabel text when the textView is not active. @IBInspectable open var titleLabelColor: UIColor? { didSet { titleLabel?.textColor = titleLabelColor } } /// The color of the titleLabel text when the textView is active. @IBInspectable open var titleLabelActiveColor: UIColor? /** A property that sets the distance between the textView and titleLabel. */ @IBInspectable open var titleLabelAnimationDistance: CGFloat = 8 /// Placeholder UILabel view. open var placeholderLabel: UILabel? { didSet { preparePlaceholderLabel() } } /// An override to the text property. @IBInspectable open override var text: String! { didSet { handleTextViewTextDidChange() } } /// An override to the attributedText property. open override var attributedText: NSAttributedString! { didSet { handleTextViewTextDidChange() } } /** Text container UIEdgeInset preset property. This updates the textContainerInset property with a preset value. */ open var textContainerEdgeInsetsPreset: EdgeInsetsPreset = .none { didSet { textContainerInset = EdgeInsetsPresetToValue(preset: textContainerEdgeInsetsPreset) } } /// Text container UIEdgeInset property. open override var textContainerInset: EdgeInsets { didSet { reload() } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. - Parameter textContainer: A NSTextContainer instance. */ public override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) prepare() } /** A convenience initializer that is mostly used with AutoLayout. - Parameter textContainer: A NSTextContainer instance. */ public convenience init(textContainer: NSTextContainer?) { self.init(frame: .zero, textContainer: textContainer) } /** Denitializer. This should never be called unless you know what you are doing. */ deinit { removeNotificationHandlers() } open override func layoutSubviews() { super.layoutSubviews() layoutShape() layoutShadowPath() placeholderLabel?.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2 titleLabel?.frame.size.width = bounds.width } /// Reloads necessary components when the view has changed. open func reload() { if let p = placeholderLabel { removeConstraints(constraints) layout(p).edges( top: textContainerInset.top, left: textContainerInset.left + textContainer.lineFragmentPadding, bottom: textContainerInset.bottom, right: textContainerInset.right + textContainer.lineFragmentPadding) } } /// Notification handler for when text editing began. @objc fileprivate func handleTextViewTextDidBegin() { titleLabel?.textColor = titleLabelActiveColor } /// Notification handler for when text changed. @objc fileprivate func handleTextViewTextDidChange() { if let p = placeholderLabel { p.isHidden = !(true == text?.isEmpty) } guard let t = text else { hideTitleLabel() return } if 0 < t.utf16.count { showTitleLabel() } else { hideTitleLabel() } } /// Notification handler for when text editing ended. @objc fileprivate func handleTextViewTextDidEnd() { guard let t = text else { hideTitleLabel() return } if 0 < t.utf16.count { showTitleLabel() } else { hideTitleLabel() } titleLabel?.textColor = titleLabelColor } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { contentScaleFactor = Screen.scale textContainerInset = .zero backgroundColor = .white clipsToBounds = false removeNotificationHandlers() prepareNotificationHandlers() reload() } /// prepares the placeholderLabel property. fileprivate func preparePlaceholderLabel() { if let v: UILabel = placeholderLabel { v.font = font v.textAlignment = textAlignment v.numberOfLines = 0 v.backgroundColor = .clear addSubview(v) reload() handleTextViewTextDidChange() } } /// Prepares the titleLabel property. fileprivate func prepareTitleLabel() { if let v: UILabel = titleLabel { v.isHidden = true addSubview(v) guard let t = text, 0 == t.utf16.count else { v.alpha = 0 return } showTitleLabel() } } /// Shows and animates the titleLabel property. fileprivate func showTitleLabel() { if let v: UILabel = titleLabel { if v.isHidden { if let s: String = placeholderLabel?.text { v.text = s } let h: CGFloat = ceil(v.font.lineHeight) v.frame = CGRect(x: 0, y: -h, width: bounds.width, height: h) v.isHidden = false UIView.animate(withDuration: 0.25, animations: { [weak self] in if let s: TextView = self { v.alpha = 1 v.frame.origin.y = -v.frame.height - s.titleLabelAnimationDistance } }) } } } /// Hides and animates the titleLabel property. fileprivate func hideTitleLabel() { if let v: UILabel = titleLabel { if !v.isHidden { UIView.animate(withDuration: 0.25, animations: { v.alpha = 0 v.frame.origin.y = -v.frame.height }) { _ in v.isHidden = true } } } } /// Prepares the Notification handlers. fileprivate func prepareNotificationHandlers() { let defaultCenter = NotificationCenter.default defaultCenter.addObserver(self, selector: #selector(handleTextViewTextDidBegin), name: NSNotification.Name.UITextViewTextDidBeginEditing, object: self) defaultCenter.addObserver(self, selector: #selector(handleTextViewTextDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: self) defaultCenter.addObserver(self, selector: #selector(handleTextViewTextDidEnd), name: NSNotification.Name.UITextViewTextDidEndEditing, object: self) } /// Removes the Notification handlers. fileprivate func removeNotificationHandlers() { let defaultCenter = NotificationCenter.default defaultCenter.removeObserver(self, name: NSNotification.Name.UITextViewTextDidBeginEditing, object: self) defaultCenter.removeObserver(self, name: NSNotification.Name.UITextViewTextDidChange, object: self) defaultCenter.removeObserver(self, name: NSNotification.Name.UITextViewTextDidEndEditing, object: self) } }
agpl-3.0
d2982b3462ecf7eb19b732842ed90300
29.326861
159
0.705154
4.428639
false
false
false
false
darrarski/DRNet
DRNet-Example-iOS/DRNet-Example-iOS/UI/MenuViewController.swift
1
3484
// // MenuViewController.swift // DRNet-Example-iOS // // Created by Dariusz Rybicki on 09/11/14. // Copyright (c) 2014 Darrarski. All rights reserved. // import UIKit class MenuViewController: UITableViewController { let menu: [MenuSection] = [ MenuSection( title: "Examples", items: [ MenuItem( title: "Example 1", subtitle: "Loading JSON using GET request with query string parameters", action: { (menuViewController) -> Void in let viewController = Example1ViewController() menuViewController.navigationController?.pushViewController(viewController, animated: true) } ), MenuItem( title: "Example 2", subtitle: "UIImageView subclass with remote image loader that supports caching and offline mode", action: { (menuViewController) -> Void in let viewController = Example2ViewController() menuViewController.navigationController?.pushViewController(viewController, animated: true) } ), ] ), ] // MARK: - Menu structure class MenuSection { let title: String let items: [MenuItem] init(title: String, items: [MenuItem]) { self.title = title self.items = items } } class MenuItem { typealias Action = (menuViewController: MenuViewController) -> Void let title: String let subtitle: String let action: Action init(title: String, subtitle: String, action: Action) { self.title = title self.subtitle = subtitle self.action = action } } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "DRNet iOS Examples" tableView.registerNib(UINib(nibName: "MenuItemCell", bundle: nil), forCellReuseIdentifier: "MenuItemCell") tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return menu.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu[section].items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MenuItemCell", forIndexPath: indexPath) as MenuItemCell cell.titleLabel.text = menu[indexPath.section].items[indexPath.row].title cell.subtitleLabel?.text = menu[indexPath.section].items[indexPath.row].subtitle return cell } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return menu[section].title } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { menu[indexPath.section].items[indexPath.row].action(menuViewController: self) } }
mit
8c3d64cfbad733f23bdc37ee65668724
32.5
119
0.598163
5.758678
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/Cheetah/CheetahLabelProperties.swift
3
783
// // CheetahLabelProperties.swift // Cheetah // // Created by Suguru Namura on 2015/08/22. // Copyright © 2015年 Suguru Namura. All rights reserved. // import UIKit class CheetahTextColorProperty: CheetahUIColorProperty { init(view: UIView!, textColor: UIColor, relative: Bool = false) { super.init() self.view = view self.to = textColor self.relative = relative } override func prepare() { guard let text = view as? UILabel else { return } super.prepare() from = text.textColor } override func update() { guard let text = view as? UILabel else { return } text.textColor = calculateUIColor(from: from, to: toCalc) } }
mit
2936559a3be8cd81df128b309a73a1b8
21.285714
69
0.582051
4.285714
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab2Search/views/SLVThemeHeaderFlexibleBar.swift
1
6380
// // SLVThemeHeaderFlexibleBar.swift // selluv-ios // // Created by 조백근 on 2017. 3. 19.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit class SLVThemeHeaderFlexibleBar: BLKFlexibleHeightBar { public static var barWidth: CGFloat = UIScreen.main.bounds.width public let backgroundImageView: UIImageView = { let imageView = UIImageView() imageView.frame = CGRect(x: 0, y: 0, width: SLVThemeHeaderFlexibleBar.barWidth, height: 250) imageView.image = UIImage(named: "profile-bg-default.png") imageView.backgroundColor = UIColor.black imageView.contentMode = .scaleToFill return imageView }() var brandNameLabel: UILabel = { let x = (SLVBrandHeaderFlexibleBar.barWidth - 240)/2 let label = UILabel() label.frame = CGRect(x: x, y: 20, width: 240, height: 44) label.textColor = UIColor.white label.backgroundColor = UIColor.clear label.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightMedium) label.textAlignment = .center return label }() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.blue setup() } //MARK: Event //staky setup func setup() { // Configure bar appearence self.maximumBarHeight = 250 self.minimumBarHeight = 64 self.backgroundColor = UIColor.white self.clipsToBounds = true self.translatesAutoresizingMaskIntoConstraints = false self.alpha9LayoutAttributes(view: self.backgroundImageView) self.addSubview(self.backgroundImageView) self.showLayoutAttributes(view: self.brandNameLabel) self.addSubview(self.brandNameLabel) } func hideLayoutAttributes(view: UIView) { let layout1 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout1.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout1.center = view.center layout1.alpha = 1.0 layout1.isHidden = false view.add(layout1, forProgress: 0.0) let layout2 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout2.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout2.center = view.center layout2.alpha = 0.5 view.add(layout2, forProgress: 0.3) let layout3 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout3.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout3.center = view.center layout3.alpha = 0.2 view.add(layout3, forProgress: 0.5) let layout4 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout4.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout4.center = view.center layout4.alpha = 0.0 view.add(layout4, forProgress: 0.7) let layout5 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout5.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout5.center = view.center layout5.isHidden = true layout5.alpha = 0.0 view.add(layout5, forProgress: 1.0) } func showLayoutAttributes(view: UIView) { let layout1 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout1.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout1.center = view.center layout1.isHidden = true layout1.alpha = 0.0 view.add(layout1, forProgress: 0.0) let layout2 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout2.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout2.center = view.center layout2.isHidden = false layout2.alpha = 0.2 view.add(layout2, forProgress: 0.3) let layout3 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout3.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout3.center = view.center layout3.alpha = 0.5 view.add(layout3, forProgress: 0.5) let layout4 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout4.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout4.center = view.center layout4.alpha = 0.8 view.add(layout4, forProgress: 0.7) let layout5 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout5.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout5.center = view.center layout5.alpha = 1 view.add(layout5, forProgress: 1.0) } func alpha9LayoutAttributes(view: UIView) { let layout1 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout1.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout1.center = view.center layout1.alpha = 1.0 layout1.isHidden = false view.add(layout1, forProgress: 0.0) let layout2 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout2.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout2.center = view.center layout2.alpha = 0.9 view.add(layout2, forProgress: 0.3) let layout3 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout3.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout3.center = CGPoint(x: width/2, y: self.maximumBarHeight/2 - 60) layout3.alpha = 0.9 view.add(layout3, forProgress: 0.5) let layout4 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout4.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout4.center = CGPoint(x: width/2, y: self.maximumBarHeight/2 - 100) layout4.alpha = 0.9 view.add(layout4, forProgress: 0.7) let layout5 = BLKFlexibleHeightBarSubviewLayoutAttributes() layout5.size = CGSize(width: view.bounds.width, height: view.bounds.height) layout5.center = CGPoint(x: width/2, y: self.minimumBarHeight/2) layout5.isHidden = false layout5.alpha = 0.9 view.add(layout5, forProgress: 1.0) } }
mit
aca04e2168cf9488477442c2197df993
39.069182
100
0.656569
4.081358
false
false
false
false
tombuildsstuff/swiftcity
SwiftCity/Entities/LastChanges.swift
1
792
public struct LastChanges { public let count: Int public let changes: [VCSChange]? init?(dictionary: [String: AnyObject]) { guard let count = dictionary["count"] as? Int else { return nil } if let changesDictionary = dictionary["change"] as? [[String: AnyObject]] { self.changes = changesDictionary.map({ (dictionary: [String : AnyObject]) -> VCSChange? in return VCSChange(dictionary: dictionary) }).filter({ (change: VCSChange?) -> Bool in return change != nil }).map({ (change: VCSChange?) -> VCSChange in return change! }) } else { self.changes = nil } self.count = count } }
mit
d37e550b01c24a256467714d4d3a8b84
29.5
102
0.520202
4.742515
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/BlockTap.swift
1
891
// // BlockTap.swift // DNSwiftProject // // Created by mainone on 16/12/20. // Copyright © 2016年 wjn. All rights reserved. // import UIKit open class BlockTap: UITapGestureRecognizer { private var tapAction: ((UITapGestureRecognizer) -> Void)? public override init(target: Any?, action: Selector?) { super.init(target: target, action: action) } public convenience init ( tapCount: Int = 1, fingerCount: Int = 1, action: ((UITapGestureRecognizer) -> Void)?) { self.init() self.numberOfTapsRequired = tapCount #if os(iOS) self.numberOfTouchesRequired = fingerCount #endif self.tapAction = action self.addTarget(self, action: #selector(BlockTap.didTap(_:))) } open func didTap (_ tap: UITapGestureRecognizer) { tapAction? (tap) } }
apache-2.0
db6a51463c1879f047d3c84cbc54f04f
24.371429
68
0.606982
4.331707
false
false
false
false
cxy921126/SoftSwift
Swimmer/Swimmer/DetailLearnController.swift
1
4381
// // DetailLearnController.swift // Swimmer // // Created by Mac mini on 16/9/20. // Copyright © 2016年 cxy. All rights reserved. // import UIKit import SnapKit let detailCellIdentifier = "detailCell" class DetailLearnController: UIViewController{ @IBOutlet weak var tableView: UITableView! var learning: Learning? var detailArr: [String] = [] override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false navigationController?.navigationBar.barStyle = .black // Do any additional setup after loading the view. tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: detailCellIdentifier) tableView.tableFooterView = UIView() setTableHeaderView() dicToArr() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) navigationController?.navigationBar.subviews.first?.alpha = 0 } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.barStyle = .default navigationController?.navigationBar.subviews.first?.alpha = 1 } var tableHeaderView: userAvatarHeader? ///存储背景图片初始高度用于计算放大倍数 var backgroundHeight: CGFloat? func setTableHeaderView(){ let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 175)) backgroundView.backgroundColor = UIColor.clear let headerView = Bundle.main.loadNibNamed("userAvatarHeader", owner: self, options: nil)?.last as! userAvatarHeader headerView.avatarView.image = UIImage(named: (learning?.user!.avatarAddress)!) headerView.genderView.image = UIImage(named: (learning?.user!.gender)!) headerView.personalityLabel.text = "个性签名:\(learning!.user!.personalDescription!)" tableHeaderView = headerView backgroundView.addSubview(tableHeaderView!) headerView.snp.makeConstraints { (make) in make.top.equalTo((headerView.superview?.snp.top)!) make.leading.equalTo((headerView.superview?.snp.leading)!) make.trailing.equalTo((headerView.superview?.snp.trailing)!) make.bottom.equalTo((headerView.superview?.snp.bottom)!) } tableView.tableHeaderView = backgroundView backgroundHeight = tableHeaderView?.backGroundView.bounds.height } func dicToArr() { detailArr.append(learning!.user!.nickName!) detailArr.append(learning!.natatorium!) detailArr.append(learning!.expectedTime!) detailArr.append(learning!.learningDescription!) } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } } extension DetailLearnController: UITableViewDataSource, UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return detailArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: detailCellIdentifier) cell?.textLabel?.text = detailArr[(indexPath as NSIndexPath).row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } extension DetailLearnController: UIScrollViewDelegate{ //MARK: 头像背景缩放 func scrollViewDidScroll(_ scrollView: UIScrollView) { let yOffset = scrollView.contentOffset.y if yOffset < 0 { // let scaleFactor = (abs(yOffset) + (tableHeaderView?.bounds.height)!) / (tableHeaderView?.bounds.height)! // tableHeaderView?.backGroundView.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor) let totalOffset = backgroundHeight! + abs(yOffset) let scaleFactor = totalOffset / backgroundHeight! tableHeaderView?.backGroundView.frame = CGRect(x: (screenWidth - screenWidth * scaleFactor)/2, y: yOffset, width: screenWidth * scaleFactor, height: totalOffset) } } }
mit
3e6315d939cc14f21112fd24ee5d707b
38.651376
173
0.690884
5.219807
false
false
false
false
oettam/camera-controls-demo
Camera/GLPreviewViewController.swift
1
1525
// // GLPreviewViewController.swift // Camera // // Created by Matteo Caldari on 28/01/15. // Copyright (c) 2015 Matteo Caldari. All rights reserved. // import UIKit import GLKit import CoreImage import OpenGLES class GLPreviewViewController: UIViewController, CameraPreviewViewController, CameraFramesDelegate { var cameraController:CameraController? { didSet { cameraController?.framesDelegate = self } } private var glContext:EAGLContext? private var ciContext:CIContext? private var renderBuffer:GLuint = GLuint() private var filter = CIFilter(name:"CIPhotoEffectMono") private var glView:GLKView { get { return view as! GLKView } } override func loadView() { self.view = GLKView() } override func viewDidLoad() { super.viewDidLoad() glContext = EAGLContext(api: .openGLES2) glView.context = glContext! glView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2) if let window = glView.window { glView.frame = window.bounds } ciContext = CIContext(eaglContext: glContext!) } // MARK: CameraControllerDelegate func cameraController(cameraController: CameraController, didOutputImage image: CIImage) { if glContext != EAGLContext.current() { EAGLContext.setCurrent(glContext) } glView.bindDrawable() filter?.setValue(image, forKey: "inputImage") let outputImage = filter?.outputImage ciContext?.draw(outputImage!, in:image.extent, from: image.extent) glView.display() } }
mit
aac979b327c2019b2f6bc548b1233504
20.478873
100
0.713443
3.950777
false
false
false
false
googlearchive/office-mover-5000
ios/OfficeMover5000/OfficeMover5000/Furniture.swift
3
2220
// // FurnitureModel.swift // OfficeMover500 // // Created by David on 10/28/14. // Copyright (c) 2014 Firebase. All rights reserved. // import UIKit var maxZIndex = 0 class Furniture { var key : String var name: String var top : Int var left : Int var zIndex: Int var rotation: Int var type : String init(key: String, json: Dictionary<String, AnyObject>) { self.key = key self.name = json["name"] as? String ?? "" self.type = json["type"] as? String ?? "desk" self.zIndex = json["z-index"] as? Int ?? ++maxZIndex self.rotation = json["rotation"] as? Int ?? 0 let defaultLoc = Furniture.defaultLocation(self.type) self.top = json["top"] as? Int ?? defaultLoc.top self.left = json["left"] as? Int ?? defaultLoc.left if self.zIndex > maxZIndex { maxZIndex = self.zIndex } } // Use this when adding one locally // You'll need to set top / left appropriately. init(key: String, type: String) { self.key = key self.name = "" self.rotation = 0 self.type = type self.zIndex = ++maxZIndex let defaultLoc = Furniture.defaultLocation(self.type) self.top = defaultLoc.top self.left = defaultLoc.left } convenience init(snap: FDataSnapshot) { if let json = snap.value as? Dictionary<String, AnyObject> { self.init(key: snap.key, json: json) } else { fatalError("blah") } } func toJson() -> Dictionary<String, AnyObject> { return [ "top" : self.top, "left" : self.left, "z-index" : self.zIndex, "name" : self.name, "rotation" : self.rotation, "type" : self.type, ]; } class private func defaultLocation(type: String) -> (top: Int, left: Int) { if let image = UIImage(named:"\(type).png") { return (top: RoomHeight/2 - Int(image.size.height)/2, left: RoomWidth/2 - Int(image.size.width)/2) } else { return (top: RoomHeight/2, left: RoomWidth/2) } } }
mit
1e150c9e35f5ad5d25f317aa02623d73
26.7625
110
0.542342
3.762712
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Geometry/Cut geometry/CutGeometryViewController.swift
1
9443
// Copyright 2018 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class CutGeometryViewController: UIViewController { // MARK: Storyboard views /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { // Create a map with a topographic basemap. mapView.map = AGSMap(basemapStyle: .arcGISTopographic) // Add the graphics overlays to the map view. mapView.graphicsOverlays.addObjects(from: [lakeGraphicsOverlay, cutGraphicsOverlay]) // Set viewpoint to the extent of the Lake Superior graphics overlay. mapView.setViewpointGeometry(lakeSuperiorPolygonGraphic.geometry!) } } // MARK: Instance properties /// A Boolean value indicating whether the geometry is cut. var isGeometryCut = false /// A polygon representing the area of Lake Superior. var lakeSuperiorPolygonGraphic: AGSGraphic { lakeGraphicsOverlay.graphics.firstObject as! AGSGraphic } /// A polyline representing the Canada/USA border. var borderPolylineGraphic: AGSGraphic { lakeGraphicsOverlay.graphics.lastObject as! AGSGraphic } /// A graphics overlay containing the Lake Superior polygon and border line. let lakeGraphicsOverlay: AGSGraphicsOverlay = { let lakeSuperiorPolygonGraphic: AGSGraphic = { // Create an array of points that represents Lake Superior (polygon). // Use the same spatial reference as the underlying base map. let points = [ AGSPoint(x: -10254374.668616, y: 5908345.076380, spatialReference: .webMercator()), AGSPoint(x: -10178382.525314, y: 5971402.386779, spatialReference: .webMercator()), AGSPoint(x: -10118558.923141, y: 6034459.697178, spatialReference: .webMercator()), AGSPoint(x: -9993252.729399, y: 6093474.872295, spatialReference: .webMercator()), AGSPoint(x: -9882498.222673, y: 6209888.368416, spatialReference: .webMercator()), AGSPoint(x: -9821057.766387, y: 6274562.532928, spatialReference: .webMercator()), AGSPoint(x: -9690092.583250, y: 6241417.023616, spatialReference: .webMercator()), AGSPoint(x: -9605207.742329, y: 6206654.660191, spatialReference: .webMercator()), AGSPoint(x: -9564786.389509, y: 6108834.986367, spatialReference: .webMercator()), AGSPoint(x: -9449989.747500, y: 6095091.726408, spatialReference: .webMercator()), AGSPoint(x: -9462116.153346, y: 6044160.821855, spatialReference: .webMercator()), AGSPoint(x: -9417652.665244, y: 5985145.646738, spatialReference: .webMercator()), AGSPoint(x: -9438671.768711, y: 5946341.148031, spatialReference: .webMercator()), AGSPoint(x: -9398250.415891, y: 5922088.336339, spatialReference: .webMercator()), AGSPoint(x: -9419269.519357, y: 5855797.317714, spatialReference: .webMercator()), AGSPoint(x: -9467775.142741, y: 5858222.598884, spatialReference: .webMercator()), AGSPoint(x: -9462924.580403, y: 5902686.086985, spatialReference: .webMercator()), AGSPoint(x: -9598740.325877, y: 5884092.264688, spatialReference: .webMercator()), AGSPoint(x: -9643203.813979, y: 5845287.765981, spatialReference: .webMercator()), AGSPoint(x: -9739406.633691, y: 5879241.702350, spatialReference: .webMercator()), AGSPoint(x: -9783061.694736, y: 5922896.763395, spatialReference: .webMercator()), AGSPoint(x: -9844502.151022, y: 5936640.023354, spatialReference: .webMercator()), AGSPoint(x: -9773360.570059, y: 6019099.583107, spatialReference: .webMercator()), AGSPoint(x: -9883306.649729, y: 5968977.105610, spatialReference: .webMercator()), AGSPoint(x: -9957681.938918, y: 5912387.211662, spatialReference: .webMercator()), AGSPoint(x: -10055501.612742, y: 5871965.858842, spatialReference: .webMercator()), AGSPoint(x: -10116942.069028, y: 5884092.264688, spatialReference: .webMercator()), AGSPoint(x: -10111283.079633, y: 5933406.315128, spatialReference: .webMercator()), AGSPoint(x: -10214761.742852, y: 5888134.399970, spatialReference: .webMercator()), AGSPoint(x: -10254374.668616, y: 5901877.659929, spatialReference: .webMercator()) ] // Create a polygon from the array of points. let polygon = AGSPolygon(points: points) // Create a blue border line symbol with a stroke weight of 4 for // the Lake Superior polygon. let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: .blue, width: 4) // Create a semi transparent blue fill symbol using the red // border line symbol for the Lake Superior polygon. let fillSymbol = AGSSimpleFillSymbol(style: .solid, color: #colorLiteral(red: 0, green: 0, blue: 1, alpha: 0.1), outline: lineSymbol) // Create and return a graphic using the polyline and fill symbol // for the border polyline. return AGSGraphic(geometry: polygon, symbol: fillSymbol) }() let borderPolylineGraphic: AGSGraphic = { // Create an array of points that represents a cut line. let points = [ AGSPoint(x: -9981328.687124, y: 6111053.281447, spatialReference: .webMercator()), AGSPoint(x: -9946518.044066, y: 6102350.620682, spatialReference: .webMercator()), AGSPoint(x: -9872545.427566, y: 6152390.920079, spatialReference: .webMercator()), AGSPoint(x: -9838822.617103, y: 6157830.083057, spatialReference: .webMercator()), AGSPoint(x: -9446115.050097, y: 5927209.572793, spatialReference: .webMercator()), AGSPoint(x: -9430885.393759, y: 5876081.440801, spatialReference: .webMercator()), AGSPoint(x: -9415655.737420, y: 5860851.784463, spatialReference: .webMercator()) ] // Create a polyline from the array of points. let polyline = AGSPolyline(points: points) // Create a red border line symbol with a stroke weight of 5. let lineSymbol = AGSSimpleLineSymbol(style: .dot, color: .red, width: 5) // Create and return a graphic using the polyline and line symbol // for the border polyline. return AGSGraphic(geometry: polyline, symbol: lineSymbol, attributes: nil) }() // Create a graphics overlay. let overlay = AGSGraphicsOverlay() // Add the Lake Superior graphics to the overlay. overlay.graphics.addObjects(from: [lakeSuperiorPolygonGraphic, borderPolylineGraphic]) return overlay }() /// The graphics overlay containing cut graphics. let cutGraphicsOverlay = AGSGraphicsOverlay() // MARK: Actions /// Cut geometry and add resulting graphics. func cutGeometry() { // Cut the Lake Superior polygon using the border polyline. guard let parts = AGSGeometryEngine.cut(lakeSuperiorPolygonGraphic.geometry!, withCutter: borderPolylineGraphic.geometry as! AGSPolyline), parts.count == 2, let firstPart = parts.first, let secondPart = parts.last else { return } // Create the graphics for the Canadian and USA sides of Lake Superior. let canadaSideGraphic = AGSGraphic(geometry: firstPart, symbol: AGSSimpleFillSymbol(style: .backwardDiagonal, color: .green, outline: nil)) let usaSideGraphic = AGSGraphic(geometry: secondPart, symbol: AGSSimpleFillSymbol(style: .forwardDiagonal, color: .yellow, outline: nil)) // Add the graphics to the graphics overlay. cutGraphicsOverlay.graphics.addObjects(from: [canadaSideGraphic, usaSideGraphic]) } /// Removes all cut graphics. func reset() { cutGraphicsOverlay.graphics.removeAllObjects() } @IBAction func cutGeometryWithPolyline(_ sender: UIBarButtonItem) { isGeometryCut ? reset() : cutGeometry() isGeometryCut.toggle() // Set button title based on whether the geometry is cut. sender.title = isGeometryCut ? "Reset" : "Cut" } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["CutGeometryViewController"] } }
apache-2.0
640e2099f18109dc48ce68c669bdf22b
53.901163
147
0.645558
4.15808
false
false
false
false
masters3d/xswift
exercises/sublist/Sources/SublistExample.swift
3
1353
import Foundation enum SublistKind { case sublist case superlist case equal case unequal } func classifier(listOne: [Int], listTwo: [Int]) -> SublistKind { if listOne == listTwo { return .equal } else if listOne.isEmpty || listTwo.isEmpty { if listOne.isEmpty { return .sublist } return .superlist } else if listOne.count != listTwo.count { var i = 0 var count = 0 var smallerList = [Int]() var iterations = 0 iterations = max(listOne.count, listTwo.count) - (min(listOne.count, listTwo.count) - 1) while iterations > 0 { var j = i while count <= min(listOne.count, listTwo.count) - 1 { if listOne.count > listTwo.count { smallerList.append(listOne[j]) } else { smallerList.append(listTwo[j]) } j+=1 count+=1 } if smallerList == listTwo { return .superlist } else if smallerList == listOne { return .sublist } else { smallerList.removeAll() i+=1 count = 0 } iterations-=1 } } return .unequal }
mit
53cbd7ff2c90badcdf2c7638ed6d1b15
17.791667
96
0.473023
4.436066
false
false
false
false
abelsanchezali/ViewBuilder
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/LayoutPerformanceViewController.swift
1
5776
// // LayoutPerformanceViewController.swift // ViewBuilderDemo // // Created by Abel Sanchez on 8/3/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit import ViewBuilder public class LayoutPerformanceViewController: UIViewController { weak var scrollPanel: ScrollPanel! weak var infoLabel: UILabel! weak var overviewLabel: UILabel! var resultViews: [LayoutPerformanceResultView]! var measureCount = 0 var isMeasuring = false override public func loadView() { view = DocumentBuilder.shared.load(Constants.bundle.path(forResource: "LayoutPerformanceView", ofType: "xml")!) scrollPanel = view.documentReferences!["scrollPanel"] as! ScrollPanel infoLabel = view.documentReferences!["infoLabel"] as! UILabel overviewLabel = view.documentReferences!["overviewLabel"] as! UILabel resultViews = [view.documentReferences!["resultView0"] as! LayoutPerformanceResultView, view.documentReferences!["resultView1"] as! LayoutPerformanceResultView, view.documentReferences!["resultView2"] as! LayoutPerformanceResultView, view.documentReferences!["resultView3"] as! LayoutPerformanceResultView] } public override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(composeHandler)) scrollPanel.delegate = self } @objc func composeHandler() { NavigationHelper.presentDocumentVisualizer(self, path: Constants.bundle.path(forResource: "LayoutPerformanceView", ofType: "xml"), completion: nil) } func startMeasuring() { isMeasuring = true let alert = UIAlertController(title: "Measuring...", message: nil, preferredStyle: .alert) present(alert, animated: true, completion: nil) measureCount += 1 var times: [Double] = [0, 0, 0, 0] AnimationHelper.delayedBlock(0.5) { let iterations = [(0, 100), (1, 1000), (2, 3000)] print("UIStackView") self.resultViews[0].resetResults() iterations.forEach({ (iter) in times[0] = self.testView(Card3CollectionViewCell(), times: iter.1) self.resultViews[0].setResultTime(times[0], index: iter.0) }) AnimationHelper.delayedBlock(0.5, block: { print("StackView") self.resultViews[1].resetResults() iterations.forEach({ (iter) in times[1] = self.testView(Card0CollectionViewCell(), times: iter.1) self.resultViews[1].setResultTime(times[1], index: iter.0) }) AnimationHelper.delayedBlock(0.5, block: { print("AutoLayout+IB") self.resultViews[2].resetResults() iterations.forEach({ (iter) in times[2] = self.testView(Card7CollectionViewCell(), times: iter.1) self.resultViews[2].setResultTime(times[2], index: iter.0) }) AnimationHelper.delayedBlock(0.5, block: { print("StackPanel") self.resultViews[3].resetResults() iterations.forEach({ (iter) in times[3] = self.testView(Card5CollectionViewCell(), times: iter.1) self.resultViews[3].setResultTime(times[3], index: iter.0) }) let minRatio = min(times[0], times[1], times[2]) / times[3] let maxRatio = max(times[0], times[1], times[2]) / times[3] self.overviewLabel.text = NSString(format: "%.1lfx - %.1lfx", minRatio, maxRatio) as String alert.dismiss(animated: true) { self.scrollPanel.scrollToBottom(true) } self.isMeasuring = false }) }) }) } } // MARK: - Testing let texts = [Lorem.paragraphs(2), Lorem.paragraphs(2), Lorem.paragraphs(2)] func testView(_ view: CollectionViewCellProtocol, times: Int) -> Double { var elapsed = 0.0 for _ in 0..<times { let viewModel = Generator.genarateViewModelFor(type(of: view).reuseIdentifier()) let start = CFAbsoluteTimeGetCurrent() _ = type(of: view).measureForFitSize(CGSize(width: 300, height: CGFloat.largeValue), dataSource: viewModel) let end = CFAbsoluteTimeGetCurrent() elapsed = elapsed + (end - start) //print(size) } print(elapsed) return elapsed } } // MARK: - UIScrollViewDelegate extension LayoutPerformanceViewController: UIScrollViewDelegate { public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if isMeasuring { return } if scrollPanel.contentOffset.y < -50 { if measureCount > 0 { let alert = UIAlertController(title: "Layout Performance", message: "Do you want to make another measurement.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) in self.startMeasuring() })) alert.addAction(UIAlertAction(title: "No", style: .destructive, handler: nil)) present(alert, animated: true, completion: nil) } else { startMeasuring() } } } }
mit
c48cc60d3fecc816f97a16faa8b4db9c
43.423077
155
0.582511
4.788557
false
false
false
false
digoreis/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0115.xcplaygroundpage/Contents.swift
2
9474
/*: # Rename Literal Syntax Protocols * Proposal: [SE-0115](0115-literal-syntax-protocols.md) * Author: [Matthew Johnson](https://github.com/anandabits) * Review Manager: [Chris Lattner](http://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000220.html) * Bug: [SR-2054](https://bugs.swift.org/browse/SR-2054) ## Introduction This proposal renames the `*LiteralConvertible` protocols to `ExpressibleBy*Literal`. Swift-evolution thread: [Literal Syntax Protocols](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160620/021865.html) An earlier thread that resulted in this proposal: [Revisiting SE-0041 Names](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160620/021714.html) ## Motivation The standard library currently has protocols that use the term `Convertible` in two different ways. The `*LiteralConvertible` protocols use the meaning of converting *from* a literal. The `Custom(Debug)StringConvertible` protocols use the meaning of converting *to* a `String`. This causes confusion for developers attempting to name their own protocols following the precedence established by the standard library. Further, the standard library team has observed: > The "literal" protocols are not about conversion, they are about adopting > a certain syntax provided by the language. "Convertible" in the name is > a red herring: a type can't be convertible from an integer literal because > there is no "IntegerLiteral" entity in the type system. > The literal *becomes* typed as the corresponding literal type > (e.g., Int or String), and as far as the user at the call site is concerned, > there is no visible conversion (even if one is happening behind the scenes). [An earlier proposal](https://github.com/apple/swift-evolution/blob/master/proposals/0041-conversion-protocol-conventions.md) was intended to address the first problem by introducing strong naming conventions for three kinds of conversion protocols (*from*, *to*, and *bidirectional*). The review highlighted the difficulty in establishing conventions that everyone is happy with. This proposal takes a different approach to solving the problem that originally inspired that proposal while also solving the awkwardness of the current names described by the standard library team. ## Proposed solution This proposal addresses both problems by renaming the protocols to `ExpressibleBy*Literal`. The proposal **does not** make any changes to the requirements of the protocols. ## Detailed design All of the `*LiteralConvertible` protocols will receive new `ExpressibleBy*Literal` names. This proposal does not change any requirements of these protocols. All requirements of all `*LiteralConvertible` protocols will remain exactly the same. The following protocol declarations and names: ```swift public protocol NilLiteralConvertible { ... } public protocol BooleanLiteralConvertible { ... } public protocol FloatLiteralConvertible { ... } public protocol IntegerLiteralConvertible { ... } public protocol UnicodeScalarLiteralConvertible { ... } public protocol ExtendedGraphemeClusterLiteralConvertible { ... } public protocol StringLiteralConvertible { ... } public protocol StringInterpolationConvertible { ... } public protocol ArrayLiteralConvertible { ... } public protocol DictionaryLiteralConvertible { ... } ``` Are changed as follows: ```swift public protocol ExpressibleByNilLiteral { ... } public protocol ExpressibleByBooleanLiteral { ... } public protocol ExpressibleByFloatLiteral { ... } public protocol ExpressibleByIntegerLiteral { ... } public protocol ExpressibleByUnicodeScalarLiteral { ... } public protocol ExpressibleByExtendedGraphemeClusterLiteral { ... } public protocol ExpressibleByStringLiteral { ... } public protocol ExpressibleByStringInterpolation { ... } public protocol ExpressibleByArrayLiteral { ... } public protocol ExpressibleByDictionaryLiteral { ... } ``` ## Impact on existing code All code that references any of the `*LiteralConvertible` protocols will need to be modified to reference the protocol via the new `ExpressibleBy*Literal` name. ## Alternatives considered Discussion of the pros and cons of the proposed and alternative naming schemes is encouraged. The core team should feel free to choose names they deem best suited for Swift after community discussion and review if they decide to accept this proposal. The discussion thread for this proposal includes abundant bike shedding on the names. This section includes selected examples to highlight different directions that have been discussed. Reviewers are encouraged to read the discussion thread if they wish to see all of the alternatives. The thread includes abundant discusison of the pros and cons of many naming ideas. Some of the names that have been suggested have been inaccurate due to a misunderstanding of what the protocols do. Dave Abrahams explained during the discussion: > No, it's exactly the opposite, as I keep saying. Conformance to this > protocol does *not* mean you can initialize the type with a literal. > Proof: > > ```swift > func f<T: IntegerLiteralConvertible>() -> T { > return T(integerLiteral: 43) // Error > return T(43) // Also an Error > } > > // It means an instance of the type can be *written* as a literal: > > func f<T: IntegerLiteralConvertible>() -> T { > return 43 // OK > } >``` > > Everybody's confused about the meaning of the protocol, and doesn't like > the proposed names because they imply exactly the actual meaning of the > protocol, which they misunderstand. ### Previous Version The original version of this proposal introduced a `Syntax` "namespace" (using an empty `enum`) and placed the protocols in that namespace with a `*Literal` naming scheme like this: ```swift public protocol _NilLiteralSyntax { ... } public /* closed */ enum Syntax { public typealias NilLiteral = _NilLiteralSyntax } ``` Several commenters suggested that this naming scheme is confusing at the site of use. The ensuing discussion led to the approach in the current proposal. Nate Cook provided the best explanation of the potential confusion: > Primarily, the new names read like we're saying that a conforming type is a > literal, compounding a common existing confusion between literals and types > that can be initialized with a literal. Swift's type inference can sometimes > make it seem like dark magic is afoot with literal conversions—for example, > you need to understand an awful lot about the standard library to figure out > why line 1 works here but not line 2: >```swift >var x = [1, 2, 3, 4, 5] >let y = [10, 20] > >x[1..<2] = [10, 20] // 1 >x[1..<2] = y // 2 >``` (Note: The comment above is still valid if it is corrected to say "types that can have instances *written as* a literal" rather than "types that can be *initialized with* a literal".) > These new names are a (small) step in the wrong direction. While it's true > that the type system doesn't have an IntegerLiteral type, the language does > have integer literals. If someone reads: > >```swift >extension MyInt : Syntax.IntegerLiteral { ... } >``` > > the implication is that MyInt is an integer literal, and therefore instances > of MyInt should be usable wherever an integer literal is usable. > The existing "Convertible" wording may be a red herring, but it at least > suggests that there's a difference between a literal and a concrete type. ### Namespace names David Sweeris suggested `Compiler` as an alternative to `Syntax`. Adrian Zubarev suggested a convention using a nested namespace `Literal.*Protocol`. ### Protocol names An alternative naming scheme suggested by Xiaodi Wu emphasizes that the type *conforms to a protocol* rather than *is a literal* is: ```swift struct Foo: Syntax.IntegerLiteralProtocol { ... } ``` ### Rename the protocols without placing them in a namespace Adrian Zubarev suggests that we could use the `*LiteralProtocol` naming scheme for these protocols (replacing `Convertible` with `Protocol`) without placing them in a namespace: ```swift public protocol NilLiteralProtocol { ... } public protocol BooleanLiteralProtocol { ... } public protocol IntegerLiteralProtocol { ... } public protocol FloatLiteralProtocol { ... } public protocol UnicodeScalarLiteralProtocol { ... } public protocol ExtendedGraphemeClusterProtocol { ... } public protocol StringLiteralProtocol { ... } public protocol StringInterpolationLiteralProtocol { ... } public protocol ArrayLiteralProtocol { ... } public protocol DictionaryLiteralProtocol { ... } ``` ### Previous proposal This proposal is a follow up to [Updating Protocol Naming Conventions for Conversions](0041-conversion-protocol-conventions.md). Many related alternatives were explored during the discussion and review of that proposal. ## Acknowledgements The name used in the final proposal was first suggested by Sean Heber. Dave Abrahams suggested moving it out of the `Syntax` namespace that was used in the original draft of this proposal. The design in the original draft was suggested by Dave Abrahams, Dmitri Gribenko, and Maxim Moiseev. Dave Abrahams, Nate Cook, David Sweeris, Adrian Zubarev and Xiaodi Wu contributed ideas to the alternatives considered section. ---------- [Previous](@previous) | [Next](@next) */
mit
d5d1b63c81a33f4524cba46573880fe4
45.660099
581
0.766997
4.465818
false
false
false
false
msdgwzhy6/SAHistoryNavigationViewController
SAHistoryNavigationViewController/NSLayoutConstraint+Fit.swift
2
1770
// // NSLayoutConstraint+Fit.swift // SAHistoryNavigationViewController // // Created by 鈴木大貴 on 2015/03/26. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit extension NSLayoutConstraint { class func applyAutoLayout(superview: UIView, target: UIView, index: Int?, top: Float?, left: Float?, right: Float?, bottom: Float?, height: Float?, width: Float?) { target.setTranslatesAutoresizingMaskIntoConstraints(false) if let index = index { superview.insertSubview(target, atIndex: index) } else { superview.addSubview(target) } var verticalFormat = "V:" if let top = top { verticalFormat += "|-(\(top))-" } verticalFormat += "[target" if let height = height { verticalFormat += "(\(height))" } verticalFormat += "]" if let bottom = bottom { verticalFormat += "-(\(bottom))-|" } let verticalConstrains = NSLayoutConstraint.constraintsWithVisualFormat(verticalFormat, options: nil, metrics: nil, views: [ "target" : target ]) superview.addConstraints(verticalConstrains) var horizonFormat = "H:" if let left = left { horizonFormat += "|-(\(left))-" } horizonFormat += "[target" if let width = width { horizonFormat += "(\(width))" } horizonFormat += "]" if let right = right { horizonFormat += "-(\(right))-|" } let horizonConstrains = NSLayoutConstraint.constraintsWithVisualFormat(horizonFormat, options: nil, metrics: nil, views: [ "target" : target ]) superview.addConstraints(horizonConstrains) } }
mit
3a42edb26d8a24cb6ed9a0aee07e1d4d
34.04
169
0.585046
4.8
false
false
false
false
NathanHaley/mobile_pick_largest_shape_game
GameMaxAreaPicker/GameView.swift
1
6328
//TODO: Refactor to not be so tightly coupled with GameViewController import UIKit class GameView: UIView { // MARK: Properties var gc: GameViewController! var shapeCount = 0 var isNew = true var isPortraitView = UIApplication.sharedApplication().statusBarOrientation.isPortrait // MARK: Shape positioning and scaling // TODO: Look at simplifying this in conjunction with addShapes, start by pulling out repeats func positionShapes(forRotation forRotation: Bool = false) { let shapeCount = subviews.count let sizes = sizeShapes(shapeCount) let sectionLength = sizes["sectionLength"]! let shapeSideLengthMax = sizes["shapeSideLengthMax"]! let positionalCenter = {(index: Int) in sectionLength * CGFloat(index + 1) - sectionLength * 0.5} var index = 0 // Check and set scale if needed if Int(gc.turnMaxSideLength) > Int(shapeSideLengthMax) { gc.scale = shapeSideLengthMax / gc.turnMaxSideLength gc.turnMaxArea = 0.0 gc.turnMaxSideLength = 0.0 } for shape in subviews { let button = shape as! CustomButton var shapeCenterX: CGFloat = 0.0 var shapeCenterY: CGFloat = 0.0 var sideLength = button.bounds.width if isPortraitView { // Incase we scaled to fit landscape, set back to original size sideLength = button.originalSize.width shapeCenterX = bounds.midX shapeCenterY = positionalCenter(index) } else { sideLength = sideLength * gc.scale shapeCenterX = positionalCenter(index) shapeCenterY = bounds.midY } let size = CGSize(width: sideLength, height: sideLength) button.sizeThatFits(size) button.frame.size = size button.center = CGPoint(x: shapeCenterX, y: shapeCenterY) index++ } // If we've backed out previous scale need to reset this if isPortraitView { gc.scale = 1.0 } for shape in subviews { vetMaxAreaAndSideLength(shape as! CustomButton) } } // MARK: Shape creation func addShapes(addCount: Int, shapeType: String = "circles") { let sizes = sizeShapes(addCount) let shapeSideLengthMax = sizes["shapeSideLengthMax"]! // Clear any previous views for clean slate for view in self.subviews { view.removeFromSuperview() } for _ in 0..<addCount { let randomFactor = Utils.randomBetweenLower(0.3, andUpper: 0.8) let randomSideLength = shapeSideLengthMax * randomFactor let newFrame = CGRect(x: 0.0, y: 0.0, width: randomSideLength, height: randomSideLength) var newShapeButton: CustomButton! if gc.gameBoardType == "circles" { newShapeButton = CircleButton(frame: newFrame) } else if gc.gameBoardType == "squares" { newShapeButton = SquareButton(frame: newFrame) } else { let randomGame = Utils.randomBetweenLower(0, andUpper: 1) if randomGame > 0.50 { newShapeButton = CircleButton(frame: newFrame) } else { newShapeButton = SquareButton(frame: newFrame) } } addSubview(newShapeButton) newShapeButton.addTarget(self, action: "tappedShapeAction:", forControlEvents: UIControlEvents.TouchDown) newShapeButton.originalSize = newShapeButton.frame.size //Apply visuals newShapeButton.fillColor = Utils.randomColor() newShapeButton.outlineColor = Utils.randomColor() vetMaxAreaAndSideLength(newShapeButton) } positionShapes() isNew = false } // MARK: Shape helpers func sizeShapes(shapeCount: Int) -> [String: CGFloat] { var longBound = max(bounds.width,bounds.height) if isPortraitView { longBound -= 60 // TODO: Adjusting for toolbar until I figure out better layout approach } let shortBound = min(bounds.width,bounds.height) let sectionLength = longBound / CGFloat(shapeCount) var shapeSideLengthMax = min(longBound / CGFloat(shapeCount), shortBound) //Use min to avoid clipping if shortBound < shapeSideLengthMax { shapeSideLengthMax = shortBound } let sizes = ["longBound": longBound, "shortBound": shortBound, "sectionLength": sectionLength, "shapeSideLengthMax": shapeSideLengthMax] return sizes } func vetMaxAreaAndSideLength(sender: CustomButton) { // Find/set the area from the largest shape if sender.area > gc.turnMaxArea { gc.turnMaxArea = sender.area } if sender.frame.width > gc.turnMaxSideLength { gc.turnMaxSideLength = sender.frame.width } } // MARK: Overrides override func layoutSubviews() { super.layoutSubviews() isPortraitView = UIApplication.sharedApplication().statusBarOrientation.isPortrait if !isNew { positionShapes(forRotation: true) } } // MARK: Actions func tappedShapeAction(sender: CustomButton!) { gc.tappedArea = sender.area NSNotificationCenter.defaultCenter().postNotificationName("shapeTap\(gc.pageIndex)", object: nil) } override func drawRect(rect: CGRect) { super.drawRect(rect) addShapes(gc.shapeCountRandom, shapeType: gc.gameBoardType) } }
mit
a2276dd8839fbc4d63a8265b78c968df
30.482587
144
0.555468
5.335582
false
false
false
false
gbuela/kanjiryokucha
KanjiRyokucha/ArrayExtensions.swift
1
1133
// // ArrayExtensions.swift // KanjiRyokucha // // Created by German Buela on 4/13/17. // Copyright © 2017 German Buela. All rights reserved. // import Foundation extension Array where Element: Equatable { func removing(_ objects: [Element]) ->[Element] { var newArray = self objects.forEach { if let index = newArray.firstIndex(of: $0) { newArray.remove(at: index) } } return newArray } } extension Array { func chunks(ofSize chunkSize: Int) -> [[Element]] { let chunks = stride(from: 0, to: count, by: chunkSize).map { Array(self[$0..<Swift.min($0 + chunkSize, count)]) } return chunks } } extension Array where Element : ReviewEntry { func count(answer: CardAnswer) -> Int { return self.filter { $0.rawAnswer == answer.rawValue }.count } var countSubmitted: Int { return self.filter { $0.submitted }.count } var countUnsubmitted: Int { return self.filter { !$0.submitted && $0.rawAnswer != CardAnswer.unanswered.rawValue }.count } }
mit
08c20fb0d17a9b073c222105ac94856f
23.608696
100
0.589223
3.97193
false
false
false
false
RailwayStations/Bahnhofsfotos
fastlane/SnapshotHelper.swift
2
11632
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotDetectUser case cannotFindHomeDirectory case cannotFindSimulatorHomeDirectory case cannotAccessSimulatorHomeDirectory(String) case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotDetectUser: return "Couldn't find Snapshot configuration files - can't detect current user " case .cannotFindHomeDirectory: return "Couldn't find Snapshot configuration files - can't detect `Users` dir" case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome): return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var waitForAnimations = true static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.app = app Snapshot.waitForAnimations = waitForAnimations do { let cacheDir = try pathPrefix() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { NSLog(error.localizedDescription) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { NSLog("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { NSLog("Couldn't detect/set locale...") } if locale.isEmpty && !deviceLanguage.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } if !locale.isEmpty { app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { NSLog("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work if Snapshot.waitForAnimations { sleep(1) // Waiting for the animation to be finished (kind of) } #if os(OSX) guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard self.app != nil else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let screenshot = XCUIScreen.main.screenshot() guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } do { // The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ") let range = NSMakeRange(0, simulator.count) simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "") let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") try screenshot.pngRepresentation.write(to: path) } catch let error { NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png") NSLog(error.localizedDescription) } #endif } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func pathPrefix() throws -> URL? { let homeDir: URL // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { throw SnapshotError.cannotDetectUser } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { throw SnapshotError.cannotFindHomeDirectory } homeDir = usersDir.appendingPathComponent(user) #else #if arch(i386) || arch(x86_64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } guard let homeDirUrl = URL(string: simulatorHostHome) else { throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) } homeDir = URL(fileURLWithPath: homeDirUrl.path) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasWhiteListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasWhiteListedIdentifier: Bool { let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return whiteListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return self.containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { guard let app = Snapshot.app else { fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") } let deviceWidth = app.windows.firstMatch.frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return self.containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.20]
apache-2.0
56d3e8532feef1b058b7618fdd42c4f8
37.389439
158
0.640818
5.512796
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/Nimble/Nimble/Matchers/HaveCount.swift
27
2147
import Foundation /// A Nimble matcher that succeeds when the actual CollectionType's count equals /// the expected value public func haveCount<T: CollectionType>(expectedValue: T.Index.Distance) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in if let actualValue = try actualExpression.evaluate() { failureMessage.postfixMessage = "have \(actualValue) with count \(actualValue.count)" let result = expectedValue == actualValue.count failureMessage.actualValue = "\(expectedValue)" return result } else { return false } } } /// A Nimble matcher that succeeds when the actual collection's count equals /// the expected value public func haveCount(expectedValue: Int) -> MatcherFunc<NMBCollection> { return MatcherFunc { actualExpression, failureMessage in if let actualValue = try actualExpression.evaluate() { failureMessage.postfixMessage = "have \(actualValue) with count \(actualValue.count)" let result = expectedValue == actualValue.count failureMessage.actualValue = "\(expectedValue)" return result } else { return false } } } extension NMBObjCMatcher { public class func haveCountMatcher(expected: NSNumber) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() if let value = actualValue as? NMBCollection { let expr = Expression(expression: ({ value as NMBCollection}), location: location) return try! haveCount(expected.integerValue).matches(expr, failureMessage: failureMessage) } else if let actualValue = actualValue { failureMessage.postfixMessage = "get type of NSArray, NSSet, NSDictionary, or NSHashTable" failureMessage.actualValue = "\(NSStringFromClass(actualValue.dynamicType))" } return false } } }
mit
d109d23e4c0be11ea3eea551174035c2
43.729167
106
0.665114
5.834239
false
false
false
false
brunomorgado/ScrollableAnimation
ScrollableAnimation/Source/Animation/ScrollableAnimation.swift
1
5336
// // ScrollableAnimation.swift // ScrollableMovie // // Created by Bruno Morgado on 18/12/14. // Copyright (c) 2014 kocomputer. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit class ScrollableAnimation: NSObject { var distance: Float var beginOffset: Float var offsetFunction: TweenBlock? var delegate: AnyObject! var isAnimating: Bool override init() { self.beginOffset = 0.0 self.distance = 0.0 self.isAnimating = false super.init() } func processAnimatable(animatable: CALayer, forOffset offset: Float, completion: (() -> ())?) { self.updateStatusForOffset(offset) if let completion = completion { completion() } } // MARK: - Private methods private func updateStatusForOffset(offset: Float) { var offsetPercentage = self.getPercentageForOffset(offset) if (offsetPercentage <= 0 || offsetPercentage >= 1) { if (isAnimating) { delegate?.scrollableAnimationDidStop!(self) } isAnimating = false } else { if (!isAnimating) { delegate?.scrollableAnimationDidStart!(self) } isAnimating = true } } // MARK: - Helper methods private func getPercentageForOffset(offset: Float) -> Float { return (offset - self.beginOffset) / self.distance } } class ScrollablePropertyAnimation: ScrollableAnimation { var keyPath: String // var additive: Bool {get set} //TODO init(keyPath: String) { self.keyPath = keyPath super.init() } } class ScrollableBasicAnimation: ScrollablePropertyAnimation { var fromValue: NSValue? var toValue: NSValue? override func processAnimatable(animatable: CALayer, forOffset offset: Float, completion: (() -> ())?) { let interpolatorFactory = InterpolatorAbstractFactory.interpolatorFactoryForType(.BasicInterpolatorFactory) let interpolator = interpolatorFactory?.interpolatorForAnimation(self, animatable: animatable) if let interpolator = interpolator { interpolator.interpolateAnimation(self, forAnimatable: animatable, forOffset: offset) } super.processAnimatable(animatable, forOffset: offset, completion) } } class ScrollableKeyframeAnimation: ScrollablePropertyAnimation { var keyOffsets = [Float]?() var values = [AnyObject]?() var functions = [TweenBlock]?() override func processAnimatable(animatable: CALayer, forOffset offset: Float, completion: (() -> ())?) { let interpolatorFactory = InterpolatorAbstractFactory.interpolatorFactoryForType(.KeyframeInterpolatorFactory) let interpolator = interpolatorFactory?.interpolatorForAnimation(self, animatable: animatable) if let interpolator = interpolator { interpolator.interpolateAnimation(self, forAnimatable: animatable, forOffset: offset) } super.processAnimatable(animatable, forOffset: offset, completion) } } @objc protocol ScrollableAnimationDelegate { optional func scrollableAnimationDidStart(anim: ScrollableAnimation!) optional func scrollableAnimationDidStop(anim: ScrollableAnimation!) } extension CALayer { func addScrollableAnimation(anim: ScrollableAnimation!, forKey key: String!, withController controller: ScrollableAnimationController) { controller.registerAnimation(anim, forKey: key, forAnimatable: self) } func removeAllScrollableAnimationsWithController(controller: ScrollableAnimationController) { controller.unregisterAllAnimationsForAnimatable(self) } func removeScrollableAnimationForKey(key: String!, withController controller: ScrollableAnimationController) { controller.unregisterAnimationForAnimatable(self, forKey: key) } func scrollableAnimationKeysWithController(controller: ScrollableAnimationController) -> [String]? { return controller.animationKeysForAnimatable(self) } func scrollableAnimationForKey(key: String!, withController controller: ScrollableAnimationController) -> ScrollableAnimation? { return controller.animationForKey(key, forAnimatable: self) } }
mit
d51c467c5ceca8e9ff671a880c50acb5
37.956204
140
0.71027
4.959108
false
false
false
false
hooman/swift
test/SIL/Distributed/distributed_actor_user_transport_init_sil.swift
1
6451
// RUN: %target-swift-frontend -O -primary-file %s -emit-sil -enable-experimental-distributed | %FileCheck %s --dump-input=fail // REQUIRES: concurrency import _Distributed @available(SwiftStdlib 5.5, *) distributed actor SimpleUserDefinedInitDistributedActor { init(kappa transport: ActorTransport, other: Int) {} init(other: Int, theTransport: ActorTransport) {} } // CHECK: // SimpleUserDefinedInitDistributedActor.init(kappa:other:) // CHECK: sil hidden{{.*}} @$s41distributed_actor_user_transport_init_sil37SimpleUserDefinedInitDistributedActorC5kappa5otherAC01_K00L9Transport_p_Sitcfc : $@convention(method) (@in ActorTransport, Int, @owned SimpleUserDefinedInitDistributedActor) -> @owned SimpleUserDefinedInitDistributedActor { // CHECK: // %0 "transport" // users: %17, %9, %8, %3 // CHECK: // %1 "other" // user: %4 // CHECK: // %2 "self" // users: %7, %14, %6, %18, %5 // CHECK: bb0(%0 : $*ActorTransport, %1 : $Int, %2 : $SimpleUserDefinedInitDistributedActor): // CHECK: debug_value_addr %0 : $*ActorTransport, let, name "transport", argno 1 // id: %3 // CHECK: debug_value %1 : $Int, let, name "other", argno 2 // id: %4 // CHECK: debug_value %2 : $SimpleUserDefinedInitDistributedActor, let, name "self", argno 3, implicit // id: %5 // CHECK: %6 = builtin "initializeDefaultActor"(%2 : $SimpleUserDefinedInitDistributedActor) : $() // Store the transport // CHECK: %7 = ref_element_addr %2 : $SimpleUserDefinedInitDistributedActor, #SimpleUserDefinedInitDistributedActor.actorTransport // user: %8 // CHECK: copy_addr %0 to [initialization] %7 : $*ActorTransport // id: %8 // Assign the identity // CHECK: %9 = open_existential_addr immutable_access %0 : $*ActorTransport to $*@opened("{{.*}}") ActorTransport // users: %13, %13, %11 // CHECK: %10 = metatype $@thick SimpleUserDefinedInitDistributedActor.Type // user: %13 // CHECK: %11 = witness_method $@opened("{{.*}}") ActorTransport, #ActorTransport.assignIdentity : <Self where Self : ActorTransport><Act where Act : DistributedActor> (Self) -> (Act.Type) -> AnyActorIdentity, %9 : $*@opened("{{.*}}") ActorTransport : $@convention(witness_method: ActorTransport) <τ_0_0 where τ_0_0 : ActorTransport><τ_1_0 where τ_1_0 : DistributedActor> (@thick τ_1_0.Type, @in_guaranteed τ_0_0) -> @out AnyActorIdentity // type-defs: %9; user: %13 // CHECK: %12 = alloc_stack $AnyActorIdentity // users: %16, %15, %13 // CHECK: %13 = apply %11<@opened("{{.*}}") ActorTransport, SimpleUserDefinedInitDistributedActor>(%12, %10, %9) : $@convention(witness_method: ActorTransport) <τ_0_0 where τ_0_0 : ActorTransport><τ_1_0 where τ_1_0 : DistributedActor> (@thick τ_1_0.Type, @in_guaranteed τ_0_0) -> @out AnyActorIdentity // type-defs: %9 // Store the identity // CHECK: %14 = ref_element_addr %2 : $SimpleUserDefinedInitDistributedActor, #SimpleUserDefinedInitDistributedActor.id // user: %15 // CHECK: copy_addr [take] %12 to [initialization] %14 : $*AnyActorIdentity // id: %15 // CHECK: dealloc_stack %12 : $*AnyActorIdentity // id: %16 // CHECK: destroy_addr %0 : $*ActorTransport // id: %17 // CHECK: return %2 : $SimpleUserDefinedInitDistributedActor // id: %18 // CHECK: } // end sil function '$s41distributed_actor_user_transport_init_sil37SimpleUserDefinedInitDistributedActorC5kappa5otherAC01_K00L9Transport_p_Sitcfc' // Even if the transport is in another position, we still locate it by the type // CHECK: // SimpleUserDefinedInitDistributedActor.init(other:theTransport:) // CHECK: sil hidden{{.*}} @$s41distributed_actor_user_transport_init_sil37SimpleUserDefinedInitDistributedActorC5other12theTransportACSi_01_K00lO0_ptcfc : $@convention(method) (Int, @in ActorTransport, @owned SimpleUserDefinedInitDistributedActor) -> @owned SimpleUserDefinedInitDistributedActor { // CHECK: // %0 "other" // user: %3 // CHECK: // %1 "theTransport" // users: %17, %9, %8, %4 // CHECK: // %2 "self" // users: %7, %14, %6, %18, %5 // CHECK: bb0(%0 : $Int, %1 : $*ActorTransport, %2 : $SimpleUserDefinedInitDistributedActor): // CHECK: debug_value %0 : $Int, let, name "other", argno 1 // id: %3 // CHECK: debug_value_addr %1 : $*ActorTransport, let, name "theTransport", argno 2 // id: %4 // CHECK: debug_value %2 : $SimpleUserDefinedInitDistributedActor, let, name "self", argno 3, implicit // id: %5 // CHECK: %6 = builtin "initializeDefaultActor"(%2 : $SimpleUserDefinedInitDistributedActor) : $() // Store the transport // CHECK: %7 = ref_element_addr %2 : $SimpleUserDefinedInitDistributedActor, #SimpleUserDefinedInitDistributedActor.actorTransport // user: %8 // CHECK: copy_addr %1 to [initialization] %7 : $*ActorTransport // id: %8 // Assign an identity // CHECK: %9 = open_existential_addr immutable_access %1 : $*ActorTransport to $*@opened("{{.*}}") ActorTransport // users: %13, %13, %11 // CHECK: %10 = metatype $@thick SimpleUserDefinedInitDistributedActor.Type // user: %13 // CHECK: %11 = witness_method $@opened("{{.*}}") ActorTransport, #ActorTransport.assignIdentity : <Self where Self : ActorTransport><Act where Act : DistributedActor> (Self) -> (Act.Type) -> AnyActorIdentity, %9 : $*@opened("{{.*}}") ActorTransport : $@convention(witness_method: ActorTransport) <τ_0_0 where τ_0_0 : ActorTransport><τ_1_0 where τ_1_0 : DistributedActor> (@thick τ_1_0.Type, @in_guaranteed τ_0_0) -> @out AnyActorIdentity // type-defs: %9; user: %13 // CHECK: %12 = alloc_stack $AnyActorIdentity // users: %16, %15, %13 // CHECK: %13 = apply %11<@opened("{{.*}}") ActorTransport, SimpleUserDefinedInitDistributedActor>(%12, %10, %9) : $@convention(witness_method: ActorTransport) <τ_0_0 where τ_0_0 : ActorTransport><τ_1_0 where τ_1_0 : DistributedActor> (@thick τ_1_0.Type, @in_guaranteed τ_0_0) -> @out AnyActorIdentity // type-defs: %9 // Store the identity // CHECK: %14 = ref_element_addr %2 : $SimpleUserDefinedInitDistributedActor, #SimpleUserDefinedInitDistributedActor.id // user: %15 // CHECK: copy_addr [take] %12 to [initialization] %14 : $*AnyActorIdentity // id: %15 // CHECK: dealloc_stack %12 : $*AnyActorIdentity // id: %16 // CHECK: destroy_addr %1 : $*ActorTransport // id: %17 // While in AST the return was "return null" after SILGen we properly return the self // CHECK: return %2 : $SimpleUserDefinedInitDistributedActor // id: %18 // CHECK: } // end sil function '$s41distributed_actor_user_transport_init_sil37SimpleUserDefinedInitDistributedActorC5other12theTransportACSi_01_K00lO0_ptcfc'
apache-2.0
81790040976797924e9af27dea07f135
85.851351
467
0.706706
3.414984
false
false
false
false
swaaws/shift
ios app/schichtplan/schichtplan/PreViewController.swift
1
18198
// // PreViewController.swift // schichtplan // // Created by Sebastian Heitzer on 27.09.16. // Copyright © 2016 Sebastian Heitzer. All rights reserved. // import UIKit import CoreData import EventKit import Foundation extension String { func toDateTime() -> NSDate { //Create Date Formatter let dateFormatter = DateFormatter() //Specify Format of String to Parse dateFormatter.dateFormat = "yyyy-MM-dd" //Parse into NSDate let dateFromString : Date = dateFormatter.date(from: self)! as Date //Return Parsed Date return dateFromString as NSDate } } class PreViewController: UIViewController{ var event = [NSManagedObject]() var managedObjectContext: NSManagedObjectContext? func addCalendar(){ var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } if key == "" { let eventStore = EKEventStore(); eventStore.requestAccess(to: .event, completion: { (granted, error) in if (granted) && (error == nil) { print("Erstelle Kalender") // Use Event Store to create a new calendar instance // Configure its title let newCalendar = EKCalendar(for: .event, eventStore: eventStore) // Probably want to prevent someone from saving a calendar // if they don't type in a name... newCalendar.title = "Schichtplan" // Access list of available sources from the Event Store let sourcesInEventStore = eventStore.sources // Filter the available sources and select the "Local" source to assign to the new calendar's // source property newCalendar.source = sourcesInEventStore.filter{ (source: EKSource) -> Bool in source.sourceType.rawValue == EKSourceType.local.rawValue }.first! // Save the calendar using the Event Store instance do { try eventStore.saveCalendar(newCalendar, commit: true) UserDefaults.standard.set(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar") } catch { let alert = UIAlertController(title: "Calendar could not save", message: (error as NSError).localizedDescription, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(OKAction) self.present(alert, animated: true, completion: nil) } } } ) } else { print("Calendar already exist") } } /* func delEvent(){ var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } if key == "" { print("nothing to do") } else { let eventStore = EKEventStore(); eventStore.requestAccess(to: .event, completion: { (granted, error) in if (granted) && (error == nil) { var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } //TODO: handle if the user has deleted the calendar print("Deleted event") func fetchEventsFromCalendar() -> Void { let selectedCalendar = eventStore.calendar(withIdentifier: key) let oneMonthAgo = NSDate(timeIntervalSinceNow: -60*60*24*365) let oneMonthAfter = NSDate(timeIntervalSinceNow: +60*60*24*365) let predicate = eventStore.predicateForEvents(withStart: oneMonthAgo as Date, end: oneMonthAfter as Date, calendars: [selectedCalendar!]) let events = eventStore.events(matching: predicate) as [EKEvent] //print("Events: \(events)") for event in events { // print("Event Title : \(event.title) Event ID: \(event.eventIdentifier)") do { try eventStore.remove(event, span: .thisEvent, commit: true) }catch{ print("can't delete event's") } } } fetchEventsFromCalendar() } }) } } */ func addEvent(){ var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } if key == "" { print("Can't add Events because Calendar not exits") } else { let eventStore = EKEventStore(); eventStore.requestAccess(to: .event, completion: { (granted, error) in if (granted) && (error == nil) { var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } //TODO: handle if the user has deleted the calendar let newCalendar = eventStore.calendar(withIdentifier: key) func new_event(title: String, begin: NSDate, end: NSDate ) { let event1 = EKEvent(eventStore: eventStore) event1.title = title event1.startDate = begin as Date event1.endDate = end as Date event1.notes = "description" event1.calendar = newCalendar! do { try eventStore.save(event1, span: .thisEvent) } catch { print("?") return } } for index in 0...(self.event.count - 1) { let derevent = self.event[index] let shift = derevent.value(forKey: "shift") as? String let dateString = derevent.value(forKey: "date") as? String // change to your date format // let nextdate = dateString?.toDateTime() // nextdate.Day += 1 // let enddate = dateString?.toDateTime() let cal = NSCalendar(identifier: .gregorian) let newDate: NSDate = cal!.date(bySettingHour: 2, minute: 0, second: 0, of: enddate as! Date)! as NSDate new_event(title: shift!, begin: (dateString?.toDateTime())!,end: newDate as NSDate) } print("create event") } } ) } } func delCalendar(){ var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } if key == "" { print("nothing to do") } else { let eventStore = EKEventStore(); eventStore.requestAccess(to: .event, completion: { (granted, error) in if (granted) && (error == nil) { var key = "" let defaults = UserDefaults.standard if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") { key = id } //TODO: handle if the user has deleted the calendar print("Delete Kalender") let newCalendar = eventStore.calendar(withIdentifier: key) let defauults = UserDefaults.standard defauults.set("", forKey: "EventTrackerPrimaryCalendar") let sourcesInEventStore = eventStore.sources // Filter the available sources and select the "Local" source to assign to the new calendar's // source property newCalendar?.source = sourcesInEventStore.filter{ (source: EKSource) -> Bool in source.sourceType.rawValue == EKSourceType.local.rawValue }.first! // Save the calendar using the Event Store instance do { try eventStore.removeCalendar(newCalendar!, commit: true) } catch { let alert = UIAlertController(title: "Calendar could not save", message: (error as NSError).localizedDescription, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(OKAction) self.present(alert, animated: true, completion: nil) } } } ) } } @IBOutlet weak var switch1: UISwitch! @IBAction func checkState(_ sender: AnyObject) { if switch1.isOn{ print("on") addCalendar() sleep(4) addEvent() sleep(4) let alert = UIAlertController(title: "Done", message: "Calendar Created and Event added", preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(OKAction) self.present(alert, animated: true, completion: nil) } if switch1.isOn == false{ print("off") delCalendar() } } func loadData(){ let request: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: "Event") do { let results = try managedObjectContext?.fetch(request) event = results! } catch{ fatalError("Error in retriving Event item") } } @IBAction func createcal(_ sender: AnyObject) { addCalendar() } @IBAction func deletevent(_ sender: AnyObject) { // delEvent() } @IBAction func createvent(_ sender: AnyObject) { addEvent() } @IBAction func deletecal(_ sender: AnyObject) { delCalendar() } @IBOutlet weak var dataincd: UILabel! @IBAction func refresh(_ sender: AnyObject) { var token = "" //------------Get Token from db-------------- let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext // read from Core Data let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Config") request.predicate = NSPredicate(format: "kind = %@", "token") request.returnsObjectsAsFaults = false do { let results = try context.fetch(request) if results.count > 0 { for result in results as! [NSManagedObject]{ if let username = result.value(forKey: "content") as? String{ token = username } } } }catch{ print("error") } print("Token is: " + token) //-------------get data from api-------------- typealias JSONDictionary = [String:Any] var datainjson = [JSONDictionary]() let url:NSURL = NSURL(string: "http://shift.example.com/api/getdata?token=" + token)! let session = URLSession.shared let httprequest = NSMutableURLRequest(url: url as URL) httprequest.addValue("application/json", forHTTPHeaderField: "Content-Type") httprequest.httpMethod = "POST" httprequest.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData let paramString = "" httprequest.httpBody = paramString.data(using: String.Encoding.utf8) let task = session.dataTask(with: httprequest as URLRequest) {( data, response, error) in guard let _:NSData = data as NSData?, let _:URLResponse = response , error == nil else { print("error") return } if let urlContent = data { do { let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) datainjson = jsonResult as! [JSONDictionary] } catch { print("JSON Processing Failed") } } } task.resume() sleep(4) let datarequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Event") datarequest.returnsObjectsAsFaults = false do { let results = try context.fetch(datarequest) for result in results as! [NSManagedObject]{ context.delete(result) } }catch{ print("error") } for data in datainjson { let newUser = NSEntityDescription.insertNewObject(forEntityName: "Event", into: context) newUser.setValue(data["date"], forKey: "date") newUser.setValue(data["shift"], forKey: "shift") do { try context.save() print("saved") }catch{ print("error") } } do { let results = try context.fetch(datarequest) self.dataincd.text = String (results.count) }catch{ print("error") } dataincd.text = String(event.count) } @IBAction func logout(_ sender: AnyObject) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Config") request.predicate = NSPredicate(format: "kind = %@", "token") request.returnsObjectsAsFaults = false do { let results = try context.fetch(request) if results.count > 0 { for result in results as! [NSManagedObject]{ context.delete(result) do { try context.save() } catch{ print("error") } } } }catch{ print("error") } performSegue(withIdentifier: "logout", sender: self) } let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() if defaults.string(forKey: "EventTrackerPrimaryCalendar") != "" { switch1.setOn(true, animated: false) } else { switch1.setOn(false, animated: false) } let appDelegate = UIApplication.shared.delegate as! AppDelegate managedObjectContext = appDelegate.persistentContainer.viewContext loadData() dataincd.text = String(event.count) } 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. } */ }
mit
018bd21e01b61673020bf0ae487c6b4f
34.471735
161
0.465956
6.069713
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Tone Filter/AKToneFilter.swift
1
3463
// // AKToneFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// A first-order recursive low-pass filter with variable frequency response. /// open class AKToneFilter: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKToneFilterAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "tone") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var halfPowerPointParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2. @objc open dynamic var halfPowerPoint: Double = 1_000.0 { willSet { if halfPowerPoint != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { halfPowerPointParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.halfPowerPoint = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - halfPowerPoint: The response curve's half-power point, in Hz. Half power is defined as peak power / root 2. /// @objc public init( _ input: AKNode? = nil, halfPowerPoint: Double = 1_000.0) { self.halfPowerPoint = halfPowerPoint _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } halfPowerPointParameter = tree["halfPowerPoint"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.halfPowerPoint = Float(halfPowerPoint) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
c624771ad51b0c36f02b7876386c9669
31.35514
119
0.608608
5.106195
false
false
false
false
e-government-ua/iMobile
iGov/Model/Subcategory+CoreDataClass.swift
1
1938
// // Subcategory+CoreDataClass.swift // iGov // // Created by Yurii Kolesnykov on 19.09.16. // Copyright © 2016 iGov. All rights reserved. // import Foundation import CoreData import SwiftyJSON @objc(Subcategory) public class Subcategory: NSManagedObject { class func create(_ context: NSManagedObjectContext, category: Category, nID: Int, sName: String, sID: String, nOrder: Int, aService: [JSON]) ->Subcategory? { if let subcategory = Subcategory.mr_createEntity(in: context) { subcategory.nID = nID as NSNumber? subcategory.sName = sName subcategory.sID = sID subcategory.nOrder = nOrder as NSNumber? subcategory.category = category subcategory.addToServices(NSSet(array: Service.parse(context, subcategory: subcategory, jsonArray: aService))) return subcategory } else { return nil } } class func parse(_ context: NSManagedObjectContext, category: Category, jsonArray: [JSON]) -> [Subcategory] { var resultArray = [Subcategory]() for element in jsonArray { if let subcategoryDict = element.dictionary { guard let nID = subcategoryDict["nID"]?.int, let sName = subcategoryDict["sName"]?.string, let sID = subcategoryDict["sID"]?.string, let nOrder = subcategoryDict["nOrder"]?.int, let services = subcategoryDict["aService"]?.array else { continue } if let newSubcategory = Subcategory.create(context, category: category, nID: nID, sName: sName, sID: sID, nOrder: nOrder, aService: services) { resultArray.append(newSubcategory) } } } return resultArray } }
gpl-3.0
b2f609fa3d5d98fbc1c5e24839d702a7
34.218182
160
0.575632
4.941327
false
false
false
false
vnu/YelpMe
YelpMe/AppDelegate.swift
1
2699
// // AppDelegate.swift // Yelp // // Created by Vinu Charanya on 2/10/16. // Copyright © 2016 Vnu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. redNavBar() return true } func redNavBar(){ let yelpColor = UIColor(red: 196.0/255, green: 18.0/255, blue: 0.0/255, alpha: 1.0) UINavigationBar.appearance().translucent = false UINavigationBar.appearance().barTintColor = yelpColor UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().tintColor = UIColor.whiteColor() UITabBar.appearance().tintColor = UIColor.whiteColor() UITabBar.appearance().barTintColor = yelpColor } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
b7d2c5feece874d6cd201e19f1ec15a8
46.333333
285
0.739437
5.417671
false
false
false
false
beckasaurus/skin-ios
skin/skin/DailyRoutineLogViewController.swift
1
7104
// // DailyRoutineLogViewController.swift // skin // // Created by Becky on 1/30/18. // Copyright © 2018 Becky Henderson. All rights reserved. // import UIKit import RealmSwift // TODO: Suggest routine if one is scheduled for day // TODO: Delete routine // TODO: scrolling in long routine lists // TODO: collapse product lists? // TODO: rearranging products in list enum DailyRoutineLogViewControllerError: Error { case invalidDate } let tableHeaderHeight: CGFloat = 50.0 class DailyRoutineLogViewController: UIViewController { @IBOutlet weak var routineLogTableView: UITableView! @IBOutlet weak var editButton: UIButton! var routineLogs: Results<RoutineLog>? var editingRoutine: RoutineLog? override func viewDidLoad() { routineLogTableView.allowsMultipleSelection = false routineLogTableView.allowsSelection = false routineLogTableView.register(RoutineLogTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "routineLogHeaderSection") } func getRoutines(for date: Date) { if let currentDatePredicate = try? predicate(for: date), let logs = realm?.objects(RoutineLog.self).filter(currentDatePredicate).sorted(byKeyPath: "time") { routineLogs = logs routineLogTableView.reloadData() } } func predicate(for date: Date) throws -> NSPredicate { guard let nextDayBegin = Calendar.current.date(bySettingHour: 00, minute: 00, second: 00, of: date), let nextDayEnd = Calendar.current.date(bySettingHour: 23, minute: 59, second: 59, of: date) else { throw DailyRoutineLogViewControllerError.invalidDate } return NSPredicate(format: "time >= %@ AND time <= %@", nextDayBegin as CVarArg, nextDayEnd as CVarArg) } } extension DailyRoutineLogViewController: DateChangeable { func didChangeDate(to date: Date) { getRoutines(for: date) } } // MARK: Add routine extension DailyRoutineLogViewController { @IBAction func addRoutineLog(sender: UIButton) { let routineLog = RoutineLog() routineLog.id = UUID().uuidString routineLog.time = Date() routineLog.name = "AM" try? realm?.write { realm?.add(routineLog) } routineLogTableView.reloadData() } } // MARK: Edit routine lists extension DailyRoutineLogViewController { @IBAction func edit(sender: UIButton) { let isCurrentlyEditing = routineLogTableView.isEditing editButton.setTitle(isCurrentlyEditing ? "Edit" : "Done", for: .normal) routineLogTableView.setEditing(!isCurrentlyEditing, animated: true) toggleSectionHeaderEditButtons() } func toggleSectionHeaderEditButtons() { let sectionCount = routineLogTableView.numberOfSections for sectionIndex in 0...sectionCount { guard let sectionHeader = routineLogTableView.headerView(forSection: sectionIndex) as? RoutineLogTableSectionHeaderView else { continue } sectionHeader.toggleDeleteButton() } } } // MARK: Add product to routine log extension DailyRoutineLogViewController: ProductSelectionDelegate { @IBAction func addProduct(sender: UIButton) { let routineIndex = sender.tag guard let routine = routineLogs?[routineIndex] else { return } editingRoutine = routine let productListSplitViewController = storyboard!.instantiateViewController(withIdentifier: productListSplitViewControllerIdentifier) as! ProductListSplitViewController let productListViewController = (productListSplitViewController.viewControllers.first! as! UINavigationController).topViewController as! ProductListViewController productListViewController.context = .selection productListViewController.delegate = self show(productListSplitViewController, sender: self) } func didSelect(product: Product) { guard let routine = editingRoutine else { return } try? realm?.write { routine.products.append(product) } routineLogTableView.reloadData() } } extension DailyRoutineLogViewController { @IBAction func deleteRoutine(sender: UIButton) { let routineIndex = sender.tag guard let routine = routineLogs?[routineIndex] else { return } try? realm?.write { self.realm?.delete(routine) } routineLogTableView.reloadData() if routineLogTableView.numberOfSections == 0 { //exit editing mode edit(sender: editButton) } } } // MARK: Table View Data Source extension DailyRoutineLogViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return routineLogs?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let routineLog = routineLogs?[section] else { return 0 } return routineLog.products.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = "routineLogProductCell" let cell: UITableViewCell if let tableCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) { cell = tableCell } else { cell = UITableViewCell(style: .subtitle, reuseIdentifier: reuseIdentifier) } let sectionIndex = indexPath.section let routineLog = routineLogs?[sectionIndex] let product = routineLog?.products[indexPath.row] cell.textLabel?.text = product?.name ?? "" cell.detailTextLabel?.text = product?.brand ?? "" return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return tableHeaderHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let routineLog = routineLogs?[section] else { return nil } let frame = CGRect(x: tableView.bounds.origin.x, y: tableView.bounds.origin.y, width: tableView.bounds.size.width, height: tableHeaderHeight) let tableHeaderView = RoutineLogTableSectionHeaderView(frame: frame, routineName: routineLog.name, section: section, editButtonTarget: self, editButtonSelector: #selector(addProduct(sender:)), deleteButtonTarget: self, deleteButtonSelector: #selector(deleteRoutine(sender:)), inEditingMode: tableView.isEditing) return tableHeaderView } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let section = indexPath.section let row = indexPath.row guard let routineLog = routineLogs?[section] else { return } try? realm?.write { routineLog.products.remove(at: row) } routineLogTableView.reloadData() } } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard sourceIndexPath.section == destinationIndexPath.section, let routineLog = routineLogs?[sourceIndexPath.section] else { return } try? realm?.write { routineLog.products.move(from: sourceIndexPath.row, to: destinationIndexPath.row) } routineLogTableView.reloadData() } }
mit
e3da164c401a82c813f14377f70b73b4
28.230453
169
0.741518
4.21543
false
false
false
false